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.
Files changed (72) hide show
  1. package/README.en.md +7 -4
  2. package/README.md +7 -4
  3. package/carsi/paper_search_carsi/adapters/ams/__init__.py +34 -1
  4. package/carsi/paper_search_carsi/adapters/annual_reviews/__init__.py +26 -1
  5. package/carsi/paper_search_carsi/adapters/aps/__init__.py +25 -2
  6. package/carsi/paper_search_carsi/adapters/copernicus/__init__.py +27 -1
  7. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +19 -1
  8. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +102 -2
  9. package/carsi/paper_search_carsi/adapters/iop/__init__.py +41 -2
  10. package/carsi/paper_search_carsi/adapters/lww/ovid.py +4 -2
  11. package/carsi/paper_search_carsi/adapters/optica/__init__.py +14 -1
  12. package/carsi/paper_search_carsi/adapters/oup/__init__.py +105 -94
  13. package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +26 -12
  14. package/carsi/paper_search_carsi/adapters/platforms/figshare/__init__.py +20 -11
  15. package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +1 -1
  16. package/carsi/paper_search_carsi/adapters/plos/__init__.py +31 -1
  17. package/carsi/paper_search_carsi/adapters/thieme/__init__.py +25 -2
  18. package/carsi/paper_search_carsi/assets/capsule.html +112 -32
  19. package/carsi/paper_search_carsi/assets/papersearch-notifier +0 -0
  20. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +119 -0
  21. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +24 -0
  22. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +1 -0
  23. package/carsi/paper_search_carsi/browser/backend.py +36 -0
  24. package/carsi/paper_search_carsi/browser/background.py +68 -0
  25. package/carsi/paper_search_carsi/browser/challenge_interaction.py +35 -0
  26. package/carsi/paper_search_carsi/browser/challenges.py +10 -0
  27. package/carsi/paper_search_carsi/browser/foreground.py +201 -0
  28. package/carsi/paper_search_carsi/browser/login.py +3 -1
  29. package/carsi/paper_search_carsi/browser/preview.py +3 -1
  30. package/carsi/paper_search_carsi/config.py +4 -1
  31. package/carsi/paper_search_carsi/engine/batch.py +73 -21
  32. package/carsi/paper_search_carsi/engine/batch_capture.py +54 -19
  33. package/carsi/paper_search_carsi/engine/batch_common.py +29 -2
  34. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +10 -0
  35. package/carsi/paper_search_carsi/engine/batch_institution.py +56 -14
  36. package/carsi/paper_search_carsi/engine/batch_login.py +254 -198
  37. package/carsi/paper_search_carsi/engine/batch_user.py +67 -2
  38. package/carsi/paper_search_carsi/engine/batch_waits.py +65 -30
  39. package/carsi/paper_search_carsi/engine/login_wait.py +125 -0
  40. package/carsi/paper_search_carsi/engine/page_activity.py +163 -0
  41. package/carsi/paper_search_carsi/engine/supplement_transfer.py +55 -0
  42. package/carsi/paper_search_carsi/engine/supplements.py +96 -24
  43. package/carsi/paper_search_carsi/entitlements.py +23 -3
  44. package/carsi/paper_search_carsi/progress_capsule.py +246 -30
  45. package/carsi/paper_search_carsi/progress_macos.py +166 -0
  46. package/carsi/paper_search_carsi/progress_reporter.py +22 -1
  47. package/carsi/paper_search_carsi/progress_view.py +1 -0
  48. package/carsi/paper_search_carsi/publishers/profiles.py +5 -3
  49. package/carsi/paper_search_carsi/server.py +17 -1
  50. package/carsi/paper_search_carsi/user_settings.py +4 -4
  51. package/carsi/pyproject.toml +1 -1
  52. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +2 -2
  53. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  54. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  55. package/dist/capabilities/pdf-discovery/batch.js +28 -4
  56. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  57. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
  58. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts +2 -6
  59. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
  60. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
  61. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
  62. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  63. package/dist/infrastructure/runlog/failureClass.js +3 -2
  64. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  65. package/dist/management/carsi/installer.d.ts +2 -1
  66. package/dist/management/carsi/installer.d.ts.map +1 -1
  67. package/dist/management/carsi/installer.js +24 -1
  68. package/dist/management/carsi/installer.js.map +1 -1
  69. package/package.json +1 -1
  70. package/skills/paper-search/references/browser-download.md +11 -7
  71. package/skills/paper-search/references/carsi-setup.md +1 -0
  72. package/skills/paper-search/references/publisher-support.md +42 -41
