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
@@ -38,9 +38,16 @@ ASSETS = Path(__file__).with_name("assets")
38
38
  PAGE = ASSETS / "capsule.html"
39
39
 
40
40
 
41
+ #: Where each language's table goes in the page.
42
+ _TABLE_MARKS = {"en": "CAPSULE_EN", "zh-Hant": "CAPSULE_ZH_HANT", "ja": "CAPSULE_JA", "ko": "CAPSULE_KO", "fr": "CAPSULE_FR"}
43
+
44
+
41
45
  def page_html() -> str:
42
- """The page with its English table in it (the window loads it as one string)."""
43
- return PAGE.read_text(encoding="utf-8").replace("/*CAPSULE_EN*/null", i18n.TABLE.read_text(encoding="utf-8"))
46
+ """The page with its tables in it, one per language (the window loads it as one string)."""
47
+ page = PAGE.read_text(encoding="utf-8")
48
+ for code, mark in _TABLE_MARKS.items():
49
+ page = page.replace(f"/*{mark}*/null", i18n.TABLES[code].read_text(encoding="utf-8"))
50
+ return page
44
51
  # PaperSearch's icon (assets/icon.svg) for the Dock.
45
52
  ICON = ASSETS / "icon-512.png"
46
53
  # The first, collapsed frame; the page then reports the size it needs.
@@ -144,6 +151,10 @@ class Notifier:
144
151
  threading.Thread(target=self._send, args=("PaperSearch", message, state), daemon=True).start()
145
152
 
146
153
 
154
+ #: How many schools 添加学校 lists at most (a country's name finds all of its).
155
+ FOUND_SHOWN = 50
156
+
157
+
147
158
  class Api:
148
159
  """What the page calls (``window.pywebview.api``). Every method returns
149
160
  plain values and never raises into the page."""
@@ -420,7 +431,7 @@ class Api:
420
431
  def set_language(self, lang: str) -> dict[str, Any]:
421
432
  """The language switch saves at once and the page follows it."""
422
433
  if lang not in i18n.LANGUAGES:
423
- return {"ok": False, "error": "语言只能是中文或英文"}
434
+ return {"ok": False, "error": "不支持这种语言"}
424
435
  try:
425
436
  user_settings.set_language(lang)
426
437
  except (OSError, ValueError) as exc:
@@ -606,7 +617,9 @@ class Api:
606
617
  "status": school_login.school_status(entity_id, pro) if pro is not None else ""})
607
618
  listed.sort(key=lambda school: not school["current"])
608
619
  current = next((school for school in listed if school["current"]), {})
