papersearch 0.7.3 → 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.
- package/NOTICE +8 -37
- package/README.fr.md +265 -0
- package/README.ja.md +265 -0
- package/README.ko.md +265 -0
- package/README.md +149 -148
- package/README.zh-Hant.md +265 -0
- package/README.zh.md +265 -0
- package/dist/capabilities/download/batch/batch.d.ts +20 -1
- package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
- package/dist/capabilities/download/batch/batch.js +1057 -208
- package/dist/capabilities/download/batch/batch.js.map +1 -1
- package/dist/capabilities/download/batch/batchFolder.d.ts.map +1 -1
- package/dist/capabilities/download/batch/batchFolder.js +3 -2
- package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
- package/dist/capabilities/download/batch/networkLoss.d.ts +11 -2
- package/dist/capabilities/download/batch/networkLoss.d.ts.map +1 -1
- package/dist/capabilities/download/batch/networkLoss.js +24 -3
- package/dist/capabilities/download/batch/networkLoss.js.map +1 -1
- package/dist/capabilities/download/batch/resume.d.ts +7 -0
- package/dist/capabilities/download/batch/resume.d.ts.map +1 -1
- package/dist/capabilities/download/batch/resume.js +50 -9
- package/dist/capabilities/download/batch/resume.js.map +1 -1
- package/dist/capabilities/download/batch/windowPlan.d.ts +96 -0
- package/dist/capabilities/download/batch/windowPlan.d.ts.map +1 -0
- package/dist/capabilities/download/batch/windowPlan.js +196 -0
- package/dist/capabilities/download/batch/windowPlan.js.map +1 -0
- package/dist/capabilities/download/content/markdown/pro.d.ts +6 -0
- package/dist/capabilities/download/content/markdown/pro.d.ts.map +1 -1
- package/dist/capabilities/download/content/markdown/pro.js.map +1 -1
- package/dist/capabilities/download/content/markdown/shortfall.d.ts +8 -5
- package/dist/capabilities/download/content/markdown/shortfall.d.ts.map +1 -1
- package/dist/capabilities/download/content/markdown/shortfall.js +22 -10
- package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
- package/dist/capabilities/download/content/markdown/step.d.ts +9 -0
- package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
- package/dist/capabilities/download/content/markdown/step.js +46 -3
- package/dist/capabilities/download/content/markdown/step.js.map +1 -1
- package/dist/capabilities/download/content/markdown/types.d.ts +10 -1
- package/dist/capabilities/download/content/markdown/types.d.ts.map +1 -1
- package/dist/capabilities/download/content/pdf/open/tiers/scihub.d.ts.map +1 -1
- package/dist/capabilities/download/content/pdf/open/tiers/scihub.js +3 -1
- package/dist/capabilities/download/content/pdf/open/tiers/scihub.js.map +1 -1
- package/dist/capabilities/download/handler.d.ts.map +1 -1
- package/dist/capabilities/download/handler.js +13 -5
- package/dist/capabilities/download/handler.js.map +1 -1
- package/dist/capabilities/download/outputLayout.d.ts.map +1 -1
- package/dist/capabilities/download/outputLayout.js +3 -1
- package/dist/capabilities/download/outputLayout.js.map +1 -1
- package/dist/capabilities/download/tools.js +2 -2
- package/dist/capabilities/download/tools.js.map +1 -1
- package/dist/capabilities/download/types.d.ts +9 -1
- package/dist/capabilities/download/types.d.ts.map +1 -1
- package/dist/cli.js +3 -1
- package/dist/cli.js.map +1 -1
- package/dist/infrastructure/http/hostGate.d.ts +24 -0
- package/dist/infrastructure/http/hostGate.d.ts.map +1 -0
- package/dist/infrastructure/http/hostGate.js +72 -0
- package/dist/infrastructure/http/hostGate.js.map +1 -0
- package/dist/infrastructure/pdf/PdfDownload.d.ts +1 -0
- package/dist/infrastructure/pdf/PdfDownload.d.ts.map +1 -1
- package/dist/infrastructure/pdf/PdfDownload.js +6 -1
- package/dist/infrastructure/pdf/PdfDownload.js.map +1 -1
- package/dist/infrastructure/runlog/RunLedger.d.ts +14 -0
- package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
- package/dist/infrastructure/runlog/RunLedger.js +30 -4
- package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
- package/dist/infrastructure/runlog/failureClass.d.ts +2 -1
- package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
- package/dist/infrastructure/runlog/failureClass.js +27 -4
- package/dist/infrastructure/runlog/failureClass.js.map +1 -1
- package/dist/infrastructure/school/SchoolAttempt.d.ts +11 -0
- package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
- package/dist/infrastructure/school/SchoolAttempt.js +48 -5
- package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
- package/dist/infrastructure/school/SchoolMcpClient.d.ts +13 -2
- package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
- package/dist/infrastructure/school/SchoolMcpClient.js +138 -15
- package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
- package/dist/infrastructure/school/SchoolProgress.d.ts +2 -0
- package/dist/infrastructure/school/SchoolProgress.d.ts.map +1 -1
- package/dist/infrastructure/school/SchoolProgress.js +2 -0
- package/dist/infrastructure/school/SchoolProgress.js.map +1 -1
- package/dist/infrastructure/school/SchoolReadiness.d.ts +9 -0
- package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
- package/dist/infrastructure/school/SchoolReadiness.js +10 -0
- package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
- package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
- package/dist/infrastructure/school/SchoolResultNormalizer.js +4 -0
- package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
- package/dist/infrastructure/school/index.d.ts +2 -2
- package/dist/infrastructure/school/index.d.ts.map +1 -1
- package/dist/infrastructure/school/index.js +1 -1
- package/dist/infrastructure/school/index.js.map +1 -1
- package/dist/infrastructure/school/types.d.ts +73 -1
- package/dist/infrastructure/school/types.d.ts.map +1 -1
- package/dist/infrastructure/school/types.js.map +1 -1
- package/dist/infrastructure/security/SecurityUtils.d.ts.map +1 -1
- package/dist/infrastructure/security/SecurityUtils.js +6 -2
- package/dist/infrastructure/security/SecurityUtils.js.map +1 -1
- package/dist/management/failures/index.d.ts +23 -0
- package/dist/management/failures/index.d.ts.map +1 -1
- package/dist/management/failures/index.js +68 -20
- package/dist/management/failures/index.js.map +1 -1
- package/dist/management/school/autoUpdate.d.ts.map +1 -1
- package/dist/management/school/autoUpdate.js +9 -1
- package/dist/management/school/autoUpdate.js.map +1 -1
- package/dist/management/school/cliProgress.d.ts.map +1 -1
- package/dist/management/school/cliProgress.js +3 -1
- package/dist/management/school/cliProgress.js.map +1 -1
- package/package.json +8 -3
- package/school/NOTICE +3 -2
- package/school/paper_search_school/adapters/__init__.py +2 -0
- package/school/paper_search_school/adapters/aps/__init__.py +3 -6
- package/school/paper_search_school/adapters/base.py +19 -2
- package/school/paper_search_school/adapters/copernicus/__init__.py +2 -7
- package/school/paper_search_school/adapters/elsevier/__init__.py +50 -1
- package/school/paper_search_school/adapters/frontiers/__init__.py +41 -2
- package/school/paper_search_school/adapters/ieee/__init__.py +6 -4
- package/school/paper_search_school/adapters/iop/__init__.py +8 -0
- package/school/paper_search_school/adapters/jama/__init__.py +8 -0
- package/school/paper_search_school/adapters/lww/__init__.py +14 -6
- package/school/paper_search_school/adapters/mdpi/__init__.py +12 -7
- package/school/paper_search_school/adapters/neurology/__init__.py +5 -2
- package/school/paper_search_school/adapters/optica/__init__.py +52 -13
- package/school/paper_search_school/adapters/oup/__init__.py +7 -4
- package/school/paper_search_school/adapters/platforms/__init__.py +4 -1
- package/school/paper_search_school/adapters/platforms/atypon/__init__.py +12 -3
- package/school/paper_search_school/adapters/platforms/figshare/__init__.py +23 -4
- package/school/paper_search_school/adapters/platforms/jstage/__init__.py +64 -0
- package/school/paper_search_school/adapters/taylor_francis/__init__.py +0 -3
- package/school/paper_search_school/adapters/thieme/__init__.py +2 -9
- package/school/paper_search_school/api_keys.py +63 -13
- package/school/paper_search_school/assets/api_keys.json +14 -0
- package/school/paper_search_school/assets/capsule.html +526 -147
- package/school/paper_search_school/assets/capsule_en.json +140 -49
- package/school/paper_search_school/assets/capsule_fr.json +141 -50
- package/school/paper_search_school/assets/capsule_ja.json +140 -49
- package/school/paper_search_school/assets/capsule_ko.json +140 -49
- package/school/paper_search_school/assets/capsule_zh-Hant.json +134 -48
- package/school/paper_search_school/browser/backend.py +125 -4
- package/school/paper_search_school/browser/batch_session.py +189 -8
- package/school/paper_search_school/browser/challenge/__init__.py +12 -9
- package/school/paper_search_school/browser/challenge/continuation.py +83 -0
- package/school/paper_search_school/browser/challenge/handlers/__init__.py +1 -0
- package/school/paper_search_school/browser/challenge/handlers/aws_waf.py +260 -0
- package/school/paper_search_school/browser/challenge/handlers/recaptcha_hcaptcha.py +167 -0
- package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +128 -0
- package/school/paper_search_school/browser/challenge/handlers/turnstile.py +174 -0
- package/school/paper_search_school/browser/challenge/kinds.py +203 -0
- package/school/paper_search_school/browser/challenge/local/__init__.py +1 -0
- package/school/paper_search_school/browser/challenge/{interaction.py → local/interaction.py} +94 -13
- package/school/paper_search_school/browser/challenge/{pointer.py → local/pointer.py} +2 -2
- package/school/paper_search_school/browser/challenge/local/prompt.py +283 -0
- package/school/paper_search_school/browser/challenge/local/submission.py +33 -0
- package/school/paper_search_school/browser/challenge/pro.py +24 -0
- package/school/paper_search_school/browser/challenge/services/__init__.py +1 -0
- package/school/paper_search_school/browser/challenge/services/solver.py +292 -0
- package/school/paper_search_school/browser/engine.py +4 -1
- package/school/paper_search_school/browser/user_turn.py +126 -0
- package/school/paper_search_school/browser/watchdog.py +213 -60
- package/school/paper_search_school/cli_config.py +10 -5
- package/school/paper_search_school/config.py +16 -10
- package/school/paper_search_school/download_diagnostics.py +7 -2
- package/school/paper_search_school/engine/access_rules.py +12 -3
- package/school/paper_search_school/engine/batch.py +52 -18
- package/school/paper_search_school/engine/batch_access.py +62 -16
- package/school/paper_search_school/engine/batch_capture.py +260 -31
- package/school/paper_search_school/engine/batch_common.py +3 -0
- package/school/paper_search_school/engine/batch_diagnostics.py +25 -5
- package/school/paper_search_school/engine/batch_institution.py +52 -3
- package/school/paper_search_school/engine/batch_login.py +398 -36
- package/school/paper_search_school/engine/batch_pdf_urls.py +38 -7
- package/school/paper_search_school/engine/batch_user.py +48 -3
- package/school/paper_search_school/engine/batch_waits.py +221 -14
- package/school/paper_search_school/engine/bridge.py +29 -6
- package/school/paper_search_school/engine/fulltext_page.py +55 -8
- package/school/paper_search_school/engine/router.py +16 -1
- package/school/paper_search_school/engine/supplements.py +7 -1
- package/school/paper_search_school/entitlements.py +29 -1
- package/school/paper_search_school/pdf_utils.py +25 -16
- package/school/paper_search_school/progress_capsule.py +69 -11
- package/school/paper_search_school/progress_reporter.py +243 -11
- package/school/paper_search_school/progress_view.py +205 -91
- package/school/paper_search_school/publishers/builtin/iop.json +2 -1
- package/school/paper_search_school/publishers/builtin/neurology.json +4 -2
- package/school/paper_search_school/publishers/site.py +12 -4
- package/school/paper_search_school/rate_limit.py +24 -1
- package/school/paper_search_school/school_login.py +170 -8
- package/school/paper_search_school/school_test.py +1 -1
- package/school/paper_search_school/server.py +179 -23
- package/school/paper_search_school/user_settings.py +46 -4
- package/school/pyproject.toml +1 -0
- package/skills/paper-search/SKILL.md +107 -107
- package/skills/paper-search/references/browser-download.md +102 -99
- package/skills/paper-search/references/capability-routing.md +89 -89
- package/skills/paper-search/references/cli-contract.md +78 -78
- package/skills/paper-search/references/federation-support.md +172 -172
- package/skills/paper-search/references/management-layer.md +78 -78
- package/skills/paper-search/references/publisher-support.md +38 -38
- package/skills/paper-search/references/school-setup.md +56 -55
- package/skills/paper-search/references/setup.md +20 -20
- package/skills/paper-search/references/troubleshooting.md +12 -12
- package/README.en.md +0 -264
- package/school/paper_search_school/browser/challenge/prompt.py +0 -154
|
@@ -3,20 +3,23 @@ import { randomUUID } from "node:crypto";
|
|
|
3
3
|
import { RunLedger } from "../../../infrastructure/runlog/RunLedger.js";
|
|
4
4
|
import { classifyFailureCode, FAILURE_CLASS_NAMES, } from "../../../infrastructure/runlog/failureClass.js";
|
|
5
5
|
import { createDefaultDownloadTiers, downloadWithFallback, } from "../content/pdf/OpenAccessFallbackService.js";
|
|
6
|
-
import { schoolAttemptDetails, schoolShortReason } from "../../../infrastructure/school/index.js";
|
|
6
|
+
import { blockedBySite, schoolAttemptDetails, schoolShortReason } from "../../../infrastructure/school/index.js";
|
|
7
7
|
import { journalOfDoi, takeNext } from "./journalKey.js";
|
|
8
8
|
import { downloadSupplementsOnly, filesPastNetworkLoss } from "../content/supplements/fetch.js";
|
|
9
9
|
import { supplementShortfall } from "../content/supplements/shortfall.js";
|
|
10
10
|
import { fulltextPageVisit } from "../content/markdown/pageVisit.js";
|
|
11
|
-
import { fulltextAlone, fulltextForItem, markdownBeside, markdownPastNetworkLoss } from "../content/markdown/step.js";
|
|
11
|
+
import { figuresMissing, figuresOnceMore, fulltextAlone, fulltextForItem, markdownBeside, markdownPastNetworkLoss } from "../content/markdown/step.js";
|
|
12
12
|
import { markdownDoubt, markdownMissing } from "../content/markdown/shortfall.js";
|
|
13
13
|
import { batchPaper, failure, reportBatchResults, stoppedItem } from "./batchSummary.js";
|
|
14
14
|
import { loadMarkdownPro, markdownBlocked } from "../content/markdown/pro.js";
|
|
15
15
|
import { PaperList } from "./batchPapers.js";
|
|
16
16
|
import { networkReachable, pastNetworkLoss } from "./networkLoss.js";
|
|
17
17
|
import { openBatchFolder } from "./batchFolder.js";
|
|
18
|
+
import { isParallel, publisherKey, WindowPlan } from "./windowPlan.js";
|
|
18
19
|
/** From this many items the progress window opens at the start, in the open-access stretch. */
|
|
19
20
|
export const OPEN_PROGRESS_MIN_ITEMS = 5;
|
|
21
|
+
/** The open-access lane's papers checked at once (user, 2026-11-29: fixed, not a setting). */
|
|
22
|
+
export const OPEN_AT_ONCE = 3;
|
|
20
23
|
/** Every source that needs no browser: open access, publisher APIs, Sci-Hub when on (the guide's 开放下载). */
|
|
21
24
|
const OPEN_CHANNEL = "开放下载";
|
|
22
25
|
/**
|
|
@@ -85,6 +88,23 @@ const SCHOOL_SIGN_IN_PAGE = "school_login";
|
|
|
85
88
|
/** How often a batch waiting for the user to go on with held publishers asks its window. */
|
|
86
89
|
const HOLD_POLL_MS = 3_000;
|
|
87
90
|
const HOLD_WAIT_PHASE = "其他篇目已完成,等你回来点“登录并继续”";
|
|
91
|
+
/**
|
|
92
|
+
* How long a publisher's papers wait after its site blocked one of them (被网站拦截: its human verification not passed,
|
|
93
|
+
* its block page): the batch goes on with the other publishers meanwhile, then tries them once more (user, 2026-11-23).
|
|
94
|
+
* Ten minutes: JAMA's first block in the publisher sweep had cleared within five (the re-check interval the user set for
|
|
95
|
+
* a blocked journal, 2026-11-16), its second held for the 47 minutes the batch went on hitting it; with one retry only,
|
|
96
|
+
* twice that interval. Shorter than the half hour after which a publisher's school session lapsed unused (Wiley,
|
|
97
|
+
* 2026-11-12), so nothing is loaded from the blocking site to keep it.
|
|
98
|
+
*/
|
|
99
|
+
export const BLOCKED_PAUSE_MS = 10 * 60_000;
|
|
100
|
+
/**
|
|
101
|
+
* Without 失败后自动重试: a publisher's papers its site blocks in a row before its others are given up for the batch
|
|
102
|
+
* (user, 2026-11-24: Wiley's one verification not passed, paper 85, gave its other 40 up untried). Each one blocked
|
|
103
|
+
* fails on its own; one not blocked starts the count again.
|
|
104
|
+
*/
|
|
105
|
+
export const BLOCKED_IN_ROW = 3;
|
|
106
|
+
/** A time of day as the batch's lines say it ("01:05"). */
|
|
107
|
+
const clockTime = (at) => new Date(at).toTimeString().slice(0, 5);
|
|
88
108
|
const AWAY_NOTICE = "[批量] 这一篇等你登录或验证已到时限;后面的篇目遇到登录或验证只等 60 秒,你在登录页开始输入就照常等";
|
|
89
109
|
/**
|
|
90
110
|
* Entitled access waited on the user (school login, verification) until its
|
|
@@ -93,7 +113,7 @@ const AWAY_NOTICE = "[批量] 这一篇等你登录或验证已到时限;后
|
|
|
93
113
|
function waitedOutOnUser(result) {
|
|
94
114
|
return (result.status !== "ok" &&
|
|
95
115
|
result.attempts.some((attempt) => attempt.stage === "entitled_access" &&
|
|
96
|
-
(attempt.code === "login_timeout" || attempt.code === "download_timeout")));
|
|
116
|
+
(attempt.code === "login_timeout" || attempt.code === "download_timeout" || attempt.code === "captcha_required")));
|
|
97
117
|
}
|
|
98
118
|
/**
|
|
99
119
|
* The seconds the backend asked this article to wait, and whose limit it is: the publisher's
|
|
@@ -118,6 +138,8 @@ export const KEEP_SESSION_EVERY_MS = 10 * 60_000;
|
|
|
118
138
|
* 2026-11-19). Each ask reads the backend's settings and count only.
|
|
119
139
|
*/
|
|
120
140
|
export const HOURLY_RECHECK_EVERY_MS = 10_000;
|
|
141
|
+
/** How often a batch's first paper, starting the backend, has the batch ask it for 同时下载 (并行下载). */
|
|
142
|
+
export const PARALLEL_ASK_EVERY_MS = 1_000;
|
|
121
143
|
/**
|
|
122
144
|
* Runs the item again after each wait the publisher's hourly limit asks for. During a
|
|
123
145
|
* wait, the backend's keepSession runs every KEEP_SESSION_EVERY_MS.
|
|
@@ -203,6 +225,47 @@ function withoutAccess(result) {
|
|
|
203
225
|
const school = [...result.attempts].reverse().find((attempt) => attempt.stage === "entitled_access");
|
|
204
226
|
return school?.status === "error" && classifyFailureCode(school.code) === "no_access";
|
|
205
227
|
}
|
|
228
|
+
/** 没权限 for a paper's Markdown: the school's own reasons for no page (no route, refused, not enabled), or a page showing no access. */
|
|
229
|
+
function markdownWithoutAccess(result) {
|
|
230
|
+
return !!result?.markdown && result.markdown.status !== "ok" && markdownMissing(result.markdown).cls === "no_access";
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* 没权限 for a paper's supplementary files: none saved, the visit for them refused for the school (it fails for the page,
|
|
234
|
+
* not file by file; a list with some saved is kept as it is).
|
|
235
|
+
*/
|
|
236
|
+
function filesWithoutAccess(result) {
|
|
237
|
+
const files = result?.supplements ?? [];
|
|
238
|
+
return files.some((file) => classifyFailureCode(file.reason) === "no_access") && !files.some((file) => file.status === "saved");
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* A paper whose PDF stands (open access, Sci-Hub) still lacking its Markdown or supplementary files under 没权限: another
|
|
242
|
+
* saved school may have them, and the batch's end asks it for those alone, the PDF not downloaded again (user,
|
|
243
|
+
* 2026-11-29: five SAGE papers' PDFs from Sci-Hub, their Markdown 出版社没开通本校 with the default school, never tried
|
|
244
|
+
* with the two others saved). ``saved``: no PDF in the batch (the Markdown or the files alone), whatever its status.
|
|
245
|
+
*/
|
|
246
|
+
function partsWithoutAccess(result, saved = result?.status === "ok") {
|
|
247
|
+
return !!result && saved && !stoppedByUser(result) && (markdownWithoutAccess(result) || filesWithoutAccess(result));
|
|
248
|
+
}
|
|
249
|
+
/** What ``partsAgain`` asks for, as the log says it. */
|
|
250
|
+
function partsNamed(result) {
|
|
251
|
+
const files = filesWithoutAccess(result);
|
|
252
|
+
const markdown = markdownWithoutAccess(result);
|
|
253
|
+
return files && markdown ? "补充材料和 Markdown" : files ? "补充材料" : "Markdown";
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* A saved paper's supplementary files and Markdown that lacked access, asked for again with ``request``'s school, its PDF
|
|
257
|
+
* standing: the files' visit reads the page for the Markdown too when that is wanted again, as a paper's first visit
|
|
258
|
+
* does (``finishOpenItem``); else the Markdown's own visit (``visit``).
|
|
259
|
+
*/
|
|
260
|
+
async function partsAgain(item, request, backend, searchers, visit, watch) {
|
|
261
|
+
const markdown = markdownWithoutAccess(item);
|
|
262
|
+
if (filesWithoutAccess(item)) {
|
|
263
|
+
delete item.supplements;
|
|
264
|
+
await filesPastNetworkLoss(item, { ...request, fulltext: markdown && request.fulltext }, backend, searchers, watch);
|
|
265
|
+
}
|
|
266
|
+
if (markdown && !stoppedByUser(item))
|
|
267
|
+
await markdownPastNetworkLoss(item, request, searchers, visit, watch);
|
|
268
|
+
}
|
|
206
269
|
/**
|
|
207
270
|
* 原因不明 (FailureClass unexplained) at the school's stage: tried once more at the batch's end, with the school it had,
|
|
208
271
|
* before any other school (user, 2026-11-22: "原因不明的也最后再试一次"); not a paper the user stopped.
|
|
@@ -213,24 +276,50 @@ function unexplainedFailure(result) {
|
|
|
213
276
|
const school = [...result.attempts].reverse().find((attempt) => attempt.stage === "entitled_access");
|
|
214
277
|
return school?.status === "error" && classifyFailureCode(school.code) === "unexplained";
|
|
215
278
|
}
|
|
279
|
+
/**
|
|
280
|
+
* 被网站拦截 at the school's stage (blockedBySite): the publisher's site blocked the network or its human verification was
|
|
281
|
+
* not passed. Its publisher's papers wait (``BLOCKED_PAUSE_MS``); none goes to the end's retry or other schools.
|
|
282
|
+
*/
|
|
283
|
+
function siteBlocked(result) {
|
|
284
|
+
if (!result || result.status === "ok" || stoppedByUser(result))
|
|
285
|
+
return false;
|
|
286
|
+
const school = [...result.attempts].reverse().find((attempt) => attempt.stage === "entitled_access");
|
|
287
|
+
return school?.status === "error" && blockedBySite(school.code);
|
|
288
|
+
}
|
|
216
289
|
/** The other saved schools a batch's papers without access go to at its end: none for a batch given its school. */
|
|
217
290
|
async function schoolsAfterDefault(backend, options) {
|
|
218
291
|
if (options.school?.trim() || !backend?.schoolSwitch)
|
|
219
292
|
return [];
|
|
220
293
|
return (await backend.schoolSwitch().catch(() => undefined))?.schools.slice(1) ?? [];
|
|
221
294
|
}
|
|
295
|
+
/**
|
|
296
|
+
* 失败后自动重试 (the settings' 等待和提醒 page; user, 2026-11-24: off by default, whoever wants it turns it on): 原因不明
|
|
297
|
+
* tried once more at the batch's end, a publisher whose site blocked it paused and tried once more after BLOCKED_PAUSE_MS.
|
|
298
|
+
* Off, or a backend that does not say: 原因不明 fails at once, and a blocking site's publisher is given up for the batch
|
|
299
|
+
* (接着下 goes on with it). Neither 没权限时换下一所学校 (its own switch) nor a lapsed school login (登录并继续) is one.
|
|
300
|
+
*/
|
|
301
|
+
async function retrySetting(backend) {
|
|
302
|
+
if (!backend?.schoolSwitch)
|
|
303
|
+
return false;
|
|
304
|
+
return (await backend.schoolSwitch().catch(() => undefined))?.retry === true;
|
|
305
|
+
}
|
|
222
306
|
/**
|
|
223
307
|
* 没权限时换下一所学校 at a batch's end (PaperSearch Pro; user, 2026-11-22): the papers still without access go to each
|
|
224
308
|
* other saved school in turn, all of them with one before the next, so that the school's login is switched once, not at
|
|
225
309
|
* every paper (switching to and fro had a school's login ask for a picture code, Windows 2026-11-22). ``visit`` tries
|
|
226
310
|
* one paper with a school.
|
|
227
311
|
*/
|
|
228
|
-
async function laterSchools(schools, waiting, announce, visit, stopped) {
|
|
312
|
+
async function laterSchools(schools, waiting, announce, visit, stopped, together) {
|
|
229
313
|
for (const school of schools) {
|
|
230
314
|
const offsets = waiting();
|
|
231
315
|
if (!offsets.length || stopped())
|
|
232
316
|
return;
|
|
233
317
|
await announce(school, offsets.length);
|
|
318
|
+
// A batch whose papers ran at once: a school's papers in its windows (``together``).
|
|
319
|
+
if (together) {
|
|
320
|
+
await together(offsets, (offset, lane) => visit(offset, school, lane));
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
234
323
|
for (const offset of offsets) {
|
|
235
324
|
if (stopped())
|
|
236
325
|
return;
|
|
@@ -280,6 +369,21 @@ function recorded(request, ledger, item) {
|
|
|
280
369
|
? { ...request, onStage: (record) => ledger.stage(item, record), recordsDir: ledger.records, diagnosticsDir: ledger.diagnostics }
|
|
281
370
|
: request;
|
|
282
371
|
}
|
|
372
|
+
/**
|
|
373
|
+
* A batch's end (user, 2026-11-23): the papers whose Markdown was saved without figures that did not download get
|
|
374
|
+
* those figures once more (figuresOnceMore); still missing, the Markdown stays saved with them marked in it. Each
|
|
375
|
+
* paper's record waits for this, to say how it ended.
|
|
376
|
+
*/
|
|
377
|
+
async function figuresAtTheEnd(papers, log, ledger) {
|
|
378
|
+
if (!papers.length)
|
|
379
|
+
return;
|
|
380
|
+
log(`[批量] Markdown 缺图的 ${papers.length} 篇再取一次图片`);
|
|
381
|
+
ledger?.phase(`Markdown 缺图的 ${papers.length} 篇再取一次图片`);
|
|
382
|
+
for (const { result, request } of papers)
|
|
383
|
+
await figuresOnceMore(result, request);
|
|
384
|
+
const still = papers.filter(({ result }) => figuresMissing(result)).length;
|
|
385
|
+
log(`[批量] 再取图片:${papers.length - still} 篇补齐` + (still ? `,${still} 篇仍缺图(Markdown 已保存,缺的图在文中标明)` : ""));
|
|
386
|
+
}
|
|
283
387
|
function openLedger(mode, batchId, options, log) {
|
|
284
388
|
const ledger = RunLedger.open({
|
|
285
389
|
kind: "download_batch",
|
|
@@ -330,7 +434,7 @@ function summary(mode, batchId, items, extra = {}) {
|
|
|
330
434
|
};
|
|
331
435
|
}
|
|
332
436
|
/** Download a list serially; one batch id ties it to one progress window. */
|
|
333
|
-
export async function downloadBatch(searchers, options, backend, log = (line) => process.stderr.write(`${line}\n`), createTiers = createDefaultDownloadTiers, pause = wait, online = networkReachable) {
|
|
437
|
+
export async function downloadBatch(searchers, options, backend, log = (line) => process.stderr.write(`${line}\n`), createTiers = createDefaultDownloadTiers, pause = wait, online = networkReachable, now = Date.now) {
|
|
334
438
|
options = { ...options, savePath: resolveDownloadPath(options.savePath) };
|
|
335
439
|
// The batch's own folder keeps its records beside its papers (user, 2026-11-17).
|
|
336
440
|
const { folderRecord: _given, ...asked } = options;
|
|
@@ -369,7 +473,7 @@ export async function downloadBatch(searchers, options, backend, log = (line) =>
|
|
|
369
473
|
? downloadSerialBatch(options, backend, log, searchers, createTiers, pause, online)
|
|
370
474
|
: options.mode === "per_item"
|
|
371
475
|
? downloadPerItem(searchers, options, backend, log, createTiers, pause, online)
|
|
372
|
-
: downloadTwoPhase(searchers, options, backend, log, createTiers, options.mode === "entitled_only" ? "entitled_only" : "two_phase", pause, online));
|
|
476
|
+
: downloadTwoPhase(searchers, options, backend, log, createTiers, options.mode === "entitled_only" ? "entitled_only" : "two_phase", pause, online, now));
|
|
373
477
|
await reportBatchResults(result, backend, startedAt, options.savePath);
|
|
374
478
|
return result;
|
|
375
479
|
};
|
|
@@ -432,8 +536,8 @@ export async function downloadBatch(searchers, options, backend, log = (line) =>
|
|
|
432
536
|
(missed ? `。附录未下全 ${missed} 篇:${[...shortfalls].map(([reason, n]) => `${reason} ${n}`).join("、")}` : "") +
|
|
433
537
|
(incomplete ? `。Markdown 未生成 ${incomplete} 篇:${[...noMarkdown].map(([reason, n]) => `${reason} ${n}`).join("、")}` : "") +
|
|
434
538
|
(doubtful ? `。Markdown 可能不全 ${doubtful} 篇(已保存,请核对):${[...doubts].map(([reason, n]) => `${reason} ${n}`).join("、")}` : ""));
|
|
435
|
-
// What is left goes on later with one word (user, 2026-11-15).
|
|
436
|
-
if ((result.failed || missed || incomplete) && result.runLog) {
|
|
539
|
+
// What is left goes on later with one word (user, 2026-11-15): a Markdown's missing figures too.
|
|
540
|
+
if ((result.failed || missed || incomplete || result.items.some(figuresMissing)) && result.runLog) {
|
|
437
541
|
log("[批量] 没下全的篇目:回来后对 AI 说“接着下”即可补(download_batch 的 resume: \"latest\",同一套环境变量)");
|
|
438
542
|
}
|
|
439
543
|
folderRecord?.refresh();
|
|
@@ -458,48 +562,91 @@ async function downloadSerialBatch(options, backend, log, searchers, createTiers
|
|
|
458
562
|
let succeeded = 0;
|
|
459
563
|
let failed = 0;
|
|
460
564
|
let away = false;
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
565
|
+
/** Papers whose Markdown lacks figures, recorded after their second try at the end (figuresAtTheEnd). */
|
|
566
|
+
const figuresLater = [];
|
|
567
|
+
let stopped = false;
|
|
568
|
+
// 没权限时换下一所学校 (PaperSearch Pro): papers whose Markdown or files lacked access wait for the other saved schools,
|
|
569
|
+
// tried at the end for those alone, one school at a time (``laterSchools``; user, 2026-11-29: the Markdown's 没权限
|
|
570
|
+
// said so and none was tried).
|
|
571
|
+
let turns;
|
|
572
|
+
const otherSchools = () => (turns ??= schoolsAfterDefault(backend, options));
|
|
573
|
+
const waiting = new Map();
|
|
574
|
+
const later = () => ({ noAccess: waiting.size, unexplained: 0, blocked: 0, login: 0,
|
|
575
|
+
papers: { noAccess: [...waiting.values()].map(({ request }) => request.doi ?? "").filter(Boolean), unexplained: [], blocked: [],
|
|
576
|
+
login: [] } });
|
|
577
|
+
/**
|
|
578
|
+
* A paper's files, its Markdown or both, with ``request``'s school. ``before``: what it had, at the batch's end with
|
|
579
|
+
* another school; only what lacked access is asked for again, the rest kept.
|
|
580
|
+
*/
|
|
581
|
+
const fetchOnce = async (item, request, entry, before) => {
|
|
466
582
|
// 接着下 (resume.ts): a paper whose PDF a batch saved before gets its Markdown beside it, not the PDF again.
|
|
467
|
-
// Done again after a network loss, from what was there before it (``
|
|
468
|
-
const markdown = (
|
|
469
|
-
const
|
|
583
|
+
// Done again after a network loss, from what was there before it (``from`` copied each time).
|
|
584
|
+
const markdown = (from) => pastNetworkLoss(() => {
|
|
585
|
+
const copy = { ...from, attempts: [...from.attempts] };
|
|
470
586
|
return item.mainPath
|
|
471
|
-
? markdownBeside(
|
|
472
|
-
: fulltextAlone(
|
|
587
|
+
? markdownBeside(copy, item.mainPath, recorded(request, ledger, entry), searchers, pageVisit(backend, request, log, pause))
|
|
588
|
+
: fulltextAlone(copy, recorded(request, ledger, entry), searchers, pageVisit(backend, request, log, pause));
|
|
473
589
|
}, watch);
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
590
|
+
if (content === "markdown")
|
|
591
|
+
return markdown(before ?? { status: "error", attempts: [] });
|
|
592
|
+
const markdownAgain = !before || markdownWithoutAccess(before);
|
|
593
|
+
let result = before ?? { status: "error", attempts: [] };
|
|
594
|
+
if (!before || filesWithoutAccess(before)) {
|
|
595
|
+
// The files' visit reads the page for the Markdown too, when that is asked for again.
|
|
596
|
+
const files = await pastNetworkLoss(() => downloadSupplementsOnly(recorded({ ...request, ...(markdownAgain ? {} : { fulltext: false }) }, ledger, entry), backend, searchers, item.mainPath), watch);
|
|
597
|
+
result = before ? { ...files, attempts: [...before.attempts, ...files.attempts], ...(before.markdown ? { markdown: before.markdown } : {}) }
|
|
598
|
+
: files;
|
|
482
599
|
}
|
|
483
|
-
if (
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
600
|
+
if (options.fulltext && markdownAgain && !stoppedByUser(result))
|
|
601
|
+
result = await markdown(result);
|
|
602
|
+
return result;
|
|
603
|
+
};
|
|
604
|
+
/** A paper finished: counted, shown, recorded (its figures once more at the end first). */
|
|
605
|
+
const finish = async (offset, entry, request, result) => {
|
|
606
|
+
const item = options.items[offset];
|
|
607
|
+
const done = succeeded + failed;
|
|
608
|
+
// The window's end when the last paper is finished, not the last in the list (some wait for the end).
|
|
609
|
+
await reportBatchItem({ ...request, batch: { id: batchId, index: done + 1, total, done, succeeded, failed } }, result, backend);
|
|
488
610
|
if (result.status === "ok")
|
|
489
611
|
succeeded += 1;
|
|
490
612
|
else
|
|
491
613
|
failed += 1;
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
614
|
+
items[offset] = itemResult(result, offset + 1, request);
|
|
615
|
+
if (figuresMissing(result))
|
|
616
|
+
figuresLater.push({ offset, entry, request, ...(item.mainPath ? { mainPath: item.mainPath } : {}) });
|
|
617
|
+
else
|
|
618
|
+
ledger?.item(entry, result);
|
|
619
|
+
papers.set(offset, batchPaper(request, items[offset], undefined, content, item.mainPath));
|
|
620
|
+
};
|
|
621
|
+
for (const [offset, item] of options.items.entries()) {
|
|
622
|
+
// Papers waiting for the end are not done yet: the counts are of those finished.
|
|
623
|
+
const batch = { id: batchId, index: offset + 1, total, done: succeeded + failed, succeeded, failed };
|
|
624
|
+
const request = { ...itemOptions(item, options), batch, ...(away ? { shortUserWait: true } : {}) };
|
|
625
|
+
const entry = runItem(offset + 1, request);
|
|
626
|
+
log(`[批量] ${content === "markdown" ? "Markdown" : options.fulltext ? "补充材料和 Markdown" : "补充材料"} ${offset + 1}/${total}:${request.doi || request.paperId}`);
|
|
627
|
+
const result = await fetchOnce(item, request, entry);
|
|
628
|
+
if (!away && waitedOutOnUser(result)) {
|
|
629
|
+
away = true;
|
|
630
|
+
log(AWAY_NOTICE);
|
|
631
|
+
}
|
|
632
|
+
if (partsWithoutAccess(result, true) && (await otherSchools()).length) {
|
|
633
|
+
// Not finished: it waits for the other schools at the end.
|
|
634
|
+
items[offset] = itemResult(result, offset + 1, request);
|
|
635
|
+
waiting.set(offset, { entry, request });
|
|
636
|
+
papers.set(offset, batchPaper(request, items[offset], "school", content, item.mainPath));
|
|
637
|
+
await papers.send();
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
await finish(offset, entry, request, result);
|
|
495
641
|
if (stoppedByUser(result)) {
|
|
642
|
+
stopped = true;
|
|
496
643
|
for (const [rest, item] of options.items.entries()) {
|
|
497
644
|
if (rest <= offset)
|
|
498
645
|
continue;
|
|
499
646
|
const request = itemOptions(item, options);
|
|
500
647
|
const skipped = itemResult({ status: "error", attempts: [notReached()],
|
|
501
648
|
...(content === "supplements" ? { supplements: [{ status: "skipped", label: "", reason: "batch_stopped" }] } : {}) }, rest + 1, request);
|
|
502
|
-
items
|
|
649
|
+
items[rest] = skipped;
|
|
503
650
|
ledger?.item(runItem(rest + 1, request), skipped);
|
|
504
651
|
papers.set(rest, batchPaper(request, skipped, undefined, content, item.mainPath));
|
|
505
652
|
}
|
|
@@ -508,6 +655,43 @@ async function downloadSerialBatch(options, backend, log, searchers, createTiers
|
|
|
508
655
|
}
|
|
509
656
|
await papers.send();
|
|
510
657
|
}
|
|
658
|
+
// The papers whose Markdown or files lacked access go to the other saved schools, one school at a time.
|
|
659
|
+
if (waiting.size && !stopped) {
|
|
660
|
+
await laterSchools(await otherSchools(), () => [...waiting.keys()], async (school, count) => {
|
|
661
|
+
log(`[批量] 没权限的 ${count} 篇换${school.name}再试`);
|
|
662
|
+
ledger?.phase(`没权限的 ${count} 篇换${school.name}再试`);
|
|
663
|
+
await backend?.reportBatchProgress?.({ id: batchId, total, done: succeeded + failed, succeeded, failed, current: "",
|
|
664
|
+
finished: false, switchTo: school.name, laterOnly: true, later: later() }).catch(() => false);
|
|
665
|
+
}, async (offset, school) => {
|
|
666
|
+
const { entry } = waiting.get(offset);
|
|
667
|
+
const item = options.items[offset];
|
|
668
|
+
const batch = { id: batchId, index: offset + 1, total, done: succeeded + failed, succeeded, failed };
|
|
669
|
+
const request = { ...itemOptions(item, options), school: school.entityId, batch, ...(away ? { shortUserWait: true } : {}) };
|
|
670
|
+
log(`[批量] 换${school.name}补${partsNamed(items[offset])}:${request.doi || request.paperId}`);
|
|
671
|
+
const result = await fetchOnce(item, request, entry, items[offset]);
|
|
672
|
+
items[offset] = itemResult(result, offset + 1, request);
|
|
673
|
+
if (stoppedByUser(result))
|
|
674
|
+
stopped = true;
|
|
675
|
+
if (!stopped && partsWithoutAccess(result, true))
|
|
676
|
+
return;
|
|
677
|
+
const { request: asked } = waiting.get(offset);
|
|
678
|
+
waiting.delete(offset);
|
|
679
|
+
await finish(offset, entry, asked, result);
|
|
680
|
+
await papers.send();
|
|
681
|
+
}, () => stopped);
|
|
682
|
+
}
|
|
683
|
+
// Without access with every school (or the batch stopped first): as they were.
|
|
684
|
+
for (const [offset, { entry, request }] of waiting)
|
|
685
|
+
await finish(offset, entry, request, items[offset]);
|
|
686
|
+
waiting.clear();
|
|
687
|
+
// Markdown saved without some figures: those once more, unless the user stopped the batch (user, 2026-11-23).
|
|
688
|
+
if (!stopped) {
|
|
689
|
+
await figuresAtTheEnd(figuresLater.map(({ offset, entry, request }) => ({ result: items[offset], request: recorded(request, ledger, entry) })), log, ledger);
|
|
690
|
+
}
|
|
691
|
+
for (const { offset, entry, request, mainPath } of figuresLater) {
|
|
692
|
+
ledger?.item(entry, items[offset]);
|
|
693
|
+
papers.set(offset, batchPaper(request, items[offset], undefined, content, mainPath));
|
|
694
|
+
}
|
|
511
695
|
await papers.send(true);
|
|
512
696
|
ledger?.close();
|
|
513
697
|
return summary(options.mode ?? "two_phase", batchId, items, {
|
|
@@ -531,10 +715,37 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
|
|
|
531
715
|
// school at a time (``laterSchools``, user 2026-11-22).
|
|
532
716
|
let turns;
|
|
533
717
|
const otherSchools = () => (turns ??= schoolsAfterDefault(backend, options));
|
|
718
|
+
let retryOn;
|
|
719
|
+
const retrying = () => (retryOn ??= retrySetting(backend));
|
|
534
720
|
const waiting = new Map();
|
|
721
|
+
/** Of the waiting papers, those whose PDF stands, waiting for their Markdown or files alone (partsWithoutAccess). */
|
|
722
|
+
const partsOnly = new Set();
|
|
535
723
|
const schoolsTried = new Map();
|
|
536
724
|
/** Papers failed for a reason not known, waiting for their one more try at the end (user, 2026-11-22). */
|
|
537
725
|
const unexplainedYet = new Map();
|
|
726
|
+
// The papers held for a later try are in the window's ring beside those done (user, 2026-11-23), told when they change.
|
|
727
|
+
const dois = (entries) => [...entries.values()].map((entry) => entry.doi ?? "").filter(Boolean);
|
|
728
|
+
const later = () => ({ noAccess: waiting.size, unexplained: unexplainedYet.size, blocked: 0, login: 0,
|
|
729
|
+
papers: { noAccess: dois(waiting), unexplained: dois(unexplainedYet), blocked: [], login: [] } });
|
|
730
|
+
let laterSaid = JSON.stringify(later());
|
|
731
|
+
/** The window told of them, and at the switch to another school, its name; none once every paper is done. */
|
|
732
|
+
const reportLater = async (school) => {
|
|
733
|
+
const counts = later();
|
|
734
|
+
if (!backend?.reportBatchProgress || succeeded + failed >= total || !school && JSON.stringify(counts) === laterSaid)
|
|
735
|
+
return;
|
|
736
|
+
laterSaid = JSON.stringify(counts);
|
|
737
|
+
await backend.reportBatchProgress({ id: batchId, total, done: succeeded + failed, succeeded, failed, current: "",
|
|
738
|
+
finished: false, later: counts, ...(school ? { switchTo: school.name } : {}), laterOnly: true }).catch(() => false);
|
|
739
|
+
};
|
|
740
|
+
/** Papers whose Markdown lacks figures, recorded after their second try at the end (figuresAtTheEnd). */
|
|
741
|
+
const figuresLater = new Map();
|
|
742
|
+
/** A finished paper into the run's records, unless its Markdown's figures wait for the end. */
|
|
743
|
+
const record = (offset, entry) => {
|
|
744
|
+
if (figuresMissing(items[offset]))
|
|
745
|
+
figuresLater.set(offset, entry);
|
|
746
|
+
else
|
|
747
|
+
ledger?.item(entry, items[offset]);
|
|
748
|
+
};
|
|
538
749
|
let stopped = false;
|
|
539
750
|
for (const [offset, item] of options.items.entries()) {
|
|
540
751
|
const index = offset + 1;
|
|
@@ -555,18 +766,23 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
|
|
|
555
766
|
await markdownPastNetworkLoss(finished, recorded({ ...request, batch }, ledger, entry), searchers, pageVisit(backend, { ...request, batch }, log, pause), watch);
|
|
556
767
|
}
|
|
557
768
|
items.push(finished);
|
|
558
|
-
|
|
559
|
-
|
|
769
|
+
const partsLacking = partsWithoutAccess(finished);
|
|
770
|
+
if ((withoutAccess(finished) && !stoppedByUser(finished) || partsLacking) && (await otherSchools()).length) {
|
|
771
|
+
// Not finished: it waits for the other schools at the end (its Markdown or files alone when its PDF stands).
|
|
560
772
|
waiting.set(offset, entry);
|
|
773
|
+
if (partsLacking)
|
|
774
|
+
partsOnly.add(offset);
|
|
561
775
|
papers.set(offset, batchPaper(request, finished, "school", content));
|
|
562
776
|
await papers.send();
|
|
777
|
+
await reportLater();
|
|
563
778
|
continue;
|
|
564
779
|
}
|
|
565
|
-
if (unexplainedFailure(finished)) {
|
|
780
|
+
if (unexplainedFailure(finished) && await retrying()) {
|
|
566
781
|
// Not finished: once more at the end, with this school.
|
|
567
782
|
unexplainedYet.set(offset, entry);
|
|
568
783
|
papers.set(offset, batchPaper(request, finished, "school", content));
|
|
569
784
|
await papers.send();
|
|
785
|
+
await reportLater();
|
|
570
786
|
continue;
|
|
571
787
|
}
|
|
572
788
|
if (result.status === "ok")
|
|
@@ -575,7 +791,7 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
|
|
|
575
791
|
failed += 1;
|
|
576
792
|
// The window's end when the last paper is finished, not the last in the list (some wait for the end).
|
|
577
793
|
await reportBatchItem({ ...request, batch: { ...batch, index: batch.done + 1 } }, finished, backend);
|
|
578
|
-
|
|
794
|
+
record(offset, entry);
|
|
579
795
|
papers.set(offset, batchPaper(request, finished, undefined, content));
|
|
580
796
|
if (publisherBlocked(result))
|
|
581
797
|
log(blockedNotice(request.doi || request.paperId));
|
|
@@ -597,6 +813,7 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
|
|
|
597
813
|
}
|
|
598
814
|
/** A paper's school stage once more (another saved school when given), its files and Markdown when it comes. */
|
|
599
815
|
const again = async (offset, entry, school) => {
|
|
816
|
+
await reportLater();
|
|
600
817
|
const request = { ...itemOptions(options.items[offset], options), ...(school ? { school: school.entityId } : {}) };
|
|
601
818
|
const batch = { id: batchId, index: offset + 1, total, done: succeeded + failed, succeeded, failed };
|
|
602
819
|
log(school ? `[批量] 换${school.name}:${request.doi || request.paperId}` : `[批量] 再试一次:${request.doi || request.paperId}`);
|
|
@@ -615,6 +832,18 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
|
|
|
615
832
|
stopped = true;
|
|
616
833
|
return finished;
|
|
617
834
|
};
|
|
835
|
+
/** A paper whose PDF stands, its Markdown or files without access, with another school: those alone. */
|
|
836
|
+
const partsAt = async (offset, entry, school) => {
|
|
837
|
+
await reportLater();
|
|
838
|
+
const request = { ...itemOptions(options.items[offset], options), school: school.entityId };
|
|
839
|
+
const batch = { id: batchId, index: offset + 1, total, done: succeeded + failed, succeeded, failed };
|
|
840
|
+
const item = items[offset];
|
|
841
|
+
log(`[批量] 换${school.name}补${partsNamed(item)}:${request.doi || request.paperId}`);
|
|
842
|
+
await partsAgain(item, recorded({ ...request, batch, ...(away ? { shortUserWait: true } : {}) }, ledger, entry), backend, searchers, pageVisit(backend, { ...request, batch, ...(away ? { shortUserWait: true } : {}) }, log, pause), watch);
|
|
843
|
+
if (stoppedByUser(item))
|
|
844
|
+
stopped = true;
|
|
845
|
+
return item;
|
|
846
|
+
};
|
|
618
847
|
/** A paper finished at the end: counted, recorded, shown. */
|
|
619
848
|
const finish = async (offset, entry) => {
|
|
620
849
|
const request = itemOptions(options.items[offset], options);
|
|
@@ -625,7 +854,7 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
|
|
|
625
854
|
else
|
|
626
855
|
failed += 1;
|
|
627
856
|
await reportBatchItem({ ...request, batch }, items[offset], backend);
|
|
628
|
-
|
|
857
|
+
record(offset, entry);
|
|
629
858
|
papers.set(offset, batchPaper(request, items[offset], undefined, content));
|
|
630
859
|
await papers.send();
|
|
631
860
|
};
|
|
@@ -651,8 +880,16 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
|
|
|
651
880
|
await laterSchools(await otherSchools(), () => [...waiting.keys()], async (school, count) => {
|
|
652
881
|
log(`[批量] 没权限的 ${count} 篇换${school.name}再试`);
|
|
653
882
|
ledger?.phase(`没权限的 ${count} 篇换${school.name}再试`);
|
|
883
|
+
await reportLater(school);
|
|
654
884
|
}, async (offset, school) => {
|
|
655
885
|
const entry = waiting.get(offset);
|
|
886
|
+
if (partsOnly.has(offset)) {
|
|
887
|
+
if (!stopped && partsWithoutAccess(await partsAt(offset, entry, school)))
|
|
888
|
+
return;
|
|
889
|
+
waiting.delete(offset);
|
|
890
|
+
await finish(offset, entry);
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
656
893
|
const finished = await again(offset, entry, school);
|
|
657
894
|
schoolsTried.set(offset, (schoolsTried.get(offset) ?? 1) + 1);
|
|
658
895
|
if (!stopped && withoutAccess(finished)) {
|
|
@@ -666,6 +903,14 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
|
|
|
666
903
|
// Without access with every school (or the batch stopped first): failed.
|
|
667
904
|
for (const [offset, entry] of waiting)
|
|
668
905
|
await finish(offset, entry);
|
|
906
|
+
// Markdown saved without some figures: those once more, unless the user stopped the batch (user, 2026-11-23).
|
|
907
|
+
if (!stopped) {
|
|
908
|
+
await figuresAtTheEnd([...figuresLater].map(([offset, entry]) => ({ result: items[offset], request: recorded(itemOptions(options.items[offset], options), ledger, entry) })), log, ledger);
|
|
909
|
+
}
|
|
910
|
+
for (const [offset, entry] of figuresLater) {
|
|
911
|
+
ledger?.item(entry, items[offset]);
|
|
912
|
+
papers.set(offset, batchPaper(itemOptions(options.items[offset], options), items[offset], undefined, content));
|
|
913
|
+
}
|
|
669
914
|
await papers.send(true);
|
|
670
915
|
ledger?.close();
|
|
671
916
|
return summary("per_item", batchId, items, {
|
|
@@ -681,7 +926,7 @@ function laneError(stage, error) {
|
|
|
681
926
|
message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) }],
|
|
682
927
|
};
|
|
683
928
|
}
|
|
684
|
-
async function downloadTwoPhase(searchers, options, backend, log, createTiers, mode = "two_phase", pause = wait, online = networkReachable) {
|
|
929
|
+
async function downloadTwoPhase(searchers, options, backend, log, createTiers, mode = "two_phase", pause = wait, online = networkReachable, now = Date.now) {
|
|
685
930
|
const batchId = randomUUID();
|
|
686
931
|
const total = options.items.length;
|
|
687
932
|
const ledger = openLedger(mode, batchId, options, log);
|
|
@@ -691,10 +936,17 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
691
936
|
const content = options.content ?? "main";
|
|
692
937
|
const papers = new PaperList(backend, batchId, options.savePath, requests.map((request) => batchPaper(request, undefined, mode === "entitled_only" ? "school" : "open", content)));
|
|
693
938
|
const recordedOffsets = new Set();
|
|
939
|
+
/** Papers whose Markdown lacks figures: recorded after their second try at the end (figuresAtTheEnd). */
|
|
940
|
+
const figuresLater = new Set();
|
|
941
|
+
let figuresTried = false;
|
|
694
942
|
/** An item goes to the run record once, when it has settled. */
|
|
695
943
|
const record = (offset) => {
|
|
696
944
|
if (recordedOffsets.has(offset))
|
|
697
945
|
return;
|
|
946
|
+
if (!figuresTried && figuresMissing(results[offset])) {
|
|
947
|
+
figuresLater.add(offset);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
698
950
|
recordedOffsets.add(offset);
|
|
699
951
|
ledger?.item(entries[offset], results[offset]);
|
|
700
952
|
};
|
|
@@ -743,11 +995,11 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
743
995
|
const reportProgress = (current) => {
|
|
744
996
|
if (!openProgress)
|
|
745
997
|
return reports;
|
|
746
|
-
const update = {
|
|
998
|
+
const update = withLater({
|
|
747
999
|
id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current, finished: false,
|
|
748
1000
|
...(openRunning ? { phase: `${OPEN_CHANNEL}:已查 ${checked}/${total} 篇,找到 ${openFound} 篇`, channel: OPEN_CHANNEL } : {}),
|
|
749
1001
|
...(missed.length ? { lanes: lanes() } : {}),
|
|
750
|
-
};
|
|
1002
|
+
});
|
|
751
1003
|
reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
|
|
752
1004
|
return reports;
|
|
753
1005
|
};
|
|
@@ -761,59 +1013,20 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
761
1013
|
const watch = { log, pause, online, notice: (phase) => {
|
|
762
1014
|
if (!backend?.reportBatchProgress || !(openProgress || missed.length))
|
|
763
1015
|
return reports;
|
|
764
|
-
const update = { id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
|
|
765
|
-
finished: false, phase };
|
|
1016
|
+
const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
|
|
1017
|
+
finished: false, phase });
|
|
766
1018
|
reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
|
|
767
1019
|
return reports;
|
|
768
1020
|
} };
|
|
1021
|
+
// The open-access lane checks OPEN_AT_ONCE papers at once (user, 2026-11-29), each site within its own limit
|
|
1022
|
+
// (infrastructure/http/hostGate.ts); a paper it misses goes to the browser's lane as soon as it is known.
|
|
1023
|
+
let nextOpen = 0;
|
|
769
1024
|
const openLane = async () => {
|
|
770
1025
|
try {
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
const tiers = createTiers(backend).filter((tier) => tier.stage !== "entitled_access" && tier.stage !== "preprint");
|
|
776
|
-
let result;
|
|
777
|
-
try {
|
|
778
|
-
result = await pastNetworkLoss(() => downloadWithFallback(searchers, recorded(request, ledger, entries[offset]), tiers), watch);
|
|
779
|
-
}
|
|
780
|
-
catch (error) {
|
|
781
|
-
result = laneError("open_access", error);
|
|
782
|
-
log(`[批量] 开放来源出错(${id(offset)}):${result.attempts[0].message};这一篇转机构下载`);
|
|
783
|
-
}
|
|
784
|
-
results[offset] = itemResult(result, offset + 1, request);
|
|
785
|
-
checked = offset + 1;
|
|
786
|
-
if (result.status === "ok") {
|
|
787
|
-
openFound += 1;
|
|
788
|
-
// Its Markdown from the open sources now; the browser's part, if any, in its queue.
|
|
789
|
-
const later = wantsFiles || wantsMarkdown &&
|
|
790
|
-
await fulltextForItem(results[offset], recorded(request, ledger, entries[offset]), searchers, "later") === "later";
|
|
791
|
-
// The window lists its PDF as saved now, as it did (its files' shortfall, if any, later).
|
|
792
|
-
settle(offset);
|
|
793
|
-
if (later) {
|
|
794
|
-
finishing.add(offset);
|
|
795
|
-
queue.push(offset);
|
|
796
|
-
notify();
|
|
797
|
-
}
|
|
798
|
-
else {
|
|
799
|
-
openSettled += 1;
|
|
800
|
-
record(offset);
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
else {
|
|
804
|
-
settle(offset, "school");
|
|
805
|
-
if (!missed.length) {
|
|
806
|
-
log(`[批量] 开放来源没有找到 ${id(offset)},机构下载同时开始`);
|
|
807
|
-
ledger?.phase("机构下载开始,开放来源同时进行");
|
|
808
|
-
}
|
|
809
|
-
missed.push(offset);
|
|
810
|
-
queue.push(offset);
|
|
811
|
-
notify();
|
|
812
|
-
}
|
|
813
|
-
await reportProgress(id(offset));
|
|
814
|
-
takeRequests();
|
|
815
|
-
await sendPapers();
|
|
816
|
-
}
|
|
1026
|
+
await Promise.all(Array.from({ length: Math.min(OPEN_AT_ONCE, total) }, async () => {
|
|
1027
|
+
for (let offset = nextOpen++; offset < total && !stopped; offset = nextOpen++)
|
|
1028
|
+
await openItem(offset);
|
|
1029
|
+
}));
|
|
817
1030
|
}
|
|
818
1031
|
finally {
|
|
819
1032
|
openRunning = false;
|
|
@@ -825,11 +1038,57 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
825
1038
|
ledger?.phase(`开放来源查完:${missed.length} 篇转机构下载`);
|
|
826
1039
|
}
|
|
827
1040
|
};
|
|
1041
|
+
/** One paper's open-access check, and where it goes then. */
|
|
1042
|
+
const openItem = async (offset) => {
|
|
1043
|
+
const request = requests[offset];
|
|
1044
|
+
log(`[批量] 开放来源 ${offset + 1}/${total}:${id(offset)}`);
|
|
1045
|
+
const tiers = createTiers(backend).filter((tier) => tier.stage !== "entitled_access" && tier.stage !== "preprint");
|
|
1046
|
+
let result;
|
|
1047
|
+
try {
|
|
1048
|
+
result = await pastNetworkLoss(() => downloadWithFallback(searchers, recorded(request, ledger, entries[offset]), tiers), watch);
|
|
1049
|
+
}
|
|
1050
|
+
catch (error) {
|
|
1051
|
+
result = laneError("open_access", error);
|
|
1052
|
+
log(`[批量] 开放来源出错(${id(offset)}):${result.attempts[0].message};这一篇转机构下载`);
|
|
1053
|
+
}
|
|
1054
|
+
results[offset] = itemResult(result, offset + 1, request);
|
|
1055
|
+
checked += 1;
|
|
1056
|
+
if (result.status === "ok") {
|
|
1057
|
+
openFound += 1;
|
|
1058
|
+
// Its Markdown from the open sources now; the browser's part, if any, in its queue.
|
|
1059
|
+
const later = wantsFiles || wantsMarkdown &&
|
|
1060
|
+
await fulltextForItem(results[offset], recorded(request, ledger, entries[offset]), searchers, "later") === "later";
|
|
1061
|
+
// The window lists its PDF as saved now, as it did (its files' shortfall, if any, later).
|
|
1062
|
+
settle(offset);
|
|
1063
|
+
if (later) {
|
|
1064
|
+
finishing.add(offset);
|
|
1065
|
+
queue.push(offset);
|
|
1066
|
+
notify();
|
|
1067
|
+
}
|
|
1068
|
+
else {
|
|
1069
|
+
openSettled += 1;
|
|
1070
|
+
record(offset);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
else {
|
|
1074
|
+
settle(offset, "school");
|
|
1075
|
+
if (!missed.length) {
|
|
1076
|
+
log(`[批量] 开放来源没有找到 ${id(offset)},机构下载同时开始`);
|
|
1077
|
+
ledger?.phase("机构下载开始,开放来源同时进行");
|
|
1078
|
+
}
|
|
1079
|
+
missed.push(offset);
|
|
1080
|
+
queue.push(offset);
|
|
1081
|
+
notify();
|
|
1082
|
+
}
|
|
1083
|
+
await reportProgress(id(offset));
|
|
1084
|
+
takeRequests();
|
|
1085
|
+
await sendPapers();
|
|
1086
|
+
};
|
|
828
1087
|
/**
|
|
829
1088
|
* The browser's part of an open-access paper: its supplementary files (the visit also
|
|
830
1089
|
* saves the page when the Markdown is wanted), then its Markdown.
|
|
831
1090
|
*/
|
|
832
|
-
const finishOpenItem = async (offset) => {
|
|
1091
|
+
const finishOpenItem = async (offset, laneBackend = backend) => {
|
|
833
1092
|
finishing.delete(offset);
|
|
834
1093
|
const done = settledOk() + failed;
|
|
835
1094
|
const request = { ...requests[offset], batch: { id: batchId, index: done + 1, total, done, succeeded: settledOk(), failed },
|
|
@@ -841,10 +1100,10 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
841
1100
|
let pageWait;
|
|
842
1101
|
let markdownFrom = item.attempts.length;
|
|
843
1102
|
try {
|
|
844
|
-
extra = await filesPastNetworkLoss(item, recorded(request, ledger, entries[offset]),
|
|
1103
|
+
extra = await filesPastNetworkLoss(item, recorded(request, ledger, entries[offset]), laneBackend, searchers, watch);
|
|
845
1104
|
markdownFrom = item.attempts.length;
|
|
846
1105
|
if (wantsMarkdown && !stoppedByUser(item)) {
|
|
847
|
-
await markdownPastNetworkLoss(item, recorded(request, ledger, entries[offset]), searchers, pageVisit(
|
|
1106
|
+
await markdownPastNetworkLoss(item, recorded(request, ledger, entries[offset]), searchers, pageVisit(laneBackend, request, log, pause, (trace) => { pageWait = trace?.loginWaitPage; learnPublisher(offset, trace?.publisher); }), watch);
|
|
848
1107
|
}
|
|
849
1108
|
}
|
|
850
1109
|
catch (error) {
|
|
@@ -863,7 +1122,8 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
863
1122
|
}
|
|
864
1123
|
// Its page stopped at the school's own sign-in page: held with its publisher, its Markdown
|
|
865
1124
|
// fetched again when the user goes on (the files it got stand).
|
|
866
|
-
if (pageWait === SCHOOL_SIGN_IN_PAGE && wentThrough(offset) && !stoppedByUser(item) && await canHold()
|
|
1125
|
+
if (pageWait === SCHOOL_SIGN_IN_PAGE && wentThrough(offset) && !stoppedByUser(item) && await canHold()
|
|
1126
|
+
&& !heldAgain(offset)) {
|
|
867
1127
|
item.attempts.length = markdownFrom;
|
|
868
1128
|
delete item.markdown;
|
|
869
1129
|
finishing.add(offset);
|
|
@@ -875,6 +1135,13 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
875
1135
|
return;
|
|
876
1136
|
}
|
|
877
1137
|
}
|
|
1138
|
+
// Its Markdown or files without access (partsWithoutAccess): not finished, it waits for the other schools at the end.
|
|
1139
|
+
if (!stopped && partsWithoutAccess(item) && (await otherSchools()).length) {
|
|
1140
|
+
partsYet.add(offset);
|
|
1141
|
+
settle(offset, "school");
|
|
1142
|
+
await sendPapers();
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
878
1145
|
openSettled += 1;
|
|
879
1146
|
if (extra)
|
|
880
1147
|
await reportBatchItem(request, extra, backend);
|
|
@@ -901,6 +1168,12 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
901
1168
|
const viaSchool = new Set();
|
|
902
1169
|
/** Each held publisher's papers, open-access ones still to be finished among them. */
|
|
903
1170
|
const held = new Map();
|
|
1171
|
+
/**
|
|
1172
|
+
* The papers that held their publisher. Gone on with by 登录并继续 and stopped at the school's sign-in page again, such
|
|
1173
|
+
* a paper fails and its publisher's other papers go on, not held a second time (Windows, 2026-11-24: Nature Digest, a
|
|
1174
|
+
* site with only its subscribers' sign-in, held Springer Nature's 73 other papers again after each 登录并继续).
|
|
1175
|
+
*/
|
|
1176
|
+
const heldBy = new Set();
|
|
904
1177
|
/** Where each paper's wait on a school login ended, as the backend said (trace.loginWaitPage). */
|
|
905
1178
|
const waitEnded = new Map();
|
|
906
1179
|
const prefixOf = (offset) => (/^10\.\d{4,9}\//.exec(requests[offset].doi.toLowerCase()) ?? [""])[0];
|
|
@@ -926,15 +1199,26 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
926
1199
|
const canHold = async () => (holdOk ??= await backend?.holdSupported?.().catch(() => false) ?? false);
|
|
927
1200
|
/** Each DOI prefix's publisher as the school's stages named it ("Science"); the last one named. */
|
|
928
1201
|
const publishers = new Map();
|
|
929
|
-
|
|
1202
|
+
// A publisher whose site blocks the batch (被网站拦截: its human verification not passed, its block page): its papers
|
|
1203
|
+
// wait in ``held`` too, the others go on, and they are tried once more after BLOCKED_PAUSE_MS, without the user; blocked
|
|
1204
|
+
// again then, the publisher is given up for this batch (user, 2026-11-23: JAMA blocked after about 15 papers, and 21
|
|
1205
|
+
// of 28 each waited out its verification, at the end again with the retry of 原因不明 and with the next school).
|
|
1206
|
+
/** Each held publisher whose site blocked the batch: when its papers are tried again. */
|
|
1207
|
+
const blockedUntil = new Map();
|
|
1208
|
+
/** Publishers whose papers went on after their pause: blocked again, the batch gives them up. */
|
|
1209
|
+
const triedAgain = new Set();
|
|
1210
|
+
/** Publishers given up: their papers not tried yet end as 被网站拦截, untried; no visit of the batch's end goes to them. */
|
|
1211
|
+
const givenUp = new Set();
|
|
1212
|
+
/** The held publishers waiting for the user (登录并继续), not those blocked. */
|
|
1213
|
+
const heldList = () => [...held.entries()].filter(([key]) => !blockedUntil.has(key)).map(([key, offsets]) => ({
|
|
930
1214
|
key, name: publishers.get(key) ?? key, count: offsets.length,
|
|
931
1215
|
}));
|
|
932
1216
|
/** The window's line and button for the held publishers (none: cleared). */
|
|
933
1217
|
const reportHeld = (waiting = false) => {
|
|
934
1218
|
if (!backend?.reportBatchProgress || !holdOk)
|
|
935
1219
|
return reports;
|
|
936
|
-
const update = { id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
|
|
937
|
-
finished: false, held: heldList(), ...(waiting ? { phase: HOLD_WAIT_PHASE, heldWait: true } : { lanes: lanes() }) };
|
|
1220
|
+
const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
|
|
1221
|
+
finished: false, held: heldList(), ...(waiting ? { phase: HOLD_WAIT_PHASE, heldWait: true } : { lanes: lanes() }) });
|
|
938
1222
|
reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
|
|
939
1223
|
return reports;
|
|
940
1224
|
};
|
|
@@ -946,13 +1230,98 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
946
1230
|
return;
|
|
947
1231
|
}
|
|
948
1232
|
held.set(key, [offset]);
|
|
1233
|
+
heldBy.add(offset);
|
|
949
1234
|
log(`[批量] ${key} 的文章前面经学校登录下到了,这一篇停在学校登录页没有完成登录:` +
|
|
950
1235
|
"这家出版社的篇目先暂停,其他照常下载;回来后在进度窗口点“登录并继续”");
|
|
951
1236
|
ledger?.phase(`暂停 ${key}:学校登录中途失效`);
|
|
952
1237
|
void reportHeld();
|
|
953
1238
|
};
|
|
954
|
-
/**
|
|
1239
|
+
/** ``offset`` held its publisher before and stopped at the school's sign-in page again after 登录并继续: not held again. */
|
|
1240
|
+
const heldAgain = (offset) => {
|
|
1241
|
+
if (!heldBy.has(offset))
|
|
1242
|
+
return false;
|
|
1243
|
+
log(`[批量] ${id(offset)} 点“登录并继续”后仍停在学校登录页:这一篇记为失败,${publisherOf(offset)} 的其他篇目接着下载`);
|
|
1244
|
+
return true;
|
|
1245
|
+
};
|
|
1246
|
+
/** The window's line while blocked publishers' papers wait: when they are tried again, how many. */
|
|
1247
|
+
const reportBlocked = () => {
|
|
1248
|
+
if (!backend?.reportBatchProgress || !blockedUntil.size)
|
|
1249
|
+
return reports;
|
|
1250
|
+
const until = Math.min(...blockedUntil.values());
|
|
1251
|
+
const count = [...blockedUntil.keys()].reduce((sum, key) => sum + (held.get(key)?.length ?? 0), 0);
|
|
1252
|
+
if (!count)
|
|
1253
|
+
return reports;
|
|
1254
|
+
const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
|
|
1255
|
+
finished: false, phase: `被网站拦截,${clockTime(until)} 再试暂停的 ${count} 篇` });
|
|
1256
|
+
reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
|
|
1257
|
+
return reports;
|
|
1258
|
+
};
|
|
1259
|
+
/**
|
|
1260
|
+
* ``key``'s site blocked the batch (``why``): the publisher's papers wait, the others go on. ``offset``, the paper it
|
|
1261
|
+
* blocked, waits with them; none when the paper was saved and only its files were refused as too many requests.
|
|
1262
|
+
*/
|
|
1263
|
+
const pauseBlocked = (key, why, offset) => {
|
|
1264
|
+
const until = now() + BLOCKED_PAUSE_MS;
|
|
1265
|
+
held.set(key, [...(held.get(key) ?? []), ...(offset === undefined ? [] : [offset])]);
|
|
1266
|
+
blockedUntil.set(key, until);
|
|
1267
|
+
log(`[批量] ${key} 的网站拦截了访问(${why}):这家出版社的篇目先暂停,${clockTime(until)} 再试一次,其他照常下载`);
|
|
1268
|
+
ledger?.phase(`暂停 ${key}:被网站拦截`);
|
|
1269
|
+
void reportBlocked();
|
|
1270
|
+
};
|
|
1271
|
+
/** Pauses with none of their publisher's papers left to wait (its files refused on its last paper): not waited out. */
|
|
1272
|
+
const dropEmptyPauses = () => {
|
|
1273
|
+
for (const key of [...blockedUntil.keys()]) {
|
|
1274
|
+
if (held.get(key)?.length)
|
|
1275
|
+
continue;
|
|
1276
|
+
blockedUntil.delete(key);
|
|
1277
|
+
held.delete(key);
|
|
1278
|
+
}
|
|
1279
|
+
};
|
|
1280
|
+
/** ``offset``'s publisher's site blocked it again after the pause, or at the batch's end: given up for this batch. */
|
|
1281
|
+
const giveUp = (offset) => {
|
|
1282
|
+
const key = publisherOf(offset);
|
|
1283
|
+
if (givenUp.has(key))
|
|
1284
|
+
return;
|
|
1285
|
+
givenUp.add(key);
|
|
1286
|
+
log(`[批量] ${key} 的网站${triedAgain.has(key) ? "暂停后仍" : ""}拦截了访问(${id(offset)}):这家出版社余下的篇目本批不再试` +
|
|
1287
|
+
"(没试的记为被网站拦截,原因不明的不再重试,没权限的不再换学校);过一阵说“接着下”再补");
|
|
1288
|
+
ledger?.phase(`不再试 ${key}:仍被网站拦截`);
|
|
1289
|
+
};
|
|
1290
|
+
/** Without 失败后自动重试: each publisher's papers blocked in a row (BLOCKED_IN_ROW of them give it up). */
|
|
1291
|
+
const blockedInRow = new Map();
|
|
1292
|
+
const blockedOnce = (offset) => {
|
|
1293
|
+
const key = publisherOf(offset);
|
|
1294
|
+
const count = (blockedInRow.get(key) ?? 0) + 1;
|
|
1295
|
+
blockedInRow.set(key, count);
|
|
1296
|
+
if (count >= BLOCKED_IN_ROW)
|
|
1297
|
+
giveUp(offset);
|
|
1298
|
+
else
|
|
1299
|
+
log(`[批量] ${key} 的网站拦截了 ${id(offset)}(连续第 ${count} 篇):这一篇记为失败,这家出版社的其他篇目接着试`);
|
|
1300
|
+
};
|
|
1301
|
+
/** Blocked publishers whose pause is over: their papers go first, once more. */
|
|
1302
|
+
const releaseBlocked = () => {
|
|
1303
|
+
let released = 0;
|
|
1304
|
+
for (const [key, until] of blockedUntil) {
|
|
1305
|
+
if (now() < until)
|
|
1306
|
+
continue;
|
|
1307
|
+
const offsets = held.get(key) ?? [];
|
|
1308
|
+
blockedUntil.delete(key);
|
|
1309
|
+
held.delete(key);
|
|
1310
|
+
// A pause nothing waited in (only a paper's files were refused) is no try: its next block pauses again.
|
|
1311
|
+
if (!offsets.length)
|
|
1312
|
+
continue;
|
|
1313
|
+
triedAgain.add(key);
|
|
1314
|
+
queue.unshift(...offsets);
|
|
1315
|
+
released += offsets.length;
|
|
1316
|
+
log(`[批量] ${key} 已暂停 ${BLOCKED_PAUSE_MS / 60_000} 分钟:暂停的 ${offsets.length} 篇再试一次`);
|
|
1317
|
+
ledger?.phase(`再试 ${key} 暂停的 ${offsets.length} 篇`);
|
|
1318
|
+
}
|
|
1319
|
+
if (released)
|
|
1320
|
+
notify();
|
|
1321
|
+
};
|
|
1322
|
+
/** The user pressed 登录并继续 (or 终止) in the window: held papers go on first. Blocked ones whose pause is over too. */
|
|
955
1323
|
const takeRequests = () => {
|
|
1324
|
+
releaseBlocked();
|
|
956
1325
|
const asked = backend?.takeBatchRequests?.(batchId);
|
|
957
1326
|
if (!asked)
|
|
958
1327
|
return;
|
|
@@ -960,6 +1329,8 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
960
1329
|
stopped = true;
|
|
961
1330
|
let resumed = 0;
|
|
962
1331
|
for (const key of asked.resume) {
|
|
1332
|
+
if (blockedUntil.has(key))
|
|
1333
|
+
continue;
|
|
963
1334
|
const offsets = held.get(key) ?? [];
|
|
964
1335
|
held.delete(key);
|
|
965
1336
|
queue.unshift(...offsets);
|
|
@@ -972,22 +1343,32 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
972
1343
|
notify();
|
|
973
1344
|
}
|
|
974
1345
|
};
|
|
1346
|
+
/** A paper its publisher's pause left untried: its school stage says so (``code``), or, its PDF from open access standing, its files. */
|
|
1347
|
+
const untried = (offset, code, files = code) => {
|
|
1348
|
+
const item = results[offset];
|
|
1349
|
+
if (finishing.has(offset)) {
|
|
1350
|
+
// Its PDF stands; its browser's part waited.
|
|
1351
|
+
if (wantsFiles)
|
|
1352
|
+
item.supplements = [{ status: "skipped", label: "", reason: files }];
|
|
1353
|
+
}
|
|
1354
|
+
else {
|
|
1355
|
+
const stage = { stage: "entitled_access", status: "error", ...schoolAttemptDetails(code) };
|
|
1356
|
+
results[offset] = itemResult({ ...item, status: "error", attempts: [...item.attempts, stage] }, offset + 1, requests[offset]);
|
|
1357
|
+
// The run record says it too, as `paper-search failures` reads it: there such a paper had no school stage, "没有走到
|
|
1358
|
+
// 机构下载" beside the batch's 被网站拦截 (BMJ, 2026-11-23: 1 + 47 against 48).
|
|
1359
|
+
ledger?.stage(entries[offset], { ...stage, startedAt: new Date().toISOString(), durationMs: 0,
|
|
1360
|
+
trace: { publisher: publisherOf(offset) } });
|
|
1361
|
+
}
|
|
1362
|
+
};
|
|
975
1363
|
/** The held papers end as paused (the batch stopped): returns them, no longer held. */
|
|
976
1364
|
const markPaused = () => {
|
|
977
1365
|
const paused = [...held.values()].flat();
|
|
978
|
-
for (const
|
|
979
|
-
const
|
|
980
|
-
|
|
981
|
-
// Its PDF stands; its browser's part waited for the login.
|
|
982
|
-
if (wantsFiles)
|
|
983
|
-
item.supplements = [{ status: "skipped", label: "", reason: "batch_stopped" }];
|
|
984
|
-
}
|
|
985
|
-
else {
|
|
986
|
-
results[offset] = itemResult({ ...item, status: "error", attempts: [...item.attempts,
|
|
987
|
-
{ stage: "entitled_access", status: "error", ...schoolAttemptDetails("login_paused") }] }, offset + 1, requests[offset]);
|
|
988
|
-
}
|
|
1366
|
+
for (const [key, offsets] of held) {
|
|
1367
|
+
for (const offset of offsets)
|
|
1368
|
+
untried(offset, blockedUntil.has(key) ? "blocked_paused" : "login_paused", "batch_stopped");
|
|
989
1369
|
}
|
|
990
1370
|
held.clear();
|
|
1371
|
+
blockedUntil.clear();
|
|
991
1372
|
return paused;
|
|
992
1373
|
};
|
|
993
1374
|
/**
|
|
@@ -1013,17 +1394,211 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
1013
1394
|
// one school before the next (``laterSchools``, user 2026-11-22).
|
|
1014
1395
|
let turns;
|
|
1015
1396
|
const otherSchools = () => (turns ??= schoolsAfterDefault(backend, options));
|
|
1397
|
+
// 失败后自动重试 (retrySetting): asked once, when the first paper might be tried again.
|
|
1398
|
+
let retryOn;
|
|
1399
|
+
const retrying = () => (retryOn ??= retrySetting(backend));
|
|
1016
1400
|
/** Papers without access with the schools tried so far, waiting for the next one. */
|
|
1017
1401
|
const withoutAccessYet = new Set();
|
|
1402
|
+
/**
|
|
1403
|
+
* Open-access papers whose PDF stands, their Markdown or files without access with the schools tried so far
|
|
1404
|
+
* (partsWithoutAccess): waiting for the next one, for those alone.
|
|
1405
|
+
*/
|
|
1406
|
+
const partsYet = new Set();
|
|
1018
1407
|
/** Papers failed for a reason not known, waiting for their one more try at the end. */
|
|
1019
1408
|
const unexplainedYet = new Set();
|
|
1020
1409
|
/** Each waiting paper's schools tried, the default one counted. */
|
|
1021
1410
|
const schoolsTried = new Map();
|
|
1411
|
+
// The papers held for a later try, by why, are in the window's ring beside those done, not in 剩余 unsaid (user,
|
|
1412
|
+
// 2026-11-23): every report to it says them, and one of its own does before a paper's school visit when they changed.
|
|
1413
|
+
/** The papers held for a later try now. */
|
|
1414
|
+
const later = () => {
|
|
1415
|
+
const waiting = (blocked) => [...held].filter(([key]) => blockedUntil.has(key) === blocked).flatMap(([, offsets]) => offsets);
|
|
1416
|
+
const until = [...blockedUntil].filter(([key]) => held.get(key)?.length).map(([, at]) => at);
|
|
1417
|
+
const dois = (offsets) => [...offsets].map((offset) => requests[offset].doi).filter(Boolean);
|
|
1418
|
+
const blocked = waiting(true), login = waiting(false);
|
|
1419
|
+
return { noAccess: withoutAccessYet.size + partsYet.size, unexplained: unexplainedYet.size, blocked: blocked.length,
|
|
1420
|
+
login: login.length, ...(until.length ? { blockedAt: Math.min(...until) } : {}),
|
|
1421
|
+
papers: { noAccess: dois([...withoutAccessYet, ...partsYet]), unexplained: dois(unexplainedYet), blocked: dois(blocked),
|
|
1422
|
+
login: dois(login) } };
|
|
1423
|
+
};
|
|
1424
|
+
/** What the window was last told of them. */
|
|
1425
|
+
let laterSaid = JSON.stringify(later());
|
|
1426
|
+
/** A report to the window with them (``later``). */
|
|
1427
|
+
const withLater = (update) => {
|
|
1428
|
+
const counts = later();
|
|
1429
|
+
laterSaid = JSON.stringify(counts);
|
|
1430
|
+
return { ...update, later: counts };
|
|
1431
|
+
};
|
|
1432
|
+
/** The window told of papers held for a later try, or back from it, when no report has said so; none once all are done. */
|
|
1433
|
+
const reportLater = () => {
|
|
1434
|
+
if (!backend?.reportBatchProgress || JSON.stringify(later()) === laterSaid || settledOk() + failed >= total)
|
|
1435
|
+
return reports;
|
|
1436
|
+
const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
|
|
1437
|
+
finished: false, laterOnly: true });
|
|
1438
|
+
reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
|
|
1439
|
+
return reports;
|
|
1440
|
+
};
|
|
1022
1441
|
// One journal's papers one after another when the backend says so (more than one school taking part, user
|
|
1023
1442
|
// 2026-11-21; kept with the switch at the end, user 2026-11-22). Asked until the backend has run a paper and can say.
|
|
1024
1443
|
let groupJournals;
|
|
1025
1444
|
let lastJournal = "";
|
|
1026
|
-
|
|
1445
|
+
/**
|
|
1446
|
+
* One paper's school visit (``offset``, not an open-access paper's browser part: ``finishOpenItem``), its Markdown,
|
|
1447
|
+
* and where it ends: saved, failed, held with its publisher, waiting for the end. ``lane``: a window of a batch whose
|
|
1448
|
+
* papers run at once (并行下载): its backend names the window, and a paper its publisher's hour holds goes back
|
|
1449
|
+
* (``lane.limited``) instead of waiting.
|
|
1450
|
+
*/
|
|
1451
|
+
/** Papers of the school lane being downloaded now (several in a batch whose papers run at once). */
|
|
1452
|
+
let inFlight = 0;
|
|
1453
|
+
const runOne = async (offset, lane, first) => {
|
|
1454
|
+
const laneBackend = lane ? lane.backend : first ?? backend;
|
|
1455
|
+
const request = requests[offset];
|
|
1456
|
+
// Papers waiting for the end (without access, 原因不明) counted too: the log goes 1/7, 2/7 … as the window does
|
|
1457
|
+
// (Windows 2026-11-22: every line said 1/7 while the papers waited); those downloading beside it too (并行下载: four
|
|
1458
|
+
// starting at once each said 2/21, user's Mac 2026-11-29).
|
|
1459
|
+
const step = succeeded + failed + withoutAccessYet.size + unexplainedYet.size + inFlight;
|
|
1460
|
+
log(openRunning
|
|
1461
|
+
? `[批量] 机构下载第 ${step} 篇(开放来源还在查):${id(offset)}`
|
|
1462
|
+
: `[批量] 机构下载 ${step}/${missed.length}:${id(offset)}`);
|
|
1463
|
+
const done = settledOk() + failed;
|
|
1464
|
+
// Its place among the papers gone through, those waiting for the end counted (the window's "k / N" goes on);
|
|
1465
|
+
// the counts are of those finished.
|
|
1466
|
+
const batch = { id: batchId, index: done + withoutAccessYet.size + partsYet.size + unexplainedYet.size + 1, total, done,
|
|
1467
|
+
succeeded: settledOk(), failed };
|
|
1468
|
+
let result;
|
|
1469
|
+
try {
|
|
1470
|
+
// Reported to the window once it is known whether the paper waits for the end (``reportBatchItem`` below).
|
|
1471
|
+
const visit = () => downloadWithFallback(searchers, watchingSchool(recorded({ ...request, batch, ...(away ? { shortUserWait: true } : {}) }, ledger, entries[offset]), offset), createTiers(laneBackend).filter((tier) => tier.stage === "entitled_access" || mode !== "entitled_only" && tier.stage === "preprint"));
|
|
1472
|
+
// A window of a batch whose papers run at once does not wait for its publisher's hour: the paper goes back and
|
|
1473
|
+
// the window takes another publisher (windowPlan.ts); one after another, the batch waits for it here.
|
|
1474
|
+
result = await pastNetworkLoss(() => lane ? visit() : pastHourlyLimit(visit, log, pause, backend), watch);
|
|
1475
|
+
}
|
|
1476
|
+
catch (error) {
|
|
1477
|
+
result = laneError("entitled_access", error);
|
|
1478
|
+
log(`[批量] 机构下载出错(${id(offset)}):${result.attempts[0].message}`);
|
|
1479
|
+
}
|
|
1480
|
+
const hourly = lane ? rateLimitWait(result) : undefined;
|
|
1481
|
+
if (lane && hourly) {
|
|
1482
|
+
lane.limited(offset, hourly.wait, hourly.publisher);
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
if (result.status === "ok" && result.version === "preprint")
|
|
1486
|
+
preprints += 1;
|
|
1487
|
+
if (!away && waitedOutOnUser(result)) {
|
|
1488
|
+
away = true;
|
|
1489
|
+
log(AWAY_NOTICE);
|
|
1490
|
+
}
|
|
1491
|
+
const open = results[offset];
|
|
1492
|
+
results[offset] = itemResult({
|
|
1493
|
+
...result,
|
|
1494
|
+
attempts: [...open.attempts, ...result.attempts],
|
|
1495
|
+
...(result.review ?? open.review ? { review: result.review ?? open.review } : {}),
|
|
1496
|
+
}, offset + 1, request);
|
|
1497
|
+
const school = result.attempts.find((attempt) => attempt.stage === "entitled_access");
|
|
1498
|
+
const holding = result.status !== "ok" && wentThrough(offset) && school?.code === LOGIN_LAPSED_CODE
|
|
1499
|
+
&& waitEnded.get(offset) === SCHOOL_SIGN_IN_PAGE && !stoppedByUser(result) && await canHold() && !heldAgain(offset);
|
|
1500
|
+
// Its publisher's site blocked it: it waits with the publisher's other papers, once (BLOCKED_PAUSE_MS).
|
|
1501
|
+
const blocked = !holding && siteBlocked(result);
|
|
1502
|
+
const pausing = blocked && !triedAgain.has(publisherOf(offset)) && await retrying();
|
|
1503
|
+
if (!blocked)
|
|
1504
|
+
blockedInRow.delete(publisherOf(offset));
|
|
1505
|
+
// Its Markdown now, from the page this visit saved, or the open sources (only these
|
|
1506
|
+
// while its school login is in doubt or its site blocks); a paused paper's when it is tried again.
|
|
1507
|
+
if (wantsMarkdown && !stoppedByUser(result) && !pausing) {
|
|
1508
|
+
await markdownPastNetworkLoss(results[offset], recorded({ ...request, batch }, ledger, entries[offset]), searchers, holding || blocked ? undefined
|
|
1509
|
+
: pageVisit(laneBackend, { ...request, batch, ...(away ? { shortUserWait: true } : {}) }, log, pause), watch);
|
|
1510
|
+
}
|
|
1511
|
+
if (result.status === "ok") {
|
|
1512
|
+
succeeded += 1;
|
|
1513
|
+
record(offset);
|
|
1514
|
+
settle(offset);
|
|
1515
|
+
if (school?.status === "ok")
|
|
1516
|
+
cameThrough(offset);
|
|
1517
|
+
// Saved, its files refused as too many requests (BMJ Open's, 2026-11-23, the paper before gut.bmj.com's check):
|
|
1518
|
+
// the publisher's other papers wait all the same.
|
|
1519
|
+
const key = publisherOf(offset);
|
|
1520
|
+
if (result.supplements?.some((file) => file.reason === "http_429") && !blockedUntil.has(key) && !triedAgain.has(key)) {
|
|
1521
|
+
// Without 失败后自动重试: no pause; one of BLOCKED_IN_ROW in a row (blockedOnce).
|
|
1522
|
+
if (await retrying())
|
|
1523
|
+
pauseBlocked(key, `${id(offset)} 的附录:请求太多`);
|
|
1524
|
+
else
|
|
1525
|
+
blockedOnce(offset);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
else if (holding) {
|
|
1529
|
+
hold(offset);
|
|
1530
|
+
}
|
|
1531
|
+
else if (pausing) {
|
|
1532
|
+
pauseBlocked(publisherOf(offset), `${id(offset)}:人机验证没过或拦截页`, offset);
|
|
1533
|
+
}
|
|
1534
|
+
else if (blocked) {
|
|
1535
|
+
// Blocked again after its pause: this one fails 被网站拦截, its publisher's others are not tried. Without 失败后自动
|
|
1536
|
+
// 重试: this one fails, its publisher's others go on until BLOCKED_IN_ROW in a row (blockedOnce).
|
|
1537
|
+
if (triedAgain.has(publisherOf(offset)))
|
|
1538
|
+
giveUp(offset);
|
|
1539
|
+
else
|
|
1540
|
+
blockedOnce(offset);
|
|
1541
|
+
failed += 1;
|
|
1542
|
+
record(offset);
|
|
1543
|
+
settle(offset);
|
|
1544
|
+
}
|
|
1545
|
+
else if (withoutAccess(result) && !stoppedByUser(result) && (await otherSchools()).length) {
|
|
1546
|
+
withoutAccessYet.add(offset);
|
|
1547
|
+
settle(offset, "school");
|
|
1548
|
+
}
|
|
1549
|
+
else if (unexplainedFailure(result) && await retrying()) {
|
|
1550
|
+
unexplainedYet.add(offset);
|
|
1551
|
+
settle(offset, "school");
|
|
1552
|
+
}
|
|
1553
|
+
else {
|
|
1554
|
+
failed += 1;
|
|
1555
|
+
record(offset);
|
|
1556
|
+
settle(offset);
|
|
1557
|
+
}
|
|
1558
|
+
// The window's line, not for a paper that waits for the end or its publisher's pause (it would close the batch
|
|
1559
|
+
// early when last).
|
|
1560
|
+
if (!withoutAccessYet.has(offset) && !unexplainedYet.has(offset) && !pausing) {
|
|
1561
|
+
await reportBatchItem({ ...request, batch: { ...batch, index: batch.done + 1 } }, result, backend);
|
|
1562
|
+
}
|
|
1563
|
+
if (stoppedByUser(result)) {
|
|
1564
|
+
stopped = true;
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
// More to come: the lanes line goes on (after the last item the window has its end).
|
|
1568
|
+
if (openRunning || queue.length || lane)
|
|
1569
|
+
await reportProgress("");
|
|
1570
|
+
if (held.size)
|
|
1571
|
+
await reportHeld();
|
|
1572
|
+
takeRequests();
|
|
1573
|
+
await sendPapers();
|
|
1574
|
+
};
|
|
1575
|
+
const runEntitled = async (...args) => {
|
|
1576
|
+
inFlight += 1;
|
|
1577
|
+
try {
|
|
1578
|
+
return await runOne(...args);
|
|
1579
|
+
}
|
|
1580
|
+
finally {
|
|
1581
|
+
inFlight -= 1;
|
|
1582
|
+
}
|
|
1583
|
+
};
|
|
1584
|
+
/**
|
|
1585
|
+
* The batch's backend for a paper in window ``window`` (并行下载): its downloads name the window, and whether the batch
|
|
1586
|
+
* runs its papers at once (``parallel``: the first paper, before the batch knows, does not say).
|
|
1587
|
+
*/
|
|
1588
|
+
const windowBackend = (window, parallel = true) => backend && new Proxy(backend, {
|
|
1589
|
+
get(target, name) {
|
|
1590
|
+
if (name === "downloadLegalDoi") {
|
|
1591
|
+
return (request) => target.downloadLegalDoi({ ...request, window, ...(parallel ? { parallel: true } : {}) });
|
|
1592
|
+
}
|
|
1593
|
+
const value = Reflect.get(target, name, target);
|
|
1594
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
1595
|
+
},
|
|
1596
|
+
});
|
|
1597
|
+
/**
|
|
1598
|
+
* ``first``: the lane's first paper goes through it (window 0, the batch not knowing yet whether it runs papers at
|
|
1599
|
+
* once), ``taken`` told which paper that is.
|
|
1600
|
+
*/
|
|
1601
|
+
const entitledLane = async (first, taken) => {
|
|
1027
1602
|
for (;;) {
|
|
1028
1603
|
while (!queue.length && openRunning && !stopped)
|
|
1029
1604
|
await new Promise((resume) => { wake = resume; });
|
|
@@ -1039,97 +1614,208 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
1039
1614
|
held.get(publisherOf(offset)).push(offset);
|
|
1040
1615
|
continue;
|
|
1041
1616
|
}
|
|
1617
|
+
if (givenUp.has(publisherOf(offset))) {
|
|
1618
|
+
// Its publisher's site still blocks after the pause: not tried, 被网站拦截.
|
|
1619
|
+
untried(offset, "blocked_paused");
|
|
1620
|
+
if (finishing.delete(offset))
|
|
1621
|
+
openSettled += 1;
|
|
1622
|
+
else
|
|
1623
|
+
failed += 1;
|
|
1624
|
+
record(offset);
|
|
1625
|
+
settle(offset);
|
|
1626
|
+
await sendPapers();
|
|
1627
|
+
continue;
|
|
1628
|
+
}
|
|
1629
|
+
await reportLater();
|
|
1630
|
+
taken?.(offset);
|
|
1042
1631
|
if (finishing.has(offset)) {
|
|
1043
|
-
await finishOpenItem(offset);
|
|
1632
|
+
await finishOpenItem(offset, first ?? backend);
|
|
1044
1633
|
if (stopped)
|
|
1045
1634
|
return;
|
|
1635
|
+
if (first)
|
|
1636
|
+
return;
|
|
1046
1637
|
if (held.size)
|
|
1047
1638
|
await reportHeld();
|
|
1048
1639
|
takeRequests();
|
|
1049
1640
|
continue;
|
|
1050
1641
|
}
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1642
|
+
await runEntitled(offset, undefined, first);
|
|
1643
|
+
if (stopped)
|
|
1644
|
+
return;
|
|
1645
|
+
if (first)
|
|
1646
|
+
return; // the first paper alone: the batch asks for 同时下载 now (``lane``)
|
|
1647
|
+
}
|
|
1648
|
+
};
|
|
1649
|
+
/**
|
|
1650
|
+
* 并行下载 (user, 2026-11-29): the browser lane with several papers at once, each in a window of its own of the one
|
|
1651
|
+
* browser, as many and of which publishers as windowPlan.ts says. A window set free takes the next paper at once;
|
|
1652
|
+
* one no longer needed closes. Each paper goes as one after another would (``runEntitled``, ``finishOpenItem``), but
|
|
1653
|
+
* one its publisher's hour holds goes back and the window takes another publisher; only when nothing else is left
|
|
1654
|
+
* does the batch wait for that hour.
|
|
1655
|
+
*/
|
|
1656
|
+
const parallelLane = async (setting, publishersOf, first) => {
|
|
1657
|
+
const keyOf = (offset) => publisherKey(requests[offset].doi, publishersOf) || `paper:${offset}`;
|
|
1658
|
+
/** Each publisher's last journal taken, for one journal's papers one after another (``groupJournals``). */
|
|
1659
|
+
const lastOf = new Map();
|
|
1660
|
+
const plan = new WindowPlan(setting, keyOf, now, (waiting, key) => {
|
|
1661
|
+
if (!groupJournals)
|
|
1662
|
+
return 0;
|
|
1663
|
+
const at = waiting.findIndex((offset) => journalOfDoi(requests[offset].doi) === lastOf.get(key));
|
|
1664
|
+
return at < 0 ? 0 : at;
|
|
1665
|
+
});
|
|
1666
|
+
/** Papers that went to a window before: one coming back (its publisher's pause over, 登录并继续) goes first. */
|
|
1667
|
+
const dispatched = new Set();
|
|
1668
|
+
/** Each publisher's name as its hour was counted (rate_limited's hourlyPublisher), for its wait. */
|
|
1669
|
+
const hourlyName = new Map();
|
|
1670
|
+
/** Windows downloading now, each its paper's run; the windows opened (closed again when no longer needed). */
|
|
1671
|
+
const running = new Map();
|
|
1672
|
+
const opened = new Set([0]);
|
|
1673
|
+
const limited = (offset, waitSec, publisher) => {
|
|
1674
|
+
const key = keyOf(offset);
|
|
1675
|
+
if (publisher)
|
|
1676
|
+
hourlyName.set(key, publisher);
|
|
1677
|
+
plan.limit(key, now() + waitSec * 1000);
|
|
1678
|
+
plan.add(offset, true);
|
|
1679
|
+
log(`[批量] ${publisher || key} 一小时内的下载已到上限(防止学校被暂停访问),${clockTime(now() + waitSec * 1000)} 前改下其他出版社`);
|
|
1680
|
+
};
|
|
1681
|
+
/** The papers that came in (the open-access lane's, those going on again) join the plan. */
|
|
1682
|
+
const feed = () => {
|
|
1683
|
+
while (queue.length) {
|
|
1684
|
+
const offset = queue.shift();
|
|
1685
|
+
plan.add(offset, dispatched.has(offset));
|
|
1686
|
+
}
|
|
1687
|
+
};
|
|
1688
|
+
/** After a paper: the window's counts and lines (the backend counts none of a window's papers itself). */
|
|
1689
|
+
const reportCounts = () => {
|
|
1690
|
+
if (!backend?.reportBatchProgress || settledOk() + failed >= total)
|
|
1691
|
+
return reports;
|
|
1692
|
+
const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
|
|
1693
|
+
finished: false, lanes: lanes() });
|
|
1694
|
+
reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
|
|
1695
|
+
return reports;
|
|
1696
|
+
};
|
|
1697
|
+
/** One paper in ``window``: the paper's run, then the window is free for the next. */
|
|
1698
|
+
const inWindow = (window, offset, key) => (async () => {
|
|
1699
|
+
opened.add(window);
|
|
1700
|
+
dispatched.add(offset);
|
|
1701
|
+
lastOf.set(key, journalOfDoi(requests[offset].doi));
|
|
1064
1702
|
try {
|
|
1065
|
-
|
|
1066
|
-
|
|
1703
|
+
await reportLater();
|
|
1704
|
+
if (finishing.has(offset))
|
|
1705
|
+
await finishOpenItem(offset, windowBackend(window));
|
|
1706
|
+
else
|
|
1707
|
+
await runEntitled(offset, { backend: windowBackend(window), limited });
|
|
1067
1708
|
}
|
|
1068
1709
|
catch (error) {
|
|
1069
|
-
|
|
1070
|
-
log(`[批量] 机构下载出错(${id(offset)}):${result.attempts[0].message}`);
|
|
1710
|
+
log(`[批量] 机构下载出错(${id(offset)}):${error instanceof Error ? error.message : String(error)}`);
|
|
1071
1711
|
}
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
results[offset] = itemResult({
|
|
1080
|
-
...result,
|
|
1081
|
-
attempts: [...open.attempts, ...result.attempts],
|
|
1082
|
-
...(result.review ?? open.review ? { review: result.review ?? open.review } : {}),
|
|
1083
|
-
}, offset + 1, request);
|
|
1084
|
-
const school = result.attempts.find((attempt) => attempt.stage === "entitled_access");
|
|
1085
|
-
const holding = result.status !== "ok" && wentThrough(offset) && school?.code === LOGIN_LAPSED_CODE
|
|
1086
|
-
&& waitEnded.get(offset) === SCHOOL_SIGN_IN_PAGE && !stoppedByUser(result) && await canHold();
|
|
1087
|
-
// Its Markdown now, from the page this visit saved, or the open sources (only these
|
|
1088
|
-
// while its school login is in doubt).
|
|
1089
|
-
if (wantsMarkdown && !stoppedByUser(result)) {
|
|
1090
|
-
await markdownPastNetworkLoss(results[offset], recorded({ ...request, batch }, ledger, entries[offset]), searchers, holding ? undefined : pageVisit(backend, { ...request, batch, ...(away ? { shortUserWait: true } : {}) }, log, pause), watch);
|
|
1091
|
-
}
|
|
1092
|
-
if (result.status === "ok") {
|
|
1093
|
-
succeeded += 1;
|
|
1094
|
-
record(offset);
|
|
1095
|
-
settle(offset);
|
|
1096
|
-
if (school?.status === "ok")
|
|
1097
|
-
cameThrough(offset);
|
|
1098
|
-
}
|
|
1099
|
-
else if (holding) {
|
|
1100
|
-
hold(offset);
|
|
1712
|
+
finally {
|
|
1713
|
+
plan.done(key);
|
|
1714
|
+
running.delete(window);
|
|
1715
|
+
await reportCounts();
|
|
1716
|
+
if (held.size)
|
|
1717
|
+
await reportHeld();
|
|
1718
|
+
notify();
|
|
1101
1719
|
}
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1720
|
+
})();
|
|
1721
|
+
/** Windows no longer needed close (the first stays: it holds the browser). */
|
|
1722
|
+
const closeIdle = () => {
|
|
1723
|
+
const keep = Math.max(1, plan.target());
|
|
1724
|
+
for (const window of [...opened].sort((a, b) => b - a)) {
|
|
1725
|
+
if (opened.size <= keep)
|
|
1726
|
+
break;
|
|
1727
|
+
if (window === 0 || running.has(window))
|
|
1728
|
+
continue;
|
|
1729
|
+
opened.delete(window);
|
|
1730
|
+
void backend?.closeWindow?.(window);
|
|
1105
1731
|
}
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1732
|
+
};
|
|
1733
|
+
/** A paper the plan gave a window that needs none: its publisher held or given up. True when it was one. */
|
|
1734
|
+
const noWindow = async (offset, key) => {
|
|
1735
|
+
if (held.has(publisherOf(offset))) {
|
|
1736
|
+
held.get(publisherOf(offset)).push(offset);
|
|
1737
|
+
plan.done(key);
|
|
1738
|
+
return true;
|
|
1109
1739
|
}
|
|
1110
|
-
|
|
1111
|
-
|
|
1740
|
+
if (givenUp.has(publisherOf(offset))) {
|
|
1741
|
+
untried(offset, "blocked_paused");
|
|
1742
|
+
if (finishing.delete(offset))
|
|
1743
|
+
openSettled += 1;
|
|
1744
|
+
else
|
|
1745
|
+
failed += 1;
|
|
1112
1746
|
record(offset);
|
|
1113
1747
|
settle(offset);
|
|
1748
|
+
plan.done(key);
|
|
1749
|
+
await sendPapers();
|
|
1750
|
+
return true;
|
|
1114
1751
|
}
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1752
|
+
return false;
|
|
1753
|
+
};
|
|
1754
|
+
if (first) {
|
|
1755
|
+
// The batch's first paper, still downloading in window 0: its publisher has that window.
|
|
1756
|
+
const key = keyOf(first.offset);
|
|
1757
|
+
plan.begin(key);
|
|
1758
|
+
dispatched.add(first.offset);
|
|
1759
|
+
lastOf.set(key, journalOfDoi(requests[first.offset].doi));
|
|
1760
|
+
running.set(0, first.run.catch(() => undefined).finally(async () => {
|
|
1761
|
+
plan.done(key);
|
|
1762
|
+
running.delete(0);
|
|
1763
|
+
await reportCounts();
|
|
1764
|
+
notify();
|
|
1765
|
+
}));
|
|
1766
|
+
}
|
|
1767
|
+
for (;;) {
|
|
1768
|
+
takeRequests();
|
|
1769
|
+
feed();
|
|
1770
|
+
if (!stopped) {
|
|
1771
|
+
for (let next = plan.take(running.size); next; next = plan.take(running.size)) {
|
|
1772
|
+
if (await noWindow(next.item, next.key))
|
|
1773
|
+
continue;
|
|
1774
|
+
let window = 0;
|
|
1775
|
+
while (running.has(window))
|
|
1776
|
+
window += 1;
|
|
1777
|
+
running.set(window, inWindow(window, next.item, next.key));
|
|
1778
|
+
}
|
|
1118
1779
|
}
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1780
|
+
closeIdle();
|
|
1781
|
+
if (!running.size) {
|
|
1782
|
+
if (stopped || (!plan.waiting && !queue.length && !openRunning))
|
|
1783
|
+
break;
|
|
1784
|
+
if (queue.length)
|
|
1785
|
+
continue; // came in meanwhile
|
|
1786
|
+
const hour = plan.hourlyWait();
|
|
1787
|
+
if (hour) {
|
|
1788
|
+
// Only that publisher is left: the batch waits for its hour, going on at once when the setting lets it
|
|
1789
|
+
// or another paper comes in.
|
|
1790
|
+
const name = hourlyName.get(hour.key) ?? hour.key;
|
|
1791
|
+
log(`[批量] 只剩 ${name} 的篇目,一小时内的下载已到上限,${clockTime(hour.until)} 继续`);
|
|
1792
|
+
let sinceKeep = 0;
|
|
1793
|
+
let over = false;
|
|
1794
|
+
while (!over && !queue.length && !stopped) {
|
|
1795
|
+
const step = Math.min(HOURLY_RECHECK_EVERY_MS, Math.max(1, hour.until - now()));
|
|
1796
|
+
await pause(step);
|
|
1797
|
+
sinceKeep += step;
|
|
1798
|
+
const asked = backend?.hourlyWait ? await backend.hourlyWait(name).catch(() => undefined) : undefined;
|
|
1799
|
+
over = now() >= hour.until || asked?.waitSec === 0;
|
|
1800
|
+
if (sinceKeep >= KEEP_SESSION_EVERY_MS) {
|
|
1801
|
+
sinceKeep = 0;
|
|
1802
|
+
await backend?.keepSession?.().catch(() => false);
|
|
1803
|
+
}
|
|
1804
|
+
takeRequests();
|
|
1805
|
+
}
|
|
1806
|
+
// The hour over, or the setting lets it go on now; a paper come in meanwhile goes first, the limit kept.
|
|
1807
|
+
if (over)
|
|
1808
|
+
plan.lift(hour.key);
|
|
1809
|
+
continue;
|
|
1810
|
+
}
|
|
1124
1811
|
}
|
|
1125
|
-
|
|
1126
|
-
if (openRunning || queue.length)
|
|
1127
|
-
await reportProgress("");
|
|
1128
|
-
if (held.size)
|
|
1129
|
-
await reportHeld();
|
|
1130
|
-
takeRequests();
|
|
1131
|
-
await sendPapers();
|
|
1812
|
+
await new Promise((resume) => { wake = resume; });
|
|
1132
1813
|
}
|
|
1814
|
+
await Promise.all(running.values());
|
|
1815
|
+
// Stopped: the papers no window took are as the lane left them (not reached).
|
|
1816
|
+
for (const offset of plan.waitingItems())
|
|
1817
|
+
if (!queue.includes(offset))
|
|
1818
|
+
queue.push(offset);
|
|
1133
1819
|
};
|
|
1134
1820
|
if (mode === "entitled_only") {
|
|
1135
1821
|
for (const [offset, request] of requests.entries()) {
|
|
@@ -1143,32 +1829,96 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
1143
1829
|
else
|
|
1144
1830
|
ledger?.phase(`开放来源 ${total} 篇`);
|
|
1145
1831
|
void sendPapers();
|
|
1146
|
-
|
|
1832
|
+
// 同时下载 (the settings' 下载 page), asked once the browser has a first paper: its papers at once when the backend
|
|
1833
|
+
// can and the user set it, else one after another.
|
|
1834
|
+
let parallel;
|
|
1835
|
+
/** 同时下载 as the batch's backend says it, once it can (a backend process the batch has); undefined until then. */
|
|
1836
|
+
const askParallel = async () => {
|
|
1837
|
+
const said = backend?.parallelSetting ? await backend.parallelSetting().catch(() => undefined) : undefined;
|
|
1838
|
+
if (said === undefined)
|
|
1839
|
+
return;
|
|
1840
|
+
parallel = isParallel(said) ? said : null;
|
|
1841
|
+
if (parallel) {
|
|
1842
|
+
log(`[批量] 同时下载:不同出版社 ${parallel.publishers} 家 × 同一出版社 ${parallel.perPublisher} 篇`);
|
|
1843
|
+
ledger?.phase(`同时下载:${parallel.publishers} 家 × ${parallel.perPublisher} 篇`);
|
|
1844
|
+
}
|
|
1845
|
+
};
|
|
1846
|
+
const lane = async () => {
|
|
1847
|
+
while (!queue.length && openRunning && !stopped)
|
|
1848
|
+
await new Promise((resume) => { wake = resume; });
|
|
1849
|
+
if (!queue.length || stopped)
|
|
1850
|
+
return;
|
|
1851
|
+
if (parallel === undefined)
|
|
1852
|
+
await askParallel();
|
|
1853
|
+
if (parallel === undefined && backend?.parallelSetting) {
|
|
1854
|
+
// No backend process to ask yet (none is started for it): the first paper goes in window 0 and starts it, the
|
|
1855
|
+
// backend launching the browser as its own settings say. As soon as the backend is up the batch asks, and papers
|
|
1856
|
+
// at once open the other windows beside the first while it goes on (user, 2026-11-29: "为什么只有一篇在开始呢?",
|
|
1857
|
+
// they waited for it to end, 1 min 45 s on a school sign-in); one after another, the lane goes on after it. The
|
|
1858
|
+
// school's sign-in asks the user in one window at a time whatever the windows (user_turn.py).
|
|
1859
|
+
let firstOffset;
|
|
1860
|
+
let firstDone = false;
|
|
1861
|
+
const firstRun = entitledLane(windowBackend(0, false), (offset) => { firstOffset = offset; })
|
|
1862
|
+
.finally(() => { firstDone = true; });
|
|
1863
|
+
// ``parallel`` as askParallel left it (set there, not here).
|
|
1864
|
+
const said = () => parallel;
|
|
1865
|
+
while (!firstDone && said() === undefined && !stopped) {
|
|
1866
|
+
await Promise.race([firstRun.catch(() => undefined), pause(PARALLEL_ASK_EVERY_MS)]);
|
|
1867
|
+
if (!firstDone)
|
|
1868
|
+
await askParallel();
|
|
1869
|
+
}
|
|
1870
|
+
const setting = said();
|
|
1871
|
+
if (setting && !firstDone && firstOffset !== undefined) {
|
|
1872
|
+
return parallelLane(setting, setting.prefixes, { offset: firstOffset, run: firstRun });
|
|
1873
|
+
}
|
|
1874
|
+
await firstRun;
|
|
1875
|
+
if (stopped)
|
|
1876
|
+
return;
|
|
1877
|
+
if (parallel === undefined)
|
|
1878
|
+
await askParallel();
|
|
1879
|
+
parallel ??= null;
|
|
1880
|
+
return lane();
|
|
1881
|
+
}
|
|
1882
|
+
return parallel ? parallelLane(parallel, parallel.prefixes) : entitledLane();
|
|
1883
|
+
};
|
|
1884
|
+
await Promise.all([mode === "entitled_only" ? undefined : openLane(), lane()]);
|
|
1147
1885
|
// The held publishers wait for the user as long as it takes (user, 2026-11-15): the
|
|
1148
1886
|
// window shows 登录并继续 and 终止. 登录并继续 downloads them, the school's login asking
|
|
1149
1887
|
// the user where it lapsed; held again, the wait starts over. 终止 ends them as paused.
|
|
1888
|
+
// Those blocked by their site wait out their pause and go on by themselves (user, 2026-11-23).
|
|
1889
|
+
dropEmptyPauses();
|
|
1150
1890
|
if (held.size && !stopped) {
|
|
1151
|
-
const waiting =
|
|
1152
|
-
|
|
1153
|
-
|
|
1891
|
+
const waiting = heldList().reduce((sum, publisher) => sum + publisher.count, 0);
|
|
1892
|
+
if (waiting) {
|
|
1893
|
+
log(`[批量] 其他篇目已完成,暂停的 ${waiting} 篇等你回来:在进度窗口点“登录并继续”,或点“终止”结束`);
|
|
1894
|
+
ledger?.phase(`等你回来:暂停的 ${waiting} 篇`);
|
|
1895
|
+
}
|
|
1896
|
+
const blockedWaiting = [...blockedUntil.keys()].reduce((sum, key) => sum + (held.get(key)?.length ?? 0), 0);
|
|
1897
|
+
if (blockedWaiting) {
|
|
1898
|
+
log(`[批量] 其他篇目已完成,被网站拦截暂停的 ${blockedWaiting} 篇 ${clockTime(Math.min(...blockedUntil.values()))} 再试一次`);
|
|
1899
|
+
ledger?.phase(`等网站解除拦截:暂停的 ${blockedWaiting} 篇`);
|
|
1900
|
+
}
|
|
1154
1901
|
}
|
|
1155
1902
|
while (held.size && !stopped) {
|
|
1156
|
-
await reportHeld(true);
|
|
1903
|
+
await (heldList().length ? reportHeld(true) : reportBlocked());
|
|
1157
1904
|
await pause(HOLD_POLL_MS);
|
|
1158
1905
|
takeRequests();
|
|
1159
1906
|
if (queue.length && !stopped) {
|
|
1160
|
-
await
|
|
1907
|
+
await lane();
|
|
1161
1908
|
}
|
|
1909
|
+
dropEmptyPauses();
|
|
1162
1910
|
}
|
|
1163
1911
|
/** A paper's school stage once more, with another saved school when given; merged into its result. */
|
|
1164
|
-
const visitAgain = async (offset, school) => {
|
|
1912
|
+
const visitAgain = async (offset, school, lane) => {
|
|
1913
|
+
const visitBackend = lane ?? backend;
|
|
1914
|
+
await reportLater();
|
|
1165
1915
|
const request = { ...requests[offset], ...(school ? { school: school.entityId } : {}) };
|
|
1166
1916
|
const done = settledOk() + failed;
|
|
1167
1917
|
const batch = { id: batchId, index: done + 1, total, done, succeeded: settledOk(), failed };
|
|
1168
1918
|
log(school ? `[批量] 换${school.name}:${id(offset)}` : `[批量] 再试一次:${id(offset)}`);
|
|
1169
1919
|
let result;
|
|
1170
1920
|
try {
|
|
1171
|
-
result = await pastNetworkLoss(() => pastHourlyLimit(() => downloadWithFallback(searchers, watchingSchool(recorded({ ...request, batch, ...(away ? { shortUserWait: true } : {}) }, ledger, entries[offset]), offset), createTiers(
|
|
1921
|
+
result = await pastNetworkLoss(() => pastHourlyLimit(() => downloadWithFallback(searchers, watchingSchool(recorded({ ...request, batch, ...(away ? { shortUserWait: true } : {}) }, ledger, entries[offset]), offset), createTiers(visitBackend).filter((tier) => tier.stage === "entitled_access")), log, pause, backend), watch);
|
|
1172
1922
|
}
|
|
1173
1923
|
catch (error) {
|
|
1174
1924
|
result = laneError("entitled_access", error);
|
|
@@ -1185,27 +1935,78 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
1185
1935
|
const item = results[offset];
|
|
1186
1936
|
// Its Markdown from the page this visit saved, unless the open sources gave it already.
|
|
1187
1937
|
if (wantsMarkdown && result.status === "ok" && item.markdown?.status !== "ok") {
|
|
1188
|
-
await markdownPastNetworkLoss(item, recorded({ ...request, batch }, ledger, entries[offset]), searchers, pageVisit(
|
|
1938
|
+
await markdownPastNetworkLoss(item, recorded({ ...request, batch }, ledger, entries[offset]), searchers, pageVisit(visitBackend, { ...request, batch, ...(away ? { shortUserWait: true } : {}) }, log, pause), watch);
|
|
1189
1939
|
}
|
|
1190
1940
|
if (stoppedByUser(result))
|
|
1191
1941
|
stopped = true;
|
|
1192
|
-
|
|
1193
|
-
|
|
1942
|
+
// Its publisher's site blocks the batch's end too: no more visits go there (no pause at the end).
|
|
1943
|
+
if (siteBlocked(result))
|
|
1944
|
+
giveUp(offset);
|
|
1194
1945
|
return item;
|
|
1195
1946
|
};
|
|
1947
|
+
/** Not visited again at the batch's end: its publisher's site still blocks (``giveUp``). */
|
|
1948
|
+
const visitable = (offset) => !givenUp.has(publisherOf(offset));
|
|
1196
1949
|
/** The window's line for a paper finished at the end (the counts before it, as ``reportBatchItem`` takes them). */
|
|
1197
1950
|
const reportSettled = async (offset) => {
|
|
1198
1951
|
const done = settledOk() + failed;
|
|
1199
1952
|
await reportBatchItem({ ...requests[offset], batch: { id: batchId, index: done + 1, total, done, succeeded: settledOk(), failed } }, results[offset], backend);
|
|
1200
1953
|
};
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1954
|
+
/**
|
|
1955
|
+
* The batch's end (原因不明 once more, the papers without access with another school): in windows by the lane's
|
|
1956
|
+
* rules when its papers ran at once (user, 2026-11-29: "重试的内容不会继续并行吗?", they went one after another),
|
|
1957
|
+
* else one after another. ``anotherSchool``: the first paper alone in window 0, the others after it: going to another
|
|
1958
|
+
* school starts the browser again (the last school's sign-in forgotten), and a paper beginning meanwhile in another
|
|
1959
|
+
* window lost its browser (user's Mac, 2026-11-29: 浏览器被关闭, 2.5 s into it, in both rounds).
|
|
1960
|
+
*/
|
|
1961
|
+
const atTheEnd = async (offsets, visit, anotherSchool = false) => {
|
|
1962
|
+
if (!parallel) {
|
|
1963
|
+
for (const offset of offsets) {
|
|
1964
|
+
if (stopped)
|
|
1965
|
+
return;
|
|
1966
|
+
await visit(offset);
|
|
1967
|
+
}
|
|
1968
|
+
return;
|
|
1969
|
+
}
|
|
1970
|
+
if (anotherSchool && offsets.length > 1) {
|
|
1971
|
+
await visit(offsets[0], windowBackend(0)).catch((error) => {
|
|
1972
|
+
log(`[批量] 机构下载出错(${id(offsets[0])}):${error instanceof Error ? error.message : String(error)}`);
|
|
1973
|
+
});
|
|
1974
|
+
offsets = offsets.slice(1);
|
|
1975
|
+
}
|
|
1976
|
+
const prefixes = parallel.prefixes;
|
|
1977
|
+
const plan = new WindowPlan(parallel, (offset) => publisherKey(requests[offset].doi, prefixes) || `paper:${offset}`, now);
|
|
1978
|
+
for (const offset of offsets)
|
|
1979
|
+
plan.add(offset);
|
|
1980
|
+
const running = new Map();
|
|
1981
|
+
while (!stopped) {
|
|
1982
|
+
for (let next = plan.take(running.size); next && !stopped; next = plan.take(running.size)) {
|
|
1983
|
+
const { item, key } = next;
|
|
1984
|
+
let window = 0;
|
|
1985
|
+
while (running.has(window))
|
|
1986
|
+
window += 1;
|
|
1987
|
+
running.set(window, visit(item, windowBackend(window)).catch((error) => {
|
|
1988
|
+
log(`[批量] 机构下载出错(${id(item)}):${error instanceof Error ? error.message : String(error)}`);
|
|
1989
|
+
}).finally(() => {
|
|
1990
|
+
plan.done(key);
|
|
1991
|
+
running.delete(window);
|
|
1992
|
+
}));
|
|
1993
|
+
}
|
|
1994
|
+
if (!running.size)
|
|
1207
1995
|
break;
|
|
1208
|
-
|
|
1996
|
+
await Promise.race(running.values());
|
|
1997
|
+
}
|
|
1998
|
+
await Promise.all(running.values());
|
|
1999
|
+
};
|
|
2000
|
+
// 原因不明 once more, the default school still signed in, before any other school (user, 2026-11-22). Not where the
|
|
2001
|
+
// site still blocks: those end as they were.
|
|
2002
|
+
const unexplainedAgain = [...unexplainedYet].filter(visitable);
|
|
2003
|
+
if (unexplainedAgain.length && !stopped) {
|
|
2004
|
+
log(`[批量] 原因不明的 ${unexplainedAgain.length} 篇再试一次`);
|
|
2005
|
+
ledger?.phase(`原因不明的 ${unexplainedAgain.length} 篇再试一次`);
|
|
2006
|
+
await atTheEnd(unexplainedAgain, async (offset, lane) => {
|
|
2007
|
+
if (stopped || !visitable(offset))
|
|
2008
|
+
return;
|
|
2009
|
+
const item = await visitAgain(offset, undefined, lane);
|
|
1209
2010
|
unexplainedYet.delete(offset);
|
|
1210
2011
|
if (!stopped && item.status !== "ok" && withoutAccess(item) && (await otherSchools()).length) {
|
|
1211
2012
|
withoutAccessYet.add(offset);
|
|
@@ -1220,7 +2021,7 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
1220
2021
|
settle(offset);
|
|
1221
2022
|
}
|
|
1222
2023
|
await sendPapers();
|
|
1223
|
-
}
|
|
2024
|
+
});
|
|
1224
2025
|
}
|
|
1225
2026
|
for (const offset of unexplainedYet) {
|
|
1226
2027
|
await reportSettled(offset);
|
|
@@ -1228,9 +2029,42 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
1228
2029
|
record(offset);
|
|
1229
2030
|
}
|
|
1230
2031
|
unexplainedYet.clear();
|
|
1231
|
-
|
|
1232
|
-
const
|
|
1233
|
-
|
|
2032
|
+
/** An open-access paper's Markdown or files done, at the end: its PDF stood all along. */
|
|
2033
|
+
const partsSettled = async (offset) => {
|
|
2034
|
+
await reportSettled(offset);
|
|
2035
|
+
openSettled += 1;
|
|
2036
|
+
record(offset);
|
|
2037
|
+
settle(offset);
|
|
2038
|
+
};
|
|
2039
|
+
/** A paper waiting for its Markdown or files (``partsYet``) with ``school``: those alone, its PDF standing. */
|
|
2040
|
+
const partsWithSchool = async (offset, school, lane) => {
|
|
2041
|
+
const visitBackend = lane ?? backend;
|
|
2042
|
+
await reportLater();
|
|
2043
|
+
const item = results[offset];
|
|
2044
|
+
const done = settledOk() + failed;
|
|
2045
|
+
const request = { ...requests[offset], school: school.entityId,
|
|
2046
|
+
batch: { id: batchId, index: done + 1, total, done, succeeded: settledOk(), failed }, ...(away ? { shortUserWait: true } : {}) };
|
|
2047
|
+
log(`[批量] 换${school.name}补${partsNamed(item)}:${id(offset)}`);
|
|
2048
|
+
await partsAgain(item, recorded(request, ledger, entries[offset]), visitBackend, searchers, pageVisit(visitBackend, request, log, pause, (trace) => learnPublisher(offset, trace?.publisher)), watch);
|
|
2049
|
+
if (stoppedByUser(item))
|
|
2050
|
+
stopped = true;
|
|
2051
|
+
// Its publisher's site blocks the batch's end: no more visits go there.
|
|
2052
|
+
if (item.markdown?.code && blockedBySite(item.markdown.code))
|
|
2053
|
+
giveUp(offset);
|
|
2054
|
+
if (!stopped && partsWithoutAccess(item))
|
|
2055
|
+
return;
|
|
2056
|
+
partsYet.delete(offset);
|
|
2057
|
+
await partsSettled(offset);
|
|
2058
|
+
await sendPapers();
|
|
2059
|
+
};
|
|
2060
|
+
// The papers without access go to the other saved schools, one school at a time; not where the site still blocks
|
|
2061
|
+
// (they end without access, with the schools tried so far).
|
|
2062
|
+
const withSchool = async (offset, school, lane) => {
|
|
2063
|
+
if (stopped || !visitable(offset))
|
|
2064
|
+
return;
|
|
2065
|
+
if (partsYet.has(offset))
|
|
2066
|
+
return partsWithSchool(offset, school, lane);
|
|
2067
|
+
const item = await visitAgain(offset, school, lane);
|
|
1234
2068
|
schoolsTried.set(offset, (schoolsTried.get(offset) ?? 1) + 1);
|
|
1235
2069
|
if (!stopped && withoutAccess(item)) {
|
|
1236
2070
|
triedSchools(item, schoolsTried.get(offset));
|
|
@@ -1247,17 +2081,18 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
1247
2081
|
}
|
|
1248
2082
|
await sendPapers();
|
|
1249
2083
|
};
|
|
1250
|
-
if (withoutAccessYet.size && !stopped) {
|
|
1251
|
-
await laterSchools(await otherSchools(), () => [...withoutAccessYet], async (school, count) => {
|
|
2084
|
+
if ((withoutAccessYet.size || partsYet.size) && !stopped) {
|
|
2085
|
+
await laterSchools(await otherSchools(), () => [...withoutAccessYet, ...partsYet].filter(visitable), async (school, count) => {
|
|
1252
2086
|
log(`[批量] 没权限的 ${count} 篇换${school.name}再试`);
|
|
1253
2087
|
ledger?.phase(`没权限的 ${count} 篇换${school.name}再试`);
|
|
1254
2088
|
if (!backend?.reportBatchProgress)
|
|
1255
2089
|
return;
|
|
1256
|
-
|
|
1257
|
-
|
|
2090
|
+
// The card names the school a moment (switchTo), in place of a line saying so.
|
|
2091
|
+
const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
|
|
2092
|
+
finished: false, switchTo: school.name, laterOnly: true });
|
|
1258
2093
|
reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
|
|
1259
2094
|
await reports;
|
|
1260
|
-
}, withSchool, () => stopped);
|
|
2095
|
+
}, withSchool, () => stopped, (offsets, each) => atTheEnd(offsets, each, true));
|
|
1261
2096
|
}
|
|
1262
2097
|
// Without access with every school (or the batch stopped first): failed.
|
|
1263
2098
|
for (const offset of withoutAccessYet) {
|
|
@@ -1266,6 +2101,20 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
|
|
|
1266
2101
|
record(offset);
|
|
1267
2102
|
}
|
|
1268
2103
|
withoutAccessYet.clear();
|
|
2104
|
+
// Their Markdown or files without access with every school: saved all the same, their PDF standing.
|
|
2105
|
+
for (const offset of partsYet)
|
|
2106
|
+
await partsSettled(offset);
|
|
2107
|
+
partsYet.clear();
|
|
2108
|
+
// Markdown saved without some figures: those once more, unless the user stopped the batch (user, 2026-11-23);
|
|
2109
|
+
// recorded before a stop's own marks on the papers not recorded yet.
|
|
2110
|
+
figuresTried = true;
|
|
2111
|
+
if (!stopped) {
|
|
2112
|
+
await figuresAtTheEnd([...figuresLater].map((offset) => ({ result: results[offset], request: recorded(requests[offset], ledger, entries[offset]) })), log, ledger);
|
|
2113
|
+
}
|
|
2114
|
+
for (const offset of figuresLater) {
|
|
2115
|
+
record(offset);
|
|
2116
|
+
settle(offset);
|
|
2117
|
+
}
|
|
1269
2118
|
await reports;
|
|
1270
2119
|
// Stopped in the window: the items neither lane reached end as not downloaded, the held as paused.
|
|
1271
2120
|
if (stopped) {
|