papersearch 0.7.0 → 0.7.2

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 (96) hide show
  1. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  2. package/dist/capabilities/download/batch/batch.js +12 -1
  3. package/dist/capabilities/download/batch/batch.js.map +1 -1
  4. package/dist/capabilities/download/batch/batchSummary.d.ts.map +1 -1
  5. package/dist/capabilities/download/batch/batchSummary.js +16 -7
  6. package/dist/capabilities/download/batch/batchSummary.js.map +1 -1
  7. package/dist/capabilities/download/batch/journalKey.d.ts +12 -0
  8. package/dist/capabilities/download/batch/journalKey.d.ts.map +1 -0
  9. package/dist/capabilities/download/batch/journalKey.js +30 -0
  10. package/dist/capabilities/download/batch/journalKey.js.map +1 -0
  11. package/dist/capabilities/download/content/pdf/DownloadTier.d.ts +4 -0
  12. package/dist/capabilities/download/content/pdf/DownloadTier.d.ts.map +1 -1
  13. package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.d.ts.map +1 -1
  14. package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.js +2 -0
  15. package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.js.map +1 -1
  16. package/dist/capabilities/download/content/pdf/school.js +2 -0
  17. package/dist/capabilities/download/content/pdf/school.js.map +1 -1
  18. package/dist/capabilities/download/types.d.ts +4 -0
  19. package/dist/capabilities/download/types.d.ts.map +1 -1
  20. package/dist/cli.js +32 -9
  21. package/dist/cli.js.map +1 -1
  22. package/dist/infrastructure/school/SchoolMcpClient.d.ts +4 -0
  23. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  24. package/dist/infrastructure/school/SchoolMcpClient.js +20 -1
  25. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  26. package/dist/infrastructure/school/SchoolReadiness.d.ts +2 -0
  27. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  28. package/dist/infrastructure/school/SchoolReadiness.js +3 -0
  29. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  30. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  31. package/dist/infrastructure/school/SchoolResultNormalizer.js +5 -0
  32. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  33. package/dist/infrastructure/school/types.d.ts +12 -0
  34. package/dist/infrastructure/school/types.d.ts.map +1 -1
  35. package/dist/management/pro/activate.d.ts +36 -0
  36. package/dist/management/pro/activate.d.ts.map +1 -0
  37. package/dist/management/pro/activate.js +122 -0
  38. package/dist/management/pro/activate.js.map +1 -0
  39. package/dist/management/pro/install.d.ts +15 -0
  40. package/dist/management/pro/install.d.ts.map +1 -1
  41. package/dist/management/pro/install.js +39 -12
  42. package/dist/management/pro/install.js.map +1 -1
  43. package/dist/management/reports/index.d.ts +6 -0
  44. package/dist/management/reports/index.d.ts.map +1 -1
  45. package/dist/management/reports/index.js +6 -0
  46. package/dist/management/reports/index.js.map +1 -1
  47. package/dist/management/school/autoUpdate.d.ts.map +1 -1
  48. package/dist/management/school/autoUpdate.js +1 -0
  49. package/dist/management/school/autoUpdate.js.map +1 -1
  50. package/dist/management/school/cliProgress.d.ts.map +1 -1
  51. package/dist/management/school/cliProgress.js +1 -0
  52. package/dist/management/school/cliProgress.js.map +1 -1
  53. package/dist/management/school/settingsWindow.d.ts +1 -0
  54. package/dist/management/school/settingsWindow.d.ts.map +1 -1
  55. package/dist/management/school/settingsWindow.js +2 -0
  56. package/dist/management/school/settingsWindow.js.map +1 -1
  57. package/dist/management/updates/selfUpdate.d.ts +86 -0
  58. package/dist/management/updates/selfUpdate.d.ts.map +1 -0
  59. package/dist/management/updates/selfUpdate.js +194 -0
  60. package/dist/management/updates/selfUpdate.js.map +1 -0
  61. package/package.json +1 -1
  62. package/school/paper_search_school/adapters/annual_reviews/__init__.py +1 -0
  63. package/school/paper_search_school/adapters/ieee/__init__.py +1 -0
  64. package/school/paper_search_school/assets/capsule.html +1152 -206
  65. package/school/paper_search_school/assets/capsule_en.json +467 -19
  66. package/school/paper_search_school/assets/capsule_fr.json +1331 -0
  67. package/school/paper_search_school/assets/capsule_ja.json +1331 -0
  68. package/school/paper_search_school/assets/capsule_ko.json +1331 -0
  69. package/school/paper_search_school/assets/capsule_zh-Hant.json +2462 -0
  70. package/school/paper_search_school/browser/backend.py +15 -5
  71. package/school/paper_search_school/cli.py +15 -1
  72. package/school/paper_search_school/cold_start.py +70 -8
  73. package/school/paper_search_school/config.py +2 -0
  74. package/school/paper_search_school/download_diagnostics.py +4 -4
  75. package/school/paper_search_school/engine/batch_capture.py +37 -2
  76. package/school/paper_search_school/engine/batch_diagnostics.py +1 -1
  77. package/school/paper_search_school/engine/batch_institution.py +59 -0
  78. package/school/paper_search_school/engine/batch_login.py +117 -3
  79. package/school/paper_search_school/engine/batch_waits.py +42 -11
  80. package/school/paper_search_school/engine/bridge.py +11 -0
  81. package/school/paper_search_school/i18n.py +46 -22
  82. package/school/paper_search_school/orchestrator.py +60 -8
  83. package/school/paper_search_school/pro_status.py +54 -63
  84. package/school/paper_search_school/progress_capsule.py +349 -39
  85. package/school/paper_search_school/progress_reporter.py +51 -5
  86. package/school/paper_search_school/progress_view.py +3 -2
  87. package/school/paper_search_school/school_login.py +39 -2
  88. package/school/paper_search_school/school_switch.py +102 -0
  89. package/school/paper_search_school/school_test.py +335 -0
  90. package/school/paper_search_school/server.py +16 -0
  91. package/school/paper_search_school/updates.py +222 -0
  92. package/school/paper_search_school/user_settings.py +8 -3
  93. package/skills/paper-search/SKILL.md +1 -1
  94. package/skills/paper-search/references/browser-download.md +2 -2
  95. package/skills/paper-search/references/cli-contract.md +1 -1
  96. package/skills/paper-search/references/school-setup.md +1 -1
