papersearch 0.4.7 → 0.4.9
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/.env.example +3 -0
- package/README.en.md +37 -12
- package/README.md +37 -12
- package/assets/logo.svg +15 -0
- package/assets/overview.en.png +0 -0
- package/assets/overview.png +0 -0
- package/assets/progress-capsule.en.png +0 -0
- package/assets/progress-capsule.png +0 -0
- package/carsi/paper_search_carsi/assets/capsule.html +87 -11
- package/carsi/paper_search_carsi/assets/icon-32.png +0 -0
- package/carsi/paper_search_carsi/assets/icon-512.png +0 -0
- package/carsi/paper_search_carsi/assets/icon-64.png +0 -0
- package/carsi/paper_search_carsi/assets/icon.svg +13 -16
- package/carsi/paper_search_carsi/browser/backend.py +7 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +53 -36
- package/carsi/paper_search_carsi/capsule_placement.py +266 -0
- package/carsi/paper_search_carsi/cli.py +27 -0
- package/carsi/paper_search_carsi/engine/batch.py +5 -1
- package/carsi/paper_search_carsi/engine/batch_access.py +2 -4
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +33 -27
- package/carsi/paper_search_carsi/engine/batch_institution.py +26 -6
- package/carsi/paper_search_carsi/engine/batch_login.py +49 -24
- package/carsi/paper_search_carsi/engine/batch_waits.py +73 -32
- package/carsi/paper_search_carsi/engine/bridge.py +5 -0
- package/carsi/paper_search_carsi/engine/page_activity.py +15 -15
- package/carsi/paper_search_carsi/failure_export.py +239 -0
- package/carsi/paper_search_carsi/issues.py +8 -6
- package/carsi/paper_search_carsi/page_snapshot.py +64 -0
- package/carsi/paper_search_carsi/progress_capsule.py +233 -93
- package/carsi/paper_search_carsi/report_sanitizer.py +248 -0
- package/carsi/paper_search_carsi/user_settings.py +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/cli.js +56 -5
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigService.d.ts +1 -1
- package/dist/config/ConfigService.d.ts.map +1 -1
- package/dist/config/ConfigService.js +1 -0
- package/dist/config/ConfigService.js.map +1 -1
- package/dist/management/failures/exportReport.d.ts +20 -0
- package/dist/management/failures/exportReport.d.ts.map +1 -0
- package/dist/management/failures/exportReport.js +73 -0
- package/dist/management/failures/exportReport.js.map +1 -0
- package/dist/management/failures/index.d.ts +20 -0
- package/dist/management/failures/index.d.ts.map +1 -1
- package/dist/management/failures/index.js +69 -43
- package/dist/management/failures/index.js.map +1 -1
- package/dist/management/updates/index.d.ts +37 -0
- package/dist/management/updates/index.d.ts.map +1 -0
- package/dist/management/updates/index.js +185 -0
- package/dist/management/updates/index.js.map +1 -0
- package/package.json +2 -1
- package/skills/paper-search/SKILL.md +3 -1
- package/skills/paper-search/references/browser-download.md +17 -4
- package/skills/paper-search/references/carsi-setup.md +1 -1
- package/skills/paper-search/references/cli-contract.md +2 -1
- package/skills/paper-search/references/management-layer.md +8 -0
|
@@ -14,11 +14,12 @@ from urllib.parse import urlsplit
|
|
|
14
14
|
_OBSERVE_SCRIPT = """() => {
|
|
15
15
|
const key = Symbol.for('papersearch.turnstile.ready');
|
|
16
16
|
if (window[key]) return;
|
|
17
|
-
const ready = window[key] = new
|
|
17
|
+
const ready = window[key] = new WeakMap();
|
|
18
|
+
let revision = 0;
|
|
18
19
|
addEventListener('message', event => {
|
|
19
20
|
if (event.origin !== 'https://challenges.cloudflare.com' || !event.source
|
|
20
21
|
|| event.data?.source !== 'cloudflare-challenge') return;
|
|
21
|
-
if (event.data.event === 'interactiveBegin') ready.
|
|
22
|
+
if (event.data.event === 'interactiveBegin') ready.set(event.source, ++revision);
|
|
22
23
|
else if (['interactiveEnd', 'complete', 'fail', 'tokenExpired']
|
|
23
24
|
.includes(event.data.event)) ready.delete(event.source);
|
|
24
25
|
});
|
|
@@ -99,7 +100,8 @@ def needs_manual_verification(page: Any) -> bool:
|
|
|
99
100
|
return False
|
|
100
101
|
|
|
101
102
|
|
|
102
|
-
def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
|
|
103
|
+
def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None],
|
|
104
|
+
observation: Callable[[str], None] | None = None) -> Literal[
|
|
103
105
|
"absent", "clicked", "unavailable"
|
|
104
106
|
]:
|
|
105
107
|
"""Try one visible checkbox; never force a click through an overlay.
|
|
@@ -110,11 +112,16 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
|
|
|
110
112
|
"""
|
|
111
113
|
from playwright.sync_api import Error, TimeoutError
|
|
112
114
|
|
|
115
|
+
def note(reason: str) -> None:
|
|
116
|
+
if observation is not None:
|
|
117
|
+
observation(reason)
|
|
118
|
+
|
|
113
119
|
until = time.monotonic() + max(0, timeout_ms) / 1000
|
|
120
|
+
unavailable = False
|
|
114
121
|
for frame in page.frames:
|
|
115
122
|
checkpoint()
|
|
116
123
|
if time.monotonic() >= until:
|
|
117
|
-
return "absent"
|
|
124
|
+
return "unavailable" if unavailable else "absent"
|
|
118
125
|
if not is_turnstile_frame(str(frame.url or "")):
|
|
119
126
|
continue
|
|
120
127
|
try:
|
|
@@ -123,60 +130,68 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
|
|
|
123
130
|
observe_checkbox(page)
|
|
124
131
|
element = frame.frame_element()
|
|
125
132
|
if not element.is_visible():
|
|
133
|
+
note("hidden_frame")
|
|
126
134
|
continue
|
|
127
135
|
controls = frame.locator('input[type="checkbox"], [role="checkbox"]')
|
|
128
136
|
count = controls.count()
|
|
129
137
|
position = None
|
|
130
138
|
if count:
|
|
131
139
|
if count != 1:
|
|
132
|
-
|
|
140
|
+
note("multiple_controls")
|
|
141
|
+
unavailable = True
|
|
142
|
+
continue
|
|
133
143
|
target = controls.first
|
|
134
|
-
if not target.is_visible()
|
|
135
|
-
|
|
144
|
+
if not target.is_visible():
|
|
145
|
+
note("hidden_control")
|
|
146
|
+
continue
|
|
147
|
+
if not target.is_enabled() or target.is_checked():
|
|
148
|
+
note("disabled_or_checked")
|
|
149
|
+
unavailable = True
|
|
150
|
+
continue
|
|
136
151
|
else:
|
|
137
152
|
title = (element.get_attribute("title") or "").lower()
|
|
138
153
|
box = element.bounding_box()
|
|
139
154
|
if ("cloudflare" not in title or "challenge" not in title or not box
|
|
140
155
|
or not 250 <= box["width"] <= 350 or not 60 <= box["height"] <= 80):
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
156
|
+
geometry = f" width={box['width']:.0f} height={box['height']:.0f}" if box else ""
|
|
157
|
+
note("unsupported_geometry_or_title" + geometry)
|
|
158
|
+
unavailable = True
|
|
159
|
+
continue
|
|
160
|
+
readiness = element.evaluate("""iframe =>
|
|
161
|
+
window[Symbol.for('papersearch.turnstile.ready')]?.get(iframe.contentWindow) || 0
|
|
162
|
+
""")
|
|
163
|
+
if not readiness:
|
|
164
|
+
note("waiting_ready_signal")
|
|
165
|
+
continue # loading/automatic check; no click has been attempted
|
|
146
166
|
target = element
|
|
147
167
|
position = {"x": 28, "y": box["height"] / 2}
|
|
148
168
|
checkpoint()
|
|
149
169
|
remaining_ms = int((until - time.monotonic()) * 1000)
|
|
150
170
|
if remaining_ms <= 0:
|
|
151
171
|
return "unavailable"
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
# Trial clicks on an iframe can reach its child document in
|
|
156
|
-
# Playwright. Hover checks visibility/stability/hit targeting
|
|
157
|
-
# without ever dispatching a checkbox click.
|
|
158
|
-
target.hover(timeout=remaining_ms, position=position, trial=True)
|
|
159
|
-
checkpoint()
|
|
160
|
-
remaining_ms = int((until - time.monotonic()) * 1000)
|
|
161
|
-
if remaining_ms <= 0:
|
|
162
|
-
return "unavailable"
|
|
163
|
-
# One readiness signal permits only one closed-shadow click. Wait
|
|
164
|
-
# for a fresh interactiveBegin before retrying; otherwise a stale
|
|
165
|
-
# signal could toggle an already checked or processing widget.
|
|
166
|
-
if position and not element.evaluate("""iframe =>
|
|
167
|
-
window[Symbol.for('papersearch.turnstile.ready')]?.delete(iframe.contentWindow) === true
|
|
168
|
-
"""):
|
|
169
|
-
return "absent"
|
|
170
|
-
remaining_ms = int((until - time.monotonic()) * 1000)
|
|
171
|
-
if remaining_ms <= 0:
|
|
172
|
-
return "unavailable"
|
|
172
|
+
# click performs visibility, stability and hit-target checks itself.
|
|
173
|
+
# A separate humanized hover uses the same short action budget twice.
|
|
174
|
+
# Keep readiness on actionability timeout so an overlay can clear.
|
|
173
175
|
# The engine observes the navigation separately. A dispatched click
|
|
174
176
|
# must not be reported as unavailable while waiting for that load.
|
|
175
177
|
target.click(timeout=remaining_ms, no_wait_after=True,
|
|
176
178
|
**({"position": position} if position else {}))
|
|
179
|
+
if position:
|
|
180
|
+
try:
|
|
181
|
+
element.evaluate("""(iframe, revision) => {
|
|
182
|
+
const ready = window[Symbol.for('papersearch.turnstile.ready')];
|
|
183
|
+
if (ready?.get(iframe.contentWindow) === revision) ready.delete(iframe.contentWindow);
|
|
184
|
+
}""", readiness)
|
|
185
|
+
except Error as exc:
|
|
186
|
+
if not any(text in str(exc).lower() for text in (
|
|
187
|
+
"frame was detached", "frame has been detached", "element is not attached",
|
|
188
|
+
"execution context was destroyed")):
|
|
189
|
+
raise
|
|
190
|
+
note("click_dispatched")
|
|
177
191
|
return "clicked"
|
|
178
192
|
except TimeoutError:
|
|
179
|
-
|
|
193
|
+
note("actionability_timeout")
|
|
194
|
+
unavailable = True
|
|
180
195
|
except Error as exc:
|
|
181
196
|
# Navigation can remove the widget before its action. Browser close,
|
|
182
197
|
# crash, watchdog and cancellation errors must still reach the caller.
|
|
@@ -184,6 +199,8 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
|
|
|
184
199
|
"frame was detached", "frame has been detached", "element is not attached",
|
|
185
200
|
"execution context was destroyed",
|
|
186
201
|
)):
|
|
187
|
-
|
|
202
|
+
note("frame_detached")
|
|
203
|
+
unavailable = True
|
|
204
|
+
continue
|
|
188
205
|
raise
|
|
189
|
-
return "absent"
|
|
206
|
+
return "unavailable" if unavailable else "absent"
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Screen-independent capsule geometry; all coordinates use top-left logical pixels."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import math
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
EDGE, TOP_GAP, BOTTOM_GAP = 20, 44, 56
|
|
12
|
+
SNAP_DISTANCE = 24
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Rect:
|
|
17
|
+
x: float
|
|
18
|
+
y: float
|
|
19
|
+
width: float
|
|
20
|
+
height: float
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def right(self) -> float:
|
|
24
|
+
return self.x + self.width
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def bottom(self) -> float:
|
|
28
|
+
return self.y + self.height
|
|
29
|
+
|
|
30
|
+
def contains_center(self, other: Rect) -> bool:
|
|
31
|
+
return self.contains(other.x + other.width / 2, other.y + other.height / 2)
|
|
32
|
+
|
|
33
|
+
def contains(self, x: float, y: float) -> bool:
|
|
34
|
+
return self.x <= x < self.right and self.y <= y < self.bottom
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class ScreenArea:
|
|
39
|
+
name: str
|
|
40
|
+
bounds: Rect
|
|
41
|
+
work: Rect
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def screen_for(rect: Rect, screens: list[ScreenArea]) -> ScreenArea:
|
|
45
|
+
"""Prefer the centre's screen, otherwise the nearest screen (unplugged display)."""
|
|
46
|
+
for screen in screens:
|
|
47
|
+
if screen.bounds.contains_center(rect):
|
|
48
|
+
return screen
|
|
49
|
+
x, y = rect.x + rect.width / 2, rect.y + rect.height / 2
|
|
50
|
+
return min(screens, key=lambda s: max(s.bounds.x - x, 0, x - s.bounds.right) ** 2
|
|
51
|
+
+ max(s.bounds.y - y, 0, y - s.bounds.bottom) ** 2)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def fit_rect(rect: Rect, work: Rect) -> Rect:
|
|
55
|
+
"""Keep a rectangle in the work area; oversized content starts at its top/left."""
|
|
56
|
+
return Rect(max(work.x, min(rect.x, work.right - rect.width)),
|
|
57
|
+
max(work.y, min(rect.y, work.bottom - rect.height)), rect.width, rect.height)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def direction_for(rect: Rect, work: Rect) -> tuple[str, str]:
|
|
61
|
+
return ("down" if rect.y + rect.height / 2 < work.y + work.height / 2 else "up",
|
|
62
|
+
"right" if rect.x + rect.width / 2 < work.x + work.width / 2 else "left")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _edge(start: float, end: float, low: float, high: float) -> int:
|
|
66
|
+
"""Return -1/1 for the nearby edge, or 0 for free placement on this axis."""
|
|
67
|
+
left, right = start - low, high - end
|
|
68
|
+
if min(left, right) > SNAP_DISTANCE:
|
|
69
|
+
return 0
|
|
70
|
+
return -1 if left <= right else 1
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Placement:
|
|
74
|
+
"""Persist only the collapsed home. Temporary expansion/clamping never moves it."""
|
|
75
|
+
def __init__(self, path: Path, corner: str) -> None:
|
|
76
|
+
self.path, self.corner = path, corner
|
|
77
|
+
self.home: Rect | None = None
|
|
78
|
+
self._dragged_card: Rect | None = None
|
|
79
|
+
self.screen: ScreenArea | None = None
|
|
80
|
+
self.direction = ("down" if corner == "top" else "up", "left")
|
|
81
|
+
self.edges = (0, 0)
|
|
82
|
+
self.expanded = False
|
|
83
|
+
self.scale = 1.0
|
|
84
|
+
self._saved: dict = {}
|
|
85
|
+
try:
|
|
86
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
87
|
+
if isinstance(data, dict):
|
|
88
|
+
self._saved = data
|
|
89
|
+
except FileNotFoundError:
|
|
90
|
+
pass
|
|
91
|
+
except (OSError, ValueError) as exc:
|
|
92
|
+
logging.getLogger(__name__).warning("Cannot read capsule placement: %s", type(exc).__name__)
|
|
93
|
+
|
|
94
|
+
def start(self, screens: list[ScreenArea], size: tuple[int, int], scale: float = 1.0) -> tuple[int, int]:
|
|
95
|
+
w, h = size
|
|
96
|
+
self.scale = scale
|
|
97
|
+
saved = self._saved
|
|
98
|
+
restored = None
|
|
99
|
+
saved_screen = None
|
|
100
|
+
self.edges = (0, 0)
|
|
101
|
+
try:
|
|
102
|
+
if saved.get("version") == 2:
|
|
103
|
+
values = [float(saved[k]) for k in ("x", "y", "width", "height")]
|
|
104
|
+
if all(math.isfinite(n) for n in values) and values[2] > 0 and values[3] > 0:
|
|
105
|
+
old_scale = float(saved.get("scale", 1))
|
|
106
|
+
if not math.isfinite(old_scale) or old_scale <= 0:
|
|
107
|
+
raise ValueError("Invalid saved DPI")
|
|
108
|
+
ratio = old_scale / scale
|
|
109
|
+
restored = Rect(values[0] * ratio, values[1] * ratio, values[2], values[3])
|
|
110
|
+
screen = next((s for s in screens if s.name == saved.get("screen")), None)
|
|
111
|
+
edges = saved.get("edges")
|
|
112
|
+
if screen and isinstance(edges, list) and len(edges) == 2 and all(
|
|
113
|
+
type(edge) is int and edge in (-1, 0, 1) for edge in edges):
|
|
114
|
+
self.edges = (edges[0], edges[1])
|
|
115
|
+
if any(self.edges):
|
|
116
|
+
saved_screen = screen
|
|
117
|
+
if screen and isinstance(saved.get("work"), list) and len(saved["work"]) == 2:
|
|
118
|
+
old_x, old_y = map(float, saved["work"])
|
|
119
|
+
if math.isfinite(old_x) and math.isfinite(old_y):
|
|
120
|
+
restored = Rect(restored.x + screen.work.x - old_x * ratio,
|
|
121
|
+
restored.y + screen.work.y - old_y * ratio,
|
|
122
|
+
restored.width, restored.height)
|
|
123
|
+
elif saved.get("corner") in ("top", "bottom"):
|
|
124
|
+
right, edge = float(saved["right"]), float(saved["edge"])
|
|
125
|
+
if math.isfinite(right) and math.isfinite(edge):
|
|
126
|
+
restored = Rect(right - w, edge if saved["corner"] == "top" else edge - h, w, h)
|
|
127
|
+
except (KeyError, TypeError, ValueError, OverflowError):
|
|
128
|
+
restored = None
|
|
129
|
+
if restored is not None and (saved_screen or any(s.bounds.contains_center(restored) for s in screens)):
|
|
130
|
+
self.screen = saved_screen or screen_for(restored, screens)
|
|
131
|
+
restored = Rect(restored.x, restored.y, min(restored.width, self.screen.work.width),
|
|
132
|
+
min(restored.height, self.screen.work.height))
|
|
133
|
+
self.home = self._fit(restored)
|
|
134
|
+
else:
|
|
135
|
+
self.edges = (0, 0)
|
|
136
|
+
self.screen = screens[0]
|
|
137
|
+
b = self.screen.bounds
|
|
138
|
+
self.home = fit_rect(Rect(b.right - EDGE - w,
|
|
139
|
+
b.y + TOP_GAP if self.corner == "top" else b.bottom - BOTTOM_GAP - h,
|
|
140
|
+
w, h), self.screen.work)
|
|
141
|
+
self.direction = self._direction(self.home)
|
|
142
|
+
return round(self.home.x), round(self.home.y)
|
|
143
|
+
|
|
144
|
+
def rescale(self, scale: float) -> None:
|
|
145
|
+
"""Rebase global coordinates when a Windows drag crosses different DPIs."""
|
|
146
|
+
ratio = self.scale / scale
|
|
147
|
+
if ratio != 1:
|
|
148
|
+
if self.home is not None:
|
|
149
|
+
self.home = self._rescaled(self.home, ratio)
|
|
150
|
+
if self._dragged_card is not None:
|
|
151
|
+
self._dragged_card = self._rescaled(self._dragged_card, ratio)
|
|
152
|
+
self.scale = scale
|
|
153
|
+
|
|
154
|
+
@staticmethod
|
|
155
|
+
def _rescaled(rect: Rect, ratio: float) -> Rect:
|
|
156
|
+
return Rect(rect.x * ratio, rect.y * ratio, rect.width, rect.height)
|
|
157
|
+
|
|
158
|
+
def begin(self, expanded: bool, actual: Rect, screens: list[ScreenArea]) -> None:
|
|
159
|
+
if self.home is None:
|
|
160
|
+
self.home = actual
|
|
161
|
+
if not self.expanded:
|
|
162
|
+
# The first measured pill can differ from START_SIZE.
|
|
163
|
+
self.home = actual
|
|
164
|
+
self.screen = screen_for(self.home, screens)
|
|
165
|
+
if not self.expanded:
|
|
166
|
+
self.direction = self._direction(self.home)
|
|
167
|
+
if expanded:
|
|
168
|
+
self.expanded = True
|
|
169
|
+
|
|
170
|
+
def target(self, width: int, height: int, expanded: bool) -> Rect:
|
|
171
|
+
assert self.home is not None and self.screen is not None
|
|
172
|
+
home, work = self.home, self.screen.work
|
|
173
|
+
width, height = min(width, int(work.width)), min(height, int(work.height))
|
|
174
|
+
if expanded or not self.expanded:
|
|
175
|
+
anchor = (self._dragged_card if expanded else None) or home
|
|
176
|
+
vertical, horizontal = self.direction
|
|
177
|
+
x = anchor.right - width if horizontal == "left" else anchor.x
|
|
178
|
+
y = anchor.bottom - height if vertical == "up" else anchor.y
|
|
179
|
+
else:
|
|
180
|
+
# A different status can change the pill's width while it is open.
|
|
181
|
+
x, y = home.x, home.y
|
|
182
|
+
return self._fit(Rect(x, y, width, height))
|
|
183
|
+
|
|
184
|
+
def finish(self, expanded: bool, actual: Rect) -> None:
|
|
185
|
+
if not expanded:
|
|
186
|
+
self.home = actual
|
|
187
|
+
self._dragged_card = None
|
|
188
|
+
self.expanded = False
|
|
189
|
+
self.save()
|
|
190
|
+
|
|
191
|
+
def _fit(self, rect: Rect) -> Rect:
|
|
192
|
+
work = self.screen.work
|
|
193
|
+
horizontal, vertical = self.edges
|
|
194
|
+
x = work.x if horizontal < 0 else work.right - rect.width if horizontal > 0 else rect.x
|
|
195
|
+
y = work.y if vertical < 0 else work.bottom - rect.height if vertical > 0 else rect.y
|
|
196
|
+
return fit_rect(Rect(x, y, rect.width, rect.height), work)
|
|
197
|
+
|
|
198
|
+
def _direction(self, rect: Rect) -> tuple[str, str]:
|
|
199
|
+
vertical, horizontal = direction_for(rect, self.screen.work)
|
|
200
|
+
x, y = self.edges
|
|
201
|
+
return ("down" if y < 0 else "up" if y > 0 else vertical,
|
|
202
|
+
"right" if x < 0 else "left" if x > 0 else horizontal)
|
|
203
|
+
|
|
204
|
+
def _drop_edges(self, rect: Rect, work: Rect, pointer: tuple[float, float] | None) -> tuple[int, int]:
|
|
205
|
+
x = _edge(rect.x, rect.right, work.x, work.right)
|
|
206
|
+
y = _edge(rect.y, rect.bottom, work.y, work.bottom)
|
|
207
|
+
if pointer is None:
|
|
208
|
+
return x, y
|
|
209
|
+
px, py = pointer
|
|
210
|
+
mouse_x = _edge(px, px, work.x, work.right)
|
|
211
|
+
mouse_y = _edge(py, py, work.y, work.bottom)
|
|
212
|
+
if not self.expanded:
|
|
213
|
+
return mouse_x or x, mouse_y or y
|
|
214
|
+
# A large card can touch a second edge by size alone. Only a release
|
|
215
|
+
# near the corner docks both axes; otherwise keep the closer edge.
|
|
216
|
+
if mouse_x or mouse_y:
|
|
217
|
+
return mouse_x, mouse_y
|
|
218
|
+
if x and y:
|
|
219
|
+
dx = abs(rect.x - work.x if x < 0 else work.right - rect.right)
|
|
220
|
+
dy = abs(rect.y - work.y if y < 0 else work.bottom - rect.bottom)
|
|
221
|
+
if dx != dy:
|
|
222
|
+
return (x, 0) if dx < dy else (0, y)
|
|
223
|
+
px_gap = abs(px - (work.x if x < 0 else work.right))
|
|
224
|
+
py_gap = abs(py - (work.y if y < 0 else work.bottom))
|
|
225
|
+
return (x, 0) if px_gap <= py_gap else (0, y)
|
|
226
|
+
return x, y
|
|
227
|
+
|
|
228
|
+
def dragged(self, after: Rect, screens: list[ScreenArea],
|
|
229
|
+
pointer: tuple[float, float] | None = None) -> Rect:
|
|
230
|
+
# At a display seam the card's centre may still be on the previous
|
|
231
|
+
# display. Prefer the display where the user actually released it.
|
|
232
|
+
self.screen = next((s for s in screens if pointer and s.bounds.contains(*pointer)), None)
|
|
233
|
+
if self.screen is None:
|
|
234
|
+
self.screen = screen_for(after, screens)
|
|
235
|
+
work = self.screen.work
|
|
236
|
+
point = pointer if pointer and self.screen.bounds.contains(*pointer) else None
|
|
237
|
+
self.edges = self._drop_edges(after, work, point)
|
|
238
|
+
after = self._fit(Rect(after.x, after.y, min(after.width, work.width), min(after.height, work.height)))
|
|
239
|
+
self.direction = self._direction(after)
|
|
240
|
+
if self.home is None or not self.expanded:
|
|
241
|
+
self.home = after
|
|
242
|
+
else:
|
|
243
|
+
self._dragged_card = after
|
|
244
|
+
vertical, horizontal = self.direction
|
|
245
|
+
w, h = self.home.width, self.home.height
|
|
246
|
+
if point is not None and any(self.edges):
|
|
247
|
+
# The card's chosen growth corner must not quantize where the
|
|
248
|
+
# much smaller pill lands along the side.
|
|
249
|
+
self.home = Rect(point[0] - w / 2, point[1] - h / 2, w, h)
|
|
250
|
+
else:
|
|
251
|
+
self.home = Rect(after.right - w if horizontal == "left" else after.x,
|
|
252
|
+
after.bottom - h if vertical == "up" else after.y, w, h)
|
|
253
|
+
self.home = self._fit(self.home)
|
|
254
|
+
self.save()
|
|
255
|
+
return after
|
|
256
|
+
|
|
257
|
+
def save(self) -> None:
|
|
258
|
+
if self.home is None or self.screen is None:
|
|
259
|
+
return
|
|
260
|
+
try:
|
|
261
|
+
self.path.write_text(json.dumps({"version": 2, "x": self.home.x, "y": self.home.y,
|
|
262
|
+
"width": self.home.width, "height": self.home.height, "screen": self.screen.name,
|
|
263
|
+
"work": [self.screen.work.x, self.screen.work.y], "scale": self.scale,
|
|
264
|
+
"edges": self.edges}), encoding="utf-8")
|
|
265
|
+
except OSError as exc:
|
|
266
|
+
logging.getLogger(__name__).warning("Cannot save capsule placement: %s", type(exc).__name__)
|
|
@@ -220,6 +220,29 @@ def _cmd_login(args: argparse.Namespace) -> int:
|
|
|
220
220
|
# other commands
|
|
221
221
|
# ---------------------------------------------------------------------------
|
|
222
222
|
|
|
223
|
+
def _cmd_report_export(args: argparse.Namespace) -> int:
|
|
224
|
+
from .config import load_config
|
|
225
|
+
from .failure_export import ExportError, MAX_REQUEST_BYTES, export_report
|
|
226
|
+
|
|
227
|
+
try:
|
|
228
|
+
raw = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1)
|
|
229
|
+
if len(raw) > MAX_REQUEST_BYTES:
|
|
230
|
+
raise ExportError("export_request_too_large")
|
|
231
|
+
request = json.loads(raw)
|
|
232
|
+
if not isinstance(request, dict):
|
|
233
|
+
raise ExportError("invalid_export_request")
|
|
234
|
+
result = export_report(request, Path(args.output), load_config())
|
|
235
|
+
except (OSError, ValueError) as exc:
|
|
236
|
+
# Never print original JSON, paths, secrets or exception payloads.
|
|
237
|
+
code = (str(exc) if isinstance(exc, ExportError) else
|
|
238
|
+
"export_target_exists" if isinstance(exc, FileExistsError) else
|
|
239
|
+
"export_permission_denied" if isinstance(exc, PermissionError) else "export_io_or_input_error")
|
|
240
|
+
print(json.dumps({"ok": False, "error": code}))
|
|
241
|
+
return 1
|
|
242
|
+
print(json.dumps(result, ensure_ascii=False))
|
|
243
|
+
return 0
|
|
244
|
+
|
|
245
|
+
|
|
223
246
|
def _cmd_run(_args: argparse.Namespace) -> int:
|
|
224
247
|
from .server import main as serve
|
|
225
248
|
|
|
@@ -436,6 +459,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
436
459
|
|
|
437
460
|
sub.add_parser("list-publishers", help="print publisher profiles and their platform labels").set_defaults(func=_cmd_list_publishers)
|
|
438
461
|
|
|
462
|
+
exp = sub.add_parser("report-export", help="export a sanitized local failure ZIP from a JSON request on stdin")
|
|
463
|
+
exp.add_argument("--output", required=True)
|
|
464
|
+
exp.set_defaults(func=_cmd_report_export)
|
|
465
|
+
|
|
439
466
|
chk = sub.add_parser("publisher-check", help="run one institutional download and print a sanitized report")
|
|
440
467
|
chk.add_argument("--doi", required=True)
|
|
441
468
|
chk.add_argument("--output-dir")
|
|
@@ -187,6 +187,7 @@ class PublisherBatchDownloader(
|
|
|
187
187
|
from . import supplements
|
|
188
188
|
from .supplement_transfer import browser_request
|
|
189
189
|
|
|
190
|
+
self._run_dir = manifest_dir or getattr(self, "_run_dir", None)
|
|
190
191
|
self._phase(result, "supplements")
|
|
191
192
|
main_state = result.state
|
|
192
193
|
progress_reporter.update(part="supplements", supplements_saved=0, supplements_total=None)
|
|
@@ -232,6 +233,7 @@ class PublisherBatchDownloader(
|
|
|
232
233
|
links = self._settled_supplement_links(page, doi)
|
|
233
234
|
if not (self._challenge_shell(page) or self._is_challenge_page(page)):
|
|
234
235
|
break
|
|
236
|
+
self._snapshot(page, result, "supplements page")
|
|
235
237
|
if links is None:
|
|
236
238
|
self._event(result, "supplements_not_supported", self.profile.name)
|
|
237
239
|
return [{"status": "skipped", "reason": "supplements_not_supported", "url": url, "label": ""}]
|
|
@@ -467,6 +469,7 @@ class PublisherBatchDownloader(
|
|
|
467
469
|
preparation = self._prepare_article(page, result, run_dir)
|
|
468
470
|
if preparation is not None:
|
|
469
471
|
return preparation
|
|
472
|
+
self._snapshot(page, result, "article access checked")
|
|
470
473
|
ip_block: str | None = None
|
|
471
474
|
# Whether this capture comes after the school's login, and its first attempt.
|
|
472
475
|
signed_in, attempts_from = self._school_login_done(), len(result.pdf_attempts)
|
|
@@ -782,7 +785,6 @@ class PublisherBatchDownloader(
|
|
|
782
785
|
pdf_path = pdf_dir / f"{safe_name(record.doi)}.pdf"
|
|
783
786
|
pdf_path.write_bytes(pdf_bytes)
|
|
784
787
|
self._event(result, "pdf_saved")
|
|
785
|
-
self._drop_snapshot_pictures(result)
|
|
786
788
|
text = pdf_extractor.extract_from_bytes(pdf_bytes)
|
|
787
789
|
result.status = "success"
|
|
788
790
|
result.reason = ""
|
|
@@ -793,6 +795,8 @@ class PublisherBatchDownloader(
|
|
|
793
795
|
result.text_length = len(text or "")
|
|
794
796
|
result.verified_match = self._text_matches_record(
|
|
795
797
|
text, record, fallback_title=self._identity_title() or result.title)
|
|
798
|
+
if result.verified_match and str(self.config.get("supplements") or "") != "with":
|
|
799
|
+
self._drop_snapshot_pictures(result)
|
|
796
800
|
self._save_publisher_session(page, result)
|
|
797
801
|
if not any(e["state"] == "pdf_saved_unconfirmed" for e in result.events):
|
|
798
802
|
from ..browser.preview import discard_frames
|
|
@@ -261,11 +261,9 @@ class AccessMixin:
|
|
|
261
261
|
return not getattr(getattr(self, "_item_result", None), "_pdf_retry_login", False)
|
|
262
262
|
|
|
263
263
|
def _school_login_done(self) -> bool:
|
|
264
|
-
"""This item
|
|
265
|
-
back to the publisher from a login or chooser page, already."""
|
|
264
|
+
"""This item reached its IdP; selecting a school is only an attempt."""
|
|
266
265
|
result = getattr(self, "_item_result", None)
|
|
267
|
-
return result is not None and (getattr(result, "_visited_idp", False) or getattr(result, "_login_round_trip", False)
|
|
268
|
-
or any(e.get("state") in self._SCHOOL_CHOSEN for e in result.events))
|
|
266
|
+
return result is not None and (getattr(result, "_visited_idp", False) or getattr(result, "_login_round_trip", False))
|
|
269
267
|
|
|
270
268
|
def _institution_pdf_entitlement_missing(self, page: Any, snapshot: SimpleNamespace | None = None) -> bool:
|
|
271
269
|
"""The article page denies access (access_rules.denial_evidence) to a
|
|
@@ -117,8 +117,10 @@ class DiagnosticsMixin:
|
|
|
117
117
|
}.get(state)
|
|
118
118
|
if state == "login_state" and getattr(result, "_login_attention", ""):
|
|
119
119
|
report = ("等待在浏览器完成机构登录", "waiting_login")
|
|
120
|
-
if state == "challenge_wait" and detail.startswith("manual "):
|
|
121
|
-
report = ("等待人工安全验证", "waiting_verification")
|
|
120
|
+
if state == "challenge_manual_wait" or state == "challenge_wait" and detail.startswith("manual "):
|
|
121
|
+
report = (("等待人工安全验证", "waiting_verification")
|
|
122
|
+
if getattr(result, "_verification_attention", False)
|
|
123
|
+
else ("正在检查安全验证", "checking_access"))
|
|
122
124
|
if state == "login_attempt_started" and detail in {"1/3", "2/3", "3/3"}:
|
|
123
125
|
report = (f"机构登录:第 {detail[0]} 次尝试,共 3 次", "checking_access")
|
|
124
126
|
if state == "login_observed":
|
|
@@ -164,7 +166,12 @@ class DiagnosticsMixin:
|
|
|
164
166
|
def _snapshot(self, page: Any, result: DownloadResult | None, why: str) -> None:
|
|
165
167
|
"""The page's URL and title, and a small picture of the window with every
|
|
166
168
|
form field masked (never their values), in the article's diagnostics folder."""
|
|
167
|
-
|
|
169
|
+
from ..browser import watchdog
|
|
170
|
+
if watchdog.fired:
|
|
171
|
+
return
|
|
172
|
+
if (result is None or len(result.snapshots) >= self.MAX_SNAPSHOTS
|
|
173
|
+
or (self.config.get("supplements") == "with" and len(result.snapshots) >= self.MAX_SNAPSHOTS - 1
|
|
174
|
+
and not why.startswith("supplements"))):
|
|
168
175
|
return
|
|
169
176
|
url = str(getattr(page, "url", "") or "")
|
|
170
177
|
entry = {"at": datetime.now().strftime("%H:%M:%S"), "why": why, "url": url[:500],
|
|
@@ -173,13 +180,9 @@ class DiagnosticsMixin:
|
|
|
173
180
|
if run_dir is not None:
|
|
174
181
|
folder = Path(run_dir) / "diagnostics" / safe_name(result.doi)
|
|
175
182
|
path = folder / f"snapshot-{len(result.snapshots) + 1}-{re.sub(r'[^a-z0-9]+', '-', why.lower())[:40]}.jpg"
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
mask=[page.locator("input, textarea, select")])
|
|
180
|
-
entry["screenshot"] = str(path)
|
|
181
|
-
except Exception:
|
|
182
|
-
pass # the URL and title are kept
|
|
183
|
+
from ..page_snapshot import capture_structure, masked_screenshot
|
|
184
|
+
entry.update(capture_structure(page, path.with_suffix(".html"), self.config))
|
|
185
|
+
entry.update(masked_screenshot(page, path))
|
|
183
186
|
result.snapshots.append(entry)
|
|
184
187
|
self._event(result, "snapshot", f"{why} | {url[:160]} | {entry['title'][:80]}")
|
|
185
188
|
|
|
@@ -187,9 +190,10 @@ class DiagnosticsMixin:
|
|
|
187
190
|
"""A successful article keeps its snapshots' URLs and titles, not their
|
|
188
191
|
pictures (the live preview's frames go the same way)."""
|
|
189
192
|
for entry in result.snapshots:
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
+
for key in ("screenshot", "html"):
|
|
194
|
+
artifact = entry.pop(key, None)
|
|
195
|
+
if artifact:
|
|
196
|
+
Path(artifact).unlink(missing_ok=True)
|
|
193
197
|
|
|
194
198
|
def _note_wait(self, result: DownloadResult | None, what: str, started: float, why: str) -> None:
|
|
195
199
|
"""A wait of more than ``LONG_WAIT_SEC``: what it waited for and why it ended."""
|
|
@@ -208,6 +212,8 @@ class DiagnosticsMixin:
|
|
|
208
212
|
# Persist fixed classifications, without changing the live workflow state.
|
|
209
213
|
packet = serialize_download_result({**asdict(result),
|
|
210
214
|
"final_url": getattr(page, "url", result.final_url)}, diagnostic=True)
|
|
215
|
+
import platform
|
|
216
|
+
packet["capture_system"] = platform.system()
|
|
211
217
|
packet["adapter"] = type(self.adapter).__name__
|
|
212
218
|
packet["browser"] = getattr(self, "browser", {})
|
|
213
219
|
from ..browser import watchdog
|
|
@@ -221,22 +227,22 @@ class DiagnosticsMixin:
|
|
|
221
227
|
except Exception as exc:
|
|
222
228
|
packet["access_state"], packet["access_evidence"] = "unknown", [f"probe failed: {type(exc).__name__}"]
|
|
223
229
|
packet_path = diag_dir / "diagnostic.json"
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
page.screenshot(path=str(diag_dir / "screenshot.png"), full_page=True)
|
|
228
|
-
except Exception:
|
|
229
|
-
pass
|
|
230
|
-
# Other tabs (a PDF or verification tab) are where the problem usually is.
|
|
230
|
+
if not stopped and result.reason != "publisher_access_blocked":
|
|
231
|
+
from ..page_snapshot import capture_structure, masked_screenshot
|
|
232
|
+
pages = []
|
|
231
233
|
try:
|
|
232
|
-
|
|
234
|
+
pages = [p for p in list(page.context.pages) if p is not page and not p.is_closed()][:2]
|
|
233
235
|
except Exception:
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
236
|
+
pass # The working page is still captured; no other tab is known.
|
|
237
|
+
packet["pages"] = []
|
|
238
|
+
for index, tab in enumerate([page] + pages):
|
|
239
|
+
stem = "screenshot" if index == 0 else f"screenshot-tab{index}"
|
|
240
|
+
row = {"url": str(getattr(tab, "url", "") or ""), "title": self._title(tab)[:200], "why": "download failed"}
|
|
241
|
+
row.update(capture_structure(tab, diag_dir / f"{stem}.html", self.config))
|
|
242
|
+
if self.adapter.diagnostic_screenshots:
|
|
243
|
+
row.update(masked_screenshot(tab, diag_dir / f"{stem}.png"))
|
|
244
|
+
packet["pages"].append(row)
|
|
245
|
+
packet_path.write_text(json.dumps(packet, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
240
246
|
result.diagnostic_path = str(packet_path)
|
|
241
247
|
|
|
242
248
|
def _denial_line(self, page: Any) -> str:
|