radiobooth 0.5.11__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.
- radiobooth/__init__.py +7 -0
- radiobooth/__main__.py +5 -0
- radiobooth/arrivals.py +258 -0
- radiobooth/autostart.py +334 -0
- radiobooth/catalog.py +148 -0
- radiobooth/cli.py +608 -0
- radiobooth/config.py +147 -0
- radiobooth/engine.py +599 -0
- radiobooth/history.py +174 -0
- radiobooth/link.py +558 -0
- radiobooth/macapp.py +126 -0
- radiobooth/onboard.py +318 -0
- radiobooth/page.py +1016 -0
- radiobooth/plexshare.py +85 -0
- radiobooth/qr.py +232 -0
- radiobooth/render/__init__.py +464 -0
- radiobooth/setup_flow.py +193 -0
- radiobooth/sources/__init__.py +1 -0
- radiobooth/sources/folder.py +565 -0
- radiobooth/sources/plex.py +325 -0
- radiobooth/sources/tags.py +366 -0
- radiobooth/targets/__init__.py +1 -0
- radiobooth/targets/playlist.py +462 -0
- radiobooth/targets/plex.py +480 -0
- radiobooth/update.py +414 -0
- radiobooth/web.py +896 -0
- radiobooth/websetup.py +315 -0
- radiobooth-0.5.11.dist-info/METADATA +146 -0
- radiobooth-0.5.11.dist-info/RECORD +32 -0
- radiobooth-0.5.11.dist-info/WHEEL +4 -0
- radiobooth-0.5.11.dist-info/entry_points.txt +3 -0
- radiobooth-0.5.11.dist-info/licenses/LICENSE +674 -0
radiobooth/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Booth Engineer, the home client for Radio Booth."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.5.11"
|
|
4
|
+
__copyright__ = "Copyright \u00a9 2026 Thomas Bohmbach, Jr."
|
|
5
|
+
SOURCE_URL = "https://github.com/radiobooth/engineer"
|
|
6
|
+
LICENSE_URL = SOURCE_URL + "/blob/main/LICENSE"
|
|
7
|
+
PRIVACY_URL = "https://my.radiobooth.fm/privacy" # Plex asks apps that use it to link a privacy notice
|
radiobooth/__main__.py
ADDED
radiobooth/arrivals.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""When each track first turned up in a library, as Radio Booth itself saw it.
|
|
2
|
+
|
|
3
|
+
Music servers stamp every track with the day they first scanned it, which for a library set up in one go is
|
|
4
|
+
the day the server was installed, not the day the listener got the record; a folder of files has no such
|
|
5
|
+
date at all. So Radio Booth keeps its own, on this machine only (library-seen.json, next to the config):
|
|
6
|
+
|
|
7
|
+
- The first catalog read of a library is its baseline. Every track in it was "here before Radio Booth kept
|
|
8
|
+
track" and never gets a date.
|
|
9
|
+
- A track in a later read that wasn't in any earlier one joined between the two reads: `joined_after` the
|
|
10
|
+
day of the read before, `joined_by` the day of this one.
|
|
11
|
+
- A "new" track that's a song already known here (same artist, title and length: a file moved or renamed,
|
|
12
|
+
a Plex rescan that gave it a new id, a second copy; or with its artist or title retagged and moved at
|
|
13
|
+
once) is no news: it keeps the status of the one known. Dates follow songs, never ids alone: an id that
|
|
14
|
+
now holds another song (a rebuilt Plex database) is judged by its new song.
|
|
15
|
+
- A track the source found before but couldn't use (a file missing its tags, say) isn't news when it
|
|
16
|
+
becomes usable: the source's `also` ids are remembered too.
|
|
17
|
+
- Many new tracks at once (a big rescan or restore) say nothing about when the listener got them, so they
|
|
18
|
+
join the baseline instead.
|
|
19
|
+
- Days are the listener's own (this computer's local date), as the DJ says them.
|
|
20
|
+
|
|
21
|
+
One record per library: its kind, name and where it is (the music folder, or the Plex server), so picking
|
|
22
|
+
another folder or server starts a new baseline rather than dating everything in it; a read that mostly
|
|
23
|
+
knows the songs of another record of its kind is that library at a new address and carries on with it.
|
|
24
|
+
It's shared by
|
|
25
|
+
everyone on this computer: it's the library's history, not a person's. Deleting the file starts it over,
|
|
26
|
+
with new baselines. Titles never go in it: songs are compared by a short hash of artist, title and length.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import hashlib
|
|
32
|
+
import json
|
|
33
|
+
from collections.abc import Iterable
|
|
34
|
+
from datetime import UTC, date, datetime
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
|
|
37
|
+
from radiobooth import config
|
|
38
|
+
|
|
39
|
+
VERSION = 1
|
|
40
|
+
BULK_MIN = 200 # new tracks in one read, at least, to count as a bulk import...
|
|
41
|
+
BULK_SHARE = 0.02 # ... and at least this share of the library
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def path() -> Path:
|
|
45
|
+
return config.path().with_name("library-seen.json")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _stamp(when: datetime) -> str:
|
|
49
|
+
"""A time in this computer's own zone, with its offset, so its date is the listener's day too."""
|
|
50
|
+
return when.astimezone().isoformat(timespec="seconds")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _short(text: str) -> str:
|
|
54
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _key(catalog: dict, where: str | None) -> str:
|
|
58
|
+
source = catalog.get("source") or {}
|
|
59
|
+
return f"{source.get('kind', '')}:{source.get('library', '')}:{_short(where or '')}"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def signature(t: dict) -> str:
|
|
63
|
+
"""A song as it's recognised again under another id: short hashes of its artist and of its title, and
|
|
64
|
+
its length in two-second steps ("<artist><title>:<steps>")."""
|
|
65
|
+
artist, title = (" ".join(str(t.get(k, "")).casefold().split()) for k in ("artist", "title"))
|
|
66
|
+
return f"{_short(artist)[:6]}{_short(title)[:6]}:{round(t.get('duration_ms', 0) / 2000)}"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _parts(sig: str) -> tuple[str, str, int] | None:
|
|
70
|
+
name, _, steps = sig.rpartition(":")
|
|
71
|
+
if len(name) != 12 or not steps.lstrip("-").isdigit():
|
|
72
|
+
return None
|
|
73
|
+
return name[:6], name[6:], int(steps)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _near(sig: str) -> list[str]:
|
|
77
|
+
"""The signature and the ones a step shorter and longer, so lengths either side of a step still match."""
|
|
78
|
+
p = _parts(sig)
|
|
79
|
+
if p is None:
|
|
80
|
+
return [sig]
|
|
81
|
+
return [sig, f"{p[0]}{p[1]}:{p[2] - 1}", f"{p[0]}{p[1]}:{p[2] + 1}"]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def same_song(a: str, b: str) -> bool:
|
|
85
|
+
"""Whether two signatures are the same song: the same title at much the same length, with the artist
|
|
86
|
+
the same or retagged ("Beatles" to "The Beatles"). The same artist alone isn't enough: their other
|
|
87
|
+
songs often run as long."""
|
|
88
|
+
pa, pb = _parts(a), _parts(b)
|
|
89
|
+
if pa is None or pb is None:
|
|
90
|
+
return a == b
|
|
91
|
+
return abs(pa[2] - pb[2]) <= 1 and pa[1] == pb[1]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _is_day(v) -> bool:
|
|
95
|
+
if not isinstance(v, str) or len(v) != 10:
|
|
96
|
+
return False
|
|
97
|
+
try:
|
|
98
|
+
date.fromisoformat(v)
|
|
99
|
+
except ValueError:
|
|
100
|
+
return False
|
|
101
|
+
return v[4] == "-" and v[7] == "-"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _is_time(v) -> bool:
|
|
105
|
+
if not isinstance(v, str):
|
|
106
|
+
return False
|
|
107
|
+
try:
|
|
108
|
+
return datetime.fromisoformat(v.replace("Z", "+00:00")).tzinfo is not None
|
|
109
|
+
except ValueError:
|
|
110
|
+
return False
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _clean(rec) -> dict | None:
|
|
114
|
+
"""A library's record as read back, with anything malformed left out; None if it can't be used."""
|
|
115
|
+
if not isinstance(rec, dict) or not (_is_time(rec.get("since")) and _is_day(rec.get("day"))):
|
|
116
|
+
return None
|
|
117
|
+
tracks, joined = rec.get("tracks"), rec.get("joined")
|
|
118
|
+
if not isinstance(tracks, dict) or not isinstance(joined, dict):
|
|
119
|
+
return None
|
|
120
|
+
return {
|
|
121
|
+
"since": rec["since"],
|
|
122
|
+
"day": rec["day"],
|
|
123
|
+
"tracks": {k: v for k, v in tracks.items() if isinstance(k, str) and isinstance(v, str)},
|
|
124
|
+
"joined": {
|
|
125
|
+
k: v
|
|
126
|
+
for k, v in joined.items()
|
|
127
|
+
if isinstance(k, str) and isinstance(v, list) and len(v) == 2 and all(map(_is_day, v))
|
|
128
|
+
},
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _load() -> dict:
|
|
133
|
+
try:
|
|
134
|
+
data = json.loads(path().read_text(encoding="utf-8"))
|
|
135
|
+
except (OSError, ValueError):
|
|
136
|
+
return {}
|
|
137
|
+
sources = data.get("sources") if isinstance(data, dict) else None
|
|
138
|
+
if not isinstance(sources, dict):
|
|
139
|
+
return {}
|
|
140
|
+
return {k: rec for k, v in sources.items() if isinstance(k, str) and (rec := _clean(v))}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
ADOPT_SHARE = (
|
|
144
|
+
0.9 # of each other's songs a read and another record of its kind share: the same library, moved
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _find(sources: dict, key: str, read: dict[str, str]) -> str | None:
|
|
149
|
+
"""The record for this library: its own key, or else the record of the same kind whose songs and this
|
|
150
|
+
read's mostly agree (each holds at least ADOPT_SHARE of the other's): the same library at a new
|
|
151
|
+
address (a Plex server reached another way, a drive mounted elsewhere), not a part of it widened."""
|
|
152
|
+
if key in sources:
|
|
153
|
+
return key
|
|
154
|
+
kind = key.split(":", 1)[0] + ":"
|
|
155
|
+
mine = {x for sig in read.values() for x in _near(sig)}
|
|
156
|
+
best, most = None, 0.0
|
|
157
|
+
for k, rec in sources.items():
|
|
158
|
+
if not k.startswith(kind):
|
|
159
|
+
continue
|
|
160
|
+
# By songs, never ids alone: two Plex databases hand out the same small numbers to different songs.
|
|
161
|
+
theirs = [sig for sig in rec["tracks"].values() if sig]
|
|
162
|
+
if not theirs or not read:
|
|
163
|
+
continue
|
|
164
|
+
sigs = set(theirs)
|
|
165
|
+
share = min(
|
|
166
|
+
sum(any(x in sigs for x in _near(sig)) for sig in read.values()) / len(read),
|
|
167
|
+
sum(sig in mine for sig in theirs) / len(theirs),
|
|
168
|
+
)
|
|
169
|
+
if share >= ADOPT_SHARE and share > most:
|
|
170
|
+
best, most = k, share
|
|
171
|
+
return best
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def watch(
|
|
175
|
+
catalog: dict, where: str | None = None, when: datetime | None = None, also: Iterable[str] = ()
|
|
176
|
+
) -> dict:
|
|
177
|
+
"""Note a fresh, whole read of the catalog's library (`where`: its folder or server; `also`: ids of
|
|
178
|
+
tracks the source found but couldn't use, which aren't news when they become usable); its record:
|
|
179
|
+
{"since": the baseline read, "day": this read's local day, "tracks": {id: signature, or "" for one
|
|
180
|
+
not usable yet}, "joined": {id: [after day, by day]}}."""
|
|
181
|
+
when = when or datetime.now(UTC)
|
|
182
|
+
today = when.astimezone().date().isoformat()
|
|
183
|
+
sources, key = _load(), _key(catalog, where)
|
|
184
|
+
read = {t["id"]: signature(t) for t in catalog["tracks"]}
|
|
185
|
+
found = _find(sources, key, read)
|
|
186
|
+
rec = sources.pop(found) if found else None
|
|
187
|
+
if rec is None:
|
|
188
|
+
rec = {"since": _stamp(when), "day": today, "tracks": dict(read), "joined": {}}
|
|
189
|
+
else:
|
|
190
|
+
known, joined = rec["tracks"], rec["joined"]
|
|
191
|
+
before = dict(joined) # each id's status as it was, by the song it held
|
|
192
|
+
by_song: dict[str, str] = {}
|
|
193
|
+
for i, sig in known.items():
|
|
194
|
+
if sig:
|
|
195
|
+
by_song.setdefault(sig, i)
|
|
196
|
+
# Known ids this read doesn't have: a song among them may be back under a new id and new tags.
|
|
197
|
+
gone = [(i, sig) for i, sig in known.items() if sig and i not in read]
|
|
198
|
+
unsettled = [] # ids to judge by their songs
|
|
199
|
+
for i, sig in read.items():
|
|
200
|
+
old = known.get(i)
|
|
201
|
+
if old and not same_song(old, sig): # the id holds another song now (ids handed out again)
|
|
202
|
+
joined.pop(i, None)
|
|
203
|
+
unsettled.append(i)
|
|
204
|
+
elif i not in known: # ("" is a track seen before that couldn't be used: no news)
|
|
205
|
+
unsettled.append(i)
|
|
206
|
+
arrived = []
|
|
207
|
+
for i in unsettled:
|
|
208
|
+
sig = read[i]
|
|
209
|
+
twin = next((o for x in _near(sig) if (o := by_song.get(x)) is not None and o != i), None)
|
|
210
|
+
if twin is None: # retagged and moved at once: a song that went missing from this read
|
|
211
|
+
twin = next((g for g, gsig in gone if same_song(gsig, sig)), None)
|
|
212
|
+
if twin is not None:
|
|
213
|
+
gone = [(g, gsig) for g, gsig in gone if g != twin]
|
|
214
|
+
if twin is not None:
|
|
215
|
+
if twin in before:
|
|
216
|
+
joined[i] = before[twin]
|
|
217
|
+
else:
|
|
218
|
+
arrived.append(i)
|
|
219
|
+
if len(arrived) < max(BULK_MIN, BULK_SHARE * len(read)):
|
|
220
|
+
for i in arrived:
|
|
221
|
+
joined[i] = [min(rec["day"], today), today]
|
|
222
|
+
known.update(read) # each song as it's tagged now, so a later move still matches it
|
|
223
|
+
rec["day"] = today
|
|
224
|
+
for i in also:
|
|
225
|
+
rec["tracks"].setdefault(i, "")
|
|
226
|
+
sources[key] = rec
|
|
227
|
+
p = path()
|
|
228
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
229
|
+
config.write_atomically(p, json.dumps({"version": VERSION, "sources": sources}) + "\n")
|
|
230
|
+
return rec
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def annotate(
|
|
234
|
+
catalog: dict,
|
|
235
|
+
fresh: bool = True,
|
|
236
|
+
where: str | None = None,
|
|
237
|
+
when: datetime | None = None,
|
|
238
|
+
also: Iterable[str] = (),
|
|
239
|
+
) -> dict:
|
|
240
|
+
"""The catalog with `history_since` and each arrival's `joined_after` and `joined_by`. `fresh`: this
|
|
241
|
+
is a whole, new read of the library, noted first (see `watch`); otherwise only what earlier reads
|
|
242
|
+
saw. Never fails a show: any trouble with the file sends the catalog without arrivals."""
|
|
243
|
+
try:
|
|
244
|
+
if fresh:
|
|
245
|
+
rec = watch(catalog, where, when, also)
|
|
246
|
+
else:
|
|
247
|
+
sources = _load()
|
|
248
|
+
read = {t["id"]: signature(t) for t in catalog["tracks"]}
|
|
249
|
+
rec = sources.get(_find(sources, _key(catalog, where), read) or "")
|
|
250
|
+
except Exception: # noqa: BLE001 - arrivals are a nicety; the show goes on without them
|
|
251
|
+
rec = None
|
|
252
|
+
if not rec:
|
|
253
|
+
return catalog
|
|
254
|
+
catalog["history_since"] = rec["since"]
|
|
255
|
+
for t in catalog["tracks"]:
|
|
256
|
+
if j := rec["joined"].get(t["id"]):
|
|
257
|
+
t["joined_after"], t["joined_by"] = j
|
|
258
|
+
return catalog
|
radiobooth/autostart.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""Start Booth Engineer when you sign in to this computer, so shows arrive without opening anything.
|
|
2
|
+
|
|
3
|
+
The packaged app is first copied to a folder of its own, so tidying Downloads never breaks it (and on macOS,
|
|
4
|
+
a background app may not read files in Downloads at all): on Windows a folder in AppData, on a Mac the
|
|
5
|
+
Applications folder (see `macapp`).
|
|
6
|
+
Windows: a shortcut in the Startup folder starts Booth in the background (no window), and a Start-menu
|
|
7
|
+
shortcut opens Booth's page. macOS: a LaunchAgent, which System Settings lists under Login Items. On both,
|
|
8
|
+
Booth runs as the app (`booth app --background`: no window, its page a click away). Linux: a systemd user
|
|
9
|
+
service running `booth run`. Each runs as you, with your settings; nothing is installed system-wide.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from radiobooth import macapp, update
|
|
21
|
+
|
|
22
|
+
NAME = "radiobooth"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def command() -> list[str]:
|
|
26
|
+
"""How to start this same Booth Engineer again: the app itself, or the installed `booth` command."""
|
|
27
|
+
if getattr(sys, "frozen", False):
|
|
28
|
+
return [sys.executable]
|
|
29
|
+
found = shutil.which("booth")
|
|
30
|
+
return [found] if found else [sys.executable, "-m", "radiobooth"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def app_home(platform: str, home: Path) -> Path:
|
|
34
|
+
"""Where the packaged app keeps its own copy. (The Mac app goes to Applications instead; this is where the
|
|
35
|
+
Mac download kept itself before it was an app, as a bare program.)"""
|
|
36
|
+
if platform == "win32":
|
|
37
|
+
return (
|
|
38
|
+
Path(os.environ.get("LOCALAPPDATA") or home / "AppData" / "Local")
|
|
39
|
+
/ "Radio Booth"
|
|
40
|
+
/ "RadioBooth.exe"
|
|
41
|
+
)
|
|
42
|
+
return home / "Library" / "Application Support" / "Radio Booth" / "Radio Booth"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def keep_app(cmd: list[str], home: Path, platform: str) -> list[str]:
|
|
46
|
+
"""The downloaded app copied to a folder of its own, so starting at sign-in still works after the
|
|
47
|
+
Downloads folder is tidied. Only for the packaged app; an installed `booth` command stays put."""
|
|
48
|
+
if not getattr(sys, "frozen", False):
|
|
49
|
+
return cmd
|
|
50
|
+
if platform == "darwin" and (app := macapp.bundle(cmd[0])):
|
|
51
|
+
return [str(macapp.launcher(macapp.install(app, home)))]
|
|
52
|
+
target = app_home(platform, home)
|
|
53
|
+
if not same_file(cmd[0], target):
|
|
54
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
55
|
+
staged = target.with_name(target.stem + ".new" + target.suffix)
|
|
56
|
+
shutil.copy2(cmd[0], staged) # a full copy first, so a failure never leaves a broken app behind
|
|
57
|
+
try:
|
|
58
|
+
put_in_place(staged, target, platform)
|
|
59
|
+
except OSError as e:
|
|
60
|
+
staged.unlink(missing_ok=True)
|
|
61
|
+
raise OSError(
|
|
62
|
+
f"Radio Booth couldn't copy itself to its own folder ({e.strerror or e}). Restart the "
|
|
63
|
+
"computer, then try again."
|
|
64
|
+
) from None
|
|
65
|
+
return [str(target)]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def same_file(path: str | Path, other: Path) -> bool:
|
|
69
|
+
"""Whether two paths name one file. Windows can spell one path several ways (short 8.3 names, letter
|
|
70
|
+
case, a folder moved elsewhere by a link), so the file itself is asked, not just the spelling."""
|
|
71
|
+
try:
|
|
72
|
+
return os.path.samefile(path, other)
|
|
73
|
+
except OSError: # one of them isn't there (yet)
|
|
74
|
+
return os.path.normcase(os.path.abspath(path)) == os.path.normcase(os.path.abspath(other))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def put_in_place(new: Path, target: Path, platform: str) -> None:
|
|
78
|
+
"""Move `new` over `target`. On Windows a program that is running can't be replaced, only renamed, so if
|
|
79
|
+
the copy in its own folder is still in use (an older Booth on its way out, say), it is moved aside first,
|
|
80
|
+
the way an update does it; the next start of the app tidies it away."""
|
|
81
|
+
try:
|
|
82
|
+
os.replace(new, target)
|
|
83
|
+
except OSError:
|
|
84
|
+
if platform != "win32" or not target.exists():
|
|
85
|
+
raise
|
|
86
|
+
update.swap_windows(new, target)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _com_shortcut(link: Path, target: str, args: str, workdir: str) -> None:
|
|
90
|
+
"""Make a Windows shortcut (.lnk) through the shell's own IShellLink, the way installers do, called
|
|
91
|
+
directly rather than by starting PowerShell: a program with no window that starts PowerShell is just what
|
|
92
|
+
antivirus software looks for."""
|
|
93
|
+
import ctypes
|
|
94
|
+
from ctypes import POINTER, WINFUNCTYPE, byref, c_ulong, c_void_p, c_wchar_p
|
|
95
|
+
|
|
96
|
+
ole32 = ctypes.OleDLL("ole32") # an HRESULT failure raises OSError
|
|
97
|
+
|
|
98
|
+
class GUID(ctypes.Structure):
|
|
99
|
+
_fields_ = [
|
|
100
|
+
("a", ctypes.c_ulong),
|
|
101
|
+
("b", ctypes.c_ushort),
|
|
102
|
+
("c", ctypes.c_ushort),
|
|
103
|
+
("d", ctypes.c_ubyte * 8),
|
|
104
|
+
]
|
|
105
|
+
|
|
106
|
+
def guid(text: str) -> GUID:
|
|
107
|
+
g = GUID()
|
|
108
|
+
ole32.CLSIDFromString(c_wchar_p(text), byref(g))
|
|
109
|
+
return g
|
|
110
|
+
|
|
111
|
+
def method(obj: c_void_p, index: int, *argtypes, restype=ctypes.HRESULT):
|
|
112
|
+
table = ctypes.cast(obj, POINTER(POINTER(c_void_p))).contents
|
|
113
|
+
fn = WINFUNCTYPE(restype, c_void_p, *argtypes)(table[index])
|
|
114
|
+
return lambda *a: fn(obj, *a)
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
ole32.CoInitializeEx(None, 2) # COINIT_APARTMENTTHREADED, for this thread
|
|
118
|
+
started = True
|
|
119
|
+
except OSError: # already initialised differently on this thread: fine to use as it is
|
|
120
|
+
started = False
|
|
121
|
+
link_obj, file_obj = c_void_p(), c_void_p()
|
|
122
|
+
try:
|
|
123
|
+
ole32.CoCreateInstance(
|
|
124
|
+
byref(guid("{00021401-0000-0000-C000-000000000046}")), # ShellLink
|
|
125
|
+
None,
|
|
126
|
+
1, # CLSCTX_INPROC_SERVER
|
|
127
|
+
byref(guid("{000214F9-0000-0000-C000-000000000046}")), # IShellLinkW
|
|
128
|
+
byref(link_obj),
|
|
129
|
+
)
|
|
130
|
+
method(link_obj, 20, c_wchar_p)(target) # SetPath
|
|
131
|
+
method(link_obj, 11, c_wchar_p)(args) # SetArguments
|
|
132
|
+
method(link_obj, 9, c_wchar_p)(workdir) # SetWorkingDirectory
|
|
133
|
+
method(link_obj, 0, POINTER(GUID), POINTER(c_void_p))( # QueryInterface
|
|
134
|
+
byref(guid("{0000010B-0000-0000-C000-000000000046}")),
|
|
135
|
+
byref(file_obj), # IPersistFile
|
|
136
|
+
)
|
|
137
|
+
method(file_obj, 6, c_wchar_p, ctypes.c_int)(str(link), 1) # Save
|
|
138
|
+
finally:
|
|
139
|
+
for obj in (file_obj, link_obj):
|
|
140
|
+
if obj.value:
|
|
141
|
+
method(obj, 2, restype=c_ulong)() # Release
|
|
142
|
+
if started:
|
|
143
|
+
ole32.CoUninitialize()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def write_shortcut(link: Path, cmd: list[str], action: str, make=None) -> None:
|
|
147
|
+
"""A shortcut at `link` that runs `cmd` with `action`, for the Start menu or the Startup folder."""
|
|
148
|
+
import ntpath
|
|
149
|
+
|
|
150
|
+
args = " ".join([*(f'"{c}"' for c in cmd[1:]), *([action] if action else [])])
|
|
151
|
+
link.parent.mkdir(parents=True, exist_ok=True)
|
|
152
|
+
(make or _com_shortcut)(link, cmd[0], args, ntpath.dirname(cmd[0]))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
APP_ARGS = ["app", "--background"]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def mac_plist(cmd: list[str], log: Path) -> str:
|
|
159
|
+
args = "".join(f"\n <string>{_xml(c)}</string>" for c in [*cmd, *APP_ARGS])
|
|
160
|
+
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
|
161
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
162
|
+
<plist version="1.0">
|
|
163
|
+
<dict>
|
|
164
|
+
<key>Label</key>
|
|
165
|
+
<string>{macapp.BUNDLE_ID}</string>
|
|
166
|
+
<key>AssociatedBundleIdentifiers</key>
|
|
167
|
+
<array>
|
|
168
|
+
<string>{macapp.BUNDLE_ID}</string>
|
|
169
|
+
</array>
|
|
170
|
+
<key>ProgramArguments</key>
|
|
171
|
+
<array>{args}
|
|
172
|
+
</array>
|
|
173
|
+
<key>RunAtLoad</key>
|
|
174
|
+
<true/>
|
|
175
|
+
<key>KeepAlive</key>
|
|
176
|
+
<dict>
|
|
177
|
+
<key>SuccessfulExit</key>
|
|
178
|
+
<false/>
|
|
179
|
+
</dict>
|
|
180
|
+
<key>ThrottleInterval</key>
|
|
181
|
+
<integer>300</integer>
|
|
182
|
+
<key>StandardErrorPath</key>
|
|
183
|
+
<string>{_xml(str(log))}</string>
|
|
184
|
+
<key>StandardOutPath</key>
|
|
185
|
+
<string>{_xml(str(log))}</string>
|
|
186
|
+
</dict>
|
|
187
|
+
</plist>
|
|
188
|
+
"""
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def systemd_unit(cmd: list[str]) -> str:
|
|
192
|
+
exe = " ".join(f'"{c}"' if " " in c else c for c in [*cmd, "run"])
|
|
193
|
+
return f"""[Unit]
|
|
194
|
+
Description=Radio Booth (Booth Engineer)
|
|
195
|
+
After=network-online.target
|
|
196
|
+
|
|
197
|
+
[Service]
|
|
198
|
+
ExecStart={exe}
|
|
199
|
+
Restart=on-failure
|
|
200
|
+
RestartSec=30
|
|
201
|
+
|
|
202
|
+
[Install]
|
|
203
|
+
WantedBy=default.target
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def checked(run, args: list[str]) -> None:
|
|
208
|
+
"""Run a service command; a failure becomes an OSError, so setup falls back to running Booth itself."""
|
|
209
|
+
done = run(args, capture_output=True, text=True)
|
|
210
|
+
if getattr(done, "returncode", 0):
|
|
211
|
+
why = (getattr(done, "stderr", "") or "").strip().splitlines()
|
|
212
|
+
raise OSError(f"{' '.join(args[:2])} failed" + (f": {why[-1]}" if why else ""))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _xml(text: str) -> str:
|
|
216
|
+
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _windows_paths(home: Path) -> tuple[Path, Path]:
|
|
220
|
+
roaming = Path(os.environ.get("APPDATA") or home / "AppData" / "Roaming")
|
|
221
|
+
programs = roaming / "Microsoft" / "Windows" / "Start Menu" / "Programs"
|
|
222
|
+
return programs, programs / "Startup"
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _mac_paths(home: Path) -> tuple[Path, Path]:
|
|
226
|
+
return macapp.agent_plist(home), home / "Library" / "Logs"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def installed(platform: str = sys.platform, home: Path | None = None) -> bool:
|
|
230
|
+
"""Whether Booth is set to start at sign-in."""
|
|
231
|
+
home = home or Path.home()
|
|
232
|
+
if platform == "win32":
|
|
233
|
+
startup = _windows_paths(home)[1]
|
|
234
|
+
return (startup / "Radio Booth.lnk").exists() or (startup / "Radio Booth.cmd").exists()
|
|
235
|
+
if platform == "darwin":
|
|
236
|
+
return _mac_paths(home)[0].exists()
|
|
237
|
+
return (home / ".config" / "systemd" / "user" / f"{NAME}.service").exists()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def outdated(platform: str = sys.platform, home: Path | None = None) -> bool:
|
|
241
|
+
"""Set to start the way versions before 0.2 did (`booth run` in a window), not as the app."""
|
|
242
|
+
home = home or Path.home()
|
|
243
|
+
if platform == "win32":
|
|
244
|
+
return (_windows_paths(home)[1] / "Radio Booth.cmd").exists()
|
|
245
|
+
if platform == "darwin":
|
|
246
|
+
plist = _mac_paths(home)[0]
|
|
247
|
+
try:
|
|
248
|
+
return plist.is_file() and "<string>app</string>" not in plist.read_text(encoding="utf-8")
|
|
249
|
+
except OSError:
|
|
250
|
+
return False
|
|
251
|
+
return False
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def start_menu(home: Path | None = None, cmd: list[str] | None = None, make=None) -> None:
|
|
255
|
+
"""Windows: the Start-menu entry that opens Booth's page, whether or not Booth starts at sign-in. Made
|
|
256
|
+
each time the app starts, so it's there for settings carried over from an older version too, and always
|
|
257
|
+
points at the app as it is now."""
|
|
258
|
+
home = home or Path.home()
|
|
259
|
+
programs = _windows_paths(home)[0]
|
|
260
|
+
programs.mkdir(parents=True, exist_ok=True)
|
|
261
|
+
(programs / "Radio Booth setup.lnk").unlink(missing_ok=True) # setup is on Booth's page now
|
|
262
|
+
write_shortcut(programs / "Radio Booth.lnk", cmd or command(), "", make)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def install(
|
|
266
|
+
platform: str = sys.platform,
|
|
267
|
+
home: Path | None = None,
|
|
268
|
+
run=subprocess.run,
|
|
269
|
+
cmd: list[str] | None = None,
|
|
270
|
+
make=None, # how a Windows shortcut is made (tests use a stand-in)
|
|
271
|
+
) -> str:
|
|
272
|
+
"""Set Booth to start at sign-in; returns what was done, in words."""
|
|
273
|
+
home = home or Path.home()
|
|
274
|
+
cmd = cmd or command()
|
|
275
|
+
if platform in ("win32", "darwin"):
|
|
276
|
+
cmd = keep_app(cmd, home, platform)
|
|
277
|
+
if platform == "win32":
|
|
278
|
+
programs, startup = _windows_paths(home)
|
|
279
|
+
startup.mkdir(parents=True, exist_ok=True)
|
|
280
|
+
(startup / "Radio Booth.cmd").unlink(missing_ok=True) # how versions before 0.2 started
|
|
281
|
+
(programs / "Radio Booth setup.lnk").unlink(missing_ok=True) # setup is on Booth's page now
|
|
282
|
+
write_shortcut(startup / "Radio Booth.lnk", cmd, " ".join(APP_ARGS), make)
|
|
283
|
+
write_shortcut(programs / "Radio Booth.lnk", cmd, "", make)
|
|
284
|
+
return (
|
|
285
|
+
"Radio Booth will start by itself, in the background, each time you sign in to Windows. To see "
|
|
286
|
+
"its page, open Radio Booth from the Start menu."
|
|
287
|
+
)
|
|
288
|
+
if platform == "darwin":
|
|
289
|
+
plist, logs = _mac_paths(home)
|
|
290
|
+
plist.parent.mkdir(parents=True, exist_ok=True)
|
|
291
|
+
logs.mkdir(parents=True, exist_ok=True)
|
|
292
|
+
plist.write_text(mac_plist(cmd, logs / "radiobooth.log"), encoding="utf-8")
|
|
293
|
+
if os.environ.get("XPC_SERVICE_NAME") != macapp.BUNDLE_ID:
|
|
294
|
+
run(["launchctl", "unload", str(plist)], capture_output=True) # an older copy, if any
|
|
295
|
+
checked(run, ["launchctl", "load", str(plist)])
|
|
296
|
+
# else this is that sign-in item, running now: unloading it would stop this very Booth. It's still
|
|
297
|
+
# loaded, and the new file is what starts Booth next time.
|
|
298
|
+
done = "Radio Booth now runs in the background and starts each time you sign in to this Mac."
|
|
299
|
+
if macapp.bundle(cmd[0]):
|
|
300
|
+
# The bare program the Mac download kept before it was an app; nothing starts it any more.
|
|
301
|
+
app_home(platform, home).unlink(missing_ok=True)
|
|
302
|
+
done += " To see its page, open Radio Booth from your Applications folder."
|
|
303
|
+
return done
|
|
304
|
+
units = home / ".config" / "systemd" / "user"
|
|
305
|
+
units.mkdir(parents=True, exist_ok=True)
|
|
306
|
+
(units / f"{NAME}.service").write_text(systemd_unit(cmd), encoding="utf-8")
|
|
307
|
+
checked(run, ["systemctl", "--user", "daemon-reload"])
|
|
308
|
+
checked(run, ["systemctl", "--user", "enable", f"{NAME}.service"])
|
|
309
|
+
checked(run, ["systemctl", "--user", "restart", f"{NAME}.service"]) # picks up new settings too
|
|
310
|
+
return f"Radio Booth now runs as the systemd user service {NAME!r} and starts when you sign in."
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def remove(platform: str = sys.platform, home: Path | None = None, run=subprocess.run) -> str:
|
|
314
|
+
"""Stop starting Booth at sign-in. A Booth running now keeps running."""
|
|
315
|
+
home = home or Path.home()
|
|
316
|
+
if platform == "win32":
|
|
317
|
+
startup = _windows_paths(home)[1]
|
|
318
|
+
for name in ("Radio Booth.lnk", "Radio Booth.cmd"):
|
|
319
|
+
(startup / name).unlink(missing_ok=True)
|
|
320
|
+
return (
|
|
321
|
+
"Radio Booth won't start by itself any more. Open Radio Booth from the Start menu when you"
|
|
322
|
+
" want it."
|
|
323
|
+
)
|
|
324
|
+
if platform == "darwin":
|
|
325
|
+
plist = _mac_paths(home)[0]
|
|
326
|
+
# Not `launchctl unload`: that would stop this Booth too, if launchd started it.
|
|
327
|
+
plist.unlink(missing_ok=True)
|
|
328
|
+
return (
|
|
329
|
+
"Radio Booth won't start by itself any more. Open Radio Booth from Applications when you want it."
|
|
330
|
+
)
|
|
331
|
+
unit = home / ".config" / "systemd" / "user" / f"{NAME}.service"
|
|
332
|
+
run(["systemctl", "--user", "disable", f"{NAME}.service"], capture_output=True)
|
|
333
|
+
unit.unlink(missing_ok=True)
|
|
334
|
+
return "Radio Booth won't start by itself any more."
|