609
- return {"ok": True, "pro": pro is not None, "schools": listed,
620
+ from . import school_switch
621
+
622
+ return {"ok": True, "pro": pro is not None, "schools": listed, "switch": school_switch.enabled(config),
610
623
  "counts": school_login.school_counts(pro) if pro is not None else {},
611
624
  "school": current.get("name", ""), "entity": bool(current.get("entity")), "saved": bool(current.get("saved")),
612
625
  "username": current.get("username", ""), "enabled": bool(current.get("enabled")),
@@ -675,6 +688,82 @@ class Api:
675
688
  return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
676
689
  return self.school_login_state()
677
690
 
691
+ # 测试登录 (user, 2026-11-21; school_test.py): a saved school's account tried on an article, as a download goes.
692
+ def school_test_article(self, key: str = "") -> dict[str, Any]:
693
+ """The article this school's test opens: {ok, doi} ("" while the user has set none)."""
694
+ if not pro_features():
695
+ return {"ok": False, "error": "这个版本没有自动登录"}
696
+ from .config import load_config
697
+ from .school_test import article
698
+
699
+ entity_id = self._login_school(load_config(), key)
700
+ return {"ok": True, **article(entity_id)} if entity_id else {"ok": False, "error": "这所学校还没有添加"}
701
+
702
+ def set_school_test_article(self, key: str = "", text: str = "") -> dict[str, Any]:
703
+ """The article set by its DOI or its page's address (user, 2026-11-21: set by them, none for them)."""
704
+ if not pro_features():
705
+ return {"ok": False, "error": "这个版本没有自动登录"}
706
+ try:
707
+ from .config import load_config
708
+ from .school_test import set_article
709
+
710
+ entity_id = self._login_school(load_config(), key)
711
+ return set_article(entity_id, str(text or "")) if entity_id else {"ok": False, "error": "这所学校还没有添加"}
712
+ except Exception as exc:
713
+ return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
714
+
715
+ def start_school_test(self, key: str = "", doi: str = "") -> dict[str, Any]:
716
+ """Starts the test of a saved school whose account is saved, on ``doi``; or says why not."""
717
+ if not pro_features():
718
+ return {"state": "idle", "error": "这个版本没有自动登录"}
719
+ try:
720
+ from . import school_login
721
+ from .config import load_config
722
+
723
+ config = load_config()
724
+ entity_id = self._login_school(config, key)
725
+ if not entity_id:
726
+ return {"state": "idle", "error": "这所学校还没有添加"}
727
+ if not school_login.saved(config, entity_id):
728
+ return {"state": "idle", "error": "先保存账号和密码,再测试"}
729
+ doi = str(doi or "").strip()
730
+ if not doi:
731
+ return {"state": "idle", "error": "先填测试文章"}
732
+ return self._school_test().start(entity_id, doi)
733
+ except Exception as exc:
734
+ return {"state": "idle", "error": f"测试没有开始:{type(exc).__name__}"}
735
+
736
+ def school_test_state(self) -> dict[str, Any]:
737
+ return self._school_test().state()
738
+
739
+ def stop_school_test(self) -> dict[str, Any]:
740
+ return self._school_test().stop()
741
+
742
+ def forget_school_test(self) -> dict[str, Any]:
743
+ self._school_test().forget()
744
+ return self._school_test().state()
745
+
746
+ def _school_test(self):
747
+ from .school_test import SchoolTest
748
+
749
+ test = getattr(self, "_test", None)
750
+ if test is None:
751
+ test = self._test = SchoolTest()
752
+ return test
753
+
754
+ def set_school_switch(self, on: bool = True) -> dict[str, Any]:
755
+ """没权限时换下一所学校 on or off (school_switch.py); the page's state after it."""
756
+ if not pro_features():
757
+ return {"ok": False, "error": "这个版本没有自动登录"}
758
+ try:
759
+ from .config import update_config
760
+ from .school_switch import SETTING
761
+
762
+ update_config(SETTING, "true" if on else "false")
763
+ except Exception as exc:
764
+ return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
765
+ return self.school_login_state()
766
+
678
767
  def clear_school_login(self, key: str = "") -> dict[str, Any]:
679
768
  if not pro_features():
680
769
  return {"ok": False, "error": "这个版本没有自动登录"}
@@ -710,16 +799,35 @@ class Api:
710
799
  saved_schools.remember(config)
711
800
  saved = {str(entry.get("idp_entity_id") or "").strip() for entry in saved_schools.saved(config)}
712
801
  pro = school_login.module()
802
+ # 支持哪些学校's own search too (user, 2026-11-21: 台湾 found nothing here, Taiwan's schools there): Pro's
803
+ # list by any of its names (Wikidata's Chinese one among them), its country, province or state, in
804
+ # Chinese or English; each school's names in other languages for the page to show.
805
+ listed = [school for school in school_login.school_list(pro) if school["key"]] if pro is not None else []
806
+ known = {school["key"]: school for school in listed}
807
+ wanted = query.lower()
808
+
809
+ def said(school: dict[str, Any]) -> str:
810
+ places = [school["province"], school["area"], school["country"]]
811
+ return " ".join([school["name"], school["name_en"], *school["names"].values(), *places,
812
+ *(i18n.translate(place, "en") for place in places if place)]).lower()
813
+
713
814
  results = [{"key": school.entity_id, "name": school.name, "name_en": school.name_en,
815
+ "names": known.get(school.entity_id, {}).get("names", {}),
714
816
  "federation": school.summary()["federation"], "added": school.entity_id in saved,
715
817
  "status": school_login.school_status(school.entity_id, pro) if pro is not None else ""}
716
818
  for school in schools if school.entity_id]
819
+ taken = {result["key"] for result in results}
820
+ results += [{"key": school["key"], "name": school["name"], "name_en": school["name_en"], "names": school["names"],
821
+ "federation": school["country"], "added": school["key"] in saved, "status": school["status"]}
822
+ for school in listed if school["key"] not in taken and wanted in said(school)]
717
823
  except Exception as exc:
718
824
  return {"ok": False, "error": f"查找失败:{type(exc).__name__}"}
719
- note = ("" if results else "这所学校所在的学术联盟还不支持" if found.unsupported
825
+ left = max(0, len(results) - FOUND_SHOWN)
826
+ note = (f"还有 {left} 所没列出,输入更完整的名称可以缩小范围" if left
827
+ else "" if results else "这所学校所在的学术联盟还不支持" if found.unsupported
720
828
  else "学校名单暂时读不到,请稍后再试" if found.unavailable
721
829
  else "没有找到这所学校:换成学校的正式中文名、英文名或网址试试")
722
- return {"ok": True, "results": results, "note": note}
830
+ return {"ok": True, "results": results[:FOUND_SHOWN], "note": note}
723
831
 
724
832
  def add_school(self, key: str = "") -> dict[str, Any]:
725
833
  """A school found by 添加学校 kept in the saved list, the default one unchanged (none yet: it)."""
@@ -804,28 +912,13 @@ class Api:
804
912
  except Exception as exc:
805
913
  return {"ok": False, "error": f"读取失败:{type(exc).__name__}"}
806
914
 
807
- def install_pro(self) -> dict[str, Any]:
808
- """The Markdown page's 安装: starts it, or says how it goes (pro_install_state)."""
809
- return self._pro_installer().start()
915
+ def install_pro(self, code: str | None = None) -> dict[str, Any]:
916
+ """Pro's 安装, or 激活并安装 with the code typed: starts it, or says how it goes (pro_install_state)."""
917
+ return self._pro_installer().start(None if code is None else str(code))
810
918
 
811
919
  def pro_install_state(self) -> dict[str, Any]:
812
920
  return self._pro_installer().state()
813
921
 
814
- def check_pro(self) -> dict[str, Any]:
815
- """The Markdown page's 检查更新: starts it, or says how it goes (pro_check_state)."""
816
- return self._pro_checker().start()
817
-
818
- def pro_check_state(self) -> dict[str, Any]:
819
- return self._pro_checker().state()
820
-
821
- def _pro_checker(self):
822
- from .pro_status import ProCheck
823
-
824
- checker = getattr(self, "_pro_check", None)
825
- if checker is None:
826
- checker = self._pro_check = ProCheck()
827
- return checker
828
-
829
922
  def _pro_installer(self):
830
923
  from .pro_status import ProInstall
831
924
 
@@ -834,6 +927,69 @@ class Api:
834
927
  installer = self._pro_install = ProInstall()
835
928
  return installer
836
929
 
930
+ # One version and one update (user, 2026-11-21; updates.py): the about page, the home page's foot, the card's dot.
931
+ def versions(self) -> dict[str, Any]:
932
+ """The version this window runs and the one installed now (an update elsewhere: they differ)."""
933
+ from . import updates
934
+
935
+ return {"running": updates.RUNNING, "installed": updates.installed_version()}
936
+
937
+ def check_versions(self, again: bool = False) -> dict[str, Any]:
938
+ return self._version_check().start(bool(again))
939
+
940
+ def versions_state(self) -> dict[str, Any]:
941
+ return self._version_check().state()
942
+
943
+ def update_all(self) -> dict[str, Any]:
944
+ """更新: what the last check found behind (PaperSearch, then its extension and Skills; Pro)."""
945
+ checked = self._version_check().state()
946
+ if checked.get("state") != "done":
947
+ return {"state": "idle", "error": "先检查更新"}
948
+ return self._updater().start(bool(checked.get("update")), bool(checked.get("pro_update")),
949
+ str(checked.get("latest") if checked.get("update") else ""))
950
+
951
+ def update_state(self) -> dict[str, Any]:
952
+ return self._updater().state()
953
+
954
+ def reopen_window(self, page: str = "about") -> dict[str, Any]:
955
+ """The settings opened again with the PaperSearch installed now, once this window has closed."""
956
+ from . import updates
957
+
958
+ page = page if page in ("home", "about") else "about"
959
+ if not updates.reopen(page):
960
+ return {"ok": False, "message": "找不到 paper-search 命令,请关掉窗口后重新打开设置"}
961
+ threading.Timer(0.3, self.request_close).start()
962
+ return {"ok": True}
963
+
964
+ def open_release_notes(self) -> dict[str, Any]:
965
+ """这次更新了什么: the release notes where the check found the new version."""
966
+ import webbrowser
967
+
968
+ url = str(self._version_check().state().get("notes") or "")
969
+ if not url.startswith("https://"):
970
+ return {"ok": False, "message": "没有更新说明"}
971
+ try:
972
+ opened = webbrowser.open(url)
973
+ except Exception as exc:
974
+ return {"ok": False, "message": f"打开失败:{type(exc).__name__}"}
975
+ return {"ok": True} if opened else {"ok": False, "message": "打开失败:没有找到默认浏览器"}
976
+
977
+ def _version_check(self):
978
+ from .updates import VersionCheck
979
+
980
+ check = getattr(self, "_versions", None)
981
+ if check is None:
982
+ check = self._versions = VersionCheck()
983
+ return check
984
+
985
+ def _updater(self):
986
+ from .updates import UpdateAll
987
+
988
+ updater = getattr(self, "_update_all", None)
989
+ if updater is None:
990
+ updater = self._update_all = UpdateAll()
991
+ return updater
992
+
837
993
  def open_issue(self) -> dict[str, Any]:
838
994
  """GitHub's new-issue page for the Markdown, its title begun."""
839
995
  import webbrowser
@@ -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).
@@ -420,9 +430,22 @@ def _short_line(value: Any, limit: int = 80) -> str:
420
430
  return " ".join(value.split())[:limit]
421
431
 
422
432
 
423
- FAILURE_CLASSES = ("no_access", "user_side", "school_side", "publisher_or_network", "article_or_site", "unsupported", "unexplained")
433
+ # The five failure classes (PaperSearch's failureClass.ts; docs/contracts/failure-reasons.zh.md), and the eight before
434
+ # 2026-11-22 as they map to them (a PaperSearch older than this backend may still send those).
435
+ FAILURE_CLASSES = ("no_access", "user_side", "external", "unsupported", "unexplained")
436
+ _OLD_CLASSES = {"school_side": "external", "publisher_or_network": "external", "article_or_site": "external",
437
+ "adaptation": "unsupported"}
438
+
439
+
440
+ def _failure_class(value: Any) -> str:
441
+ value = _OLD_CLASSES.get(value, value) if isinstance(value, str) else value
442
+ return value if value in FAILURE_CLASSES else "unexplained"
443
+
424
444
  _RESULT_CONTENTS = ("main", "supplements", "both", "markdown")
425
- _MAX_RESULT_FAILURES = 1000 # the caller's batch limit
445
+ # A bound against malformed input only: a batch has no limit since 7a38a068 (user, 2026-11-17). Left at its old 1000,
446
+ # a batch's papers after the 1000th were left out of the lists (user, 2026-11-21: 失败 1 on the card, the list empty,
447
+ # the failed paper the 1211th of 1551; 成功 and 剩余 stopped at 1000 too).
448
+ _MAX_BATCH_PAPERS = 100_000
426
449
  _MAX_RESULT_TEXT = 300
427
450
 
428
451
 
@@ -479,11 +502,11 @@ def _batch_results(raw: Any) -> dict[str, Any] | None:
479
502
  }
480
503
  for key in ("failures", "supplement_failures", "markdown_failures"):
481
504
  listed = raw.get(key)
482
- for item in (listed if isinstance(listed, list) else [])[:_MAX_RESULT_FAILURES]:
505
+ for item in (listed if isinstance(listed, list) else [])[:_MAX_BATCH_PAPERS]:
483
506
  if not isinstance(item, dict) or not text(item.get("reason")):
484
507
  continue
485
508
  summary[key].append({
486
- "cls": item.get("cls") if item.get("cls") in FAILURE_CLASSES else "unexplained",
509
+ "cls": _failure_class(item.get("cls")),
487
510
  **{field: text(item.get(field)) for field in ("reason", "title", "journal", "doi", "note")},
488
511
  # A site not yet supported (its note says where it fell short).
489
512
  **({"unverified": True} if item.get("unverified") is True else {}),
@@ -517,7 +540,7 @@ def _paper(raw: Any) -> dict[str, Any] | None:
517
540
  if not isinstance(raw, dict) or raw.get("state") not in PAPER_STATES:
518
541
  return None
519
542
  index = raw.get("index")
520
- if not isinstance(index, int) or isinstance(index, bool) or not 1 <= index <= _MAX_RESULT_FAILURES:
543
+ if not isinstance(index, int) or isinstance(index, bool) or not 1 <= index <= _MAX_BATCH_PAPERS:
521
544
  return None
522
545
  paper = {"index": index, "state": raw["state"],
523
546
  **{field: _display_text(raw.get(field)) for field in ("doi", "title", "journal")}}
@@ -531,18 +554,17 @@ def _paper(raw: Any) -> dict[str, Any] | None:
531
554
  if isinstance(files, int) and not isinstance(files, bool) and 0 <= files <= 100_000:
532
555
  paper["supplements_saved"] = files
533
556
  if raw.get("supplement_reason"): # saved, but not every supplementary file
534
- paper.update(supplement_cls=raw.get("supplement_cls") if raw.get("supplement_cls") in FAILURE_CLASSES
535
- else "unexplained", supplement_reason=_display_text(raw.get("supplement_reason")))
557
+ paper.update(supplement_cls=_failure_class(raw.get("supplement_cls")),
558
+ supplement_reason=_display_text(raw.get("supplement_reason")))
536
559
  if raw.get("markdown_reason"): # saved, without the Markdown asked for
537
- paper.update(markdown_cls=raw.get("markdown_cls") if raw.get("markdown_cls") in FAILURE_CLASSES
538
- else "unexplained", markdown_reason=_display_text(raw.get("markdown_reason")))
560
+ paper.update(markdown_cls=_failure_class(raw.get("markdown_cls")),
561
+ markdown_reason=_display_text(raw.get("markdown_reason")))
539
562
  # Saved with a Markdown its checks found short, from a registered site's page (user, 2026-11-17).
540
563
  if _display_text(raw.get("markdown_doubt_reason")):
541
564
  paper.update(markdown_doubt_reason=_display_text(raw.get("markdown_doubt_reason")),
542
565
  markdown_doubt_note=_display_text(raw.get("markdown_doubt_note")))
543
566
  elif paper["state"] == "failed":
544
- paper.update(cls=raw.get("cls") if raw.get("cls") in FAILURE_CLASSES else "unexplained",
545
- reason=_display_text(raw.get("reason")))
567
+ paper.update(cls=_failure_class(raw.get("cls")), reason=_display_text(raw.get("reason")))
546
568
  # Its page from a site not yet supported (user, 2026-11-16): the site, whether its Markdown
547
569
  # was kept or the batch gave the site up, a note on what it lacked, the kept report.
548
570
  host = raw.get("markdown_host")
@@ -590,7 +612,7 @@ def sync_papers(batch_id: str, folder: str, papers: Any) -> bool:
590
612
  if isinstance(folder, str) and 0 < len(folder) <= 4096 and os.path.isabs(folder):
591
613
  listed["folder"] = folder
592
614
  known = listed["papers"]
593
- for raw in papers[:_MAX_RESULT_FAILURES]:
615
+ for raw in papers[:_MAX_BATCH_PAPERS]:
594
616
  paper = _paper(raw)
595
617
  if paper is None:
596
618
  continue
@@ -667,6 +689,7 @@ def tracked_download(current: str, output_dir: Any = None, batch: BatchContext |
667
689
  markdown=bool(markdown), page_reading=False)
668
690
  if output_dir:
669
691
  set_output_dir(output_dir)
692
+ name_journal(current)
670
693
  outcome: dict[str, Any] = {}
671
694
  try:
672
695
  yield outcome
@@ -717,6 +740,38 @@ def _finish_download(outcome: dict[str, Any], current: str, batch: BatchContext
717
740
  finish()
718
741
 
719
742
 
743
+ def name_journal(current: str, look_up: Callable[[str], dict[str, Any]] | None = None) -> threading.Thread | None:
744
+ """The paper's journal on the card, where PaperSearch gave none (a list of DOIs; user, 2026-11-21: the card said
745
+ Elsevier, the publisher, for a paper of Metabolism): looked up beside the download (Crossref, kept by
746
+ entitlements.journal_identity), said once known, while the card is still on that paper."""
747
+ if look_up is None and os.environ.get("SCHOOL_PROGRESS_BAR") == "0":
748
+ return None # no card to say it on (and no lookups from the tests)
749
+ with _LOCK:
750
+ if not _STATE or _STATE.get("journal") or str(_STATE.get("current") or "") != current or not current:
751
+ return None
752
+
753
+ def look() -> None:
754
+ try:
755
+ if look_up is None:
756
+ from .entitlements import journal_identity
757
+
758
+ name = str(journal_identity(current).get("journal") or "").strip()
759
+ else:
760
+ name = str(look_up(current).get("journal") or "").strip()
761
+ except Exception:
762
+ return # the card keeps the publisher
763
+ if not name:
764
+ return
765
+ with _LOCK:
766
+ if _STATE and str(_STATE.get("current") or "") == current and not _STATE.get("journal"):
767
+ _STATE["journal"] = name
768
+ _write_state()
769
+
770
+ thread = threading.Thread(target=look, name="journal-name", daemon=True)
771
+ thread.start()
772
+ return thread
773
+
774
+
720
775
  def _write_state() -> None:
721
776
  """Called under _LOCK; revisions count successful atomic replacements only."""
722
777
  payload = {
@@ -61,7 +61,7 @@ TERMINAL_STATUSES = frozenset({"done", "failed", "cancelled", "interrupted"})
61
61
  MAX_REASON_ROWS = 5
62
62
  OPEN_FAILURES_UP_TO = 3
63
63
  MAX_LISTED_PAPERS = 200
64
- CLASS_ORDER = ("no_access", "user_side", "school_side", "publisher_or_network", "article_or_site", "unsupported", "unexplained")
64
+ CLASS_ORDER = ("no_access", "user_side", "external", "unsupported", "unexplained")
65
65
  DEFAULT_LINGER_SECONDS = 8.0
66
66
  NOTICE_SECONDS = 10.0 # how long the download's answer to a click stays on screen
67
67
 
@@ -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).
@@ -3,12 +3,14 @@
3
3
  "profile": {
4
4
  "name": "SAGE",
5
5
  "doi_prefixes": [
6
- "10.1177"
6
+ "10.1177",
7
+ "10.1191",
8
+ "10.1258"
7
9
  ],
8
10
  "base_domains": [
9
11
  "sagepub.com"
10
12
  ],
11
- "article_url_template": "https://doi.org/{doi}",
13
+ "article_url_template": "https://journals.sagepub.com/doi/{doi}",
12
14
  "pdf_url_templates": [
13
15
  "https://journals.sagepub.com/doi/pdf/{doi}"
14
16
  ],
@@ -3,7 +3,9 @@
3
3
  "profile": {
4
4
  "name": "Thieme",
5
5
  "doi_prefixes": [
6
- "10.1055"
6
+ "10.1055",
7
+ "10.1160",
8
+ "10.3414"
7
9
  ],
8
10
  "base_domains": [
9
11
  "thieme-connect.com",
@@ -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,84 @@
1
+ """没权限时换下一所学校 (PaperSearch Pro; user, 2026-11-21).
2
+
3
+ A paper the school has no access to, failed under 没权限 (signed in and refused, the school's sign-in not enabled for
4
+ the publisher, no route for it there, or marked by the user as without access), is tried with the next saved school:
5
+ one Pro fills the sign-in of, its account saved and its auto sign-in on; the default school first, then the list's
6
+ order. A download on its own switches at once. A batch switches once at its end (download/batch/batch.ts): its papers
7
+ all with the default school, then those without access together with the next school, and so on (user, 2026-11-22:
8
+ switching to and fro at each paper had a school's login ask for a picture code). Only 没权限 switches: a sign-in that
9
+ failed (a wrong password, a code to type, a page that stopped it) is the user's to see, not another account's. Each
10
+ switch forgets the sign-in before it (cold_start.before_sign_in), the batch's browser closed first to let go of it.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ #: The switch on the sign-in page (config), on unless turned off.
17
+ SETTING = "school_switch"
18
+
19
+ #: 没权限 besides a refusal after the sign-in (failureClass.ts): the school's sign-in not enabled for the publisher (IEEE
20
+ #: "Your institution may not be enabled", AHA's OpenAthens "restricted by your organization"), the publisher with no route
21
+ #: for it, or the user's mark, made with the default school. Another school may have it (user, 2026-11-22: IEEE was not
22
+ #: tried with the second school; every paper under 没权限 is).
23
+ NOT_THIS_SCHOOL = ("institution_not_registered", "institution_federation_unavailable", "no_entitlement")
24
+
25
+ #: Set on a download's config when its school is not the default one: the user's 没权限 marks were made with the
26
+ #: default school and do not skip another's visit (engine/bridge.py).
27
+ MARKS_OFF = "no_access_marks_off"
28
+
29
+
30
+ def enabled(config: dict[str, Any]) -> bool:
31
+ return config.get(SETTING) is not False
32
+
33
+
34
+ def no_access(result: dict[str, Any] | None) -> bool:
35
+ """The school has no access to this article, a 没权限 failure (not a sign-in that failed)."""
36
+ if not result or result.get("success"):
37
+ return False
38
+ if result.get("error_type") in NOT_THIS_SCHOOL:
39
+ return True
40
+ return result.get("error_type") == "paywall" and result.get("reason_code") == "institution_pdf_entitlement_missing"
41
+
42
+
43
+ #: A failure after one of the school's entries by one name, its next entry to be tried (user, 2026-11-22: "同名学校的话,
44
+ #: 那就直接选一个……如果这个不行的话,再向下一个"): 没权限, or the login not reached or not finished (JAMA's first
45
+ #: entry of a test school was its library proxy, whose sign-in asks for a picture code).
46
+ ENTRY_DID_NOT_DO = ("login_not_reached", "login_timeout", "idp_no_return_to_publisher")
47
+
48
+
49
+ def entry_did_not_do(result: dict[str, Any] | None) -> bool:
50
+ """The download failed after one of several entries by the school's name: the next one may do."""
51
+ return bool(result) and not result.get("success") and int(result.get("same_name_entries") or 0) > 1 and (
52
+ no_access(result) or result.get("error_type") in ENTRY_DID_NOT_DO)
53
+
54
+
55
+ def schools(config: dict[str, Any]) -> list[dict[str, Any]]:
56
+ """The schools taking part, in order: the default one, then each other saved school Pro fills the sign-in of, its
57
+ account saved and its auto sign-in on. [] without Pro."""
58
+ from . import school_login
59
+ from .schools import saved as saved_schools
60
+
61
+ pro = school_login.module()
62
+ if pro is None:
63
+ return []
64
+ saved_schools.remember(config)
65
+ listed = saved_schools.saved(config)
66
+ current = [entry for entry in listed if saved_schools.is_current(config, entry)]
67
+ order: list[dict[str, Any]] = current[:]
68
+ for entry in listed:
69
+ entity = str(entry.get("idp_entity_id") or "").strip()
70
+ if entry in current or not entity:
71
+ continue
72
+ account = school_login.saved(config, entity) or {}
73
+ if account.get("enabled") and school_login.fills_for(entity, pro):
74
+ order.append(entry)
75
+ return order
76
+
77
+
78
+ def grouping(config: dict[str, Any]) -> bool:
79
+ """Whether a batch takes one journal's papers one after another: on, and more than one school taking part."""
80
+ return enabled(config) and len(schools(config)) > 1
81
+
82
+
83
+ def name(entry: dict[str, Any]) -> str:
84
+ return str(entry.get("school_name") or entry.get("school_name_en") or entry.get("idp_entity_id") or "")