papersearch 0.7.1 → 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 (94) 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 +927 -202
  65. package/school/paper_search_school/assets/capsule_en.json +290 -22
  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/cli.py +15 -1
  71. package/school/paper_search_school/cold_start.py +70 -8
  72. package/school/paper_search_school/config.py +2 -0
  73. package/school/paper_search_school/download_diagnostics.py +4 -4
  74. package/school/paper_search_school/engine/batch_capture.py +35 -1
  75. package/school/paper_search_school/engine/batch_diagnostics.py +1 -1
  76. package/school/paper_search_school/engine/batch_institution.py +41 -0
  77. package/school/paper_search_school/engine/batch_login.py +65 -1
  78. package/school/paper_search_school/engine/batch_waits.py +22 -8
  79. package/school/paper_search_school/engine/bridge.py +11 -0
  80. package/school/paper_search_school/i18n.py +46 -22
  81. package/school/paper_search_school/orchestrator.py +60 -8
  82. package/school/paper_search_school/pro_status.py +54 -63
  83. package/school/paper_search_school/progress_capsule.py +180 -24
  84. package/school/paper_search_school/progress_reporter.py +51 -5
  85. package/school/paper_search_school/progress_view.py +3 -2
  86. package/school/paper_search_school/school_login.py +18 -4
  87. package/school/paper_search_school/school_switch.py +102 -0
  88. package/school/paper_search_school/school_test.py +335 -0
  89. package/school/paper_search_school/server.py +16 -0
  90. package/school/paper_search_school/updates.py +222 -0
  91. package/school/paper_search_school/user_settings.py +8 -3
  92. package/skills/paper-search/SKILL.md +1 -1
  93. package/skills/paper-search/references/cli-contract.md +1 -1
  94. package/skills/paper-search/references/school-setup.md +1 -1
@@ -40,7 +40,9 @@ _STAGE_LISTENER: ContextVar[tuple[str, Callable[[str], None]] | None] = ContextV
40
40
 
41
41
  STAGES = frozenset({
42
42
  "starting", "opening_article", "waiting_login", "waiting_verification",
43
- "checking_access", "fetching_pdf", "pdf_captured",
43
+ # switching_school (没权限时换下一所学校): no step of its own, the card's line says "没权限,换××" (a school's name can
44
+ # be long: the step bar's label would squeeze the bars; the line ends in … and says it all on hover).
45
+ "checking_access", "fetching_pdf", "pdf_captured", "switching_school",
44
46
  "saved_pending_verification", "access_ready", "supplements_checked", "route_failed", "failed", "cancelled", "interrupted", "unknown",
45
47
  })
46
48
  _IDENTITY_FIELDS = frozenset({"schema_version", "run_id", "revision", "owner_pid"})
@@ -270,6 +272,10 @@ def _batch_state(batch_id: str) -> dict[str, Any] | None:
270
272
  return None
271
273
 
272
274
 
275
+ #: What the card says of the paper it shows, which another paper does not keep (_adopt_batch).
276
+ PAPER_FIELDS = ("title", "journal", "publisher", "notice")
277
+
278
+
273
279
  def _adopt_batch(batch_id: str, total: int, counts: tuple[int | None, int | None, int | None],
274
280
  *, beside_download: bool = False, **fields: Any) -> bool | None:
