papersearch 0.4.4 → 0.4.6
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 +7 -4
- package/README.md +7 -4
- package/carsi/paper_search_carsi/adapters/ams/__init__.py +34 -1
- package/carsi/paper_search_carsi/adapters/annual_reviews/__init__.py +26 -1
- package/carsi/paper_search_carsi/adapters/aps/__init__.py +25 -2
- package/carsi/paper_search_carsi/adapters/copernicus/__init__.py +27 -1
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +19 -1
- package/carsi/paper_search_carsi/adapters/ieee/__init__.py +102 -2
- package/carsi/paper_search_carsi/adapters/iop/__init__.py +41 -2
- package/carsi/paper_search_carsi/adapters/lww/ovid.py +4 -2
- package/carsi/paper_search_carsi/adapters/optica/__init__.py +14 -1
- package/carsi/paper_search_carsi/adapters/oup/__init__.py +105 -94
- package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +26 -12
- package/carsi/paper_search_carsi/adapters/platforms/figshare/__init__.py +20 -11
- package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/plos/__init__.py +31 -1
- package/carsi/paper_search_carsi/adapters/thieme/__init__.py +25 -2
- package/carsi/paper_search_carsi/assets/capsule.html +112 -32
- package/carsi/paper_search_carsi/assets/papersearch-notifier +0 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/api.js +119 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +24 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +1 -0
- package/carsi/paper_search_carsi/browser/backend.py +36 -0
- package/carsi/paper_search_carsi/browser/background.py +68 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +35 -0
- package/carsi/paper_search_carsi/browser/challenges.py +10 -0
- package/carsi/paper_search_carsi/browser/foreground.py +201 -0
- package/carsi/paper_search_carsi/browser/login.py +3 -1
- package/carsi/paper_search_carsi/browser/preview.py +3 -1
- package/carsi/paper_search_carsi/config.py +4 -1
- package/carsi/paper_search_carsi/engine/batch.py +73 -21
- package/carsi/paper_search_carsi/engine/batch_capture.py +54 -19
- package/carsi/paper_search_carsi/engine/batch_common.py +29 -2
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +10 -0
- package/carsi/paper_search_carsi/engine/batch_institution.py +56 -14
- package/carsi/paper_search_carsi/engine/batch_login.py +254 -198
- package/carsi/paper_search_carsi/engine/batch_user.py +67 -2
- package/carsi/paper_search_carsi/engine/batch_waits.py +65 -30
- package/carsi/paper_search_carsi/engine/login_wait.py +125 -0
- package/carsi/paper_search_carsi/engine/page_activity.py +163 -0
- package/carsi/paper_search_carsi/engine/supplement_transfer.py +55 -0
- package/carsi/paper_search_carsi/engine/supplements.py +96 -24
- package/carsi/paper_search_carsi/entitlements.py +23 -3
- package/carsi/paper_search_carsi/progress_capsule.py +246 -30
- package/carsi/paper_search_carsi/progress_macos.py +166 -0
- package/carsi/paper_search_carsi/progress_reporter.py +22 -1
- package/carsi/paper_search_carsi/progress_view.py +1 -0
- package/carsi/paper_search_carsi/publishers/profiles.py +5 -3
- package/carsi/paper_search_carsi/server.py +17 -1
- package/carsi/paper_search_carsi/user_settings.py +4 -4
- package/carsi/pyproject.toml +1 -1
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +2 -2
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.js +28 -4
- package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts +2 -6
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
- package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
- package/dist/infrastructure/runlog/failureClass.js +3 -2
- package/dist/infrastructure/runlog/failureClass.js.map +1 -1
- package/dist/management/carsi/installer.d.ts +2 -1
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +24 -1
- package/dist/management/carsi/installer.js.map +1 -1
- package/package.json +1 -1
- package/skills/paper-search/references/browser-download.md +11 -7
- package/skills/paper-search/references/carsi-setup.md +1 -0
- package/skills/paper-search/references/publisher-support.md +42 -41
|
@@ -190,9 +190,10 @@ class InstitutionMixin:
|
|
|
190
190
|
}
|
|
191
191
|
return null;
|
|
192
192
|
}"""
|
|
193
|
-
# The chooser's own submit: the nearest
|
|
194
|
-
# the first after it
|
|
195
|
-
#
|
|
193
|
+
# The chooser's own submit: the nearest control around what was chosen,
|
|
194
|
+
# the first after it. A custom UI can hide both its school list and native
|
|
195
|
+
# submit; a unique nearby native Select/Continue still belongs to it.
|
|
196
|
+
# What was chosen is a list (its index among document.querySelectorAll('select')) or
|
|
196
197
|
# an entry (a selector), whose form's controls only, or with no form none of
|
|
197
198
|
# another form's; ``controls`` names the controls that count (null: any button
|
|
198
199
|
# or link-button). Never a control of the page outside the chooser, such as the
|
|
@@ -200,18 +201,23 @@ class InstitutionMixin:
|
|
|
200
201
|
_LIST_SUBMIT_JS = r"""([anchor, controls]) => {
|
|
201
202
|
const s = typeof anchor === 'number' ? document.querySelectorAll('select')[anchor] : document.querySelector(anchor);
|
|
202
203
|
if (!s) return null;
|
|
203
|
-
const own =
|
|
204
|
+
const own = s.form || s.closest('form');
|
|
204
205
|
const shown = el => el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden' && !el.disabled;
|
|
205
|
-
const text = el => (el.innerText || el.value || el.getAttribute('aria-label') || el.getAttribute('title') || '')
|
|
206
|
+
const text = el => (el.innerText || el.value || el.textContent || el.getAttribute('aria-label') || el.getAttribute('title') || '')
|
|
206
207
|
.replace(/\s+/g, ' ').trim();
|
|
207
208
|
const CONTROL = controls || ('button, input[type="submit"], input[type="button"], input[type="image"], '
|
|
208
209
|
+ 'a[href^="javascript" i], a[role="button"], [role="button"], a.button, a.btn');
|
|
209
|
-
const NOT = /cancel|back|reset|clear|register|personal|sign ?up|help|close|remember|forgot/i;
|
|
210
|
+
const NOT = /cancel|back|reset|clear|register|personal|sign ?up|help|close|remember|forgot|subscribe|purchase|\bbuy\b/i;
|
|
211
|
+
const NATIVE_ACTION = /^(?:select|continue|go|next|sign\s*in|log\s*in|选择|继续|登录)$|access.*institut/i;
|
|
210
212
|
for (let box = s.parentElement, n = 0; box && n < 6; box = box.parentElement, n++) {
|
|
211
|
-
const
|
|
212
|
-
&& !NOT.test(text(c)) && (
|
|
213
|
-
|
|
214
|
-
const
|
|
213
|
+
const candidates = [...box.querySelectorAll(CONTROL)].filter(c => !s.contains(c) && !c.disabled && text(c).length <= 60
|
|
214
|
+
&& !NOT.test(text(c)) && (('form' in c ? c.form : c.closest('form')) === own));
|
|
215
|
+
const found = candidates.filter(shown);
|
|
216
|
+
const native = typeof anchor === 'number' && !shown(s) && own
|
|
217
|
+
? candidates.filter(c => c.type === 'submit' && c.form === own && !shown(c) && NATIVE_ACTION.test(text(c))) : [];
|
|
218
|
+
if (!found.length && native.length !== 1) continue;
|
|
219
|
+
const pick = native.length === 1 ? native[0]
|
|
220
|
+
: (found.find(c => s.compareDocumentPosition(c) & Node.DOCUMENT_POSITION_FOLLOWING) || found[found.length - 1]);
|
|
215
221
|
document.querySelectorAll('[data-paper-search-submit]').forEach(e => e.removeAttribute('data-paper-search-submit'));
|
|
216
222
|
pick.setAttribute('data-paper-search-submit', '');
|
|
217
223
|
return text(pick).slice(0, 80) || pick.tagName;
|
|
@@ -260,9 +266,18 @@ class InstitutionMixin:
|
|
|
260
266
|
|
|
261
267
|
@staticmethod
|
|
262
268
|
def _filled_lists(lists: Any, federation: dict) -> dict:
|
|
263
|
-
"""
|
|
269
|
+
"""Filled school lists, not the header's journal/language/search lists.
|
|
270
|
+
|
|
271
|
+
Only positive institution evidence can establish that a school is
|
|
272
|
+
missing. An unrelated filled dropdown says nothing about an empty
|
|
273
|
+
institution list that is still loading.
|
|
274
|
+
"""
|
|
275
|
+
school = re.compile(r"institut|school|universit|\buniv\b|college|organi[sz]ation|\bidp\b|大学|学院|研究院", re.I)
|
|
264
276
|
return {str(s.get("name")): list(s.get("options") or ()) for s in lists or ()
|
|
265
|
-
if s.get("i") != federation.get("i") and len(s.get("options") or ()) > 1
|
|
277
|
+
if s.get("i") != federation.get("i") and len(s.get("options") or ()) > 1
|
|
278
|
+
and (school.search(str(s.get("name") or "")) or any(
|
|
279
|
+
school.search(str(o[1])) for o in s.get("options") or ()
|
|
280
|
+
if isinstance(o, (list, tuple)) and len(o) == 2))}
|
|
266
281
|
|
|
267
282
|
# The list chosen in, marked by its index among document.querySelectorAll('select'):
|
|
268
283
|
# a locator's "select" would also count lists inside shadow roots.
|
|
@@ -591,12 +606,39 @@ class InstitutionMixin:
|
|
|
591
606
|
entries = []
|
|
592
607
|
for role in ("link", "button"):
|
|
593
608
|
try:
|
|
594
|
-
for entry in page.get_by_role(role, name=re.compile(r"^\s*access through\s
|
|
609
|
+
for entry in page.get_by_role(role, name=re.compile(r"^\s*access through\s*\S", re.I)).all()[:10]:
|
|
595
610
|
if entry.is_visible() is True:
|
|
596
|
-
label = re.sub(r"^\s*access through\s
|
|
611
|
+
label = re.sub(r"^\s*access through\s*", "", entry.inner_text(timeout=1_000), flags=re.I)
|
|
597
612
|
entries.append((self._institution_match_score(label), label, entry))
|
|
598
613
|
except Exception:
|
|
599
614
|
continue
|
|
615
|
+
if not any(score >= 2 for score, _, _ in entries):
|
|
616
|
+
# A widget's accessible name can differ from its visible school
|
|
617
|
+
# text, or it can be a clickable div/span without a role. Use
|
|
618
|
+
# the visible control text, still requiring a click affordance.
|
|
619
|
+
candidates = page.evaluate("""() => {
|
|
620
|
+
document.querySelectorAll('[data-paper-search-remembered]').forEach(e =>
|
|
621
|
+
e.removeAttribute('data-paper-search-remembered'));
|
|
622
|
+
const items = [...document.querySelectorAll('a,button,[role="button"],div,span')].filter(el => {
|
|
623
|
+
const native = el.matches('a[href],button,[role="button"]');
|
|
624
|
+
if (!native && el.closest('a,button,[role="button"]')) return false;
|
|
625
|
+
const text = (el.textContent || '').trim();
|
|
626
|
+
return text.length <= 160 && /^access through\\s*\\S/i.test(text)
|
|
627
|
+
&& el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden'
|
|
628
|
+
&& !el.disabled && el.getAttribute('aria-disabled') !== 'true'
|
|
629
|
+
&& (native || typeof el.onclick === 'function' || getComputedStyle(el).cursor === 'pointer');
|
|
630
|
+
});
|
|
631
|
+
return items.filter(el => !items.some(other => other !== el && el.contains(other)))
|
|
632
|
+
.slice(0,10).map((el,i) => {
|
|
633
|
+
el.setAttribute('data-paper-search-remembered', String(i));
|
|
634
|
+
return {i, text:(el.textContent || '').trim()};
|
|
635
|
+
});
|
|
636
|
+
}""")
|
|
637
|
+
if isinstance(candidates, list):
|
|
638
|
+
for candidate in candidates:
|
|
639
|
+
label = re.sub(r"^\s*access through\s*", "", candidate["text"], flags=re.I)
|
|
640
|
+
entries.append((self._institution_match_score(label), label,
|
|
641
|
+
page.locator(f'[data-paper-search-remembered="{candidate["i"]}"]')))
|
|
600
642
|
top = max((score for score, _, _ in entries), default=0)
|
|
601
643
|
best = [(label, entry) for score, label, entry in entries if score == top]
|
|
602
644
|
if top >= 2 and len(best) == 1:
|
|
@@ -7,11 +7,14 @@ from __future__ import annotations
|
|
|
7
7
|
import json
|
|
8
8
|
import re
|
|
9
9
|
import time
|
|
10
|
+
from contextlib import contextmanager
|
|
10
11
|
from typing import Any
|
|
11
12
|
from types import SimpleNamespace
|
|
12
13
|
from urllib.parse import unquote, urljoin, urlparse
|
|
13
14
|
|
|
14
15
|
from . import access_rules
|
|
16
|
+
from .login_wait import LoginWait
|
|
17
|
+
from .. import progress_reporter
|
|
15
18
|
from .batch_common import (AWAY_WAIT_SEC, POLL_MS, DownloadResult, PublisherContentError, _is_browser_error,
|
|
16
19
|
_is_navigation_cut, open_page, pump_until, settle)
|
|
17
20
|
|
|
@@ -64,6 +67,11 @@ class LoginMixin:
|
|
|
64
67
|
# A verification can let the page through to the publisher's redirect
|
|
65
68
|
# page (RSC's silent sign-in check, judged as the article, 2026-11-01).
|
|
66
69
|
self._wait_past_redirect_page(page, result)
|
|
70
|
+
# A blank document may draw its verification panel only while waiting
|
|
71
|
+
# for text. Handle it before interpreting the panel as article access
|
|
72
|
+
# or looking for an institution entry that cannot exist on it.
|
|
73
|
+
if not self._wait_for_challenge(page, result):
|
|
74
|
+
return False
|
|
67
75
|
self._raise_on_publisher_content_error(page)
|
|
68
76
|
self._dismiss_cookie_banners(page, result)
|
|
69
77
|
snapshot = self._access_snapshot(page) if not self._is_auth_page(str(page.url)) else None
|
|
@@ -127,7 +135,22 @@ class LoginMixin:
|
|
|
127
135
|
return url[:200]
|
|
128
136
|
return f"{url[:200]} | {verdict} ({basis or 'no rule'}): {evidence[:160]}"
|
|
129
137
|
|
|
130
|
-
|
|
138
|
+
# Readiness only needs a text node. body.innerText lays out the entire
|
|
139
|
+
# article, which can exhaust the page budget on a long document.
|
|
140
|
+
_PAGE_TEXT_JS = """() => {
|
|
141
|
+
if (document.contentType !== 'text/html') return -1;
|
|
142
|
+
if (!document.body) return 0;
|
|
143
|
+
const excluded = el => el.matches('script, style, noscript, template, [hidden]')
|
|
144
|
+
|| el.style.display === 'none' || el.style.visibility === 'hidden';
|
|
145
|
+
if (excluded(document.body)) return 0;
|
|
146
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
|
|
147
|
+
acceptNode: node => node.nodeType === Node.ELEMENT_NODE
|
|
148
|
+
? (excluded(node) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_SKIP)
|
|
149
|
+
: (node.nodeValue.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP)
|
|
150
|
+
});
|
|
151
|
+
const text = walker.nextNode();
|
|
152
|
+
return text ? text.nodeValue.trim().length : 0;
|
|
153
|
+
}"""
|
|
131
154
|
|
|
132
155
|
def _wait_for_page_text(self, page: Any, result: DownloadResult) -> None:
|
|
133
156
|
"""Wait for the document before judging access, within the page budget.
|
|
@@ -201,9 +224,44 @@ class LoginMixin:
|
|
|
201
224
|
self._return_to_article_after_login(page, result)
|
|
202
225
|
return signed_in
|
|
203
226
|
finally:
|
|
227
|
+
self._set_login_attention(result, "")
|
|
204
228
|
last = next((e["state"] for e in reversed(result.events) if e["state"] != "wait"), "")
|
|
205
229
|
self._note_wait(result, "school login", started, "signed in" if signed_in else (result.reason or last))
|
|
206
230
|
|
|
231
|
+
def _set_login_attention(self, result: DownloadResult, message: str, deadline: float | None = None,
|
|
232
|
+
*, page: Any = None) -> None:
|
|
233
|
+
"""A user step, once per prompt; automatic SSO keeps its ordinary progress."""
|
|
234
|
+
if page is not None and message:
|
|
235
|
+
result._attention_page = page
|
|
236
|
+
elif not message:
|
|
237
|
+
result._attention_page = None
|
|
238
|
+
key = f"publisher-login:{id(self)}:{result.doi}"
|
|
239
|
+
wait = getattr(result, "_login_wait", None)
|
|
240
|
+
if wait is not None and wait.paused:
|
|
241
|
+
deadline = None
|
|
242
|
+
if message == getattr(result, "_login_attention", ""):
|
|
243
|
+
if message:
|
|
244
|
+
progress_reporter.update_attention_deadline(key, deadline)
|
|
245
|
+
return
|
|
246
|
+
if message:
|
|
247
|
+
progress_reporter.set_attention(key, message, current=result.doi, phase="机构登录", deadline=deadline)
|
|
248
|
+
progress_reporter.report_stage("waiting_login", current=result.doi)
|
|
249
|
+
else:
|
|
250
|
+
progress_reporter.clear_attention(key)
|
|
251
|
+
result._login_attention = message
|
|
252
|
+
|
|
253
|
+
@contextmanager
|
|
254
|
+
def _login_wait_budget(self, result: DownloadResult, attribute: str, deadline: float, clock):
|
|
255
|
+
wait = result._login_wait = LoginWait(deadline, clock, attribute=attribute)
|
|
256
|
+
try:
|
|
257
|
+
yield wait
|
|
258
|
+
finally:
|
|
259
|
+
try:
|
|
260
|
+
setattr(result, attribute, wait.close())
|
|
261
|
+
finally:
|
|
262
|
+
result._login_wait = None
|
|
263
|
+
self._set_login_attention(result, "")
|
|
264
|
+
|
|
207
265
|
def _complete_login_steps(self, page: Any, result: DownloadResult) -> bool:
|
|
208
266
|
own = self.adapter.complete_login(page, result)
|
|
209
267
|
if own is not None:
|
|
@@ -264,208 +322,218 @@ class LoginMixin:
|
|
|
264
322
|
self._select_institution(page, result)
|
|
265
323
|
|
|
266
324
|
deadline = self._user_wait_deadline(result)
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
f"{self._login_wait_page(page)} after {self.page_wait_sec:.0f} s")
|
|
292
|
-
self._wait_ran_out(result)
|
|
293
|
-
return False
|
|
294
|
-
marker = f"{self._title(page)} | {getattr(page, 'url', '')[:160]}"
|
|
295
|
-
here = urlparse(str(getattr(page, "url", "") or ""))
|
|
296
|
-
on_publisher = self._on_publisher_host(here.geturl())
|
|
297
|
-
if here.hostname and (not on_publisher or self._is_idp_host(here.netloc)):
|
|
298
|
-
visited_idp = True
|
|
299
|
-
if self._is_idp_host(here.netloc):
|
|
300
|
-
result._visited_idp = True # the school's own login: a denial now is the school's
|
|
301
|
-
if here.hostname and (not on_publisher or self._is_auth_page(here.geturl())):
|
|
302
|
-
away_from_publisher = True
|
|
303
|
-
elif here.hostname and away_from_publisher:
|
|
304
|
-
away_from_publisher, returned = False, True
|
|
305
|
-
result._login_round_trip = True
|
|
306
|
-
self._event(result, "login_round_trip_returned", here.geturl()[:160])
|
|
307
|
-
if (on_publisher and self._is_success_article_url(here.geturl())
|
|
308
|
-
and not self._is_auth_page(here.geturl()) and not self._challenge_shell(page)
|
|
309
|
-
and (returned or time.time() - last_probe >= self.WAIT_PROBE_EVERY_SEC)
|
|
310
|
-
and self._looks_logged_out(page)):
|
|
311
|
-
# Whoever signed in (this program or the user), the article page may
|
|
312
|
-
# give its PDF although it still looks signed out to the rules (ASCE's
|
|
313
|
-
# "GET ACCESS" after the login waited out five minutes, 2026-11-02): try it.
|
|
314
|
-
after_login, returned, last_probe = returned, False, time.time()
|
|
315
|
-
if self._probe_pdf_while_waiting(page, result, after_login=after_login):
|
|
316
|
-
return False # signed in, and the page still offers or denies the article
|
|
317
|
-
elif (visited_idp and on_publisher and article_returns < 2
|
|
318
|
-
and not self._is_success_article_url(here.geturl())
|
|
319
|
-
and not self._is_auth_page(here.geturl())
|
|
320
|
-
and not self._challenge_shell(page)):
|
|
321
|
-
# Back from the IdP on a publisher page that is neither the
|
|
322
|
-
# article nor a login/chooser page (Taylor & Francis drops the
|
|
323
|
-
# redirect and lands on its home page): open the article.
|
|
324
|
-
article_returns += 1
|
|
325
|
-
try:
|
|
326
|
-
open_page(page, result.article_url, timeout_ms=60_000)
|
|
327
|
-
self._event(result, "idp_return_article", here.geturl()[:160])
|
|
328
|
-
settle(page, 3_000)
|
|
329
|
-
if not self._challenge_shell(page) and not self._looks_logged_out(page):
|
|
330
|
-
return True
|
|
331
|
-
except Exception as exc:
|
|
332
|
-
self._event(result, "idp_return_article_error", type(exc).__name__)
|
|
333
|
-
continue
|
|
334
|
-
if marker != last_state:
|
|
335
|
-
self._event(result, "login_state", marker)
|
|
336
|
-
last_state = marker
|
|
337
|
-
confirmation = self._idp_confirmation(page)
|
|
338
|
-
if confirmation:
|
|
339
|
-
# The user decides: the engine never agrees on their behalf.
|
|
340
|
-
self._event(result, "idp_confirmation_required", confirmation)
|
|
341
|
-
page_since, page_inputs = time.time(), self._visible_input_values(page) if self._user_away else ()
|
|
342
|
-
elif self._user_away:
|
|
343
|
-
inputs = self._visible_input_values(page)
|
|
344
|
-
if inputs != page_inputs:
|
|
345
|
-
# Someone is typing here: wait for them, within the article's total.
|
|
346
|
-
page_since, page_inputs = time.time(), inputs
|
|
347
|
-
elif time.time() - page_since >= AWAY_WAIT_SEC:
|
|
348
|
-
# Nothing moved on this page and the user seems away.
|
|
349
|
-
self._wait_ran_out(result)
|
|
325
|
+
with self._login_wait_budget(result, "_user_wait_deadline", deadline, time.time) as wait:
|
|
326
|
+
last_state = ""
|
|
327
|
+
last_auto_action = ""
|
|
328
|
+
last_auto_action_at = 0.0
|
|
329
|
+
visited_idp = False
|
|
330
|
+
page_since = time.time()
|
|
331
|
+
outside_since = time.time() # last seen on the user's own login step
|
|
332
|
+
article_returns = 0
|
|
333
|
+
session_returns = 0
|
|
334
|
+
away_from_publisher = False # on an IdP, federation or chooser page since the last probe
|
|
335
|
+
returned = False # back on the publisher's site after such a page: try the PDF
|
|
336
|
+
last_probe = time.time()
|
|
337
|
+
while True:
|
|
338
|
+
self._check_user_decision(result, page)
|
|
339
|
+
user_step = self._users_login_step(page)
|
|
340
|
+
wait.observe(page, user_step)
|
|
341
|
+
deadline = wait.deadline
|
|
342
|
+
if time.time() >= deadline:
|
|
343
|
+
break
|
|
344
|
+
time.sleep(1) # each pass checks the page again: a step done goes on within a second
|
|
345
|
+
if getattr(result, "_institution_not_listed", False):
|
|
346
|
+
# The publisher's institution search has no entry for the school.
|
|
347
|
+
result.reason = "institution_federation_unavailable"
|
|
348
|
+
self._event(result, result.reason, "the school is not in the publisher's institution list")
|
|
350
349
|
return False
|
|
351
|
-
|
|
352
|
-
if
|
|
350
|
+
over, outside_since = self._page_wait_over(page, outside_since)
|
|
351
|
+
if over:
|
|
352
|
+
# Off the school's login page for a whole page wait (a publisher
|
|
353
|
+
# page, a chooser, a redirect that goes nowhere): nobody is typing.
|
|
354
|
+
self._event(result, "page_wait_ended",
|
|
355
|
+
f"{self._login_wait_page(page)} after {self.page_wait_sec:.0f} s")
|
|
356
|
+
self._wait_ran_out(result)
|
|
353
357
|
return False
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
358
|
+
message = ""
|
|
359
|
+
if user_step:
|
|
360
|
+
kind = self._login_wait_page(page)
|
|
361
|
+
message = ("请在浏览器窗口选择学校并完成机构登录" if kind in {"school_choice", "institution_chooser"}
|
|
362
|
+
else "请在浏览器窗口完成机构登录")
|
|
363
|
+
self._set_login_attention(result, message, deadline, page=page)
|
|
364
|
+
marker = f"{self._title(page)} | {getattr(page, 'url', '')[:160]}"
|
|
365
|
+
here = urlparse(str(getattr(page, "url", "") or ""))
|
|
366
|
+
on_publisher = self._on_publisher_host(here.geturl())
|
|
367
|
+
if here.hostname and (not on_publisher or self._is_idp_host(here.netloc)):
|
|
368
|
+
visited_idp = True
|
|
369
|
+
if self._is_idp_host(here.netloc):
|
|
370
|
+
result._visited_idp = True # the school's own login: a denial now is the school's
|
|
371
|
+
if here.hostname and (not on_publisher or self._is_auth_page(here.geturl())):
|
|
372
|
+
away_from_publisher = True
|
|
373
|
+
elif here.hostname and away_from_publisher:
|
|
374
|
+
away_from_publisher, returned = False, True
|
|
375
|
+
result._login_round_trip = True
|
|
376
|
+
self._event(result, "login_round_trip_returned", here.geturl()[:160])
|
|
377
|
+
if (on_publisher and self._is_success_article_url(here.geturl())
|
|
378
|
+
and not self._is_auth_page(here.geturl()) and not self._challenge_shell(page)
|
|
379
|
+
and (returned or time.time() - last_probe >= self.WAIT_PROBE_EVERY_SEC)
|
|
380
|
+
and self._looks_logged_out(page)):
|
|
381
|
+
# Whoever signed in (this program or the user), the article page may
|
|
382
|
+
# give its PDF although it still looks signed out to the rules (ASCE's
|
|
383
|
+
# "GET ACCESS" after the login waited out five minutes, 2026-11-02): try it.
|
|
384
|
+
after_login, returned, last_probe = returned, False, time.time()
|
|
385
|
+
if self._probe_pdf_while_waiting(page, result, after_login=after_login):
|
|
386
|
+
return False # signed in, and the page still offers or denies the article
|
|
387
|
+
elif (visited_idp and on_publisher and article_returns < 2
|
|
388
|
+
and not self._is_success_article_url(here.geturl())
|
|
389
|
+
and not self._is_auth_page(here.geturl())
|
|
390
|
+
and not self._challenge_shell(page)):
|
|
391
|
+
# Back from the IdP on a publisher page that is neither the
|
|
392
|
+
# article nor a login/chooser page (Taylor & Francis drops the
|
|
393
|
+
# redirect and lands on its home page): open the article.
|
|
394
|
+
article_returns += 1
|
|
395
|
+
try:
|
|
396
|
+
open_page(page, result.article_url, timeout_ms=60_000)
|
|
397
|
+
self._event(result, "idp_return_article", here.geturl()[:160])
|
|
398
|
+
settle(page, 3_000)
|
|
399
|
+
if not self._challenge_shell(page) and not self._looks_logged_out(page):
|
|
400
|
+
return True
|
|
401
|
+
except Exception as exc:
|
|
402
|
+
self._event(result, "idp_return_article_error", type(exc).__name__)
|
|
403
|
+
continue
|
|
404
|
+
if marker != last_state:
|
|
405
|
+
self._event(result, "login_state", marker)
|
|
406
|
+
last_state = marker
|
|
407
|
+
confirmation = self._idp_confirmation(page)
|
|
408
|
+
if confirmation:
|
|
409
|
+
# The user decides: the engine never agrees on their behalf.
|
|
410
|
+
self._event(result, "idp_confirmation_required", confirmation)
|
|
411
|
+
page_since = time.time()
|
|
412
|
+
elif self._user_away:
|
|
413
|
+
if wait.paused:
|
|
414
|
+
page_since = time.time()
|
|
415
|
+
elif time.time() - page_since >= AWAY_WAIT_SEC:
|
|
416
|
+
# Nothing moved on this page and the user seems away.
|
|
417
|
+
self._wait_ran_out(result)
|
|
418
|
+
return False
|
|
419
|
+
if self._challenge_shell(page):
|
|
359
420
|
if not self._wait_for_challenge(page, result, deadline=deadline):
|
|
360
421
|
return False
|
|
361
422
|
continue
|
|
423
|
+
if self._return_from_login_site(page, result):
|
|
424
|
+
continue
|
|
425
|
+
if manual_selection:
|
|
426
|
+
if self._is_challenge_page(page):
|
|
427
|
+
if not self._wait_for_challenge(page, result, deadline=deadline):
|
|
428
|
+
return False
|
|
429
|
+
continue
|
|
430
|
+
block_reason = self._login_block_reason(page)
|
|
431
|
+
if block_reason:
|
|
432
|
+
self._event(result, block_reason, getattr(self, "_block_evidence", ""))
|
|
433
|
+
return False
|
|
434
|
+
stuck = self._stuck_on_school_site(page, result)
|
|
435
|
+
if stuck:
|
|
436
|
+
result.reason = result.state = "idp_no_return_to_publisher"
|
|
437
|
+
result._stopped_host = urlparse(stuck).hostname or ""
|
|
438
|
+
self._event(result, "idp_no_return_to_publisher",
|
|
439
|
+
f"{stuck[:200]} | {self._title(page)[:80]} | {self.SCHOOL_SITE_STAY_SEC} s without returning")
|
|
440
|
+
self._snapshot(page, result, "login stopped on the school's site")
|
|
441
|
+
return False
|
|
442
|
+
if self._follow_federated_login_option(page, result):
|
|
443
|
+
continue
|
|
444
|
+
if self._is_human_login_page(page):
|
|
445
|
+
if not any(s["why"] == "waiting for the user: school login" for s in result.snapshots):
|
|
446
|
+
self._snapshot(page, result, "waiting for the user: school login")
|
|
447
|
+
continue
|
|
448
|
+
if manual_selection and self.adapter.institution_chooser_open(page):
|
|
449
|
+
# The publisher's own chooser: choose there; no generic
|
|
450
|
+
# Continue/SSO action while the user may be interacting.
|
|
451
|
+
self._select_institution(page, result)
|
|
452
|
+
continue
|
|
453
|
+
self._dismiss_cookie_banners(page, result)
|
|
454
|
+
self._click_optional_continue(page, result)
|
|
455
|
+
if self._is_challenge_page(page):
|
|
456
|
+
if self._wait_for_challenge(page, result, deadline=deadline):
|
|
457
|
+
continue
|
|
458
|
+
self._event(result, "challenge_or_viewer_timeout", self._body_text(page, 500))
|
|
459
|
+
return False
|
|
460
|
+
if self._return_to_record_article_if_needed(page, result, result.doi):
|
|
461
|
+
if not self._looks_logged_out(page):
|
|
462
|
+
return True
|
|
463
|
+
continue
|
|
464
|
+
if self._article_access_available(page):
|
|
465
|
+
return True
|
|
466
|
+
# After the IdP some publishers (Taylor & Francis) land on their
|
|
467
|
+
# home page with the institution session active: go back to the
|
|
468
|
+
# article. CARSI is automated too, so this applies in every mode.
|
|
469
|
+
if (session_returns < 2 and self._has_publisher_institution_session(page)
|
|
470
|
+
and not self._is_success_article_url(getattr(page, "url", ""))):
|
|
471
|
+
# Bounded: a page type the rules do not know as an article
|
|
472
|
+
# (ScienceDirect book chapters, 2026-10-31) reloaded forever.
|
|
473
|
+
session_returns += 1
|
|
474
|
+
try:
|
|
475
|
+
open_page(page, result.article_url, timeout_ms=60_000)
|
|
476
|
+
self._event(result, "institution_session_return_article", result.article_url)
|
|
477
|
+
settle(page, 3_000)
|
|
478
|
+
self._dismiss_cookie_banners(page, result)
|
|
479
|
+
if not self._looks_logged_out(page):
|
|
480
|
+
return True
|
|
481
|
+
continue
|
|
482
|
+
except Exception as exc:
|
|
483
|
+
self._event(result, "institution_session_return_error", f"{type(exc).__name__}: {exc}")
|
|
362
484
|
block_reason = self._login_block_reason(page)
|
|
363
485
|
if block_reason:
|
|
364
|
-
self._event(result, block_reason, getattr(self, "_block_evidence", ""))
|
|
486
|
+
self._event(result, block_reason, getattr(self, "_block_evidence", "") or self._body_text(page, 500))
|
|
365
487
|
return False
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
if manual_selection and self.adapter.institution_chooser_open(page):
|
|
381
|
-
# The publisher's own chooser: choose there; no generic
|
|
382
|
-
# Continue/SSO action while the user may be interacting.
|
|
383
|
-
self._select_institution(page, result)
|
|
384
|
-
continue
|
|
385
|
-
self._dismiss_cookie_banners(page, result)
|
|
386
|
-
self._click_optional_continue(page, result)
|
|
387
|
-
if self._is_challenge_page(page):
|
|
388
|
-
if self._wait_for_challenge(page, result, deadline=deadline):
|
|
488
|
+
if manual_selection:
|
|
489
|
+
if self._open_adapter_login_page(page, result):
|
|
490
|
+
entry_opened = False # the next site's own entry is still to be opened
|
|
491
|
+
continue
|
|
492
|
+
if (not entry_opened and self._is_success_article_url(str(page.url))
|
|
493
|
+
and not self._has_visible_editable_input(page)):
|
|
494
|
+
# The first entry lookup can run before the article page has
|
|
495
|
+
# rendered its entry (a publisher's silent redirect; ScienceDirect
|
|
496
|
+
# right after linkinghub, 2026-10-31). Open the official entry
|
|
497
|
+
# once it appears, then leave the user's institution selection alone.
|
|
498
|
+
entry_opened = self._click_sso_entry(page, result)
|
|
499
|
+
if entry_opened:
|
|
500
|
+
continue
|
|
501
|
+
self._select_institution(page, result)
|
|
389
502
|
continue
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
503
|
+
if marker != last_auto_action or time.time() - last_auto_action_at > 10:
|
|
504
|
+
if self._select_institution(page, result):
|
|
505
|
+
settle(page, 2_000)
|
|
506
|
+
last_auto_action = marker
|
|
507
|
+
last_auto_action_at = time.time()
|
|
508
|
+
continue
|
|
509
|
+
if self._looks_logged_out(page) and self._click_sso_entry(page, result):
|
|
510
|
+
settle(page, 2_000)
|
|
511
|
+
self._select_institution(page, result)
|
|
512
|
+
last_auto_action = marker
|
|
513
|
+
last_auto_action_at = time.time()
|
|
514
|
+
continue
|
|
515
|
+
if self._click_openathens_entry(page, result):
|
|
516
|
+
settle(page, 2_000)
|
|
517
|
+
self._select_institution(page, result)
|
|
518
|
+
last_auto_action = marker
|
|
519
|
+
last_auto_action_at = time.time()
|
|
520
|
+
continue
|
|
521
|
+
self._select_institution(page, result)
|
|
522
|
+
last_auto_action = marker
|
|
523
|
+
last_auto_action_at = time.time()
|
|
524
|
+
if self._article_access_available(page):
|
|
394
525
|
return True
|
|
395
|
-
|
|
396
|
-
if self._article_access_available(page):
|
|
397
|
-
return True
|
|
398
|
-
# After the IdP some publishers (Taylor & Francis) land on their
|
|
399
|
-
# home page with the institution session active: go back to the
|
|
400
|
-
# article. CARSI is automated too, so this applies in every mode.
|
|
401
|
-
if (session_returns < 2 and self._has_publisher_institution_session(page)
|
|
402
|
-
and not self._is_success_article_url(getattr(page, "url", ""))):
|
|
403
|
-
# Bounded: a page type the rules do not know as an article
|
|
404
|
-
# (ScienceDirect book chapters, 2026-10-31) reloaded forever.
|
|
405
|
-
session_returns += 1
|
|
526
|
+
if not manual_selection and self._has_publisher_institution_session(page):
|
|
406
527
|
try:
|
|
407
528
|
open_page(page, result.article_url, timeout_ms=60_000)
|
|
408
529
|
self._event(result, "institution_session_return_article", result.article_url)
|
|
409
530
|
settle(page, 3_000)
|
|
410
531
|
self._dismiss_cookie_banners(page, result)
|
|
411
|
-
|
|
412
|
-
return True
|
|
413
|
-
continue
|
|
532
|
+
return not self._looks_logged_out(page)
|
|
414
533
|
except Exception as exc:
|
|
415
534
|
self._event(result, "institution_session_return_error", f"{type(exc).__name__}: {exc}")
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
self._event(result, block_reason, getattr(self, "_block_evidence", "") or self._body_text(page, 500))
|
|
419
|
-
return False
|
|
420
|
-
if manual_selection:
|
|
421
|
-
if self._open_adapter_login_page(page, result):
|
|
422
|
-
entry_opened = False # the next site's own entry is still to be opened
|
|
423
|
-
continue
|
|
424
|
-
if (not entry_opened and self._is_success_article_url(str(page.url))
|
|
425
|
-
and not self._has_visible_editable_input(page)):
|
|
426
|
-
# The first entry lookup can run before the article page has
|
|
427
|
-
# rendered its entry (a publisher's silent redirect; ScienceDirect
|
|
428
|
-
# right after linkinghub, 2026-10-31). Open the official entry
|
|
429
|
-
# once it appears, then leave the user's institution selection alone.
|
|
430
|
-
entry_opened = self._click_sso_entry(page, result)
|
|
431
|
-
if entry_opened:
|
|
432
|
-
continue
|
|
433
|
-
self._select_institution(page, result)
|
|
434
|
-
continue
|
|
435
|
-
if marker != last_auto_action or time.time() - last_auto_action_at > 10:
|
|
436
|
-
if self._select_institution(page, result):
|
|
437
|
-
settle(page, 2_000)
|
|
438
|
-
last_auto_action = marker
|
|
439
|
-
last_auto_action_at = time.time()
|
|
440
|
-
continue
|
|
441
|
-
if self._looks_logged_out(page) and self._click_sso_entry(page, result):
|
|
442
|
-
settle(page, 2_000)
|
|
443
|
-
self._select_institution(page, result)
|
|
444
|
-
last_auto_action = marker
|
|
445
|
-
last_auto_action_at = time.time()
|
|
446
|
-
continue
|
|
447
|
-
if self._click_openathens_entry(page, result):
|
|
448
|
-
settle(page, 2_000)
|
|
449
|
-
self._select_institution(page, result)
|
|
450
|
-
last_auto_action = marker
|
|
451
|
-
last_auto_action_at = time.time()
|
|
452
|
-
continue
|
|
453
|
-
self._select_institution(page, result)
|
|
454
|
-
last_auto_action = marker
|
|
455
|
-
last_auto_action_at = time.time()
|
|
456
|
-
if self._article_access_available(page):
|
|
457
|
-
return True
|
|
458
|
-
if not manual_selection and self._has_publisher_institution_session(page):
|
|
459
|
-
try:
|
|
460
|
-
open_page(page, result.article_url, timeout_ms=60_000)
|
|
461
|
-
self._event(result, "institution_session_return_article", result.article_url)
|
|
462
|
-
settle(page, 3_000)
|
|
463
|
-
self._dismiss_cookie_banners(page, result)
|
|
464
|
-
return not self._looks_logged_out(page)
|
|
465
|
-
except Exception as exc:
|
|
466
|
-
self._event(result, "institution_session_return_error", f"{type(exc).__name__}: {exc}")
|
|
467
|
-
self._wait_ran_out(result)
|
|
468
|
-
return False
|
|
535
|
+
self._wait_ran_out(result)
|
|
536
|
+
return False
|
|
469
537
|
|
|
470
538
|
# The school's account cannot sign in (login state J). Shibboleth's own
|
|
471
539
|
# words ("Your account is locked.", "Your password has expired.") and the
|
|
@@ -688,18 +756,6 @@ class LoginMixin:
|
|
|
688
756
|
return ""
|
|
689
757
|
return url if time.time() - seen[1] >= self.SCHOOL_SITE_STAY_SEC else ""
|
|
690
758
|
|
|
691
|
-
@staticmethod
|
|
692
|
-
def _visible_input_values(page: Any) -> tuple[str, ...]:
|
|
693
|
-
"""What the visible text and password fields hold; a change means someone types."""
|
|
694
|
-
try:
|
|
695
|
-
values = page.evaluate("""() => [...document.querySelectorAll('input')]
|
|
696
|
-
.filter(i => ['', 'text', 'email', 'password', 'tel', 'number'].includes((i.type || '').toLowerCase())
|
|
697
|
-
&& i.getClientRects().length > 0)
|
|
698
|
-
.map(i => i.value || '')""")
|
|
699
|
-
except Exception:
|
|
700
|
-
return ()
|
|
701
|
-
return tuple(str(v) for v in values) if isinstance(values, list) else ()
|
|
702
|
-
|
|
703
759
|
def _open_adapter_login_page(self, page: Any, result: DownloadResult | None) -> bool:
|
|
704
760
|
"""Go to the adapter's next login page, each once per item (an Elsevier
|
|
705
761
|
journal's own institution login, then ScienceDirect's same article);
|