papersearch 0.5.15 → 0.6.0
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 +28 -9
- package/README.md +28 -9
- package/carsi/paper_search_carsi/adapters/base.py +7 -0
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +23 -3
- package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +14 -11
- package/carsi/paper_search_carsi/adapters/sage/__init__.py +2 -4
- package/carsi/paper_search_carsi/adapters/thieme/__init__.py +12 -10
- package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +2 -1
- package/carsi/paper_search_carsi/cli.py +65 -22
- package/carsi/paper_search_carsi/cold_start.py +3 -1
- package/carsi/paper_search_carsi/config.py +10 -3
- package/carsi/paper_search_carsi/download_diagnostics.py +1 -1
- package/carsi/paper_search_carsi/engine/batch_access.py +3 -2
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +1 -1
- package/carsi/paper_search_carsi/engine/batch_institution.py +199 -79
- package/carsi/paper_search_carsi/engine/batch_login.py +39 -24
- package/carsi/paper_search_carsi/engine/batch_waits.py +2 -1
- package/carsi/paper_search_carsi/engine/bridge.py +16 -18
- package/carsi/paper_search_carsi/engine/login_wait.py +25 -3
- package/carsi/paper_search_carsi/federations/__init__.py +155 -0
- package/carsi/paper_search_carsi/federations/builtin/carsi.json +22 -0
- package/carsi/paper_search_carsi/federations/builtin/gakunin.json +11 -0
- package/carsi/paper_search_carsi/federations/builtin/hkaf.json +12 -0
- package/carsi/paper_search_carsi/federations/builtin/kafe.json +11 -0
- package/carsi/paper_search_carsi/federations/builtin/openathens.json +21 -0
- package/carsi/paper_search_carsi/federations/builtin/sgaf.json +11 -0
- package/carsi/paper_search_carsi/federations/builtin/sifulan.json +11 -0
- package/carsi/paper_search_carsi/federations/schools.py +393 -0
- package/carsi/paper_search_carsi/report_sanitizer.py +15 -0
- package/carsi/pyproject.toml +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +23 -16
- package/dist/management/carsi/installer.js.map +1 -1
- package/package.json +1 -1
- package/skills/paper-search/SKILL.md +4 -3
- package/skills/paper-search/references/carsi-setup.md +9 -8
- package/skills/paper-search/references/cli-contract.md +1 -1
- package/skills/paper-search/references/federation-support.md +31 -0
- package/skills/paper-search/references/setup.md +1 -1
|
@@ -341,8 +341,9 @@ class AccessMixin:
|
|
|
341
341
|
"library", "libraries", "hospital", "the", "and", "for"})
|
|
342
342
|
|
|
343
343
|
def _school_names(self) -> list[str]:
|
|
344
|
-
|
|
345
|
-
|
|
344
|
+
from ..federations import schools
|
|
345
|
+
|
|
346
|
+
return [n for n in [*schools.names(self.config), str(self.institution_query or "").strip()] if n]
|
|
346
347
|
|
|
347
348
|
def _names_configured_school(self, label: str) -> bool:
|
|
348
349
|
"""The label contains the configured school's Chinese name or every
|
|
@@ -98,7 +98,7 @@ class DiagnosticsMixin:
|
|
|
98
98
|
"sso_start": ("正在查找机构登录入口", "checking_access"),
|
|
99
99
|
"institution_federation_selected": ("已进入所选机构认证联盟", "checking_access"),
|
|
100
100
|
"institution_selection_required": ("检查学校选择入口", "checking_access"),
|
|
101
|
-
"institution_entry_unresolved": ("
|
|
101
|
+
"institution_entry_unresolved": ("官方机构入口尚未确认所属联盟", "checking_access"),
|
|
102
102
|
"login_state": ("检查机构登录页面", "checking_access"),
|
|
103
103
|
"idp_confirmation_required": ("请在浏览器里确认学校认证页的提示(信息发送同意、使用条款或二次验证)", "waiting_login"),
|
|
104
104
|
"idp_confirmation_accepted": ("已确认学校认证页的提示", "checking_access"),
|
|
@@ -9,22 +9,17 @@ import time
|
|
|
9
9
|
from typing import Any
|
|
10
10
|
from urllib.parse import parse_qs, unquote, urlencode, urljoin, urlparse
|
|
11
11
|
|
|
12
|
+
from .. import federations
|
|
13
|
+
from ..federations import schools
|
|
12
14
|
from .batch_common import (DownloadResult, _is_browser_error, _is_navigation_cut, logger, open_page,
|
|
13
15
|
pump_until, settle)
|
|
14
16
|
|
|
15
17
|
|
|
16
18
|
def _school_auth_patterns(config: dict[str, Any]) -> tuple[str, ...]:
|
|
17
|
-
"""The configured school's
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
empty without one. The package names no school itself.
|
|
22
|
-
"""
|
|
23
|
-
entity_id = str(config.get("idp_entity_id", "") or "").strip()
|
|
24
|
-
if not entity_id.startswith("https://"):
|
|
25
|
-
return ()
|
|
26
|
-
host = (urlparse(entity_id).hostname or "").lower()
|
|
27
|
-
return (host,) if host else ()
|
|
19
|
+
"""The configured school's login hosts, for telling its login pages apart
|
|
20
|
+
(``schools.login_hosts``: its entityID's host and those its federation lists);
|
|
21
|
+
empty without one. The package names no school itself."""
|
|
22
|
+
return schools.login_hosts(config)
|
|
28
23
|
|
|
29
24
|
|
|
30
25
|
# Institution search input selectors, tried in order on WAYF pages
|
|
@@ -41,6 +36,12 @@ class InstitutionMixin:
|
|
|
41
36
|
# The school chosen this often on one chooser address, the chooser back each time.
|
|
42
37
|
SCHOOL_CHOICE_REPEATS = 3
|
|
43
38
|
|
|
39
|
+
@property
|
|
40
|
+
def federation(self) -> "federations.Federation | None":
|
|
41
|
+
"""The federation of the user's school (the federation layer); None: no
|
|
42
|
+
school is configured and the user chooses the institution."""
|
|
43
|
+
return federations.configured(self.config)
|
|
44
|
+
|
|
44
45
|
@staticmethod
|
|
45
46
|
def _school_choices_here(result: DownloadResult, url: str) -> int:
|
|
46
47
|
return sum(e["state"] == "auto_institution_entry" and str(e.get("detail", "")).endswith(f"@ {url}")
|
|
@@ -73,7 +74,14 @@ class InstitutionMixin:
|
|
|
73
74
|
return False # the user reported a wrong school: they choose it in the window
|
|
74
75
|
if self.adapter.leave_email_step(page, result):
|
|
75
76
|
return True # an email field takes no school name (Elsevier ID, 2026-11-11)
|
|
76
|
-
|
|
77
|
+
federation = self.federation
|
|
78
|
+
if federation is not None:
|
|
79
|
+
here = str(getattr(page, "url", "") or "")
|
|
80
|
+
if self._is_idp_host(urlparse(here).netloc) or self._on_school_login_page(here):
|
|
81
|
+
# The school's own login page is the user's: nothing is chosen or
|
|
82
|
+
# typed there (its CAS page took the school's name in a search
|
|
83
|
+
# field once, 2026-11-11).
|
|
84
|
+
return False
|
|
77
85
|
if self._has_publisher_institution_session(page):
|
|
78
86
|
# The publisher already shows a signed-in school: nothing to choose
|
|
79
87
|
# (RSC's account menu names it and was clicked as an entry, 2026-11-01).
|
|
@@ -81,6 +89,10 @@ class InstitutionMixin:
|
|
|
81
89
|
here = str(getattr(page, "url", "") or "")
|
|
82
90
|
if self._school_choices_here(result, here) >= self.SCHOOL_CHOICE_REPEATS:
|
|
83
91
|
return self._after_repeated_school_choice(page, result, here)
|
|
92
|
+
# The OpenAthens wayfinder goes straight to the school's entity on the
|
|
93
|
+
# route that signs in there.
|
|
94
|
+
if federation.openathens_entries and self._select_openathens_wayfinder(page, result):
|
|
95
|
+
return True
|
|
84
96
|
# Everything except human verification and the user's credentials is
|
|
85
97
|
# automated once an institution is configured: a remembered
|
|
86
98
|
# "Access through <school>" entry, the school in a publisher list or
|
|
@@ -89,10 +101,10 @@ class InstitutionMixin:
|
|
|
89
101
|
return True
|
|
90
102
|
if self.institution_query and self._assist_configured_institution(page, result):
|
|
91
103
|
return True
|
|
92
|
-
if self.institution_query and self.
|
|
104
|
+
if self.institution_query and self._select_federation_link(page, result, here):
|
|
93
105
|
return True
|
|
94
106
|
if self.institution_query and not getattr(result, "_institution_not_listed", False):
|
|
95
|
-
self.
|
|
107
|
+
self._check_federation_school_links(page, result, here)
|
|
96
108
|
if getattr(result, "_institution_not_listed", False):
|
|
97
109
|
return False
|
|
98
110
|
if self.adapter.prepare_institution_choice(page, result) is False:
|
|
@@ -110,10 +122,10 @@ class InstitutionMixin:
|
|
|
110
122
|
return False
|
|
111
123
|
if chosen is not None:
|
|
112
124
|
return chosen
|
|
113
|
-
if self.institution_query and self.
|
|
125
|
+
if self.institution_query and self._assist_federation_discovery(page, result):
|
|
114
126
|
return True
|
|
115
127
|
if not any(event["state"] == "institution_selection_required" for event in result.events):
|
|
116
|
-
self._event(result, "institution_selection_required",
|
|
128
|
+
self._event(result, "institution_selection_required", federation.code)
|
|
117
129
|
return False
|
|
118
130
|
current_url = str(getattr(page, "url", "") or "")
|
|
119
131
|
host = (urlparse(current_url).netloc or "").lower()
|
|
@@ -233,7 +245,6 @@ class InstitutionMixin:
|
|
|
233
245
|
}
|
|
234
246
|
return null;
|
|
235
247
|
}"""
|
|
236
|
-
_CARSI_OPTION = re.compile(r"\bCARSI\b", re.I)
|
|
237
248
|
_FEDERATION_LINK_LIST = "ul.federation--list"
|
|
238
249
|
_FEDERATION_SCHOOL_LIST = "ul.federation--list-inner"
|
|
239
250
|
# How long one pass waits for the school's option once the federation is chosen
|
|
@@ -266,11 +277,14 @@ class InstitutionMixin:
|
|
|
266
277
|
return select, hits[0][0], hits[0][1], "entityID" if by_id else "name"
|
|
267
278
|
return None
|
|
268
279
|
|
|
269
|
-
def
|
|
270
|
-
"""``(select, value, label)``: a federation list's single
|
|
280
|
+
def _federation_option(self, lists: list[dict]) -> tuple[dict, str, str] | None:
|
|
281
|
+
"""``(select, value, label)``: a federation list's single entry for the school's federation."""
|
|
282
|
+
federation = self.federation
|
|
283
|
+
if federation is None:
|
|
284
|
+
return None
|
|
271
285
|
for select in lists:
|
|
272
286
|
hits = [(str(o[0]), str(o[1])) for o in select.get("options") or ()
|
|
273
|
-
if isinstance(o, (list, tuple)) and len(o) == 2 and o[0] and
|
|
287
|
+
if isinstance(o, (list, tuple)) and len(o) == 2 and o[0] and federation.matches(str(o[1]))]
|
|
274
288
|
if len(hits) == 1:
|
|
275
289
|
return select, hits[0][0], hits[0][1]
|
|
276
290
|
return None
|
|
@@ -309,8 +323,8 @@ class InstitutionMixin:
|
|
|
309
323
|
_PAGE_LOAD_JS = "() => performance.timeOrigin"
|
|
310
324
|
|
|
311
325
|
def _federation_choice_page(self, page: Any, result: DownloadResult) -> tuple[str, str] | None:
|
|
312
|
-
"""This page (its address and its load) when
|
|
313
|
-
federation list now; None when not: the program chose
|
|
326
|
+
"""This page (its address and its load) when the school's federation may be chosen in its
|
|
327
|
+
federation list now; None when not: the program chose the federation on this very
|
|
314
328
|
page and it shows another federation since (the user's choice, left alone),
|
|
315
329
|
or the page is navigating (looked at again next pass). A chooser that
|
|
316
330
|
reloads, at the same address or another, with its first federation
|
|
@@ -332,45 +346,48 @@ class InstitutionMixin:
|
|
|
332
346
|
return None
|
|
333
347
|
|
|
334
348
|
def _federation_chosen(self, result: DownloadResult, here: tuple[str, str], detail: str) -> None:
|
|
335
|
-
"""Record that the program chose
|
|
349
|
+
"""Record that the program chose the school's federation on page ``here`` (``_federation_choice_page``)."""
|
|
336
350
|
result._federation_pages = getattr(result, "_federation_pages", set()) | {here}
|
|
337
351
|
self._event(result, "institution_federation_selected", detail)
|
|
338
352
|
|
|
339
|
-
def
|
|
340
|
-
|
|
353
|
+
def _select_federation_link(self, page: Any, result: DownloadResult, url: str) -> bool:
|
|
354
|
+
"""A publisher's list of federation links (Atypon's): the school's federation's."""
|
|
355
|
+
federation = self.federation
|
|
356
|
+
if federation is None or not self._on_publisher_host(url):
|
|
341
357
|
return False
|
|
342
358
|
listing = page.locator(self._FEDERATION_LINK_LIST).first
|
|
343
359
|
try:
|
|
344
360
|
if listing.is_visible() is not True:
|
|
345
361
|
return False
|
|
346
|
-
links = listing.get_by_role("link", name=
|
|
362
|
+
links = listing.get_by_role("link", name=federation.chooser_pattern)
|
|
347
363
|
if links.count() != 1:
|
|
348
364
|
return False
|
|
349
365
|
href = links.first.get_attribute("href", timeout=800)
|
|
350
366
|
if not href or not self._manual_institution_target_allowed(urljoin(url, href)):
|
|
351
367
|
return False
|
|
352
368
|
here = self._federation_choice_page(page, result)
|
|
353
|
-
if here is None or not self._click_control(page, links.first, result, "choose
|
|
369
|
+
if here is None or not self._click_control(page, links.first, result, f"choose {federation.name} federation"):
|
|
354
370
|
return False
|
|
355
371
|
except Exception as exc:
|
|
356
372
|
if not _is_browser_error(exc):
|
|
357
373
|
raise
|
|
358
374
|
self._event(result, "institution_step_interrupted", type(exc).__name__)
|
|
359
375
|
return False
|
|
360
|
-
self._federation_chosen(result, here, f"
|
|
376
|
+
self._federation_chosen(result, here, f"{federation.code}: federation link @ {url}")
|
|
361
377
|
return True
|
|
362
378
|
|
|
363
|
-
def
|
|
364
|
-
"""Only a complete link directory can establish absence after choosing
|
|
365
|
-
|
|
379
|
+
def _check_federation_school_links(self, page: Any, result: DownloadResult, url: str) -> None:
|
|
380
|
+
"""Only a complete link directory can establish absence after choosing the federation."""
|
|
381
|
+
federation = self.federation
|
|
382
|
+
if federation is None or not self._on_publisher_host(url):
|
|
366
383
|
return
|
|
367
384
|
try:
|
|
368
385
|
listing = page.locator(self._FEDERATION_SCHOOL_LIST).first
|
|
369
386
|
if listing.is_visible() is not True:
|
|
370
387
|
return
|
|
371
|
-
heading = page.get_by_role("heading", level=1, name=
|
|
388
|
+
heading = page.get_by_role("heading", level=1, name=federation.chooser_pattern).first
|
|
372
389
|
if heading.is_visible() is not True or self._is_challenge_page(page):
|
|
373
|
-
self._school_list_unconfirmed(result, url, "no
|
|
390
|
+
self._school_list_unconfirmed(result, url, f"no {federation.name} heading, or a verification page")
|
|
374
391
|
return
|
|
375
392
|
rows = listing.locator(":scope > li")
|
|
376
393
|
entries = page.evaluate(self._ENTRIES_JS, self._FEDERATION_SCHOOL_LIST + " > li > a[href]")
|
|
@@ -387,7 +404,8 @@ class InstitutionMixin:
|
|
|
387
404
|
if any(self._institution_entry_score(entry, entity_id)
|
|
388
405
|
or self._canonical_school_name(entry["t"]) in names for entry in entries):
|
|
389
406
|
return
|
|
390
|
-
self._event(result, "auto_institution_not_found",
|
|
407
|
+
self._event(result, "auto_institution_not_found",
|
|
408
|
+
f"{self.institution_query} ({federation.name} list, {len(entries)} schools) @ {url}")
|
|
391
409
|
result._institution_not_listed = True
|
|
392
410
|
except Exception as exc:
|
|
393
411
|
if not _is_browser_error(exc):
|
|
@@ -395,11 +413,11 @@ class InstitutionMixin:
|
|
|
395
413
|
self._event(result, "institution_step_interrupted", type(exc).__name__)
|
|
396
414
|
|
|
397
415
|
def _school_list_unconfirmed(self, result: DownloadResult, url: str, why: str) -> None:
|
|
398
|
-
"""Why a shown
|
|
416
|
+
"""Why a shown school list of the federation could not settle the school's absence, once per page:
|
|
399
417
|
the school was left to choose by hand and the wait ran out (Science, 2026-11-11)."""
|
|
400
|
-
if not any(e["state"] == "
|
|
418
|
+
if not any(e["state"] == "federation_school_list_unconfirmed" and str(e.get("detail", "")).endswith(f"@ {url}")
|
|
401
419
|
for e in result.events):
|
|
402
|
-
self._event(result, "
|
|
420
|
+
self._event(result, "federation_school_list_unconfirmed", f"{why} @ {url}")
|
|
403
421
|
|
|
404
422
|
def _close_blank_overlay(self, page: Any, result: DownloadResult) -> None:
|
|
405
423
|
try:
|
|
@@ -413,7 +431,7 @@ class InstitutionMixin:
|
|
|
413
431
|
|
|
414
432
|
def _select_from_institution_lists(self, page: Any, result: DownloadResult) -> bool:
|
|
415
433
|
"""One rule for school lists in <select>s, shown or hidden: the federation
|
|
416
|
-
list's
|
|
434
|
+
list's entry for the school's federation, then the school's option (by entityID, the
|
|
417
435
|
option's value, else by name), then the list's own submit control. Once per
|
|
418
436
|
page; True when something was chosen. Without the school in a filled list
|
|
419
437
|
the publisher has no route for it (``_institution_not_listed``)."""
|
|
@@ -425,7 +443,7 @@ class InstitutionMixin:
|
|
|
425
443
|
return False # only the publisher's and the federations' choosers
|
|
426
444
|
lists = self._page_selects(page)
|
|
427
445
|
school = self._school_option(lists)
|
|
428
|
-
federation = None if school else self.
|
|
446
|
+
federation = None if school else self._federation_option(lists)
|
|
429
447
|
if school is None and federation is None:
|
|
430
448
|
return False
|
|
431
449
|
if federation is not None:
|
|
@@ -439,7 +457,7 @@ class InstitutionMixin:
|
|
|
439
457
|
if here is None:
|
|
440
458
|
return False
|
|
441
459
|
self._set_select(page, select, value)
|
|
442
|
-
self._federation_chosen(result, here, f"
|
|
460
|
+
self._federation_chosen(result, here, f"{self.federation.code}: {label} in {select.get('name')} @ {url}")
|
|
443
461
|
page.wait_for_timeout(500)
|
|
444
462
|
self._close_blank_overlay(page, result)
|
|
445
463
|
started, seen = time.time(), {}
|
|
@@ -457,7 +475,7 @@ class InstitutionMixin:
|
|
|
457
475
|
name, options = next(iter(filled.items()))
|
|
458
476
|
sample = ", ".join(str(o[1]) for o in options[1:6])
|
|
459
477
|
self._event(result, "auto_institution_not_found",
|
|
460
|
-
f"
|
|
478
|
+
f"{self.federation.code} list {name} ({len(options)} options: {sample}) @ {url}")
|
|
461
479
|
result._institution_not_listed = True
|
|
462
480
|
return False
|
|
463
481
|
count = max((len(s.get("options") or ()) for s in seen.get("lists") or () if s.get("i") != select.get("i")), default=0)
|
|
@@ -525,8 +543,11 @@ class InstitutionMixin:
|
|
|
525
543
|
if head >= 2 and all(self._institution_match_score(note) >= 2 for note in notes):
|
|
526
544
|
return head
|
|
527
545
|
best = 0
|
|
546
|
+
text = re.sub(r"^the ", "", text) # "University of Kita" is "The University of Kita"
|
|
547
|
+
if self._name_residue(text) == "":
|
|
548
|
+
return 3 # only the school's own names ("<Chinese name> <English name>")
|
|
528
549
|
for name in self._institution_names():
|
|
529
|
-
name = " ".join(name.translate(self._QUOTES).split()).lower()
|
|
550
|
+
name = re.sub(r"^the ", "", " ".join(name.translate(self._QUOTES).split()).lower())
|
|
530
551
|
if not name:
|
|
531
552
|
continue
|
|
532
553
|
if text == name:
|
|
@@ -568,6 +589,77 @@ class InstitutionMixin:
|
|
|
568
589
|
return 4
|
|
569
590
|
return self._institution_match_score(entry.get("t", ""))
|
|
570
591
|
|
|
592
|
+
def _name_residue(self, text: str) -> str | None:
|
|
593
|
+
"""What is left of ``text`` (lower case) once the school's names are taken
|
|
594
|
+
out, as words; None when it holds none of them."""
|
|
595
|
+
names = sorted({re.sub(r"^the ", "", " ".join(n.translate(self._QUOTES).split()).lower())
|
|
596
|
+
for n in self._institution_names()} - {""}, key=len, reverse=True)
|
|
597
|
+
rest, found = f" {text} ", False
|
|
598
|
+
for name in names:
|
|
599
|
+
if name in rest:
|
|
600
|
+
rest, found = rest.replace(name, " "), True
|
|
601
|
+
return " ".join(re.sub(r"[\W_]+", " ", rest).split()) if found else None
|
|
602
|
+
|
|
603
|
+
# Words a unit of the school itself may add to its name (its library, campus,
|
|
604
|
+
# hospital): such an entry may be the school's, so the search settles nothing.
|
|
605
|
+
_OWN_UNIT = re.compile(r"^(?:graduate school|school of|faculty of|department of|institute of|cent(?:er|re) for)\b"
|
|
606
|
+
r"|^(?:(?:the|main|central|university|univ|library|libraries|campus|branch|hospital|"
|
|
607
|
+
r"medical|medicine|dentistry|nursing|pharmacy|law|business|graduate|department|"
|
|
608
|
+
r"health|engineering|center|centre|faculty|school|college|of|and)\b\s*)+$")
|
|
609
|
+
|
|
610
|
+
# A search's own word that it found nothing (Elsevier's "Can't find your
|
|
611
|
+
# institution?" is always there and does not count).
|
|
612
|
+
_NO_RESULTS = re.compile(r"\bno (?:results?|matches|matching (?:institutions?|organi[sz]ations?)|"
|
|
613
|
+
r"(?:institutions?|organi[sz]ations?) (?:were )?found)\b|\b0 results\b|"
|
|
614
|
+
r"没有找到|无结果|未找到|找不到(?:相关|匹配)", re.I)
|
|
615
|
+
# How long the results must stay the same before they settle the school's absence.
|
|
616
|
+
SEARCH_SETTLED_SEC = 4
|
|
617
|
+
|
|
618
|
+
def _search_lists_no_school(self, page: Any, result: DownloadResult, url: str, scored: list) -> bool:
|
|
619
|
+
"""The school's name was searched on this page, the results are shown and
|
|
620
|
+
have not changed for ``SEARCH_SETTLED_SEC``, and none is the school: other
|
|
621
|
+
schools whose names contain its own ("<school> of Advanced Science",
|
|
622
|
+
Elsevier 2026-11-11), or the search saying it found none. Then the publisher has no entry for the school: the login ends at
|
|
623
|
+
once (``_institution_not_listed``), not at the end of the wait."""
|
|
624
|
+
def searched_here(event: dict) -> bool:
|
|
625
|
+
# A record keeps 500 characters: a long address (Elsevier ID's) is cut short in it.
|
|
626
|
+
where = str(event.get("detail", "")).split(" @ ", 1)[-1]
|
|
627
|
+
return event["state"] == "auto_institution_search" and len(where) > 10 and url.startswith(where)
|
|
628
|
+
|
|
629
|
+
if not any(searched_here(e) for e in result.events):
|
|
630
|
+
return False # nothing searched here: a page's other lists say nothing
|
|
631
|
+
others = sorted({str(it.get("t") or "")[:80] for score, it in scored if score == 1})
|
|
632
|
+
# A unit of the school (its library, campus, a faculty) may be its way in,
|
|
633
|
+
# unless its publisher marks it as signing in no one (IP, VPN, email).
|
|
634
|
+
may_sign_in = [str(it.get("t") or "") for score, it in scored if score == 1
|
|
635
|
+
and self.adapter.institution_entry_signs_in(unquote(str(it.get("ids") or ""))) is not False]
|
|
636
|
+
residues = [self._name_residue(" ".join(o.translate(self._QUOTES).split()).lower()) for o in may_sign_in]
|
|
637
|
+
if any(r is not None and self._OWN_UNIT.match(r) for r in residues):
|
|
638
|
+
return False # perhaps the school's own library or campus: left to the user
|
|
639
|
+
if others:
|
|
640
|
+
evidence = f"{len(others)} other entries: " + "; ".join(others[:3])
|
|
641
|
+
else:
|
|
642
|
+
try:
|
|
643
|
+
said = self._NO_RESULTS.search(self._body_text(page, 4_000) or "")
|
|
644
|
+
except Exception as exc:
|
|
645
|
+
if not _is_browser_error(exc):
|
|
646
|
+
raise
|
|
647
|
+
return False
|
|
648
|
+
if not said:
|
|
649
|
+
return False # results not shown yet: looked at again next pass
|
|
650
|
+
evidence = f'"{said.group(0)}"'
|
|
651
|
+
now = time.time()
|
|
652
|
+
seen = getattr(result, "_search_miss", None)
|
|
653
|
+
if not seen or seen[0] != url or seen[1] != evidence:
|
|
654
|
+
result._search_miss = (url, evidence, now)
|
|
655
|
+
return False
|
|
656
|
+
if now - seen[2] < self.SEARCH_SETTLED_SEC:
|
|
657
|
+
return False
|
|
658
|
+
self._event(result, "auto_institution_not_found",
|
|
659
|
+
f"{self.institution_query} (search: {evidence[:160]}) @ {url}")
|
|
660
|
+
result._institution_not_listed = True
|
|
661
|
+
return True
|
|
662
|
+
|
|
571
663
|
def _click_unique_institution_entry(self, page: Any, result: DownloadResult, url: str) -> bool:
|
|
572
664
|
"""Click the single best visible entry for the configured school.
|
|
573
665
|
|
|
@@ -588,11 +680,36 @@ class InstitutionMixin:
|
|
|
588
680
|
entity_id = self._entity_id()
|
|
589
681
|
|
|
590
682
|
scored = [(self._institution_entry_score(it, entity_id), it) for it in items if isinstance(it, dict)]
|
|
683
|
+
if self.federation is not None:
|
|
684
|
+
# An entry its publisher marks as signing in no school (Elsevier's
|
|
685
|
+
# entries carry their route: IP, VPN or a work email, no entityID) is
|
|
686
|
+
# not the school's sign-in, whatever its name (2026-11-11).
|
|
687
|
+
without = [it for score, it in scored if score >= 2
|
|
688
|
+
and self.adapter.institution_entry_signs_in(unquote(str(it.get("ids") or ""))) is False]
|
|
689
|
+
if without:
|
|
690
|
+
scored = [(score, it) for score, it in scored if not any(it is w for w in without)]
|
|
691
|
+
if not any(score >= 2 for score, _ in scored):
|
|
692
|
+
self._event(result, "auto_institution_not_found",
|
|
693
|
+
f"{self.institution_query} (listed only without a school sign-in: "
|
|
694
|
+
f"{len(without)} entr{'y' if len(without) == 1 else 'ies'}) @ {url}")
|
|
695
|
+
result._institution_not_listed = True
|
|
696
|
+
return False
|
|
591
697
|
top = max([score for score, _ in scored] or [0])
|
|
592
698
|
best = [it for score, it in scored if score == top]
|
|
699
|
+
if top < 2 and self.federation is not None and self._search_lists_no_school(page, result, url, scored):
|
|
700
|
+
return False
|
|
593
701
|
same = (len(best) == 1 or top == 4
|
|
594
702
|
or (len({(it.get("t"), it.get("h")) for it in best}) == 1 and best[0].get("h")))
|
|
595
703
|
if top < 2 or not same:
|
|
704
|
+
# The entries' names first (all of them), then what each carries.
|
|
705
|
+
seen = (" | ".join(str(it.get("t") or "")[:50] for it in best[:8]) + " :: "
|
|
706
|
+
+ "; ".join(unquote(str(it.get("ids") or ""))[:600] for it in best[:4]))
|
|
707
|
+
if top >= 1 and not any(e["state"] == "institution_entries_ambiguous"
|
|
708
|
+
and str(e.get("detail", "")).startswith(seen) for e in result.events):
|
|
709
|
+
# Which entries were alike, and what each carries: the record to
|
|
710
|
+
# tell the school's entry from the others by (Elsevier listed two
|
|
711
|
+
# entries with one school's name, neither its federation's, 2026-11-11).
|
|
712
|
+
self._event(result, "institution_entries_ambiguous", f"{seen} @ {url[:200]}")
|
|
596
713
|
return False
|
|
597
714
|
target = best[0]
|
|
598
715
|
before = str(getattr(page, "url", "") or "")
|
|
@@ -642,6 +759,10 @@ class InstitutionMixin:
|
|
|
642
759
|
return False
|
|
643
760
|
self._event(result, "auto_institution_entry", f"{target['t'][:80]} @ {url}")
|
|
644
761
|
self._event(result, "institution_selected", target["t"][:80] + (" (entityID)" if top == 4 else ""))
|
|
762
|
+
if top < 4:
|
|
763
|
+
# Chosen by its name: what the entry carries, to tell later whether it
|
|
764
|
+
# was the school's sign-in (Elsevier's entries carry their route, 2026-11-11).
|
|
765
|
+
self._event(result, "institution_entry_data", unquote(str(target.get("ids") or ""))[:480])
|
|
645
766
|
if not self._left_page(page, before):
|
|
646
767
|
# Elsevier ID's entry goes straight on to the school; its page's other
|
|
647
768
|
# "Submit and continue" belongs to something else.
|
|
@@ -819,8 +940,8 @@ class InstitutionMixin:
|
|
|
819
940
|
if not once("institution_search"):
|
|
820
941
|
return self._handle_institution_search_miss(page, result, url)
|
|
821
942
|
if not self._is_challenge_page(page):
|
|
822
|
-
if self.
|
|
823
|
-
self._event(result, "auto_institution_search", f"
|
|
943
|
+
if self._assist_federation_discovery(page, result):
|
|
944
|
+
self._event(result, "auto_institution_search", f"{self.federation.code} @ {url}")
|
|
824
945
|
return True
|
|
825
946
|
for selector in self._institution_search_selectors(page):
|
|
826
947
|
try:
|
|
@@ -924,15 +1045,16 @@ class InstitutionMixin:
|
|
|
924
1045
|
self._left_page(page, url, timeout_ms=10_000)
|
|
925
1046
|
return True
|
|
926
1047
|
|
|
927
|
-
def
|
|
928
|
-
"""On
|
|
1048
|
+
def _assist_federation_discovery(self, page: Any, result: DownloadResult) -> bool:
|
|
1049
|
+
"""On the school's federation's own discovery page (CARSI's), type the
|
|
1050
|
+
configured institution and click its entry.
|
|
929
1051
|
|
|
930
1052
|
Publisher federation choosers are left alone: there the only automatic
|
|
931
|
-
step is selecting the
|
|
1053
|
+
step is selecting the federation. Nothing is submitted here; the
|
|
932
1054
|
user confirms in the window. Without a match the page is left as is.
|
|
933
1055
|
"""
|
|
934
|
-
|
|
935
|
-
if not (
|
|
1056
|
+
federation = self.federation
|
|
1057
|
+
if federation is None or not federation.on_discovery_page(str(getattr(page, "url", "") or "")):
|
|
936
1058
|
return False
|
|
937
1059
|
if any(event["state"] == "institution_selected" for event in result.events):
|
|
938
1060
|
return False
|
|
@@ -944,7 +1066,7 @@ class InstitutionMixin:
|
|
|
944
1066
|
if (box.input_value(timeout=2_000) or "").strip():
|
|
945
1067
|
return False # the user already typed; never overwrite
|
|
946
1068
|
box.fill(self.institution_query)
|
|
947
|
-
self._event(result, "institution_search", f"
|
|
1069
|
+
self._event(result, "institution_search", f"{federation.code}:{selector}")
|
|
948
1070
|
pump_until(page, lambda: self._any_visible(page, self._institution_result_selectors()), 2_000)
|
|
949
1071
|
for result_selector in self._institution_result_selectors():
|
|
950
1072
|
try:
|
|
@@ -1018,49 +1140,39 @@ class InstitutionMixin:
|
|
|
1018
1140
|
|
|
1019
1141
|
# Campus identity-provider hostnames (idp.example.edu.cn, ids.lzu.edu.cn, sso.x.edu ...).
|
|
1020
1142
|
_IDP_HOST_RE = re.compile(r"^(?:idp?|ids|sso|cas|login|passport|auth(?:server)?|shibboleth|webauth)\.[^/]+\.edu(?:\.cn)?$")
|
|
1143
|
+
# Identity services schools sign in with behind their identity provider (the
|
|
1144
|
+
# school's own tenant there): Microsoft Entra, Okta, OneLogin, Auth0, Ping,
|
|
1145
|
+
# SeciossLink (2026-11-11: four schools' logins went on to these).
|
|
1146
|
+
_IDENTITY_SERVICE_HOSTS = ("login.microsoftonline.com", "okta.com", "oktapreview.com", "onelogin.com",
|
|
1147
|
+
"auth0.com", "pingone.com", "b2clogin.com", "secioss.com")
|
|
1021
1148
|
|
|
1022
1149
|
def _institution_names(self) -> tuple[str, ...]:
|
|
1023
1150
|
"""The school being chosen, plus its English name when it is the one saved by setup.
|
|
1024
1151
|
|
|
1025
|
-
Setup saves both names from the
|
|
1152
|
+
Setup saves both names from the federation's list; the package names no school itself.
|
|
1026
1153
|
"""
|
|
1027
1154
|
query = (self.institution_query or "").strip()
|
|
1028
1155
|
names = [query] if query else []
|
|
1029
|
-
if query and query ==
|
|
1030
|
-
|
|
1031
|
-
if english and english not in names:
|
|
1032
|
-
names.append(english)
|
|
1156
|
+
if query and query == schools.name(self.config):
|
|
1157
|
+
names.extend(n for n in schools.names(self.config) if n not in names)
|
|
1033
1158
|
return tuple(names)
|
|
1034
1159
|
|
|
1035
1160
|
def _entity_id(self) -> str:
|
|
1036
|
-
"""The configured school's SAML entityID
|
|
1037
|
-
from the CARSI list), else the CARSI list's entry for ``carsi_idp_name``."""
|
|
1161
|
+
"""The configured school's SAML entityID (``schools.entity_id``), resolved once."""
|
|
1038
1162
|
configured = str(self.config.get("idp_entity_id") or "").strip()
|
|
1039
1163
|
if configured:
|
|
1040
1164
|
return configured
|
|
1041
1165
|
resolved = getattr(self, "_resolved_entity_id", None)
|
|
1042
1166
|
if resolved is None:
|
|
1043
|
-
|
|
1044
|
-
|
|
1167
|
+
try:
|
|
1168
|
+
from ..config import DATA_DIR
|
|
1045
1169
|
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
try:
|
|
1053
|
-
from ..carsi_schools import CACHE_FILE, choose_school, parse_school_list
|
|
1054
|
-
from ..config import DATA_DIR
|
|
1055
|
-
|
|
1056
|
-
cache = DATA_DIR / CACHE_FILE
|
|
1057
|
-
if not cache.is_file():
|
|
1058
|
-
return ""
|
|
1059
|
-
school, _ = choose_school(parse_school_list(cache.read_text(encoding="utf-8")), name)
|
|
1060
|
-
except Exception as exc: # an unreadable copy: the names decide
|
|
1061
|
-
logger.info("institution: CARSI list unreadable (%s)", type(exc).__name__)
|
|
1062
|
-
return ""
|
|
1063
|
-
return school.entity_id if school else ""
|
|
1170
|
+
resolved = schools.entity_id(self.config, DATA_DIR)
|
|
1171
|
+
except Exception as exc: # an unreadable copy: the names decide
|
|
1172
|
+
logger.info("institution: member list unreadable (%s)", type(exc).__name__)
|
|
1173
|
+
resolved = ""
|
|
1174
|
+
self._resolved_entity_id = resolved
|
|
1175
|
+
return resolved
|
|
1064
1176
|
|
|
1065
1177
|
@staticmethod
|
|
1066
1178
|
def _carries_entity_id(text: str, entity_id: str) -> bool:
|
|
@@ -1074,6 +1186,11 @@ class InstitutionMixin:
|
|
|
1074
1186
|
pattern = re.compile(r"(?<![\w.:/-])" + re.escape(entity_id) + r"(?![\w.:/-])")
|
|
1075
1187
|
return any(pattern.search(t.replace("\\/", "/")) for t in decoded)
|
|
1076
1188
|
|
|
1189
|
+
def _on_school_login_page(self, url: str) -> bool:
|
|
1190
|
+
"""The configured school's own login page on a service shared by many
|
|
1191
|
+
schools (``schools.login_pages``: its OpenAthens sign-in page)."""
|
|
1192
|
+
return schools.on_login_page(self.config, url)
|
|
1193
|
+
|
|
1077
1194
|
def _is_idp_host(self, host: str) -> bool:
|
|
1078
1195
|
"""True for the configured school's identity provider or any generic campus IdP hostname."""
|
|
1079
1196
|
host = (host or "").lower().split(":")[0]
|
|
@@ -1081,6 +1198,8 @@ class InstitutionMixin:
|
|
|
1081
1198
|
return False
|
|
1082
1199
|
if any(token in host for token in _school_auth_patterns(self.config)):
|
|
1083
1200
|
return True
|
|
1201
|
+
if any(host == d or host.endswith("." + d) for d in (*schools.domains(self.config), *self._IDENTITY_SERVICE_HOSTS)):
|
|
1202
|
+
return True
|
|
1084
1203
|
return bool(self._IDP_HOST_RE.match(host))
|
|
1085
1204
|
|
|
1086
1205
|
def _institution_result_selectors(self) -> tuple[str, ...]:
|
|
@@ -1138,7 +1257,7 @@ class InstitutionMixin:
|
|
|
1138
1257
|
return False
|
|
1139
1258
|
|
|
1140
1259
|
_CHOOSER_URL_MARKERS = ("shibboleth.htm", "/action/ssostart", "wayfinder.openathens.net",
|
|
1141
|
-
"
|
|
1260
|
+
"/wayf", "/discovery", "/ds/", "institution-search")
|
|
1142
1261
|
|
|
1143
1262
|
# A search box naming an institution in its placeholder or label, or in its id or
|
|
1144
1263
|
# name (De Gruyter's LibLynx box has neither placeholder nor label, 2026-11-02).
|
|
@@ -1164,7 +1283,8 @@ class InstitutionMixin:
|
|
|
1164
1283
|
"""
|
|
1165
1284
|
try:
|
|
1166
1285
|
url = str(getattr(page, "url", "") or "").lower()
|
|
1167
|
-
if any(marker in url for marker in self._CHOOSER_URL_MARKERS)
|
|
1286
|
+
if (any(marker in url for marker in self._CHOOSER_URL_MARKERS)
|
|
1287
|
+
or any(domain in url for domain in federations.service_domains())):
|
|
1168
1288
|
return True
|
|
1169
1289
|
return bool(page.evaluate('''() => {
|
|
1170
1290
|
const visible = (el) => !el.disabled && el.checkVisibility();
|