papersearch 0.5.1 → 0.5.2
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 +8 -13
- package/README.md +8 -13
- package/carsi/paper_search_carsi/assets/api_keys.json +1 -1
- package/carsi/paper_search_carsi/assets/capsule_en.json +5 -0
- package/carsi/paper_search_carsi/browser/cookies.py +3 -206
- package/carsi/paper_search_carsi/cli.py +73 -37
- package/carsi/paper_search_carsi/config.py +24 -106
- package/carsi/paper_search_carsi/download_diagnostics.py +3 -3
- package/carsi/paper_search_carsi/engine/batch.py +15 -0
- package/carsi/paper_search_carsi/engine/batch_common.py +6 -0
- package/carsi/paper_search_carsi/engine/bridge.py +17 -4
- package/carsi/paper_search_carsi/orchestrator.py +19 -2
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +2 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/cli.js +19 -3
- package/dist/cli.js.map +1 -1
- package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
- package/dist/infrastructure/runlog/failureClass.js +1 -0
- package/dist/infrastructure/runlog/failureClass.js.map +1 -1
- package/dist/management/carsi/login.d.ts +28 -0
- package/dist/management/carsi/login.d.ts.map +1 -0
- package/dist/management/carsi/login.js +46 -0
- package/dist/management/carsi/login.js.map +1 -0
- package/dist/management/skills/nextSteps.d.ts.map +1 -1
- package/dist/management/skills/nextSteps.js +4 -3
- package/dist/management/skills/nextSteps.js.map +1 -1
- package/package.json +1 -1
- package/skills/paper-search/SKILL.md +11 -9
- package/skills/paper-search/references/browser-download.md +2 -1
- package/skills/paper-search/references/capability-routing.md +1 -1
- package/skills/paper-search/references/carsi-setup.md +14 -3
- package/skills/paper-search/references/cli-contract.md +1 -0
- package/skills/paper-search/references/publisher-support.md +1 -1
- package/carsi/paper_search_carsi/browser/login.py +0 -332
|
@@ -1,332 +0,0 @@
|
|
|
1
|
-
"""Institutional login via stealth browser: the window of ``login --kind custom``."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import json
|
|
6
|
-
import time
|
|
7
|
-
import atexit
|
|
8
|
-
from pathlib import Path
|
|
9
|
-
from typing import Any
|
|
10
|
-
|
|
11
|
-
from .backend import CHROME_MISSING, launch
|
|
12
|
-
from .backend import is_available as _browser_backend_available
|
|
13
|
-
from ..log import get_logger
|
|
14
|
-
|
|
15
|
-
log = get_logger()
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
class PersistentBrowser:
|
|
19
|
-
"""Keeps a stealth browser alive across multiple operations.
|
|
20
|
-
|
|
21
|
-
Login once, reuse the same browser for all subsequent downloads.
|
|
22
|
-
The WebVPN session stays valid because the browser instance never closes.
|
|
23
|
-
"""
|
|
24
|
-
|
|
25
|
-
def __init__(self):
|
|
26
|
-
self._browser = None
|
|
27
|
-
self._context = None
|
|
28
|
-
self._page = None
|
|
29
|
-
self._cookies_saved = False
|
|
30
|
-
|
|
31
|
-
@property
|
|
32
|
-
def is_alive(self) -> bool:
|
|
33
|
-
if self._browser is None:
|
|
34
|
-
return False
|
|
35
|
-
try:
|
|
36
|
-
self._page.url # noqa: B018
|
|
37
|
-
return True
|
|
38
|
-
except Exception:
|
|
39
|
-
self._cleanup()
|
|
40
|
-
return False
|
|
41
|
-
|
|
42
|
-
def get_page(self, config: dict[str, Any] | None = None):
|
|
43
|
-
"""Get or create the browser page. Returns (context, page)."""
|
|
44
|
-
if self.is_alive:
|
|
45
|
-
return self._context, self._page
|
|
46
|
-
return self._start(config)
|
|
47
|
-
|
|
48
|
-
def _start(self, config: dict[str, Any] | None = None):
|
|
49
|
-
"""Start a new browser instance. Restores saved state if available."""
|
|
50
|
-
if not _browser_backend_available(config=config):
|
|
51
|
-
raise RuntimeError(f"no browser backend available: {CHROME_MISSING}")
|
|
52
|
-
log.info(" [browser] Starting persistent browser...")
|
|
53
|
-
self._browser = launch(
|
|
54
|
-
headless=False, humanize=True,
|
|
55
|
-
args=["--disable-features=CrossOriginOpenerPolicy"],
|
|
56
|
-
)
|
|
57
|
-
self._context = self._browser.new_context()
|
|
58
|
-
self._page = self._context.new_page()
|
|
59
|
-
|
|
60
|
-
if config:
|
|
61
|
-
self._restore_state(config)
|
|
62
|
-
|
|
63
|
-
return self._context, self._page
|
|
64
|
-
|
|
65
|
-
def _restore_state(self, config: dict[str, Any]):
|
|
66
|
-
"""Restore saved cookies and localStorage into the browser."""
|
|
67
|
-
from ..config import DATA_DIR
|
|
68
|
-
cache_dir = Path(config.get("cache_dir", str(DATA_DIR / "cache")))
|
|
69
|
-
state_file = cache_dir / "browser_state.json"
|
|
70
|
-
if not state_file.exists():
|
|
71
|
-
return
|
|
72
|
-
try:
|
|
73
|
-
state = json.loads(state_file.read_text(encoding="utf-8"))
|
|
74
|
-
except Exception:
|
|
75
|
-
log.info(" [browser] browser_state.json corrupted, starting fresh")
|
|
76
|
-
return
|
|
77
|
-
|
|
78
|
-
cookies = state.get("cookies", [])
|
|
79
|
-
if cookies:
|
|
80
|
-
try:
|
|
81
|
-
self._context.add_cookies(cookies)
|
|
82
|
-
log.info(f" [browser] Restored {len(cookies)} cookies")
|
|
83
|
-
except Exception as e:
|
|
84
|
-
log.info(f" [browser] Cookie restore warning: {e}")
|
|
85
|
-
|
|
86
|
-
storage = state.get("localStorage", {})
|
|
87
|
-
for origin, items in storage.items():
|
|
88
|
-
try:
|
|
89
|
-
self._page.goto(origin, wait_until="commit", timeout=10000)
|
|
90
|
-
for key, value in items.items():
|
|
91
|
-
self._page.evaluate(f"localStorage.setItem({json.dumps(key)}, {json.dumps(value)})")
|
|
92
|
-
except Exception as e:
|
|
93
|
-
log.info(f" [browser] localStorage restore failed for {origin}: {e}")
|
|
94
|
-
|
|
95
|
-
log.info(" [browser] Browser state restored")
|
|
96
|
-
|
|
97
|
-
def save_cookies(self, config: dict[str, Any]):
|
|
98
|
-
"""Save current browser state (cookies + localStorage) to disk."""
|
|
99
|
-
if not self._context:
|
|
100
|
-
return
|
|
101
|
-
try:
|
|
102
|
-
from ..config import DATA_DIR
|
|
103
|
-
cache_dir = Path(config.get("cache_dir", str(DATA_DIR / "cache")))
|
|
104
|
-
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
105
|
-
|
|
106
|
-
cookies = self._context.cookies()
|
|
107
|
-
|
|
108
|
-
localStorage = {}
|
|
109
|
-
for page in self._context.pages:
|
|
110
|
-
try:
|
|
111
|
-
url = page.url
|
|
112
|
-
if url.startswith("http"):
|
|
113
|
-
from urllib.parse import urlparse
|
|
114
|
-
origin = f"{urlparse(url).scheme}://{urlparse(url).hostname}"
|
|
115
|
-
items = page.evaluate("""
|
|
116
|
-
(() => {
|
|
117
|
-
const items = {};
|
|
118
|
-
for (let i = 0; i < localStorage.length; i++) {
|
|
119
|
-
const key = localStorage.key(i);
|
|
120
|
-
items[key] = localStorage.getItem(key);
|
|
121
|
-
}
|
|
122
|
-
return items;
|
|
123
|
-
})()
|
|
124
|
-
""")
|
|
125
|
-
if items:
|
|
126
|
-
localStorage[origin] = items
|
|
127
|
-
except Exception:
|
|
128
|
-
pass
|
|
129
|
-
|
|
130
|
-
state = {"cookies": cookies, "localStorage": localStorage}
|
|
131
|
-
state_file = cache_dir / "browser_state.json"
|
|
132
|
-
state_file.write_text(json.dumps(state, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
133
|
-
|
|
134
|
-
cookie_file = cache_dir / "instsci-cookies.json"
|
|
135
|
-
cookie_data = [
|
|
136
|
-
{"name": c["name"], "value": c["value"], "domain": c.get("domain", ""), "path": c.get("path", "/")}
|
|
137
|
-
for c in cookies
|
|
138
|
-
]
|
|
139
|
-
cookie_file.write_text(json.dumps(cookie_data, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
140
|
-
|
|
141
|
-
netscape_file = cache_dir / "instsci-cookies.txt"
|
|
142
|
-
from .cookies import cookies_to_netscape
|
|
143
|
-
netscape_file.write_text(cookies_to_netscape(cookies), encoding="utf-8")
|
|
144
|
-
|
|
145
|
-
self._cookies_saved = True
|
|
146
|
-
log.info(f" [browser] Saved {len(cookies)} cookies + {len(localStorage)} localStorage origins")
|
|
147
|
-
except Exception as e:
|
|
148
|
-
log.info(f" [browser] Failed to save state: {e}")
|
|
149
|
-
|
|
150
|
-
def _cleanup(self):
|
|
151
|
-
"""Close browser gracefully."""
|
|
152
|
-
try:
|
|
153
|
-
if self._browser:
|
|
154
|
-
self._browser.close()
|
|
155
|
-
except Exception:
|
|
156
|
-
pass
|
|
157
|
-
self._browser = None
|
|
158
|
-
self._context = None
|
|
159
|
-
self._page = None
|
|
160
|
-
|
|
161
|
-
def close(self):
|
|
162
|
-
"""Explicitly close the browser."""
|
|
163
|
-
self._cleanup()
|
|
164
|
-
log.info(" [browser] Persistent browser closed")
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
# Module-level singleton
|
|
168
|
-
_browser = PersistentBrowser()
|
|
169
|
-
# Logging/capture streams may already be closed during interpreter shutdown.
|
|
170
|
-
# Explicit close still logs; the exit hook only releases owned browser resources.
|
|
171
|
-
atexit.register(_browser._cleanup)
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
def get_browser(config: dict[str, Any] | None = None):
|
|
175
|
-
"""Get the persistent browser singleton. Returns (browser, context, page)."""
|
|
176
|
-
context, page = _browser.get_page(config)
|
|
177
|
-
return _browser, context, page
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
def save_browser_cookies(config: dict[str, Any]):
|
|
181
|
-
"""Save cookies from the persistent browser."""
|
|
182
|
-
_browser.save_cookies(config)
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
def close_browser():
|
|
186
|
-
"""Close the persistent browser."""
|
|
187
|
-
_browser.close()
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
def _save_cookies_json(cookies: list[dict[str, Any]], cookie_file: Path) -> None:
|
|
191
|
-
"""Save cookies in JSON format."""
|
|
192
|
-
cookie_data = [
|
|
193
|
-
{"name": c["name"], "value": c["value"], "domain": c.get("domain", ""), "path": c.get("path", "/")}
|
|
194
|
-
for c in cookies
|
|
195
|
-
]
|
|
196
|
-
cookie_file.parent.mkdir(parents=True, exist_ok=True)
|
|
197
|
-
cookie_file.write_text(
|
|
198
|
-
json.dumps(cookie_data, indent=2, ensure_ascii=False),
|
|
199
|
-
encoding="utf-8",
|
|
200
|
-
)
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
def _save_cookies_netscape(cookies: list[dict[str, Any]], cookie_file: Path) -> None:
|
|
204
|
-
"""Save cookies in Netscape format (the shared browser imports this format)."""
|
|
205
|
-
from .cookies import cookies_to_netscape
|
|
206
|
-
cookie_file.write_text(cookies_to_netscape(cookies), encoding="utf-8")
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
def _import_to_browser(cookie_file: Path, config: dict[str, Any]) -> int:
|
|
210
|
-
"""Import cookies into the shared browser. Returns count imported."""
|
|
211
|
-
try:
|
|
212
|
-
from .engine import import_cookies, is_available
|
|
213
|
-
if not is_available(config):
|
|
214
|
-
log.info(" [browser] no browser backend, skipping auto-import")
|
|
215
|
-
return 0
|
|
216
|
-
count = import_cookies(cookie_file, config)
|
|
217
|
-
log.info(f" [browser] Imported {count} cookies into the browser")
|
|
218
|
-
return count
|
|
219
|
-
except Exception as exc:
|
|
220
|
-
log.info(f" [browser] Could not auto-import to the browser: {exc}")
|
|
221
|
-
return 0
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
def open_login_browser(
|
|
225
|
-
url: str,
|
|
226
|
-
config: dict[str, Any],
|
|
227
|
-
*,
|
|
228
|
-
cookie_file: Path,
|
|
229
|
-
detect_login: Any = None,
|
|
230
|
-
max_wait: int = 300,
|
|
231
|
-
auto_import: bool = True,
|
|
232
|
-
keep_alive: bool = False,
|
|
233
|
-
publisher: str = "",
|
|
234
|
-
) -> bool | tuple[bool, Any, Any, Any]:
|
|
235
|
-
"""Open a visible stealth browser for interactive login.
|
|
236
|
-
|
|
237
|
-
Args:
|
|
238
|
-
url: Login URL to open.
|
|
239
|
-
config: backend config dict.
|
|
240
|
-
cookie_file: Path to save captured cookies (JSON).
|
|
241
|
-
detect_login: Optional callable(browser_context, page) -> bool for custom login detection.
|
|
242
|
-
max_wait: Max seconds to wait for login.
|
|
243
|
-
auto_import: Whether to auto-import cookies into the shared browser.
|
|
244
|
-
keep_alive: If True, return (True, context, page) without closing browser.
|
|
245
|
-
publisher: Publisher name (unused; kept for callers).
|
|
246
|
-
|
|
247
|
-
Returns:
|
|
248
|
-
True if login succeeded, or (True, context, page) if keep_alive.
|
|
249
|
-
"""
|
|
250
|
-
log.info(f" [browser] Opening stealth browser: {url}")
|
|
251
|
-
print(f"\n 请在浏览器中登录 ({url})")
|
|
252
|
-
print(" 程序会自动检测登录完成...\n")
|
|
253
|
-
|
|
254
|
-
if not _browser_backend_available(config=config):
|
|
255
|
-
log.info(f" [browser] {CHROME_MISSING}")
|
|
256
|
-
return (False, None, None, None) if keep_alive else False
|
|
257
|
-
|
|
258
|
-
try:
|
|
259
|
-
browser = launch(headless=False, humanize=True,
|
|
260
|
-
args=["--disable-features=CrossOriginOpenerPolicy"])
|
|
261
|
-
context = browser.new_context()
|
|
262
|
-
page = context.new_page()
|
|
263
|
-
|
|
264
|
-
try:
|
|
265
|
-
page.goto(url, wait_until="domcontentloaded", timeout=60000)
|
|
266
|
-
except Exception as exc:
|
|
267
|
-
log.info(f" [browser] Page load warning: {exc}")
|
|
268
|
-
print(" 页面加载超时,但仍可手动登录。")
|
|
269
|
-
|
|
270
|
-
elapsed = 0
|
|
271
|
-
while elapsed < max_wait:
|
|
272
|
-
try:
|
|
273
|
-
page.wait_for_timeout(3000)
|
|
274
|
-
elapsed += 3
|
|
275
|
-
current_url = page.url
|
|
276
|
-
except Exception:
|
|
277
|
-
log.info(" [browser] Browser closed by user.")
|
|
278
|
-
if not keep_alive:
|
|
279
|
-
try:
|
|
280
|
-
browser.close()
|
|
281
|
-
except Exception:
|
|
282
|
-
pass
|
|
283
|
-
return (False, None, None, None) if keep_alive else False
|
|
284
|
-
|
|
285
|
-
# A custom detector is authoritative: when it says "not yet", the
|
|
286
|
-
# generic URL-shape fallback below must NOT confirm the login —
|
|
287
|
-
# it used to bless an unauthenticated redirect to the publisher
|
|
288
|
-
# (cookie count > 3) as success for CARSI/EZProxy (#29, #62).
|
|
289
|
-
if detect_login is not None:
|
|
290
|
-
if detect_login(context, page):
|
|
291
|
-
cookies = context.cookies()
|
|
292
|
-
_save_cookies_json(cookies, cookie_file)
|
|
293
|
-
netscape_path = cookie_file.with_suffix(".txt")
|
|
294
|
-
_save_cookies_netscape(cookies, netscape_path)
|
|
295
|
-
log.info(f" [browser] Login successful! Saved {len(cookies)} cookies.")
|
|
296
|
-
print(f" 登录成功!Cookie 已保存至 {cookie_file}")
|
|
297
|
-
if auto_import:
|
|
298
|
-
_import_to_browser(netscape_path, config)
|
|
299
|
-
if keep_alive:
|
|
300
|
-
return True, context, page
|
|
301
|
-
browser.close()
|
|
302
|
-
return True
|
|
303
|
-
continue
|
|
304
|
-
|
|
305
|
-
url_lower = current_url.lower()
|
|
306
|
-
if "login" not in url_lower and "cas" not in url_lower and "sso" not in url_lower:
|
|
307
|
-
cookies = context.cookies()
|
|
308
|
-
if len(cookies) > 3:
|
|
309
|
-
_save_cookies_json(cookies, cookie_file)
|
|
310
|
-
netscape_path = cookie_file.with_suffix(".txt")
|
|
311
|
-
_save_cookies_netscape(cookies, netscape_path)
|
|
312
|
-
log.info(f" [browser] Login successful! Saved {len(cookies)} cookies.")
|
|
313
|
-
print(f" 登录成功!Cookie 已保存至 {cookie_file}")
|
|
314
|
-
if auto_import:
|
|
315
|
-
_import_to_browser(netscape_path, config)
|
|
316
|
-
if keep_alive:
|
|
317
|
-
return True, context, page
|
|
318
|
-
browser.close()
|
|
319
|
-
return True
|
|
320
|
-
|
|
321
|
-
print(" 登录超时。")
|
|
322
|
-
if not keep_alive:
|
|
323
|
-
try:
|
|
324
|
-
browser.close()
|
|
325
|
-
except Exception:
|
|
326
|
-
pass
|
|
327
|
-
return (False, None, None, None) if keep_alive else False
|
|
328
|
-
|
|
329
|
-
except Exception as exc:
|
|
330
|
-
log.info(f" [browser] Login error: {exc}")
|
|
331
|
-
print(f" 登录出错: {exc}")
|
|
332
|
-
return (False, None, None, None) if keep_alive else False
|