papersearch 0.8.0 → 0.8.1

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 (101) hide show
  1. package/NOTICE +1 -1
  2. package/README.fr.md +5 -8
  3. package/README.ja.md +5 -8
  4. package/README.ko.md +5 -8
  5. package/README.md +148 -151
  6. package/README.zh-Hant.md +5 -8
  7. package/README.zh.md +265 -0
  8. package/dist/capabilities/download/batch/batch.d.ts +4 -0
  9. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  10. package/dist/capabilities/download/batch/batch.js +714 -198
  11. package/dist/capabilities/download/batch/batch.js.map +1 -1
  12. package/dist/capabilities/download/batch/windowPlan.d.ts +96 -0
  13. package/dist/capabilities/download/batch/windowPlan.d.ts.map +1 -0
  14. package/dist/capabilities/download/batch/windowPlan.js +196 -0
  15. package/dist/capabilities/download/batch/windowPlan.js.map +1 -0
  16. package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
  17. package/dist/capabilities/download/content/markdown/step.js +4 -1
  18. package/dist/capabilities/download/content/markdown/step.js.map +1 -1
  19. package/dist/capabilities/download/content/pdf/open/tiers/scihub.d.ts.map +1 -1
  20. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js +3 -1
  21. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js.map +1 -1
  22. package/dist/infrastructure/http/hostGate.d.ts +24 -0
  23. package/dist/infrastructure/http/hostGate.d.ts.map +1 -0
  24. package/dist/infrastructure/http/hostGate.js +72 -0
  25. package/dist/infrastructure/http/hostGate.js.map +1 -0
  26. package/dist/infrastructure/pdf/PdfDownload.d.ts +1 -0
  27. package/dist/infrastructure/pdf/PdfDownload.d.ts.map +1 -1
  28. package/dist/infrastructure/pdf/PdfDownload.js +6 -1
  29. package/dist/infrastructure/pdf/PdfDownload.js.map +1 -1
  30. package/dist/infrastructure/runlog/RunLedger.d.ts +7 -0
  31. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  32. package/dist/infrastructure/runlog/RunLedger.js +17 -4
  33. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  34. package/dist/infrastructure/school/SchoolMcpClient.d.ts +12 -2
  35. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  36. package/dist/infrastructure/school/SchoolMcpClient.js +122 -11
  37. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  38. package/dist/infrastructure/school/SchoolReadiness.d.ts +7 -0
  39. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  40. package/dist/infrastructure/school/SchoolReadiness.js +8 -0
  41. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  42. package/dist/infrastructure/school/index.d.ts +1 -1
  43. package/dist/infrastructure/school/index.d.ts.map +1 -1
  44. package/dist/infrastructure/school/types.d.ts +31 -1
  45. package/dist/infrastructure/school/types.d.ts.map +1 -1
  46. package/dist/infrastructure/school/types.js.map +1 -1
  47. package/dist/infrastructure/security/SecurityUtils.d.ts.map +1 -1
  48. package/dist/infrastructure/security/SecurityUtils.js +6 -2
  49. package/dist/infrastructure/security/SecurityUtils.js.map +1 -1
  50. package/dist/management/failures/index.d.ts.map +1 -1
  51. package/dist/management/failures/index.js +5 -2
  52. package/dist/management/failures/index.js.map +1 -1
  53. package/dist/management/school/autoUpdate.d.ts.map +1 -1
  54. package/dist/management/school/autoUpdate.js +9 -1
  55. package/dist/management/school/autoUpdate.js.map +1 -1
  56. package/dist/management/school/cliProgress.d.ts.map +1 -1
  57. package/dist/management/school/cliProgress.js +3 -1
  58. package/dist/management/school/cliProgress.js.map +1 -1
  59. package/package.json +2 -2
  60. package/school/paper_search_school/adapters/base.py +3 -0
  61. package/school/paper_search_school/adapters/optica/__init__.py +50 -4
  62. package/school/paper_search_school/adapters/platforms/atypon/__init__.py +4 -3
  63. package/school/paper_search_school/adapters/platforms/figshare/__init__.py +23 -4
  64. package/school/paper_search_school/assets/capsule.html +380 -41
  65. package/school/paper_search_school/assets/capsule_en.json +72 -4
  66. package/school/paper_search_school/assets/capsule_fr.json +72 -4
  67. package/school/paper_search_school/assets/capsule_ja.json +72 -4
  68. package/school/paper_search_school/assets/capsule_ko.json +72 -4
  69. package/school/paper_search_school/assets/capsule_zh-Hant.json +66 -3
  70. package/school/paper_search_school/browser/backend.py +125 -4
  71. package/school/paper_search_school/browser/batch_session.py +188 -7
  72. package/school/paper_search_school/browser/challenge/continuation.py +19 -1
  73. package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +38 -10
  74. package/school/paper_search_school/browser/challenge/pro.py +24 -0
  75. package/school/paper_search_school/browser/challenge/services/solver.py +24 -4
  76. package/school/paper_search_school/browser/engine.py +4 -1
  77. package/school/paper_search_school/browser/user_turn.py +126 -0
  78. package/school/paper_search_school/browser/watchdog.py +213 -60
  79. package/school/paper_search_school/config.py +5 -0
  80. package/school/paper_search_school/engine/batch.py +9 -7
  81. package/school/paper_search_school/engine/batch_access.py +27 -7
  82. package/school/paper_search_school/engine/batch_capture.py +45 -13
  83. package/school/paper_search_school/engine/batch_institution.py +14 -0
  84. package/school/paper_search_school/engine/batch_login.py +177 -22
  85. package/school/paper_search_school/engine/batch_user.py +48 -3
  86. package/school/paper_search_school/engine/batch_waits.py +42 -2
  87. package/school/paper_search_school/engine/bridge.py +1 -2
  88. package/school/paper_search_school/engine/fulltext_page.py +10 -1
  89. package/school/paper_search_school/engine/supplements.py +7 -1
  90. package/school/paper_search_school/entitlements.py +28 -0
  91. package/school/paper_search_school/progress_capsule.py +33 -5
  92. package/school/paper_search_school/progress_reporter.py +189 -6
  93. package/school/paper_search_school/progress_view.py +142 -48
  94. package/school/paper_search_school/rate_limit.py +24 -1
  95. package/school/paper_search_school/school_login.py +170 -8
  96. package/school/paper_search_school/server.py +164 -19
  97. package/school/paper_search_school/user_settings.py +33 -4
  98. package/skills/paper-search/SKILL.md +1 -1
  99. package/skills/paper-search/references/browser-download.md +2 -2
  100. package/LICENSE-paper-search-mcp-nodejs +0 -24
  101. package/README.en.md +0 -268