@@ -268,99 +268,110 @@ class OUPAdapter(PublisherAdapter):
268
268
  last_progress_at = time.monotonic()
269
269
  action_done = False
270
270
  pending_retry = ""
271
- waiting = None # (since, page marker, typed values) while the page is the user's
272
- while time.monotonic() < deadline:
273
- try:
274
- state = self.login_state(page, deadline)
275
- if time.monotonic() >= deadline:
276
- break
277
- parsed = urlparse(str(page.url))
278
- marker = (state, parsed.hostname, parsed.path)
279
- if marker != last_marker:
280
- d._event(result, "login_observed", state)
281
- last_marker = marker
282
- last_progress_at = time.monotonic()
283
- action_done = False
284
- if state == "article_ready":
285
- result.reason = ""
286
- return True
287
- if state in {"login_page_closed", "login_credentials_rejected",
288
- "institution_not_registered", "institution_pdf_entitlement_missing",
289
- "publisher_temporarily_unavailable"}:
290
- result.reason = state
291
- d._event(result, "login_stopped", state)
292
- return False
293
- if state in {"verification", "human_login", "institution_chooser"}:
294
- # A stale redirect timer must never reload a human form.
295
- pending_retry = ""
296
- last_progress_at = time.monotonic()
297
- if state == "institution_chooser":
298
- d._select_institution(page, result)
299
- if d._user_away:
300
- # The user seems away: as everywhere, a page of theirs on
301
- # which nothing moves and nothing is typed ends the article.
302
- typed = d._visible_input_values(page)
303
- if waiting is None or waiting[1:] != (marker, typed):
304
- waiting = (time.monotonic(), marker, typed)
305
- elif time.monotonic() - waiting[0] >= AWAY_WAIT_SEC:
306
- d._wait_ran_out(result)
307
- result.reason = "login_timeout"
308
- d._event(result, "login_stopped", result.reason)
309
- return False
310
- else:
311
- if state == "transient_error":
312
- pending_retry = "transient_error"
313
- elif state == "publisher_login" and not action_done and getattr(result, "_oxford_login_entry_attempt", 0) == attempt:
314
- pending_retry = "returned_auth_wall"
315
- elif time.monotonic() - last_progress_at >= 45:
316
- pending_retry = "redirect_stalled"
317
- if pending_retry:
318
- if attempt >= max_attempts:
319
- result.reason = "login_retries_exhausted"
320
- d._event(result, "login_stopped", result.reason)
321
- return False
322
- d._event(result, "login_retry_wait", f"{attempt + 1}/3")
323
- page.wait_for_timeout(min(3_000 * attempt, max(1, int((deadline - time.monotonic()) * 1000))))
324
- if time.monotonic() >= deadline:
325
- break
326
- # Recheck after backoff: the user or redirect may have
327
- # completed while the browser dispatched pending events.
328
- after_wait = self.login_state(page, deadline)
329
- if time.monotonic() >= deadline:
330
- break
331
- if after_wait not in {"transient_error", "publisher_login", "redirect_wait"}:
332
- pending_retry = ""
333
- continue
334
- attempt += 1
335
- result._oxford_login_attempt = attempt
336
- d._event(result, "login_attempt_started", f"{attempt}/3")
337
- pending_retry = ""
271
+ waiting = None # (since, page marker) while the page is the user's
272
+ with d._login_wait_budget(result, "_oxford_login_deadline", deadline, time.monotonic) as wait:
273
+ while time.monotonic() < wait.deadline:
274
+ deadline = wait.deadline
275
+ try:
276
+ d._check_user_decision(result, page)
277
+ state = self.login_state(page, deadline)
278
+ deadline = wait.deadline
279
+ if time.monotonic() >= deadline:
280
+ break
281
+ user_step = state == "human_login" or (state == "institution_chooser" and d._users_login_step(page))
282
+ wait.observe(page, user_step)
283
+ deadline = wait.deadline
284
+ message = ("请在浏览器窗口选择学校并完成机构登录" if state == "institution_chooser"
285
+ else "请在浏览器窗口完成机构登录") if user_step else ""
286
+ d._set_login_attention(result, message, time.time() + deadline - time.monotonic(), page=page)
287
+ parsed = urlparse(str(page.url))
288
+ marker = (state, parsed.hostname, parsed.path)
289
+ if marker != last_marker:
290
+ d._event(result, "login_observed", state)
291
+ last_marker = marker
338
292
  last_progress_at = time.monotonic()