275
281
  """Continue this batch's report in the current process, or start it (True).
@@ -307,6 +313,10 @@ def _adopt_batch(batch_id: str, total: int, counts: tuple[int | None, int | None
307
313
  and isinstance(owner, int) and owner != os.getpid() and _pid_alive(owner)):
308
314
  return None
309
315
  _STARTED_MONO = time.monotonic()
316
+ if previous is not None and fields.get("current") and str(fields["current"]).lower() != str(previous.get("current") or "").lower():
317
+ # Another paper: the last one's title, journal, publisher and notice go with it (user, 2026-11-21: the card kept
318
+ # one paper's title, and its publisher in place of 开放下载, while the open-access lane went through others).
319
+ previous = {key: value for key, value in previous.items() if key not in PAPER_FIELDS}
310
320
  if previous is None:
311
321
  previous = {
312
322
  # A lone download comes as a batch of one (its finished card gets the reason).
@@ -422,7 +432,10 @@ def _short_line(value: Any, limit: int = 80) -> str:
422
432
 
423
433
  FAILURE_CLASSES = ("no_access", "user_side", "school_side", "publisher_or_network", "article_or_site", "unsupported", "unexplained")
424
434
  _RESULT_CONTENTS = ("main", "supplements", "both", "markdown")
425
- _MAX_RESULT_FAILURES = 1000 # the caller's batch limit
435
+ # A bound against malformed input only: a batch has no limit since 7a38a068 (user, 2026-11-17). Left at its old 1000,
436
+ # a batch's papers after the 1000th were left out of the lists (user, 2026-11-21: 失败 1 on the card, the list empty,
437
+ # the failed paper the 1211th of 1551; 成功 and 剩余 stopped at 1000 too).
438
+ _MAX_BATCH_PAPERS = 100_000
426
439
  _MAX_RESULT_TEXT = 300
427
440
 
428
441
 
@@ -479,7 +492,7 @@ def _batch_results(raw: Any) -> dict[str, Any] | None:
479
492
  }
480
493
  for key in ("failures", "supplement_failures", "markdown_failures"):
481
494
  listed = raw.get(key)
482
- for item in (listed if isinstance(listed, list) else [])[:_MAX_RESULT_FAILURES]:
495
+ for item in (listed if isinstance(listed, list) else [])[:_MAX_BATCH_PAPERS]:
483
496
  if not isinstance(item, dict) or not text(item.get("reason")):
484
497
  continue
485
498
  summary[key].append({
@@ -517,7 +530,7 @@ def _paper(raw: Any) -> dict[str, Any] | None:
517
530
  if not isinstance(raw, dict) or raw.get("state") not in PAPER_STATES:
518
531
  return None
519
532
  index = raw.get("index")
520
- if not isinstance(index, int) or isinstance(index, bool) or not 1 <= index <= _MAX_RESULT_FAILURES:
533
+ if not isinstance(index, int) or isinstance(index, bool) or not 1 <= index <= _MAX_BATCH_PAPERS:
521
534
  return None
522
535
  paper = {"index": index, "state": raw["state"],
523
536
  **{field: _display_text(raw.get(field)) for field in ("doi", "title", "journal")}}
@@ -590,7 +603,7 @@ def sync_papers(batch_id: str, folder: str, papers: Any) -> bool:
590
603
  if isinstance(folder, str) and 0 < len(folder) <= 4096 and os.path.isabs(folder):
591
604
  listed["folder"] = folder
592
605
  known = listed["papers"]
593
- for raw in papers[:_MAX_RESULT_FAILURES]:
606
+ for raw in papers[:_MAX_BATCH_PAPERS]:
594
607
  paper = _paper(raw)
595
608
  if paper is None:
596
609
  continue
@@ -667,6 +680,7 @@ def tracked_download(current: str, output_dir: Any = None, batch: BatchContext |
667
680
  markdown=bool(markdown), page_reading=False)
668
681
  if output_dir:
669
682
  set_output_dir(output_dir)
683
+ name_journal(current)
670
684
  outcome: dict[str, Any] = {}
671
685
  try:
672
686
  yield outcome
@@ -717,6 +731,38 @@ def _finish_download(outcome: dict[str, Any], current: str, batch: BatchContext
717
731
  finish()
718
732
 
719
733
 
734
+ def name_journal(current: str, look_up: Callable[[str], dict[str, Any]] | None = None) -> threading.Thread | None:
735
+ """The paper's journal on the card, where PaperSearch gave none (a list of DOIs; user, 2026-11-21: the card said
736
+ Elsevier, the publisher, for a paper of Metabolism): looked up beside the download (Crossref, kept by
737
+ entitlements.journal_identity), said once known, while the card is still on that paper."""
738
+ if look_up is None and os.environ.get("SCHOOL_PROGRESS_BAR") == "0":
739
+ return None # no card to say it on (and no lookups from the tests)
740
+ with _LOCK:
741
+ if not _STATE or _STATE.get("journal") or str(_STATE.get("current") or "") != current or not current:
742
+ return None
743
+
744
+ def look() -> None:
745
+ try:
746
+ if look_up is None:
747
+ from .entitlements import journal_identity
748
+
749
+ name = str(journal_identity(current).get("journal") or "").strip()
750
+ else:
751
+ name = str(look_up(current).get("journal") or "").strip()
752
+ except Exception:
753
+ return # the card keeps the publisher
754
+ if not name:
755
+ return
756
+ with _LOCK:
757
+ if _STATE and str(_STATE.get("current") or "") == current and not _STATE.get("journal"):
758
+ _STATE["journal"] = name
759
+ _write_state()
760
+
761
+ thread = threading.Thread(target=look, name="journal-name", daemon=True)
762
+ thread.start()
763
+ return thread
764
+
765
+
720
766
  def _write_state() -> None:
721
767
  """Called under _LOCK; revisions count successful atomic replacements only."""
722
768
  payload = {
@@ -311,8 +311,9 @@ def paper_lists(listed: Any, state: dict[str, Any] | None) -> dict[str, Any]:
311
311
  if paper.get("detail"):
312
312
  details[paper["detail"]] = details.get(paper["detail"], 0) + 1
313
313
  label = way + ("(" + "、".join(f"{name} {n}" for name, n in details.items()) + ")" if details else "")
314
- saved.append(group(label, [row(p, p.get("journal"), (p.get("detail") or "开放获取") if way == OPEN_DOWNLOAD else "")
315
- for p in items]))
314
+ # 机构下载's detail: the saved school it went through, when not the default one (没权限时换下一所学校).
315
+ saved.append(group(label, [row(p, p.get("journal"), (p.get("detail") or "开放获取") if way == OPEN_DOWNLOAD
316
+ else str(p.get("detail") or "")) for p in items]))
316
317
 
317
318
  # A batch of the Markdown alone fails a paper for its Markdown: a site not yet supported's
318
319
  # note stands in for the journal, as on the finished card (user, 2026-11-16).
@@ -89,18 +89,32 @@ def school_status(entity_id: str, pro: Any | None = None) -> str:
89
89
  return status if status in {"verified", "surveyed", "trial", "check"} else ""
90
90
 
91
91
 
92
- def school_list(pro: Any | None = None) -> list[dict[str, str]]:
93
- """The schools Pro knows, each with its name, English name, country, province (a mainland school's) and status,
94
- for the settings page; [] from an older Pro (one without the English name or the country: "" there)."""
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)."""
95
102
  pro = pro if pro is not None else module()
96
103
  try:
97
104
  listed = pro.school_list() if pro is not None and hasattr(pro, "school_list") else []
98
- return [{key: str(school.get(key) or "") for key in ("name", "name_en", "country", "province", "status")}
105
+ return [{**{key: str(school.get(key) or "") for key in SCHOOL_FIELDS}, "names": _names(school.get("names"))}
99
106
  for school in listed if isinstance(school, dict) and school.get("name")]
100
107
  except Exception:
101
108
  return []
102
109
 
103
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
+
104
118
  def school_counts(pro: Any | None = None) -> dict[str, int]:
105
119
  """How many schools Pro fills in for everyone and how many ask for a check; {} from an older Pro."""
106
120
  pro = pro if pro is not None else module()
@@ -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