@@ -275,8 +275,11 @@ class Api:
275
275
  # Asked for from a reminder, or from the paper on the card at any
276
276
  # time while it has a browser (user request, 2026-11-08).
277
277
  state = read_state() or {}
278
- if (state.get("status") != "running"
279
- or str(state.get("current") or "") != current
278
+ # Papers downloading at once (user, 2026-11-29): each row's own, not only the card's.
279
+ papers = state.get("papers") if isinstance(state.get("papers"), dict) else {}
280
+ downloading = {str(state.get("current") or "")} | {
281
+ str(paper.get("current") or "") for paper in papers.values() if isinstance(paper, dict)}
282
+ if (state.get("status") != "running" or current not in downloading
280
283
  or str(state.get("run_id") or "") != run_id):
281
284
  return "当前没有正在下载的浏览器"
282
285
  if not state.get("attention") and state.get("channel"):
@@ -312,6 +315,21 @@ class Api:
312
315
  except Exception as exc:
313
316
  return f"记录失败:{type(exc).__name__}"
314
317
 
318
+ def choose_way(self, index: int, current: str, run_id: str = "") -> str:
319
+ """The way the user picked on the 选择登录方式 card (a sign-in chooser's, user 2026-11-29), for the paper
320
+ asked for; the running download presses it in the browser and keeps it for the school."""
321
+ try:
322
+ from .entitlements import request_way
323
+
324
+ state = read_state() or {}
325
+ if (state.get("status") != "running" or str(state.get("current") or "") != str(current)
326
+ or str(state.get("run_id") or "") != str(run_id)):
327
+ return "这篇已不在等待选择"
328
+ request_way(str(current), int(index), str(run_id))
329
+ return ""
330
+ except Exception as exc:
331
+ return f"记录失败:{type(exc).__name__}"
332
+
315
333
  def issue_kinds(self) -> list[list[str]]:
316
334
  from .issues import ISSUE_KINDS
317
335
 
@@ -442,6 +460,8 @@ class Api:
442
460
  "notify": user_settings.notify_enabled(),
443
461
  "hourly_now": user_settings.hourly_now(),
444
462
  "retry": user_settings.retry_enabled(),
463
+ # 同时下载: serial or parallel; its two numbers are fields (page "parallel").
464
+ "parallel": user_settings.parallel_enabled(),
445
465
  "download_dir": download_directory.current(),
446
466
  "language": self._lang,
447
467
  # Whether the settings have the Markdown page (PaperSearch Pro's, edition.py).
@@ -535,9 +555,11 @@ class Api:
535
555
  return False
536
556
  return True
537
557
 
538
- def save_settings(self, values: dict[str, Any], download_dir: str | None = None) -> dict[str, Any]:
558
+ def save_settings(self, values: dict[str, Any], download_dir: str | None = None,
559
+ parallel: bool | None = None) -> dict[str, Any]:
539
560
  """Check the fields of one settings page, then save them all; nothing is
540
- saved when one is wrong. The notification switch saves on its own."""
561
+ saved when one is wrong. The notification switch saves on its own.
562
+ ``parallel``: the 下载 page's 同时下载, serial (False) or parallel (True)."""
541
563
  checked, errors = {}, {}
542
564
  for field in user_settings.FIELDS:
543
565
  if field.name not in (values or {}):
@@ -558,6 +580,8 @@ class Api:
558
580
  if download_dir is not None:
559
581
  download_directory.save(download_dir)
560
582
  user_settings.save(checked)
583
+ if isinstance(parallel, bool):
584
+ user_settings.set_parallel(parallel)
561
585
  except Exception as exc:
562
586
  return {"ok": False, "errors": {"": f"保存失败:{type(exc).__name__}"}}
563
587
  return {"ok": True}
@@ -644,7 +668,8 @@ class Api:
644
668
  "current": saved_schools.is_current(config, entry), "entity": bool(entity_id),
645
669
  "saved": bool(account), "username": school_login.masked(account.get("username", "")) if account else "",
646
670
  "enabled": bool(account.get("enabled")), "off": str(account.get("off") or ""),
647
- "status": school_login.school_status(entity_id, pro) if pro is not None else ""})
671
+ "status": school_login.school_status(entity_id, pro) if pro is not None else "",
672
+ **(school_login.entry_for(entity_id, pro) if pro is not None else {})})
648
673
  listed.sort(key=lambda school: not school["current"])