@@ -7,6 +7,7 @@ from __future__ import annotations
7
7
  import inspect
8
8
  import re
9
9
  import time
10
+ from collections.abc import Callable
10
11
  from contextlib import ExitStack
11
12
  from typing import Any
12
13
  from urllib.parse import urlparse
@@ -24,17 +25,21 @@ class UserWaitMixin:
24
25
  page: Any,
25
26
  result: DownloadResult,
26
27
  deadline: float,
28
+ until: Callable[[], bool] | None = None,
27
29
  ) -> bool:
30
+ """``until``: what the wait is for has arrived behind the verification page
31
+ (``_wait_for_challenge``)."""
28
32
  try:
29
33
  signature = inspect.signature(self._wait_for_challenge)
30
34
  except (TypeError, ValueError):
31
35
  return self._wait_for_challenge(page, result)
32
- accepts_deadline = "deadline" in signature.parameters or any(
33
- param.kind == inspect.Parameter.VAR_KEYWORD for param in signature.parameters.values()
34
- )
35
- if accepts_deadline:
36
- return self._wait_for_challenge(page, result, deadline=deadline)
37
- return self._wait_for_challenge(page, result)
36
+ any_keyword = any(param.kind == inspect.Parameter.VAR_KEYWORD for param in signature.parameters.values())
37
+ options: dict[str, Any] = {}
38
+ if "deadline" in signature.parameters or any_keyword:
39
+ options["deadline"] = deadline
40
+ if until is not None and ("until" in signature.parameters or any_keyword):
41
+ options["until"] = until
42
+ return self._wait_for_challenge(page, result, **options)
38
43
 
39
44
  # A wait off the school's login page (verification, the publisher's pages and
40
45
  # choosers, the PDF step): config ``browser_page_wait_timeout``, else this.
@@ -433,7 +438,7 @@ class UserWaitMixin:
433
438
  if self._press_confirm_control(page, result, attempt, deadline):
434
439
  return True
435
440
  return False
