papersearch 0.7.1 → 0.7.3

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 (126) hide show
  1. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  2. package/dist/capabilities/download/batch/batch.js +306 -12
  3. package/dist/capabilities/download/batch/batch.js.map +1 -1
  4. package/dist/capabilities/download/batch/batchFolder.js +1 -1
  5. package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
  6. package/dist/capabilities/download/batch/batchSummary.d.ts.map +1 -1
  7. package/dist/capabilities/download/batch/batchSummary.js +17 -8
  8. package/dist/capabilities/download/batch/batchSummary.js.map +1 -1
  9. package/dist/capabilities/download/batch/journalKey.d.ts +12 -0
  10. package/dist/capabilities/download/batch/journalKey.d.ts.map +1 -0
  11. package/dist/capabilities/download/batch/journalKey.js +30 -0
  12. package/dist/capabilities/download/batch/journalKey.js.map +1 -0
  13. package/dist/capabilities/download/batch/networkLoss.d.ts +1 -1
  14. package/dist/capabilities/download/batch/networkLoss.js +1 -1
  15. package/dist/capabilities/download/content/markdown/shortfall.js +5 -5
  16. package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
  17. package/dist/capabilities/download/content/pdf/DownloadTier.d.ts +4 -0
  18. package/dist/capabilities/download/content/pdf/DownloadTier.d.ts.map +1 -1
  19. package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.d.ts.map +1 -1
  20. package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.js +2 -0
  21. package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.js.map +1 -1
  22. package/dist/capabilities/download/content/pdf/school.js +2 -0
  23. package/dist/capabilities/download/content/pdf/school.js.map +1 -1
  24. package/dist/capabilities/download/types.d.ts +4 -0
  25. package/dist/capabilities/download/types.d.ts.map +1 -1
  26. package/dist/cli.js +32 -9
  27. package/dist/cli.js.map +1 -1
  28. package/dist/infrastructure/runlog/failureClass.d.ts +16 -9
  29. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  30. package/dist/infrastructure/runlog/failureClass.js +64 -54
  31. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  32. package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
  33. package/dist/infrastructure/school/SchoolAttempt.js +61 -56
  34. package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
  35. package/dist/infrastructure/school/SchoolMcpClient.d.ts +9 -1
  36. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  37. package/dist/infrastructure/school/SchoolMcpClient.js +31 -1
  38. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  39. package/dist/infrastructure/school/SchoolReadiness.d.ts +2 -0
  40. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  41. package/dist/infrastructure/school/SchoolReadiness.js +3 -0
  42. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  43. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  44. package/dist/infrastructure/school/SchoolResultNormalizer.js +5 -0
  45. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  46. package/dist/infrastructure/school/index.d.ts +1 -1
  47. package/dist/infrastructure/school/index.d.ts.map +1 -1
  48. package/dist/infrastructure/school/types.d.ts +19 -0
  49. package/dist/infrastructure/school/types.d.ts.map +1 -1
  50. package/dist/management/failures/index.d.ts +5 -2
  51. package/dist/management/failures/index.d.ts.map +1 -1
  52. package/dist/management/failures/index.js +21 -4
  53. package/dist/management/failures/index.js.map +1 -1
  54. package/dist/management/pro/activate.d.ts +36 -0
  55. package/dist/management/pro/activate.d.ts.map +1 -0
  56. package/dist/management/pro/activate.js +122 -0
  57. package/dist/management/pro/activate.js.map +1 -0
  58. package/dist/management/pro/install.d.ts +15 -0
  59. package/dist/management/pro/install.d.ts.map +1 -1
  60. package/dist/management/pro/install.js +39 -12
  61. package/dist/management/pro/install.js.map +1 -1
  62. package/dist/management/reports/index.d.ts +6 -0
  63. package/dist/management/reports/index.d.ts.map +1 -1
  64. package/dist/management/reports/index.js +6 -0
  65. package/dist/management/reports/index.js.map +1 -1
  66. package/dist/management/school/autoUpdate.d.ts.map +1 -1
  67. package/dist/management/school/autoUpdate.js +1 -0
  68. package/dist/management/school/autoUpdate.js.map +1 -1
  69. package/dist/management/school/cliProgress.d.ts.map +1 -1
  70. package/dist/management/school/cliProgress.js +1 -0
  71. package/dist/management/school/cliProgress.js.map +1 -1
  72. package/dist/management/school/settingsWindow.d.ts +1 -0
  73. package/dist/management/school/settingsWindow.d.ts.map +1 -1
  74. package/dist/management/school/settingsWindow.js +2 -0
  75. package/dist/management/school/settingsWindow.js.map +1 -1
  76. package/dist/management/updates/selfUpdate.d.ts +86 -0
  77. package/dist/management/updates/selfUpdate.d.ts.map +1 -0
  78. package/dist/management/updates/selfUpdate.js +194 -0
  79. package/dist/management/updates/selfUpdate.js.map +1 -0
  80. package/package.json +1 -1
  81. package/school/paper_search_school/adapters/annual_reviews/__init__.py +1 -0
  82. package/school/paper_search_school/adapters/base.py +4 -0
  83. package/school/paper_search_school/adapters/ieee/__init__.py +1 -0
  84. package/school/paper_search_school/adapters/oup/__init__.py +20 -0
  85. package/school/paper_search_school/adapters/sage/__init__.py +4 -1
  86. package/school/paper_search_school/adapters/taylor_francis/__init__.py +3 -0
  87. package/school/paper_search_school/adapters/thieme/__init__.py +4 -2
  88. package/school/paper_search_school/assets/capsule.html +1044 -243
  89. package/school/paper_search_school/assets/capsule_en.json +320 -74
  90. package/school/paper_search_school/assets/capsule_fr.json +1309 -0
  91. package/school/paper_search_school/assets/capsule_ja.json +1309 -0
  92. package/school/paper_search_school/assets/capsule_ko.json +1309 -0
  93. package/school/paper_search_school/assets/capsule_zh-Hant.json +2436 -0
  94. package/school/paper_search_school/cli.py +15 -1
  95. package/school/paper_search_school/cold_start.py +82 -9
  96. package/school/paper_search_school/config.py +2 -0
  97. package/school/paper_search_school/download_diagnostics.py +4 -4
  98. package/school/paper_search_school/engine/access_rules.py +3 -2
  99. package/school/paper_search_school/engine/batch.py +12 -4
  100. package/school/paper_search_school/engine/batch_access.py +21 -9
  101. package/school/paper_search_school/engine/batch_capture.py +36 -2
  102. package/school/paper_search_school/engine/batch_diagnostics.py +1 -1
  103. package/school/paper_search_school/engine/batch_institution.py +171 -29
  104. package/school/paper_search_school/engine/batch_login.py +65 -1
  105. package/school/paper_search_school/engine/batch_waits.py +22 -8
  106. package/school/paper_search_school/engine/bridge.py +27 -3
  107. package/school/paper_search_school/engine/router.py +2 -1
  108. package/school/paper_search_school/i18n.py +46 -22
  109. package/school/paper_search_school/orchestrator.py +90 -12
  110. package/school/paper_search_school/pro_status.py +54 -63
  111. package/school/paper_search_school/progress_capsule.py +180 -24
  112. package/school/paper_search_school/progress_reporter.py +68 -13
  113. package/school/paper_search_school/progress_view.py +4 -3
  114. package/school/paper_search_school/publishers/builtin/sage.json +4 -2
  115. package/school/paper_search_school/publishers/builtin/thieme.json +3 -1
  116. package/school/paper_search_school/school_login.py +18 -4
  117. package/school/paper_search_school/school_switch.py +84 -0
  118. package/school/paper_search_school/school_test.py +335 -0
  119. package/school/paper_search_school/server.py +21 -3
  120. package/school/paper_search_school/updates.py +222 -0
  121. package/school/paper_search_school/user_settings.py +8 -3
  122. package/skills/paper-search/SKILL.md +1 -1
  123. package/skills/paper-search/references/browser-download.md +7 -9
  124. package/skills/paper-search/references/cli-contract.md +1 -1
  125. package/skills/paper-search/references/publisher-support.md +2 -2
  126. package/skills/paper-search/references/school-setup.md +1 -1