649
674
  current = next((school for school in listed if school["current"]), {})
650
675
  from . import school_switch
@@ -1141,7 +1166,10 @@ class Api:
1141
1166
  def read():
1142
1167
  point = AppKit.NSEvent.mouseLocation()
1143
1168
  frame = self._window.native.frame()
1169
+ # Also the pointer in the page (from its top left): the window not active, the page gets no pointer
1170
+ # moves, and the row under it is found from here (并行下载, user's Mac 2026-11-29).
1144
1171
  return {"x": point.x, "y": point.y,
1172
+ "page_x": point.x - frame.origin.x, "page_y": frame.origin.y + frame.size.height - point.y,
1145
1173
  "inside": frame.origin.x + 10 <= point.x < frame.origin.x + frame.size.width - 10
1146
1174
  and frame.origin.y + 10 <= point.y < frame.origin.y + frame.size.height - 10}
1147
1175
  return _cocoa_call(read)
@@ -37,6 +37,15 @@ _STATE: dict[str, Any] = {}
37
37
  _STARTED_MONO: float = 0.0
38
38
  _STAGE_LISTENER: ContextVar[tuple[str, Callable[[str], None]] | None] = ContextVar(
39
39
  "school_request_stage_listener", default=None)
40
+ #: 并行下载 (user, 2026-11-29): the window of a batch whose papers run at once that the current download runs in
41
+ #: (server.py binds it); None for a download on its own or a batch one paper after another.
42
+ _WINDOW: ContextVar[int | None] = ContextVar("school_progress_window", default=None)
43
+ #: What the card says of the paper downloading. In a batch whose papers run at once, each window's paper keeps its own
44
+ #: under ``papers`` (by window), and the card's own fields are those of the paper it shows (``_show``). The browser's
45
+ #: processes (``browser_pid``, ``browser_pids``) are the batch's: its windows are one Chrome (user's Mac, 2026-11-29: a
46
+ #: click on a row said 未能切到下载浏览器, the paper shown being one whose window had none to say).
47
+ PAPER_KEYS = ("current", "title", "journal", "publisher", "notice", "stage", "phase", "part", "transfer",
48
+ "supplements_saved", "supplements_total", "page_reading", "content", "markdown")
40
49
 
