feat: add multi-user support for favorites management and room clock synchronization

- Implemented a new API endpoint for retrieving and managing user favorites in /api/users.
- Added functionality for admins to edit the shared "main" user's favorites.
- Created a one-shot DB smoke test script for verifying multi-user kiosk migrations.
- Introduced a RoomClock class for synchronizing server time across clients using WebSocket.
This commit is contained in:
Marco Mooren
2026-05-13 13:53:12 +02:00
parent f6cdfd975c
commit 29423288ca
41 changed files with 4229 additions and 275 deletions

View File

@@ -17,21 +17,23 @@ import { api } from '../shared/api.js';
import { connectWs } from '../shared/ws.js';
import { el, clear } from '../shared/dom.js';
import { Player } from '../player.js';
import { RoomClock } from '../shared/clock.js';
import { mountVisualizer } from './visualizer.js';
import { showStartModal, autoplayDismissed } from '../shared/playGate.js';
import { mountDebugPane } from '../shared/debug.js';
// Fake list mirrors what a typical desktop sees. Used only when no native
// bridge is present (i.e. running in a normal browser tab, not Electron).
const FAKE_DEVICES = [
{ id: 'default', label: 'System default', kind: 'speakers' },
{ id: 'speakers-internal', label: 'Built-in speakers', kind: 'speakers' },
{ id: 'headphones-jack', label: 'Headphones (3.5mm)', kind: 'headphones' },
{ id: 'hdmi-tv', label: 'HDMI Living-room TV', kind: 'hdmi' },
{ id: 'bt-marshall', label: 'Bluetooth Marshall Stanmore', kind: 'bluetooth' },
{ id: 'usb-audient', label: 'USB Audient EVO 4', kind: 'usb' }
];
// The audio-output picker and the spectrum visualiser only work inside the
// Electron shell (real device enumeration, plus the CORS-rewrite that lets
// AnalyserNode read PCM from cross-origin radio streams). In a plain browser
// tab those features are hidden — the master still functions as the room's
// authoritative source for any connected kiosks.
const app = document.getElementById('app');
const state = {
user: null,
users: [], // public list of all users (for the tab strip + avatar picker)
mainUser: null, // the shared/house identity, e.g. morphix
device: { trusted: false, users: [] }, // trusted-device whitelist for fast switching
rooms: [],
roomSlug: null,
room: null,
@@ -42,15 +44,46 @@ const state = {
loading: false, volume: 0.7, error: null
},
voteStats: null,
favorites: [],
favorites: [], // current viewer's *own* favorites (write target, heart indicator)
tabUser: null, // username currently shown in the favorites strip (defaults to self)
tabFavorites: [], // favorites for the active tab (== state.favorites when tabUser is self)
tabLoading: false,
favGenre: '', // active genre filter for favorites browser
showOutputs: false, // output picker is hidden behind a button
showAvatars: false, // avatar / user-switch popover
session: null // { id, stationId, startedAt } for the open play_history row
};
const native = window.oradioNative || null;
let ws = null;
let player = null;
// Mandatory click-to-start in plain browsers — same scheme as the kiosk.
// Auto-resume on cold-boot (hello-state replay) must wait for the user to
// tap Start before calling player.audio.play(). Electron bypasses via
// autoplayDismissed().
let gestureUnlocked = false;
function markGesture() { gestureUnlocked = true; }
async function ensureGesture(stationName, subtitle) {
if (gestureUnlocked) return true;
if (autoplayDismissed()) { gestureUnlocked = true; return true; }
try {
await showStartModal({
stationName: stationName || 'Radio',
subtitle: subtitle || 'Tap Start to enable audio.',
onStart: () => { gestureUnlocked = true; }
});
return gestureUnlocked;
} catch {
return false;
}
}
// Master command de-dup: track the station id of the in-flight play (so a
// second cmd for the same id is a no-op) and a generation counter so a slow
// /api/stations/:id fetch from an OLD cmd can't call playStation() after a
// newer cmd has already been handled.
let _pendingStationId = null;
let _cmdGen = 0;
const clock = new RoomClock();
async function bootstrap() {
try { state.user = await api.get('/api/auth/me'); }
@@ -66,30 +99,105 @@ async function bootstrap() {
|| (state.rooms[0] && state.rooms[0].slug)
|| `u-${state.user.id}`;
// Initial device list.
if (native?.listOutputs) {
state.devices.list = await native.listOutputs();
state.devices.current = (await native.getCurrent()) || state.devices.list[0]?.id;
// Initial device list — Electron only. In the browser the picker is
// hidden, so we leave the list empty.
if (native?.isElectron && native.listOutputs) {
try {
state.devices.list = await native.listOutputs();
state.devices.current = (await native.getCurrent()) || state.devices.list[0]?.id || 'default';
} catch (err) {
console.warn('[master] listOutputs failed', err);
state.devices.list = [];
state.devices.current = 'default';
}
native.onCurrentChanged?.((id) => { state.devices.current = id; advertiseDevices(); render(); });
} else {
state.devices.list = FAKE_DEVICES;
state.devices.current = 'default';
state.devices.list = [];
state.devices.current = null;
}
player = new Player({
onState: (s) => {
// Capture the previous snapshot BEFORE merging so we can tell
// whether the change is actually worth broadcasting.
const prev = { ...state.np };
Object.assign(state.np, s);
// Push display truth out to the room.
sendState();
render();
// Push display truth out to the room ONLY on meaningful changes:
// station, playing flag, or volume. The Player emits during the
// loading phase (playing:false, loading:true) used to thrash the
// server-persisted state and cause all peers to see a
// playing-false flicker. We also intentionally do NOT send while
// `loading` is true — onPlayingOnce will send a single state
// with started_at once audio actually starts.
const station = state.np.stationId;
const playing = !!state.np.playing;
const volume = state.np.volume;
const stationOrPlayingChanged = station !== prev.stationId || playing !== !!prev.playing;
const volumeChanged = Math.abs((volume ?? 0) - (prev.volume ?? 0)) > 0.001;
const isLoading = s.loading === true;
// Defensive guard: Player.play() already swallows the pause
// event from its internal stop() via _silentStop, but if any
// other path produces a (stationId=null, playing=false) emit
// mid-switch (e.g. an `error` event), don't broadcast that
// ghost — the kiosks would briefly clear their UI.
const ghostStop = s.playing === false && s.stationId == null && _pendingStationId != null;
if (!isLoading && !ghostStop) {
if (stationOrPlayingChanged) {
// Station / playing transitions are user-visible — send now
// and drop any pending throttled volume broadcast (the
// state we send carries the latest volume).
if (_volumeBroadcastT) { clearTimeout(_volumeBroadcastT); _volumeBroadcastT = null; }
sendState();
} else if (volumeChanged) {
broadcastVolumeSoon();
}
}
scheduleRender();
}
});
// The master IS the anchor: when its <audio> reports its first decoded
// sample for a (new) station, re-broadcast started_at so every peer
// aligns on a real wall-clock instant instead of the server's
// command-time estimate.
player.onPlayingOnce = (station) => {
if (!ws || !station) return;
const startedAt = clock.now ? clock.now() : Date.now();
try {
ws.send({
type: 'state',
stationId: station.id,
playing: true,
volume: state.np.volume,
started_at: startedAt
});
} catch { /* ignore */ }
// Local sync engine should re-target too so the master's own output
// honours the shared deadline.
if (player.sync.enabled) player.updateSyncTarget(startedAt);
else applyMasterSync(startedAt);
};
// Load favorites so the touch browser + heart indicator work.
try { state.favorites = await api.get('/api/me/favorites'); }
catch { state.favorites = []; }
// Multi-user surface: list of all users (tab strip), the main/shared
// identity (pinned tab + "Follow main" target), and this device's
// trusted-user whitelist (for fast switching).
try { state.users = await api.get('/api/auth/users/public'); }
catch { state.users = []; }
try { state.mainUser = await api.get('/api/auth/main'); }
catch { state.mainUser = null; }
try { state.device = await api.get('/api/auth/devices/me'); }
catch { state.device = { trusted: false, users: [] }; }
// Default tab is yourself; the strip pins main first regardless.
state.tabUser = state.user.username;
state.tabFavorites = state.favorites;
openWs();
startSyncPosBroadcast();
mountDebugPane({ player, clock, getWs: () => ws, role: 'master' });
render();
}
@@ -101,15 +209,60 @@ if (typeof window !== 'undefined') {
function openWs() {
if (ws) { try { ws.close(); } catch { } }
clock.detach();
ws = connectWs(handleWs, {
room: state.roomSlug,
kind: 'display',
onOpen: () => advertiseDevices()
});
clock.attachWs(ws);
}
// Every 2 s while audio is actually playing, broadcast a sync-pos snapshot.
// Peers on non-HLS streams use this as the timeline anchor: at server-clock
// `atServerNow` the master's <audio>.currentTime was `masterCT`, so each
// peer projects its own expected position forward from that point. HLS
// peers prefer PROGRAM-DATE-TIME when available and ignore this; the
// snapshot is still useful as a fallback if PDT is missing or skewed.
let _syncPosTimer = null;
function startSyncPosBroadcast() {
if (_syncPosTimer) return;
_syncPosTimer = setInterval(() => {
if (!ws || !player) return;
if (player.audio.paused || player.audio.readyState < 2) return;
const station = state.np.stationId;
if (!Number.isFinite(station)) return;
try {
ws.send({
type: 'sync-pos',
stationId: station,
masterCT: player.audio.currentTime,
atServerNow: clock.now ? clock.now() : Date.now(),
pdtMs: player.hls?.playingDate?.getTime?.() ?? null,
bufferMs: player.sync?.bufferMs ?? null
});
} catch { /* ignore transient send errors */ }
}, 2000);
}
function stopSyncPosBroadcast() {
if (_syncPosTimer) { clearInterval(_syncPosTimer); _syncPosTimer = null; }
}
if (typeof window !== 'undefined') {
window.addEventListener('pagehide', stopSyncPosBroadcast);
}
// The master is the room's authoritative audio source, but it still routes
// its own output through a DelayNode so the shared room deadline
// (startedAt + bufferMs) gives every late-joining listener room to align.
function applyMasterSync(startedAt) {
if (!player) return;
if (startedAt) player.enableSync({ clock, startedAt });
else player.disableSync();
}
function handleWs(msg) {
if (!msg || !msg.type) return;
if (msg.type === 'clock-pong') { clock.handlePong(msg); return; }
switch (msg.type) {
case 'hello': {
state.room = msg.room;
@@ -128,9 +281,21 @@ function handleWs(msg) {
if (typeof rs?.volume === 'number') {
player.setVolume(rs.volume);
}
applyMasterSync(rs?.started_at || null);
render();
return;
}
case 'state': {
// Server echoes our own state plus its canonical started_at; the
// master uses that as the sync anchor too.
if (msg.started_at) {
if (player?.sync?.enabled) player.updateSyncTarget(msg.started_at);
else applyMasterSync(msg.started_at);
} else {
applyMasterSync(null);
}
return;
}
case 'presence':
state.peers = msg.peers || [];
render();
@@ -156,13 +321,31 @@ function handleCommand(msg) {
case 'play': {
const id = Number(msg.stationId);
if (!Number.isFinite(id)) return;
api.get(`/api/stations/${id}`).then((st) => playStation(st)).catch(() => { });
// Idempotency: ignore a play for the station already current OR
// already pending. Without these guards a flood of commands (e.g.
// multiple kiosks racing, or repeated clicks) would call
// playStation() in a loop, each one doing stop()+play() and
// producing audible start/stop thrashing.
if (id === state.np.stationId) return;
if (id === _pendingStationId) return;
_pendingStationId = id;
const gen = ++_cmdGen;
api.get(`/api/stations/${id}`).then((st) => {
// Bail if a newer command superseded this one while the
// station metadata fetch was in flight.
if (gen !== _cmdGen) return;
_pendingStationId = null;
playStation(st);
}).catch(() => {
if (gen === _cmdGen) _pendingStationId = null;
});
return;
}
case 'pause':
player.togglePause();
if (state.np.playing) player.togglePause();
return;
case 'stop':
if (!state.np.stationId) return;
player.stop();
endCurrentSession();
state.np.playing = false;
@@ -171,11 +354,21 @@ function handleCommand(msg) {
render();
return;
case 'volume':
if (typeof msg.value === 'number') player.setVolume(msg.value);
if (typeof msg.value === 'number' && Math.abs(msg.value - state.np.volume) > 0.001) {
player.setVolume(msg.value);
}
return;
case 'setSink':
setSink(String(msg.deviceId || ''));
return;
case 'setSyncBuffer':
if (Number.isFinite(msg.value) && player) {
player.setSyncBufferMs(msg.value);
// The next sync-pos broadcast (within 2s) carries the new
// bufferMs so late joiners and reconnecting peers pick it up
// from `hello.last_sync_pos`.
}
return;
default:
return;
}
@@ -183,6 +376,13 @@ function handleCommand(msg) {
async function playStation(station, { silent } = {}) {
if (!station) return;
// User-initiated playStation calls (station-card click) ARE the
// gesture. Silent/hello-resume paths leave gestureUnlocked false so
// ensureGesture below surfaces the Start modal.
if (!silent) markGesture();
// Any in-flight command for a different station is now stale.
_cmdGen++;
_pendingStationId = null;
// Close any previous session before swapping. We compute the duration
// locally so resumes-after-suspend don't get charged the whole gap.
endCurrentSession();
@@ -193,7 +393,16 @@ async function playStation(station, { silent } = {}) {
plays: station.plays || 0, score: station.score || 0
};
render();
// Mandatory gesture in plain browsers — silent/hello-resume paths
// would otherwise call audio.play() without one and iOS/Chromium
// would refuse. ensureGesture short-circuits once unlocked.
const ok = await ensureGesture(station.name, silent ? 'Tap Start to resume the group audio.' : 'Tap Start to play.');
if (!ok) return;
await player.play(station);
if (player.audio.paused) {
// Gesture confirmed but browser hasn't started yet — try once more.
player.audio.play().catch(() => { });
}
if (!silent) {
try {
const stats = await api.post(`/api/stations/${station.id}/play`);
@@ -229,16 +438,7 @@ function endCurrentSession({ beacon = false } = {}) {
}
function sendState() {
if (!ws || !state.np.stationId) {
ws?.send({
type: 'state',
stationId: state.np.stationId,
playing: !!state.np.playing,
volume: state.np.volume
});
return;
}
ws.send({
ws?.send({
type: 'state',
stationId: state.np.stationId,
playing: !!state.np.playing,
@@ -246,6 +446,55 @@ function sendState() {
});
}
// Volume changes from the slider can fire at 60+ Hz. Coalesce the broadcast
// onto a short trailing timer so dragging produces ~12 messages/sec instead
// of hundreds. Cleared when a station/playing change forces an immediate send.
let _volumeBroadcastT = null;
function broadcastVolumeSoon() {
if (_volumeBroadcastT) return;
_volumeBroadcastT = setTimeout(() => {
_volumeBroadcastT = null;
sendState();
}, 80);
}
// Single rAF gate around render() so a burst of state updates within the same
// frame collapses to one DOM rebuild. Without this, dragging the volume
// slider triggered a render per pointer event, tearing the slider out from
// under the user's pointer.
let _renderScheduled = false;
function scheduleRender() {
if (_renderScheduled) return;
_renderScheduled = true;
requestAnimationFrame(() => {
_renderScheduled = false;
render();
});
}
// `render()` does a full clear+rebuild of the DOM. If we re-render while the
// user is dragging a range slider, the slider element they're holding gets
// destroyed mid-drag and the browser drops the drag. Track active slider
// drags at the document level and have render() bail until the pointer is
// released. After release we trigger one catch-up render.
let _dragLockCount = 0;
function isRangeInput(t) {
return t instanceof HTMLInputElement && t.type === 'range';
}
if (typeof window !== 'undefined') {
document.addEventListener('pointerdown', (e) => {
if (isRangeInput(e.target)) _dragLockCount++;
}, true);
const release = (e) => {
if (isRangeInput(e.target) && _dragLockCount > 0) {
_dragLockCount--;
scheduleRender();
}
};
document.addEventListener('pointerup', release, true);
document.addEventListener('pointercancel', release, true);
}
function advertiseDevices() {
ws?.send({
type: 'devices',
@@ -261,10 +510,12 @@ async function setSink(deviceId) {
catch (err) { console.warn('[master] setOutput failed', err); return; }
}
state.devices.current = deviceId;
// Browser-only fallback: try `audio.setSinkId` if the device id maps to a
// real MediaDevices id. For the fake list this is a no-op visualisation.
if (player?.audio?.setSinkId && /^[a-f0-9]{16,}$/.test(deviceId)) {
try { await player.audio.setSinkId(deviceId); } catch { }
// Route both the audio element AND the AudioContext. Once the WebAudio
// graph is built (always, for the master) audio exits via the context's
// destination — setSinkId on the element alone is silently ignored.
if (native?.isElectron) {
try { await player.setSinkId(deviceId); }
catch (err) { console.warn('[master] setSinkId failed', err); }
}
advertiseDevices();
state.showOutputs = false;
@@ -278,6 +529,7 @@ function countDisplays(peers) {
// ---------- Favorites ----------
function isFavorite(stationId) {
// The heart always reflects the *viewer's* library, not the active tab.
return !!stationId && state.favorites.some((f) => f.id === stationId);
}
@@ -288,6 +540,8 @@ async function toggleFavorite(stationId) {
if (has) await api.del(`/api/me/favorites/${stationId}`);
else await api.put(`/api/me/favorites/${stationId}`, { position: state.favorites.length });
state.favorites = await api.get('/api/me/favorites');
// If you're currently viewing your own tab, refresh that view too.
if (state.tabUser === state.user.username) state.tabFavorites = state.favorites;
render();
} catch (err) {
console.warn('[master] toggleFavorite failed', err);
@@ -296,7 +550,7 @@ async function toggleFavorite(stationId) {
function favoriteGenres() {
const counts = new Map();
for (const s of state.favorites) {
for (const s of state.tabFavorites) {
for (const g of (s.genres || [])) counts.set(g, (counts.get(g) || 0) + 1);
}
return [...counts.entries()]
@@ -305,13 +559,105 @@ function favoriteGenres() {
}
function filteredFavorites() {
if (!state.favGenre) return state.favorites;
return state.favorites.filter((s) => (s.genres || []).includes(state.favGenre));
if (!state.favGenre) return state.tabFavorites;
return state.tabFavorites.filter((s) => (s.genres || []).includes(state.favGenre));
}
// ---------- Favorite tabs (users-as-folders) ----------
/** Ordered list of tabs: main first (★), then self if not main, then others. */
function favoriteTabs() {
const tabs = [];
const seen = new Set();
if (state.mainUser) {
tabs.push({ ...state.mainUser, main: true });
seen.add(state.mainUser.username);
}
if (state.user && !seen.has(state.user.username)) {
tabs.push({ ...state.user, self: true });
seen.add(state.user.username);
}
for (const u of state.users) {
if (!seen.has(u.username)) {
tabs.push(u);
seen.add(u.username);
}
}
// Annotate "self" on whichever tab matches the current viewer.
for (const t of tabs) if (t.username === state.user.username) t.self = true;
return tabs;
}
async function switchTab(username) {
if (!username || username === state.tabUser) return;
state.tabUser = username;
state.favGenre = '';
if (username === state.user.username) {
state.tabFavorites = state.favorites;
render();
return;
}
state.tabLoading = true;
render();
try {
state.tabFavorites = await api.get(`/api/users/${encodeURIComponent(username)}/favorites`);
} catch (err) {
console.warn('[master] failed to load favorites for', username, err);
state.tabFavorites = [];
} finally {
state.tabLoading = false;
render();
}
}
/** Can the viewer write into the currently-shown tab? */
function canEditCurrentTab() {
if (!state.tabUser) return false;
if (state.tabUser === state.user.username) return true;
// Admins can curate the shared/main tab.
return state.user.role === 'admin'
&& state.mainUser && state.tabUser === state.mainUser.username;
}
// ---------- User switching (avatar picker) ----------
async function switchUser(username) {
if (!username || username === state.user.username) {
state.showAvatars = false;
render();
return;
}
try {
await api.post('/api/auth/switch', { username });
} catch (err) {
console.warn('[master] switch failed', err);
alert(err.message || 'Could not switch user');
return;
}
// Hard reload: re-bootstrap so all per-user caches (rooms, favorites, WS) are reset.
location.reload();
}
// ---------- Follow main ----------
async function followMain() {
if (!state.mainUser) return;
const personalSlug = `u-${state.mainUser.id}`;
state.roomSlug = personalSlug;
history.replaceState(null, '', `?room=${encodeURIComponent(personalSlug)}`);
// Make sure it appears in the room dropdown by refetching.
try { state.rooms = await api.get('/api/rooms'); } catch { }
openWs();
render();
}
// ---------- Render ----------
function render() {
// Bail while the user is actively dragging a range slider — see
// `_dragLockCount` for the rationale. The next pointerup will schedule
// a catch-up render.
if (_dragLockCount > 0) return;
// Preserve scroll position of the favorites grid across re-renders so that
// tapping a tile (which triggers a full re-render) does not jump back to top.
const prevFavScroll = app.querySelector('.favs-grid')?.scrollLeft ?? 0;
@@ -337,15 +683,19 @@ function render() {
el('option', { value: r.slug, selected: r.slug === state.roomSlug }, r.name)))
),
el('div', { class: 'pill peers' }, `${state.peers.length} peer${state.peers.length === 1 ? '' : 's'}`),
el('div', { class: 'pill role-pill', title: 'This master is the authoritative audio source for the room.' },
'◉ Broadcasting'),
np.error ? el('div', { class: 'err-banner' }, np.error) : null,
el('div', { class: 'grow' }),
el('button', {
// Output picker: Electron only. In a browser tab the picker would
// be useless (no real device enumeration / sink switching).
native?.isElectron ? el('button', {
class: 'pill out-btn' + (state.showOutputs ? ' active' : ''),
title: 'Audio output',
onClick: () => { state.showOutputs = !state.showOutputs; render(); }
}, '🔊 ', currentDeviceLabel()),
el('div', { class: 'pill' }, native ? 'native' : 'browser'),
el('div', { class: 'pill' }, state.user.username),
}, '🔊 ', currentDeviceLabel()) : null,
renderFollowMainPill(),
renderUserPill(),
),
// Stage: now-playing block (with transport + volume embedded)
@@ -376,6 +726,9 @@ function render() {
}, fav ? '★' : '☆') : null
),
el('div', { class: 'genres' }, ...(st?.genres || []).slice(0, 6).map((g) => el('span', { class: 'tag' }, g))),
// Live spectrum analyser (Electron only). The canvas is
// hooked up after the DOM is appended (see below).
native?.isElectron ? el('canvas', { class: 'np-spectrum', 'data-spectrum': '1' }) : null,
state.voteStats ? el('div', { class: 'stats' },
el('span', {}, '▲ ', el('b', {}, String(state.voteStats.up || 0))),
el('span', {}, '▼ ', el('b', {}, String(state.voteStats.down || 0))),
@@ -388,13 +741,14 @@ function render() {
class: 'ctrl primary',
title: 'Play / pause',
disabled: !st,
onClick: () => player.togglePause()
onClick: () => { markGesture(); player.togglePause(); }
}, np.playing ? '❚❚' : '▶'),
el('button', {
class: 'ctrl',
title: 'Stop',
disabled: !st,
onClick: () => {
markGesture();
player.stop();
endCurrentSession();
state.np.playing = false;
@@ -406,7 +760,15 @@ function render() {
el('span', { class: 'vol-icon' }, '🔊'),
el('input', {
type: 'range', min: 0, max: 1, step: 0.01, value: np.volume,
onInput: (e) => player.setVolume(Number(e.target.value))
onInput: (e) => {
const v = Number(e.target.value);
player.setVolume(v);
// Update the % label inline so it tracks the
// slider while the drag-lock is suppressing
// full renders.
const valEl = e.target.parentNode?.querySelector('.val');
if (valEl) valEl.textContent = Math.round(v * 100) + '%';
}
}),
el('span', { class: 'val' }, Math.round(np.volume * 100) + '%')
)
@@ -419,7 +781,8 @@ function render() {
el('span', {}, p.user?.username || '?')
))
: [el('span', { class: 'peer' }, 'Just you.')])
)
),
renderZonesPanel()
)
)
),
@@ -430,7 +793,8 @@ function render() {
),
// Output picker popover (hidden by default; toggled by topbar button).
state.showOutputs ? renderOutputPopover() : null
native?.isElectron && state.showOutputs ? renderOutputPopover() : null,
state.showAvatars ? renderAvatarPopover() : null
);
app.appendChild(shell);
// Restore favorites grid scroll position after the DOM swap.
@@ -439,6 +803,11 @@ function render() {
if (prevFavScroll) favGrid.scrollLeft = prevFavScroll;
attachDragScroll(favGrid);
}
// Hook up the spectrum visualiser to the freshly-rendered canvas. The
// visualiser module guards against running outside Electron and against
// double-mounting on the same <audio> element.
const canvas = app.querySelector('canvas.np-spectrum');
if (canvas && player) mountVisualizer(canvas, player);
}
// Pointer-drag horizontal scrolling for the favorites strip. Mouse users can
@@ -500,12 +869,65 @@ function scrollFavs(direction) {
grid.scrollBy({ left: direction * delta, behavior: 'smooth' });
}
// Per-zone volume panel: one slider per non-display peer. Master can dim a
// specific kiosk's local audio without touching the room's master volume.
// Sends `command:peerVolume` which the server forwards only to that user.
const _zoneVolumes = new Map(); // userId -> last value (UI memory only)
function renderZonesPanel() {
if (!ws) return null;
const zones = (state.peers || []).filter((p) => p.kind !== 'display');
if (!zones.length) return null;
return el('div', { class: 'zones-panel', title: 'Per-zone (local) volume for each connected client.' },
el('div', { class: 'zones-label' }, 'Zones'),
...zones.map((p) => {
const uid = p.user?.id;
const username = p.user?.username || '?';
const cur = _zoneVolumes.get(uid) ?? 0.7;
return el('div', { class: 'zone-row' },
el('span', { class: 'zone-name', title: `${username} (${p.kind})` }, username),
el('input', {
type: 'range', min: 0, max: 1, step: 0.05, value: cur,
'aria-label': `Volume for ${username}`,
onInput: (e) => {
const v = Number(e.target.value);
_zoneVolumes.set(uid, v);
try { ws.send({ type: 'command', action: 'peerVolume', userId: uid, value: v }); } catch { /* ignore */ }
const valEl = e.target.parentNode?.querySelector('.zone-val');
if (valEl) valEl.textContent = Math.round(v * 100) + '%';
}
}),
el('span', { class: 'zone-val' }, Math.round(cur * 100) + '%')
);
})
);
}
function renderFavoritesCard() {
const tabs = favoriteTabs();
const editable = canEditCurrentTab();
const genres = favoriteGenres();
const favs = filteredFavorites();
const tabName = state.tabUser === state.user.username
? 'My favorites'
: (state.mainUser && state.tabUser === state.mainUser.username)
? `${state.tabUser} (main)`
: state.tabUser;
return el('div', { class: 'card favs-card' },
el('div', { class: 'fav-tabs' }, ...tabs.map((t) => el('button', {
class: 'fav-tab' + (t.username === state.tabUser ? ' active' : '') + (t.main ? ' main' : '') + (t.self ? ' self' : ''),
title: t.username + (t.main ? ' (main / shared)' : '') + (t.self ? ' (you)' : ''),
onClick: () => switchTab(t.username)
},
el('span', { class: 'fav-tab-glyph' }, t.main ? '★' : (t.avatar_emoji || '●')),
el('span', { class: 'fav-tab-name' }, t.username),
))),
el('div', { class: 'favs-header' },
el('h3', {}, `Favorites (${favs.length}${state.favGenre ? `/${state.favorites.length}` : ''})`),
el('h3', {},
tabName,
' ',
el('span', { class: 'fav-count' }, `(${favs.length}${state.favGenre ? `/${state.tabFavorites.length}` : ''})`),
!editable ? el('span', { class: 'fav-readonly', title: 'Read-only — switch to your own tab to edit' }, ' · read-only') : null
),
genres.length ? el('select', {
class: 'genre-filter',
title: 'Filter by genre',
@@ -526,22 +948,26 @@ function renderFavoritesCard() {
onClick: () => scrollFavs(1)
}, '')
),
el('div', { class: 'favs-grid' }, ...(favs.length ? favs.map((s) => {
const art = s.image_display_url || s.image_url;
const active = state.np.stationId === s.id;
return el('button', {
class: 'fav-tile' + (active ? ' active' : ''),
title: s.name,
onClick: () => playStation(s)
},
el('div', {
class: 'fav-art' + (art ? '' : ' empty'),
style: art ? { backgroundImage: `url("${art}")` } : {}
}),
el('div', { class: 'fav-name' }, s.name)
);
}) : [el('div', { class: 'favs-empty' },
state.favGenre ? 'No favorites in this genre.' : 'No favorites yet. Star a station to add it.')]))
el('div', { class: 'favs-grid' }, ...(state.tabLoading
? [el('div', { class: 'favs-empty' }, 'Loading…')]
: favs.length ? favs.map((s) => {
const art = s.image_display_url || s.image_url;
const active = state.np.stationId === s.id;
return el('button', {
class: 'fav-tile' + (active ? ' active' : ''),
title: s.name,
onClick: () => playStation(s)
},
el('div', {
class: 'fav-art' + (art ? '' : ' empty'),
style: art ? { backgroundImage: `url("${art}")` } : {}
}),
el('div', { class: 'fav-name' }, s.name)
);
}) : [el('div', { class: 'favs-empty' },
state.favGenre ? 'No favorites in this genre.'
: editable ? 'No favorites yet. Star a station to add it.'
: `${state.tabUser} has no favorites yet.`)]))
);
}
@@ -576,6 +1002,77 @@ function currentDeviceLabel() {
return d ? d.label : '—';
}
// ---------- User pill + avatar popover + follow-main ----------
function renderUserPill() {
const trusted = !!state.device.trusted;
const others = (state.device.users || []).filter((u) => u.username !== state.user.username);
const canSwitch = trusted && others.length > 0;
return el('button', {
class: 'pill user-pill' + (state.showAvatars ? ' active' : ''),
title: canSwitch ? 'Switch user' : (trusted ? 'No other users on this device' : 'This device is not trusted for fast switching'),
onClick: () => {
if (!canSwitch) return;
state.showAvatars = !state.showAvatars;
render();
}
},
el('span', {
class: 'avatar',
style: state.user.avatar_color ? { background: state.user.avatar_color } : {}
}, state.user.avatar_emoji || state.user.username.slice(0, 1).toUpperCase()),
el('span', {}, state.user.username),
canSwitch ? el('span', { class: 'caret' }, '▾') : null
);
}
function renderFollowMainPill() {
if (!state.mainUser) return null;
const mainSlug = `u-${state.mainUser.id}`;
const following = state.roomSlug === mainSlug;
const isMainHerself = state.user.id === state.mainUser.id;
if (isMainHerself && following) return null; // pointless when main controls main
return el('button', {
class: 'pill follow-pill' + (following ? ' active' : ''),
title: following ? `Following ${state.mainUser.username}'s group` : `Join ${state.mainUser.username}'s group (the house default)`,
onClick: () => { followMain(); }
}, following ? `◉ Following ${state.mainUser.username}` : `↗ Follow ${state.mainUser.username}`);
}
function renderAvatarPopover() {
const users = state.device.users || [];
return el('div', {
class: 'avatar-popover-wrap',
onClick: (e) => { if (e.target === e.currentTarget) { state.showAvatars = false; render(); } }
},
el('div', { class: 'avatar-popover card' },
el('div', { class: 'avatar-popover-head' },
el('h3', {}, 'Switch user'),
el('button', {
class: 'close', title: 'Close',
onClick: () => { state.showAvatars = false; render(); }
}, '×')
),
el('div', { class: 'avatar-list' }, ...users.map((u) => el('button', {
class: 'avatar-row' + (u.username === state.user.username ? ' active' : ''),
onClick: () => switchUser(u.username)
},
el('span', {
class: 'avatar lg',
style: u.avatar_color ? { background: u.avatar_color } : {}
}, u.avatar_emoji || u.username.slice(0, 1).toUpperCase()),
el('span', { class: 'avatar-name' },
u.username,
u.is_main ? el('span', { class: 'avatar-tag' }, ' ★ main') : null,
u.username === state.user.username ? el('span', { class: 'avatar-tag dim' }, ' (signed in)') : null
)
))),
el('div', { class: 'avatar-hint' },
'Add users via the admin panel → Trust device.')
)
);
}
function showLogin() {
clear(app);
app.appendChild(el('div', { class: 'login' },

View File

@@ -267,6 +267,27 @@ body {
color: var(--fg);
}
/* Live spectrum analyser canvas (Electron-only feature). Sits between the
genre tags and the stats line. Height is fixed; internal width is set by
the visualiser module based on devicePixelRatio. */
.master .np .meta .np-spectrum {
display: block;
width: 100%;
height: 72px;
border-radius: 8px;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), rgba(0, 0, 0, 0.25));
border: 1px solid rgba(255, 255, 255, 0.06);
}
/* "Broadcasting" role indicator in the topbar \u2014 makes it explicit that
this window IS the room's audio source. */
.master .topbar .role-pill {
background: rgba(80, 220, 255, 0.10);
border-color: rgba(80, 220, 255, 0.35);
color: rgb(180, 235, 255);
letter-spacing: 0.02em;
}
/* ---------- Transport (embedded in now-playing) ---------- */
.master .np .transport {
display: flex;
@@ -721,3 +742,271 @@ body {
padding: 12px 4px;
text-align: center;
width: 100%;
}
/* ---------- Favorite tabs (users-as-folders) ---------- */
.master .fav-tabs {
display: flex;
gap: 4px;
padding: 6px 12px 0;
overflow-x: auto;
scrollbar-width: none;
}
.master .fav-tabs::-webkit-scrollbar {
display: none;
}
.master .fav-tab {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
background: var(--bg-2);
color: var(--muted);
border: 1px solid var(--line);
border-bottom: none;
font-size: 12px;
cursor: pointer;
white-space: nowrap;
height: 30px;
}
.master .fav-tab:hover {
color: var(--fg);
background: var(--bg-3);
}
.master .fav-tab.active {
background: var(--bg-1);
color: var(--fg);
border-color: var(--accent);
border-bottom-color: var(--bg-1);
margin-bottom: -1px;
}
.master .fav-tab.main .fav-tab-glyph {
color: var(--accent-2);
}
.master .fav-tab.self {
font-weight: 700;
}
.master .fav-tab-glyph {
font-size: 13px;
line-height: 1;
}
.master .fav-count {
color: var(--muted-2);
font-weight: 400;
font-size: 12px;
}
.master .fav-readonly {
color: var(--muted-2);
font-weight: 400;
font-size: 11px;
font-style: italic;
}
/* ---------- User pill + avatar ---------- */
.master .topbar .user-pill {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 10px 4px 4px;
cursor: pointer;
}
.master .topbar .user-pill .avatar {
display: inline-grid;
place-items: center;
width: 24px;
height: 24px;
background: var(--accent);
color: #1a0a00;
font-weight: 800;
font-size: 12px;
line-height: 1;
border-radius: 0;
}
.master .topbar .user-pill .caret {
color: var(--muted-2);
font-size: 10px;
}
.master .topbar .user-pill.active {
border-color: var(--accent);
color: var(--fg);
}
.master .topbar .follow-pill {
cursor: pointer;
}
.master .topbar .follow-pill.active {
border-color: var(--accent);
color: var(--accent-2);
}
/* ---------- Avatar / user-switch popover ---------- */
.avatar-popover-wrap {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.45);
display: grid;
place-items: center;
z-index: 100;
}
.avatar-popover {
min-width: 340px;
max-width: 480px;
background: var(--bg-1);
border: 1px solid var(--line);
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.6);
}
.avatar-popover-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
border-bottom: 1px solid var(--line);
}
.avatar-popover-head h3 {
margin: 0;
font-size: 14px;
font-weight: 700;
letter-spacing: .06em;
text-transform: uppercase;
color: var(--muted);
}
.avatar-popover .close {
background: transparent;
border: none;
color: var(--muted);
font-size: 20px;
cursor: pointer;
line-height: 1;
}
.avatar-list {
display: grid;
gap: 4px;
padding: 8px;
max-height: 60vh;
overflow-y: auto;
}
.avatar-row {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 12px;
background: var(--bg-2);
border: 1px solid var(--line);
color: var(--fg);
cursor: pointer;
text-align: left;
font-size: 14px;
}
.avatar-row:hover {
border-color: var(--accent);
}
.avatar-row.active {
background: var(--bg-3);
cursor: default;
}
.avatar.lg {
display: inline-grid;
place-items: center;
width: 36px;
height: 36px;
background: var(--accent);
color: #1a0a00;
font-weight: 800;
font-size: 16px;
line-height: 1;
}
.avatar-name {
flex: 1;
}
.avatar-tag {
color: var(--accent-2);
font-size: 11px;
font-weight: 600;
letter-spacing: .04em;
}
.avatar-tag.dim {
color: var(--muted-2);
font-weight: 400;
}
.avatar-hint {
padding: 8px 16px 14px;
color: var(--muted-2);
font-size: 11px;
text-align: center;
}
/* === Click-to-start gate modal === */
.play-gate-backdrop {
position: fixed; inset: 0;
background: rgba(0,0,0,0.72);
backdrop-filter: blur(6px);
display: flex; align-items: center; justify-content: center;
z-index: 9999;
}
.play-gate-card {
background: #161a22; border: 1px solid #262b36;
border-radius: 20px; padding: 28px 32px;
min-width: 320px; max-width: 480px;
box-shadow: 0 18px 40px rgba(0,0,0,0.55);
text-align: center; color: #e9ecf2;
}
.play-gate-title { margin: 0 0 8px; font-size: 20px; }
.play-gate-station { color: #ff7a3d; font-weight: 600; margin-bottom: 4px; }
.play-gate-sub { color: #8a90a0; font-size: 13px; margin-bottom: 16px; }
.play-gate-row { display: flex; gap: 12px; justify-content: center; margin-top: 18px; }
.play-gate-start, .play-gate-cancel {
padding: 10px 22px; border-radius: 14px;
border: 1px solid #262b36; background: #1f242e; color: #e9ecf2;
font-size: 15px; cursor: pointer;
}
.play-gate-start { background: #ff7a3d; border-color: #ff7a3d; color: #07080b; font-weight: 600; }
.play-gate-start:hover { filter: brightness(1.1); }
.play-gate-cancel:hover { background: #0e1116; }
.play-gate-dismiss {
display: flex; gap: 8px; align-items: center; justify-content: center;
margin-top: 14px; color: #8a90a0; font-size: 12px; cursor: pointer;
}
/* === Zones panel === */
.zones-panel {
margin-top: 12px;
padding: 10px 12px;
background: #0e1116;
border: 1px solid #262b36;
border-radius: 12px;
display: flex; flex-direction: column; gap: 6px;
}
.zones-label {
font-size: 11px; color: #8a90a0; text-transform: uppercase; letter-spacing: 0.1em;
}
.zone-row {
display: grid; grid-template-columns: 120px 1fr 44px; align-items: center; gap: 10px;
}
.zone-name { font-size: 13px; color: #e9ecf2; overflow: hidden; text-overflow: ellipsis; }
.zone-row input[type=range] { width: 100%; }
.zone-val { font-size: 12px; color: #8a90a0; text-align: right; font-variant-numeric: tabular-nums; }

108
web/master/visualizer.js Normal file
View File

@@ -0,0 +1,108 @@
// Live spectrum analyser for the Master view.
//
// The audio graph (AudioContext + MediaElementSource + AnalyserNode + DelayNode)
// is owned by `web/player.js`. We only ask the player for the analyser node
// and draw it. This way `createMediaElementSource` is called exactly once per
// <audio> element regardless of who needs WebAudio.
//
// Whether the visualiser actually animates depends on the audio source being
// CORS-clean:
// - In Electron, the main process injects `Access-Control-Allow-Origin: *`
// on media responses, so direct Icecast streams work.
// - In a plain browser, the player routes through the same-origin
// `/api/stations/:id/proxy` endpoint whenever room sync is active, which
// also makes the analyser readable. Solo-mode playback in a plain browser
// uses the direct stream and the analyser will read silence-of-data —
// that's a fundamental browser CORS constraint, not a bug here.
let rafId = null;
let analyser = null;
let dataArr = null;
let currentCanvas = null;
let activePlayer = null;
function resizeCanvas(canvas) {
const dpr = window.devicePixelRatio || 1;
const cssW = canvas.clientWidth || canvas.width || 1;
const cssH = canvas.clientHeight || canvas.height || 1;
const w = Math.max(1, Math.round(cssW * dpr));
const h = Math.max(1, Math.round(cssH * dpr));
if (canvas.width !== w) canvas.width = w;
if (canvas.height !== h) canvas.height = h;
}
function draw(canvas) {
// Late binding: the player builds its graph lazily on first 'playing'
// event, so the analyser may only appear a moment after we mount.
if (!analyser && activePlayer) {
analyser = activePlayer.getAnalyser();
if (analyser) dataArr = new Uint8Array(analyser.frequencyBinCount);
}
if (!analyser || !dataArr) return;
resizeCanvas(canvas);
const ctx2d = canvas.getContext('2d');
if (!ctx2d) return;
analyser.getByteFrequencyData(dataArr);
const w = canvas.width;
const h = canvas.height;
ctx2d.clearRect(0, 0, w, h);
// Aggregate the ~512 raw bins into ~64 visual bars for legibility on the
// master stage. We weight lower frequencies (musically more interesting)
// by sampling logarithmically.
const bars = 64;
const binCount = dataArr.length;
const gap = Math.max(1, Math.floor(w / bars / 6));
const barW = (w - gap * (bars - 1)) / bars;
const grad = ctx2d.createLinearGradient(0, h, 0, 0);
grad.addColorStop(0, 'rgba(80, 220, 255, 0.85)');
grad.addColorStop(0.6, 'rgba(140, 120, 255, 0.85)');
grad.addColorStop(1, 'rgba(255, 100, 200, 0.95)');
ctx2d.fillStyle = grad;
for (let i = 0; i < bars; i++) {
const t0 = i / bars;
const t1 = (i + 1) / bars;
const lo = Math.floor(Math.pow(t0, 2) * binCount);
const hi = Math.max(lo + 1, Math.floor(Math.pow(t1, 2) * binCount));
let sum = 0;
for (let j = lo; j < hi && j < binCount; j++) sum += dataArr[j];
const avg = sum / (hi - lo); // 0..255
const norm = Math.pow(avg / 255, 0.7);
const barH = Math.max(2, Math.round(norm * h));
const x = Math.round(i * (barW + gap));
ctx2d.fillRect(x, h - barH, Math.max(1, Math.round(barW)), barH);
}
}
function loop() {
if (!currentCanvas) { rafId = null; return; }
draw(currentCanvas);
rafId = requestAnimationFrame(loop);
}
/**
* Attach the analyser tap to `player.audio` (via the player's shared graph)
* and start drawing into `canvas`. Idempotent.
*/
export function mountVisualizer(canvas, player) {
if (!canvas || !player?.audio) return;
activePlayer = player;
// Tickle the graph so the analyser is wired up before audio starts.
if (typeof player._ensureAudioGraph === 'function') {
try { player._ensureAudioGraph(); } catch { /* CORS — see file header */ }
}
analyser = player.getAnalyser();
if (analyser) dataArr = new Uint8Array(analyser.frequencyBinCount);
currentCanvas = canvas;
if (rafId == null) rafId = requestAnimationFrame(loop);
}
export function unmountVisualizer() {
currentCanvas = null;
if (rafId != null) {
cancelAnimationFrame(rafId);
rafId = null;
}
}