diff --git a/CLAUDE.md b/CLAUDE.md index e040702..f0da26c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,6 +64,8 @@ pi_writer.py → pi_image.py (cloud-init SD card, installs server.py as a system Its settings sit in the access section; in the apps it needs remote access, since the app itself only listens on 127.0.0.1. * **Preset looks** – `Device.looks` keeps `colors`/`linknames` per preset name; `sync_look` swaps them whenever a read of the DSP shows another name (the DSP has no preset IDs: same name = same look). Preset files carry them as `look`. +* **Reset** (`App.reset_config`, `POST /api/reset`) – stops all devices before anything else and sends them nothing, then defaults from + a fresh `App`. Refused during an audio test or mute all, because the DSP would stay changed. Keeps `config.before-reset.json`. * **Network search** – `App.scan_network` probes the local /24 networks on TCP 9761 (handshake + device info), skipping DSPs this app is connected to. * **Copy settings / mute all** – `App.copy_settings` (`POST /api/copy`, groups level/filters/eq/dynamics/routing) and diff --git a/README.md b/README.md index 25f0fc1..70cb144 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ Control both devices at the same time from your phone, tablet or computer – ov * **Custom logo** – your own logo top left and as the browser icon (settings → Logo; PNG/JPG/WebP/SVG, ideally square, ≥ 64×64 px) * **Fits every screen** – menu in the top bar on wide screens, a sidebar when the window gets narrow, a bottom bar on phones * **Mute all** – one button mutes every channel of every connected DSP; releasing it unmutes only what was open before +* **Reset app settings** – back to a fresh app (⚙ → Backup); DSPs are disconnected first and nothing on them changes * **Settings backup** – devices, amplifier data, SoundField plan, PIN and remote access in one file * **Device lock** – DSPs locked with their 4-character code (e.g. `A1BA`) are detected on connect and the app asks for the code; optionally it remembers the code and unlocks automatically. A new code can be set under ⚙ diff --git a/server.py b/server.py index b8fe9d8..6088396 100644 --- a/server.py +++ b/server.py @@ -16,6 +16,7 @@ import math import mimetypes import re import secrets +import shutil import socket import struct import sys @@ -406,6 +407,34 @@ class App: "limiter": self.limiter, "remote": self.remote, "soundfield": self.soundfield, "logo": self.logo, "dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en, "dj_margin": self.dj_margin, "dj_cal": self.dj_cal} + async def reset_config(self): + """Back to a fresh app. Only the app: the DSPs get disconnected first and receive nothing.""" + if any(d.test_active for d in self.real_devices()): + raise ValueError("End the audio test first: the DSP would stay at the lowered level") + if self.mute_all["active"]: + raise ValueError("Release mute all first: the DSPs would stay muted") + self.demo_resume = set() + if self.demo["enabled"]: + await self.stop_demo() + for dev in self.real_devices(): + await dev.stop() + del self.devices[dev.id] + self.broadcast({"type": "removed", "device": dev.id}) + if self.config_path.exists(): # one way back, in case this was a mistake + shutil.copyfile(self.config_path, self.config_path.with_name("config.before-reset.json")) + sessions = {k: v for k, v in self.sessions.items() if k in self.app_sessions} + keep = {"config_path", "clients", "app_token", "app_sessions", "remote_server", "remote_writers", "failures", "dj_streams"} + for name, value in vars(App(self.config_path)).items(): + if name not in keep: + setattr(self, name, value) + self.sessions = sessions + self.apply_config({}) + self.save() + self.broadcast({"type": "reset"}) + await asyncio.sleep(0.2) # let the phones hear it before their connection goes + if self.app_token: + await self.start_remote() + async def restore_config(self, doc: dict, session: str): if not isinstance(doc, dict) or doc.get("format") != CONFIG_FORMAT: raise ValueError("Not a DSP Control settings backup") @@ -1293,6 +1322,16 @@ class App: if path == "/api/pin" and method == "POST": await self.respond_json(writer, *await self.change_pin(session, data)) return + if path == "/api/reset" and method == "POST": + if not is_app and not self.check_pin(str(data.get("pin", ""))): + await self.respond_json(writer, 400, {"error": "Wrong PIN"}) + else: + try: + await self.reset_config() + await self.respond_json(writer, 200, {"ok": True}) + except ValueError as e: + await self.respond_json(writer, 400, {"error": str(e)}) + return if path == "/api/backup": if method == "GET": await self.respond_json(writer, 200, self.export_config()) diff --git a/static/app.js b/static/app.js index 21f3dd9..a6b00f8 100644 --- a/static/app.js +++ b/static/app.js @@ -2220,6 +2220,34 @@ function deviceForm(d) { } // App settings backup: devices, amplifiers/limiter data, PIN, remote access (not the DSP presets) +// a fresh app: what this browser remembers goes as well +function appWasReset() { + try { Object.keys(localStorage).filter(k => k.startsWith("dsp.")).forEach(k => localStorage.removeItem(k)); sessionStorage.clear(); } catch { /* private mode */ } + location.replace(S.isApp ? "/?start=app&lang=en" : "/"); +} + +async function resetDialog() { + const letters = "ABCDEFGHJKMNPQRSTUVWXYZ"; // no I, L and O: easy to mistake + const code = [0, 1].map(() => letters[Math.floor(Math.random() * letters.length)]).join(""); + const matches = () => input.value.trim().toUpperCase() === code; + const input = h("input", { type: "text", class: "code resetcode", maxlength: 2, autocomplete: "off", autocapitalize: "characters", spellcheck: "false", "aria-label": t("Letters"), + oninput: () => { document.querySelector("#modal .dlg-actions button:last-child").disabled = !matches(); } }); + const pin = h("input", { type: "password", inputmode: "numeric", maxlength: 4, autocomplete: "off", placeholder: "••••" }); + const stuck = S.order.map(id => S.devices[id]).filter(d => !d.demo && d.test_saved && d.status !== "online").map(d => d.name); + const open = modal({ title: t("Reset all app settings?"), + body: h("div", { class: "form" }, + h("p", { class: "dlg-text" }, t("All DSPs are disconnected at once, then this app starts fresh: DSP list, colours and group names, amplifiers, SoundField plan, dashboard, DJ Brake, remote access and language are gone, and the PIN is 1234 again.")), + h("p", { class: "dlg-text" }, h("b", {}, t("Nothing changes on the DSPs: their settings and presets stay as they are."))), + stuck.length ? h("p", { class: "dlg-text resetwarn" }, t("{names} still has the lowered levels of an interrupted audio test. The app can no longer undo that after the reset.", { names: stuck.join(", ") })) : null, + S.isApp ? null : h("label", {}, t("Current PIN"), pin), + h("div", { class: "resetcheck" }, h("span", {}, t("To confirm, type these letters:")), h("b", { class: "resetletters", "aria-label": code }, code), input)), + actions: [{ label: t("Cancel") }, { label: t("Reset"), primary: true, cls: "danger-on", value: () => matches() ? true : undefined }] }); + document.querySelector("#modal .dlg-actions button:last-child").disabled = true; + if (!await open) return; + try { await api("POST", "/api/reset", { pin: pin.value }); appWasReset(); } + catch (e) { toast(t("Error: ") + trMsg(e.message)); } +} + function backupCard() { const exportCfg = async () => { try { if (await saveFile(`DSP-Control-${t("Settings")}_${today()}.json`, await api("GET", "/api/backup"))) toast(t("Settings backed up")); } @@ -2248,7 +2276,8 @@ function backupCard() { return h("div", { class: "card" }, h("h3", {}, t("App settings")), h("p", { class: "info" }, t("Saves devices, amplifiers & limiter calculator, PIN and remote access to a file. ") + t("The settings inside the DSPs are saved per device via “File…” at the top.")), - h("div", { class: "row" }, h("button", { onclick: exportCfg }, t("Back up…")), h("button", { onclick: restore }, t("Restore…")))); + h("div", { class: "row" }, h("button", { onclick: exportCfg }, t("Back up…")), h("button", { onclick: restore }, t("Restore…")), + h("button", { class: "danger", onclick: resetDialog }, t("Reset all app settings…")))); } // Desktop app only: let phones/tablets on the LAN use this PC as server (they need the PIN) @@ -2727,6 +2756,8 @@ function connectEvents() { sfOnRemote(ev.data); break; case "dashboard": dashRemote(ev.data); break; + case "reset": + appWasReset(); break; case "djbrake": S.djbrake = ev.enabled; S.djIgnore = ev.ignore; S.djHint = ev.hint; S.djHintEn = ev.hint_en; S.djMargin = ev.margin; if (S.settings && !S.busy) render(); break; case "logo": diff --git a/static/dashboard.js b/static/dashboard.js index 34f9422..4c6a408 100644 --- a/static/dashboard.js +++ b/static/dashboard.js @@ -4,17 +4,13 @@ // Every module only looks: nothing here changes a DSP. Browsing (channel, EQ band) stays in this session. const DASH_ROW = 40; // grid row + gap in px, see .dash -const DASH_DEFAULT = () => [ - { type: "status", w: 4 }, { type: "meters", w: 8 }, - { type: "curve", w: 8 }, { type: "mixer", w: 4 }, -].map((m, i) => ({ id: `m${i}`, cfg: {}, ...m })); let dashEdit = false, dashTimer = 0, dashSaveTimer = 0; // dragging modules around is no good on a touchscreen: there only their settings can be changed const dashTouch = () => matchMedia("(pointer: coarse)").matches; const dashBrowse = new Map(); // module id -> { kind, idx, band } -const dashMods = () => S.dash || (S.dash = DASH_DEFAULT()); +const dashMods = () => S.dash || (S.dash = []); const dashDevs = () => S.order.map(id => S.devices[id]).filter(d => d && (!d.demo || S.demo.enabled)); // the chosen DSP, or the first one if it is gone (e.g. while demo mode is on) const dashDev = m => S.devices[m.cfg.device] && dashDevs().includes(S.devices[m.cfg.device]) ? S.devices[m.cfg.device] : dashDevs()[0]; @@ -408,7 +404,7 @@ function viewDash() { viewOnly() ? null : h("button", { class: dashEdit ? "on" : "", onclick: () => { dashEdit = !dashEdit; render(); } }, dashEdit ? t("Done") : dashTouch() ? t("Widget settings") : t("Customise"))), dashEdit && !dashTouch() ? dashPalette() : null, mods.length ? h("div", { class: "dash" + (dashEdit && !dashTouch() ? " editing" : "") }, mods.map(dashModule)) - : h("div", { class: "dash" + (dashEdit ? " editing" : "") }, h("div", { class: "dmod dblank", style: dashSizeStyle(12, 4) }, t("Nothing here yet – press “Customise” and add modules."))), + : h("div", { class: "dash" + (dashEdit ? " editing" : "") }, h("div", { class: "dmod dblank", style: dashSizeStyle(12, 4) }, dashTouch() ? t("Nothing here yet – you can add modules on a computer.") : t("Nothing here yet – press “Customise” and add modules."))), ]; } diff --git a/static/i18n.js b/static/i18n.js index 50aa983..379675f 100644 --- a/static/i18n.js +++ b/static/i18n.js @@ -707,6 +707,16 @@ const DE = { "Forget learned levels": "Gelernte Pegel vergessen", "Colours and group names belong to the loaded preset (by its name) and come back when you load it.": "Farben und Gruppennamen gehören zum geladenen Preset (über seinen Namen) und kommen beim Laden wieder.", "Widget settings": "Widget-Einstellungen", + "Reset all app settings…": "Alle App-Einstellungen zurücksetzen…", + "Reset all app settings?": "Alle App-Einstellungen zurücksetzen?", + "All DSPs are disconnected at once, then this app starts fresh: DSP list, colours and group names, amplifiers, SoundField plan, dashboard, DJ Brake, remote access and language are gone, and the PIN is 1234 again.": "Alle DSPs werden sofort getrennt, dann startet die App frisch: DSP-Liste, Farben und Gruppennamen, Verstärker, SoundField-Plan, Dashboard, DJ Brake, Fernzugriff und Sprache sind weg, und die PIN ist wieder 1234.", + "Nothing changes on the DSPs: their settings and presets stay as they are.": "An den DSPs ändert sich nichts: Ihre Einstellungen und Presets bleiben, wie sie sind.", + "{names} still has the lowered levels of an interrupted audio test. The app can no longer undo that after the reset.": "{names} hat noch die abgesenkten Pegel eines abgebrochenen Audiotests. Nach dem Zurücksetzen kann die App das nicht mehr rückgängig machen.", + "To confirm, type these letters:": "Zum Bestätigen diese Buchstaben eingeben:", + "Letters": "Buchstaben", + "Nothing here yet – you can add modules on a computer.": "Noch nichts da – Module kannst du am Computer hinzufügen.", + "End the audio test first: the DSP would stay at the lowered level": "Beende zuerst den Audiotest: Der DSP würde sonst auf dem abgesenkten Pegel bleiben", + "Release mute all first: the DSPs would stay muted": "Hebe zuerst „Alle stumm“ auf: Die DSPs würden sonst stumm bleiben", }; const DE_PATTERNS = [ diff --git a/static/style.css b/static/style.css index def4a04..8e4f82a 100644 --- a/static/style.css +++ b/static/style.css @@ -1045,3 +1045,8 @@ label.chk input { flex: none; width: 18px; height: 18px; margin: 1px 0 0; accent .docui { padding: 0 4px; } html { touch-action: pan-x pan-y; } .djlim > button.small { margin-top: 8px; } +.resetcheck { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; margin-top: 12px; } +.resetcheck > span { flex: 1 1 100%; color: var(--dim); } +.resetletters { padding: 6px 14px; border-radius: 8px; font: 700 22px ui-monospace, Menlo, Consolas, monospace; letter-spacing: .25em; color: var(--text); background: var(--panel3); user-select: none; -webkit-user-select: none; } +input.resetcode { width: 4.5em; font-size: 20px; text-transform: uppercase; } +.resetwarn { color: var(--warn); } diff --git a/tests/test_protocol.py b/tests/test_protocol.py index 0eccefe..1787bc0 100644 --- a/tests/test_protocol.py +++ b/tests/test_protocol.py @@ -241,6 +241,32 @@ def test_dj_brake_follows_music(): assert abs(again.dj_cal["x:0"] - app.dj_cal["x:0"]) < 0.01 +def test_reset_config(): + import asyncio, json, server, tempfile + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "c.json" + app = server.App(path) + app.load() + app.set_pin("9999", save=False) + app.djbrake, app.lang, app.dj_cal = True, "de", {"x:0": 5.0} + app.dashboard = {"modules": []} + app.app_token = "t" + app.app_sessions, app.sessions = {"a"}, {"a": 9e12, "b": 9e12} + app.save() + app.mute_all["active"] = True + try: + asyncio.run(app.reset_config()) + raise AssertionError("mute all must block the reset") + except ValueError: + assert app.djbrake + app.mute_all["active"] = False + app.remote["enabled"] = False + asyncio.run(app.reset_config()) + assert not app.djbrake and app.lang == "" and app.dashboard is None and app.dj_cal == {} and app.check_pin("1234") + assert app.app_token == "t" and app.app_sessions == {"a"} and set(app.sessions) == {"a"} + assert json.loads(path.with_name("config.before-reset.json").read_text())["djbrake"] is True + + def test_looks_follow_presets(): from dsp.device import Device d = Device("x", "x", "127.0.0.1")