41
50
  STAGES = frozenset({
42
51
  "starting", "opening_article", "waiting_login", "waiting_verification",
@@ -276,6 +285,42 @@ def _batch_state(batch_id: str) -> dict[str, Any] | None:
276
285
  PAPER_FIELDS = ("title", "journal", "publisher", "notice")
277
286
 
278
287
 
288
+ def bind_window(window: int | None):
289
+ """The current download's window in a batch whose papers run at once (None: none); the token to unbind."""
290
+ return _WINDOW.set(window)
291
+
292
+
293
+ def unbind_window(token) -> None:
294
+ _WINDOW.reset(token)
295
+
296
+
297
+ def _window_paper() -> dict[str, Any] | None:
298
+ """Under _LOCK: the current window's paper in a batch whose papers run at once ({} once it has left the card:
299
+ what it says then goes nowhere); None for a download that is no window's."""
300
+ window = _WINDOW.get()
301
+ if window is None or not _STATE:
302
+ return None
303
+ papers = _STATE.get("papers")
304
+ return papers.get(str(window), {}) if isinstance(papers, dict) else {}
305
+
306
+
307
+ def _show() -> None:
308
+ """Under _LOCK: the card shows one of the papers downloading at once: the one asking for the user, else the one
309
+ downloading longest (it stays until it ends). Its fields become the card's."""
310
+ papers = _STATE.get("papers") if _STATE else None
311
+ if not isinstance(papers, dict) or not papers:
312
+ return
313
+ asking = [str(entry.get("current") or "") for entry in (_STATE.get("attention") or {}).values() if isinstance(entry, dict)]
314
+ shown = next((paper for paper in papers.values() if asking and paper.get("current") in asking), None)
315
+ if shown is None:
316
+ shown = min(papers.values(), key=lambda paper: paper.get("since") or 0)
317
+ for key in PAPER_KEYS:
318
+ if key in shown:
319
+ _STATE[key] = shown[key]
320
+ elif key not in ("current", "stage", "phase"):
321
+ _STATE.pop(key, None)
322
+
323
+
279
324
  def _adopt_batch(batch_id: str, total: int, counts: tuple[int | None, int | None, int | None],
280
325
  *, beside_download: bool = False, **fields: Any) -> bool | None:
281
326
  """Continue this batch's report in the current process, or start it (True).
@@ -296,6 +341,10 @@ def _adopt_batch(batch_id: str, total: int, counts: tuple[int | None, int | None
296
341
  pass
297
342
  previous = _batch_state(batch_id)
298
343
  with _LOCK:
344
+ if (not beside_download and _STATE.get("batch_id") == batch_id and _STATE.get("status") == "running"
345
+ and _STATE.get("papers") and _WINDOW.get() is None):
346
+ # Papers downloading at once: a report of the caller changes the totals and its lines only.
347
+ beside_download = True
299
348
  if beside_download:
300
349
  if (_STATE.get("batch_id") == batch_id and _STATE.get("status") == "running"
301
350
  and not _STATE.get("awaiting_next")):
@@ -329,6 +378,31 @@ def _adopt_batch(batch_id: str, total: int, counts: tuple[int | None, int | None
329
378
  "revision": 0,
330
379
  }
331
380
  done, succeeded, failed = counts
381
+ window = _WINDOW.get()
382
+ if _STATE.get("batch_id") == batch_id and _STATE.get("status") in ("running", "done"):
383
+ previous = _STATE # this process's own report, newer than the file it read above
384
+ if window is not None and previous is not None and previous.get("status") == "running":
385
+ # A window's paper of a batch whose papers run at once: the others' papers and prompts stay, and the counts
386
+ # its download came with (the caller's when it started) never take back what was counted since.
387
+ papers = previous.get("papers") if isinstance(previous.get("papers"), dict) else {}
388
+ paper = {"since": time.time(), **{k: v for k, v in fields.items() if k in PAPER_KEYS}}
389
+ _STATE = {
390
+ **previous,
391
+ "batch_id": batch_id,
392
+ "total": int(total),
393
+ "status": "running",
394
+ "awaiting_next": False,
395
+ "owner_pid": os.getpid(),
396
+ "papers": {**papers, str(window): paper},
397
+ **{k: v for k, v in fields.items() if k not in PAPER_KEYS},
398
+ **{key: max(int(previous.get(key) or 0), value)
399
+ for key, value in (("done", done), ("success", succeeded), ("failed", failed)) if value is not None},
400
+ }
401
+ _STATE.pop("finished_at", None)
402
+ _STATE.pop("results", None)
403
+ _show()
404
+ _write_state()
405
+ return True
332
406
  _STATE = {
333
407
  **previous,
334
408
  "batch_id": batch_id,
@@ -342,6 +416,8 @@ def _adopt_batch(batch_id: str, total: int, counts: tuple[int | None, int | None
342
416
  **({"failed": failed} if failed is not None else {}),
343
417
  **fields,
344
418
  }
419
+ if window is not None:
420
+ _STATE["papers"] = {str(window): {"since": time.time(), **{k: v for k, v in fields.items() if k in PAPER_KEYS}}}
345
421
  _STATE.pop("finished_at", None)
346
422
  _STATE.pop("results", None)
347
423
  _write_state()
@@ -428,6 +504,10 @@ def sync_batch(batch_id: str, total: int, done: int, succeeded: int, failed: int
428
504
  return False
429
505
  phase, channel, lanes = _short_line(phase), _short_line(channel), _short_line(lanes)
430
506
  school = _short_line(switch_to, 40)
507
+ if finished:
508
+ with _LOCK:
509
+ if _STATE.get("batch_id") == ctx.batch_id:
510
+ _STATE.pop("papers", None) # the batch's end: no window's paper is left on the card
431
511
  adopted = _adopt_batch(ctx.batch_id, total, (done, succeeded, failed),
432
512
  beside_download=bool(lanes) and not finished,
433
513
  **({"current": current} if current else {}),
@@ -743,7 +823,9 @@ def tracked_download(current: str, output_dir: Any = None, batch: BatchContext |
743
823
  try:
744
824
  yield outcome
745
825
  finally:
746
- if outcome.get("paused") and batch is not None:
826
+ if _WINDOW.get() is not None and batch is not None:
827
+ _leave_window(outcome)
828
+ elif outcome.get("paused") and batch is not None:
747
829
  with _LOCK:
748
830
  if _STATE:
749
831
  _STATE.update(awaiting_next=True, phase=str(outcome["paused"]),
@@ -753,6 +835,29 @@ def tracked_download(current: str, output_dir: Any = None, batch: BatchContext |
753
835
  _finish_download(outcome, current, batch, content)
754
836
 
755
837
 
838
+ def _leave_window(outcome: dict[str, Any]) -> None:
839
+ """A window's paper of a batch whose papers run at once ended (or waits for its publisher's hour): it leaves the
840
+ card, which shows another one downloading; with none left the card waits for the next, as between two papers of
841
+ a batch. The caller counts it (its next report)."""
842
+ with _LOCK:
843
+ if not _STATE:
844
+ return
845
+ papers = _STATE.get("papers") if isinstance(_STATE.get("papers"), dict) else {}
846
+ papers.pop(str(_WINDOW.get()), None)
847
+ attention = _STATE.get("attention") if isinstance(_STATE.get("attention"), dict) else {}
848
+ current = str(((outcome.get("result") or {}).get("identifier")) or "")
849
+ for key in [key for key, entry in attention.items() if isinstance(entry, dict) and current
850
+ and str(entry.get("current") or "").lower() == current.lower()]:
851
+ attention.pop(key, None)
852
+ if papers:
853
+ _show()
854
+ else:
855
+ _STATE.pop("papers", None)
856
+ _STATE.update(awaiting_next=True, transfer=None, phase=str(outcome.get("paused") or "")
857
+ or f"已完成 {int(_STATE.get('done') or 0)}/{int(_STATE.get('total') or 0)} 篇,等待下一篇")
858
+ _write_state()
859
+
860
+
756
861
  def _finish_download(outcome: dict[str, Any], current: str, batch: BatchContext | None,
757
862
  content: str = "main") -> None:
758
863
  """Count the download and show how it ended (end of ``tracked_download``)."""
@@ -796,7 +901,11 @@ def name_journal(current: str, look_up: Callable[[str], dict[str, Any]] | None =
796
901
  if look_up is None and os.environ.get("SCHOOL_PROGRESS_BAR") == "0":
797
902
  return None # no card to say it on (and no lookups from the tests)
798
903
  with _LOCK:
799
- if not _STATE or _STATE.get("journal") or str(_STATE.get("current") or "") != current or not current:
904
+ paper = _window_paper()
905
+ if paper is not None:
906
+ if paper.get("journal") or str(paper.get("current") or "") != current or not current:
907
+ return None
908
+ elif not _STATE or _STATE.get("journal") or str(_STATE.get("current") or "") != current or not current:
800
909
  return None
801
910
 
802
911
  def look() -> None:
@@ -812,6 +921,13 @@ def name_journal(current: str, look_up: Callable[[str], dict[str, Any]] | None =
812
921
  if not name:
813
922
  return
814
923
  with _LOCK:
924
+ papers = _STATE.get("papers") if _STATE and isinstance(_STATE.get("papers"), dict) else {}
925
+ for paper in papers.values():
926
+ if str(paper.get("current") or "") == current and not paper.get("journal"):
927
+ paper["journal"] = name
928
+ _show()
929
+ _write_state()
930
+ return
815
931
  if _STATE and str(_STATE.get("current") or "") == current and not _STATE.get("journal"):
816
932
  _STATE["journal"] = name
817
933
  _write_state()
@@ -931,10 +1047,69 @@ def update(**kw: Any) -> None:
931
1047
  with _LOCK:
932
1048
  if not _STATE:
933
1049
  return
934
- _STATE.update(kw)
1050
+ paper = _window_paper()
1051
+ if paper is not None:
1052
+ paper.update({k: v for k, v in kw.items() if k in PAPER_KEYS})
1053
+ _STATE.update({k: v for k, v in kw.items() if k not in PAPER_KEYS})
1054
+ _show()
1055
+ else:
1056
+ _STATE.update(kw)
935
1057
  _write_state()
936
1058
 
937
1059
 
1060
+ #: A file arriving is written into the report at most this often (the window reads it twice a second).
1061
+ TRANSFER_WRITE_SEC = 0.5
1062
+
1063
+
1064
+ class Transfer:
1065
+ """One file arriving, said on the window's card (``transfer``: the PDF or a supplementary file, which of
1066
+ how many, its name, the bytes so far and in all, when it started and when bytes last came). User,
1067
+ 2026-11-26: a big file's size and how far it has come, so that a slow one is not taken for a stuck
1068
+ one. A context manager: the report forgets it when it ends (another's, started since, is kept)."""
1069
+
1070
+ def __init__(self, kind: str, size: int = 0, *, index: int = 0, count: int = 0, name: str = "") -> None:
1071
+ self.kind, self.index, self.count, self.name = kind, int(index or 0), int(count or 0), str(name or "")[:120]
1072
+ self.size = max(0, int(size or 0))
1073
+ self.done = 0
1074
+ self.started = self.at = time.time()
1075
+ self._written = 0.0
1076
+ self._id = uuid.uuid4().hex[:12]
1077
+
1078
+ def __enter__(self) -> "Transfer":
1079
+ self._write()
1080
+ return self
1081
+
1082
+ def __exit__(self, *exc: Any) -> None:
1083
+ self.close()
1084
+
1085
+ def add(self, count: int) -> None:
1086
+ """``count`` more bytes have come."""
1087
+ if count <= 0:
1088
+ return
1089
+ self.done += count
1090
+ self.at = time.time()
1091
+ if self.at - self._written >= TRANSFER_WRITE_SEC:
1092
+ self._write()
1093
+
1094
+ def _write(self) -> None:
1095
+ self._written = time.time()
1096
+ update(transfer={"id": self._id, "kind": self.kind, "index": self.index, "count": self.count,
1097
+ "name": self.name, "size": self.size, "done": self.done,
1098
+ "started": self.started, "at": self.at})
1099
+
1100
+ def close(self) -> None:
1101
+ with _LOCK:
1102
+ holder = _window_paper()
1103
+ holder = _STATE if holder is None else holder
1104
+ current = holder.get("transfer")
1105
+ if not (isinstance(current, dict) and current.get("id") == self._id):
1106
+ return
1107
+ holder["transfer"] = None
1108
+ if holder is not _STATE:
1109
+ _show()
1110
+ _write_state()
1111
+
1112
+
938
1113
  def batch_id() -> str:
939
1114
  """The caller's serial batch the current download belongs to; "" for a download on its own."""
940
1115
  with _LOCK:
@@ -945,12 +1120,15 @@ def current_part() -> str:
945
1120
  """The part of the paper the window says is being fetched ("main", "supplements",
946
1121
  "markdown"), or ""."""
947
1122
  with _LOCK:
948
- return str(_STATE.get("part") or "")
1123
+ paper = _window_paper()
1124
+ return str((_STATE if paper is None else paper).get("part") or "")
949
1125
 
950
1126
 
951
1127
  def advance(ok: bool, current: str = "", phase: str = "", *, pending: bool = False) -> None:
952
1128
  """Record one finished item (the hot path for per-paper lanes); ``pending``:
953
1129
  finished, but whether it succeeded is the caller's to count."""
1130
+ if _WINDOW.get() is not None:
1131
+ return # papers downloading at once: the batch's caller counts each (its reports)
954
1132
  with _LOCK:
955
1133
  if not _STATE:
956
1134
  return
@@ -973,9 +1151,10 @@ def has_attention(*, current: str = "", excluding: str = "") -> bool:
973
1151
 
974
1152
 
975
1153
  def set_attention(key: str, message: str, *, current: str = "", phase: str = "",
976
- deadline: float | None = None) -> None:
1154
+ deadline: float | None = None, ways: list[str] | None = None, school: str = "") -> None:
977
1155
  """Show a manual-action reminder without stopping other workers; ``deadline``
978
- (epoch seconds) is when the wait ends, for the window's countdown."""
1156
+ (epoch seconds) is when the wait ends, for the window's countdown. ``ways``: the ways a sign-in chooser
1157
+ offers, picked from in the window itself (with ``school``, whose they are; user, 2026-11-29)."""
979
1158
  with _LOCK:
980
1159
  if not _STATE:
981
1160
  return
@@ -991,6 +1170,9 @@ def set_attention(key: str, message: str, *, current: str = "", phase: str = "",
991
1170
  }
992
1171
  if deadline is not None:
993
1172
  attention[str(key)]["deadline"] = float(deadline)
1173
+ if ways:
1174
+ attention[str(key)].update(ways=[str(way) for way in ways], school=str(school or ""))
1175
+ _show() # papers downloading at once: the card shows the one asking
994
1176
  _write_state()
995
1177
 
996
1178
 
@@ -1025,6 +1207,7 @@ def clear_attention(key: str) -> None:
1025
1207
  if not isinstance(attention, dict):
1026
1208
  return
1027
1209
  attention.pop(str(key), None)
1210
+ _show()
1028
1211
  _write_state()
1029
1212
 
1030
1213
 
@@ -443,6 +443,140 @@ def _switch_note(state: dict[str, Any], now: float) -> str:
443
443
  return f"换{raw['school']}再试"
444
444
 
445
445
 
446
+ #: A file arriving is shown once it has taken this long (a small one comes and goes unshown), and said to have
447
+ #: stopped once no byte has come for this long (user, 2026-11-26).
448
+ TRANSFER_SHOWN_SEC = 3
449
+ TRANSFER_STALLED_SEC = 20
450
+
451
+
452
+ def _megabytes(count: float) -> str:
453
+ value = count / (1024 * 1024)
454
+ return f"{value:.0f}" if value >= 100 else f"{value:.1f}"
455
+
456
+
457
+ def transfer_view(raw: Any, now: float) -> dict[str, Any] | None:
458
+ """The card's row for a file arriving (progress_reporter.Transfer), or None while there is none or it is
459
+ new: what it is (PDF, or which supplementary file of how many), its share of its size (None when the site
460
+ gave none), what has come in MB, and whether it has stopped (nothing for TRANSFER_STALLED_SEC; ``said``
461
+ says so on hover). Numbers only on the card, the same in every language (user, 2026-11-26)."""
462
+ if not isinstance(raw, dict):
463
+ return None
464
+ try:
465
+ started, at = float(raw["started"]), float(raw["at"])
466
+ done, size = max(0, int(raw.get("done") or 0)), max(0, int(raw.get("size") or 0))
467
+ except (KeyError, TypeError, ValueError):
468
+ return None
469
+ if now - started < TRANSFER_SHOWN_SEC:
470
+ return None
471
+ known = 0 < size and done <= size # a compressed answer may bring more than its stated size
472
+ quiet = max(0.0, now - at)
473
+ kind = "supplement" if raw.get("kind") == "supplement" else "pdf"
474
+ index, count = _count(raw.get("index")), _count(raw.get("count"))
475
+ stalled = quiet >= TRANSFER_STALLED_SEC
476
+ return {"kind": kind, "label": "PDF" if kind == "pdf" else (f"{index}/{count}" if index and count else ""),
477
+ "share": round(100 * done / size, 1) if known else None,
478
+ "amount": f"{_megabytes(done)} / {_megabytes(size)} MB" if known else f"{_megabytes(done)} MB",
479
+ "stalled": stalled, "said": f"{int(quiet)} 秒没有新数据" if stalled else "",
480
+ "name": str(raw.get("name") or "")[:120]}
481
+
482
+
483
+ def _step(state: dict[str, Any]) -> tuple[dict[str, Any] | None, tuple[str, ...]]:
484
+ """A running paper's step on the card (None: none to show) and the steps it is among, from its part and stage."""
485
+ part_key = str(state.get("part") or "")
486
+ stage = str(state.get("stage") or "")
487
+ if part_key == "markdown":
488
+ # Its steps as a PDF's are shown, up to the page's read (it had none, 2026-11-16).
489
+ if state.get("page_reading"):
490
+ return {"index": 2, "label": "读全文网页"}, MARKDOWN_STEPS
491
+ if stage == "access_ready":
492
+ return {"index": 2, "label": "全文网页已读取"}, MARKDOWN_STEPS
493
+ if stage in STAGE_STEP and STAGE_STEP[stage][0] <= 1:
494
+ index, label = STAGE_STEP[stage]
495
+ return {"index": index, "label": label}, MARKDOWN_STEPS
496
+ return None, MARKDOWN_STEPS
497
+ if part_key == "supplements":
498
+ found = state.get("supplements_total")
499
+ label = (f"补充材料 {_count(state.get('supplements_saved'))}/{found}"
500
+ if isinstance(found, int) else "查找补充材料")
501
+ return {"index": 4, "label": label}, STEPS
502
+ if part_key == "main" and stage in STAGE_STEP:
503
+ index, label = STAGE_STEP[stage]
504
+ return {"index": index, "label": label}, STEPS
505
+ return None, STEPS
506
+
507
+
508
+ def _prompt(item: dict[str, Any], now: float, more: int) -> dict[str, Any]:
509
+ """What a reminder asks of the user, short (the capsule's words), with its countdown; ``more``: the others."""
510
+ message = str(item.get("message") or "请查看浏览器,可能需要手动操作")
511
+ # The surrounding SSO/verification stage is not evidence of the action
512
+ # being requested. In particular, an idle page is not a school login.
513
+ short = ("页面暂时无进展" if "无进展" in message or "没有进展" in message else
514
+ "请选择学校" if "选择学校" in message else
515
+ "请登录学校" if "登录" in message else
516
+ "请完成验证" if "验证" in message else "需要你处理")
517
+ if message.startswith("学校登录页只能用") and "扫码登录" in message:
518
+ app = message.split("只能用", 1)[1].split("扫码登录", 1)[0]
519
+ short = {"微信": "请用微信扫码", "企业微信": "请用企业微信扫码", "钉钉": "请用钉钉扫码"}.get(app, "请在浏览器扫码登录")
520
+ elif message == "学校登录页只能用短信验证码登录,请在浏览器窗口完成。":
521
+ short = "请用短信验证码登录"
522
+ elif message == "学校登录页需要扫码或短信验证,请在浏览器窗口完成。":
523
+ short = "请完成扫码或短信验证"
524
+ deadline = item.get("deadline")
525
+ remaining = (max(0, int(deadline - now))
526
+ if isinstance(deadline, (int, float)) and not isinstance(deadline, bool) else None)
527
+ ways = [str(way) for way in item.get("ways") or [] if str(way)]
528
+ if ways:
529
+ short = "选择登录方式" # picked in the window itself (user, 2026-11-29)
530
+ prompt = {"message": message, "short": short, "more": more,
531
+ "remaining": fmt_clock(remaining) if remaining is not None else "",
532
+ "login": short in ("请登录学校", "选择登录方式") or message.startswith("学校登录页")}
533
+ if ways:
534
+ prompt.update(ways=ways, school=str(item.get("school") or ""))
535
+ return prompt
536
+
537
+
538
+ def _notice(state: dict[str, Any], now: float) -> str:
539
+ """The download's answer to a click on this paper, for NOTICE_SECONDS."""
540
+ raw = state.get("notice")
541
+ if isinstance(raw, dict) and str(raw.get("current") or "") == str(state.get("current") or ""):
542
+ try:
543
+ if now - float(raw.get("at") or 0) < NOTICE_SECONDS:
544
+ return str(raw.get("text") or "")
545
+ except (TypeError, ValueError):
546
+ pass
547
+ return ""
548
+
549
+
550
+ def _papers(state: dict[str, Any], attention: list[dict[str, Any]], now: float) -> list[dict[str, Any]]:
551
+ """并行下载 (user, 2026-11-29): the papers downloading at once, a row each on the card from two on (one alone is
552
+ the card's own paper): its journal and title, its step, the file arriving or its line, the download's answer to a
553
+ click, and what it asks of the user (``ask``). The one asking first, the others in their windows' order, so that a
554
+ row stays where it is while its paper runs."""
555
+ raw = state.get("papers")
556
+ if not isinstance(raw, dict) or len(raw) < 2:
557
+ return []
558
+ rows = []
559
+ for window, paper in sorted(raw.items(), key=lambda item: int(item[0]) if str(item[0]).isdigit() else 0):
560
+ if not isinstance(paper, dict):
561
+ continue
562
+ current = str(paper.get("current") or "")
563
+ asking = [item for item in attention if current and str(item.get("current") or "").lower() == current.lower()]
564
+ step, steps = (None, STEPS) if asking else _step(paper)
565
+ journal, publisher = str(paper.get("journal") or ""), str(paper.get("publisher") or "")
566
+ transfer = None if asking else transfer_view(paper.get("transfer"), now)
567
+ rows.append({
568
+ "window": str(window), "current": current, "title": str(paper.get("title") or ""),
569
+ "journal": journal or publisher.removeprefix("site:") or current,
570
+ "step": step, "steps": list(steps), "transfer": transfer,
571
+ # Neither a step nor a file: what it is doing ("没权限,换××"), without the part the card's line names.
572
+ "line": "" if asking or step or transfer else str(paper.get("phase") or "")
573
+ or STAGE_TEXT.get(str(paper.get("stage") or ""), ""),
574
+ "notice": _notice(paper, now),
575
+ "ask": _prompt(asking[-1], now, len(asking) - 1) if asking else None,
576
+ })
577
+ return sorted(rows, key=lambda row: row["ask"] is None)
578
+
579
+
446
580
  def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