@@ -0,0 +1,335 @@
1
+ """The sign-in page's 测试登录 (PaperSearch Pro; user, 2026-11-21): one article downloaded with a saved school's
2
+ account, the way a download goes (the school chosen, its sign-in filled in, back to the article, the PDF fetched and
3
+ checked), to see that the account works; the PDF is deleted after. It starts signed out (the download browser's school
4
+ sign-ins and publisher sessions forgotten, cold_start.before_sign_in): a session left by another school, or by this one,
5
+ would open the article without the account.
6
+
7
+ The article: the one the user set for the school (its DOI or its page's address, ``set_article``); none is set for
8
+ them (user, 2026-11-21: they fill it in themselves, one their school subscribes to). The test runs as a process of its own
9
+ (``python -m paper_search_school.cli school-test``) that reports as a download does (the window's progress file) and
10
+ writes its verdict to ``progress/school-test.json``; the window asks ``SchoolTest.state()`` until it ends. It stops the
11
+ way the card's 终止任务 stops a download.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import html
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import threading
24
+ import time
25
+ import urllib.parse
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ from .data_home import default_data_dir
30
+
31
+ #: The task the progress file names while a test runs.
32
+ TASK = "学校登录测试"
33
+ #: The steps the page shows, by the download's stage (progress_reporter.STAGES).
34
+ STEPS = ("打开文章页", "学校登录", "下载全文", "核对 PDF")
35
+ STAGE_STEP = {"starting": 0, "opening_article": 0, "checking_access": 1, "waiting_login": 1, "waiting_verification": 1,
36
+ "route_failed": 1, "fetching_pdf": 2, "pdf_captured": 3, "saved_pending_verification": 3}
37
+ #: How long a stopped test may take to end before its process is ended.
38
+ STOP_GRACE = 30.0
39
+ AGENT = {"User-Agent": "Mozilla/5.0 (PaperSearch school test; +https://github.com/dr-dumpling/papersearch)"}
40
+
41
+
42
+ def _articles_path() -> Path:
43
+ return default_data_dir() / "school_test_articles.json"
44
+
45
+
46
+ def result_path() -> Path:
47
+ return default_data_dir() / "progress" / "school-test.json"
48
+
49
+
50
+ def _read(path: Path) -> dict[str, Any]:
51
+ try:
52
+ data = json.loads(path.read_text(encoding="utf-8"))
53
+ except (OSError, ValueError):
54
+ return {}
55
+ return data if isinstance(data, dict) else {}
56
+
57
+
58
+ def _write(path: Path, data: dict[str, Any]) -> None:
59
+ path.parent.mkdir(parents=True, exist_ok=True)
60
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.")
61
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
62
+ json.dump(data, fh, ensure_ascii=False)
63
+ os.replace(tmp, path)
64
+
65
+
66
+ # -- the article ----------------------------------------------------------------------------------
67
+
68
+ def article(entity_id: str) -> dict[str, Any]:
69
+ """The article this school's test opens: {doi}, "" while none is set."""
70
+ return {"doi": str((_read(_articles_path()).get(entity_id) or {}).get("doi") or "") if entity_id else ""}
71
+
72
+
73
+ def set_article(entity_id: str, text: str, fetch=None) -> dict[str, Any]:
74
+ """The article the user set for this school's test, by its DOI or its page's address (``doi_of``); empty: none.
75
+ {ok, doi} or {ok: False, error}."""
76
+ text = str(text or "").strip()
77
+ data = _read(_articles_path())
78
+ if not text:
79
+ data.pop(entity_id, None)
80
+ else:
81
+ doi, error = doi_of(text, fetch)
82
+ if not doi:
83
+ return {"ok": False, "error": error}
84
+ data[entity_id] = {"doi": doi, "given": text[:500]}
85
+ _write(_articles_path(), data)
86
+ return {"ok": True, **article(entity_id)}
87
+
88
+
89
+ _DOI = re.compile(r"10\.\d{4,9}/[^\s\"'<>?#&]+")
90
+ #: What a publisher puts after the DOI in an article's address (/full, .pdf); bioRxiv's version (v2) besides.
91
+ _AFTER_DOI = re.compile(r"(?:/(?:full|abstract|pdf|epdf|fulltext|meta|html|references|figures)|\.(?:pdf|full|abstract))$", re.I)
92
+
93
+
94
+ def _get(url: str, fetch=None):
95
+ if fetch is None:
96
+ import requests
97
+
98
+ fetch = requests.get
99
+ return fetch(url, timeout=15, headers=AGENT)
100
+
101
+
102
+ def _http_json(url: str, fetch=None) -> dict[str, Any]:
103
+ response = _get(url, fetch)
104
+ response.raise_for_status()
105
+ return response.json()
106
+
107
+
108
+ def doi_of(text: str, fetch=None) -> tuple[str, str]:
109
+ """(the DOI, "") of an article given by its DOI or its page's address; ("", why not) when it cannot be told.
110
+ In the address itself (doi.org, Springer, Wiley, Taylor & Francis, NEJM ...); Nature's by its article's name;
111
+ PubMed's by its PMID (NCBI); ScienceDirect's, Cell's and the Lancet's by its PII (Crossref); else the page's own
112
+ citation_doi, where the site lets it be read (Oxford's and JAMA's turn such a request away)."""
113
+ from .identifiers import normalize_doi, to_halfwidth
114
+
115
+ text = to_halfwidth(str(text or "")).strip()
116
+ plain = urllib.parse.unquote(text)
117
+ found = _DOI.search(normalize_doi(plain)) or _DOI.search(plain)
118
+ if found:
119
+ doi = found.group(0).rstrip(".,;:。,;")
120
+ while doi.endswith(")") and doi.count(")") > doi.count("("): # a bracket around it, not one of its own
121
+ doi = doi[:-1]
122
+ while _AFTER_DOI.search(doi):
123
+ doi = _AFTER_DOI.sub("", doi)
124
+ if doi.lower().startswith("10.1101/"):
125
+ doi = re.sub(r"v\d+$", "", doi)
126
+ return doi, ""
127
+ if not re.match(r"https?://", plain, re.I):
128
+ return "", "认不出这篇文章:请填 DOI 或文章网址"
129
+ host = (urllib.parse.urlparse(plain).hostname or "").lower()
130
+ path = urllib.parse.urlparse(plain).path
131
+ try:
132
+ nature = re.match(r"/articles/([a-z0-9.\-]+)", path, re.I) if host.endswith("nature.com") else None
133
+ if nature:
134
+ return "10.1038/" + nature.group(1), ""
135
+ pubmed = re.match(r"/(\d{5,9})", path) if host == "pubmed.ncbi.nlm.nih.gov" else None
136
+ if pubmed:
137
+ pmid = pubmed.group(1)
138
+ result = _http_json(f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id={pmid}&retmode=json",
139
+ fetch).get("result", {}).get(pmid, {})
140
+ doi = next((a.get("value") for a in result.get("articleids") or [] if a.get("idtype") == "doi"), "")
141
+ return (doi, "") if doi else ("", "PubMed 没有这篇的 DOI,请改填 DOI")
142
+ pii = re.search(r"(?:/pii/|/fulltext/|/abstract/|/PII)(S[0-9X()\-]{15,})", path, re.I)
143
+ if pii:
144
+ key = re.sub(r"[^0-9X]", "", pii.group(1).upper()[1:])
145
+ items = _http_json(f"https://api.crossref.org/works?filter=alternative-id:S{key}&rows=1&select=DOI",
146
+ fetch).get("message", {}).get("items") or []
147
+ if items:
148
+ return str(items[0]["DOI"]), ""
149
+ page = _get(plain, fetch)
150
+ meta = re.search(r"<meta[^>]+name=[\"'](?:citation_doi|dc\.identifier|prism\.doi)[\"'][^>]+content=[\"']([^\"']+)",
151
+ page.text if page.status_code == 200 else "", re.I)
152
+ doi = _DOI.search(html.unescape(meta.group(1))) if meta else None
153
+ if doi:
154
+ return doi.group(0), ""
155
+ except Exception:
156
+ return "", "没能查到这个网址的 DOI,请改填 DOI"
157
+ return "", "这个网址读不出 DOI,请改填 DOI(文章页上 doi.org/10. 开头的那串)"
158
+
159
+
160
+ # -- the verdict ----------------------------------------------------------------------------------
161
+
162
+ _LOGIN_UNFINISHED = {"login_timeout", "login_not_reached", "login_retries_exhausted", "login_page_closed",
163
+ "idp_login_error", "idp_no_return_to_publisher", "institution_federation_unavailable",
164
+ "institution_not_registered"}
165
+
166
+
167
+ def judge(result: dict[str, Any], *, filled: bool, refused: bool) -> dict[str, Any]:
168
+ """What the page says of a test: ok, a title and a line under it. ``filled``: Pro typed the account in during
169
+ the test; ``refused``: the school turned the password down (Pro turned the account off)."""
170
+ kind = str(result.get("error_type") or "")
171
+ if result.get("success"):
172
+ return {"ok": True, "title": "登录和下载都正常",
173
+ "detail": "自动填写了账号密码,全文已下载并核对" if filled
174
+ else "这次没有用到账号密码:浏览器里还是登录状态,或学校网络直接有权限"}
175
+ if refused or kind == "login_credentials_rejected":
176
+ return {"ok": False, "title": "学校说密码不对", "detail": "自动登录已关闭;改好密码后保存,再测一次"}
177
+ if kind == "idp_account_locked":
178
+ return {"ok": False, "title": "学校说账号被锁定", "detail": "先到学校网站解锁账号,再测一次"}
179
+ if kind == "idp_password_expired":
180
+ return {"ok": False, "title": "学校说密码已过期", "detail": "先到学校网站改密码,改好后保存,再测一次"}
181
+ if kind == "batch_stopped":
182
+ return {"ok": False, "title": "已停止测试", "detail": ""}
183
+ if kind == "paywall" and result.get("reason_code") == "institution_pdf_entitlement_missing" or kind == "no_entitlement":
184
+ return {"ok": False, "title": "登录成功,但这篇没有访问权限", "detail": "学校可能没订这本刊,换一篇再测"}
185
+ if kind in _LOGIN_UNFINISHED or kind == "paywall":
186
+ return {"ok": False, "title": "没有完成学校登录",
187
+ "detail": "自动填写了账号密码,但没有回到文章;学校可能还要验证码或二次验证" if filled
188
+ else "卡在学校登录这一步;学校的登录页要你自己操作时,在下载浏览器里完成"}
189
+ if kind == "access_blocked":
190
+ return {"ok": False, "title": "出版社网站拦住了访问", "detail": "稍后再测,或换一篇"}
191
+ if kind == "download_timeout":
192
+ return {"ok": False, "title": "没有拿到全文", "detail": "页面或安全验证一直没有完成,换一篇或稍后再测"}
193
+ if kind == "network_unavailable":
194
+ return {"ok": False, "title": "网络不通", "detail": "检查网络后再测"}
195
+ if kind in ("browser_closed", "browser_connection_lost"):
196
+ return {"ok": False, "title": "下载浏览器关掉了", "detail": "再测一次"}
197
+ if kind == "browser_busy":
198
+ return {"ok": False, "title": "下载浏览器还开着", "detail": "等下载结束、关掉下载浏览器后再测"}
199
+ if kind in ("school_not_saved", "school_ambiguous"):
200
+ return {"ok": False, "title": "没有找到这所学校", "detail": "回到学校列表,重新添加后再测"}
201
+ return {"ok": False, "title": "没有下载成功", "detail": f"原因代码:{kind or 'unknown'}"}
202
+
203
+
204
+ # -- the test's own process -----------------------------------------------------------------------
205
+
206
+ def _signed_in_since(entity_id: str, since: float) -> bool:
207
+ """Whether Pro typed this school's account in since ``since`` (school_login.take_turn counts each)."""
208
+ from .school_login import _turns_file
209
+
210
+ times = _read(_turns_file()).get(entity_id) or []
211
+ return any(isinstance(t, (int, float)) and t >= since for t in times)
212
+
213
+
214
+ def _account_off(entity_id: str) -> str:
215
+ from . import school_login
216
+ from .config import load_config
217
+
218
+ return str((school_login.saved(load_config(), entity_id) or {}).get("off") or "")
219
+
220
+
221
+ def run(entity_id: str, doi: str) -> int:
222
+ """``school-test``: the download, reported as one; its verdict in ``result_path()``."""
223
+ from . import progress_reporter
224
+ from .orchestrator import download_institutional
225
+
226
+ since, started = time.time(), time.monotonic()
227
+ off_before = _account_off(entity_id)
228
+ scratch = Path(tempfile.mkdtemp(prefix="paper-search-school-test-"))
229
+ progress_reporter.start_task(TASK, total=1, current=doi, phase="打开文章页")
230
+ result: dict[str, Any] = {}
231
+ try:
232
+ # Not from the cache, not into it: the test is the download itself.
233
+ result = download_institutional(doi, scratch, strategy="institutional_only", school=entity_id, fresh=True)
234
+ finally:
235
+ ok = bool(result.get("success"))
236
+ progress_reporter.advance(ok, current=doi, phase="测试通过" if ok else "测试没有通过")
237
+ progress_reporter.finish()
238
+ shutil.rmtree(scratch, ignore_errors=True) # the PDF goes with it
239
+ verdict = judge(result, filled=_signed_in_since(entity_id, since),
240
+ refused=_account_off(entity_id) == "rejected" and off_before != "rejected")
241
+ _write(result_path(), {"key": entity_id, "doi": doi, "seconds": round(time.monotonic() - started), **verdict})
242
+ return 0 if verdict["ok"] else 1
243
+
244
+
245
+ # -- the window's side ----------------------------------------------------------------------------
246
+
247
+ def _live(doi: str) -> dict[str, Any]:
248
+ """Where the running test is: its step and what the download says (a reminder first)."""
249
+ from .progress_reporter import read_state
250
+
251
+ state = read_state() or {}
252
+ if state.get("task") != TASK or str(state.get("current") or "") != doi:
253
+ return {"step": 0, "phase": ""}
254
+ attention = [value for value in (state.get("attention") or {}).values() if isinstance(value, dict)]
255
+ phase = str(attention[-1].get("message") or "") if attention else str(state.get("phase") or "")
256
+ return {"step": STAGE_STEP.get(str(state.get("stage") or ""), 0), "phase": phase, "run_id": str(state.get("run_id") or "")}
257
+
258
+
259
+ class SchoolTest:
260
+ """The settings window's 测试登录: one test at a time, its process watched in the background."""
261
+
262
+ def __init__(self, popen=None) -> None:
263
+ self._popen = popen or subprocess.Popen
264
+ self._lock = threading.Lock()
265
+ self._state: dict[str, Any] = {"state": "idle"}
266
+ self._process: Any = None
267
+
268
+ def state(self) -> dict[str, Any]:
269
+ with self._lock:
270
+ state = dict(self._state)
271
+ if state.get("state") == "running":
272
+ live = _live(str(state.get("doi") or ""))
273
+ live.pop("run_id", None)
274
+ state.update(live)
275
+ return state
276
+
277
+ def start(self, entity_id: str, doi: str) -> dict[str, Any]:
278
+ from .progress_reporter import read_state
279
+
280
+ with self._lock:
281
+ if self._state.get("state") == "running":
282
+ return dict(self._state)
283
+ if (read_state() or {}).get("status") == "running":
284
+ return {"state": "idle", "error": "正在下载,等这次下载结束再测试"}
285
+ result_path().unlink(missing_ok=True)
286
+ command = [sys.executable, "-m", "paper_search_school.cli", "school-test", "--school", entity_id, "--doi", doi]
287
+ extra = {"creationflags": 0x08000000} if os.name == "nt" else {"start_new_session": True}
288
+ process = self._popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **extra)
289
+ with self._lock:
290
+ self._process = process
291
+ self._state = {"state": "running", "key": entity_id, "doi": doi, "started": time.time(), "step": 0, "phase": ""}
292
+ threading.Thread(target=self._wait, args=(process, entity_id, doi), name="school-test", daemon=True).start()
293
+ return self.state()
294
+
295
+ def _wait(self, process: Any, entity_id: str, doi: str) -> None:
296
+ process.wait()
297
+ verdict = _read(result_path())
298
+ if verdict.get("key") != entity_id or verdict.get("doi") != doi:
299
+ with self._lock:
300
+ stopped = bool(self._state.get("stopping"))
301
+ verdict = ({"ok": False, "title": "已停止测试", "detail": ""} if stopped
302
+ else {"ok": False, "title": "测试没有完成", "detail": "测试进程意外结束,可以再测一次"})
303
+ with self._lock:
304
+ self._process = None
305
+ self._state = {"state": "done", "key": entity_id, "doi": doi, "ok": bool(verdict.get("ok")),
306
+ "title": str(verdict.get("title") or ""), "detail": str(verdict.get("detail") or ""),
307
+ "seconds": int(verdict.get("seconds") or 0)}
308
+
309
+ def stop(self) -> dict[str, Any]:
310
+ """Asked to stop as the card's 终止任务 asks a download; ended after STOP_GRACE if it goes on."""
311
+ from .entitlements import STOP_BATCH, request_action
312
+
313
+ with self._lock:
314
+ process, doi = self._process, str(self._state.get("doi") or "")
315
+ if process is None:
316
+ return dict(self._state)
317
+ self._state = {**self._state, "stopping": True}
318
+ run_id = _live(doi).get("run_id")
319
+ if run_id:
320
+ request_action(doi, STOP_BATCH, run_id)
321
+
322
+ def end_later() -> None:
323
+ try:
324
+ process.wait(timeout=STOP_GRACE)
325
+ except subprocess.TimeoutExpired:
326
+ process.terminate()
327
+
328
+ threading.Thread(target=end_later, name="school-test-stop", daemon=True).start()
329
+ return self.state()
330
+
331
+ def forget(self) -> None:
332
+ """A finished test's verdict no longer shown (another school opened, the page left)."""
333
+ with self._lock:
334
+ if self._state.get("state") == "done":
335
+ self._state = {"state": "idle"}
@@ -132,6 +132,9 @@ def school_download(
132
132
  if not result.get("success"):
133
133
  if result.get("error_type") == "access_blocked":
134
134
  outcome["failure_phase"] = "网站已阻止当前访问,未取得 PDF"
135
+ if isinstance(result.get("schools_tried"), int):
136
+ # 没权限时换下一所学校: every saved school tried, none with access (user, 2026-11-21).
137
+ outcome["failure_phase"] = f"{result['schools_tried']} 所学校都没有权限"
135
138
  if result.get("error_type") == "rate_limited":
136
139
  until = time.time() + int(result.get("retry_after_sec") or 0)
137
140
  outcome["paused"] = outcome["failure_phase"] = progress_reporter.hourly_phase(
@@ -239,6 +242,22 @@ async def school_keep_session() -> str:
239
242
  return json.dumps(result)
240
243
 
241
244
 
245
+ @mcp_app.tool()
246
+ def school_switch_state() -> str:
247
+ """The schools a batch's papers without access (没权限) are tried with at its end, one after another
248
+ (没权限时换下一所学校, school_switch.py): the default one first, each named as ``school_download``'s ``school``
249
+ takes it (its entityID); none while the switch is off; and whether the batch takes one journal's papers one after
250
+ another (``group``: on and more than one school). Opens no browser. Answers
251
+ {"on": bool, "schools": [{"name": ..., "entity_id": ...}, ...], "group": bool}."""
252
+ from . import school_switch
253
+
254
+ config = load_config()
255
+ on = school_switch.enabled(config)
256
+ schools = [{"name": school_switch.name(entry), "entity_id": str(entry.get("idp_entity_id") or "").strip()}
257
+ for entry in school_switch.schools(config)] if on else []
258
+ return json.dumps({"on": on, "schools": schools, "group": on and len(schools) > 1}, ensure_ascii=False)
259
+
260
+
242
261
  @mcp_app.tool()
243
262
  def school_hourly_wait(publisher: str) -> str:
244
263
  """While a batch waits for the hourly limit the user set: the seconds until ``publisher`` (as
@@ -318,9 +337,8 @@ def school_batch_papers(batch_id: str, folder: str, papers: list[dict[str, Any]]
318
337
  doi, title, journal, state ("open": open access not checked yet, "school": waiting
319
338
  for or in the institutional download, "ok", "failed"); a saved one adds via
320
339
  (开放下载 or 机构下载), detail (出版社 API, Sci-Hub, 预印本) and path (the PDF,
321
- absolute); a failed one cls (no_access, user_side, school_side, publisher_or_network,
322
- article_or_site, unsupported, unexplained)
323
- and reason}]. folder: the batch's download folder (absolute); the window opens
340
+ absolute); a failed one cls (no_access, user_side, external, unsupported, unexplained; the
341
+ classes before 2026-11-22 are taken as these) and reason}]. folder: the batch's download folder (absolute); the window opens
324
342
  a PDF only from inside it. Never touches the running download's progress.
325
343
  """
326
344
  from . import progress_reporter
@@ -0,0 +1,222 @@
1
+ """The settings window's one version and one update (user, 2026-11-21: PaperSearch and Pro one thing to them, updated
2
+ by one button).
3
+
4
+ The window checks PaperSearch's newest version (``paper-search update check``: npm's release, or the private
5
+ install's own repository) and, with Pro installed, Pro's (``paper-search pro check``). 更新 then runs, one after
6
+ another, what is behind: PaperSearch itself (``update install``), the school extension (``school update``) and the
7
+ Skills (``skills update``) after it, Pro (``pro install``); each step's outcome is kept for the page. A window holds the
8
+ code it started with: once PaperSearch itself is updated it opens again (``reopen``), and one left open while an
9
+ update happened elsewhere says so (``installed_version`` beside ``RUNNING``).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import re
16
+ import subprocess
17
+ import sys
18
+ import threading
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any, Callable
22
+
23
+ _VERSION = re.compile(r"\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?")
24
+
25
+
26
+ def _version(value: Any) -> str:
27
+ text = str(value or "").strip()
28
+ return text if _VERSION.fullmatch(text) else ""
29
+
30
+
31
+ def installed_version() -> str:
32
+ """The PaperSearch version installed now: the extension's install record, rewritten by each update."""
33
+ try:
34
+ record = json.loads((Path(sys.prefix).parent / "install.json").read_text(encoding="utf-8"))
35
+ except (OSError, ValueError):
36
+ return ""
37
+ return _version(record.get("paperSearchVersion")) if isinstance(record, dict) else ""
38
+
39
+
40
+ #: The version this window runs: as PaperSearch passed it when it started the window, else as installed then.
41
+ RUNNING = _version(os.environ.get("PAPER_SEARCH_VERSION")) or installed_version()
42
+
43
+ #: The steps of 更新, in order, each with what the page calls it.
44
+ STEPS = {"paper_search": "PaperSearch", "school": "学校订阅下载扩展", "skills": "Skill", "pro": "Pro"}
45
+
46
+
47
+ def _quiet_env() -> dict[str, str]:
48
+ # A step updates only what it is for: no Skill update or version reminder alongside.
49
+ return {**os.environ, "PAPER_SEARCH_SKILL_AUTO_UPDATE": "false", "PAPER_SEARCH_UPDATE_NOTIFY": "false"}
50
+
51
+
52
+ def _last_json(text: str) -> dict[str, Any]:
53
+ for line in reversed([line for line in str(text or "").splitlines() if line.strip()]):
54
+ try:
55
+ data = json.loads(line)
56
+ except ValueError:
57
+ continue
58
+ if isinstance(data, dict):
59
+ return data
60
+ try:
61
+ data = json.loads(text)
62
+ return data if isinstance(data, dict) else {}
63
+ except ValueError:
64
+ return {}
65
+
66
+
67
+ def _run(argv: list[str], timeout: int) -> tuple[int, str]:
68
+ extra = {"creationflags": 0x08000000} if os.name == "nt" else {}
69
+ done = subprocess.run(argv, capture_output=True, encoding="utf-8", errors="replace", env=_quiet_env(),
70
+ timeout=timeout, stdin=subprocess.DEVNULL, **extra)
71
+ return done.returncode, done.stdout
72
+
73
+
74
+ class VersionCheck:
75
+ """PaperSearch's newest version and, with Pro installed, Pro's: {state: idle, running, done (current, latest,
76
+ update, notes, pro_update, pro_latest), failed (message)}; checked again once its answer is an hour old."""
77
+
78
+ def __init__(self, command_of: Callable[[], list[str] | None] | None = None,
79
+ run: Callable[[list[str], int], tuple[int, str]] | None = None,
80
+ pro_installed: Callable[[], bool] | None = None, now: Callable[[], float] = time.time) -> None:
81
+ from .api_keys import paper_search_command
82
+
83
+ self._command_of = command_of or paper_search_command
84
+ self._run = run or _run
85
+ self._pro_installed = pro_installed or _pro_installed
86
+ self._now = now
87
+ self._lock = threading.Lock()
88
+ self._state: dict[str, Any] = {"state": "idle"}
89
+ self._at = 0.0
90
+
91
+ def state(self) -> dict[str, Any]:
92
+ with self._lock:
93
+ return dict(self._state)
94
+
95
+ def start(self, again: bool = False) -> dict[str, Any]:
96
+ with self._lock:
97
+ fresh = self._state.get("state") == "done" and self._now() - self._at < 3600
98
+ if self._state.get("state") == "running" or (fresh and not again):
99
+ return dict(self._state)
100
+ self._state = {"state": "running"}
101
+ threading.Thread(target=self._check, name="version-check", daemon=True).start()
102
+ return {"state": "running"}
103
+
104
+ def _check(self) -> None:
105
+ command = self._command_of()
106
+ state: dict[str, Any]
107
+ if command is None:
108
+ state = {"state": "failed", "message": "找不到 paper-search 命令"}
109
+ else:
110
+ try:
111
+ answer = _last_json(self._run([*command, "update", "check", "--format", "json"], 60)[1])
112
+ latest = _version(answer.get("latest") or answer.get("latestVersion"))
113
+ if answer.get("ok") is not True or not latest:
114
+ state = {"state": "failed", "message": str(answer.get("message") or "检查更新出错")}
115
+ else:
116
+ update = answer.get("update") if "update" in answer else answer.get("updateAvailable")
117
+ state = {"state": "done", "current": _version(answer.get("current") or answer.get("currentVersion")) or RUNNING,
118
+ "latest": latest, "update": update is True, "notes": str(answer.get("releaseNotesUrl") or ""),
119
+ "pro_update": False, "pro_latest": ""}
120
+ if self._pro_installed():
121
+ pro = _last_json(self._run([*command, "pro", "check"], 60)[1])
122
+ if pro.get("ok") is True:
123
+ state.update(pro_update=pro.get("update") is True, pro_latest=_version(pro.get("latest")))
124
+ except (OSError, subprocess.SubprocessError):
125
+ state = {"state": "failed", "message": "检查更新出错"}
126
+ with self._lock:
127
+ self._state = state
128
+ self._at = self._now()
129
+
130
+
131
+ def _pro_installed() -> bool:
132
+ try:
133
+ from .pro_status import status
134
+
135
+ return bool(status().get("installed"))
136
+ except Exception:
137
+ return False
138
+
139
+
140
+ class UpdateAll:
141
+ """更新: what is behind, one step after another; {state: idle, running (steps, step), done (steps, reopen),
142
+ failed (steps, step, message)}. ``reopen``: PaperSearch itself was updated, the window opens again."""
143
+
144
+ def __init__(self, command_of: Callable[[], list[str] | None] | None = None,
145
+ run: Callable[[list[str], int], tuple[int, str]] | None = None) -> None:
146
+ from .api_keys import paper_search_command
147
+
148
+ self._command_of = command_of or paper_search_command
149
+ self._run = run or _run
150
+ self._lock = threading.Lock()
151
+ self._state: dict[str, Any] = {"state": "idle"}
152
+
153
+ def state(self) -> dict[str, Any]:
154
+ with self._lock:
155
+ return {**self._state, **({"steps": list(self._state["steps"])} if "steps" in self._state else {})}
156
+
157
+ def start(self, core: bool, pro: bool, target: str = "") -> dict[str, Any]:
158
+ """``core``: PaperSearch is behind (then the extension and the Skills after it); ``pro``: Pro is."""
159
+ from .progress_reporter import read_state
160
+
161
+ steps = (["paper_search", "school", "skills"] if core else []) + (["pro"] if pro else [])
162
+ with self._lock:
163
+ if self._state.get("state") == "running":
164
+ return dict(self._state)
165
+ if not steps:
166
+ return {"state": "idle"}
167
+ if (read_state() or {}).get("status") == "running":
168
+ return {"state": "idle", "error": "正在下载,等这次下载结束再更新"}
169
+ self._state = {"state": "running", "steps": steps, "step": 0, "target": target}
170
+ threading.Thread(target=self._go, args=(steps,), name="update-all", daemon=True).start()
171
+ return self.state()
172
+
173
+ def _go(self, steps: list[str]) -> None:
174
+ command = self._command_of()
175
+ if command is None:
176
+ return self._failed(0, "找不到 paper-search 命令")
177
+ argv = {"paper_search": ["update", "install"], "school": ["school", "update"], "skills": ["skills", "update"],
178
+ "pro": ["pro", "install"]}
179
+ for index, step in enumerate(steps):
180
+ with self._lock:
181
+ self._state = {**self._state, "step": index}
182
+ try:
183
+ code, out = self._run([*command, *argv[step]], 900)
184
+ except (OSError, subprocess.SubprocessError):
185
+ return self._failed(index, f"更新{STEPS[step]}出错")
186
+ answer = _last_json(out)
187
+ if code != 0 or answer.get("ok") is False:
188
+ return self._failed(index, str(answer.get("message") or answer.get("error") or f"更新{STEPS[step]}出错"))
189
+ with self._lock:
190
+ self._state = {**self._state, "state": "done", "step": len(steps), "reopen": "paper_search" in steps}
191
+
192
+ def _failed(self, index: int, message: str) -> None:
193
+ with self._lock:
194
+ self._state = {**self._state, "state": "failed", "step": index, "message": message}
195
+
196
+
197
+ #: Started by ``reopen``: waits for the window it was started by to close, then opens the settings again with the
198
+ #: PaperSearch installed now (its new window).
199
+ _REOPEN = """
200
+ import json, subprocess, sys, time
201
+ from paper_search_school.progress_reporter import _pid_alive
202
+ pid, argv = int(sys.argv[1]), json.loads(sys.argv[2])
203
+ deadline = time.time() + 60
204
+ while _pid_alive(pid) and time.time() < deadline:
205
+ time.sleep(0.3)
206
+ extra = {"creationflags": 0x08000000} if sys.platform == "win32" else {"start_new_session": True}
207
+ subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **extra)
208
+ """
209
+
210
+
211
+ def reopen(page: str = "about", command_of: Callable[[], list[str] | None] | None = None, popen=None) -> bool:
212
+ """The settings opened again at ``page`` once this window has closed (the caller closes it); False when
213
+ PaperSearch's command is not found (the window stays)."""
214
+ from .api_keys import paper_search_command
215
+
216
+ command = (command_of or paper_search_command)()
217
+ if command is None:
218
+ return False
219
+ extra = {"creationflags": 0x08000000} if os.name == "nt" else {"start_new_session": True}
220
+ (popen or subprocess.Popen)([sys.executable, "-c", _REOPEN, str(os.getpid()), json.dumps([*command, "settings", page])],
221
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=_quiet_env(), **extra)
222
+ return True
@@ -85,10 +85,15 @@ LANGUAGE_KEY = "progress_language"
85
85
 
86
86
 
87
87
  def language() -> str:
88
- """The progress window's language: "zh" (the default) or "en"."""
89
- return "en" if _config.load_config().get(LANGUAGE_KEY) == "en" else "zh"
88
+ """The progress window's language: "zh" (simplified Chinese, the default) or another of i18n.LANGUAGES."""
89
+ from . import i18n
90
+
91
+ saved = _config.load_config().get(LANGUAGE_KEY)
92
+ return saved if saved in i18n.LANGUAGES else "zh"
90
93
 
91
94
 
92
95
  def set_language(lang: str) -> None:
93
- _config.update_config(LANGUAGE_KEY, "en" if lang == "en" else "zh")
96
+ from . import i18n
97
+
98
+ _config.update_config(LANGUAGE_KEY, lang if lang in i18n.LANGUAGES else "zh")
94
99
 
@@ -4,7 +4,7 @@ description: |
4
4
  用本机 paper-search 命令做文献工作:检索论文、核对 DOI/PMID、搜正文片段(找方法和结果的原文)、查期刊影响因子与分区、查施引和参考文献、下载全文和补充材料。
5
5
  用户要找文献、查期刊、下载论文,或说“请开始配置”时使用;英文请求(literature search、journal metrics、paper download、start setup)同样适用。
6
6
  metadata:
7
- version: "0.7.1"
7
+ version: "0.7.3"
8
8
  ---
9
9
 
10
10
  # 文献检索与下载(paper-search)