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
@@ -7,11 +7,14 @@ from __future__ import annotations
7
7
  import json
8
8
  import re
9
9
  import time
10
+ from contextlib import contextmanager
10
11
  from typing import Any
11
12
  from types import SimpleNamespace
12
13
  from urllib.parse import unquote, urljoin, urlparse
13
14
 
14
15
  from . import access_rules
16
+ from .login_wait import LoginWait
17
+ from .. import progress_reporter
15
18
  from .batch_common import (AWAY_WAIT_SEC, POLL_MS, DownloadResult, PublisherContentError, _is_browser_error,
16
19
  _is_navigation_cut, open_page, pump_until, settle)
17
20
 
@@ -64,6 +67,11 @@ class LoginMixin:
64
67
  # A verification can let the page through to the publisher's redirect
65
68
  # page (RSC's silent sign-in check, judged as the article, 2026-11-01).
66
69
  self._wait_past_redirect_page(page, result)
70
+ # A blank document may draw its verification panel only while waiting
71
+ # for text. Handle it before interpreting the panel as article access
72
+ # or looking for an institution entry that cannot exist on it.
73
+ if not self._wait_for_challenge(page, result):
74
+ return False
67
75
  self._raise_on_publisher_content_error(page)
68
76
  self._dismiss_cookie_banners(page, result)
69
77
  snapshot = self._access_snapshot(page) if not self._is_auth_page(str(page.url)) else None
@@ -127,7 +135,22 @@ class LoginMixin:
127
135
  return url[:200]
128
136
  return f"{url[:200]} | {verdict} ({basis or 'no rule'}): {evidence[:160]}"
129
137
 
130
- _PAGE_TEXT_JS = "() => document.contentType !== 'text/html' ? -1 : (document.body ? document.body.innerText.trim().length : 0)"
138
+ # Readiness only needs a text node. body.innerText lays out the entire
139
+ # article, which can exhaust the page budget on a long document.
140
+ _PAGE_TEXT_JS = """() => {
141
+ if (document.contentType !== 'text/html') return -1;
142
+ if (!document.body) return 0;
143
+ const excluded = el => el.matches('script, style, noscript, template, [hidden]')
144
+ || el.style.display === 'none' || el.style.visibility === 'hidden';
145
+ if (excluded(document.body)) return 0;
146
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
147
+ acceptNode: node => node.nodeType === Node.ELEMENT_NODE
148
+ ? (excluded(node) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_SKIP)
149
+ : (node.nodeValue.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP)
150
+ });
151
+ const text = walker.nextNode();
152
+ return text ? text.nodeValue.trim().length : 0;
153
+ }"""
131
154
 
132
155
  def _wait_for_page_text(self, page: Any, result: DownloadResult) -> None:
133
156
  """Wait for the document before judging access, within the page budget.
@@ -201,9 +224,44 @@ class LoginMixin:
201
224
  self._return_to_article_after_login(page, result)
202
225
  return signed_in
203
226
  finally:
227
+ self._set_login_attention(result, "")
204
228
  last = next((e["state"] for e in reversed(result.events) if e["state"] != "wait"), "")
205
229
  self._note_wait(result, "school login", started, "signed in" if signed_in else (result.reason or last))
206
230
 
231
+ def _set_login_attention(self, result: DownloadResult, message: str, deadline: float | None = None,
232
+ *, page: Any = None) -> None:
233
+ """A user step, once per prompt; automatic SSO keeps its ordinary progress."""
234
+ if page is not None and message:
235
+ result._attention_page = page
236
+ elif not message:
237
+ result._attention_page = None
238
+ key = f"publisher-login:{id(self)}:{result.doi}"
239
+ wait = getattr(result, "_login_wait", None)
240
+ if wait is not None and wait.paused:
241
+ deadline = None
242
+ if message == getattr(result, "_login_attention", ""):
243
+ if message:
244
+ progress_reporter.update_attention_deadline(key, deadline)
245
+ return
246
+ if message:
247
+ progress_reporter.set_attention(key, message, current=result.doi, phase="机构登录", deadline=deadline)
248
+ progress_reporter.report_stage("waiting_login", current=result.doi)
249
+ else:
250
+ progress_reporter.clear_attention(key)
251
+ result._login_attention = message
252
+
253
+ @contextmanager
254
+ def _login_wait_budget(self, result: DownloadResult, attribute: str, deadline: float, clock):
255
+ wait = result._login_wait = LoginWait(deadline, clock, attribute=attribute)
256
+ try:
257
+ yield wait
258
+ finally:
259
+ try:
260
+ setattr(result, attribute, wait.close())
261
+ finally:
262
+ result._login_wait = None
263
+ self._set_login_attention(result, "")
264
+
207
265
  def _complete_login_steps(self, page: Any, result: DownloadResult) -> bool:
208
266
  own = self.adapter.complete_login(page, result)
209
267
  if own is not None:
@@ -264,208 +322,218 @@ class LoginMixin:
264
322
  self._select_institution(page, result)
265
323
 
266
324
  deadline = self._user_wait_deadline(result)
267
- last_state = ""
268
- last_auto_action = ""
269
- last_auto_action_at = 0.0
270
- visited_idp = False
271
- page_since, page_inputs = time.time(), ()
272
- outside_since = time.time() # last seen on the user's own login step
273
- article_returns = 0
274
- session_returns = 0
275
- away_from_publisher = False # on an IdP, federation or chooser page since the last probe
276
- returned = False # back on the publisher's site after such a page: try the PDF
277
- last_probe = time.time()
278
- while time.time() < deadline:
279
- time.sleep(1) # each pass checks the page again: a step done goes on within a second
280
- self._check_user_decision(result, page)
281
- if getattr(result, "_institution_not_listed", False):
282
- # The publisher's institution search has no entry for the school.
283
- result.reason = "institution_federation_unavailable"
284
- self._event(result, result.reason, "the school is not in the publisher's institution list")
285
- return False
286
- over, outside_since = self._page_wait_over(page, outside_since)
287
- if over:
288
- # Off the school's login page for a whole page wait (a publisher
289
- # page, a chooser, a redirect that goes nowhere): nobody is typing.
290
- self._event(result, "page_wait_ended",
291
- f"{self._login_wait_page(page)} after {self.page_wait_sec:.0f} s")
292
- self._wait_ran_out(result)
293
- return False
294
- marker = f"{self._title(page)} | {getattr(page, 'url', '')[:160]}"
295
- here = urlparse(str(getattr(page, "url", "") or ""))
296
- on_publisher = self._on_publisher_host(here.geturl())
297
- if here.hostname and (not on_publisher or self._is_idp_host(here.netloc)):
298
- visited_idp = True
299
- if self._is_idp_host(here.netloc):
300
- result._visited_idp = True # the school's own login: a denial now is the school's
301
- if here.hostname and (not on_publisher or self._is_auth_page(here.geturl())):
302
- away_from_publisher = True
303
- elif here.hostname and away_from_publisher:
304
- away_from_publisher, returned = False, True
305
- result._login_round_trip = True
306
- self._event(result, "login_round_trip_returned", here.geturl()[:160])
307
- if (on_publisher and self._is_success_article_url(here.geturl())
308
- and not self._is_auth_page(here.geturl()) and not self._challenge_shell(page)
309
- and (returned or time.time() - last_probe >= self.WAIT_PROBE_EVERY_SEC)
310
- and self._looks_logged_out(page)):
311
- # Whoever signed in (this program or the user), the article page may
312
- # give its PDF although it still looks signed out to the rules (ASCE's
313
- # "GET ACCESS" after the login waited out five minutes, 2026-11-02): try it.
314
- after_login, returned, last_probe = returned, False, time.time()
315
- if self._probe_pdf_while_waiting(page, result, after_login=after_login):
316
- return False # signed in, and the page still offers or denies the article
317
- elif (visited_idp and on_publisher and article_returns < 2
318
- and not self._is_success_article_url(here.geturl())
319
- and not self._is_auth_page(here.geturl())
320
- and not self._challenge_shell(page)):
321
- # Back from the IdP on a publisher page that is neither the
322
- # article nor a login/chooser page (Taylor & Francis drops the
323
- # redirect and lands on its home page): open the article.
324
- article_returns += 1
325
- try:
326
- open_page(page, result.article_url, timeout_ms=60_000)
327
- self._event(result, "idp_return_article", here.geturl()[:160])
328
- settle(page, 3_000)
329
- if not self._challenge_shell(page) and not self._looks_logged_out(page):
330
- return True
331
- except Exception as exc:
332
- self._event(result, "idp_return_article_error", type(exc).__name__)
333
- continue
334
- if marker != last_state:
335
- self._event(result, "login_state", marker)
336
- last_state = marker
337
- confirmation = self._idp_confirmation(page)
338
- if confirmation:
339
- # The user decides: the engine never agrees on their behalf.
340
- self._event(result, "idp_confirmation_required", confirmation)
341
- page_since, page_inputs = time.time(), self._visible_input_values(page) if self._user_away else ()
342
- elif self._user_away:
343
- inputs = self._visible_input_values(page)
344
- if inputs != page_inputs:
345
- # Someone is typing here: wait for them, within the article's total.
346
- page_since, page_inputs = time.time(), inputs
347
- elif time.time() - page_since >= AWAY_WAIT_SEC:
348
- # Nothing moved on this page and the user seems away.
349
- self._wait_ran_out(result)
325
+ with self._login_wait_budget(result, "_user_wait_deadline", deadline, time.time) as wait:
326
+ last_state = ""
327
+ last_auto_action = ""
328
+ last_auto_action_at = 0.0
329
+ visited_idp = False
330
+ page_since = time.time()
331
+ outside_since = time.time() # last seen on the user's own login step
332
+ article_returns = 0
333
+ session_returns = 0
334
+ away_from_publisher = False # on an IdP, federation or chooser page since the last probe
335
+ returned = False # back on the publisher's site after such a page: try the PDF
336
+ last_probe = time.time()
337
+ while True:
338
+ self._check_user_decision(result, page)
339
+ user_step = self._users_login_step(page)
340
+ wait.observe(page, user_step)
341
+ deadline = wait.deadline
342
+ if time.time() >= deadline:
343
+ break
344
+ time.sleep(1) # each pass checks the page again: a step done goes on within a second
345
+ if getattr(result, "_institution_not_listed", False):
346
+ # The publisher's institution search has no entry for the school.
347
+ result.reason = "institution_federation_unavailable"
348
+ self._event(result, result.reason, "the school is not in the publisher's institution list")
350
349
  return False
351
- if self._challenge_shell(page):
352
- if not self._wait_for_challenge(page, result, deadline=deadline):
350
+ over, outside_since = self._page_wait_over(page, outside_since)
351
+ if over:
352
+ # Off the school's login page for a whole page wait (a publisher
353
+ # page, a chooser, a redirect that goes nowhere): nobody is typing.
354
+ self._event(result, "page_wait_ended",
355
+ f"{self._login_wait_page(page)} after {self.page_wait_sec:.0f} s")
356
+ self._wait_ran_out(result)
353
357
  return False
354
- continue
355
- if self._return_from_login_site(page, result):
356
- continue
357
- if manual_selection:
358
- if self._is_challenge_page(page):
358
+ message = ""
359
+ if user_step:
360
+ kind = self._login_wait_page(page)
361
+ message = ("请在浏览器窗口选择学校并完成机构登录" if kind in {"school_choice", "institution_chooser"}
362
+ else "请在浏览器窗口完成机构登录")
363
+ self._set_login_attention(result, message, deadline, page=page)
364
+ marker = f"{self._title(page)} | {getattr(page, 'url', '')[:160]}"
365
+ here = urlparse(str(getattr(page, "url", "") or ""))
366
+ on_publisher = self._on_publisher_host(here.geturl())
367
+ if here.hostname and (not on_publisher or self._is_idp_host(here.netloc)):
368
+ visited_idp = True
369
+ if self._is_idp_host(here.netloc):
370
+ result._visited_idp = True # the school's own login: a denial now is the school's
371
+ if here.hostname and (not on_publisher or self._is_auth_page(here.geturl())):
372
+ away_from_publisher = True
373
+ elif here.hostname and away_from_publisher:
374
+ away_from_publisher, returned = False, True
375
+ result._login_round_trip = True
376
+ self._event(result, "login_round_trip_returned", here.geturl()[:160])
377
+ if (on_publisher and self._is_success_article_url(here.geturl())
378
+ and not self._is_auth_page(here.geturl()) and not self._challenge_shell(page)
379
+ and (returned or time.time() - last_probe >= self.WAIT_PROBE_EVERY_SEC)
380
+ and self._looks_logged_out(page)):
381
+ # Whoever signed in (this program or the user), the article page may
382
+ # give its PDF although it still looks signed out to the rules (ASCE's
383
+ # "GET ACCESS" after the login waited out five minutes, 2026-11-02): try it.
384
+ after_login, returned, last_probe = returned, False, time.time()
385
+ if self._probe_pdf_while_waiting(page, result, after_login=after_login):
386
+ return False # signed in, and the page still offers or denies the article
387
+ elif (visited_idp and on_publisher and article_returns < 2
388
+ and not self._is_success_article_url(here.geturl())
389
+ and not self._is_auth_page(here.geturl())
390
+ and not self._challenge_shell(page)):
391
+ # Back from the IdP on a publisher page that is neither the
392
+ # article nor a login/chooser page (Taylor & Francis drops the
393
+ # redirect and lands on its home page): open the article.
394
+ article_returns += 1
395
+ try:
396
+ open_page(page, result.article_url, timeout_ms=60_000)
397
+ self._event(result, "idp_return_article", here.geturl()[:160])
398
+ settle(page, 3_000)
399
+ if not self._challenge_shell(page) and not self._looks_logged_out(page):
400
+ return True
401
+ except Exception as exc:
402
+ self._event(result, "idp_return_article_error", type(exc).__name__)
403
+ continue
404
+ if marker != last_state:
405
+ self._event(result, "login_state", marker)
406
+ last_state = marker
407
+ confirmation = self._idp_confirmation(page)
408
+ if confirmation:
409
+ # The user decides: the engine never agrees on their behalf.
410
+ self._event(result, "idp_confirmation_required", confirmation)
411
+ page_since = time.time()
412
+ elif self._user_away:
413
+ if wait.paused:
414
+ page_since = time.time()
415
+ elif time.time() - page_since >= AWAY_WAIT_SEC:
416
+ # Nothing moved on this page and the user seems away.
417
+ self._wait_ran_out(result)
418
+ return False
419
+ if self._challenge_shell(page):
359
420
  if not self._wait_for_challenge(page, result, deadline=deadline):
360
421
  return False
361
422
  continue
423
+ if self._return_from_login_site(page, result):
424
+ continue
425
+ if manual_selection:
426
+ if self._is_challenge_page(page):
427
+ if not self._wait_for_challenge(page, result, deadline=deadline):
428
+ return False
429
+ continue
430
+ block_reason = self._login_block_reason(page)
431
+ if block_reason:
432
+ self._event(result, block_reason, getattr(self, "_block_evidence", ""))
433
+ return False
434
+ stuck = self._stuck_on_school_site(page, result)
435
+ if stuck:
436
+ result.reason = result.state = "idp_no_return_to_publisher"
437
+ result._stopped_host = urlparse(stuck).hostname or ""
438
+ self._event(result, "idp_no_return_to_publisher",
439
+ f"{stuck[:200]} | {self._title(page)[:80]} | {self.SCHOOL_SITE_STAY_SEC} s without returning")
440
+ self._snapshot(page, result, "login stopped on the school's site")
441
+ return False
442
+ if self._follow_federated_login_option(page, result):
443
+ continue
444
+ if self._is_human_login_page(page):
445
+ if not any(s["why"] == "waiting for the user: school login" for s in result.snapshots):
446
+ self._snapshot(page, result, "waiting for the user: school login")
447
+ continue
448
+ if manual_selection and self.adapter.institution_chooser_open(page):
449
+ # The publisher's own chooser: choose there; no generic
450
+ # Continue/SSO action while the user may be interacting.
451
+ self._select_institution(page, result)
452
+ continue
453
+ self._dismiss_cookie_banners(page, result)
454
+ self._click_optional_continue(page, result)
455
+ if self._is_challenge_page(page):
456
+ if self._wait_for_challenge(page, result, deadline=deadline):
457
+ continue
458
+ self._event(result, "challenge_or_viewer_timeout", self._body_text(page, 500))
459
+ return False
460
+ if self._return_to_record_article_if_needed(page, result, result.doi):
461
+ if not self._looks_logged_out(page):
462
+ return True
463
+ continue
464
+ if self._article_access_available(page):
465
+ return True
466
+ # After the IdP some publishers (Taylor & Francis) land on their
467
+ # home page with the institution session active: go back to the
468
+ # article. CARSI is automated too, so this applies in every mode.
469
+ if (session_returns < 2 and self._has_publisher_institution_session(page)
470
+ and not self._is_success_article_url(getattr(page, "url", ""))):
471
+ # Bounded: a page type the rules do not know as an article
472
+ # (ScienceDirect book chapters, 2026-10-31) reloaded forever.
473
+ session_returns += 1
474
+ try:
475
+ open_page(page, result.article_url, timeout_ms=60_000)
476
+ self._event(result, "institution_session_return_article", result.article_url)
477
+ settle(page, 3_000)
478
+ self._dismiss_cookie_banners(page, result)
479
+ if not self._looks_logged_out(page):
480
+ return True
481
+ continue
482
+ except Exception as exc:
483
+ self._event(result, "institution_session_return_error", f"{type(exc).__name__}: {exc}")
362
484
  block_reason = self._login_block_reason(page)
363
485
  if block_reason:
364
- self._event(result, block_reason, getattr(self, "_block_evidence", ""))
486
+ self._event(result, block_reason, getattr(self, "_block_evidence", "") or self._body_text(page, 500))
365
487
  return False
366
- stuck = self._stuck_on_school_site(page, result)
367
- if stuck:
368
- result.reason = result.state = "idp_no_return_to_publisher"
369
- result._stopped_host = urlparse(stuck).hostname or ""
370
- self._event(result, "idp_no_return_to_publisher",
371
- f"{stuck[:200]} | {self._title(page)[:80]} | {self.SCHOOL_SITE_STAY_SEC} s without returning")
372
- self._snapshot(page, result, "login stopped on the school's site")
373
- return False
374
- if self._follow_federated_login_option(page, result):
375
- continue
376
- if self._is_human_login_page(page):
377
- if not any(s["why"] == "waiting for the user: school login" for s in result.snapshots):
378
- self._snapshot(page, result, "waiting for the user: school login")
379
- continue
380
- if manual_selection and self.adapter.institution_chooser_open(page):
381
- # The publisher's own chooser: choose there; no generic
382
- # Continue/SSO action while the user may be interacting.
383
- self._select_institution(page, result)
384
- continue
385
- self._dismiss_cookie_banners(page, result)
386
- self._click_optional_continue(page, result)
387
- if self._is_challenge_page(page):
388
- if self._wait_for_challenge(page, result, deadline=deadline):
488
+ if manual_selection:
489
+ if self._open_adapter_login_page(page, result):
490
+ entry_opened = False # the next site's own entry is still to be opened
491
+ continue
492
+ if (not entry_opened and self._is_success_article_url(str(page.url))
493
+ and not self._has_visible_editable_input(page)):
494
+ # The first entry lookup can run before the article page has
495
+ # rendered its entry (a publisher's silent redirect; ScienceDirect
496
+ # right after linkinghub, 2026-10-31). Open the official entry
497
+ # once it appears, then leave the user's institution selection alone.
498
+ entry_opened = self._click_sso_entry(page, result)
499
+ if entry_opened:
500
+ continue
501
+ self._select_institution(page, result)
389
502
  continue
390
- self._event(result, "challenge_or_viewer_timeout", self._body_text(page, 500))
391
- return False
392
- if self._return_to_record_article_if_needed(page, result, result.doi):
393
- if not self._looks_logged_out(page):
503
+ if marker != last_auto_action or time.time() - last_auto_action_at > 10:
504
+ if self._select_institution(page, result):
505
+ settle(page, 2_000)
506
+ last_auto_action = marker
507
+ last_auto_action_at = time.time()
508
+ continue
509
+ if self._looks_logged_out(page) and self._click_sso_entry(page, result):
510
+ settle(page, 2_000)
511
+ self._select_institution(page, result)
512
+ last_auto_action = marker
513
+ last_auto_action_at = time.time()
514
+ continue
515
+ if self._click_openathens_entry(page, result):
516
+ settle(page, 2_000)
517
+ self._select_institution(page, result)
518
+ last_auto_action = marker
519
+ last_auto_action_at = time.time()
520
+ continue
521
+ self._select_institution(page, result)
522
+ last_auto_action = marker
523
+ last_auto_action_at = time.time()
524
+ if self._article_access_available(page):
394
525
  return True
395
- continue
396
- if self._article_access_available(page):
397
- return True
398
- # After the IdP some publishers (Taylor & Francis) land on their
399
- # home page with the institution session active: go back to the
400
- # article. CARSI is automated too, so this applies in every mode.
401
- if (session_returns < 2 and self._has_publisher_institution_session(page)
402
- and not self._is_success_article_url(getattr(page, "url", ""))):
403
- # Bounded: a page type the rules do not know as an article
404
- # (ScienceDirect book chapters, 2026-10-31) reloaded forever.
405
- session_returns += 1
526
+ if not manual_selection and self._has_publisher_institution_session(page):
406
527
  try:
407
528
  open_page(page, result.article_url, timeout_ms=60_000)
408
529
  self._event(result, "institution_session_return_article", result.article_url)
409
530
  settle(page, 3_000)
410
531
  self._dismiss_cookie_banners(page, result)
411
- if not self._looks_logged_out(page):
412
- return True
413
- continue
532
+ return not self._looks_logged_out(page)
414
533
  except Exception as exc:
415
534
  self._event(result, "institution_session_return_error", f"{type(exc).__name__}: {exc}")
416
- block_reason = self._login_block_reason(page)
417
- if block_reason:
418
- self._event(result, block_reason, getattr(self, "_block_evidence", "") or self._body_text(page, 500))
419
- return False
420
- if manual_selection:
421
- if self._open_adapter_login_page(page, result):
422
- entry_opened = False # the next site's own entry is still to be opened
423
- continue
424
- if (not entry_opened and self._is_success_article_url(str(page.url))
425
- and not self._has_visible_editable_input(page)):
426
- # The first entry lookup can run before the article page has
427
- # rendered its entry (a publisher's silent redirect; ScienceDirect
428
- # right after linkinghub, 2026-10-31). Open the official entry
429
- # once it appears, then leave the user's institution selection alone.
430
- entry_opened = self._click_sso_entry(page, result)
431
- if entry_opened:
432
- continue
433
- self._select_institution(page, result)
434
- continue
435
- if marker != last_auto_action or time.time() - last_auto_action_at > 10:
436
- if self._select_institution(page, result):
437
- settle(page, 2_000)
438
- last_auto_action = marker
439
- last_auto_action_at = time.time()
440
- continue
441
- if self._looks_logged_out(page) and self._click_sso_entry(page, result):
442
- settle(page, 2_000)
443
- self._select_institution(page, result)
444
- last_auto_action = marker
445
- last_auto_action_at = time.time()
446
- continue
447
- if self._click_openathens_entry(page, result):
448
- settle(page, 2_000)
449
- self._select_institution(page, result)
450
- last_auto_action = marker
451
- last_auto_action_at = time.time()
452
- continue
453
- self._select_institution(page, result)
454
- last_auto_action = marker
455
- last_auto_action_at = time.time()
456
- if self._article_access_available(page):
457
- return True
458
- if not manual_selection and self._has_publisher_institution_session(page):
459
- try:
460
- open_page(page, result.article_url, timeout_ms=60_000)
461
- self._event(result, "institution_session_return_article", result.article_url)
462
- settle(page, 3_000)
463
- self._dismiss_cookie_banners(page, result)
464
- return not self._looks_logged_out(page)
465
- except Exception as exc:
466
- self._event(result, "institution_session_return_error", f"{type(exc).__name__}: {exc}")
467
- self._wait_ran_out(result)
468
- return False
535
+ self._wait_ran_out(result)
536
+ return False
469
537
 
470
538
  # The school's account cannot sign in (login state J). Shibboleth's own
471
539
  # words ("Your account is locked.", "Your password has expired.") and the
@@ -688,18 +756,6 @@ class LoginMixin:
688
756
  return ""
689
757
  return url if time.time() - seen[1] >= self.SCHOOL_SITE_STAY_SEC else ""
690
758
 
691
- @staticmethod
692
- def _visible_input_values(page: Any) -> tuple[str, ...]:
693
- """What the visible text and password fields hold; a change means someone types."""
694
- try:
695
- values = page.evaluate("""() => [...document.querySelectorAll('input')]
696
- .filter(i => ['', 'text', 'email', 'password', 'tel', 'number'].includes((i.type || '').toLowerCase())
697
- && i.getClientRects().length > 0)
698
- .map(i => i.value || '')""")
699
- except Exception:
700
- return ()
701
- return tuple(str(v) for v in values) if isinstance(values, list) else ()
702
-
703
759
  def _open_adapter_login_page(self, page: Any, result: DownloadResult | None) -> bool:
704
760
  """Go to the adapter's next login page, each once per item (an Elsevier
