papersearch 0.4.5 → 0.4.7
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 +64 -21
- package/carsi/paper_search_carsi/assets/papersearch-notifier +0 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/api.js +142 -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 +62 -20
- 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 +31 -10
- package/carsi/paper_search_carsi/engine/batch_institution.py +56 -14
- package/carsi/paper_search_carsi/engine/batch_login.py +264 -204
- package/carsi/paper_search_carsi/engine/batch_user.py +67 -2
- package/carsi/paper_search_carsi/engine/batch_waits.py +76 -30
- package/carsi/paper_search_carsi/engine/login_wait.py +125 -0
- package/carsi/paper_search_carsi/engine/page_activity.py +177 -0
- package/carsi/paper_search_carsi/engine/supplements.py +12 -1
- package/carsi/paper_search_carsi/entitlements.py +23 -3
- package/carsi/paper_search_carsi/progress_capsule.py +130 -18
- 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 +8 -6
- 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
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/* Only loaded in PaperSearch's owned Camoufox process, never in the user's browser.
|
|
2
|
+
* Camoufox's Juggler restores/focuses a native window for every automated click.
|
|
3
|
+
* Suppress that focus while retaining its tab selection and trusted input path.
|
|
4
|
+
* Explicit Page.bringToFront and native user input retain normal activation.
|
|
5
|
+
*/
|
|
6
|
+
var { ExtensionCommon } = ChromeUtils.importESModule("resource://gre/modules/ExtensionCommon.sys.mjs");
|
|
7
|
+
var papersearchBackground = class extends ExtensionCommon.ExtensionAPI {
|
|
8
|
+
onStartup() {
|
|
9
|
+
if (!Services.prefs.getBoolPref("papersearch.background.enabled", false)) return;
|
|
10
|
+
this.start().catch(async error => {
|
|
11
|
+
console.error("PaperSearch background helper:", error);
|
|
12
|
+
await IOUtils.writeJSON(PathUtils.join(PathUtils.profileDir, "papersearch-background.json"),
|
|
13
|
+
{ready: false, session: Services.prefs.getStringPref("papersearch.background.session", ""),
|
|
14
|
+
error: String(error).slice(0, 300)});
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
onShutdown() { this.restore?.(); }
|
|
18
|
+
async start() {
|
|
19
|
+
const {PageTarget, TargetRegistry} = ChromeUtils.importESModule("chrome://juggler/content/TargetRegistry.js");
|
|
20
|
+
const {PageHandler} = ChromeUtils.importESModule("chrome://juggler/content/protocol/PageHandler.js");
|
|
21
|
+
const activate = PageTarget.prototype.activateAndRun;
|
|
22
|
+
const bringToFront = PageHandler.prototype["Page.bringToFront"];
|
|
23
|
+
if (typeof activate !== "function" || typeof bringToFront !== "function") {
|
|
24
|
+
throw new Error("Unsupported Camoufox activation API");
|
|
25
|
+
}
|
|
26
|
+
const newPage = TargetRegistry.prototype._newPageInternal;
|
|
27
|
+
if (typeof newPage !== "function") throw new Error("Unsupported Camoufox page API");
|
|
28
|
+
const {Helper} = ChromeUtils.importESModule("chrome://juggler/content/Helper.js");
|
|
29
|
+
const helper = new Helper();
|
|
30
|
+
TargetRegistry.prototype._newPageInternal = async function({browserContextId}) {
|
|
31
|
+
const win = Services.wm.getMostRecentWindow("navigator:browser");
|
|
32
|
+
if (!win?.gBrowser) return await newPage.call(this, {browserContextId});
|
|
33
|
+
const browserContext = this.browserContextForId(browserContextId);
|
|
34
|
+
const tab = win.gBrowser.addTab("about:blank", {
|
|
35
|
+
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
|
|
36
|
+
userContextId: browserContext.userContextId,
|
|
37
|
+
skipAnimation: true,
|
|
38
|
+
});
|
|
39
|
+
let target = this._browserToTarget.get(tab.linkedBrowser);
|
|
40
|
+
while (!target) {
|
|
41
|
+
await helper.awaitEvent(this, TargetRegistry.Events.TargetCreated);
|
|
42
|
+
target = this._browserToTarget.get(tab.linkedBrowser);
|
|
43
|
+
}
|
|
44
|
+
await target.activateAndRun();
|
|
45
|
+
if (browserContext.crossProcessCookie.settings.timezoneId && await target.hasFailedToOverrideTimezone()) {
|
|
46
|
+
throw new Error("Failed to override timezone");
|
|
47
|
+
}
|
|
48
|
+
return target.id();
|
|
49
|
+
};
|
|
50
|
+
const pending = new WeakMap();
|
|
51
|
+
PageTarget.prototype.activateAndRun = async function(...args) {
|
|
52
|
+
const win = this._window;
|
|
53
|
+
let state = pending.get(win);
|
|
54
|
+
if (!state) {
|
|
55
|
+
state = {focus: win.focus, depth: 0};
|
|
56
|
+
pending.set(win, state);
|
|
57
|
+
win.focus = () => {};
|
|
58
|
+
}
|
|
59
|
+
state.depth++;
|
|
60
|
+
try { return await activate.apply(this, args); }
|
|
61
|
+
finally {
|
|
62
|
+
if (--state.depth === 0) {
|
|
63
|
+
win.focus = state.focus;
|
|
64
|
+
pending.delete(win);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
PageHandler.prototype["Page.bringToFront"] = async function(...args) {
|
|
69
|
+
const win = this._pageTarget._window;
|
|
70
|
+
if (win.windowState === win.STATE_MINIMIZED) win.restore();
|
|
71
|
+
(pending.get(win)?.focus || win.focus).call(win);
|
|
72
|
+
return await bringToFront.apply(this, args);
|
|
73
|
+
};
|
|
74
|
+
if (Services.prefs.getBoolPref("papersearch.background.bootstrap", false) &&
|
|
75
|
+
!Services.wm.getMostRecentWindow("navigator:browser")) {
|
|
76
|
+
const {AppConstants} = ChromeUtils.importESModule("resource://gre/modules/AppConstants.sys.mjs");
|
|
77
|
+
const uri = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
|
|
78
|
+
uri.data = "about:blank";
|
|
79
|
+
const win = Services.ww.openWindow(null, AppConstants.BROWSER_CHROME_URL, "_blank",
|
|
80
|
+
"chrome,dialog=no,all", uri);
|
|
81
|
+
const focus = win.focus;
|
|
82
|
+
win.focus = () => {};
|
|
83
|
+
const {ctypes} = ChromeUtils.importESModule("resource://gre/modules/ctypes.sys.mjs");
|
|
84
|
+
const user = ctypes.open("user32.dll");
|
|
85
|
+
const getStyle = user.declare("GetWindowLongPtrW", ctypes.winapi_abi, ctypes.intptr_t,
|
|
86
|
+
ctypes.voidptr_t, ctypes.int);
|
|
87
|
+
const setStyle = user.declare("SetWindowLongPtrW", ctypes.winapi_abi, ctypes.intptr_t,
|
|
88
|
+
ctypes.voidptr_t, ctypes.int, ctypes.intptr_t);
|
|
89
|
+
const setPosition = user.declare("SetWindowPos", ctypes.winapi_abi, ctypes.int,
|
|
90
|
+
ctypes.voidptr_t, ctypes.voidptr_t, ctypes.int, ctypes.int, ctypes.int, ctypes.int, ctypes.uint32_t);
|
|
91
|
+
const setAlpha = user.declare("SetLayeredWindowAttributes", ctypes.winapi_abi, ctypes.int,
|
|
92
|
+
ctypes.voidptr_t, ctypes.uint32_t, ctypes.unsigned_char, ctypes.uint32_t);
|
|
93
|
+
const getAlpha = user.declare("GetLayeredWindowAttributes", ctypes.winapi_abi, ctypes.int,
|
|
94
|
+
ctypes.voidptr_t, ctypes.uint32_t.ptr, ctypes.unsigned_char.ptr, ctypes.uint32_t.ptr);
|
|
95
|
+
const native = win.docShell.treeOwner.QueryInterface(Ci.nsIBaseWindow);
|
|
96
|
+
const hwnd = ctypes.voidptr_t(ctypes.UInt64(native.nativeHandle));
|
|
97
|
+
const style = Number(getStyle(hwnd, -20).toString());
|
|
98
|
+
const color = ctypes.uint32_t(), alpha = ctypes.unsigned_char(), alphaFlags = ctypes.uint32_t();
|
|
99
|
+
if ((style & 0x00080000) && !getAlpha(hwnd, color.address(), alpha.address(), alphaFlags.address())) {
|
|
100
|
+
user.close();
|
|
101
|
+
throw new Error("Cannot preserve browser window opacity");
|
|
102
|
+
}
|
|
103
|
+
// NOACTIVATE alone still lets Gecko's first ShowWindow cover another
|
|
104
|
+
// app. Keep only the initial, not-yet-painted window transparent until
|
|
105
|
+
// it can be placed behind existing windows, then restore normal styles.
|
|
106
|
+
setStyle(hwnd, -20, style | 0x08080000); // WS_EX_NOACTIVATE | WS_EX_LAYERED
|
|
107
|
+
if (!setAlpha(hwnd, 0, 0, 2)) {
|
|
108
|
+
setStyle(hwnd, -20, style);
|
|
109
|
+
user.close();
|
|
110
|
+
throw new Error("Cannot prepare the browser's background display");
|
|
111
|
+
}
|
|
112
|
+
let observer, timer;
|
|
113
|
+
try {
|
|
114
|
+
await new Promise((resolve, reject) => {
|
|
115
|
+
timer = win.setTimeout(() => reject(new Error("Browser window initialization timed out")), 10000);
|
|
116
|
+
observer = subject => {
|
|
117
|
+
if (subject !== win) return;
|
|
118
|
+
resolve();
|
|
119
|
+
};
|
|
120
|
+
Services.obs.addObserver(observer, "browser-delayed-startup-finished");
|
|
121
|
+
});
|
|
122
|
+
} finally {
|
|
123
|
+
if (observer) Services.obs.removeObserver(observer, "browser-delayed-startup-finished");
|
|
124
|
+
win.clearTimeout(timer);
|
|
125
|
+
const placed = setPosition(hwnd, ctypes.voidptr_t(1), 0, 0, 0, 0, 0x0013); // HWND_BOTTOM; NOSIZE|NOMOVE|NOACTIVATE
|
|
126
|
+
const opacityRestored = !(style & 0x00080000) || setAlpha(hwnd, color.value, alpha.value, alphaFlags.value);
|
|
127
|
+
setStyle(hwnd, -20, style);
|
|
128
|
+
user.close();
|
|
129
|
+
win.focus = focus;
|
|
130
|
+
if (!placed) throw new Error("Cannot place the browser behind existing windows");
|
|
131
|
+
if (!opacityRestored) throw new Error("Cannot restore the browser window opacity");
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
await IOUtils.writeJSON(PathUtils.join(PathUtils.profileDir, "papersearch-background.json"),
|
|
135
|
+
{ready: true, session: Services.prefs.getStringPref("papersearch.background.session", "")});
|
|
136
|
+
this.restore = () => {
|
|
137
|
+
TargetRegistry.prototype._newPageInternal = newPage;
|
|
138
|
+
PageTarget.prototype.activateAndRun = activate;
|
|
139
|
+
PageHandler.prototype["Page.bringToFront"] = bringToFront;
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"manifest_version": 2,
|
|
3
|
+
"name": "PaperSearch background browser",
|
|
4
|
+
"version": "1.0",
|
|
5
|
+
"browser_specific_settings": {
|
|
6
|
+
"gecko": {
|
|
7
|
+
"id": "background@papersearch.local"
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
"experiment_apis": {
|
|
11
|
+
"papersearchBackground": {
|
|
12
|
+
"schema": "schema.json",
|
|
13
|
+
"parent": {
|
|
14
|
+
"scopes": [
|
|
15
|
+
"addon_parent"
|
|
16
|
+
],
|
|
17
|
+
"events": [
|
|
18
|
+
"startup"
|
|
19
|
+
],
|
|
20
|
+
"script": "api.js"
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
[{"namespace": "papersearchBackground"}]
|
|
@@ -474,13 +474,20 @@ def _camoufox_options(headless: bool, proxy: Any, args: list[str] | None, humani
|
|
|
474
474
|
"focusmanager.testmode": True,
|
|
475
475
|
"dom.disable_window_flip": True,
|
|
476
476
|
"browser.tabs.loadDivertedInBackground": True,
|
|
477
|
+
"browser.link.open_newwindow": 3,
|
|
478
|
+
"browser.link.open_newwindow.restriction": 0,
|
|
477
479
|
**(opts.get("firefox_user_prefs") or {}),
|
|
480
|
+
"papersearch.background.enabled": not headless,
|
|
481
|
+
"papersearch.background.bootstrap": False,
|
|
478
482
|
}
|
|
479
483
|
if not headless and opts.get("ignore_default_args") is not True:
|
|
480
484
|
# Playwright adds -foreground to every headed Firefox launch.
|
|
481
485
|
opts["ignore_default_args"] = list(dict.fromkeys([
|
|
482
486
|
*(opts.get("ignore_default_args") or []), "-foreground",
|
|
483
487
|
]))
|
|
488
|
+
if not headless:
|
|
489
|
+
from .background import options as background_options
|
|
490
|
+
background_options(opts)
|
|
484
491
|
opts.update(headless=headless, humanize=humanize, proxy=proxy)
|
|
485
492
|
pinned = pinned_camoufox_dir()
|
|
486
493
|
if pinned is not None and "executable_path" not in opts:
|
|
@@ -556,6 +563,23 @@ def _launch_camoufox_persistent(user_data_dir: str, headless: bool, proxy: Any,
|
|
|
556
563
|
from playwright.sync_api import sync_playwright
|
|
557
564
|
|
|
558
565
|
opts = _camoufox_options(headless, proxy, args, humanize, kwargs)
|
|
566
|
+
if os.name == "nt" and not headless:
|
|
567
|
+
# Let the owned helper create the first window without activation.
|
|
568
|
+
from .background import ADDON_DIR, install_startup_helper
|
|
569
|
+
install_startup_helper(Path(user_data_dir))
|
|
570
|
+
opts["addons"] = [p for p in opts["addons"] if str(p) != str(ADDON_DIR)]
|
|
571
|
+
opts["ignore_default_args"] = [*(opts.get("ignore_default_args") or []), "about:blank"]
|
|
572
|
+
opts["args"] = [*(opts.get("args") or []), "-silent"]
|
|
573
|
+
opts["firefox_user_prefs"].update({
|
|
574
|
+
"papersearch.background.bootstrap": True,
|
|
575
|
+
"xpinstall.signatures.required": False,
|
|
576
|
+
"extensions.autoDisableScopes": 0,
|
|
577
|
+
"extensions.enabledScopes": 1,
|
|
578
|
+
"extensions.startupScanScopes": 1,
|
|
579
|
+
# Gecko's first-profile video self-test opens an offscreen dialog
|
|
580
|
+
# that still steals focus before any download window is created.
|
|
581
|
+
"media.sanity-test.disabled": True,
|
|
582
|
+
})
|
|
559
583
|
pw = sync_playwright().start()
|
|
560
584
|
try:
|
|
561
585
|
context = NewBrowser(pw, persistent_context=True, user_data_dir=user_data_dir, **opts)
|
|
@@ -629,11 +653,23 @@ def launch_persistent_context(
|
|
|
629
653
|
LAST_LAUNCH.update(holder=holder or "free", waited=round(time.monotonic() - waited_from, 1), released=released)
|
|
630
654
|
if proxy is None:
|
|
631
655
|
proxy = _proxy_from_config(config)
|
|
656
|
+
from uuid import uuid4
|
|
657
|
+
background_session = uuid4().hex
|
|
658
|
+
if not headless:
|
|
659
|
+
kwargs["firefox_user_prefs"] = {**(kwargs.get("firefox_user_prefs") or {}),
|
|
660
|
+
"papersearch.background.session": background_session}
|
|
632
661
|
context = _launch_camoufox_persistent(
|
|
633
662
|
str(profile), headless=headless, proxy=proxy, args=args, humanize=humanize, **kwargs
|
|
634
663
|
)
|
|
635
664
|
if not callable(getattr(context, "close", None)):
|
|
636
665
|
return context
|
|
666
|
+
if not headless:
|
|
667
|
+
from .background import ready as background_ready
|
|
668
|
+
try:
|
|
669
|
+
background_ready(profile, background_session)
|
|
670
|
+
except Exception:
|
|
671
|
+
context.close()
|
|
672
|
+
raise
|
|
637
673
|
restored = _restore_session_cookies(context, profile)
|
|
638
674
|
if restored:
|
|
639
675
|
logger.info("browser_backend: restored %d session cookie(s) from the previous run", restored)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""The owned Camoufox's bundled background helper; no native input or global hooks.
|
|
2
|
+
|
|
3
|
+
The helper is an internal Firefox experiment because window activation belongs
|
|
4
|
+
in browser chrome, outside web pages. It has no network/content permissions and
|
|
5
|
+
is not installed in a user's normal browser. Camoufox's version is pinned.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import hashlib
|
|
11
|
+
import io
|
|
12
|
+
import time
|
|
13
|
+
import zipfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
ADDON_ID = "background@papersearch.local"
|
|
18
|
+
ADDON_DIR = Path(__file__).resolve().parents[1] / "assets" / "quiet-browser"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def install_startup_helper(profile: Path) -> None:
|
|
22
|
+
"""Load before Windows creates its first window, inside the owned profile only."""
|
|
23
|
+
files = {p.name: p.read_bytes() for p in sorted(ADDON_DIR.iterdir()) if p.is_file()}
|
|
24
|
+
version = int.from_bytes(hashlib.sha256(b"".join(files.values())).digest()[:3], "big")
|
|
25
|
+
manifest = json.loads(files["manifest.json"])
|
|
26
|
+
manifest["version"] = f"1.0.{version}"
|
|
27
|
+
files["manifest.json"] = json.dumps(manifest).encode()
|
|
28
|
+
data = io.BytesIO()
|
|
29
|
+
with zipfile.ZipFile(data, "w", zipfile.ZIP_DEFLATED) as archive:
|
|
30
|
+
for name, content in files.items():
|
|
31
|
+
archive.writestr(zipfile.ZipInfo(name), content)
|
|
32
|
+
target = profile / "extensions" / (ADDON_ID + ".xpi")
|
|
33
|
+
content = data.getvalue()
|
|
34
|
+
if target.is_file() and target.read_bytes() == content:
|
|
35
|
+
return
|
|
36
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
temporary = target.with_suffix(".tmp")
|
|
38
|
+
temporary.write_bytes(content)
|
|
39
|
+
temporary.replace(target)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def options(opts: dict[str, Any]) -> None:
|
|
43
|
+
"""Configure only this launch; the shared installed browser is never patched."""
|
|
44
|
+
addons = list(opts.get("addons") or [])
|
|
45
|
+
if str(ADDON_DIR) not in addons:
|
|
46
|
+
addons.append(str(ADDON_DIR))
|
|
47
|
+
opts["addons"] = addons
|
|
48
|
+
prefs = opts["firefox_user_prefs"]
|
|
49
|
+
prefs.update({"extensions.experiments.enabled": True,
|
|
50
|
+
"layout.throttled_frame_rate": 60})
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def ready(profile: Path, session: str) -> None:
|
|
54
|
+
"""Verify before visiting any site; never claim quiet mode if the helper failed."""
|
|
55
|
+
path = profile / "papersearch-background.json"
|
|
56
|
+
deadline = time.monotonic() + 10
|
|
57
|
+
while time.monotonic() < deadline:
|
|
58
|
+
try:
|
|
59
|
+
if path.stat().st_size <= 4096:
|
|
60
|
+
result = json.loads(path.read_text(encoding="utf-8"))
|
|
61
|
+
if isinstance(result, dict) and result.get("session") == session:
|
|
62
|
+
if result.get("ready") is True:
|
|
63
|
+
return
|
|
64
|
+
raise RuntimeError("Camoufox background helper initialization failed")
|
|
65
|
+
except (OSError, ValueError):
|
|
66
|
+
pass # not written yet, or the atomic write is still being replaced
|
|
67
|
+
time.sleep(.05)
|
|
68
|
+
raise RuntimeError("Camoufox background helper did not initialize within 10 seconds")
|
|
@@ -64,6 +64,41 @@ def is_turnstile_frame(url: str) -> bool:
|
|
|
64
64
|
and "/turnstile/" in parsed.path)
|
|
65
65
|
|
|
66
66
|
|
|
67
|
+
def is_image_verification(page: Any) -> bool:
|
|
68
|
+
"""Image puzzles expose controls but may have no readable instructions."""
|
|
69
|
+
return page.evaluate("""() => document.title.trim().toLowerCase() === 'human verification'
|
|
70
|
+
&& !document.querySelector('meta[name="citation_doi"]')
|
|
71
|
+
&& [...document.querySelectorAll('button, [role="button"], canvas, iframe')].some(el =>
|
|
72
|
+
el.getClientRects().length > 0)""") is True
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def needs_manual_verification(page: Any) -> bool:
|
|
76
|
+
"""A visible reCAPTCHA on an already recognised verification page.
|
|
77
|
+
|
|
78
|
+
Reading a checked box or a response token cannot prove that the enclosing
|
|
79
|
+
page's confirmation was submitted. Leave both actions to the user.
|
|
80
|
+
"""
|
|
81
|
+
from playwright.sync_api import Error
|
|
82
|
+
|
|
83
|
+
if is_image_verification(page):
|
|
84
|
+
return True # image/puzzle tasks are always left to the user
|
|
85
|
+
for frame in page.frames:
|
|
86
|
+
parsed = urlsplit(str(frame.url or ""))
|
|
87
|
+
if (parsed.scheme != "https" or parsed.hostname not in {
|
|
88
|
+
"www.google.com", "www.recaptcha.net", "recaptcha.net"}
|
|
89
|
+
or not parsed.path.startswith(("/recaptcha/api2/", "/recaptcha/enterprise/"))):
|
|
90
|
+
continue
|
|
91
|
+
try:
|
|
92
|
+
if frame.frame_element().is_visible():
|
|
93
|
+
return True
|
|
94
|
+
except Error as exc:
|
|
95
|
+
if not any(text in str(exc).lower() for text in (
|
|
96
|
+
"frame was detached", "frame has been detached", "element is not attached",
|
|
97
|
+
"execution context was destroyed")):
|
|
98
|
+
raise
|
|
99
|
+
return False
|
|
100
|
+
|
|
101
|
+
|
|
67
102
|
def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]) -> Literal[
|
|
68
103
|
"absent", "clicked", "unavailable"
|
|
69
104
|
]:
|
|
@@ -49,11 +49,21 @@ def is_challenge_path(url: str) -> bool:
|
|
|
49
49
|
return "/crawlprevention/" in path or path == "/captcha" or path.startswith("/captcha/")
|
|
50
50
|
|
|
51
51
|
|
|
52
|
+
def continues_manual_challenge(title: str) -> bool:
|
|
53
|
+
"""An already recognised image challenge keeps its title between puzzle steps."""
|
|
54
|
+
return str(title or "").strip().lower() == "human verification"
|
|
55
|
+
|
|
56
|
+
|
|
52
57
|
def has_challenge_text(title: str, text: str) -> bool:
|
|
53
58
|
"""Recognise verification wording after explicit access blocks are excluded."""
|
|
54
59
|
haystack = f"{title} {text}".lower()
|
|
55
60
|
if str(title or "").strip().lower() == "human verification":
|
|
56
61
|
body = " ".join(str(text or "").lower().split())
|
|
62
|
+
# Image-only verification screens can expose no body text until the
|
|
63
|
+
# user presses Begin. Keep the exact interstitial title requirement:
|
|
64
|
+
# an article discussing human verification is not a challenge.
|
|
65
|
+
if body in {"", "begin", "begin english"}:
|
|
66
|
+
return True
|
|
57
67
|
if "complete the security check" in body and "you are not a bot" in body:
|
|
58
68
|
return True
|
|
59
69
|
return (any(marker in haystack for marker in _TEXT_MARKERS)
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""An explicit capsule click brings its download browser to the foreground.
|
|
2
|
+
|
|
3
|
+
No browser is launched here. Native activation is limited to the connected
|
|
4
|
+
ego profile's owner or descendants of this page's Playwright driver.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ctypes
|
|
9
|
+
import os
|
|
10
|
+
import subprocess
|
|
11
|
+
import threading
|
|
12
|
+
from concurrent.futures import Future
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
def _process_parents() -> dict[int, int]:
|
|
16
|
+
if os.name != "nt":
|
|
17
|
+
result = subprocess.run(["ps", "-axo", "pid=,ppid="], capture_output=True, text=True,
|
|
18
|
+
check=True, timeout=2)
|
|
19
|
+
return {int(parts[0]): int(parts[1]) for line in result.stdout.splitlines()
|
|
20
|
+
if len(parts := line.split()) == 2}
|
|
21
|
+
from ctypes import wintypes
|
|
22
|
+
|
|
23
|
+
class ProcessEntry(ctypes.Structure):
|
|
24
|
+
_fields_ = [("size", wintypes.DWORD), ("usage", wintypes.DWORD), ("pid", wintypes.DWORD),
|
|
25
|
+
("heap", ctypes.c_size_t), ("module", wintypes.DWORD), ("threads", wintypes.DWORD),
|
|
26
|
+
("parent", wintypes.DWORD), ("priority", wintypes.LONG), ("flags", wintypes.DWORD),
|
|
27
|
+
("exe", wintypes.WCHAR * 260)]
|
|
28
|
+
|
|
29
|
+
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
30
|
+
kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
|
|
31
|
+
kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
|
|
32
|
+
for name in ("Process32FirstW", "Process32NextW"):
|
|
33
|
+
fn = getattr(kernel, name)
|
|
34
|
+
fn.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]
|
|
35
|
+
fn.restype = wintypes.BOOL
|
|
36
|
+
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
|
|
37
|
+
snapshot = kernel.CreateToolhelp32Snapshot(2, 0)
|
|
38
|
+
if snapshot == ctypes.c_void_p(-1).value:
|
|
39
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
40
|
+
try:
|
|
41
|
+
entry = ProcessEntry(size=ctypes.sizeof(ProcessEntry))
|
|
42
|
+
more = kernel.Process32FirstW(snapshot, ctypes.byref(entry))
|
|
43
|
+
parents = {}
|
|
44
|
+
while more and len(parents) < 65536:
|
|
45
|
+
parents[int(entry.pid)] = int(entry.parent)
|
|
46
|
+
more = kernel.Process32NextW(snapshot, ctypes.byref(entry))
|
|
47
|
+
return parents
|
|
48
|
+
finally:
|
|
49
|
+
kernel.CloseHandle(snapshot)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _browser_pids(page: Any, config: dict) -> list[int]:
|
|
53
|
+
from .backend import BACKEND_EGO, ego_user_data_dir, resolve_backend
|
|
54
|
+
from .profiles import _profile_owner_pid
|
|
55
|
+
|
|
56
|
+
if resolve_backend(config) == BACKEND_EGO:
|
|
57
|
+
pid = _profile_owner_pid(str(ego_user_data_dir(config)))
|
|
58
|
+
return [pid] if pid else []
|
|
59
|
+
# Playwright has no public browser PID. Its pipe transport is the driver
|
|
60
|
+
# that launched this exact browser, including a persistent context.
|
|
61
|
+
driver = page.context._impl_obj._connection._transport._proc.pid
|
|
62
|
+
if not isinstance(driver, int) or isinstance(driver, bool) or driver <= 1:
|
|
63
|
+
raise RuntimeError("the download browser driver has no valid owner PID")
|
|
64
|
+
parents = _process_parents()
|
|
65
|
+
frontier, found = {int(driver)}, []
|
|
66
|
+
while frontier:
|
|
67
|
+
children = {pid for pid, parent in parents.items() if parent in frontier and pid not in found}
|
|
68
|
+
found.extend(sorted(children))
|
|
69
|
+
frontier = children
|
|
70
|
+
return found
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _activate_windows(pids: list[int], title: str = "") -> bool:
|
|
74
|
+
from ctypes import wintypes
|
|
75
|
+
|
|
76
|
+
user = ctypes.WinDLL("user32", use_last_error=True)
|
|
77
|
+
callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
|
78
|
+
user.EnumWindows.argtypes = [callback_type, wintypes.LPARAM]
|
|
79
|
+
user.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
|
|
80
|
+
user.IsWindowVisible.argtypes = [wintypes.HWND]
|
|
81
|
+
user.IsIconic.argtypes = [wintypes.HWND]
|
|
82
|
+
user.GetWindow.argtypes = [wintypes.HWND, wintypes.UINT]
|
|
83
|
+
user.GetWindow.restype = wintypes.HWND
|
|
84
|
+
user.ShowWindow.argtypes = [wintypes.HWND, ctypes.c_int]
|
|
85
|
+
user.SetForegroundWindow.argtypes = [wintypes.HWND]
|
|
86
|
+
user.GetForegroundWindow.restype = wintypes.HWND
|
|
87
|
+
user.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
|
|
88
|
+
found = []
|
|
89
|
+
|
|
90
|
+
@callback_type
|
|
91
|
+
def visit(hwnd, _):
|
|
92
|
+
pid = wintypes.DWORD()
|
|
93
|
+
user.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
|
|
94
|
+
if pid.value in pids and user.IsWindowVisible(hwnd) and not user.GetWindow(hwnd, 4):
|
|
95
|
+
found.append(hwnd)
|
|
96
|
+
return True
|
|
97
|
+
|
|
98
|
+
user.EnumWindows(visit, 0)
|
|
99
|
+
if not found:
|
|
100
|
+
return False
|
|
101
|
+
matches = []
|
|
102
|
+
for hwnd in found:
|
|
103
|
+
text = ctypes.create_unicode_buffer(1024)
|
|
104
|
+
user.GetWindowTextW(hwnd, text, len(text))
|
|
105
|
+
if title and text.value.casefold().startswith(title.casefold()):
|
|
106
|
+
matches.append(hwnd)
|
|
107
|
+
active = user.GetForegroundWindow()
|
|
108
|
+
candidates = matches or found
|
|
109
|
+
hwnd = active if active in candidates else candidates[0]
|
|
110
|
+
if user.IsIconic(hwnd):
|
|
111
|
+
user.ShowWindow(hwnd, 9) # SW_RESTORE, only this browser's minimized window
|
|
112
|
+
return bool(user.SetForegroundWindow(hwnd))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def mac_browser_pid(page: Any, config: dict) -> int:
|
|
116
|
+
"""The owned browser application, never one of its nonactivatable helpers."""
|
|
117
|
+
import AppKit
|
|
118
|
+
|
|
119
|
+
for pid in _browser_pids(page, config):
|
|
120
|
+
app = AppKit.NSRunningApplication.runningApplicationWithProcessIdentifier_(pid)
|
|
121
|
+
if (app is not None and app.bundleURL() is not None
|
|
122
|
+
and app.activationPolicy() == AppKit.NSApplicationActivationPolicyRegular):
|
|
123
|
+
return pid
|
|
124
|
+
return 0
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def activate_mac(pid: int) -> bool:
|
|
128
|
+
"""Called by the clicked capsule, whose Cocoa loop owns the activation handoff.
|
|
129
|
+
|
|
130
|
+
macOS 14+ requires cooperative activation. The CLI's worker has no Cocoa
|
|
131
|
+
main loop and must not dispatch UI work to its own main thread.
|
|
132
|
+
"""
|
|
133
|
+
import AppKit
|
|
134
|
+
|
|
135
|
+
def activate() -> bool:
|
|
136
|
+
app = AppKit.NSRunningApplication.runningApplicationWithProcessIdentifier_(pid)
|
|
137
|
+
if app is None or app.activationPolicy() != AppKit.NSApplicationActivationPolicyRegular:
|
|
138
|
+
return False
|
|
139
|
+
current = AppKit.NSRunningApplication.currentApplication()
|
|
140
|
+
native = AppKit.NSApplication.sharedApplication()
|
|
141
|
+
app.unhide()
|
|
142
|
+
if hasattr(native, "yieldActivationToApplication_"):
|
|
143
|
+
native.yieldActivationToApplication_(app)
|
|
144
|
+
activated = bool(app.activateFromApplication_options_(current, AppKit.NSApplicationActivateAllWindows))
|
|
145
|
+
else:
|
|
146
|
+
activated = bool(app.activateWithOptions_(AppKit.NSApplicationActivateIgnoringOtherApps
|
|
147
|
+
| AppKit.NSApplicationActivateAllWindows))
|
|
148
|
+
# Activation alone leaves miniaturized Firefox windows in the Dock.
|
|
149
|
+
# The same reopen event as a Dock click restores them. Address the
|
|
150
|
+
# existing PID, so a stale request can never launch another browser.
|
|
151
|
+
return activated and _reopen_mac(pid)
|
|
152
|
+
|
|
153
|
+
if threading.current_thread() is threading.main_thread():
|
|
154
|
+
return activate()
|
|
155
|
+
from PyObjCTools import AppHelper
|
|
156
|
+
|
|
157
|
+
answer: Future[bool] = Future()
|
|
158
|
+
|
|
159
|
+
def on_main():
|
|
160
|
+
if not answer.set_running_or_notify_cancel():
|
|
161
|
+
return
|
|
162
|
+
try:
|
|
163
|
+
answer.set_result(activate())
|
|
164
|
+
except Exception as exc:
|
|
165
|
+
answer.set_exception(exc)
|
|
166
|
+
|
|
167
|
+
AppHelper.callAfter(on_main)
|
|
168
|
+
try:
|
|
169
|
+
return answer.result(timeout=2)
|
|
170
|
+
except TimeoutError as exc:
|
|
171
|
+
answer.cancel()
|
|
172
|
+
raise TimeoutError("browser activation did not reach the capsule's native thread") from exc
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _reopen_mac(pid: int) -> bool:
|
|
176
|
+
import Foundation
|
|
177
|
+
|
|
178
|
+
descriptor = Foundation.NSAppleEventDescriptor
|
|
179
|
+
event = descriptor.appleEventWithEventClass_eventID_targetDescriptor_returnID_transactionID_(
|
|
180
|
+
int.from_bytes(b"aevt", "big"), int.from_bytes(b"rapp", "big"),
|
|
181
|
+
descriptor.descriptorWithProcessIdentifier_(pid), -1, 0)
|
|
182
|
+
_, error = event.sendEventWithOptions_timeout_error_(
|
|
183
|
+
Foundation.NSAppleEventSendWaitForReply | Foundation.NSAppleEventSendNeverInteract, 2, None)
|
|
184
|
+
if error is not None:
|
|
185
|
+
raise RuntimeError("the owned browser did not accept its reopen event")
|
|
186
|
+
return True
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def show(page: Any, config: dict) -> None:
|
|
190
|
+
page.bring_to_front() # select this task's tab; macOS activation is done by the capsule
|
|
191
|
+
if os.name != "nt":
|
|
192
|
+
return
|
|
193
|
+
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
title = page.locator('head > title').first.text_content(timeout=1000) or ""
|
|
197
|
+
except PlaywrightTimeoutError:
|
|
198
|
+
title = "" # a title is optional; native activation still selects the task browser
|
|
199
|
+
if _activate_windows(_browser_pids(page, config), title.strip()):
|
|
200
|
+
return
|
|
201
|
+
raise RuntimeError("the download browser window could not be activated")
|
|
@@ -172,7 +172,9 @@ class PersistentBrowser:
|
|
|
172
172
|
|
|
173
173
|
# Module-level singleton
|
|
174
174
|
_browser = PersistentBrowser()
|
|
175
|
-
|
|
175
|
+
# Logging/capture streams may already be closed during interpreter shutdown.
|
|
176
|
+
# Explicit close still logs; the exit hook only releases owned browser resources.
|
|
177
|
+
atexit.register(_browser._cleanup)
|
|
176
178
|
|
|
177
179
|
|
|
178
180
|
def get_browser(config: dict[str, Any] | None = None):
|
|
@@ -154,7 +154,9 @@ class BrowserPreview:
|
|
|
154
154
|
row = {'page_id': page_id, 'host': host, 'kind': kind, 'screenshot_status': 'unavailable'}
|
|
155
155
|
captured_at = time.time()
|
|
156
156
|
try:
|
|
157
|
-
|
|
157
|
+
# This is only a preview label, not an access decision. The
|
|
158
|
+
# :visible selector forces layout of a potentially long article.
|
|
159
|
+
if page.locator('input[type="password"]').count():
|
|
158
160
|
row['kind'] = 'login'
|
|
159
161
|
# The user requested the actual rendered page without preview
|
|
160
162
|
# masks. Field values are never extracted into JSON or logs.
|
|
@@ -101,12 +101,14 @@ DEFAULT_CONFIG: dict[str, Any] = {
|
|
|
101
101
|
# 任务启动时自动弹出悬浮进度条(独立进程,已有实例则不重复弹出)。
|
|
102
102
|
"progress_bar_auto": True,
|
|
103
103
|
# 需要登录学校或完成验证时,除了进度胶囊变色,再发一条系统通知;进度窗口的设置里可以关。
|
|
104
|
-
"progress_notify":
|
|
104
|
+
"progress_notify": False,
|
|
105
105
|
# 每篇文章在学校登录页等待用户输入的总时长上限,秒;从第一次等待算起。
|
|
106
106
|
"browser_login_timeout": 180,
|
|
107
107
|
# 不在学校登录页时(出版社页面、选机构页、人机验证、取 PDF 时等待处理)最多等多久,秒;
|
|
108
108
|
# 连续超过就结束这一篇。进度窗口里可以改。
|
|
109
109
|
"browser_page_wait_timeout": 60,
|
|
110
|
+
# 页面没有实际进展多久后提醒人工查看;仅控制提醒,不延长页面等待上限。
|
|
111
|
+
"browser_stall_notify_after": 30,
|
|
110
112
|
# 每个出版社每小时最多打开的文章数,防止学校因下载过多被出版社暂停访问;0 = 不限。
|
|
111
113
|
"publisher_hourly_limit": 100,
|
|
112
114
|
# Turnstile 交互门(如 sci-hub.vg):无头会话下无法点击,默认跳过并冷却。
|
|
@@ -163,6 +165,7 @@ def save_config(config: dict[str, Any]) -> None:
|
|
|
163
165
|
|
|
164
166
|
_VALIDATION_RULES: dict[str, tuple[type, Any, Any]] = {
|
|
165
167
|
# key: (type, min_value, max_value)
|
|
168
|
+
"browser_stall_notify_after": (int, 1, 600),
|
|
166
169
|
"connect_timeout": (int, 1, 60),
|
|
167
170
|
"read_timeout": (int, 1, 120),
|
|
168
171
|
"request_delay_min": (float, 0.0, 30.0),
|