papersearch 0.6.2 → 0.6.4
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/README.en.md +12 -20
- package/README.md +12 -20
- package/dist/capabilities/pdf-discovery/school/SchoolMcpClient.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/school/SchoolMcpClient.js +6 -2
- package/dist/capabilities/pdf-discovery/school/SchoolMcpClient.js.map +1 -1
- package/dist/infrastructure/pdf/PdfIdentity.d.ts.map +1 -1
- package/dist/infrastructure/pdf/PdfIdentity.js +27 -6
- package/dist/infrastructure/pdf/PdfIdentity.js.map +1 -1
- package/package.json +1 -1
- package/school/paper_search_school/adapters/base.py +3 -2
- package/school/paper_search_school/adapters/elsevier/__init__.py +46 -0
- package/school/paper_search_school/assets/capsule.html +25 -12
- package/school/paper_search_school/assets/capsule_en.json +6 -6
- package/school/paper_search_school/browser/batch_session.py +65 -5
- package/school/paper_search_school/engine/batch_institution.py +99 -5
- package/school/paper_search_school/engine/batch_login.py +18 -5
- package/school/paper_search_school/engine/bridge.py +2 -2
- package/school/paper_search_school/engine/pdf_guard.py +28 -7
- package/school/paper_search_school/federations/builtin/azsciencenet.json +11 -0
- package/school/paper_search_school/federations/builtin/belnet.json +11 -0
- package/school/paper_search_school/federations/builtin/cstcloud.json +11 -0
- package/school/paper_search_school/federations/builtin/cynet.json +11 -0
- package/school/paper_search_school/federations/builtin/edugate.json +11 -0
- package/school/paper_search_school/federations/builtin/eduidlu.json +11 -0
- package/school/paper_search_school/federations/builtin/irfed.json +11 -0
- package/school/paper_search_school/federations/builtin/iucc.json +11 -0
- package/school/paper_search_school/federations/builtin/maeen.json +11 -0
- package/school/paper_search_school/federations/builtin/renater.json +11 -0
- package/school/paper_search_school/federations/builtin/surfconext.json +11 -0
- package/school/paper_search_school/federations/builtin/ukfederation.json +11 -0
- package/school/paper_search_school/federations/schools.py +68 -14
- package/school/paper_search_school/progress_view.py +11 -5
- package/school/paper_search_school/rate_limit.py +30 -16
- package/school/paper_search_school/server.py +2 -1
- package/skills/paper-search/SKILL.md +1 -1
- package/skills/paper-search/references/federation-support.md +84 -11
- package/skills/paper-search/references/school-setup.md +3 -2
|
@@ -326,6 +326,10 @@ let open = false; // the card is showing
|
|
|
326
326
|
let panel = ""; // "", "menu", "report", "confirm", "settings": kept until the user leaves it
|
|
327
327
|
let flash = { text: "", until: 0 };
|
|
328
328
|
let settings = null, settingsErrors = {}, notifyOn = true;
|
|
329
|
+
// What is typed on this settings page and not yet saved. Any redraw shows it instead of the
|
|
330
|
+
// saved value: a click on the card's background is a drag, and its end redraws the card
|
|
331
|
+
// (a typed hourly limit went back to the saved one, Windows, 2026-11-13).
|
|
332
|
+
let settingsDraft = {};
|
|
329
333
|
let notifyCheck = null; // the notification check under the switch: {state: testing, sent, off, unseen or failed}
|
|
330
334
|
// Settings pages: "home" lists download, wait and keys. settingsOnly: this window was started
|
|
331
335
|
// just to show them (`paper-search-school settings`), so it closes with them unless a download runs.
|
|
@@ -426,7 +430,8 @@ function stat(list, value, label, color) {
|
|
|
426
430
|
|
|
427
431
|
function runningCard() {
|
|
428
432
|
const v = V;
|
|
429
|
-
|
|
433
|
+
// Held by the hourly limit, the time used gives way: the line stays one line (2026-11-13).
|
|
434
|
+
const sub = [v.total ? v.done + "/" + v.total : "", v.part, v.elapsed && !v.hold ? "已用 " + v.elapsed : ""].filter(Boolean).join(" · ");
|
|
430
435
|
return '<div class="card-body">' + header(v.headline, sub, false) + paperBlock()
|
|
431
436
|
+ '<div class="stats">' + stat("ok", v.ok, "成功", "var(--ok)") + stat("failed", v.bad, "失败", "var(--bad)")
|
|
432
437
|
+ stat("left", v.left == null ? "—" : v.left, "剩余") + "</div>"
|
|
@@ -608,7 +613,7 @@ function settingsHome() {
|
|
|
608
613
|
|
|
609
614
|
function fieldRows(page) {
|
|
610
615
|
return fieldsOn(page).map((f) => '<div class="row"><span>' + esc(f.label) + '</span><span><input data-field="' + esc(f.name)
|
|
611
|
-
+ '" value="' + esc(f.value) + '" aria-label="' + esc(f.label) + '" inputmode="numeric"> <span class="dim">' + esc(f.unit) + "</span></span></div>"
|
|
616
|
+
+ '" value="' + esc(f.name in settingsDraft ? settingsDraft[f.name] : f.value) + '" aria-label="' + esc(f.label) + '" inputmode="numeric"> <span class="dim">' + esc(f.unit) + "</span></span></div>"
|
|
612
617
|
+ (settingsErrors[f.name] ? '<div class="err">' + esc(settingsErrors[f.name]) + "</div>" : "")).join("");
|
|
613
618
|
}
|
|
614
619
|
|
|
@@ -621,7 +626,7 @@ function settingsFoot() {
|
|
|
621
626
|
function settingsDownload() {
|
|
622
627
|
return settingsHead("下载")
|
|
623
628
|
+ '<div class="folder-setting"><label for="download-dir">默认下载文件夹</label><div class="folder-row">'
|
|
624
|
-
+ '<input id="download-dir" type="text" value="' + esc(settings.download_dir || '') + '" placeholder="输入完整路径">'
|
|
629
|
+
+ '<input id="download-dir" type="text" value="' + esc(("download_dir" in settingsDraft ? settingsDraft.download_dir : settings.download_dir) || '') + '" placeholder="输入完整路径">'
|
|
625
630
|
+ '<button class="btn" data-act="choose_folder">选择…</button></div>'
|
|
626
631
|
+ '<div class="hint">用于后续下载;命令中指定路径时优先使用指定路径。</div>'
|
|
627
632
|
+ (settingsErrors.download_dir ? '<div class="err">' + esc(settingsErrors.download_dir) + '</div>' : '') + '</div>'
|
|
@@ -744,7 +749,7 @@ function updateStrip() {
|
|
|
744
749
|
}
|
|
745
750
|
|
|
746
751
|
async function loadSettings() {
|
|
747
|
-
settings = await api().settings(); notifyOn = settings.notify; settingsErrors = {}; notifyCheck = null;
|
|
752
|
+
settings = await api().settings(); notifyOn = settings.notify; settingsErrors = {}; settingsDraft = {}; notifyCheck = null;
|
|
748
753
|
try { apiKeys = await api().api_keys(); } catch (error) { apiKeys = null; }
|
|
749
754
|
}
|
|
750
755
|
|
|
@@ -768,7 +773,7 @@ async function savedValues(service) {
|
|
|
768
773
|
}
|
|
769
774
|
|
|
770
775
|
function leaveSettings() {
|
|
771
|
-
panel = ""; editing = ""; editValues = {}; settingsNote = "";
|
|
776
|
+
panel = ""; editing = ""; editValues = {}; settingsDraft = {}; settingsNote = "";
|
|
772
777
|
if (settingsOnly && !busy()) return act("close");
|
|
773
778
|
return render(true);
|
|
774
779
|
}
|
|
@@ -955,11 +960,11 @@ async function act(action, target) {
|
|
|
955
960
|
return render(true);
|
|
956
961
|
}
|
|
957
962
|
case "settings_page":
|
|
958
|
-
settingsPage = target.dataset.page; settingsErrors = {}; settingsNote = ""; editing = ""; editValues = {}; return render(true);
|
|
963
|
+
settingsPage = target.dataset.page; settingsErrors = {}; settingsDraft = {}; settingsNote = ""; editing = ""; editValues = {}; return render(true);
|
|
959
964
|
case "back":
|
|
960
965
|
if (panel !== "settings") { panel = ""; return render(true); }
|
|
961
966
|
if (settingsPage === "home") return leaveSettings();
|
|
962
|
-
settingsPage = "home"; editing = ""; editValues = {}; settingsErrors = {}; return render(true);
|
|
967
|
+
settingsPage = "home"; editing = ""; editValues = {}; settingsErrors = {}; settingsDraft = {}; return render(true);
|
|
963
968
|
case "progress": case "close_settings": return leaveSettings();
|
|
964
969
|
case "edit_key":
|
|
965
970
|
editValues = await savedValues(target.dataset.service);
|
|
@@ -1028,11 +1033,14 @@ async function act(action, target) {
|
|
|
1028
1033
|
case "notify_settings": return api().open_notification_settings();
|
|
1029
1034
|
case "choose_folder": {
|
|
1030
1035
|
const selected = await api().choose_download_directory();
|
|
1031
|
-
if (selected) {
|
|
1036
|
+
if (selected) { settingsDraft.download_dir = selected; root.querySelector('#download-dir').value = selected; }
|
|
1032
1037
|
return;
|
|
1033
1038
|
}
|
|
1034
1039
|
case "defaults":
|
|
1035
|
-
for (const f of fieldsOn(settingsPage)) {
|
|
1040
|
+
for (const f of fieldsOn(settingsPage)) {
|
|
1041
|
+
const input = root.querySelector('input[data-field="' + f.name + '"]');
|
|
1042
|
+
if (input) { input.value = f.default; settingsDraft[f.name] = String(f.default); }
|
|
1043
|
+
}
|
|
1036
1044
|
return;
|
|
1037
1045
|
case "save": {
|
|
1038
1046
|
// Only this page's fields; the notification switch has saved itself.
|
|
@@ -1041,9 +1049,7 @@ async function act(action, target) {
|
|
|
1041
1049
|
const folder = root.querySelector('#download-dir');
|
|
1042
1050
|
const result = await api().save_settings(values, folder ? folder.value : null);
|
|
1043
1051
|
if (!result.ok) {
|
|
1044
|
-
settingsErrors = result.errors || {};
|
|
1045
|
-
settings.fields.forEach((f) => { if (f.name in values) f.value = values[f.name]; });
|
|
1046
|
-
if (folder) settings.download_dir = folder.value;
|
|
1052
|
+
settingsErrors = result.errors || {}; // what was typed stays in settingsDraft
|
|
1047
1053
|
return render(true);
|
|
1048
1054
|
}
|
|
1049
1055
|
await loadSettings();
|
|
@@ -1112,6 +1118,13 @@ window.addEventListener("pointercancel", finishDrag);
|
|
|
1112
1118
|
root.addEventListener("lostpointercapture", finishDrag);
|
|
1113
1119
|
window.addEventListener("blur", finishDrag);
|
|
1114
1120
|
|
|
1121
|
+
root.addEventListener("input", (event) => {
|
|
1122
|
+
// What is typed goes into the page's model at once, so that a redraw keeps it.
|
|
1123
|
+
const input = event.target;
|
|
1124
|
+
if (input.dataset.field) settingsDraft[input.dataset.field] = input.value;
|
|
1125
|
+
else if (input.id === "download-dir") settingsDraft.download_dir = input.value;
|
|
1126
|
+
else if (input.dataset.key && editing) editValues[input.dataset.key] = input.value;
|
|
1127
|
+
});
|
|
1115
1128
|
root.addEventListener("click", (event) => {
|
|
1116
1129
|
const target = event.target.closest("[data-act]");
|
|
1117
1130
|
if (target) { event.stopPropagation(); act(target.dataset.act, target); }
|
|
@@ -521,16 +521,16 @@
|
|
|
521
521
|
"Resumes $1"
|
|
522
522
|
],
|
|
523
523
|
[
|
|
524
|
-
"^(.+) 已达设置的每小时 (\\d+) 篇,(\\d{1,2}:\\d{2})
|
|
525
|
-
"$1: your $2/hour limit;
|
|
524
|
+
"^(.+) 已达设置的每小时 (\\d+) 篇,(\\d{1,2}:\\d{2}) 重新计数$",
|
|
525
|
+
"$1: your $2/hour limit; resets $3"
|
|
526
526
|
],
|
|
527
527
|
[
|
|
528
|
-
"^已达设置的每小时 (\\d+) 篇,(\\d{1,2}:\\d{2})
|
|
529
|
-
"Your $1/hour limit reached;
|
|
528
|
+
"^已达设置的每小时 (\\d+) 篇,(\\d{1,2}:\\d{2}) 重新计数$",
|
|
529
|
+
"Your $1/hour limit reached; resets $2"
|
|
530
530
|
],
|
|
531
531
|
[
|
|
532
|
-
"^已达设置的每小时上限,(\\d{1,2}:\\d{2})
|
|
533
|
-
"Your hourly limit reached;
|
|
532
|
+
"^已达设置的每小时上限,(\\d{1,2}:\\d{2}) 重新计数$",
|
|
533
|
+
"Your hourly limit reached; resets $1"
|
|
534
534
|
],
|
|
535
535
|
[
|
|
536
536
|
"^(.+) 一小时内已打开 (\\d+) 篇(每小时上限),(\\d{1,2}:\\d{2}) 继续这一篇$",
|
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
"""One browser window and tab kept for a serial MCP batch, on its Playwright
|
|
2
2
|
worker thread. Used when the backend declares ``batch_window``
|
|
3
3
|
(browser/backend.py); only plain Playwright calls, no backend of its own."""
|
|
4
|
+
import time
|
|
4
5
|
from contextvars import ContextVar
|
|
6
|
+
from urllib.parse import urlsplit
|
|
5
7
|
|
|
8
|
+
from . import challenges
|
|
6
9
|
from .preview import ensure_enabled
|
|
7
10
|
|
|
8
11
|
|
|
9
|
-
# How long a keep-alive load of the article page may take
|
|
10
|
-
|
|
12
|
+
# How long a keep-alive load of the article page may take, and how long the page then
|
|
13
|
+
# has to settle back on the article's site (a Cloudflare check cleared, a sign-in the
|
|
14
|
+
# publisher runs by itself); the client waits up to a minute for all of it.
|
|
15
|
+
KEEP_SESSION_TIMEOUT_MS = 25_000
|
|
16
|
+
KEEP_SESSION_SETTLE_SECONDS = 20
|
|
11
17
|
|
|
12
18
|
|
|
13
19
|
class BatchBrowser:
|
|
@@ -37,15 +43,31 @@ class BatchBrowser:
|
|
|
37
43
|
article page, loaded again in the batch's tab, so the publisher's institutional
|
|
38
44
|
session does not lapse for want of a request (Wiley: about half an hour,
|
|
39
45
|
2026-11-12). Only after a paper that saved its PDF: a tab left on a school's
|
|
40
|
-
login page is never taken away from the user.
|
|
46
|
+
login page is never taken away from the user.
|
|
47
|
+
|
|
48
|
+
A Cloudflare check met on the way is cleared as a download clears it (its
|
|
49
|
+
checkbox only). A page that does not come back to the article's site (a check
|
|
50
|
+
that does not clear, the publisher's own sign-in, a load that hangs) leaves the
|
|
51
|
+
tab blank, and no keep-alive runs again until a paper saves; the next paper signs
|
|
52
|
+
in as a download does. The tab sat spinning on a Cloudflare check, and on
|
|
53
|
+
Elsevier's sign-in page (id.elsevier.com) that never loaded, for the rest of the
|
|
54
|
+
wait (Windows, 2026-11-13)."""
|
|
41
55
|
page = self.page
|
|
42
56
|
if self.context is None or page is None or page.is_closed() or not self.article_url:
|
|
43
57
|
return {"kept": False, "reason": "no_publisher_page"}
|
|
44
58
|
try:
|
|
45
59
|
page.goto(self.article_url, wait_until="domcontentloaded", timeout=KEEP_SESSION_TIMEOUT_MS)
|
|
60
|
+
reason = _settle(page, _site(self.article_url))
|
|
46
61
|
except Exception as exc:
|
|
47
|
-
|
|
48
|
-
|
|
62
|
+
reason = type(exc).__name__
|
|
63
|
+
if not reason:
|
|
64
|
+
return {"kept": True}
|
|
65
|
+
self.article_url = ""
|
|
66
|
+
try:
|
|
67
|
+
page.goto("about:blank", timeout=5_000)
|
|
68
|
+
except Exception:
|
|
69
|
+
pass
|
|
70
|
+
return {"kept": False, "reason": reason}
|
|
49
71
|
|
|
50
72
|
def finish_item(self):
|
|
51
73
|
# Keep the original tab and its native window. Article/PDF/login
|
|
@@ -61,3 +83,41 @@ class BatchBrowser:
|
|
|
61
83
|
|
|
62
84
|
|
|
63
85
|
active_batch: ContextVar[BatchBrowser | None] = ContextVar("active_browser_batch", default=None)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _on_verification(page) -> bool:
|
|
89
|
+
try:
|
|
90
|
+
title = page.title()
|
|
91
|
+
except Exception:
|
|
92
|
+
title = "" # mid-navigation: the URL still tells
|
|
93
|
+
return challenges.looks_like_challenge(str(page.url or ""), title)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _site(url: str) -> str:
|
|
97
|
+
host = urlsplit(str(url or "")).hostname or ""
|
|
98
|
+
return host[4:] if host.startswith("www.") else host
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _settle(page, site: str) -> str:
|
|
102
|
+
""""" once the page has settled on the article's site, no Cloudflare check up; else,
|
|
103
|
+
after KEEP_SESSION_SETTLE_SECONDS, "verification" or "signin" (another site: the
|
|
104
|
+
publisher's sign-in, a school's login). A check's checkbox is clicked as in a
|
|
105
|
+
download (at most three times, three seconds apart)."""
|
|
106
|
+
from .challenge_interaction import click_checkbox
|
|
107
|
+
until = time.monotonic() + KEEP_SESSION_SETTLE_SECONDS
|
|
108
|
+
clicks, next_click = 0, 0.0
|
|
109
|
+
page.wait_for_timeout(2000) # a redirect the page makes once loaded
|
|
110
|
+
while True:
|
|
111
|
+
if _on_verification(page):
|
|
112
|
+
reason = "verification"
|
|
113
|
+
now = time.monotonic()
|
|
114
|
+
if clicks < 3 and now >= next_click:
|
|
115
|
+
if click_checkbox(page, timeout_ms=2500, checkpoint=lambda: None) == "clicked":
|
|
116
|
+
clicks, next_click = clicks + 1, time.monotonic() + 3
|
|
117
|
+
elif _site(page.url) == site:
|
|
118
|
+
return ""
|
|
119
|
+
else:
|
|
120
|
+
reason = "signin"
|
|
121
|
+
if time.monotonic() >= until:
|
|
122
|
+
return reason
|
|
123
|
+
page.wait_for_timeout(1000)
|
|
@@ -603,7 +603,8 @@ class InstitutionMixin:
|
|
|
603
603
|
|
|
604
604
|
# Words a unit of the school itself may add to its name (its library, campus,
|
|
605
605
|
# hospital): such an entry may be the school's, so the search settles nothing.
|
|
606
|
-
|
|
606
|
+
# A campus by its own name too ("<school> - Campus <name>", 2026-11-13).
|
|
607
|
+
_OWN_UNIT = re.compile(r"^(?:graduate school|school of|faculty of|department of|institute of|cent(?:er|re) for|campus)\b"
|
|
607
608
|
r"|^(?:(?:the|main|central|university|univ|library|libraries|campus|branch|hospital|"
|
|
608
609
|
r"medical|medicine|dentistry|nursing|pharmacy|law|business|graduate|department|"
|
|
609
610
|
r"health|engineering|center|centre|faculty|school|college|of|and)\b\s*)+$")
|
|
@@ -615,6 +616,8 @@ class InstitutionMixin:
|
|
|
615
616
|
r"没有找到|无结果|未找到|找不到(?:相关|匹配)", re.I)
|
|
616
617
|
# How long the results must stay the same before they settle the school's absence.
|
|
617
618
|
SEARCH_SETTLED_SEC = 4
|
|
619
|
+
# Entries enough to be a search's results, not a page's own links.
|
|
620
|
+
UNRELATED_RESULTS = 3
|
|
618
621
|
|
|
619
622
|
def _search_lists_no_school(self, page: Any, result: DownloadResult, url: str, scored: list) -> bool:
|
|
620
623
|
"""The school's name was searched on this page, the results are shown and
|
|
@@ -637,6 +640,7 @@ class InstitutionMixin:
|
|
|
637
640
|
residues = [self._name_residue(" ".join(o.translate(self._QUOTES).split()).lower()) for o in may_sign_in]
|
|
638
641
|
if any(r is not None and self._OWN_UNIT.match(r) for r in residues):
|
|
639
642
|
return False # perhaps the school's own library or campus: left to the user
|
|
643
|
+
settled = self.SEARCH_SETTLED_SEC
|
|
640
644
|
if others:
|
|
641
645
|
evidence = f"{len(others)} other entries: " + "; ".join(others[:3])
|
|
642
646
|
else:
|
|
@@ -646,21 +650,105 @@ class InstitutionMixin:
|
|
|
646
650
|
if not _is_browser_error(exc):
|
|
647
651
|
raise
|
|
648
652
|
return False
|
|
649
|
-
|
|
653
|
+
baseline = getattr(result, "_search_baseline", None)
|
|
654
|
+
before = baseline[1] if isinstance(baseline, tuple) and baseline[0] == url else set()
|
|
655
|
+
# Only what the search added: the page's own links listed before it are no results
|
|
656
|
+
# (2026-11-13: "About Elsevier", "Cookie settings" ended four searches still loading).
|
|
657
|
+
unrelated = sorted({str(it.get("t") or "")[:60] for score, it in scored if score == 0
|
|
658
|
+
and str(it.get("t") or "").strip() and str(it.get("t") or "")[:60] not in before})
|
|
659
|
+
if said:
|
|
660
|
+
evidence = f'"{said.group(0)}"'
|
|
661
|
+
elif len(unrelated) >= self.UNRELATED_RESULTS and not self._search_list_closed(page, result, url):
|
|
662
|
+
# A fuzzy search listing only schools of other names, none carrying
|
|
663
|
+
# the school's entityID (2026-11-13: "University of <town>" for one
|
|
664
|
+
# school, 20 of them): longer, a slow search may still be replacing them.
|
|
665
|
+
evidence, settled = f"{len(unrelated)} unrelated entries: " + "; ".join(unrelated[:3]), 2 * settled
|
|
666
|
+
else:
|
|
650
667
|
return False # results not shown yet: looked at again next pass
|
|
651
|
-
evidence = f'"{said.group(0)}"'
|
|
652
668
|
now = time.time()
|
|
653
669
|
seen = getattr(result, "_search_miss", None)
|
|
654
670
|
if not seen or seen[0] != url or seen[1] != evidence:
|
|
655
671
|
result._search_miss = (url, evidence, now)
|
|
656
672
|
return False
|
|
657
|
-
if now - seen[2] <
|
|
673
|
+
if now - seen[2] < settled:
|
|
658
674
|
return False
|
|
659
675
|
self._event(result, "auto_institution_not_found",
|
|
660
676
|
f"{self.institution_query} (search: {evidence[:160]}) @ {url}")
|
|
661
677
|
result._institution_not_listed = True
|
|
662
678
|
return True
|
|
663
679
|
|
|
680
|
+
# How long a search by one of the school's names may show nothing before the next is typed.
|
|
681
|
+
SEARCH_RETRY_SEC = 6
|
|
682
|
+
|
|
683
|
+
def _search_queries(self, names: list[str]) -> list[str]:
|
|
684
|
+
"""The school's names to search by, in Latin letters first (straight apostrophes)."""
|
|
685
|
+
typed = [n.translate(self._QUOTES) for n in names]
|
|
686
|
+
return list(dict.fromkeys([q for q in typed if q.isascii()] + [q for q in typed if not q.isascii()]))
|
|
687
|
+
|
|
688
|
+
def _search_again_by_another_name(self, page: Any, result: DownloadResult, url: str, names: list[str]) -> bool:
|
|
689
|
+
"""The search by one of the school's names has shown nothing for
|
|
690
|
+
``SEARCH_RETRY_SEC`` (its list closed, or no entry beyond the page's own):
|
|
691
|
+
the box is cleared and the next name typed, once each (2026-11-13: a school
|
|
692
|
+
listed by its French name, searched by its English one, found nothing).
|
|
693
|
+
A box holding anything but our own query is the user's and stays."""
|
|
694
|
+
box_at = getattr(result, "_search_box", None)
|
|
695
|
+
if (not isinstance(box_at, tuple) or box_at[0] != url
|
|
696
|
+
or time.time() - float(getattr(result, "_search_typed_at", 0) or 0) < self.SEARCH_RETRY_SEC):
|
|
697
|
+
return False
|
|
698
|
+
tried = []
|
|
699
|
+
for event in result.events:
|
|
700
|
+
query, _, where = str(event.get("detail", "")).partition(" @ ")
|
|
701
|
+
if event["state"] == "auto_institution_search" and len(where) > 10 and url.startswith(where):
|
|
702
|
+
tried.append(query)
|
|
703
|
+
left = [q for q in self._search_queries(names) if q not in tried]
|
|
704
|
+
if not left:
|
|
705
|
+
return False
|
|
706
|
+
baseline = getattr(result, "_search_baseline", None)
|
|
707
|
+
before = baseline[1] if isinstance(baseline, tuple) and baseline[0] == url else set()
|
|
708
|
+
if not self._search_list_closed(page, result, url) and self._entry_texts(page) - before:
|
|
709
|
+
return False # results shown: they decide
|
|
710
|
+
box = page.locator(box_at[1]).first
|
|
711
|
+
try:
|
|
712
|
+
if str(box.input_value(timeout=2_000) or "").strip() not in tried:
|
|
713
|
+
return False
|
|
714
|
+
box.fill("")
|
|
715
|
+
box.press_sequentially(left[0], delay=40)
|
|
716
|
+
except Exception as exc:
|
|
717
|
+
if not _is_browser_error(exc):
|
|
718
|
+
raise
|
|
719
|
+
return False
|
|
720
|
+
result._search_typed_at = time.time()
|
|
721
|
+
result._search_miss = None
|
|
722
|
+
self._event(result, "auto_institution_search", f"{left[0]} @ {url}")
|
|
723
|
+
return True
|
|
724
|
+
|
|
725
|
+
def _search_list_closed(self, page: Any, result: DownloadResult, url: str) -> bool:
|
|
726
|
+
"""The search box typed in says its list is closed (``aria-expanded="false"``):
|
|
727
|
+
no results are shown, whatever else the page lists (2026-11-13: a search
|
|
728
|
+
showing nothing, its page's links taken for results)."""
|
|
729
|
+
box = getattr(result, "_search_box", None)
|
|
730
|
+
if not isinstance(box, tuple) or box[0] != url:
|
|
731
|
+
return False
|
|
732
|
+
try:
|
|
733
|
+
return page.evaluate("""(selector) => {
|
|
734
|
+
const el = document.querySelector(selector);
|
|
735
|
+
return !!el && el.getAttribute('aria-expanded') === 'false';
|
|
736
|
+
}""", box[1]) is True
|
|
737
|
+
except Exception as exc:
|
|
738
|
+
if not _is_browser_error(exc):
|
|
739
|
+
raise
|
|
740
|
+
return True # not readable now: nothing concluded from it
|
|
741
|
+
|
|
742
|
+
def _entry_texts(self, page: Any) -> set[str]:
|
|
743
|
+
"""The entries a page lists now, by their text (``_ENTRIES_JS``)."""
|
|
744
|
+
try:
|
|
745
|
+
items = page.evaluate(self._ENTRIES_JS, self._ENTRY_SELECTOR)
|
|
746
|
+
except Exception as exc:
|
|
747
|
+
if not _is_browser_error(exc):
|
|
748
|
+
raise
|
|
749
|
+
return set()
|
|
750
|
+
return {str(it.get("t") or "")[:60] for it in items if isinstance(it, dict)} if isinstance(items, list) else set()
|
|
751
|
+
|
|
664
752
|
def _click_unique_institution_entry(self, page: Any, result: DownloadResult, url: str) -> bool:
|
|
665
753
|
"""Click the single best visible entry for the configured school.
|
|
666
754
|
|
|
@@ -939,6 +1027,8 @@ class InstitutionMixin:
|
|
|
939
1027
|
# never on a verification page, which the challenge wait takes first: a
|
|
940
1028
|
# search there found no school and ended the login (fixture, 2026-11-01).
|
|
941
1029
|
if not once("institution_search"):
|
|
1030
|
+
if self._search_again_by_another_name(page, result, url, names):
|
|
1031
|
+
return True
|
|
942
1032
|
return self._handle_institution_search_miss(page, result, url)
|
|
943
1033
|
if not self._is_challenge_page(page):
|
|
944
1034
|
if self._assist_federation_discovery(page, result):
|
|
@@ -952,7 +1042,11 @@ class InstitutionMixin:
|
|
|
952
1042
|
if str(box.input_value(timeout=2_000) or "").strip():
|
|
953
1043
|
return False # the user is typing; never replace it
|
|
954
1044
|
# The English name, with a straight apostrophe (CARSI writes "Xi’an", 2026-11-01).
|
|
955
|
-
query =
|
|
1045
|
+
query = self._search_queries(names)[0]
|
|
1046
|
+
# What the page lists before the search (its own links): no result of it.
|
|
1047
|
+
result._search_baseline = (url, self._entry_texts(page))
|
|
1048
|
+
result._search_box = (url, selector)
|
|
1049
|
+
result._search_typed_at = time.time()
|
|
956
1050
|
# Key by key: search-as-you-type lists (SAMS Sigma, OpenAthens)
|
|
957
1051
|
# do not search on a filled value (2026-11-01).
|
|
958
1052
|
box.press_sequentially(query, delay=40)
|
|
@@ -578,9 +578,10 @@ class LoginMixin:
|
|
|
578
578
|
_IDP_CONFIRMATION_JS = """() => document.querySelector('[name="_eventId_TermsRejected"]') ? 'terms-of-use'
|
|
579
579
|
: document.querySelector('[name="_shib_idp_consentOptions"], [name="_shib_idp_consentIds"]') ? 'attribute-release' : ''"""
|
|
580
580
|
# Shibboleth's "Message Security Error": the identity provider could not trust the
|
|
581
|
-
# publisher's request (a school's IdP to Elsevier, 2026-11-12)
|
|
581
|
+
# publisher's request (a school's IdP to Elsevier, 2026-11-12); AD FS's "An error
|
|
582
|
+
# occurred. Contact your administrator" (two schools' AD FS, 2026-11-13).
|
|
582
583
|
_IDP_ERROR_RE = re.compile(r"未知错误|系统错误|服务异常|认证失败|出错了|\b5\d{4}\b.{0,20}错误|an unexpected error|error code|system error"
|
|
583
|
-
r"|message security error", re.I)
|
|
584
|
+
r"|message security error|an error occurred\. contact your administrator", re.I)
|
|
584
585
|
|
|
585
586
|
# A publisher's own terms form on the way to the school: SIAM's SAML consent
|
|
586
587
|
# ("I have read and agree to the Terms and Conditions and Privacy Policy.",
|
|
@@ -734,6 +735,7 @@ class LoginMixin:
|
|
|
734
735
|
r"|application you have accessed is not registered|may not be enabled for this type of authentication"
|
|
735
736
|
r"|can't find your institution|access to this resource has been restricted by your organization|oa-ap-4032"
|
|
736
737
|
r"|不支持的请求|does not have access to this resource|message security error|reported an idp error"
|
|
738
|
+
r"|an error occurred\. contact your administrator|application not authorized to use cas"
|
|
737
739
|
r"|temporarily unavailable|verify you are human|are you a robot|checking your browser|正在进行安全验证", re.I)
|
|
738
740
|
|
|
739
741
|
def _login_block_reason(self, page: Any) -> str:
|
|
@@ -832,6 +834,10 @@ class LoginMixin:
|
|
|
832
834
|
return "institution_pdf_entitlement_missing"
|
|
833
835
|
if "application you have accessed is not registered" in haystack:
|
|
834
836
|
return "institution_not_registered"
|
|
837
|
+
# Apereo CAS as the school's identity provider, the publisher not enabled there
|
|
838
|
+
# ("Application Not Authorized to Use CAS", 2026-11-13).
|
|
839
|
+
if "application not authorized to use cas" in haystack and self._is_idp_host(urlparse(current_url).netloc):
|
|
840
|
+
return "institution_not_registered"
|
|
835
841
|
if "your institution may not be enabled for this type of authentication" in haystack:
|
|
836
842
|
return "institution_not_registered"
|
|
837
843
|
if "can't find your institution" in haystack and "institution sign in" in haystack:
|
|
@@ -1480,11 +1486,18 @@ class LoginMixin:
|
|
|
1480
1486
|
url = str(getattr(page, "url", "") or "")
|
|
1481
1487
|
return self._school_password_box(page, url) or self._idp_user_action(page)
|
|
1482
1488
|
|
|
1489
|
+
_CREDENTIAL_BOX = 'input[type="password"]:visible, input[autocomplete="one-time-code"]:visible'
|
|
1490
|
+
|
|
1483
1491
|
def _school_password_box(self, page: Any, url: str) -> bool:
|
|
1484
|
-
"""A password or one-time-code field that is not a personal account's box on the
|
|
1492
|
+
"""A password or one-time-code field that is not a personal account's box on the
|
|
1493
|
+
publisher's site; on the school's side also one in a frame of its page (a
|
|
1494
|
+
school's login form shown in a frame, its page's own copy hidden: 2026-11-13)."""
|
|
1485
1495
|
try:
|
|
1486
|
-
|
|
1487
|
-
|
|
1496
|
+
if page.locator(self._CREDENTIAL_BOX).count() and not self._personal_login_box(page, url):
|
|
1497
|
+
return True
|
|
1498
|
+
frames = page.frames if isinstance(getattr(page, "frames", None), list) else []
|
|
1499
|
+
return (len(frames) > 1 and self._is_idp_host(urlparse(url).netloc)
|
|
1500
|
+
and any(frame.locator(self._CREDENTIAL_BOX).count() for frame in frames[1:]))
|
|
1488
1501
|
except Exception as exc:
|
|
1489
1502
|
if not _is_navigation_cut(exc):
|
|
1490
1503
|
raise
|
|
@@ -307,14 +307,14 @@ def _try_builtin_institutional(
|
|
|
307
307
|
"error_type": "access_blocked", "reason": "journal_blocked_earlier", "action": "review_access",
|
|
308
308
|
"blocked_by": blocked_by}
|
|
309
309
|
|
|
310
|
-
# At most ``publisher_hourly_limit`` articles per publisher in
|
|
310
|
+
# At most ``publisher_hourly_limit`` articles per publisher in each hour
|
|
311
311
|
# (state L): psc's batch waits the given seconds and tries this one again.
|
|
312
312
|
from .. import rate_limit
|
|
313
313
|
rate_key = publisher_name or (urlparse(resolved_url).hostname or "")
|
|
314
314
|
limit = int(config.get("publisher_hourly_limit", rate_limit.DEFAULT_LIMIT) or 0)
|
|
315
315
|
wait = rate_limit.wait_seconds(rate_key, limit)
|
|
316
316
|
if wait:
|
|
317
|
-
log.info(" [Institutional] %s: %d articles
|
|
317
|
+
log.info(" [Institutional] %s: %d articles this hour, a new hour in %d s", rate_key, limit, wait)
|
|
318
318
|
return {"success": False, "identifier": doi, "doi": doi, "source": "institutional:rate_limit",
|
|
319
319
|
"error_type": "rate_limited", "reason": "publisher_hourly_limit", "action": "wait",
|
|
320
320
|
"retry_after_sec": wait, "publisher": rate_key, "limit": limit}
|
|
@@ -20,12 +20,13 @@ another article. A title's numbers must always be exact. An attachment
|
|
|
20
20
|
(supplementary material, disclosure form) and a notice about the article
|
|
21
21
|
(correction, retraction, briefing, letter to the editor), each known by its own
|
|
22
22
|
heading line, are not the article, unless the notice is itself the requested
|
|
23
|
-
item: its title says so, or the pages name it (its DOI in the header
|
|
24
|
-
whole title and its DOI) and print no other DOI. A DOI the pages label as the article
|
|
23
|
+
item: its title says so, or the pages name it (its DOI in the header or right above
|
|
24
|
+
its copyright line, or its whole title and its DOI) and print no other DOI. A DOI the pages label as the article
|
|
25
25
|
a notice is about ("DOI of original article:", "Correction to:") is no other DOI for
|
|
26
26
|
the notice itself (a letter that names the article it discusses); when that label
|
|
27
27
|
points at the requested DOI, the PDF is a notice about it. A scan without a text layer is
|
|
28
|
-
``"source"`` when the URL it came from names the DOI
|
|
28
|
+
``"source"`` when the URL it came from names the DOI, or its suffix when that is long
|
|
29
|
+
enough to name one article (an Elsevier PII) (``assess`` with ``source``;
|
|
29
30
|
the frontend passes it, the engine does not); so is a page that prints no DOI at all and is
|
|
30
31
|
no notice or attachment, for an item named like a section rather than an article (a
|
|
31
32
|
one-page "Journal Club" note, "Issue Information").
|
|
@@ -83,6 +84,10 @@ _ABOUT_REACH = 200 # how far after its label the DOI of the article a notice is
|
|
|
83
84
|
# A DOI may break right after its prefix ("https://doi.org/10.1016/" then "S0140-…", The Lancet).
|
|
84
85
|
_DOI_IN_TEXT = re.compile(r"10\.\d{4,9}/(?:[ \t]*\n[ \t]*)?[^\s\"<>]+")
|
|
85
86
|
_LETTER = re.compile(r"[a-zЀ-ӿ一-鿿]")
|
|
87
|
+
# The copyright line right after a DOI ("https://doi.org/…" then "1063-4584/© 2025 …"):
|
|
88
|
+
# the item's own footer. Text extraction can put the footer after the reference list
|
|
89
|
+
# (Elsevier letters and replies, 2026-11-13).
|
|
90
|
+
_COPYRIGHT_AFTER = re.compile(r"\s*(?:\d{4}-\d{3}[\dx]\s*/\s*)?©", re.I)
|
|
86
91
|
_ENTITIES = {"amp": "&", "lt": "<", "gt": ">", "quot": '"', "apos": "'"}
|
|
87
92
|
|
|
88
93
|
|
|
@@ -211,6 +216,13 @@ def _doi_named(pages: str, target: str) -> bool:
|
|
|
211
216
|
return re.search(rf"(?<![0-9.]){head}{pattern(suffix)}(?![0-9a-z_/-]|\.[0-9a-z])", pages) is not None
|
|
212
217
|
|
|
213
218
|
|
|
219
|
+
def _doi_above_copyright(text: str, target: str) -> bool:
|
|
220
|
+
"""The target DOI with the copyright line right after it: its own footer, wherever
|
|
221
|
+
the text extraction put it."""
|
|
222
|
+
return any(_bare(_clean_doi(match)) == _bare(target) and _COPYRIGHT_AFTER.match(text, match.end())
|
|
223
|
+
for match in _DOI_IN_TEXT.finditer(text))
|
|
224
|
+
|
|
225
|
+
|
|
214
226
|
def _clean_doi(match: re.Match[str]) -> str:
|
|
215
227
|
return re.sub(r"[.,;:)\]]+$", "", re.sub(r"\s+", "", match.group(0)))
|
|
216
228
|
|
|
@@ -268,7 +280,8 @@ def evidence(first_pages: str, identifier: str, title: str = "") -> dict | None:
|
|
|
268
280
|
front = _REFERENCES_HEADING.split(text, maxsplit=1)[0]
|
|
269
281
|
target = _target_doi(identifier)
|
|
270
282
|
chars, at = _letters(front)
|
|
271
|
-
|
|
283
|
+
own_footer = _doi_above_copyright(text, target)
|
|
284
|
+
doi = _doi_named(front, target) or own_footer
|
|
272
285
|
found = _title_evidence(front, chars, at, title) if (title or "").strip() else None
|
|
273
286
|
if found is None and doi and _short_title_beside_doi(front, target, title or ""):
|
|
274
287
|
found = "single"
|
|
@@ -282,7 +295,9 @@ def evidence(first_pages: str, identifier: str, title: str = "") -> dict | None:
|
|
|
282
295
|
# editor" heading) and print no other DOI. A notice about an article prints its
|
|
283
296
|
# own DOI as well ("Author Correction" then "Correction to: Nature
|
|
284
297
|
# https://doi.org/<the article>"; a Frontiers corrigendum, 2026-11-02).
|
|
285
|
-
|
|
298
|
+
# Its DOI above its copyright line names it as well as its header does (a letter with
|
|
299
|
+
# a short title, 2026-11-13).
|
|
300
|
+
named = (_doi_named(front[:HEAD_CHARS], target) or own_footer or (doi and found == "strong")) and not others
|
|
286
301
|
return {
|
|
287
302
|
"not_article": _not_the_article(text[:HEAD_CHARS], title or "", named),
|
|
288
303
|
"doi": doi,
|
|
@@ -305,8 +320,14 @@ def _source_names_doi(source: str, target: str) -> bool:
|
|
|
305
320
|
"""The URL a PDF came from names the DOI, not as part of a longer DOI (a ".pdf" may follow)."""
|
|
306
321
|
if not re.match(r"10\.\d{4,9}/\S", target):
|
|
307
322
|
return False
|
|
308
|
-
|
|
309
|
-
|
|
323
|
+
url = _decoded(source).lower()
|
|
324
|
+
if re.search(rf"(?<![0-9.]){re.escape(target)}(?![0-9a-z_/-]|\.(?!pdf(?![0-9a-z]))[0-9a-z])", url):
|
|
325
|
+
return True
|
|
326
|
+
# A suffix long enough to name one article on its own, as a path segment: an Elsevier
|
|
327
|
+
# PII ("/article/S1063-4584(25)01284-1/pdf" for 10.1016/S1063-4584(25)01284-1, 2026-11-13).
|
|
328
|
+
suffix = _suffix(target)
|
|
329
|
+
return len(_bare(suffix)) >= SHARED_SUFFIX and re.search(
|
|
330
|
+
rf"/{re.escape(suffix)}(?![0-9a-z_-]|\.(?!pdf(?![0-9a-z]))[0-9a-z])", url) is not None
|
|
310
331
|
|
|
311
332
|
|
|
312
333
|
def assess(first_pages: str, identifier: str, title: str = "", source: str = "") -> str:
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "azsciencenet",
|
|
3
|
+
"name": "AzScienceNet",
|
|
4
|
+
"country": "AZ",
|
|
5
|
+
"registration_authorities": ["https://edugain.azsciencenet.az"],
|
|
6
|
+
"chooser_labels": ["AzScienceNet Identity Federation"],
|
|
7
|
+
"chooser_pattern": "\\bAzScienceNet\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["edugain.azsciencenet.az"],
|
|
10
|
+
"metadata_url": "https://registry1.azsciencenet.az/rr3/signedmetadata/federation/AzScienceNetIF/metadata.xml"
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "belnet",
|
|
3
|
+
"name": "Belnet",
|
|
4
|
+
"country": "BE",
|
|
5
|
+
"registration_authorities": ["http://federation.belnet.be/"],
|
|
6
|
+
"chooser_labels": ["Belnet Federation"],
|
|
7
|
+
"chooser_pattern": "\\bBelnet\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["federation.belnet.be"],
|
|
10
|
+
"metadata_url": "https://federation.belnet.be/metadata/edugain-metadata.xml"
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "cstcloud",
|
|
3
|
+
"name": "CSTCloud",
|
|
4
|
+
"country": "CN",
|
|
5
|
+
"registration_authorities": ["https://www.cstcloud.net/"],
|
|
6
|
+
"chooser_labels": ["CSTCloud Federation"],
|
|
7
|
+
"chooser_pattern": "\\bCSTCloud\\b|中国科技云",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["cstcloud.net"],
|
|
10
|
+
"metadata_url": "http://www.cstcloud.net/discovery/metadata/cstcloud-fed-metadata-sig.xml"
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "cynet",
|
|
3
|
+
"name": "CyNet",
|
|
4
|
+
"country": "CY",
|
|
5
|
+
"registration_authorities": ["https://cif.cynet.ac.cy"],
|
|
6
|
+
"chooser_labels": ["CyNet Identity Federation"],
|
|
7
|
+
"chooser_pattern": "\\bCyNet\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["cif.cynet.ac.cy"],
|
|
10
|
+
"metadata_url": "https://cif.cynet.ac.cy/md/edugain-upstream.xml"
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "edugate",
|
|
3
|
+
"name": "Edugate",
|
|
4
|
+
"country": "IE",
|
|
5
|
+
"registration_authorities": ["http://www.heanet.ie"],
|
|
6
|
+
"chooser_labels": ["Ireland - Edugate Federation"],
|
|
7
|
+
"chooser_pattern": "\\bEdugate\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["edugate.heanet.ie"],
|
|
10
|
+
"metadata_url": "https://edugate.heanet.ie/rr3/signedmetadata/federationexport/ZWR1R0FJTg~~/metadata.xml"
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "eduidlu",
|
|
3
|
+
"name": "eduID Luxembourg",
|
|
4
|
+
"country": "LU",
|
|
5
|
+
"registration_authorities": ["http://eduid.lu"],
|
|
6
|
+
"chooser_labels": ["eduID Luxembourg"],
|
|
7
|
+
"chooser_pattern": "\\beduID\\s+Luxembourg\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["eduid.lu"],
|
|
10
|
+
"metadata_url": "https://www.eduid.lu/metadata/upstream.xml"
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "irfed",
|
|
3
|
+
"name": "IRFED",
|
|
4
|
+
"country": "IR",
|
|
5
|
+
"registration_authorities": ["https://irfed.ir/"],
|
|
6
|
+
"chooser_labels": ["IRFED"],
|
|
7
|
+
"chooser_pattern": "\\bIRFED\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["irfed.ir"],
|
|
10
|
+
"metadata_url": "https://irfed.ir/IRFED.xml"
|
|
11
|
+
}
|