705
761
  journal's own institution login, then ScienceDirect's same article);
@@ -1225,12 +1281,16 @@ class LoginMixin:
1225
1281
  and not self._personal_login_box(page, url))
1226
1282
 
1227
1283
  def _personal_login_box(self, page: Any, url: str) -> bool:
1228
- """The password field is a personal account's login box on the publisher's
1229
- own article page, nobody typing in it: BMJ shows one next to "Log in via
1230
- institution", and the article page was waited on for 5 minutes as if it
1231
- were the school's login (2026-11-02)."""
1232
- return (self._on_publisher_host(url) and self._is_success_article_url(url) and not self._is_auth_page(url)
1233
- and not self._has_visible_editable_input(page))
1284
+ """A publisher account form can be on an article, login page or SSO host.
1285
+
1286
+ An untouched form next to a separate institutional entry is not the
1287
+ school's credentials step. Preserve a known IdP and any form the user
1288
+ is already filling; return only field presence/activity, never values.
1289
+ """
1290
+ if self._is_idp_host(urlparse(url).netloc) or self._has_visible_editable_input(page):
1291
+ return False
1292
+ return ((self._on_publisher_host(url) and self._is_success_article_url(url) and not self._is_auth_page(url))
1293
+ or isinstance(page.evaluate(self._INSTITUTION_ENTRY_JS), dict))
1234
1294
 
1235
1295
  def _follow_federated_login_option(self, page: Any, result: DownloadResult) -> bool:
1236
1296
  """The publisher's login page offers an institutional option next to the
@@ -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
- stop = threading.Event()
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