339
293
  action_done = False
340
- open_page(page, result.article_url,
341
- timeout_ms=max(1, min(15_000, int((deadline - time.monotonic()) * 1000))))
342
- continue
343
- if state == "publisher_login" and not action_done:
344
- action_done = self.advance_login(page, result, deadline)
345
- if action_done:
346
- result._oxford_login_entry_attempt = attempt
347
- remaining_ms = max(0, int((deadline - time.monotonic()) * 1000))
348
- if remaining_ms:
349
- page.wait_for_timeout(min(1_000, remaining_ms))
350
- except Exception as exc:
351
- if page.is_closed():
352
- result.reason = "login_page_closed"
353
- d._event(result, "login_stopped", result.reason)
354
- return False
355
- # Only browser navigation/timeouts are retryable. Programming
356
- # errors must retain the normal unexpected_error path.
357
- if not self.retryable_navigation_error(exc):
358
- raise
359
- d._event(result, "login_navigation_interrupted", type(exc).__name__)
360
- pending_retry = "navigation_error"
361
- remaining = int((deadline - time.monotonic()) * 1000)
362
- if remaining > 0:
363
- page.wait_for_timeout(min(1_000, remaining))
364
- result.reason = "login_timeout"
365
- d._event(result, "login_stopped", result.reason)
366
- return False
294
+ if state == "article_ready":
295
+ result.reason = ""
296
+ return True
297
+ if state in {"login_page_closed", "login_credentials_rejected",
298
+ "institution_not_registered", "institution_pdf_entitlement_missing",
299
+ "publisher_temporarily_unavailable"}:
300
+ result.reason = state
301
+ d._event(result, "login_stopped", state)
302
+ return False
303
+ if state in {"verification", "human_login", "institution_chooser"}:
304
+ # A stale redirect timer must never reload a human form.
305
+ pending_retry = ""
306
+ last_progress_at = time.monotonic()
307
+ if state == "institution_chooser":
308
+ d._select_institution(page, result)
309
+ if wait.paused:
310
+ waiting = None
311
+ if d._user_away and not wait.paused:
312
+ # The user seems away: as everywhere, a page of theirs on
313
+ # which nothing moves and nothing is typed ends the article.
314
+ if waiting is None or waiting[1] != marker:
315
+ waiting = (time.monotonic(), marker)
316
+ elif time.monotonic() - waiting[0] >= AWAY_WAIT_SEC:
317
+ d._wait_ran_out(result)
318
+ result.reason = "login_timeout"
319
+ d._event(result, "login_stopped", result.reason)
320
+ return False
321
+ else:
322
+ if state == "transient_error":
323
+ pending_retry = "transient_error"
324
+ elif state == "publisher_login" and not action_done and getattr(result, "_oxford_login_entry_attempt", 0) == attempt:
325
+ pending_retry = "returned_auth_wall"
326
+ elif time.monotonic() - last_progress_at >= 45:
327
+ pending_retry = "redirect_stalled"
328
+ if pending_retry:
329
+ if attempt >= max_attempts:
330
+ result.reason = "login_retries_exhausted"
331
+ d._event(result, "login_stopped", result.reason)
332
+ return False
333
+ d._event(result, "login_retry_wait", f"{attempt + 1}/3")
334
+ page.wait_for_timeout(min(3_000 * attempt, max(1, int((deadline - time.monotonic()) * 1000))))
335
+ if time.monotonic() >= deadline:
336
+ break
337
+ # Recheck after backoff: the user or redirect may have
338
+ # completed while the browser dispatched pending events.
339
+ after_wait = self.login_state(page, deadline)
340
+ if time.monotonic() >= deadline:
341
+ break
342
+ if after_wait not in {"transient_error", "publisher_login", "redirect_wait"}:
343
+ pending_retry = ""
344
+ continue
345
+ attempt += 1
346
+ result._oxford_login_attempt = attempt
347
+ d._event(result, "login_attempt_started", f"{attempt}/3")
348
+ pending_retry = ""
349
+ last_progress_at = time.monotonic()
350
+ action_done = False
351
+ open_page(page, result.article_url,
352
+ timeout_ms=max(1, min(15_000, int((deadline - time.monotonic()) * 1000))))
353
+ continue
354
+ if state == "publisher_login" and not action_done:
355
+ action_done = self.advance_login(page, result, deadline)
356
+ if action_done:
357
+ result._oxford_login_entry_attempt = attempt
358
+ remaining_ms = max(0, int((deadline - time.monotonic()) * 1000))
359
+ if remaining_ms:
360
+ page.wait_for_timeout(min(1_000, remaining_ms))
361
+ except Exception as exc:
362
+ if page.is_closed():
363
+ result.reason = "login_page_closed"
364
+ d._event(result, "login_stopped", result.reason)
365
+ return False
366
+ # Only browser navigation/timeouts are retryable. Programming
367
+ # errors must retain the normal unexpected_error path.
368
+ if not self.retryable_navigation_error(exc):
369
+ raise
370
+ d._event(result, "login_navigation_interrupted", type(exc).__name__)
371
+ pending_retry = "navigation_error"
372
+ remaining = int((deadline - time.monotonic()) * 1000)
373
+ if remaining > 0:
374
+ page.wait_for_timeout(min(1_000, remaining))
375
+ result.reason = "login_timeout"
376
+ d._event(result, "login_stopped", result.reason)
377
+ return False
@@ -26,7 +26,7 @@ _ARTICLE = re.compile(r"/doi/(?:(?:abs|full|pdf|epdf|pdfdirect|reader)/)?(10\.\d
26
26
  _CARSI = "China CERNET Federation (CARSI)"
27
27
  # Supplement files: /doi/suppl/<DOI>/suppl_file/<name>, with the link text.
28
28
  _SUPPLEMENT_ROWS_JS = """() => [...document.querySelectorAll('a[href*="/doi/suppl/"]')].map(a => ({
29
- href: a.href, label: (a.innerText || a.getAttribute('title') || '').replace(/\\s+/g, ' ').trim().slice(0, 200)}))"""
29
+ href: a.href, label: ((a.textContent || '').trim() || a.getAttribute('title') || '').replace(/\\s+/g, ' ').trim().slice(0, 200)}))"""
30
30
  # The page's institution-login links, read at once: a link-by-link lookup waited
31
31
  # 30 s on a page still navigating after a silent IdP return (ASCE, 2026-11-02).
32
32
  _SSOSTART_LINKS_JS = """() => [...document.querySelectorAll('a[href*="/action/ssostart"]')].map(a => ({
@@ -54,17 +54,31 @@ class AtyponAdapter(PublisherAdapter):
54
54
 
55
55
  def supplement_links(self, page: Any, doi: str) -> list[SupplementLink] | None:
56
56
  """Files under ``/doi/suppl/<this DOI>/suppl_file/``; a supplement link of
57
- another article on the page (AHA, 2026-11-01) is not this article's."""
58
- links: list[SupplementLink] = []
59
- rows = page.evaluate(_SUPPLEMENT_ROWS_JS)
60
- prefix = f"/doi/suppl/{doi.lower()}/suppl_file/"
61
- for row in rows if isinstance(rows, list) and doi else []:
62
- target = urlparse(str(row.get("href") or "") if isinstance(row, dict) else "")
63
- url = target._replace(fragment="").geturl()
64
- if (self._on_site(url) and unquote(target.path).lower().startswith(prefix)
65
- and url not in {link.url for link in links}):
66
- links.append(SupplementLink(url, str(row.get("label") or "")))
67
- return links
57
+ another article on the page is not this article's. Follow the observed
58
+ supplement landing page once when the article only links to that page.
59
+ """
60
+ landing_path = f"/doi/suppl/{doi.lower()}"
61
+ for attempt in range(2):
62
+ links: list[SupplementLink] = []
63
+ landing = ""
64
+ rows = page.evaluate(_SUPPLEMENT_ROWS_JS)
65
+ for row in rows if isinstance(rows, list) and doi else []:
66
+ target = urlparse(str(row.get("href") or "") if isinstance(row, dict) else "")
67
+ url = target._replace(fragment="").geturl()
68
+ if not self._on_site(url):
69
+ continue
70
+ path = unquote(target.path).lower()
71
+ if path.startswith(landing_path + "/suppl_file/"):
72
+ if url not in {link.url for link in links}:
73
+ links.append(SupplementLink(url, str(row.get("label") or "")))
74
+ elif path.rstrip("/") == landing_path:
75
+ landing = landing or url
76
+ if links or not landing or attempt:
77
+ return links
78
+ if unquote(urlparse(str(page.url)).path).lower().rstrip("/") == landing_path:
79
+ return []
80
+ open_page(page, landing, timeout_ms=30_000)
81
+ return []
68
82
 
69
83
  def institution_chooser_open(self, page: Any) -> bool:
70
84
  return self._chooser(str(getattr(page, "url", "") or "")) and page.locator("select#shib-search--fed").is_visible()
@@ -19,14 +19,19 @@ _MAX_RESOURCES = 5
19
19
  _MAX_ARTICLES = 50
20
20
  _MAX_BYTES = 200 * 1024 * 1024
21
21
  _BUDGET_SEC = 30
22
- _PAGE_LINKS = """() => ({
23
- doi: document.querySelector('meta[name="citation_doi"]')?.content || '',
22
+ _PAGE_LINKS = """() => {
24
23
  // A cited dataset is not a supplement of the article citing it.
25
- links: [...document.querySelectorAll('a[href], iframe[src]')]
24
+ const links = [...document.querySelectorAll('a[href], iframe[src]')]
26
25
  .filter(a => !a.closest('[role="doc-bibliography"], [role="doc-biblioentry"], '
27
- + '#references, #bibliography, .ref-list, .article-section__references'))
28
- .map(a => a.href || a.src)
29
- })"""
26
+ + '#references, #bibliography, #articleReferences, .ref-list, .article-section__references'));
27
+ return {
28
+ doi: document.querySelector('meta[name="citation_doi"]')?.content || '',
29
+ links: links.map(a => a.href || a.src),
30
+ labelled: links.filter(a => a.tagName === 'A' &&
31
+ /^(?:supplement(?:ary)?(?: (?:material|information|data|file|document))?|supporting information)\\s*\\d*$/i
32
+ .test((a.textContent || '').replace(/\\s+/g,' ').trim())).map(a => a.href)
33
+ };
34
+ }"""
30
35
 
31
36
 
32
37
  def _doi(value: Any) -> str:
@@ -66,13 +71,17 @@ def resource(url: str) -> tuple[str, str, str] | None:
66
71
  return m[1], m[2], m[3] or ""
67
72
 
68
73
 
69
- def _belongs(data: dict, doi: str) -> bool:
74
+ def _belongs(data: dict, doi: str, *, labelled: bool = False) -> bool:
70
75
  resource_doi = _doi(data.get("resource_doi"))
71
76
  if resource_doi:
72
77
  return resource_doi == doi
73
- return any(isinstance(item, dict) and item.get("relation") == "IsSupplementTo"
74
- and _doi(item.get("identifier")) == doi
75
- for item in data.get("related_materials") or [])
78
+ parents = [_doi(item.get("identifier")) for item in data.get("related_materials") or []
79
+ if isinstance(item, dict) and item.get("relation") == "IsSupplementTo"]
80
+ if parents:
81
+ return doi in parents
82
+ # Some publisher deposits omit the backlink. An explicit Supplement link
83
+ # on the DOI-verified article is then sufficient; a plain citation is not.
84
+ return labelled
76
85
 
77
86
 
78
87
  def supplement_links(page: Any, doi: str, *, clock=time.monotonic, pause=time.sleep) -> list[SupplementLink] | None:
@@ -124,7 +133,7 @@ def supplement_links(page: Any, doi: str, *, clock=time.monotonic, pause=time.sl
124
133
  if (requested != actual if version else
125
134
  re.sub(r"\.v\d+$", "", requested) != re.sub(r"\.v\d+$", "", actual)):
126
135
  raise ValueError("figshare_resource_doi_mismatch")
127
- if not _belongs(detail, doi):
136
+ if not _belongs(detail, doi, labelled=root in data.get("labelled", [])):
128
137
  raise ValueError("figshare_article_mismatch")
129
138
  articles = [detail]
130
139
  if kind == "collections":
@@ -25,7 +25,7 @@ _ARTICLE = re.compile(r"/[^/]+/article(?:-abstract)?/(?:doi/10\.\d{4,9}/.+/)?\d+
25
25
  _SUPPLEMENT = re.compile(r"/[^/]+/article-supplement/(\d{5,})/")
26
26
  _SUPPLEMENT_ROWS_JS = """() => [...document.querySelectorAll('a[href]')].map(a => ({
27
27
  href: a.href, label: (a.innerText || a.getAttribute('title') || '').replace(/\\s+/g, ' ').trim().slice(0, 200),
28
- in_section: !!a.closest('[class*="supplementary-material"]')}))"""
28
+ in_section: !!a.closest('[class*="supplementary-material"], .dataSuppLink')}))"""
29
29
 
30
30
 
31
31
  def supplement_links(page: Any, doi: str, hosts: frozenset[str]) -> list[SupplementLink]:
@@ -5,14 +5,44 @@ path comes from the source page or the DOI's journal code.
5
5
  """
6
6
  from __future__ import annotations
7
7
 
8
+ import re
9
+ from typing import Any
10
+ from urllib.parse import parse_qs, urlparse
11
+
8
12
  from ...engine.router import _append_plos_candidates
9
- from ..base import PublisherAdapter, register
13
+ from ..base import PublisherAdapter, SupplementLink, register
14
+
15
+ _SUPPLEMENT_ROWS_JS = """() => [...document.querySelectorAll('a[href]')].map(a => ({
16
+ href: a.href, label: (a.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 240)
17
+ }))"""
18
+
19
+
20
+ def supplement_links_from_rows(rows: list[dict], doi: str) -> list[SupplementLink]:
21
+ links: list[SupplementLink] = []
22
+ seen: set[str] = set()
23
+ for row in rows:
24
+ target = urlparse(str(row.get("href") or ""))
25
+ query = parse_qs(target.query)
26
+ ids = query.get("id", [])
27
+ if (target.scheme != "https" or target.netloc != "journals.plos.org"
28
+ or not re.fullmatch(r"/[a-z]+/article/file", target.path)
29
+ or query.get("type") != ["supplementary"] or len(ids) != 1
30
+ or not re.fullmatch(re.escape(doi) + r"\.s\d+", ids[0], re.I)):
31
+ continue
32
+ identity = ids[0].lower()
33
+ if identity not in seen:
34
+ seen.add(identity)
35
+ links.append(SupplementLink(target._replace(fragment="").geturl(), str(row.get("label") or "")))
36
+ return links
10
37
 
11
38
 
12
39
  @register
13
40
  class PLOSAdapter(PublisherAdapter):
14
41
  publisher = "plos"
15
42
 
43
+ def supplement_links(self, page: Any, doi: str) -> list[SupplementLink]:
44
+ return supplement_links_from_rows(page.evaluate(_SUPPLEMENT_ROWS_JS), doi)
45
+
16
46
  @classmethod
17
47
  def profile_pdf_candidates(cls, doi: str, source_url: str) -> list[str]:
18
48
  urls: list[str] = []
@@ -13,14 +13,34 @@ from __future__ import annotations
13
13
  import re
14
14
  import time
15
15
  from typing import Any
16
- from urllib.parse import parse_qs, urlencode, urljoin, urlparse
16
+ from urllib.parse import parse_qs, unquote, urlencode, urljoin, urlparse
17
17
 
18
18
  from ...engine.router import is_thieme_article_pdf_url
19
19
  from ...engine.batch_common import _is_browser_error, open_page
20
- from ..base import PublisherAdapter, register
20
+ from ..base import PublisherAdapter, SupplementLink, register
21
21
 
22
22
  _HOSTS = frozenset({"thieme-connect.de", "www.thieme-connect.de", "thieme-connect.com", "www.thieme-connect.com"})
23
23
 
24
+ _SUPPLEMENT_ROWS_JS = """() => [...document.querySelectorAll('a[href]')].map(a => ({
25
+ href: a.href, label: (a.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 240)
26
+ }))"""
27
+
28
+
29
+ def supplement_links_from_rows(rows: list[dict], doi: str) -> list[SupplementLink]:
30
+ stem = doi.lower().replace(".", "-").replace("/", "-")
31
+ links: list[SupplementLink] = []
32
+ seen: set[str] = set()
33
+ for row in rows:
34
+ target = urlparse(str(row.get("href") or ""))
35
+ path = unquote(target.path).lower()
36
+ url = target._replace(fragment="").geturl()
37
+ if (target.scheme == "https" and target.netloc.lower() in _HOSTS
38
+ and re.fullmatch(r"/media/[^/]+/\d+/supmat/" + re.escape(stem) + r"_[^/]+", path)
39
+ and url not in seen):
40
+ seen.add(url)
41
+ links.append(SupplementLink(url, str(row.get("label") or "")))
42
+ return links
43
+
24
44
 
25
45
  @register
26
46
  class ThiemeAdapter(PublisherAdapter):
@@ -29,6 +49,9 @@ class ThiemeAdapter(PublisherAdapter):
29
49
  binds_response_url = True
30
50
  requires_institution_entry = True
31
51
 
52
+ def supplement_links(self, page: Any, doi: str) -> list[SupplementLink]:
53
+ return supplement_links_from_rows(page.evaluate(_SUPPLEMENT_ROWS_JS), doi)
54
+
32
55
  @classmethod
33
56
  def profile_pdf_candidate_url(cls, url: str) -> bool | None:
34
57
  return is_thieme_article_pdf_url(url)