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
|
@@ -5,7 +5,9 @@ keeps what it needs, in two steps that never load the article page again:
|
|
|
5
5
|
|
|
6
6
|
1. ``read_page``, on the article page before the PDF is captured: once the page has
|
|
7
7
|
stopped changing, and only when it names this DOI and shows the full text (the
|
|
8
|
-
adapter's ``fulltext_shown_js``, waited for up to 15 s: a body may come after
|
|
8
|
+
adapter's ``fulltext_shown_js``, waited for up to 15 s: a body may come after; not waited for
|
|
9
|
+
when the adapter's ``fulltext_withheld_js`` finds the site saying this reader gets the abstract
|
|
10
|
+
alone), the page's HTML and the figure images it lists
|
|
9
11
|
(the adapter's ``fulltext_images_js``). An adapter's ``fulltext_prepare_js`` runs
|
|
10
12
|
first, in the page's own world (ScienceDirect keeps each formula's MathML), given the
|
|
11
13
|
text of the document its ``fulltext_prepare_source`` names (PLOS's article XML, which the
|
|
@@ -62,6 +64,27 @@ _PAGE_DOI_JS = """() => {
|
|
|
62
64
|
}"""
|
|
63
65
|
|
|
64
66
|
|
|
67
|
+
def paragraph_text_js(paragraphs: str, outside: str, threshold: str, *, root: str = "") -> str:
|
|
68
|
+
"""A ``fulltext_shown_js`` that counts the article's paragraph text: the elements
|
|
69
|
+
``paragraphs`` selects (inside the first ``root`` when one is given: no full text without
|
|
70
|
+
it), those inside ``outside`` aside, their text's length compared with ``threshold``
|
|
71
|
+
("> 500", ">= 200": each adapter's own). The selectors are written in single quotes."""
|
|
72
|
+
if not re.fullmatch(r">=? \d+", threshold):
|
|
73
|
+
raise ValueError(f"threshold is a comparison with a number: {threshold!r}")
|
|
74
|
+
if any("'" in selector or "\\" in selector for selector in (paragraphs, outside, root)):
|
|
75
|
+
raise ValueError("a selector with a quote or a backslash")
|
|
76
|
+
lines = ["() => {"]
|
|
77
|
+
scope = "document"
|
|
78
|
+
if root:
|
|
79
|
+
lines += [f" const root = document.querySelector('{root}');", " if (!root) return false;"]
|
|
80
|
+
scope = "root"
|
|
81
|
+
lines.append(f" const text = [...{scope}.querySelectorAll('{paragraphs}')]")
|
|
82
|
+
if outside:
|
|
83
|
+
lines.append(f" .filter((p) => !p.closest('{outside}'))")
|
|
84
|
+
lines += [" .reduce((total, p) => total + (p.textContent || '').length, 0);", f" return text {threshold};", "}"]
|
|
85
|
+
return "\n".join(lines)
|
|
86
|
+
|
|
87
|
+
|
|
65
88
|
# For an adapter's ``fulltext_prepare_js`` on a MathJax page that keeps no MathML in the
|
|
66
89
|
# DOM (ScienceDirect's MathJax 4, Wiley's lazy MathJax 4.1, 2026-11-14): each formula's
|
|
67
90
|
# source written onto its element as data-original-mathml, which PaperSearch reads. A
|
|
@@ -92,6 +115,16 @@ MATHJAX_SOURCES_JS = r"""async () => {
|
|
|
92
115
|
}"""
|
|
93
116
|
|
|
94
117
|
|
|
118
|
+
def _names_doi(named: str, doi: str) -> bool:
|
|
119
|
+
"""Whether the DOI a page names (``_PAGE_DOI_JS``) is this one, or the page names none. A
|
|
120
|
+
DOI written as the end of a sentence is the same DOI: the AMA Journal of Ethics writes
|
|
121
|
+
"10.1001/amajethics.2025.884." in its citation_doi too, and its pages were taken for another
|
|
122
|
+
article's (other_article, 2026-11-22)."""
|
|
123
|
+
named = normalize_doi(named).lower()
|
|
124
|
+
wanted = (normalize_doi(doi) or "").lower()
|
|
125
|
+
return not named or named == wanted or named.rstrip(".") == wanted.rstrip(".")
|
|
126
|
+
|
|
127
|
+
|
|
95
128
|
def page_dir(output_dir: Path, doi: str) -> Path:
|
|
96
129
|
return Path(output_dir) / (re.sub(r"[^A-Za-z0-9._-]+", "_", doi) + "_fulltext_page")
|
|
97
130
|
|
|
@@ -192,13 +225,19 @@ def read_page(page: Any, doi: str, adapter: Any, *, sample: bool = False) -> tup
|
|
|
192
225
|
shown_js = _SAMPLE_SHOWN_JS if general else own
|
|
193
226
|
if not wait_stable(page):
|
|
194
227
|
return None, "page_not_stable"
|
|
195
|
-
|
|
196
|
-
if named and named != (normalize_doi(doi) or "").lower():
|
|
228
|
+
if not _names_doi(str(page.evaluate(_PAGE_DOI_JS) or ""), doi):
|
|
197
229
|
return None, "other_article"
|
|
198
230
|
if not sample:
|
|
199
231
|
pdf_only = str(page.evaluate(_PDF_ONLY_JS) or "")
|
|
200
232
|
if pdf_only:
|
|
201
233
|
return None, f"fulltext_not_shown: {PDF_ONLY}: {pdf_only}"
|
|
234
|
+
# The site's own words that this reader gets the abstract alone (Optica's "Not Accessible"
|
|
235
|
+
# box): no body is coming, not a page to wait SHOWN_WAIT_MS on. The school's login may
|
|
236
|
+
# still open it (the read after the login is the caller's).
|
|
237
|
+
withheld_js = getattr(adapter, "fulltext_withheld_js", None)
|
|
238
|
+
withheld = " ".join(str(page.evaluate(withheld_js) or "").split()) if withheld_js and own else ""
|
|
239
|
+
if withheld:
|
|
240
|
+
return None, f"fulltext_not_shown: {withheld[:160]}"
|
|
202
241
|
# A site may show the abstract first and fetch the body after it (ScienceDirect: the
|
|
203
242
|
# page stood still with "body":{} in its state, 2026-11-14): wait for the full text.
|
|
204
243
|
from .batch_common import pump_until
|
|
@@ -321,11 +360,19 @@ def save_page(read: dict[str, Any], output_dir: Path, doi: str, request: Any, *,
|
|
|
321
360
|
failed.append({"url": url, "reason": "not_an_image"})
|
|
322
361
|
continue
|
|
323
362
|
body = bytearray()
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
363
|
+
try:
|
|
364
|
+
whole = True
|
|
365
|
+
for chunk in response.chunks():
|
|
366
|
+
body.extend(chunk)
|
|
367
|
+
if total + len(body) > MAX_BYTES or clock() > deadline:
|
|
368
|
+
whole = False
|
|
369
|
+
break
|
|
370
|
+
except Exception as exc:
|
|
371
|
+
# A read that fails part way (PLOS's image host timing out, 2026-11-23) is recorded like
|
|
372
|
+
# one that could not start: this figure is missing, the page and the PDF go on.
|
|
373
|
+
failed.append({"url": url, "reason": type(exc).__name__})
|
|
374
|
+
continue
|
|
375
|
+
if whole:
|
|
329
376
|
if not body:
|
|
330
377
|
failed.append({"url": url, "reason": "empty"})
|
|
331
378
|
continue
|
|
@@ -18,6 +18,20 @@ from ..publishers.profiles import PublisherProfile
|
|
|
18
18
|
|
|
19
19
|
PDF_LINK_TEXT_MARKERS = ("pdf", "download pdf", "full text pdf", "view pdf")
|
|
20
20
|
PDF_URL_MARKERS = (".pdf", "/pdf", "/epdf", "/pdfdirect", "/pdfft", "download=true")
|
|
21
|
+
# Open Journal Systems' galley file: /<journal>/article/download/<article>/<galley>[/<file>],
|
|
22
|
+
# an address with no "pdf" in it. Its citation_pdf_url and the galley's Download link are this
|
|
23
|
+
# address; the article's "View PDF" (/article/view/<article>/<galley>) is a page around the PDF
|
|
24
|
+
# (Via Medica's Reports of Practical Oncology and Radiotherapy: the click ended on that page and
|
|
25
|
+
# nothing was tried after it, 2026-11-23). The article part can be the article's name instead of
|
|
26
|
+
# its number (Fringe Global's JSIHS: /article/download/ai-and-edge-analytics-.../239/1341, 2026-11-24).
|
|
27
|
+
GALLEY_DOWNLOAD_PATH = re.compile(r"/article/download/[^/]+/\d+(?:/\d+)?/?$")
|
|
28
|
+
# An Open Journal Systems article page or its galley's page: /article/view/<article>[/<galley>].
|
|
29
|
+
OJS_VIEW_PATH = re.compile(r"/article/view/([^/]+)(?:/\d+)?/?$")
|
|
30
|
+
# bepress Digital Commons' file: /cgi/viewcontent.cgi?article=<n>&context=<journal>, its
|
|
31
|
+
# bepress_citation_pdf_url (Osgoode Hall Law Journal: not taken as a PDF address, 2026-11-24).
|
|
32
|
+
VIEWCONTENT_PATH = re.compile(r"/cgi/viewcontent\.cgi$")
|
|
33
|
+
# Platform paths that serve the article's file with no "pdf" in them.
|
|
34
|
+
PLATFORM_FILE_PATH = re.compile(f"{GALLEY_DOWNLOAD_PATH.pattern}|{VIEWCONTENT_PATH.pattern}")
|
|
21
35
|
PDF_JS_DEFAULT_URL_RE = re.compile(
|
|
22
36
|
r"PDFViewerApplicationOptions\.set\(\s*['\"]defaultUrl['\"]\s*,\s*['\"]([^'\"]+)['\"]",
|
|
23
37
|
flags=re.IGNORECASE,
|
|
@@ -209,7 +223,8 @@ def is_pdf_candidate_url(profile: PublisherProfile, url: str) -> bool:
|
|
|
209
223
|
if verdict is not None:
|
|
210
224
|
return verdict
|
|
211
225
|
lower = url.lower()
|
|
212
|
-
return lower.endswith(".pdf") or any(marker.lower() in lower for marker in profile.pdf_url_markers)
|
|
226
|
+
return (lower.endswith(".pdf") or any(marker.lower() in lower for marker in profile.pdf_url_markers)
|
|
227
|
+
or bool(PLATFORM_FILE_PATH.search(urlparse(url).path)))
|
|
213
228
|
|
|
214
229
|
|
|
215
230
|
def is_thieme_article_pdf_url(url: str, doi: str = "") -> bool:
|
|
@@ -24,6 +24,7 @@ from urllib.parse import unquote, urlparse
|
|
|
24
24
|
from ..adapters.base import SupplementLink
|
|
25
25
|
from ..browser.watchdog import BrowserUnresponsive, BrowserOperationTimeout
|
|
26
26
|
from ..browser import watchdog
|
|
27
|
+
from .. import progress_reporter
|
|
27
28
|
from ..entitlements import UserMarkedNoEntitlement, UserSkippedArticle, UserStoppedBatch
|
|
28
29
|
|
|
29
30
|
MAX_FILES = 50
|
|
@@ -242,7 +243,11 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
242
243
|
size = 0
|
|
243
244
|
try:
|
|
244
245
|
chunks = response.chunks() if callable(getattr(response, "chunks", None)) else [response.body()]
|
|
245
|
-
|
|
246
|
+
# Which file of how many, its size and how far it has come, on the window's card (user,
|
|
247
|
+
# 2026-11-26: a big one is seen coming, or seen stopped).
|
|
248
|
+
with tempfile.NamedTemporaryFile(dir=target, prefix=".supplement-", suffix=".part", delete=False) as fh, \
|
|
249
|
+
progress_reporter.Transfer("supplement", length, index=index + 1, count=len(unique),
|
|
250
|
+
name=name) as arriving:
|
|
246
251
|
temporary = Path(fh.name)
|
|
247
252
|
for chunk in chunks:
|
|
248
253
|
_check_interrupted()
|
|
@@ -253,6 +258,7 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
253
258
|
continue
|
|
254
259
|
size += len(chunk)
|
|
255
260
|
fh.write(chunk)
|
|
261
|
+
arriving.add(len(chunk))
|
|
256
262
|
last_progress = now
|
|
257
263
|
if activity is not None:
|
|
258
264
|
activity()
|
|
@@ -206,12 +206,40 @@ def request_action(current: str, action: str, run_id: str = "") -> None:
|
|
|
206
206
|
_write_json(control_path(), data)
|
|
207
207
|
|
|
208
208
|
|
|
209
|
+
def way_path() -> Path:
|
|
210
|
+
return control_path().with_name("way.json")
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def request_way(current: str, index: int, run_id: str = "") -> None:
|
|
214
|
+
"""Written by the progress window when the user picks one of the ways a sign-in chooser offers (OpenAthens's
|
|
215
|
+
"Choose how to sign in", user 2026-11-29): its index, for the paper it was asked for."""
|
|
216
|
+
_write_json(way_path(), {"current": current, "index": int(index), "run_id": run_id, "at": time.time()})
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def take_way(doi: str, since: float) -> int | None:
|
|
220
|
+
"""The way the user picked for this paper (asked for after ``since``), consumed once; None when none yet."""
|
|
221
|
+
data = _read_json(way_path())
|
|
222
|
+
if not data or str(data.get("current", "")).lower() != (doi or "").lower():
|
|
223
|
+
return None
|
|
224
|
+
try:
|
|
225
|
+
at, index = float(data.get("at", 0)), int(data.get("index"))
|
|
226
|
+
except (TypeError, ValueError):
|
|
227
|
+
return None
|
|
228
|
+
if at < since:
|
|
229
|
+
return None
|
|
230
|
+
try:
|
|
231
|
+
way_path().unlink()
|
|
232
|
+
except OSError:
|
|
233
|
+
pass
|
|
234
|
+
return index
|
|
235
|
+
|
|
236
|
+
|
|
209
237
|
def resume_path() -> Path:
|
|
210
238
|
return control_path().with_name("resume.json")
|
|
211
239
|
|
|
212
240
|
|
|
213
241
|
def request_resume(key: str, batch_id: str) -> None:
|
|
214
|
-
"""The user asked the batch to go on with a publisher it holds (
|
|
242
|
+
"""The user asked the batch to go on with a publisher it holds (its key: its name, else its DOI prefix)."""
|
|
215
243
|
data = _read_json(resume_path())
|
|
216
244
|
keys = list(data.get("keys") or []) if data.get("batch_id") == batch_id else []
|
|
217
245
|
if key not in keys:
|
|
@@ -12,11 +12,6 @@ import requests
|
|
|
12
12
|
|
|
13
13
|
from .network import fetch
|
|
14
14
|
|
|
15
|
-
try:
|
|
16
|
-
from bs4 import BeautifulSoup
|
|
17
|
-
except Exception:
|
|
18
|
-
BeautifulSoup = None
|
|
19
|
-
|
|
20
15
|
|
|
21
16
|
def is_pdf_file(path: Path) -> bool:
|
|
22
17
|
try:
|
|
@@ -156,6 +151,13 @@ def iter_urls(obj: Any) -> Any:
|
|
|
156
151
|
|
|
157
152
|
|
|
158
153
|
def extract_pdf_url_from_html(html: str, base_url: str) -> str | None:
|
|
154
|
+
"""The PDF address the page states about itself, or ``None``.
|
|
155
|
+
|
|
156
|
+
Only ``citation_pdf_url``: the page's other links are references, related
|
|
157
|
+
papers and other documents. One guessed from them was a UN ageing-policy PDF
|
|
158
|
+
for a Journal of Global Aging article (2026-11-24), so no address is better
|
|
159
|
+
than a wrong one.
|
|
160
|
+
"""
|
|
159
161
|
urls: list[str] = []
|
|
160
162
|
for match in re.finditer(
|
|
161
163
|
r"""<meta[^>]+name=["']citation_pdf_url["'][^>]+content=["']([^"']+)["']""", html, re.I
|
|
@@ -165,22 +167,29 @@ def extract_pdf_url_from_html(html: str, base_url: str) -> str | None:
|
|
|
165
167
|
r"""<meta[^>]+content=["']([^"']+)["'][^>]+name=["']citation_pdf_url["']""", html, re.I
|
|
166
168
|
):
|
|
167
169
|
urls.append(urllib.parse.urljoin(base_url, match.group(1)))
|
|
168
|
-
if BeautifulSoup is not None:
|
|
169
|
-
soup = BeautifulSoup(html, "html.parser")
|
|
170
|
-
for tag in soup.find_all(["iframe", "embed", "a"]):
|
|
171
|
-
candidate = tag.get("src") or tag.get("href")
|
|
172
|
-
if candidate:
|
|
173
|
-
urls.append(urllib.parse.urljoin(base_url, candidate))
|
|
174
|
-
else:
|
|
175
|
-
for match in re.finditer(r"""(?:src|href)=["']([^"']+)["']""", html, re.I):
|
|
176
|
-
urls.append(urllib.parse.urljoin(base_url, match.group(1)))
|
|
177
|
-
|
|
178
170
|
for url in dedupe(urls):
|
|
179
|
-
|
|
171
|
+
# The page's own declaration, not a guessed link: the plausibility rules
|
|
172
|
+
# above are for links read off a page, and they reject the publisher's
|
|
173
|
+
# own "/journals/…/article-p181.pdf" (Bristol, 2026-11-25).
|
|
174
|
+
if url.startswith(("http://", "https://")) and not url.startswith("data:"):
|
|
180
175
|
return url
|
|
181
176
|
return None
|
|
182
177
|
|
|
183
178
|
|
|
179
|
+
def pdf_links_from_html(html: str, base_url: str) -> list[str]:
|
|
180
|
+
"""Every address in the page that could be a PDF, for the caller to judge.
|
|
181
|
+
|
|
182
|
+
The choice is the caller's, by the same rule its usual address flow uses:
|
|
183
|
+
a link here is only a candidate, not this article's PDF.
|
|
184
|
+
"""
|
|
185
|
+
if not html:
|
|
186
|
+
return []
|
|
187
|
+
urls: list[str] = []
|
|
188
|
+
for match in re.finditer(r"""(?:src|href)=["']([^"']+)["']""", html, re.I):
|
|
189
|
+
urls.append(urllib.parse.urljoin(base_url, match.group(1)))
|
|
190
|
+
return [url for url in dedupe(urls) if is_plausible_pdf_url(url)]
|
|
191
|
+
|
|
192
|
+
|
|
184
193
|
def download_pdf(
|
|
185
194
|
url: str,
|
|
186
195
|
output_path: Path,
|
|
@@ -172,7 +172,7 @@ class Api:
|
|
|
172
172
|
self._mac_drag: _MacDrag | None = None # macOS: presses tracked natively (main)
|
|
173
173
|
self._native_drag = False # this drag follows the mouse natively, not the page
|
|
174
174
|
# papers.json: when read, its batch, the sites not yet supported its pages came from.
|
|
175
|
-
self._papers_seen: tuple[int, str
|
|
175
|
+
self._papers_seen: tuple[int, str] = (0, "")
|
|
176
176
|
self._hovering = False
|
|
177
177
|
self._layout: tuple[int, bool, Rect, Rect] | None = None
|
|
178
178
|
self._closed = False
|
|
@@ -195,15 +195,34 @@ class Api:
|
|
|
195
195
|
# 成功, 失败 and 剩余 open their lists once the caller has sent this batch's papers.
|
|
196
196
|
if snapshot and snapshot.get("batch_id") and self._papers_batch() == snapshot["batch_id"]:
|
|
197
197
|
shown["lists"] = True
|
|
198
|
-
# The sites not yet supported its pages came from: a line while it runs (2026-11-16).
|
|
199
|
-
if shown.get("mode") in ("running", "attention") and self._papers_seen[2]:
|
|
200
|
-
shown["sites"] = self._papers_seen[2]
|
|
201
198
|
except Exception:
|
|
202
199
|
shown = {"mode": "idle"}
|
|
200
|
+
if shown.get("mode") in ("running", "attention"):
|
|
201
|
+
shown["holds"] = self._holds()
|
|
203
202
|
shown["lang"] = self._lang
|
|
204
203
|
request = take_settings_request() # `paper-search-school settings`: show the settings
|
|
205
204
|
return {**shown, "open_settings": request} if request else shown
|
|
206
205
|
|
|
206
|
+
# Read again at most this often: the settings change by hand, the page asks every second.
|
|
207
|
+
_HOLDS_EVERY_SEC = 5.0
|
|
208
|
+
|
|
209
|
+
def _holds(self) -> bool:
|
|
210
|
+
"""Whether a batch may hold papers for a later try, and the card shows 重试 (user, 2026-11-24): 失败后自动重试 on
|
|
211
|
+
(原因不明 at the end, a blocking site after its pause), or 没权限时换下一所学校 on with another saved school. Each
|
|
212
|
+
switch its own; both off, none waits and the card has no 重试, its papers failed at once."""
|
|
213
|
+
cached = getattr(self, "_holds_cache", None)
|
|
214
|
+
if cached and time.time() - cached[0] < self._HOLDS_EVERY_SEC:
|
|
215
|
+
return cached[1]
|
|
216
|
+
try:
|
|
217
|
+
from . import config as _config, school_switch
|
|
218
|
+
loaded = _config.load_config()
|
|
219
|
+
holds = (user_settings.retry_enabled()
|
|
220
|
+
or (school_switch.enabled(loaded) and len(school_switch.schools(loaded)) > 1))
|
|
221
|
+
except Exception:
|
|
222
|
+
holds = True # not known: as before, 重试 shown
|
|
223
|
+
self._holds_cache = (time.time(), bool(holds))
|
|
224
|
+
return bool(holds)
|
|
225
|
+
|
|
207
226
|
# --- watching the task, also while the capsule is minimized ------------
|
|
208
227
|
def watch(self) -> None:
|
|
209
228
|
"""Notifications and closing, off the page: the system slows a minimized
|
|
@@ -256,8 +275,11 @@ class Api:
|
|
|
256
275
|
# Asked for from a reminder, or from the paper on the card at any
|
|
257
276
|
# time while it has a browser (user request, 2026-11-08).
|
|
258
277
|
state = read_state() or {}
|
|
259
|
-
|
|
260
|
-
|
|
278
|
+
# Papers downloading at once (user, 2026-11-29): each row's own, not only the card's.
|
|
279
|
+
papers = state.get("papers") if isinstance(state.get("papers"), dict) else {}
|
|
280
|
+
downloading = {str(state.get("current") or "")} | {
|
|
281
|
+
str(paper.get("current") or "") for paper in papers.values() if isinstance(paper, dict)}
|
|
282
|
+
if (state.get("status") != "running" or current not in downloading
|
|
261
283
|
or str(state.get("run_id") or "") != run_id):
|
|
262
284
|
return "当前没有正在下载的浏览器"
|
|
263
285
|
if not state.get("attention") and state.get("channel"):
|
|
@@ -293,6 +315,21 @@ class Api:
|
|
|
293
315
|
except Exception as exc:
|
|
294
316
|
return f"记录失败:{type(exc).__name__}"
|
|
295
317
|
|
|
318
|
+
def choose_way(self, index: int, current: str, run_id: str = "") -> str:
|
|
319
|
+
"""The way the user picked on the 选择登录方式 card (a sign-in chooser's, user 2026-11-29), for the paper
|
|
320
|
+
asked for; the running download presses it in the browser and keeps it for the school."""
|
|
321
|
+
try:
|
|
322
|
+
from .entitlements import request_way
|
|
323
|
+
|
|
324
|
+
state = read_state() or {}
|
|
325
|
+
if (state.get("status") != "running" or str(state.get("current") or "") != str(current)
|
|
326
|
+
or str(state.get("run_id") or "") != str(run_id)):
|
|
327
|
+
return "这篇已不在等待选择"
|
|
328
|
+
request_way(str(current), int(index), str(run_id))
|
|
329
|
+
return ""
|
|
330
|
+
except Exception as exc:
|
|
331
|
+
return f"记录失败:{type(exc).__name__}"
|
|
332
|
+
|
|
296
333
|
def issue_kinds(self) -> list[list[str]]:
|
|
297
334
|
from .issues import ISSUE_KINDS
|
|
298
335
|
|
|
@@ -336,11 +373,11 @@ class Api:
|
|
|
336
373
|
if changed != self._papers_seen[0]:
|
|
337
374
|
listed = read_papers() or {}
|
|
338
375
|
batch = str(listed.get("batch_id") or "")
|
|
339
|
-
self._papers_seen = (changed, batch
|
|
376
|
+
self._papers_seen = (changed, batch)
|
|
340
377
|
return self._papers_seen[1]
|
|
341
378
|
|
|
342
379
|
def paper_lists(self) -> dict[str, Any]:
|
|
343
|
-
return progress_view.paper_lists(read_papers(), read_state())
|
|
380
|
+
return progress_view.paper_lists(read_papers(), read_state(), self._holds())
|
|
344
381
|
|
|
345
382
|
# --- pages from sites not yet supported (user, 2026-11-16) -------------
|
|
346
383
|
def _batch_papers(self) -> list[dict[str, Any]]:
|
|
@@ -422,6 +459,9 @@ class Api:
|
|
|
422
459
|
"default": f.default, "page": f.page} for f in user_settings.FIELDS],
|
|
423
460
|
"notify": user_settings.notify_enabled(),
|
|
424
461
|
"hourly_now": user_settings.hourly_now(),
|
|
462
|
+
"retry": user_settings.retry_enabled(),
|
|
463
|
+
# 同时下载: serial or parallel; its two numbers are fields (page "parallel").
|
|
464
|
+
"parallel": user_settings.parallel_enabled(),
|
|
425
465
|
"download_dir": download_directory.current(),
|
|
426
466
|
"language": self._lang,
|
|
427
467
|
# Whether the settings have the Markdown page (PaperSearch Pro's, edition.py).
|
|
@@ -460,6 +500,16 @@ class Api:
|
|
|
460
500
|
return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
|
|
461
501
|
return {"ok": True, "hourly_now": enabled}
|
|
462
502
|
|
|
503
|
+
def set_retry(self, enabled: bool) -> dict[str, Any]:
|
|
504
|
+
"""失败后自动重试 saves immediately, like the notification switch (the next batch reads it)."""
|
|
505
|
+
if not isinstance(enabled, bool):
|
|
506
|
+
return {"ok": False, "error": "开关必须为开启或关闭"}
|
|
507
|
+
try:
|
|
508
|
+
user_settings.set_retry(enabled)
|
|
509
|
+
except (OSError, ValueError) as exc:
|
|
510
|
+
return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
|
|
511
|
+
return {"ok": True, "retry": enabled}
|
|
512
|
+
|
|
463
513
|
# The settings' check of system notifications (user, 2026-11-10): a switch turned on,
|
|
464
514
|
# or a test notification, says when the system keeps them from showing.
|
|
465
515
|
def check_notifications(self) -> dict[str, str]:
|
|
@@ -505,9 +555,11 @@ class Api:
|
|
|
505
555
|
return False
|
|
506
556
|
return True
|
|
507
557
|
|
|
508
|
-
def save_settings(self, values: dict[str, Any], download_dir: str | None = None
|
|
558
|
+
def save_settings(self, values: dict[str, Any], download_dir: str | None = None,
|
|
559
|
+
parallel: bool | None = None) -> dict[str, Any]:
|
|
509
560
|
"""Check the fields of one settings page, then save them all; nothing is
|
|
510
|
-
saved when one is wrong. The notification switch saves on its own.
|
|
561
|
+
saved when one is wrong. The notification switch saves on its own.
|
|
562
|
+
``parallel``: the 下载 page's 同时下载, serial (False) or parallel (True)."""
|
|
511
563
|
checked, errors = {}, {}
|
|
512
564
|
for field in user_settings.FIELDS:
|
|
513
565
|
if field.name not in (values or {}):
|
|
@@ -528,6 +580,8 @@ class Api:
|
|
|
528
580
|
if download_dir is not None:
|
|
529
581
|
download_directory.save(download_dir)
|
|
530
582
|
user_settings.save(checked)
|
|
583
|
+
if isinstance(parallel, bool):
|
|
584
|
+
user_settings.set_parallel(parallel)
|
|
531
585
|
except Exception as exc:
|
|
532
586
|
return {"ok": False, "errors": {"": f"保存失败:{type(exc).__name__}"}}
|
|
533
587
|
return {"ok": True}
|
|
@@ -614,7 +668,8 @@ class Api:
|
|
|
614
668
|
"current": saved_schools.is_current(config, entry), "entity": bool(entity_id),
|
|
615
669
|
"saved": bool(account), "username": school_login.masked(account.get("username", "")) if account else "",
|
|
616
670
|
"enabled": bool(account.get("enabled")), "off": str(account.get("off") or ""),
|
|
617
|
-
"status": school_login.school_status(entity_id, pro) if pro is not None else ""
|
|
671
|
+
"status": school_login.school_status(entity_id, pro) if pro is not None else "",
|
|
672
|
+
**(school_login.entry_for(entity_id, pro) if pro is not None else {})})
|
|
618
673
|
listed.sort(key=lambda school: not school["current"])
|
|
619
674
|
current = next((school for school in listed if school["current"]), {})
|
|
620
675
|
from . import school_switch
|
|
@@ -1111,7 +1166,10 @@ class Api:
|
|
|
1111
1166
|
def read():
|
|
1112
1167
|
point = AppKit.NSEvent.mouseLocation()
|
|
1113
1168
|
frame = self._window.native.frame()
|
|
1169
|
+
# Also the pointer in the page (from its top left): the window not active, the page gets no pointer
|
|
1170
|
+
# moves, and the row under it is found from here (并行下载, user's Mac 2026-11-29).
|
|
1114
1171
|
return {"x": point.x, "y": point.y,
|
|
1172
|
+
"page_x": point.x - frame.origin.x, "page_y": frame.origin.y + frame.size.height - point.y,
|
|
1115
1173
|
"inside": frame.origin.x + 10 <= point.x < frame.origin.x + frame.size.width - 10
|
|
1116
1174
|
and frame.origin.y + 10 <= point.y < frame.origin.y + frame.size.height - 10}
|
|
1117
1175
|
return _cocoa_call(read)
|