tabwright 0.1.0__py3-none-any.whl
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.
- tabwright/__init__.py +3 -0
- tabwright/adapters/__init__.py +20 -0
- tabwright/adapters/chromium.py +133 -0
- tabwright/adapters/firefox.py +319 -0
- tabwright/adapters/snss.py +261 -0
- tabwright/cli.py +461 -0
- tabwright/extension/background.js +161 -0
- tabwright/extension/manifest.json +25 -0
- tabwright/gui.py +672 -0
- tabwright/library.py +52 -0
- tabwright/live.py +126 -0
- tabwright/mcp_server.py +107 -0
- tabwright/model.py +183 -0
- tabwright/native_host.py +143 -0
- tabwright/policy.py +36 -0
- tabwright/tools.py +316 -0
- tabwright-0.1.0.dist-info/METADATA +275 -0
- tabwright-0.1.0.dist-info/RECORD +21 -0
- tabwright-0.1.0.dist-info/WHEEL +4 -0
- tabwright-0.1.0.dist-info/entry_points.txt +2 -0
- tabwright-0.1.0.dist-info/licenses/LICENSE +21 -0
tabwright/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Browser adapters. ``get(name)`` returns the adapter module for a browser name.
|
|
2
|
+
|
|
3
|
+
Every adapter exposes ``read(path, browser)``, ``read_profile(browser, profile, data_dir)``,
|
|
4
|
+
``write_file(session, path)``, ``apply(session, browser, profile, data_dir) -> Path`` (offline
|
|
5
|
+
write; browser stopped),
|
|
6
|
+
``pids``, ``stop`` and ``start``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from tabwright.adapters import chromium, firefox
|
|
12
|
+
|
|
13
|
+
BROWSERS = {name: chromium for name in chromium.BROWSERS} | {name: firefox for name in firefox.BROWSERS}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def get(name: str):
|
|
17
|
+
try:
|
|
18
|
+
return BROWSERS[name]
|
|
19
|
+
except KeyError:
|
|
20
|
+
raise SystemExit(f"unknown browser {name!r}; known: {', '.join(sorted(BROWSERS))}") from None
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Chromium-family adapter: profile discovery, session read/write, process control.
|
|
2
|
+
|
|
3
|
+
Write path is offline: the browser must be stopped. ``apply`` writes a new
|
|
4
|
+
``Session_*`` file and marks the profile as crashed so the browser offers to
|
|
5
|
+
restore it on next launch (``exit_type`` lives in ``Preferences``, which is
|
|
6
|
+
not MAC-protected).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import signal
|
|
14
|
+
import subprocess
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from tabwright.adapters import snss
|
|
19
|
+
from tabwright.model import Session
|
|
20
|
+
|
|
21
|
+
# name -> (user data dir under ~/.config, binary names to try)
|
|
22
|
+
BROWSERS = {
|
|
23
|
+
"brave": ("BraveSoftware/Brave-Browser", ["brave-browser", "brave-browser-stable", "brave"]),
|
|
24
|
+
"chrome": ("google-chrome", ["google-chrome", "google-chrome-stable"]),
|
|
25
|
+
"chromium": ("chromium", ["chromium", "chromium-browser"]),
|
|
26
|
+
"edge": ("microsoft-edge", ["microsoft-edge", "microsoft-edge-stable"]),
|
|
27
|
+
"vivaldi": ("vivaldi", ["vivaldi", "vivaldi-stable"]),
|
|
28
|
+
}
|
|
29
|
+
WINDOWS_EPOCH_OFFSET = 11644473600
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def user_data_dir(browser: str) -> Path:
|
|
33
|
+
return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / BROWSERS[browser][0]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def sessions_dir(browser: str, profile: str = "Default", data_dir: Path | None = None) -> Path:
|
|
37
|
+
return (data_dir or user_data_dir(browser)) / profile / "Sessions"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def newest_session_file(sdir: Path) -> Path:
|
|
41
|
+
files = sorted(sdir.glob("Session_*"), key=lambda p: int(p.name.split("_")[1]))
|
|
42
|
+
if not files:
|
|
43
|
+
raise SystemExit(f"no Session_* files in {sdir}")
|
|
44
|
+
return files[-1]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def read(path: Path, browser: str = "") -> Session:
|
|
48
|
+
_, cmds = snss.read_commands(str(path))
|
|
49
|
+
return snss.parse(cmds, browser=browser)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def chromium_timestamp() -> int:
|
|
53
|
+
return int((time.time() + WINDOWS_EPOCH_OFFSET) * 1_000_000)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def write(session: Session, sdir: Path) -> Path:
|
|
57
|
+
"""Write ``session`` as a new, newest Session_* file in ``sdir``; returns its path."""
|
|
58
|
+
sdir.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
out = sdir / f"Session_{chromium_timestamp()}"
|
|
60
|
+
snss.write_commands(str(out), snss.build(session))
|
|
61
|
+
return out
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def write_file(session: Session, path: Path) -> None:
|
|
65
|
+
snss.write_commands(str(path), snss.build(session))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def read_profile(browser: str, profile: str = "Default", data_dir: Path | None = None) -> Session:
|
|
69
|
+
return read(newest_session_file(sessions_dir(browser, profile, data_dir)), browser=browser)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def apply(session: Session, browser: str, profile: str = "Default", data_dir: Path | None = None) -> Path:
|
|
73
|
+
"""Offline write: new Session_* file plus the crashed flag so the browser offers to restore."""
|
|
74
|
+
sdir = sessions_dir(browser, profile, data_dir)
|
|
75
|
+
out = write(session, sdir)
|
|
76
|
+
mark_crashed(sdir.parent)
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def mark_crashed(profile_dir: Path) -> None:
|
|
81
|
+
pref = profile_dir / "Preferences"
|
|
82
|
+
data = json.loads(pref.read_text()) if pref.exists() else {}
|
|
83
|
+
data.setdefault("profile", {})["exit_type"] = "Crashed"
|
|
84
|
+
pref.write_text(json.dumps(data))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def pids(browser: str, data_dir: Path | None = None) -> list[int]:
|
|
88
|
+
"""Main-process pids for ``browser`` using ``data_dir`` (the default dir when None)."""
|
|
89
|
+
bins = BROWSERS[browser][1]
|
|
90
|
+
out = []
|
|
91
|
+
for p in Path("/proc").iterdir():
|
|
92
|
+
if not p.name.isdigit():
|
|
93
|
+
continue
|
|
94
|
+
try:
|
|
95
|
+
raw = (p / "cmdline").read_bytes().rstrip(b"\0")
|
|
96
|
+
except OSError:
|
|
97
|
+
continue
|
|
98
|
+
# Chromium rewrites its cmdline as one space-joined string, so split on spaces when no NULs remain
|
|
99
|
+
argv = raw.split(b"\0") if b"\0" in raw else raw.split(b" ")
|
|
100
|
+
if not argv or not any(
|
|
101
|
+
os.path.basename(argv[0].decode(errors="replace")) == b_ for b_ in bins + ["brave"]
|
|
102
|
+
):
|
|
103
|
+
continue
|
|
104
|
+
if any(a.startswith(b"--type=") for a in argv):
|
|
105
|
+
continue # child process
|
|
106
|
+
udd = next((a.split(b"=", 1)[1].decode() for a in argv if a.startswith(b"--user-data-dir=")), None)
|
|
107
|
+
if (data_dir is None and udd is None) or (data_dir is not None and udd == str(data_dir)):
|
|
108
|
+
out.append(int(p.name))
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def stop(browser: str, data_dir: Path | None = None, force: bool = False, timeout: float = 10) -> list[int]:
|
|
113
|
+
"""Stop the browser. Graceful SIGTERM rewrites the session file and clears the crash
|
|
114
|
+
flag; ``force`` sends SIGKILL immediately, leaving session files exactly as on disk."""
|
|
115
|
+
ps = pids(browser, data_dir)
|
|
116
|
+
for pid in ps:
|
|
117
|
+
os.kill(pid, signal.SIGKILL if force else signal.SIGTERM)
|
|
118
|
+
deadline = time.time() + timeout
|
|
119
|
+
while time.time() < deadline and pids(browser, data_dir):
|
|
120
|
+
time.sleep(0.2)
|
|
121
|
+
for pid in pids(browser, data_dir):
|
|
122
|
+
os.kill(pid, signal.SIGKILL)
|
|
123
|
+
return ps
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def start(browser: str, data_dir: Path | None = None, args: list[str] = ()) -> int:
|
|
127
|
+
for b in BROWSERS[browser][1]:
|
|
128
|
+
if any((Path(d) / b).exists() for d in os.environ.get("PATH", "").split(os.pathsep)):
|
|
129
|
+
cmd = [b, *([f"--user-data-dir={data_dir}"] if data_dir else []), *args]
|
|
130
|
+
return subprocess.Popen(
|
|
131
|
+
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True
|
|
132
|
+
).pid
|
|
133
|
+
raise SystemExit(f"no binary found for {browser}: tried {BROWSERS[browser][1]}")
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Firefox-family adapter (Firefox, Tor Browser): sessionstore read/write, process control.
|
|
2
|
+
|
|
3
|
+
Session files are mozlz4 (``mozLz40\\0`` + u32 size + one LZ4 block) around JSON.
|
|
4
|
+
Clean exit leaves ``sessionstore.jsonlz4`` in the profile; while running (or after a
|
|
5
|
+
crash) ``sessionstore-backups/recovery.jsonlz4`` is newer. Apply writes both, with
|
|
6
|
+
``sessionCheckpoints.json`` left in the crashed shape so Firefox restores on launch
|
|
7
|
+
regardless of its startup-page setting. Tor Browser keeps no session on disk.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import configparser
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import signal
|
|
16
|
+
import subprocess
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from tabwright.model import Group, Session, Tab, Window
|
|
21
|
+
|
|
22
|
+
HOME = Path.home()
|
|
23
|
+
TOR_ROOT = HOME / ".local/share/torbrowser/tbb/x86_64/tor-browser/Browser"
|
|
24
|
+
# name -> (profile roots holding profiles.ini, binaries)
|
|
25
|
+
BROWSERS = {
|
|
26
|
+
"firefox": (
|
|
27
|
+
[HOME / ".mozilla/firefox", HOME / "snap/firefox/common/.mozilla/firefox"],
|
|
28
|
+
["firefox", "firefox-esr", "firefox-bin"],
|
|
29
|
+
),
|
|
30
|
+
"tor": (
|
|
31
|
+
[TOR_ROOT / "TorBrowser/Data/Browser"],
|
|
32
|
+
[str(TOR_ROOT / "start-tor-browser"), "torbrowser-launcher"],
|
|
33
|
+
),
|
|
34
|
+
}
|
|
35
|
+
COLORS = {"gray": "grey"} # Firefox name -> model name; everything else matches
|
|
36
|
+
MAGIC = b"mozLz40\0"
|
|
37
|
+
CRASHED_CHECKPOINTS = {
|
|
38
|
+
"profile-after-change": True,
|
|
39
|
+
"final-ui-startup": True,
|
|
40
|
+
"sessionstore-windows-restored": True,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# ----------------------------------------------------------------- mozlz4
|
|
45
|
+
def lz4_decompress(src: bytes) -> bytes:
|
|
46
|
+
out = bytearray()
|
|
47
|
+
i, n = 0, len(src)
|
|
48
|
+
while i < n:
|
|
49
|
+
token = src[i]
|
|
50
|
+
i += 1
|
|
51
|
+
lit = token >> 4
|
|
52
|
+
if lit == 15:
|
|
53
|
+
while True:
|
|
54
|
+
x = src[i]
|
|
55
|
+
i += 1
|
|
56
|
+
lit += x
|
|
57
|
+
if x != 255:
|
|
58
|
+
break
|
|
59
|
+
out += src[i : i + lit]
|
|
60
|
+
i += lit
|
|
61
|
+
if i >= n:
|
|
62
|
+
break
|
|
63
|
+
off = src[i] | src[i + 1] << 8
|
|
64
|
+
i += 2
|
|
65
|
+
ml = token & 15
|
|
66
|
+
if ml == 15:
|
|
67
|
+
while True:
|
|
68
|
+
x = src[i]
|
|
69
|
+
i += 1
|
|
70
|
+
ml += x
|
|
71
|
+
if x != 255:
|
|
72
|
+
break
|
|
73
|
+
ml += 4
|
|
74
|
+
start = len(out) - off
|
|
75
|
+
for k in range(ml): # overlapping copies must go byte by byte
|
|
76
|
+
out.append(out[start + k])
|
|
77
|
+
return bytes(out)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def lz4_compress(data: bytes) -> bytes:
|
|
81
|
+
"""Literal-only LZ4 block: valid for every decoder, no size reduction (session files are small)."""
|
|
82
|
+
n = len(data)
|
|
83
|
+
if n == 0:
|
|
84
|
+
return b"\0"
|
|
85
|
+
head = bytearray([0xF0]) if n >= 15 else bytearray([n << 4])
|
|
86
|
+
if n >= 15:
|
|
87
|
+
rest = n - 15
|
|
88
|
+
while rest >= 255:
|
|
89
|
+
head.append(255)
|
|
90
|
+
rest -= 255
|
|
91
|
+
head.append(rest)
|
|
92
|
+
return bytes(head) + data
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def mozlz4_read(path: Path) -> dict:
|
|
96
|
+
raw = path.read_bytes()
|
|
97
|
+
if raw[:8] != MAGIC:
|
|
98
|
+
raise SystemExit(f"{path} is not a mozlz4 file")
|
|
99
|
+
return json.loads(lz4_decompress(raw[12:]))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def mozlz4_write(path: Path, data: dict) -> None:
|
|
103
|
+
body = json.dumps(data, separators=(",", ":")).encode()
|
|
104
|
+
path.write_bytes(MAGIC + len(body).to_bytes(4, "little") + lz4_compress(body))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ----------------------------------------------------------------- profiles
|
|
108
|
+
def profile_dir(browser: str, profile: str = "Default", data_dir: Path | None = None) -> Path:
|
|
109
|
+
"""``data_dir`` is an explicit profile directory; otherwise resolve ``profile`` (a name, or
|
|
110
|
+
"Default" for the default-marked one) through profiles.ini in the known roots."""
|
|
111
|
+
if data_dir:
|
|
112
|
+
return Path(data_dir)
|
|
113
|
+
for root in BROWSERS[browser][0]:
|
|
114
|
+
ini = root / "profiles.ini"
|
|
115
|
+
if not ini.exists():
|
|
116
|
+
continue
|
|
117
|
+
cp = configparser.ConfigParser()
|
|
118
|
+
cp.read(ini)
|
|
119
|
+
sections = [cp[s] for s in cp.sections() if s.startswith("Profile")]
|
|
120
|
+
for s in sections:
|
|
121
|
+
if (profile == "Default" and s.get("Default") == "1") or s.get("Name") == profile:
|
|
122
|
+
p = Path(s["Path"])
|
|
123
|
+
return root / p if s.get("IsRelative", "1") == "1" else p
|
|
124
|
+
if profile == "Default" and sections:
|
|
125
|
+
s = sections[0]
|
|
126
|
+
return root / s["Path"] if s.get("IsRelative", "1") == "1" else Path(s["Path"])
|
|
127
|
+
raise SystemExit(f"no {browser} profile {profile!r} found under {[str(r) for r in BROWSERS[browser][0]]}")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def session_file(pdir: Path) -> Path:
|
|
131
|
+
recovery = pdir / "sessionstore-backups/recovery.jsonlz4"
|
|
132
|
+
clean = pdir / "sessionstore.jsonlz4"
|
|
133
|
+
for p in (recovery, clean, pdir / "sessionstore-backups/previous.jsonlz4"):
|
|
134
|
+
if p.exists():
|
|
135
|
+
return p
|
|
136
|
+
hint = " (Tor Browser keeps no session on disk; use --live)" if "tor-browser" in str(pdir) else ""
|
|
137
|
+
raise SystemExit(f"no session file in {pdir}{hint}")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ----------------------------------------------------------------- model <-> sessionstore
|
|
141
|
+
def parse(d: dict, browser: str = "") -> Session:
|
|
142
|
+
s = Session(browser=browser, extra={"sessionstore": {k: v for k, v in d.items() if k != "windows"}})
|
|
143
|
+
for w in d.get("windows", []):
|
|
144
|
+
geo_keys = ("screenX", "screenY", "width", "height", "sizemode")
|
|
145
|
+
win = Window(extra={k: v for k, v in w.items() if k not in ("tabs", "groups", "selected", *geo_keys)})
|
|
146
|
+
if any(k in w for k in geo_keys):
|
|
147
|
+
win.geometry = {
|
|
148
|
+
"x": w.get("screenX", 0),
|
|
149
|
+
"y": w.get("screenY", 0),
|
|
150
|
+
"width": w.get("width", 1280),
|
|
151
|
+
"height": w.get("height", 800),
|
|
152
|
+
"state": w.get("sizemode", "normal"),
|
|
153
|
+
}
|
|
154
|
+
groups = {g["id"]: g for g in w.get("groups", [])}
|
|
155
|
+
sel = w.get("selected", 1) - 1
|
|
156
|
+
for i, t in enumerate(w.get("tabs", [])):
|
|
157
|
+
entries = t.get("entries", [])
|
|
158
|
+
cur = entries[min(max(t.get("index", 1), 1), len(entries)) - 1] if entries else {}
|
|
159
|
+
tab = Tab(
|
|
160
|
+
url=cur.get("url", ""),
|
|
161
|
+
title=cur.get("title", ""),
|
|
162
|
+
pinned=bool(t.get("pinned")),
|
|
163
|
+
active=i == sel,
|
|
164
|
+
extra={k: v for k, v in t.items() if k not in ("pinned", "groupId")},
|
|
165
|
+
)
|
|
166
|
+
gid = t.get("groupId")
|
|
167
|
+
if gid is not None:
|
|
168
|
+
last = win.items[-1] if win.items else None
|
|
169
|
+
if isinstance(last, Group) and last.extra.get("id") == gid:
|
|
170
|
+
last.tabs.append(tab)
|
|
171
|
+
else:
|
|
172
|
+
g = groups.get(gid, {})
|
|
173
|
+
win.items.append(
|
|
174
|
+
Group(
|
|
175
|
+
title=g.get("name", ""),
|
|
176
|
+
color=COLORS.get(g.get("color", "grey"), g.get("color", "grey")),
|
|
177
|
+
collapsed=bool(g.get("collapsed")),
|
|
178
|
+
tabs=[tab],
|
|
179
|
+
extra={**g, "id": gid},
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
else:
|
|
183
|
+
win.items.append(tab)
|
|
184
|
+
s.windows.append(win)
|
|
185
|
+
return s
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def build(s: Session) -> dict:
|
|
189
|
+
inv = {v: k for k, v in COLORS.items()}
|
|
190
|
+
d = {"version": ["sessionrestore", 1], **s.extra.get("sessionstore", {}), "windows": []}
|
|
191
|
+
d["session"] = {**d.get("session", {}), "recentCrashes": 0, "lastUpdate": int(time.time() * 1000)}
|
|
192
|
+
for w in s.windows:
|
|
193
|
+
tabs, groups, sel = [], [], 1
|
|
194
|
+
for it in w.items:
|
|
195
|
+
if isinstance(it, Group):
|
|
196
|
+
gid = it.extra.get("id") or f"tw-{len(groups) + 1}"
|
|
197
|
+
groups.append(
|
|
198
|
+
{
|
|
199
|
+
**it.extra,
|
|
200
|
+
"id": gid,
|
|
201
|
+
"name": it.title,
|
|
202
|
+
"color": inv.get(it.color, it.color),
|
|
203
|
+
"collapsed": it.collapsed,
|
|
204
|
+
}
|
|
205
|
+
)
|
|
206
|
+
members = [(t, gid) for t in it.tabs]
|
|
207
|
+
else:
|
|
208
|
+
members = [(it, None)]
|
|
209
|
+
for t, gid in members:
|
|
210
|
+
if t.active:
|
|
211
|
+
sel = len(tabs) + 1
|
|
212
|
+
entry = {k: v for k, v in t.extra.items()}
|
|
213
|
+
entries = entry.get("entries") or [{"url": t.url, "title": t.title}]
|
|
214
|
+
idx = min(max(entry.get("index", 1), 1), len(entries))
|
|
215
|
+
if entries[idx - 1].get("url") != t.url: # model changed the URL: point at a fresh entry
|
|
216
|
+
entries, idx = [{"url": t.url, "title": t.title}], 1
|
|
217
|
+
tab = {**entry, "entries": entries, "index": idx}
|
|
218
|
+
if t.pinned:
|
|
219
|
+
tab["pinned"] = True
|
|
220
|
+
if gid is not None:
|
|
221
|
+
tab["groupId"] = gid
|
|
222
|
+
tabs.append(tab)
|
|
223
|
+
geo = {}
|
|
224
|
+
if w.geometry:
|
|
225
|
+
g = w.geometry
|
|
226
|
+
geo = {
|
|
227
|
+
"screenX": g["x"],
|
|
228
|
+
"screenY": g["y"],
|
|
229
|
+
"width": g["width"],
|
|
230
|
+
"height": g["height"],
|
|
231
|
+
"sizemode": g["state"],
|
|
232
|
+
}
|
|
233
|
+
d["windows"].append({**w.extra, **geo, "tabs": tabs, "groups": groups, "selected": sel})
|
|
234
|
+
d["selectedWindow"] = 1 if s.windows else 0
|
|
235
|
+
return d
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def read(path: Path, browser: str = "firefox") -> Session:
|
|
239
|
+
return parse(mozlz4_read(path), browser)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def write_file(session: Session, path: Path) -> None:
|
|
243
|
+
mozlz4_write(path, build(session))
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def read_profile(browser: str, profile: str = "Default", data_dir: Path | None = None) -> Session:
|
|
247
|
+
return read(session_file(profile_dir(browser, profile, data_dir)), browser)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def write(session: Session, pdir: Path) -> Path:
|
|
251
|
+
"""Write the session as both the clean and the recovery file and mark the checkpoints as
|
|
252
|
+
an unfinished shutdown so Firefox restores it on launch; returns the recovery path."""
|
|
253
|
+
data = build(session)
|
|
254
|
+
(pdir / "sessionstore-backups").mkdir(parents=True, exist_ok=True)
|
|
255
|
+
recovery = pdir / "sessionstore-backups/recovery.jsonlz4"
|
|
256
|
+
mozlz4_write(recovery, data)
|
|
257
|
+
mozlz4_write(pdir / "sessionstore.jsonlz4", data)
|
|
258
|
+
(pdir / "sessionCheckpoints.json").write_text(json.dumps(CRASHED_CHECKPOINTS))
|
|
259
|
+
return recovery
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def apply(session: Session, browser: str, profile: str = "Default", data_dir: Path | None = None) -> Path:
|
|
263
|
+
return write(session, profile_dir(browser, profile, data_dir))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# ----------------------------------------------------------------- processes
|
|
267
|
+
def pids(browser: str, data_dir: Path | None = None) -> list[int]:
|
|
268
|
+
"""Main Firefox processes; with ``data_dir`` only the one started on that profile dir."""
|
|
269
|
+
out = []
|
|
270
|
+
for p in Path("/proc").iterdir():
|
|
271
|
+
if not p.name.isdigit():
|
|
272
|
+
continue
|
|
273
|
+
try:
|
|
274
|
+
argv = (p / "cmdline").read_bytes().rstrip(b"\0").split(b"\0")
|
|
275
|
+
except OSError:
|
|
276
|
+
continue
|
|
277
|
+
if not argv or os.path.basename(argv[0].decode(errors="replace")) not in (
|
|
278
|
+
"firefox",
|
|
279
|
+
"firefox-bin",
|
|
280
|
+
"firefox-esr",
|
|
281
|
+
):
|
|
282
|
+
continue
|
|
283
|
+
if b"-contentproc" in argv:
|
|
284
|
+
continue
|
|
285
|
+
if browser == "tor" and b"tor-browser" not in argv[0]:
|
|
286
|
+
continue
|
|
287
|
+
if browser == "firefox" and b"tor-browser" in argv[0]:
|
|
288
|
+
continue
|
|
289
|
+
prof = next((argv[i + 1] for i, a in enumerate(argv[:-1]) if a in (b"-profile", b"--profile")), None)
|
|
290
|
+
if data_dir is None or (
|
|
291
|
+
prof is not None and Path(prof.decode()).resolve() == Path(data_dir).resolve()
|
|
292
|
+
):
|
|
293
|
+
out.append(int(p.name))
|
|
294
|
+
return out
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def stop(browser: str, data_dir: Path | None = None, force: bool = False, timeout: float = 15) -> list[int]:
|
|
298
|
+
ps = pids(browser, data_dir)
|
|
299
|
+
for pid in ps:
|
|
300
|
+
os.kill(pid, signal.SIGKILL if force else signal.SIGTERM)
|
|
301
|
+
deadline = time.time() + timeout
|
|
302
|
+
while time.time() < deadline and pids(browser, data_dir):
|
|
303
|
+
time.sleep(0.2)
|
|
304
|
+
for pid in pids(browser, data_dir):
|
|
305
|
+
os.kill(pid, signal.SIGKILL)
|
|
306
|
+
return ps
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def start(browser: str, data_dir: Path | None = None, args: list[str] = ()) -> int:
|
|
310
|
+
for b in BROWSERS[browser][1]:
|
|
311
|
+
found = Path(b).exists() or any(
|
|
312
|
+
(Path(d) / b).exists() for d in os.environ.get("PATH", "").split(os.pathsep)
|
|
313
|
+
)
|
|
314
|
+
if found:
|
|
315
|
+
cmd = [b, *(["--profile", str(data_dir), "--no-remote"] if data_dir else []), *args]
|
|
316
|
+
return subprocess.Popen(
|
|
317
|
+
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True
|
|
318
|
+
).pid
|
|
319
|
+
raise SystemExit(f"no binary found for {browser}: tried {BROWSERS[browser][1]}")
|