447
581
  """Everything the capsule shows for one snapshot of the progress file.
448
582
 
@@ -489,7 +623,9 @@ def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
489
623
  mode, tone, headline = "done", "ok", "下载完成"
490
624
 
491
625
  part_key = str(state.get("part") or "")
492
- if running and not awaiting and part_key in PARTS:
626
+ papers = _papers(state, attention, now) if running and not awaiting else []
627
+ # Papers listed: what the batch fetches, not the part one of them is at.
628
+ if running and not awaiting and part_key in PARTS and not papers:
493
629
  part = CONTENT_LABELS[part_key]
494
630
  else:
495
631
  part = content_label(str(state.get("content") or "main"), bool(state.get("markdown")))
@@ -505,58 +641,14 @@ def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
505
641
  if held_wait:
506
642
  publisher = journal = current = title = "" # the last paper is over
507
643
 
508
- step = None
509
- steps = STEPS
510
- if running and not attention and not awaiting:
511
- if part_key == "markdown":
512
- # Its steps as a PDF's are shown, up to the page's read (it had none, 2026-11-16).
513
- steps = MARKDOWN_STEPS
514
- stage = str(state.get("stage") or "")
515
- if state.get("page_reading"):
516
- step = {"index": 2, "label": "读全文网页"}
517
- elif stage == "access_ready":
518
- step = {"index": 2, "label": "全文网页已读取"}
519
- elif stage in STAGE_STEP and STAGE_STEP[stage][0] <= 1:
520
- index, label = STAGE_STEP[stage]
521
- step = {"index": index, "label": label}
522
- elif part_key == "supplements":
523
- found = state.get("supplements_total")
524
- label = (f"补充材料 {_count(state.get('supplements_saved'))}/{found}"
525
- if isinstance(found, int) else "查找补充材料")
526
- step = {"index": 4, "label": label}
527
- elif part_key == "main" and str(state.get("stage") or "") in STAGE_STEP:
528
- index, label = STAGE_STEP[str(state.get("stage"))]
529
- step = {"index": index, "label": label}
644
+ step, steps = _step(state) if running and not attention and not awaiting else (None, STEPS)
530
645
 
531
646
  started = _time(state.get("started_at"))
532
647
  ended = now if running else _time(state.get("finished_at"))
533
648
  elapsed = fmt_clock(ended - started) if started is not None and ended is not None else ""
534
649
 
535
- prompt = None
536
- if attention:
537
- item = attention[-1]
538
- message = str(item.get("message") or "请查看浏览器,可能需要手动操作")
539
- # The surrounding SSO/verification stage is not evidence of the action
540
- # being requested. In particular, an idle page is not a school login.
541
- short = ("页面暂时无进展" if "无进展" in message or "没有进展" in message else
542
- "请选择学校" if "选择学校" in message else
543
- "请登录学校" if "登录" in message else
544
- "请完成验证" if "验证" in message else "需要你处理")
545
- deadline = item.get("deadline")
546
- remaining = (max(0, int(deadline - now))
547
- if isinstance(deadline, (int, float)) and not isinstance(deadline, bool) else None)
548
- prompt = {"message": message, "short": short, "more": len(attention) - 1,
549
- "remaining": fmt_clock(remaining) if remaining is not None else "",
550
- "login": short == "请登录学校"}
551
-
552
- notice = ""
553
- raw = state.get("notice")
554
- if isinstance(raw, dict) and str(raw.get("current") or "") == str(state.get("current") or ""):
555
- try:
556
- if now - float(raw.get("at") or 0) < NOTICE_SECONDS:
557
- notice = str(raw.get("text") or "")
558
- except (TypeError, ValueError):
559
- pass
650
+ prompt = _prompt(attention[-1], now, len(attention) - 1) if attention else None
651
+ notice = _notice(state, now)
560
652
  # Held by the hourly limit the user set: the capsule and the card say so, and that
561
653
  # it is the user's setting, not the publisher's (2026-11-12).
562
654
  line = status_text(state, running) if running else ""
@@ -589,6 +681,8 @@ def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
589
681
  "title": title, "current": current,
590
682
  "run_id": str(state.get("run_id") or ""),
591
683
  "step": step, "steps": list(steps), "line": line,
684
+ "transfer": transfer_view(state.get("transfer"), now) if running and not attention and not awaiting and not hold else None,
685
+ "papers": papers,
592
686
  "elapsed": elapsed, "attention": prompt, "notice": notice, "hold": bool(hold),
593
687
  "completion_detail": str(state.get("phase") or "")
594
688
  if not running and state.get("stage") == "supplements_checked" else "",
@@ -13,6 +13,7 @@ the same article again.
13
13
  """
