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
@@ -77,7 +77,8 @@ def module() -> Any | None:
77
77
 
78
78
  def school_status(entity_id: str, pro: Any | None = None) -> str:
79
79
  """``verified`` (signed in for real), ``surveyed`` (its form filled in and pressed, the school's
80
- "wrong password" read: user, 2026-11-19, enough), ``trial`` (being tested), or "" (not tested)."""
80
+ "wrong password" read: user, 2026-11-19, enough), ``trial`` (being tested), ``check`` (its sign-in
81
+ asks the user for a check: never filled in), or "" (not tested)."""
81
82
  pro = pro if pro is not None else module()
82
83
  if pro is None or not entity_id:
83
84
  return ""
@@ -85,7 +86,43 @@ def school_status(entity_id: str, pro: Any | None = None) -> str:
85
86
  status = str(pro.school_status(entity_id) or "")
86
87
  except Exception:
87
88
  return ""
88
- return status if status in {"verified", "surveyed", "trial"} else ""
89
+ return status if status in {"verified", "surveyed", "trial", "check"} else ""
90
+
91
+
92
+ # What the settings page reads of each school: the area (a US state, a UK nation) and kind (university, research
93
+ # institute, hospital) split the big countries (Pro 0.3.1; an older Pro has neither, "" there).
94
+ #: key: its entityID (添加学校 adds a school found in this list by it; "" from an older Pro).
95
+ SCHOOL_FIELDS = ("key", "name", "name_en", "country", "province", "area", "kind", "status")
96
+
97
+
98
+ def school_list(pro: Any | None = None) -> list[dict[str, Any]]:
99
+ """The schools Pro knows, each with its name, English name, country, province (a mainland school's), area,
100
+ kind, status and names in other languages, for the settings page; [] from an older Pro (one without a field: ""
101
+ there, {} for the names)."""
102
+ pro = pro if pro is not None else module()
103
+ try:
104
+ listed = pro.school_list() if pro is not None and hasattr(pro, "school_list") else []
105
+ return [{**{key: str(school.get(key) or "") for key in SCHOOL_FIELDS}, "names": _names(school.get("names"))}
106
+ for school in listed if isinstance(school, dict) and school.get("name")]
107
+ except Exception:
108
+ return []
109
+
110
+
111
+ def _names(raw: Any) -> dict[str, str]:
112
+ """A school's names in other languages ({language code: name}), each text; {} from an older Pro."""
113
+ if not isinstance(raw, dict):
114
+ return {}
115
+ return {str(lang): str(name) for lang, name in raw.items() if isinstance(lang, str) and isinstance(name, str) and name}
116
+
117
+
118
+ def school_counts(pro: Any | None = None) -> dict[str, int]:
119
+ """How many schools Pro fills in for everyone and how many ask for a check; {} from an older Pro."""
120
+ pro = pro if pro is not None else module()
121
+ try:
122
+ counts = pro.school_counts() if pro is not None and hasattr(pro, "school_counts") else {}
123
+ return {key: int(counts.get(key) or 0) for key in ("filled", "check")} if isinstance(counts, dict) else {}
124
+ except Exception:
125
+ return {}
89
126
 
90
127
 
91
128
  def fills_for(entity_id: str, pro: Any | None = None) -> bool:
@@ -0,0 +1,102 @@
1
+ """没权限时换下一所学校 (PaperSearch Pro; user, 2026-11-21).
2
+
3
+ An article the school signed in to but has no access to (its publisher says so) is tried with the next saved school:
4
+ one Pro fills the sign-in of, its account saved and its auto sign-in on; the default school first, then the list's
5
+ order. A journal one of them got is remembered for the rest of the download task (a batch; a single download is a task
6
+ of its own) and tried with it first; a task starts again from the default school. Only "no access" switches: a sign-in
7
+ that failed (a wrong password, a code to type, a page that stopped it) is the user's to see, not another account's.
8
+ Each switch forgets the sign-in before it (cold_start.before_sign_in), the batch's browser closed first to let go of it.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ #: The switch on the sign-in page (config), on unless turned off.
15
+ SETTING = "school_switch"
16
+
17
+ #: (task, journal) -> the entityID of the school that got the journal's article in that task.
18
+ _GOT: dict[tuple[str, str], str] = {}
19
+
20
+
21
+ def enabled(config: dict[str, Any]) -> bool:
22
+ return config.get(SETTING) is not False
23
+
24
+
25
+ def no_access(result: dict[str, Any] | None) -> bool:
26
+ """Signed in, and the publisher has no access for the school to this article (not a sign-in that failed)."""
27
+ return bool(result) and not result.get("success") and result.get("error_type") == "paywall" \
28
+ and result.get("reason_code") == "institution_pdf_entitlement_missing"
29
+
30
+
31
+ def schools(config: dict[str, Any]) -> list[dict[str, Any]]:
32
+ """The schools taking part, in order: the default one, then each other saved school Pro fills the sign-in of, its
33
+ account saved and its auto sign-in on. [] without Pro."""
34
+ from . import school_login
35
+ from .schools import saved as saved_schools
36
+
37
+ pro = school_login.module()
38
+ if pro is None:
39
+ return []
40
+ saved_schools.remember(config)
41
+ listed = saved_schools.saved(config)
42
+ current = [entry for entry in listed if saved_schools.is_current(config, entry)]
43
+ order: list[dict[str, Any]] = current[:]
44
+ for entry in listed:
45
+ entity = str(entry.get("idp_entity_id") or "").strip()
46
+ if entry in current or not entity:
47
+ continue
48
+ account = school_login.saved(config, entity) or {}
49
+ if account.get("enabled") and school_login.fills_for(entity, pro):
50
+ order.append(entry)
51
+ return order
52
+
53
+
54
+ def grouping(config: dict[str, Any]) -> bool:
55
+ """Whether a batch takes one journal's papers one after another: on, and more than one school taking part."""
56
+ return enabled(config) and len(schools(config)) > 1
57
+
58
+
59
+ def _task() -> str:
60
+ from . import progress_reporter
61
+
62
+ return progress_reporter.batch_id()
63
+
64
+
65
+ def journal(doi: str) -> str:
66
+ """The journal's key: its ISSNs (Crossref, kept), else its title; "" when not known."""
67
+ from .entitlements import journal_identity
68
+
69
+ try:
70
+ identity = journal_identity(doi)
71
+ except Exception:
72
+ return ""
73
+ issns = identity.get("issn") or []
74
+ return "issn:" + ",".join(sorted(issns)) if issns else str(identity.get("journal") or "").strip().lower()
75
+
76
+
77
+ def remembered(doi: str) -> str:
78
+ """The school (entityID) that got this article's journal earlier in this task; "" when none or not in a task."""
79
+ task = _task()
80
+ key = journal(doi) if task else ""
81
+ return _GOT.get((task, key), "") if key else ""
82
+
83
+
84
+ def remember(doi: str, entity: str) -> None:
85
+ task = _task()
86
+ key = journal(doi) if task and entity else ""
87
+ if key:
88
+ _GOT[(task, key)] = entity
89
+
90
+
91
+ def order_for(config: dict[str, Any], doi: str) -> list[dict[str, Any]]:
92
+ """The schools to try for this article, in turn: its journal's school of this task first, then the default one
93
+ and the rest."""
94
+ listed = schools(config)
95
+ if len(listed) < 2:
96
+ return listed # nothing to switch to: no journal looked up
97
+ first = remembered(doi)
98
+ return sorted(listed, key=lambda entry: str(entry.get("idp_entity_id") or "").strip() != first) if first else listed
99
+
100
+
101
+ def name(entry: dict[str, Any]) -> str:
102
+ return str(entry.get("school_name") or entry.get("school_name_en") or entry.get("idp_entity_id") or "")
@@ -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,19 @@ 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
+ """Whether a batch takes one journal's papers one after another (没权限时换下一所学校, school_switch.py): the switch
248
+ on and more than one school taking part, so that a school switched to for a journal is not switched away from and
249
+ back. Opens no browser. Answers {"on": bool, "schools": n, "group": bool}."""
250
+ from . import school_switch
251
+
252
+ config = load_config()
253
+ count = len(school_switch.schools(config))
254
+ on = school_switch.enabled(config)
255
+ return json.dumps({"on": on, "schools": count, "group": on and count > 1})
256
+
257
+
242
258
  @mcp_app.tool()
243
259
  def school_hourly_wait(publisher: str) -> str:
244
260
  """While a batch waits for the hourly limit the user set: the seconds until ``publisher`` (as