436
- if ((attempt["attempts"] >= 3 and now >= attempt["retry_at"])
441
+ if ((attempt["attempts"] >= 2 and now >= attempt["retry_at"])
437
442
  or (attempt.get("unavailable") and now >= attempt["handoff_at"])):
438
443
  return False
439
444
  if now >= automatic_end:
@@ -441,7 +446,15 @@ class UserWaitMixin:
441
446
  return True
442
447
  if self._recover_stuck_widget(page, result, attempt):
443
448
  return True
444
- if now >= attempt["retry_at"] and attempt["attempts"] < 3:
449
+ if now >= attempt["retry_at"] and attempt["attempts"] < 2:
450
+ if attempt.get("managed"):
451
+ if challenge_interaction.verification_widget(page):
452
+ # The widget appeared after all (a frame that drew late):
453
+ # back to pressing it, with the budget that is left.
454
+ attempt["managed"] = False
455
+ else:
456
+ attempt["retry_at"] = now + 3
457
+ return True
445
458
  reasons = []
446
459
  outcome = challenge_interaction.click_checkbox(
447
460
  page, timeout_ms=min(2500, max(1, int((automatic_end - now) * 1000))),
@@ -450,6 +463,15 @@ class UserWaitMixin:
450
463
  attempt=attempt["attempts"],
451
464
  )
452
465
  reason = ", ".join(dict.fromkeys(reasons)) or outcome
466
+ if outcome == "absent" and not challenge_interaction.verification_widget(page):
467
+ # Nothing was pressed and the page holds no widget: Cloudflare's
468
+ # managed challenge (or an iframe still loading). A managed one
469
+ # clears on its own; waiting is the only move, and the wait must
470
+ # not be spent on presses that cannot happen.
471
+ attempt["managed"] = True
472
+ self._event(result, "challenge_managed",
473
+ "no widget on the page: waiting for the challenge to clear")
474
+ return True
453
475
  if reason != attempt.get("last_observation"):
454
476
  self._event(result, "challenge_observation", reason)
455
477
  attempt["last_observation"] = reason
@@ -462,7 +484,7 @@ class UserWaitMixin:
462
484
  if activity is not None:
463
485
  activity.progress(page)
464
486
  self._event(result, "challenge_interaction",
465
- f"checkbox clicked; attempt {attempt['attempts']}/3; awaiting verification")
487
+ f"checkbox clicked; attempt {attempt['attempts']}/2; awaiting verification")
466
488
  names = [str(item.get("event"))
467
489
  for item in challenge_interaction.interaction_events(page)]
468
490
  if names:
@@ -554,8 +576,12 @@ class UserWaitMixin:
554
576
  else:
555
577
  progress_reporter.update_attention_deadline(key, deadline)
556
578
 
557
- def _wait_for_challenge(self, page: Any, result: DownloadResult, *, deadline: float | None = None) -> bool:
558
- """Wait while a verification page is up, until ``_wait_deadline``."""
579
+ def _wait_for_challenge(self, page: Any, result: DownloadResult, *, deadline: float | None = None,
580
+ until: Callable[[], bool] | None = None) -> bool:
581
+ """Wait while a verification page is up, until ``_wait_deadline``. ``until``: the
582
+ wait ends, as passed, once it says what it waits for has arrived though the page
583
+ is still up (the PDF's answer, captured while ScienceDirect's tab stayed on "Just
584
+ a moment...": two articles failed with the PDF in hand, 2026-11-21)."""
559
585
  interaction = ExitStack()
560
586
  activity, activity_owned = self._observe_page_activity(page, result)
561
587
  automatic: dict[str, Any] = {}
@@ -570,6 +596,11 @@ class UserWaitMixin:
570
596
  checks = 0
571
597
  while True:
572
598
  self._check_user_decision(result, page)
599
+ if until is not None and until():
600
+ if waited:
601
+ result.state = state_before
602
+ self._event(result, "challenge_wait_ended", "what it waited for arrived")
603
+ return True
573
604
  # While the interstitial is up, look only at title and URL.
574
605
  shell = self._challenge_shell(page)
575
606
  if not shell:
@@ -42,6 +42,9 @@ _FAILURE_KINDS = {
42
42
  "browser_unresponsive": ("browser_unresponsive", "review_browser"),
43
43
  "browser_operation_timeout": ("browser_operation_timeout", "review_browser"),
44
44
  "publisher_access_blocked": ("access_blocked", "review_access"),
45
+ # The site said its downloads are used up for now (batch_capture ``_note_download_limit``):
46
+ # like a block, the journal's later articles wait and one re-checks now and then.
47
+ "publisher_download_limit": ("access_blocked", "review_access"),
45
48
  "publisher_unreachable": ("publisher_unreachable", "review_publisher_error"),
46
49
  "sso_required": ("paywall", "login_required"),
47
50
  "institution_pdf_entitlement_missing": ("paywall", "review_entitlement"),
@@ -124,9 +127,17 @@ def _failure_reason_code(result: Any) -> str:
124
127
  reason_code = "login_timeout" if wait_page in ("school_login", "school_choice") else "login_not_reached"
125
128
  elif reason_code == "sso_required" and getattr(result, "_user_wait_expired", False):
126
129
  reason_code = "login_timeout" # the login waited on the user until its time was up
130
+ if getattr(result, "_download_limit", "") and reason_code in _PDF_NOT_ARRIVED:
131
+ # The site had said its downloads were used up: that, not the wait, is why.
132
+ reason_code = "publisher_download_limit"
127
133
  return reason_code
128
134
 
129
135
 
136
+ # Failures that only say the PDF did not come (a site's download-limit notice says why).
137
+ _PDF_NOT_ARRIVED = frozenset({"challenge_or_viewer_timeout", "pdf_not_captured", "download_failed",
138
+ "request_failed", "download_timeout", "browser_operation_timeout", ""})
139
+
140
+
130
141
  def try_institutional(
131
142
  doi: str,
132
143
  output_path: Path,
@@ -1,8 +1,10 @@
1
- """The progress window in English: ``assets/capsule_en.json`` maps each Chinese
2
- text it can show (its own, the download's prompts and phases, PaperSearch's
3
- failure reasons) to a short English one. The page translates what it shows with
4
- it; the system notifications use it here. A text the table does not know stays
5
- as it is."""
1
+ """The progress window in other languages than its own simplified Chinese: ``assets/capsule_en.json`` maps each
2
+ Chinese text it can show (its own, the download's prompts and phases, PaperSearch's failure reasons) to a short
3
+ English one; ``assets/capsule_zh-Hant.json`` (made from it by ``school/tools/zh_hant_table.py``, user 2026-11-21)
4
+ says each in Traditional Chinese, and turns any other text character by character; ``capsule_ja.json``,
5
+ ``capsule_ko.json`` and ``capsule_fr.json`` say them in Japanese, Korean and French (user, 2026-11-21), a text they
6
+ do not know in English. The page translates what it shows with them; the system notifications use them here. In
7
+ English a text the table does not know stays as it is."""
6
8
  from __future__ import annotations
7
9
 
8
10
  import json
@@ -10,42 +12,64 @@ import re
10
12
  from functools import lru_cache
11
13
  from pathlib import Path
12
14
 
13
- TABLE = Path(__file__).resolve().parent / "assets" / "capsule_en.json"
14
- LANGUAGES = ("zh", "en")
15
+ ASSETS = Path(__file__).resolve().parent / "assets"
16
+ #: Each language's table; Chinese (zh, simplified) is the windows' own.
17
+ TABLES = {"en": ASSETS / "capsule_en.json", "zh-Hant": ASSETS / "capsule_zh-Hant.json",
18
+ "ja": ASSETS / "capsule_ja.json", "ko": ASSETS / "capsule_ko.json", "fr": ASSETS / "capsule_fr.json"}
19
+ TABLE = TABLES["en"]
20
+ LANGUAGES = ("zh", "zh-Hant", "en", "ja", "ko", "fr")
15
21
  _HAN = re.compile(r"[\u4e00-\u9fff]")
16
22
  _BRACKETS = re.compile(r"^(.+?)((.+))$")
23
+ _LISTED = re.compile(r"^([^:]+):(.+)$")
17
24
 
18
25
 
19
- @lru_cache(maxsize=1)
20
- def table() -> dict:
21
- return json.loads(TABLE.read_text(encoding="utf-8"))
26
+ @lru_cache(maxsize=None)
27
+ def table(lang: str = "en") -> dict:
28
+ return json.loads(TABLES[lang].read_text(encoding="utf-8"))
22
29
 
23
30
 
24
- @lru_cache(maxsize=1)
25
- def _patterns() -> list[tuple[re.Pattern, str]]:
26
- # The table's replacements are written for JavaScript ($1); Python's are \g<1>.
27
- return [(re.compile(source), re.sub(r"\$(\d)", r"\\g<\1>", target)) for source, target in table()["patterns"]]
31
+ @lru_cache(maxsize=None)
32
+ def _patterns(lang: str = "en") -> list[tuple[re.Pattern, str]]:
33
+ return [(re.compile(source), target) for source, target in table(lang)["patterns"]]
28
34
 
29
35
 
30
- def _one(text: str) -> str:
36
+ def _part(text: str, lang: str) -> str:
37
+ return _one(text, lang) if _HAN.search(text) else text
38
+
39
+
40
+ def _one(text: str, lang: str = "en") -> str:
31
41
  core = text.strip()
32
42
  if not core or not _HAN.search(core):
33
43
  return text
34
- exact = table()["exact"].get(core)
44
+ exact = table(lang)["exact"].get(core)
35
45
  if exact is None:
36
- for pattern, target in _patterns():
37
- if pattern.search(core):
38
- exact = pattern.sub(target, core)
46
+ for pattern, target in _patterns(lang):
47
+ found = pattern.search(core)
48
+ if found:
49
+ # What it names is said too where it is a text of the table; a name keeps its words (as the page does).
50
+ said = re.sub(r"\$(\d)", lambda m: _part(found.group(int(m.group(1))) or "", lang), target)
51
+ exact = core[:found.start()] + said + core[found.end():]
39
52
  break
53
+ if exact is None and lang == "zh-Hant":
54
+ # Not a text of the table: its characters (a name keeps its words).
55
+ chars = table(lang)["chars"]
56
+ exact = "".join(chars.get(c, c) for c in core)
40
57
  parts = _BRACKETS.match(core) if exact is None else None
41
58
  if parts:
42
59
  # "开放下载 18(出版社 API 3、预印本 1)": the text and what its brackets list, each on its own.
43
- exact = f"{_one(parts[1])} ({', '.join(_one(item) for item in parts[2].split('、'))})"
60
+ exact = f"{_one(parts[1], lang)} ({', '.join(_one(item, lang) for item in parts[2].split('、'))})"
61
+ listed = _LISTED.match(core) if exact is None else None
62
+ if listed and _one(listed[1], lang) != listed[1]:
63
+ # "读取失败:TimeoutError": a known word, then what it says, each on its own (as the page does).
64
+ exact = f"{_one(listed[1], lang)}: {', '.join(_one(item, lang) for item in listed[2].split(','))}"
65
+ if exact is None and lang not in ("en", "zh-Hant"):
66
+ # Japanese, Korean, French: what their table does not know, in English rather than in Chinese.
67
+ return _one(text, "en")
44
68
  return text if exact is None else text.replace(core, exact)
45
69
 
46
70
 
47
71
  def translate(text: str, lang: str) -> str:
48
72
  """``text`` in ``lang``; its " · " parts one by one, as the page does."""
49
- if lang != "en" or not text:
73
+ if lang not in TABLES or not text:
50
74
  return text
51
- return " · ".join(_one(part) for part in text.split(" · "))
75
+ return " · ".join(_one(part, lang) for part in text.split(" · "))
@@ -45,9 +45,13 @@ def download_institutional(
45
45
  login_wait: int | None = None,
46
46
  fulltext: bool | str | None = None,
47
47
  school: str | None = None,
48
+ fresh: bool = False,
48
49
  ) -> dict[str, Any]:
49
50
  """Download one DOI through institutional access only.
50
51
 
52
+ ``fresh`` (the settings' 测试登录, school_test.py): neither from the cache nor into it: the download itself is
53
+ what is tested.
54
+
51
55
  ``login_only`` (``login``): the download's own steps up to the article's
52
56
  access, then stop: no PDF, nothing cached. ``login_wait``: seconds to wait
53
57
  on the school's login page instead of the setting.
@@ -97,6 +101,8 @@ def download_institutional(
97
101
  extra["login_wait"] = login_wait
98
102
  if school and school.strip():
99
103
  extra["school"] = school.strip()
104
+ if fresh:
105
+ extra["fresh"] = True
100
106
  return _download_impl(doi, output_dir, **extra)
101
107
  finally:
102
108
  with _INFLIGHT_LOCK:
@@ -107,7 +113,7 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
107
113
  supplements: str | None = None, user_wait: str | None = None,
108
114
  diagnostics_dir: str | None = None, title: str | None = None,
109
115
  login_only: bool = False, login_wait: int | None = None,
110
- fulltext: str | None = None, school: str | None = None) -> dict[str, Any]:
116
+ fulltext: str | None = None, school: str | None = None, fresh: bool = False) -> dict[str, Any]:
111
117
  config = load_config()
112
118
  if school:
113
119
  # Another saved school for this download alone, as the user asked; the config's own
@@ -146,7 +152,7 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
146
152
  config["diagnostics_dir"] = str(Path(diagnostics_dir).resolve())
147
153
  output_path = target_dir / f"{safe_filename(doi)}.pdf"
148
154
 
149
- cached = None if login_only else cache_get(doi, config)
155
+ cached = None if login_only or fresh else cache_get(doi, config)
150
156
  if cached and cached.get("success"):
151
157
  cached_file = Path(str(cached.get("file") or ""))
152
158
  if cached_file.exists() and is_pdf_file(cached_file):
@@ -161,12 +167,56 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
161
167
  return cached
162
168
 
163
169
  log.info(f"paper-search-school - {doi}")
164
-
165
- try:
166
- result = try_institutional(doi, output_path, config)
167
- except Exception as exc:
168
- log.info(f" [Institutional] route exception: {type(exc).__name__}")
169
- return fail(doi, "institutional route raised", error_type="source_exception", action="review_logs")
170
+ # Another school than the one the browser last signed in with: that sign-in forgotten first; a test
171
+ # (``fresh``) always starts signed out, so that the account is what it tries (user, 2026-11-21).
172
+ from .cold_start import before_sign_in
173
+ from . import school_switch
174
+ from .schools import saved as saved_schools
175
+
176
+ # 没权限时换下一所学校 (school_switch.py): the schools to try in turn, its journal's school of this task first.
177
+ # One alone: the switch off, a school named for this download, the test of one, a sign-in only.
178
+ turns = (school_switch.order_for(config, doi) if school_switch.enabled(config) and not school and not fresh
179
+ and not login_only else [])
180
+ if turns and not saved_schools.is_current(config, turns[0]):
181
+ saved_schools.apply(config, turns[0])
182
+ turn = 0
183
+ while True:
184
+ signed = before_sign_in(config, always=fresh)
185
+ if signed == "cleared":
186
+ log.info(" [Institutional] the browser's sign-in with another school forgotten")
187
+ elif signed == "busy" and fresh:
188
+ return fail(doi, "the download browser is open", error_type="browser_busy", action="close_browser")
189
+
190
+ try:
191
+ result = try_institutional(doi, output_path, config)
192
+ except Exception as exc:
193
+ log.info(f" [Institutional] route exception: {type(exc).__name__}")
194
+ return fail(doi, "institutional route raised", error_type="source_exception", action="review_logs")
195
+ if turn + 1 >= len(turns) or not school_switch.no_access(result):
196
+ break
197
+ # Signed in, no access: the next school, its sign-in after this one's is forgotten (the batch's browser closed
198
+ # first to let go of it; one that will not let go ends the turns: the next would try this school's session).
199
+ turn += 1
200
+ following = turns[turn]
201
+ log.info(f" [Institutional] no access with {school_switch.name(turns[turn - 1])}; next: {school_switch.name(following)}")
202
+ from . import progress_reporter
203
+ from .browser.batch_session import active_batch
204
+
205
+ progress_reporter.update(stage="switching_school", phase=f"没权限,换{school_switch.name(following)}")
206
+ batch = active_batch.get()
207
+ if batch is not None:
208
+ batch.close()
209
+ saved_schools.apply(config, following)
210
+ if before_sign_in(config) == "busy":
211
+ log.info(" [Institutional] the browser kept the last school's sign-in; no other school tried")
212
+ turn -= 1
213
+ break
214
+ if len(turns) > 1 and result and result.get("success"):
215
+ school_switch.remember(doi, str(config.get("idp_entity_id") or "").strip())
216
+ if turn or not saved_schools.is_current(load_config(), turns[turn]):
217
+ result["school"] = school_switch.name(turns[turn]) # not the default school's: the results say whose
218
+ elif turns and turn and school_switch.no_access(result):
219
+ result["schools_tried"] = turn + 1 # the lists say "N 所学校都没有权限"
170
220
  # An article that re-checked a blocked journal's site: open again unless blocked again.
171
221
  from . import blocked_journals
172
222
  blocked_journals.recheck_ended(doi, blocked=bool(result) and result.get("error_type") == "access_blocked")
@@ -193,5 +243,7 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
193
243
  result.setdefault("doi", doi)
194
244
  result["file"] = str(file_path)
195
245
  result.setdefault("size_kb", round(file_path.stat().st_size / 1024, 1))
246
+ if fresh:
247
+ return result
196
248
  cache_set(doi, result, config)
197
249
  return result
@@ -6,6 +6,7 @@ from __future__ import annotations
6
6
 
7
7
  import json
8
8
  import os
9
+ import re
9
10
  from pathlib import Path
10
11
  from typing import Any, Mapping
11
12
  from urllib.parse import quote
@@ -47,7 +48,7 @@ def status(env: Mapping[str, str] | None = None) -> dict[str, Any]:
47
48
  command line counts) and whether Pro is free now (pro/access.json, which Pro keeps)."""
48
49
  path = entry(env)
49
50
  if not path.is_file():
50
- return {"installed": False, "version": ""}
51
+ return {"installed": False, "version": "", "activation": activation(env)}
51
52
  manifest = _read(path.parent / "pro.json")
52
53
  sites = manifest.get("sites")
53
54
  stats = _read(data_home(env) / "pro" / "stats.json")
@@ -62,9 +63,28 @@ def status(env: Mapping[str, str] | None = None) -> dict[str, Any]:
62
63
  "complete": min(converted, _count(stats.get("complete"))),
63
64
  "access": {"mode": access.get("mode") if access.get("mode") in ("free", "key") else "free",
64
65
  "until": _day(until)},
66
+ "activation": activation(env),
65
67
  }
66
68
 
67
69
 
70
+ _DAY = re.compile(r"^\d{4}-\d{2}-\d{2}$")
71
+
72
+
73
+ def activation(env: Mapping[str, str] | None = None) -> dict[str, str]:
74
+ """Whether this computer is activated (user, 2026-11-21), from ``pro/activation.json``, which
75
+ ``paper-search pro activate`` keeps (src/management/pro/activate.ts): none, active or expired,
76
+ the code's last four characters and the day it ends. The code itself is not handed on."""
77
+ record = _read(data_home(env) / "pro" / "activation.json")
78
+ code = record.get("code")
79
+ if not isinstance(code, str) or not code:
80
+ return {"state": "none", "tail": "", "until": ""}
81
+ until = record.get("until") if isinstance(record.get("until"), str) and _DAY.match(record["until"]) else ""
82
+ import time
83
+
84
+ expired = bool(until) and until < time.strftime("%Y-%m-%d", time.localtime())
85
+ return {"state": "expired" if expired else "active", "tail": code[-4:], "until": until}
86
+
87
+
68
88
  def _day(ms: Any) -> str:
69
89
  """A free setting's end ("2027-03-01"), from Pro's milliseconds; "" for none."""
70
90
  import time
@@ -74,64 +94,11 @@ def _day(ms: Any) -> str:
74
94
  return time.strftime("%Y-%m-%d", time.localtime(ms / 1000))
75
95
 
76
96
 
77
- class ProCheck:
78
- """The Markdown page's 检查更新: ``paper-search pro check`` in the background (user, 2026-11-19);
79
- the page asks for ``state()`` until it is done: the newest version and whether it is newer."""
80
-
81
- def __init__(self, command_of=None, run=None):
82
- import threading
83
-
84
- from .api_keys import paper_search_command
85
-
86
- self._command_of = command_of or paper_search_command
87
- self._run_command = run
88
- self._lock = threading.Lock()
89
- self._state: dict[str, Any] = {"state": "idle"}
90
-
91
- def state(self) -> dict[str, Any]:
92
- with self._lock:
93
- return dict(self._state)
94
-
95
- def start(self) -> dict[str, Any]:
96
- import threading
97
-
98
- with self._lock:
99
- if self._state.get("state") == "running":
100
- return dict(self._state)
101
- self._state = {"state": "running"}
102
- threading.Thread(target=self._check, name="pro-check", daemon=True).start()
103
- return {"state": "running"}
104
-
105
- def _check(self) -> None:
106
- import subprocess
107
-
108
- command = self._command_of()
109
- answer: dict[str, Any] = {}
110
- if command is None:
111
- answer = {"ok": False, "message": "找不到 paper-search 命令"}
112
- else:
113
- env = {**os.environ, "PAPER_SEARCH_SKILL_AUTO_UPDATE": "false", "PAPER_SEARCH_UPDATE_NOTIFY": "false"}
114
- try:
115
- run = self._run_command or (lambda argv: subprocess.run(
116
- argv, capture_output=True, encoding="utf-8", errors="replace", env=env, timeout=60).stdout)
117
- lines = [line for line in str(run([*command, "pro", "check"]) or "").splitlines() if line.strip()]
118
- answer = json.loads(lines[-1]) if lines else {}
119
- except Exception:
120
- answer = {}
121
- with self._lock:
122
- if isinstance(answer, dict) and answer.get("ok") is True:
123
- self._state = {"state": "done", "latest": str(answer.get("latest") or ""),
124
- "update": answer.get("update") is True}
125
- else:
126
- message = answer.get("message") if isinstance(answer, dict) else ""
127
- self._state = {"state": "failed", "message": str(message or "检查更新出错")}
128
-
129
-
130
97
  class ProInstall:
131
98
  """The settings window's 安装: ``paper-search pro install --progress`` in the background, its
132
99
  progress lines read as they come; the page asks for ``state()`` until it is done or failed."""
133
100
 
134
- def __init__(self, command_of=None, popen=None):
101
+ def __init__(self, command_of=None, popen=None, run=None):
135
102
  import subprocess
136
103
  import threading
137
104
 
@@ -139,6 +106,7 @@ class ProInstall:
139
106
 
140
107
  self._command_of = command_of or paper_search_command
141
108
  self._popen = popen or subprocess.Popen
109
+ self._run_command = run or subprocess.run
142
110
  self._lock = threading.Lock()
143
111
  self._state: dict[str, Any] = {"state": "idle"}
144
112
 
@@ -150,25 +118,47 @@ class ProInstall:
150
118
  with self._lock:
151
119
  self._state = state
152
120
 
153
- def start(self) -> dict[str, Any]:
121
+ def start(self, code: str | None = None) -> dict[str, Any]:
122
+ """安装, or with the code typed on Pro's page 激活并安装: ``paper-search pro activate`` first
123
+ (user, 2026-11-21), the code handed on standard input; the install only once it is active."""
154
124
  import threading
155
125
 
156
126
  with self._lock:
157
127
  if self._state.get("state") == "running":
158
128
  return dict(self._state)
159
- self._state = started = {"state": "running", "done": 0, "total": 0}
160
- threading.Thread(target=self._run, name="pro-install", daemon=True).start()
129
+ activating = code is not None
130
+ self._state = started = ({"state": "running", "step": "activate"} if activating
131
+ else {"state": "running", "step": "install", "done": 0, "total": 0})
132
+ threading.Thread(target=self._run, args=(code,), name="pro-install", daemon=True).start()
161
133
  return dict(started)
162
134
 
163
- def _run(self) -> None:
135
+ def _activate(self, command: list[str], env: dict[str, str], code: str) -> bool:
136
+ try:
137
+ run = self._run_command([*command, "pro", "activate"], input=code, capture_output=True, encoding="utf-8",
138
+ errors="replace", env=env, timeout=60)
139
+ lines = [line for line in (run.stdout or "").splitlines() if line.strip()]
140
+ answer = json.loads(lines[-1]) if lines else {}
141
+ except Exception:
142
+ answer = {}
143
+ if isinstance(answer, dict) and answer.get("ok") is True:
144
+ return True
145
+ message = answer.get("message") or answer.get("error") if isinstance(answer, dict) else ""
146
+ self._set(state="failed", step="activate", message=str(message or "激活出错"))
147
+ return False
148
+
149
+ def _run(self, code: str | None = None) -> None:
164
150
  import subprocess
165
151
 
166
152
  command = self._command_of()
167
153
  if command is None:
168
- self._set(state="failed", message="找不到 paper-search 命令")
154
+ self._set(state="failed", step="activate" if code is not None else "install", message="找不到 paper-search 命令")
169
155
  return
170
156
  # An install must not also update the Skill or check for a new version.
171
157
  env = {**os.environ, "PAPER_SEARCH_SKILL_AUTO_UPDATE": "false", "PAPER_SEARCH_UPDATE_NOTIFY": "false"}
158
+ if code is not None:
159
+ if not self._activate(command, env, code):
160
+ return
161
+ self._set(state="running", step="install", done=0, total=0)
172
162
  last: dict[str, Any] = {}
173
163
  try:
174
164
  process = self._popen([*command, "pro", "install", "--progress"], stdout=subprocess.PIPE,
@@ -179,14 +169,15 @@ class ProInstall:
179
169
  except ValueError:
180
170
  continue
181
171
  if isinstance(message, dict) and message.get("event") == "progress":
182
- self._set(state="running", done=int(message.get("done") or 0), total=int(message.get("total") or 0))
172
+ self._set(state="running", step="install", done=int(message.get("done") or 0),
173
+ total=int(message.get("total") or 0))
183
174
  elif isinstance(message, dict):
184
175
  last = message
185
176
  process.wait(timeout=60)
186
177
  except Exception:
187
- self._set(state="failed", message="安装出错")
178
+ self._set(state="failed", step="install", message="安装出错")
188
179
  return
189
180
  if last.get("ok") is True:
190
181
  self._set(state="done", version=str(last.get("version") or ""))
191
182
  else:
192
- self._set(state="failed", message=str(last.get("message") or last.get("error") or "安装出错"))
183
+ self._set(state="failed", step="install", message=str(last.get("message") or last.get("error") or "安装出错"))