14
14
  from __future__ import annotations
15
15
 
16
+ import threading
16
17
  import time
17
18
  from pathlib import Path
18
19
 
@@ -20,6 +21,9 @@ from .entitlements import _data_dir, _read_json, _write_json
20
21
 
21
22
  HOUR = 3600
22
23
  DEFAULT_LIMIT = 100
24
+ #: A batch's windows open articles at once (并行下载, user 2026-11-29): the check and the count are one step under it, so
25
+ #: that a publisher's windows together stay within its limit and none of their counts is lost.
26
+ _LOCK = threading.RLock()
23
27
 
24
28
 
25
29
  def ledger_path() -> Path:
@@ -64,9 +68,28 @@ def record(key: str, now: float | None = None) -> None:
64
68
  """Count one article opened on ``key``'s site, in its hour or in a new one; hours over are dropped."""
65
69
  if not key:
66
70
  return
67
- now = time.time() if now is None else now
71
+ with _LOCK:
72
+ _record(key, time.time() if now is None else now)
73
+
74
+
75
+ def _record(key: str, now: float) -> None:
68
76
  data = _read_json(ledger_path())
69
77
  kept = {name: {"start": hour[0], "count": hour[1]} for name in data if (hour := _hour(data, name, now))}
70
78
  current = kept.get(key, {"start": now, "count": 0})
71
79
  kept[key] = {"start": current["start"], "count": current["count"] + 1}
72
80
  _write_json(ledger_path(), kept)
81
+
82
+
83
+ def take(key: str, limit: int, now: float | None = None) -> int:
84
+ """Open one more article on ``key``'s site if its hour allows: 0, and it is counted; else the seconds to wait
85
+ (``wait_seconds``), nothing counted. One step, so that windows opening articles at once never pass the limit."""
86
+ if not key:
87
+ return 0
88
+ with _LOCK:
89
+ wait = wait_seconds(key, limit) if now is None else wait_seconds(key, limit, now)
90
+ if not wait:
91
+ if now is None:
92
+ record(key)
93
+ else:
94
+ record(key, now)
95
+ return wait