Compare commits

..

9 Commits

49 changed files with 45 additions and 6590 deletions

23
.gitignore vendored
View File

@ -33,26 +33,6 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Finder (MacOS) folder config
.DS_Store
# Xcode
DerivedData/
ios/**/build/
*.xcuserstate
*.xcscmblueprint
*.xccheckout
*.moved-aside
xcuserdata/
*.xcresult
*.xcarchive
*.app
*.appex
*.dSYM
*.dSYM.zip
*.ipa
# Swift Package Manager / Xcode package scratch
.build/
.swiftpm/
tmp/
library_cache.db
musicroom.db
@ -60,6 +40,3 @@ blastoise.db
config.json
*.db-shm
*.db-wal
# machine-local ops notes (see AGENTS.md)
HiddenAgents.md

View File

@ -2,10 +2,6 @@
Synchronized music streaming server built with Bun. Manages "channels" (virtual radio stations) that play through queues sequentially. Clients connect, receive now-playing state, download audio, and sync playback locally.
## HiddenAgents.md
If a `HiddenAgents.md` file exists in this repository, read it as well. It is git-ignored and contains machine-local operational details about how this server is deployed and managed on this host.
## Architecture
### Server
@ -77,15 +73,6 @@ The client uses `track.id` for:
- Fetching audio (`/api/tracks/:trackId`)
- Checking cache status (`M.cachedTracks.has(trackId)`)
## XSS Prevention
All server-controlled strings (channel names, usernames, track titles, playlist names, toast messages) must be escaped before reaching `innerHTML`:
- **`M.escapeHtml(str)`** (`public/utils.js`) — the single shared escaping helper. Do not define local copies.
- **`M.trackComponent.getTitle(track)`** (`public/trackComponent.js`) — the single source of truth for a track's display title. Use it instead of inline `track.title || track.filename` fallbacks.
A Content-Security-Policy header is set on all static responses in `routes/static.ts` (`script-src 'self'`, no inline scripts) as defense-in-depth.
## Client Caching System
### Segment-Based Buffering

34
db.ts
View File

@ -55,17 +55,6 @@ db.run(`
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS user_preferences (
user_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
updated_at INTEGER DEFAULT (unixepoch()),
PRIMARY KEY (user_id, key),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
`);
// Types
export interface User {
id: number;
@ -260,29 +249,6 @@ export function getUserPermissions(userId: number): Permission[] {
return db.query("SELECT * FROM permissions WHERE user_id = ?").all(userId) as Permission[];
}
// User preferences functions (key-value store, per account)
export function getUserPreference(userId: number, key: string): string | null {
const row = db.query("SELECT value FROM user_preferences WHERE user_id = ? AND key = ?").get(userId, key) as { value: string } | null;
return row ? row.value : null;
}
export function getAllUserPreferences(userId: number): Record<string, string> {
const rows = db.query("SELECT key, value FROM user_preferences WHERE user_id = ?").all(userId) as { key: string; value: string }[];
const prefs: Record<string, string> = {};
for (const row of rows) prefs[row.key] = row.value;
return prefs;
}
export function setUserPreference(userId: number, key: string, value: string): void {
db.query(`
INSERT INTO user_preferences (user_id, key, value, updated_at)
VALUES (?, ?, ?, unixepoch())
ON CONFLICT(user_id, key) DO UPDATE SET
value = excluded.value,
updated_at = excluded.updated_at
`).run(userId, key, value);
}
export function getAllUsers(): Omit<User, 'password_hash'>[] {
const users = db.query("SELECT id, username, is_admin, is_guest, created_at FROM users WHERE is_guest = 0").all() as any[];
return users.map(u => ({ ...u, is_admin: !!u.is_admin, is_guest: false }));

File diff suppressed because it is too large Load Diff

View File

@ -1,176 +0,0 @@
# Blastoise API Reference
Blastoise is a synchronized music server. The server owns channel time and
queues; clients play audio locally.
```text
Reference HTTP: http://mhsgroove.peterino.com:3001
Reference WS: ws://mhsgroove.peterino.com:3001
Local HTTP: http://localhost:3001
Local WS: ws://localhost:3001
```
Auth is an HttpOnly cookie named `blastoise_session`. Same-origin browser apps
can use normal `fetch`. Separate-origin browser apps need a same-origin proxy
or CORS with credentials. Native apps must store `Set-Cookie` and send it as
`Cookie` on HTTP and WebSocket requests.
Full details: [api-reference-full.md](./api-reference-full.md)
## Golden Rule
Use `track.id` for every machine operation:
```text
GET /api/tracks/:trackId
```
`track.id` is a content hash like `sha256:...`. `filename` and `title` are only
for display. Queue entries, playlists, cache keys, direct links, and audio URLs
should all use `track.id`.
## Core Shapes
```ts
type PlaybackMode = "once" | "repeat-all" | "repeat-one" | "shuffle";
type Track = {
id: string; filename: string; title: string | null;
artist?: string | null; album?: string | null; duration: number;
replayGainDb?: number | null; replayPeak?: number | null; available?: boolean;
};
type ChannelInfo = {
id: string; name: string; description: string; trackCount: number;
listenerCount: number; listeners: string[]; isDefault: boolean;
createdBy: number | null;
};
type ChannelState = {
track: Track | null; currentTimestamp: number; channelName: string;
channelId: string; description: string; paused: boolean; currentIndex: number;
listenerCount: number; isDefault: boolean; playbackMode: PlaybackMode;
queue?: Track[];
};
type Playlist = {
id: string; name: string; description: string; ownerId: number;
ownerName?: string; isPublic: boolean; shareToken: string | null;
trackIds: string[]; createdAt: number; updatedAt: number;
};
```
`ChannelState.queue` is optional. It appears on WebSocket connect, queue
changes, and periodic refreshes. Keep the last known queue when omitted.
## Startup
```text
GET /api/status
GET /api/auth/me
GET /api/library
GET /api/channels
WS /api/channels/:channelId/ws
```
Choose a channel: saved channel, else `isDefault`, else first channel.
## Endpoints
| Area | Endpoints |
|---|---|
| Status | `GET /api/status` |
| Auth | `POST /api/auth/signup`, `POST /api/auth/login`, `POST /api/auth/logout`, `GET /api/auth/me`, `POST /api/auth/kick-others` |
| Channels | `GET /api/channels`, `POST /api/channels`, `GET/PATCH/DELETE /api/channels/:id` |
| Playback control | `POST /api/channels/:id/jump`, `POST /api/channels/:id/seek`, `POST /api/channels/:id/mode` |
| Queue | `PATCH /api/channels/:id/queue` |
| Library/audio | `GET /api/library`, `GET /api/tracks/:trackId`, `POST /api/upload` |
| Playlists | `GET/POST /api/playlists`, `GET/PATCH/DELETE /api/playlists/:id`, `PATCH /api/playlists/:id/tracks` |
| Sharing | `POST/DELETE /api/playlists/:id/share`, `GET/POST /api/playlists/shared/:token` |
| URL import | `POST /api/fetch`, `POST /api/fetch/confirm`, `GET /api/fetch`, `DELETE /api/fetch/:itemId`, `DELETE /api/fetch` |
Common bodies:
```json
{ "username": "test", "password": "testuser" }
{ "name": "Channel or playlist name", "description": "optional" }
{ "mode": "repeat-all" }
{ "index": 3 }
{ "timestamp": 45.5 }
```
Queue and playlist track mutation:
```json
{ "set": ["sha256:a", "sha256:b"] }
{ "add": ["sha256:c"], "insertAt": 2 }
{ "remove": [3, 4] }
{ "move": [5, 6], "to": 1 }
```
Remove/move use positions, not track IDs. Duplicate tracks are allowed.
Audio supports range requests:
```text
Range: bytes=0-999999
```
## WebSocket
Connect to:
```text
ws://mhsgroove.peterino.com:3001/api/channels/:channelId/ws
```
Client messages:
```json
{ "action": "switch", "channelId": "abc123" }
{ "action": "pause" }
{ "action": "unpause" }
{ "action": "seek", "timestamp": 45.5 }
{ "action": "jump", "index": 3 }
```
Server messages:
```json
{ "type": "channel_list", "channels": [] }
{ "type": "switched", "channelId": "abc123" }
{ "type": "kick", "reason": "Kicked by another session" }
{ "type": "toast", "message": "Added: Song", "toastType": "info" }
{ "type": "scan_progress", "scanning": true, "processed": 1, "total": 20 }
{ "type": "fetch_progress", "id": "job", "status": "downloading", "progress": 50 }
```
Any message without `type` is a `ChannelState`.
Guests can listen and switch channels, but cannot control playback or mutate
queues. Unauthorized WebSocket control messages are ignored.
## Sync Algorithm
On every `ChannelState`:
1. Store the state and `performance.now()`.
2. If `state.queue` exists, replace the local queue cache.
3. If `state.track` is null, pause and clear the player.
4. If `state.track.id` changed, set `audio.src` to `/api/tracks/:trackId` and
seek to `state.currentTimestamp`.
5. If same track and drift is `>= 2s`, seek to `state.currentTimestamp`.
6. If `state.paused`, pause. Otherwise call `audio.play()`.
7. Between WebSocket updates, estimate time as
`state.currentTimestamp + elapsedSeconds`, unless paused.
The server is the source of truth.
## Gotchas
- Some errors are JSON `{ "error": "..." }`; some are plain text. Handle both.
- `GET /api/channels/:id` does not include the queue. WebSocket connect does.
- `POST /api/playlists/shared/:token` copies a playlist; there is no `/copy`.
- Cache by `track.id`, never by filename.
- The server does not decode audio. Clients are synchronized local players.

View File

@ -1,585 +0,0 @@
# Build Me A Blastoise Frontend
This is a pasteable build brief for an LLM or coding agent. It tells the agent
how to build a frontend for a Blastoise music server without needing to read the
server code.
Reference the short API contract in:
```text
docs/api-reference.md
```
Use the full reference for edge cases:
```text
docs/api-reference-full.md
```
## Paste This Prompt Into Your LLM
```text
You are building a frontend for Blastoise, a synchronized music streaming
server. Build the actual app, not a landing page.
Use the Blastoise API documented in docs/api-reference.md. The server owns
channel state and time. The client owns UI, local audio playback, local caching,
and drift correction.
Reference server for testing:
- HTTP base URL: http://mhsgroove.peterino.com:3001
- WebSocket base URL: ws://mhsgroove.peterino.com:3001
Core rule:
- Always identify tracks by track.id.
- Always play audio from /api/tracks/:trackId.
- filename and title are display fields only.
Build an app with:
- Auth screen: login, signup, and guest mode when /api/status says guests are
allowed.
- Channel list: load /api/channels, show listener counts, connect to a channel
WebSocket, support switching channels.
- Now playing player: show current track, time, duration, play/pause, seek,
previous/next, playback mode.
- Library: list tracks from /api/library, search/filter, click a track to play
locally, add tracks to queue.
- Queue: render the current channel queue, highlight currentIndex, add/remove,
move/reorder when the user has control permission.
- Playlists: list /api/playlists, show playlist details, add playlists/tracks
to queue, create/edit/delete owned playlists.
- Optional URL import UI if /api/status reports ytdlp.enabled and
ytdlp.available.
Do not assume the WebSocket always includes queue. It includes queue on connect,
after queue changes, and periodic refreshes. Keep the last known queue until a
new queue arrives.
Do not use alert() or prompt(). Use inline inputs, modals, toasts, or standard
UI components.
Auth uses an HttpOnly cookie named blastoise_session. If this app is served
from the same origin as the server, browser fetch calls can use relative URLs.
If this app is hosted separately, either proxy API requests through the same
origin or add CORS/credentials support to the server.
Implement robust API helpers that handle JSON errors and plain text errors.
Some Blastoise endpoints return JSON error objects, while some return plain
text.
Synced playback algorithm:
1. Connect to WS /api/channels/:channelId/ws.
2. When a normal ChannelState message arrives, store it with performance.now().
3. If state.queue exists, replace the local queue cache.
4. If state.track is null, pause and clear the player.
5. If track.id changed, set audio.src to /api/tracks/:trackId, seek to
state.currentTimestamp, then play unless state.paused.
6. If track.id is the same and abs(audio.currentTime - state.currentTimestamp)
>= 2, seek to state.currentTimestamp.
7. If state.paused, pause locally. If not paused, play locally.
8. Between WebSocket updates, estimate server time as
state.currentTimestamp + elapsedSeconds since receipt, unless paused.
Control actions:
- Send WebSocket { action: "pause" } and { action: "unpause" } for play/pause.
- Send WebSocket { action: "seek", timestamp } for seek.
- Send WebSocket { action: "jump", index } for queue jumps.
- Send WebSocket { action: "switch", channelId } to switch channels.
- Use REST PATCH /api/channels/:channelId/queue for add/remove/move/set queue.
- Use REST POST /api/channels/:channelId/mode for playback mode.
Use track.id for local caching. If you build caching, store complete audio blobs
in IndexedDB under track.id. Range requests to /api/tracks/:trackId are
supported.
Make the interface responsive. Desktop can use panels for Channels, Library,
Queue, and Playlists. Mobile should use tabs or a single-panel navigation.
```
## Implementation Order
Follow this order. It keeps the project useful from the first milestone and
prevents sync bugs from getting buried under UI.
### Step 1: Create The API Client
Build a small wrapper around `fetch`.
Requirements:
- Use relative URLs when the frontend is same-origin.
- Allow an `API_BASE` override for native or separately hosted builds.
- Send `credentials: "include"` for browser fetch calls.
- Parse successful JSON.
- On errors, try JSON first, then fall back to text.
- Expose helpers for JSON, form upload, and raw audio URLs.
Recommended shape:
```ts
const API_BASE = "";
async function apiJson(path: string, options: RequestInit = {}) {
const res = await fetch(API_BASE + path, {
credentials: "include",
...options,
headers: {
...(options.body instanceof FormData ? {} : { "Content-Type": "application/json" }),
...(options.headers || {}),
},
});
const text = await res.text();
let data: any = null;
if (text) {
try {
data = JSON.parse(text);
} catch {
data = text;
}
}
if (!res.ok) {
const message =
typeof data === "object" && data
? data.error || data.message || `HTTP ${res.status}`
: data || `HTTP ${res.status}`;
throw new Error(message);
}
return data;
}
function trackUrl(trackId: string) {
return `${API_BASE}/api/tracks/${encodeURIComponent(trackId)}`;
}
```
Native apps should store `Set-Cookie` from login/signup/me and send it as
`Cookie` in later HTTP and WebSocket requests.
### Step 2: Load Status And Session
On app start:
```text
GET /api/status
GET /api/auth/me
```
Use `/api/status` to decide whether to show:
- guest mode,
- signup,
- URL import.
Use `/api/auth/me` to get the user and effective permissions. When guests are
enabled, this call can create a guest session.
Auth actions:
```text
POST /api/auth/login { username, password }
POST /api/auth/signup { username, password }
POST /api/auth/logout
```
After login, signup, logout, or guest creation, reload:
```text
GET /api/auth/me
GET /api/library
GET /api/channels
GET /api/playlists
```
### Step 3: Load Library And Channels
Load:
```text
GET /api/library
GET /api/channels
```
Store tracks in two forms:
```ts
const library: Track[] = [];
const tracksById = new Map<string, Track>();
```
Pick the channel:
1. Last saved channel ID if still present.
2. The channel with `isDefault: true`.
3. The first channel.
Then connect the WebSocket.
### Step 4: Build WebSocket State Handling
Connect:
```ts
function wsUrl(channelId: string) {
const base = API_BASE || window.location.origin;
const url = new URL(base);
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
url.pathname = `/api/channels/${encodeURIComponent(channelId)}/ws`;
return url.toString();
}
```
Handle message types:
```ts
function onSocketMessage(data: any) {
if (data.type === "channel_list") {
setChannels(data.channels);
return;
}
if (data.type === "switched") {
setCurrentChannelId(data.channelId);
return;
}
if (data.type === "kick") {
disconnectAndShowLoginOrToast(data.reason);
return;
}
if (data.type === "toast") {
showToast(data.message, data.toastType);
return;
}
if (data.type === "scan_progress") {
updateScanProgress(data);
return;
}
if (typeof data.type === "string" && data.type.startsWith("fetch_")) {
updateFetchTask(data);
return;
}
applyChannelState(data);
}
```
Reconnect while the user wants sync. Use a short delay such as 2 or 3 seconds.
### Step 5: Implement The Player Correctly
Keep this state:
```ts
let channelState: ChannelState | null = null;
let channelStateReceivedAt = 0;
let currentTrackId: string | null = null;
let queue: Track[] = [];
```
Apply state:
```ts
async function applyChannelState(state: ChannelState) {
channelState = state;
channelStateReceivedAt = performance.now();
if (state.queue) queue = state.queue;
if (!state.track) {
audio.pause();
currentTrackId = null;
return;
}
const target = state.currentTimestamp;
const nextTrackId = state.track.id;
if (nextTrackId !== currentTrackId) {
currentTrackId = nextTrackId;
audio.src = getPlayableUrl(nextTrackId);
audio.currentTime = target;
} else if (Math.abs(audio.currentTime - target) >= 2) {
audio.currentTime = target;
}
if (state.paused) {
audio.pause();
} else {
audio.play().catch(() => showClickToPlay());
}
}
```
Estimate current synced time for progress UI:
```ts
function syncedTime() {
if (!channelState?.track) return 0;
if (channelState.paused) return channelState.currentTimestamp;
return channelState.currentTimestamp + (performance.now() - channelStateReceivedAt) / 1000;
}
```
Use the audio element's actual `currentTime` while audio is playing, but use
`syncedTime()` while waiting to play, paused, reconnecting, or rendering remote
state.
### Step 6: Add Controls
Use WebSocket for simple channel controls:
```ts
ws.send(JSON.stringify({ action: "pause" }));
ws.send(JSON.stringify({ action: "unpause" }));
ws.send(JSON.stringify({ action: "seek", timestamp }));
ws.send(JSON.stringify({ action: "jump", index }));
ws.send(JSON.stringify({ action: "switch", channelId }));
```
Use REST for queue mutation:
```text
PATCH /api/channels/:channelId/queue
```
Bodies:
```json
{ "add": ["sha256:track"], "insertAt": 3 }
{ "remove": [2] }
{ "move": [5], "to": 1 }
{ "set": ["sha256:a", "sha256:b"] }
```
Use REST for playback mode:
```text
POST /api/channels/:channelId/mode
{ "mode": "shuffle" }
```
If a control returns `403`, show a permission toast. Guests can listen but
cannot control.
### Step 7: Render Library, Queue, And Local Playback
Library:
- Render `/api/library`.
- Search over title, filename, artist, and album.
- Add selected tracks to queue with `PATCH /api/channels/:id/queue`.
- Play a track locally by setting the audio source to `/api/tracks/:trackId`
and disconnecting or marking the player unsynced.
Queue:
- Render the last known `queue`.
- Highlight `currentIndex`.
- Jump by index.
- Remove by index.
- Reorder by index.
- Remember that duplicate track IDs can exist in the queue. Queue operations
that remove or move tracks must use positions, not IDs.
Local playback:
- It is okay to let users preview/play a single track outside channel sync.
- Keep this mode visually distinct from synced playback.
- Offer a "sync" button to reconnect to the selected channel.
### Step 8: Add Playlists
Load:
```text
GET /api/playlists
```
Render two lists:
- `mine`
- `shared`
Details:
```text
GET /api/playlists/:playlistId
```
Join `playlist.trackIds` with `tracksById` from the library to render track
titles.
Common actions:
```text
POST /api/playlists
PATCH /api/playlists/:id
DELETE /api/playlists/:id
PATCH /api/playlists/:id/tracks
POST /api/playlists/:id/share
DELETE /api/playlists/:id/share
POST /api/playlists/shared/:token
```
To add a playlist to queue:
```json
{ "add": ["sha256:a", "sha256:b"] }
```
To play next:
```json
{ "add": ["sha256:a", "sha256:b"], "insertAt": currentIndex + 1 }
```
### Step 9: Add Upload And URL Import
Upload:
```text
POST /api/upload
multipart/form-data field: file
```
Accepted file extensions:
```text
.mp3 .ogg .flac .wav .m4a .aac .opus .wma .mp4
```
URL import is optional. Show it only when:
```ts
status.ytdlp?.enabled && status.ytdlp?.available
```
Flow:
```text
POST /api/fetch { url }
```
If response is `type: "single"`, show a queued/download task.
If response is `type: "playlist"`, show a confirmation modal, then:
```text
POST /api/fetch/confirm { playlistTitle, items }
```
Poll:
```text
GET /api/fetch
```
Listen for WebSocket progress messages:
```text
fetch_progress
fetch_complete
fetch_error
fetch_cancelled
```
### Step 10: Add Optional Local Caching
Caching is not needed for a valid frontend, but it is one of Blastoise's best
features.
Use IndexedDB:
```ts
interface CachedTrack {
id: string;
blob: Blob;
contentType: string;
}
```
Rules:
- Key by `track.id`.
- Never key by filename.
- Prefer cached blob URLs for playback.
- Fall back to `/api/tracks/:trackId`.
- Use range requests to prefetch seek segments if you want a buffer bar.
- Revoke blob URLs when replacing or deleting cached blobs.
Simple mode:
1. When a user plays a track, fetch the full file in the background.
2. Store it in IndexedDB under `track.id`.
3. Next time, play from `URL.createObjectURL(blob)`.
Advanced mode:
1. Divide each track into virtual segments.
2. Use `Range: bytes=start-end` requests to fill missing segments.
3. When all segments are present, download and persist the full blob.
### Step 11: Validate The App
Manual smoke test:
1. Start the server with `bun run server.ts`.
2. Open the frontend.
3. Load status and auth state.
4. Continue as guest or log in with the test user if configured.
5. Load library and channels.
6. Connect to the default channel WebSocket.
7. Confirm first WebSocket state includes `queue`.
8. Confirm audio source uses `/api/tracks/:trackId`.
9. Seek locally after a state update and confirm drift correction snaps back.
10. Pause/unpause from one client and confirm another client follows.
11. Add a track to queue and confirm both clients receive a state with `queue`.
12. Switch channels and confirm the server sends `switched`.
13. Test mobile layout.
Permission smoke test:
1. Use a guest session.
2. Confirm listening works.
3. Try pause/seek/jump.
4. Confirm the UI reports lack of permission or no-ops gracefully.
Playlist smoke test:
1. Create a playlist as a non-guest user.
2. Add tracks to it.
3. Add the playlist to queue.
4. Make it public or generate a share token.
5. Load it through the shared endpoint.
## Common Pitfalls
| Symptom | Likely Cause |
|---|---|
| Audio 404s | The app used `filename` instead of `track.id` in `/api/tracks/:id`. |
| Queue disappears after a state update | The client replaced queue with `undefined`; WebSocket queue is optional. |
| Sync slowly drifts | The client only uses local audio time and does not correct against server timestamps. |
| Guests can see controls that do nothing | Guests cannot control playback even if they can listen. |
| Queue remove deletes the wrong duplicate | The UI removed by track ID instead of queue position. |
| Login works in same-origin dev but not hosted frontend | Cookie auth needs same-origin, a reverse proxy, or CORS with credentials. |
| Shared playlist copy fails | The route is `POST /api/playlists/shared/:token`, with no `/copy` suffix. |
| Native WebSocket connects as guest after login | The client did not send the stored session cookie in the WebSocket request. |
## Minimal Viable Scope
If you want the smallest useful Blastoise frontend, build only:
- `GET /api/auth/me`
- `GET /api/library`
- `GET /api/channels`
- `WS /api/channels/:id/ws`
- `GET /api/tracks/:trackId`
- WebSocket actions: `switch`, `pause`, `unpause`, `seek`, `jump`
That is enough to make a synchronized player.

View File

@ -1,380 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 56;
objects = {
/* Begin PBXBuildFile section */
1A2B3C4D5E6F700000000001 /* BlastoisePingApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000101 /* BlastoisePingApp.swift */; };
1A2B3C4D5E6F700000000002 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000102 /* ContentView.swift */; };
1A2B3C4D5E6F700000000004 /* pixelify_sans.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000105 /* pixelify_sans.ttf */; };
1A2B3C4D5E6F700000000010 /* AppTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000110 /* AppTypes.swift */; };
1A2B3C4D5E6F700000000011 /* AppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000111 /* AppModel.swift */; };
1A2B3C4D5E6F700000000012 /* Theme.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000112 /* Theme.swift */; };
1A2B3C4D5E6F700000000013 /* AuthView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000113 /* AuthView.swift */; };
1A2B3C4D5E6F700000000014 /* HeaderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000114 /* HeaderView.swift */; };
1A2B3C4D5E6F700000000015 /* PlayerDeckView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000115 /* PlayerDeckView.swift */; };
1A2B3C4D5E6F700000000016 /* Panels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000116 /* Panels.swift */; };
1A2B3C4D5E6F700000000017 /* Components.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A2B3C4D5E6F700000000117 /* Components.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
1A2B3C4D5E6F700000000100 /* BlastoisePing.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = BlastoisePing.app; sourceTree = BUILT_PRODUCTS_DIR; };
1A2B3C4D5E6F700000000101 /* BlastoisePingApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlastoisePingApp.swift; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000102 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000103 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000105 /* pixelify_sans.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = Fonts/pixelify_sans.ttf; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000110 /* AppTypes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppTypes.swift; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000111 /* AppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppModel.swift; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000112 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000113 /* AuthView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthView.swift; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000114 /* HeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HeaderView.swift; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000115 /* PlayerDeckView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerDeckView.swift; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000116 /* Panels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels.swift; sourceTree = "<group>"; };
1A2B3C4D5E6F700000000117 /* Components.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Components.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
1A2B3C4D5E6F700000000200 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
1A2B3C4D5E6F700000000300 = {
isa = PBXGroup;
children = (
1A2B3C4D5E6F700000000301 /* BlastoisePing */,
1A2B3C4D5E6F700000000302 /* Products */,
);
sourceTree = "<group>";
};
1A2B3C4D5E6F700000000301 /* BlastoisePing */ = {
isa = PBXGroup;
children = (
1A2B3C4D5E6F700000000101 /* BlastoisePingApp.swift */,
1A2B3C4D5E6F700000000102 /* ContentView.swift */,
1A2B3C4D5E6F700000000304 /* State */,
1A2B3C4D5E6F700000000303 /* Models */,
1A2B3C4D5E6F700000000305 /* UI */,
1A2B3C4D5E6F700000000306 /* Views */,
1A2B3C4D5E6F700000000103 /* Info.plist */,
1A2B3C4D5E6F700000000105 /* pixelify_sans.ttf */,
);
path = BlastoisePing;
sourceTree = "<group>";
};
1A2B3C4D5E6F700000000303 /* Models */ = {
isa = PBXGroup;
children = (
1A2B3C4D5E6F700000000110 /* AppTypes.swift */,
);
path = Models;
sourceTree = "<group>";
};
1A2B3C4D5E6F700000000304 /* State */ = {
isa = PBXGroup;
children = (
1A2B3C4D5E6F700000000111 /* AppModel.swift */,
);
path = State;
sourceTree = "<group>";
};
1A2B3C4D5E6F700000000305 /* UI */ = {
isa = PBXGroup;
children = (
1A2B3C4D5E6F700000000112 /* Theme.swift */,
);
path = UI;
sourceTree = "<group>";
};
1A2B3C4D5E6F700000000306 /* Views */ = {
isa = PBXGroup;
children = (
1A2B3C4D5E6F700000000113 /* AuthView.swift */,
1A2B3C4D5E6F700000000114 /* HeaderView.swift */,
1A2B3C4D5E6F700000000115 /* PlayerDeckView.swift */,
1A2B3C4D5E6F700000000116 /* Panels.swift */,
1A2B3C4D5E6F700000000117 /* Components.swift */,
);
path = Views;
sourceTree = "<group>";
};
1A2B3C4D5E6F700000000302 /* Products */ = {
isa = PBXGroup;
children = (
1A2B3C4D5E6F700000000100 /* BlastoisePing.app */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
1A2B3C4D5E6F700000000400 /* BlastoisePing */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1A2B3C4D5E6F700000000701 /* Build configuration list for PBXNativeTarget "BlastoisePing" */;
buildPhases = (
1A2B3C4D5E6F700000000500 /* Sources */,
1A2B3C4D5E6F700000000600 /* Resources */,
1A2B3C4D5E6F700000000200 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = BlastoisePing;
productName = BlastoisePing;
productReference = 1A2B3C4D5E6F700000000100 /* BlastoisePing.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
1A2B3C4D5E6F700000000800 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1540;
LastUpgradeCheck = 1540;
TargetAttributes = {
1A2B3C4D5E6F700000000400 = {
CreatedOnToolsVersion = 15.4;
};
};
};
buildConfigurationList = 1A2B3C4D5E6F700000000700 /* Build configuration list for PBXProject "BlastoisePing" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 1A2B3C4D5E6F700000000300;
productRefGroup = 1A2B3C4D5E6F700000000302 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
1A2B3C4D5E6F700000000400 /* BlastoisePing */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
1A2B3C4D5E6F700000000600 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
1A2B3C4D5E6F700000000004 /* pixelify_sans.ttf in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
1A2B3C4D5E6F700000000500 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
1A2B3C4D5E6F700000000001 /* BlastoisePingApp.swift in Sources */,
1A2B3C4D5E6F700000000002 /* ContentView.swift in Sources */,
1A2B3C4D5E6F700000000010 /* AppTypes.swift in Sources */,
1A2B3C4D5E6F700000000011 /* AppModel.swift in Sources */,
1A2B3C4D5E6F700000000012 /* Theme.swift in Sources */,
1A2B3C4D5E6F700000000013 /* AuthView.swift in Sources */,
1A2B3C4D5E6F700000000014 /* HeaderView.swift in Sources */,
1A2B3C4D5E6F700000000015 /* PlayerDeckView.swift in Sources */,
1A2B3C4D5E6F700000000016 /* Panels.swift in Sources */,
1A2B3C4D5E6F700000000017 /* Components.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
1A2B3C4D5E6F700000000900 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
1A2B3C4D5E6F700000000901 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
1A2B3C4D5E6F700000000902 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "";
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = BlastoisePing/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.1;
PRODUCT_BUNDLE_IDENTIFIER = com.peterino.blastoiseping;
PRODUCT_NAME = "$(TARGET_NAME)";
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
1A2B3C4D5E6F700000000903 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "";
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = BlastoisePing/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.1;
PRODUCT_BUNDLE_IDENTIFIER = com.peterino.blastoiseping;
PRODUCT_NAME = "$(TARGET_NAME)";
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
1A2B3C4D5E6F700000000700 /* Build configuration list for PBXProject "BlastoisePing" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1A2B3C4D5E6F700000000900 /* Debug */,
1A2B3C4D5E6F700000000901 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
1A2B3C4D5E6F700000000701 /* Build configuration list for PBXNativeTarget "BlastoisePing" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1A2B3C4D5E6F700000000902 /* Debug */,
1A2B3C4D5E6F700000000903 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 1A2B3C4D5E6F700000000800 /* Project object */;
}

View File

@ -1,10 +0,0 @@
import SwiftUI
@main
struct BlastoisePingApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}

View File

@ -1,126 +0,0 @@
import SwiftUI
struct ContentView: View {
@StateObject private var model = AppModel()
@State private var username = ""
@State private var password = ""
@State private var selectedTab: MainTab = .rooms
var body: some View {
NavigationStack {
ZStack {
Theme.background.ignoresSafeArea()
if model.authState == .signedIn {
mainApp
} else {
AuthView(
model: model,
username: $username,
password: $password
)
}
}
.navigationTitle("Blastoise")
.toolbarColorScheme(.dark, for: .navigationBar)
.toolbarBackground(Theme.background, for: .navigationBar)
.toolbarBackground(.visible, for: .navigationBar)
.font(Theme.bodyFont)
.buttonBorderShape(.roundedRectangle(radius: Theme.corner))
}
.onChange(of: model.authState) { _, authState in
if authState == .signedIn {
password = ""
}
}
}
private var mainApp: some View {
ScrollView {
VStack(spacing: 14) {
HeaderView(model: model)
PlayerDeckView(model: model)
tabStrip
selectedPanel
DebugFooterView(model: model)
}
.padding(.horizontal, 14)
.padding(.bottom, 18)
}
}
private var tabStrip: some View {
HStack(spacing: 8) {
ForEach(MainTab.allCases) { tab in
Button {
selectedTab = tab
if tab == .library {
Task { await model.loadLibraryIfNeeded() }
} else if tab == .playlists {
Task { await model.loadPlaylistsIfNeeded() }
}
} label: {
Label(tab.title, systemImage: tab.icon)
.labelStyle(.iconOnly)
.frame(width: 44, height: 40)
.background(selectedTab == tab ? Theme.accent : Theme.panel2)
.foregroundStyle(selectedTab == tab ? Theme.background : Theme.text)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
}
.accessibilityLabel(tab.title)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
@ViewBuilder
private var selectedPanel: some View {
switch selectedTab {
case .rooms:
RoomsPanel(model: model)
case .queue:
QueuePanel(model: model)
case .people:
PeoplePanel(model: model)
case .library:
LibraryPanel(model: model)
case .playlists:
PlaylistsPanel(model: model)
case .debug:
DebugPanel(model: model)
}
}
}
private enum MainTab: String, CaseIterable, Identifiable {
case rooms
case queue
case people
case library
case playlists
case debug
var id: String { rawValue }
var title: String {
switch self {
case .rooms: return "Rooms"
case .queue: return "Queue"
case .people: return "People"
case .library: return "Library"
case .playlists: return "Lists"
case .debug: return "Debug"
}
}
var icon: String {
switch self {
case .rooms: return "radio"
case .queue: return "list.bullet"
case .people: return "person.2"
case .library: return "music.note.list"
case .playlists: return "rectangle.stack"
case .debug: return "waveform.path.ecg"
}
}
}

View File

@ -1,63 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Blastoise</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSLocalNetworkUsageDescription</key>
<string>Blastoise Ping can check a server running on your local network.</string>
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
<key>UIAppFonts</key>
<array>
<string>pixelify_sans.ttf</string>
</array>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchScreen</key>
<dict/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>

View File

@ -1,298 +0,0 @@
import Foundation
enum SourceMode: String {
case radio = "RADIO"
case library = "LIBRARY"
}
enum AuthState: String {
case checking = "CHECKING"
case signedOut = "SIGNED OUT"
case signedIn = "SIGNED IN"
}
enum APIError: LocalizedError {
case invalidURL
case file(String)
case http(Int, String)
var errorDescription: String? {
switch self {
case .invalidURL:
return "Invalid URL"
case .file(let message):
return message
case .http(let status, let body):
return "HTTP \(status): \(body)"
}
}
}
struct Track: Codable, Hashable, Identifiable {
var id: String
var filename: String
var title: String
var duration: Double
var artist: String?
var album: String?
var available: Bool?
init(
id: String,
filename: String,
title: String,
duration: Double,
artist: String? = nil,
album: String? = nil,
available: Bool? = nil
) {
self.id = id
self.filename = filename
self.title = title
self.duration = duration
self.artist = artist
self.album = album
self.available = available
}
}
struct ChannelInfo: Decodable, Identifiable {
let id: String
let name: String
let description: String
let listenerCount: Int
let isDefault: Bool
let trackCount: Int
let listeners: [String]
enum CodingKeys: String, CodingKey {
case id
case name
case description
case listenerCount
case isDefault
case trackCount
case listeners
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = try c.decode(String.self, forKey: .id)
name = try c.decodeIfPresent(String.self, forKey: .name) ?? "Room"
description = try c.decodeIfPresent(String.self, forKey: .description) ?? ""
listenerCount = try c.decodeIfPresent(Int.self, forKey: .listenerCount) ?? 0
isDefault = try c.decodeIfPresent(Bool.self, forKey: .isDefault) ?? false
trackCount = try c.decodeIfPresent(Int.self, forKey: .trackCount) ?? 0
listeners = try c.decodeIfPresent([String].self, forKey: .listeners) ?? []
}
}
struct ChannelState: Decodable {
let track: Track?
let currentTimestamp: Double
let channelName: String
let channelId: String
let paused: Bool
let queue: [Track]?
let currentIndex: Int
let playbackMode: String
let listenerCount: Int
let listeners: [String]
enum CodingKeys: String, CodingKey {
case track
case currentTimestamp
case channelName
case channelId
case paused
case queue
case currentIndex
case playbackMode
case listenerCount
case listeners
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
track = try c.decodeIfPresent(Track.self, forKey: .track)
currentTimestamp = try c.decodeIfPresent(Double.self, forKey: .currentTimestamp) ?? 0
channelName = try c.decodeIfPresent(String.self, forKey: .channelName) ?? ""
channelId = try c.decodeIfPresent(String.self, forKey: .channelId) ?? ""
paused = try c.decodeIfPresent(Bool.self, forKey: .paused) ?? true
queue = try c.decodeIfPresent([Track].self, forKey: .queue)
currentIndex = try c.decodeIfPresent(Int.self, forKey: .currentIndex) ?? 0
playbackMode = try c.decodeIfPresent(String.self, forKey: .playbackMode) ?? "repeat-all"
listenerCount = try c.decodeIfPresent(Int.self, forKey: .listenerCount) ?? 0
listeners = try c.decodeIfPresent([String].self, forKey: .listeners) ?? []
}
}
struct PlaylistBundle: Decodable {
let mine: [Playlist]
let shared: [Playlist]
}
struct Playlist: Decodable, Identifiable {
let id: String
let name: String
let description: String
let ownerId: Int
let ownerName: String
let isPublic: Bool
let shareToken: String?
let trackIds: [String]
enum CodingKeys: String, CodingKey {
case id
case name
case description
case ownerId
case ownerName
case isPublic
case shareToken
case trackIds
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = try c.decode(String.self, forKey: .id)
name = try c.decodeIfPresent(String.self, forKey: .name) ?? "Playlist"
description = try c.decodeIfPresent(String.self, forKey: .description) ?? ""
ownerId = try c.decodeIfPresent(Int.self, forKey: .ownerId) ?? 0
ownerName = try c.decodeIfPresent(String.self, forKey: .ownerName) ?? ""
isPublic = try c.decodeIfPresent(Bool.self, forKey: .isPublic) ?? false
shareToken = try c.decodeIfPresent(String.self, forKey: .shareToken)
trackIds = try c.decodeIfPresent([String].self, forKey: .trackIds) ?? []
}
}
struct UserSession: Decodable {
let id: Int
let username: String
let isAdmin: Bool
let isGuest: Bool
let permissions: [Permission]
enum CodingKeys: String, CodingKey {
case id
case username
case isAdmin
case isAdminSnake = "is_admin"
case isGuest
case isGuestSnake = "is_guest"
case permissions
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = try c.decodeIfPresent(Int.self, forKey: .id) ?? 0
username = try c.decodeIfPresent(String.self, forKey: .username) ?? "guest"
isAdmin = try c.decodeIfPresent(Bool.self, forKey: .isAdmin)
?? c.decodeIfPresent(Bool.self, forKey: .isAdminSnake)
?? false
isGuest = try c.decodeIfPresent(Bool.self, forKey: .isGuest)
?? c.decodeIfPresent(Bool.self, forKey: .isGuestSnake)
?? false
permissions = try c.decodeIfPresent([Permission].self, forKey: .permissions) ?? []
}
}
struct Permission: Decodable {
let resourceType: String
let resourceId: String?
let permission: String
enum CodingKeys: String, CodingKey {
case resourceType
case resourceTypeSnake = "resource_type"
case resourceId
case resourceIdSnake = "resource_id"
case permission
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
resourceType = try c.decodeIfPresent(String.self, forKey: .resourceType)
?? c.decodeIfPresent(String.self, forKey: .resourceTypeSnake)
?? ""
resourceId = try c.decodeIfPresent(String.self, forKey: .resourceId)
?? c.decodeIfPresent(String.self, forKey: .resourceIdSnake)
permission = try c.decodeIfPresent(String.self, forKey: .permission) ?? ""
}
}
struct AuthEnvelope: Decodable {
let user: UserSession?
let permissions: [Permission]
enum CodingKeys: String, CodingKey {
case user
case permissions
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
user = try c.decodeIfPresent(UserSession.self, forKey: .user)
permissions = try c.decodeIfPresent([Permission].self, forKey: .permissions) ?? []
}
}
struct QueueResponse: Decodable {
let success: Bool?
let queueLength: Int?
}
struct ModeResponse: Decodable {
let success: Bool?
let playbackMode: String?
}
struct FetchItem: Codable, Hashable {
let id: String?
let url: String
let title: String
}
struct FetchPlaylistResponse: Decodable {
let type: String
let title: String
let count: Int
let items: [FetchItem]
let requiresConfirmation: Bool?
}
struct FetchSingleResponse: Decodable {
let type: String
let id: String?
let title: String
let queueType: String?
}
enum FetchResponse: Decodable {
case single(FetchSingleResponse)
case playlist(FetchPlaylistResponse)
enum CodingKeys: String, CodingKey {
case type
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let type = try c.decodeIfPresent(String.self, forKey: .type)
switch type {
case "playlist":
self = .playlist(try FetchPlaylistResponse(from: decoder))
default:
self = .single(try FetchSingleResponse(from: decoder))
}
}
}
struct FetchConfirmResponse: Decodable {
let message: String
let queueType: String?
let estimatedTime: String?
let playlistId: String?
let playlistName: String?
let items: [FetchItem]?
}

File diff suppressed because it is too large Load Diff

View File

@ -1,77 +0,0 @@
import SwiftUI
struct Theme {
static let background = Color(red: 0.055, green: 0.052, blue: 0.067)
static let panel = Color(red: 0.112, green: 0.105, blue: 0.135)
static let panel2 = Color(red: 0.170, green: 0.157, blue: 0.205)
static let stroke = Color(red: 0.475, green: 0.425, blue: 0.545)
static let text = Color(red: 0.965, green: 0.930, blue: 0.760)
static let muted = Color(red: 0.640, green: 0.585, blue: 0.710)
static let accent = Color(red: 1.000, green: 0.812, blue: 0.176)
static let ready = Color(red: 0.350, green: 0.820, blue: 1.000)
static let amber = Color(red: 1.000, green: 0.570, blue: 0.240)
static let red = Color(red: 1.000, green: 0.310, blue: 0.340)
static let corner: CGFloat = 0
static let smallCorner: CGFloat = 0
static func pixel(_ size: CGFloat, weight: Font.Weight = .regular) -> Font {
.custom("PixelifySans-Regular", size: size).weight(weight)
}
static func mono(_ size: CGFloat, weight: Font.Weight = .regular) -> Font {
pixel(size, weight: weight).monospacedDigit()
}
static let bodyFont = pixel(16)
static let headlineFont = pixel(19, weight: .semibold)
static let captionFont = pixel(13)
static let microFont = mono(11, weight: .semibold)
static func display(_ size: CGFloat) -> Font { pixel(size, weight: .bold) }
}
extension View {
func panel() -> some View {
self
.padding(14)
.background(Theme.panel)
.overlay(
RoundedRectangle(cornerRadius: Theme.corner)
.stroke(Theme.stroke, lineWidth: 1)
)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
}
func rowStyle(isActive: Bool = false) -> some View {
self
.padding(10)
.background(isActive ? Theme.panel2.opacity(1.0) : Theme.panel2.opacity(0.76))
.overlay(
RoundedRectangle(cornerRadius: Theme.corner)
.stroke(isActive ? Theme.accent : Theme.stroke.opacity(0.38), lineWidth: 1)
)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
}
func textFieldStyle() -> some View {
self
.padding(12)
.foregroundStyle(Theme.text)
.background(Theme.panel2)
.overlay(
RoundedRectangle(cornerRadius: Theme.corner)
.stroke(Theme.stroke, lineWidth: 1)
)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
}
}
func formatTime(_ ms: Int64) -> String {
let total = max(0, Int(ms / 1000))
return "\(total / 60):" + String(format: "%02d", total % 60)
}
func formatDuration(_ duration: TimeInterval) -> String {
guard duration.isFinite, duration > 0 else { return "--:--" }
return formatTime(Int64(duration * 1000))
}

View File

@ -1,101 +0,0 @@
import SwiftUI
struct AuthView: View {
@ObservedObject var model: AppModel
@Binding var username: String
@Binding var password: String
@FocusState private var focused: Field?
private enum Field {
case server
case username
case password
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 18) {
VStack(alignment: .leading, spacing: 8) {
Text("BLASTOISE")
.font(Theme.display(40))
.foregroundStyle(Theme.text)
Text("Tune into a shared room, stream the queue, and keep your local player in sync.")
.foregroundStyle(Theme.muted)
}
VStack(alignment: .leading, spacing: 12) {
Label("Server", systemImage: "server.rack")
.foregroundStyle(Theme.text)
.font(Theme.headlineFont)
field("http://host:3001", text: $model.serverURL, field: .server)
HStack(spacing: 10) {
Button {
model.serverURL = "http://mhsgroove.peterino.com:3001"
} label: {
Label("Default", systemImage: "radio")
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
Button {
model.serverURL = "http://localhost:3001"
} label: {
Label("Local", systemImage: "desktopcomputer")
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
}
}
.panel()
VStack(alignment: .leading, spacing: 12) {
Label("Account", systemImage: "person.crop.circle")
.foregroundStyle(Theme.text)
.font(Theme.headlineFont)
field("username", text: $username, field: .username)
SecureField("password", text: $password)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.focused($focused, equals: .password)
.textFieldStyle()
HStack(spacing: 10) {
Button {
focused = nil
Task { await model.signIn(username: username, password: password) }
} label: {
Label("Sign In", systemImage: "arrow.right.circle")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.tint(Theme.accent)
Button {
focused = nil
Task { await model.signUp(username: username, password: password) }
} label: {
Label("Sign Up", systemImage: "person.badge.plus")
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
}
}
.panel()
StatusStrip(model: model)
}
.padding(18)
.frame(maxWidth: 640, alignment: .topLeading)
}
}
private func field(_ placeholder: String, text: Binding<String>, field: Field) -> some View {
TextField(placeholder, text: text)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.keyboardType(field == .server ? .URL : .default)
.focused($focused, equals: field)
.textFieldStyle()
}
}

View File

@ -1,101 +0,0 @@
import SwiftUI
struct DebugFooterView: View {
@ObservedObject var model: AppModel
var body: some View {
HStack(spacing: 8) {
Circle()
.fill(model.authState == .signedIn ? Theme.ready : Theme.amber)
.frame(width: 8, height: 8)
Text(model.status)
.font(Theme.mono(12))
.foregroundStyle(Theme.muted)
.lineLimit(1)
Spacer()
}
.padding(.horizontal, 2)
}
}
struct StatusStrip: View {
@ObservedObject var model: AppModel
var body: some View {
HStack(spacing: 8) {
Circle()
.fill(model.authState == .checking ? Theme.amber : model.authState == .signedIn ? Theme.ready : Theme.red)
.frame(width: 10, height: 10)
Text(model.status)
.font(Theme.mono(12))
.foregroundStyle(Theme.muted)
Spacer()
}
.panel()
}
}
struct PanelTitle: View {
private let title: String
private let icon: String
init(_ title: String, icon: String) {
self.title = title
self.icon = icon
}
var body: some View {
Label(title, systemImage: icon)
.font(Theme.headlineFont)
.foregroundStyle(Theme.text)
}
}
struct EmptyLine: View {
private let text: String
init(_ text: String) {
self.text = text
}
var body: some View {
Text(text)
.font(Theme.captionFont)
.foregroundStyle(Theme.muted)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(12)
.background(Theme.panel2)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
}
}
struct TrackLine<Actions: View>: View {
let track: Track
let isActive: Bool
let subtitle: String
@ViewBuilder let actions: () -> Actions
var body: some View {
HStack(spacing: 10) {
Rectangle()
.fill(isActive ? Theme.ready : Theme.amber)
.frame(width: 4)
.clipShape(RoundedRectangle(cornerRadius: Theme.smallCorner))
VStack(alignment: .leading, spacing: 4) {
Text(track.title)
.font(Theme.pixel(16, weight: .semibold))
.foregroundStyle(Theme.text)
.lineLimit(2)
Text(subtitle)
.font(Theme.captionFont)
.foregroundStyle(Theme.muted)
.lineLimit(1)
}
Spacer(minLength: 8)
actions()
}
.rowStyle(isActive: isActive)
}
}

View File

@ -1,53 +0,0 @@
import SwiftUI
struct HeaderView: View {
@ObservedObject var model: AppModel
var body: some View {
VStack(spacing: 10) {
HStack(spacing: 10) {
VStack(alignment: .leading, spacing: 2) {
Text("BLASTOISE")
.font(Theme.display(28))
.foregroundStyle(Theme.text)
Text(model.currentUser?.username ?? "signed out")
.font(Theme.mono(12))
.foregroundStyle(Theme.muted)
}
Spacer()
Button {
Task { await model.connectToServer() }
} label: {
Image(systemName: "arrow.clockwise")
.frame(width: 38, height: 36)
}
.buttonStyle(.bordered)
Button(role: .destructive) {
Task { await model.logout() }
} label: {
Image(systemName: "rectangle.portrait.and.arrow.right")
.frame(width: 38, height: 36)
}
.buttonStyle(.bordered)
}
HStack(spacing: 8) {
Image(systemName: "server.rack")
.foregroundStyle(Theme.amber)
TextField("server", text: $model.serverURL)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.font(Theme.mono(12))
.foregroundStyle(Theme.text)
}
.padding(10)
.background(Theme.panel2)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
}
.padding(14)
.background(Theme.background)
}
}

View File

@ -1,431 +0,0 @@
import SwiftUI
import UniformTypeIdentifiers
struct RoomsPanel: View {
@ObservedObject var model: AppModel
var body: some View {
VStack(alignment: .leading, spacing: 10) {
PanelTitle("Rooms", icon: "radio")
if model.channels.isEmpty {
EmptyLine("No rooms loaded")
} else {
ForEach(model.channels) { channel in
HStack(spacing: 10) {
VStack(alignment: .leading, spacing: 4) {
HStack {
Text(channel.name)
.font(Theme.headlineFont)
.foregroundStyle(Theme.text)
if channel.isDefault {
Text("DEFAULT")
.font(Theme.microFont)
.foregroundStyle(Theme.background)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.background(Theme.amber)
.clipShape(RoundedRectangle(cornerRadius: Theme.smallCorner))
}
}
Text(channel.description.isEmpty ? "\(channel.trackCount) tracks" : channel.description)
.font(Theme.captionFont)
.foregroundStyle(Theme.muted)
Text("\(channel.listenerCount) listener(s)")
.font(Theme.mono(12))
.foregroundStyle(Theme.ready)
}
Spacer()
Button {
Task { await model.joinChannel(channel.id) }
} label: {
Image(systemName: model.currentChannelId == channel.id ? "checkmark.circle.fill" : "dot.radiowaves.left.and.right")
.frame(width: 44, height: 38)
}
.buttonStyle(.borderedProminent)
.tint(model.currentChannelId == channel.id ? Theme.ready : Theme.accent)
}
.rowStyle(isActive: model.currentChannelId == channel.id)
}
}
}
.panel()
}
}
struct QueuePanel: View {
@ObservedObject var model: AppModel
var body: some View {
VStack(alignment: .leading, spacing: 10) {
PanelTitle("Queue", icon: "list.bullet")
if model.queue.isEmpty {
EmptyLine(model.queueLoaded ? "Queue is empty" : "Queue not loaded")
} else {
ForEach(Array(model.queue.prefix(80).enumerated()), id: \.offset) { index, track in
TrackLine(
track: track,
isActive: index == model.currentIndex,
subtitle: "#\(index + 1) \(formatDuration(track.duration))"
) {
Button {
model.jumpToQueueIndex(index)
} label: {
Image(systemName: "play.fill")
.frame(width: 38, height: 34)
}
.buttonStyle(.bordered)
Button(role: .destructive) {
Task { await model.removeQueueIndex(index) }
} label: {
Image(systemName: "trash")
.frame(width: 38, height: 34)
}
.buttonStyle(.bordered)
}
}
}
}
.panel()
}
}
struct PeoplePanel: View {
@ObservedObject var model: AppModel
var body: some View {
VStack(alignment: .leading, spacing: 10) {
PanelTitle("People", icon: "person.2")
if model.listeners.isEmpty {
EmptyLine("No listener names in this room yet")
} else {
ForEach(model.listeners, id: \.self) { listener in
HStack {
Image(systemName: listener == model.currentUser?.username ? "person.fill.checkmark" : "person.fill")
.foregroundStyle(listener == model.currentUser?.username ? Theme.ready : Theme.muted)
Text(listener)
.foregroundStyle(Theme.text)
Spacer()
if listener == model.currentUser?.username {
Text("YOU")
.font(Theme.microFont)
.foregroundStyle(Theme.ready)
}
}
.rowStyle(isActive: listener == model.currentUser?.username)
}
}
}
.panel()
}
}
struct LibraryPanel: View {
@ObservedObject var model: AppModel
@State private var query = ""
@State private var fetchURL = ""
@State private var fileImporterPresented = false
var matches: [Track] {
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let base = model.libraryTracks
if trimmed.isEmpty {
return Array(base.prefix(80))
}
return Array(base.filter {
$0.title.lowercased().contains(trimmed) ||
$0.filename.lowercased().contains(trimmed) ||
($0.artist ?? "").lowercased().contains(trimmed)
}.prefix(80))
}
var body: some View {
VStack(alignment: .leading, spacing: 10) {
PanelTitle("Library", icon: "music.note.list")
importTools
HStack(spacing: 8) {
Image(systemName: "magnifyingglass")
.foregroundStyle(Theme.muted)
TextField("Search tracks", text: $query)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.foregroundStyle(Theme.text)
}
.padding(10)
.background(Theme.panel2)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
if !model.libraryLoaded {
EmptyLine("Loading library")
} else if matches.isEmpty {
EmptyLine("No matching tracks")
} else {
ForEach(matches) { track in
TrackLine(
track: track,
isActive: model.sourceMode == .library && model.currentTrackId == track.id,
subtitle: track.artist ?? track.filename
) {
Button {
model.playLibraryTrack(track)
} label: {
Image(systemName: "play.fill")
.frame(width: 38, height: 34)
}
.buttonStyle(.borderedProminent)
.tint(Theme.accent)
Menu {
Button("Add to Queue") {
Task { await model.queueTrack(track, playNext: false) }
}
Button("Play Next") {
Task { await model.queueTrack(track, playNext: true) }
}
} label: {
Image(systemName: "plus")
.frame(width: 38, height: 34)
}
.buttonStyle(.bordered)
}
}
}
}
.panel()
.fileImporter(
isPresented: $fileImporterPresented,
allowedContentTypes: [.audio, .movie],
allowsMultipleSelection: true
) { result in
switch result {
case .success(let urls):
Task { await model.uploadFiles(urls) }
case .failure(let error):
model.importStatus = "File picker failed: \(error.localizedDescription)"
}
}
}
private var importTools: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 8) {
Button {
fileImporterPresented = true
} label: {
Label(model.isUploading ? "Uploading" : "Upload Files", systemImage: "square.and.arrow.up")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.tint(Theme.accent)
.disabled(model.isUploading)
Button {
Task { await model.loadLibrary() }
} label: {
Image(systemName: "arrow.clockwise")
.frame(width: 42, height: 34)
}
.buttonStyle(.bordered)
.accessibilityLabel("Reload Library")
}
HStack(spacing: 8) {
Image(systemName: "link")
.foregroundStyle(Theme.muted)
TextField("Fetch from website URL", text: $fetchURL)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.keyboardType(.URL)
.foregroundStyle(Theme.text)
Button {
Task { await model.fetchFromWebsite(fetchURL) }
} label: {
Image(systemName: model.isFetching ? "hourglass" : "arrow.down.circle")
.frame(width: 40, height: 34)
}
.buttonStyle(.bordered)
.disabled(model.isFetching)
.accessibilityLabel("Fetch URL")
}
.padding(10)
.background(Theme.panel2)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
if let playlist = model.pendingFetchPlaylist {
VStack(alignment: .leading, spacing: 8) {
Text("Playlist found")
.font(Theme.mono(12, weight: .bold))
.foregroundStyle(Theme.amber)
Text("\(playlist.title) · \(playlist.count) items")
.font(Theme.pixel(16, weight: .semibold))
.foregroundStyle(Theme.text)
.lineLimit(2)
HStack(spacing: 8) {
Button {
Task { await model.confirmFetchPlaylist() }
} label: {
Label("Queue Playlist", systemImage: "checkmark.circle")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.tint(Theme.ready)
.disabled(model.isFetching)
Button {
model.cancelFetchPlaylist()
} label: {
Label("Cancel", systemImage: "xmark")
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
}
}
.padding(10)
.background(Theme.panel2)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
}
if !model.importStatus.isEmpty {
Text(model.importStatus)
.font(Theme.mono(12))
.foregroundStyle(Theme.muted)
.lineLimit(2)
}
}
}
}
struct PlaylistsPanel: View {
@ObservedObject var model: AppModel
var body: some View {
VStack(alignment: .leading, spacing: 12) {
PanelTitle("Playlists", icon: "rectangle.stack")
if model.allPlaylists.isEmpty {
EmptyLine(model.playlistsLoaded ? "No playlists" : "Loading playlists")
} else {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(model.allPlaylists.prefix(40)) { playlist in
let isSelected = model.selectedPlaylistId == playlist.id
Button {
Task { await model.loadPlaylist(playlist.id) }
} label: {
VStack(alignment: .leading, spacing: 4) {
Text(playlist.name)
.font(Theme.pixel(16, weight: .bold))
.foregroundStyle(isSelected ? Theme.background : Theme.text)
.lineLimit(1)
Text("\(playlist.trackIds.count) tracks")
.font(Theme.mono(12))
.foregroundStyle(isSelected ? Theme.background.opacity(0.72) : Theme.muted)
}
.frame(width: 150, alignment: .leading)
.padding(10)
}
.buttonStyle(.plain)
.background(isSelected ? Theme.accent : Theme.panel2)
.overlay(
RoundedRectangle(cornerRadius: Theme.corner)
.stroke(isSelected ? Theme.text : Theme.stroke.opacity(0.38), lineWidth: 1)
)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
}
}
}
}
if let playlist = model.selectedPlaylist {
HStack {
VStack(alignment: .leading, spacing: 3) {
Text(playlist.name)
.font(Theme.headlineFont)
.foregroundStyle(Theme.text)
Text(playlist.ownerName.isEmpty ? "\(playlist.trackIds.count) tracks" : "by \(playlist.ownerName)")
.font(Theme.captionFont)
.foregroundStyle(Theme.muted)
}
Spacer()
Button {
Task { await model.addPlaylistToQueue(playlist, playNext: false) }
} label: {
Image(systemName: "text.badge.plus")
.frame(width: 38, height: 34)
}
.buttonStyle(.bordered)
Button {
Task { await model.addPlaylistToQueue(playlist, playNext: true) }
} label: {
Image(systemName: "text.line.first.and.arrowtriangle.forward")
.frame(width: 38, height: 34)
}
.buttonStyle(.bordered)
}
ForEach(Array(playlist.trackIds.prefix(80).enumerated()), id: \.offset) { index, trackId in
let track = model.track(for: trackId) ?? Track(id: trackId, filename: trackId, title: trackId, duration: 0)
TrackLine(
track: track,
isActive: model.currentTrackId == track.id,
subtitle: "#\(index + 1)"
) {
Button {
Task { await model.queueTrack(track, playNext: false) }
} label: {
Image(systemName: "plus")
.frame(width: 38, height: 34)
}
.buttonStyle(.bordered)
Button {
Task { await model.queueTrack(track, playNext: true) }
} label: {
Image(systemName: "arrow.up.to.line")
.frame(width: 38, height: 34)
}
.buttonStyle(.bordered)
}
}
}
}
.panel()
}
}
struct DebugPanel: View {
@ObservedObject var model: AppModel
var body: some View {
VStack(alignment: .leading, spacing: 10) {
PanelTitle("Diagnostics", icon: "waveform.path.ecg")
debugRow("Server", model.serverURL)
debugRow("Auth", model.authState.rawValue)
debugRow("User", model.currentUser?.username ?? "-")
debugRow("Room", model.currentChannelId ?? "-")
debugRow("Track", model.currentTrackId ?? "-")
debugRow("Expected", "\(model.expectedPositionMs)ms")
debugRow("Player", "\(model.playerPositionMs)ms")
debugRow("Drift", "\(model.driftMs)ms")
Divider().overlay(Theme.stroke)
ForEach(model.debugEvents, id: \.self) { event in
Text(event)
.font(Theme.mono(12))
.foregroundStyle(Theme.muted)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.panel()
}
private func debugRow(_ label: String, _ value: String) -> some View {
HStack(alignment: .top) {
Text(label)
.foregroundStyle(Theme.muted)
.frame(width: 78, alignment: .leading)
Text(value)
.foregroundStyle(Theme.text)
.textSelection(.enabled)
Spacer(minLength: 0)
}
.font(Theme.mono(12))
}
}

View File

@ -1,126 +0,0 @@
import SwiftUI
struct PlayerDeckView: View {
@ObservedObject var model: AppModel
var progress: Double {
guard model.trackDuration > 0 else { return 0 }
return min(1, max(0, Double(model.playerPositionMs) / (model.trackDuration * 1000)))
}
var body: some View {
VStack(alignment: .leading, spacing: 14) {
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 4) {
Text(model.sourceMode.rawValue)
.font(Theme.mono(12, weight: .bold))
.foregroundStyle(Theme.accent)
Text(model.channelName)
.font(Theme.headlineFont)
.foregroundStyle(Theme.text)
Text(model.trackTitle)
.font(Theme.pixel(22, weight: .bold))
.foregroundStyle(Theme.text)
.lineLimit(2)
}
Spacer()
VStack(alignment: .trailing, spacing: 4) {
Text(model.playbackMode.uppercased())
.font(Theme.mono(12))
.foregroundStyle(Theme.amber)
Text(model.playbackState.uppercased())
.font(Theme.mono(12))
.foregroundStyle(model.isPlaying ? Theme.ready : Theme.muted)
}
}
VStack(alignment: .leading, spacing: 8) {
ProgressView(value: progress)
.tint(Theme.ready)
.background(Theme.panel2)
.clipShape(RoundedRectangle(cornerRadius: Theme.smallCorner))
HStack {
Text(formatTime(model.playerPositionMs))
Spacer()
Text(formatDuration(model.trackDuration))
}
.font(Theme.mono(12))
.foregroundStyle(Theme.muted)
}
HStack(spacing: 8) {
iconButton("backward.end.fill") { model.previous() }
iconButton("gobackward.15") { model.seekBy(seconds: -15) }
Button {
model.togglePlay()
} label: {
Image(systemName: model.isPlaying ? "pause.fill" : "play.fill")
.font(Theme.pixel(24, weight: .bold))
.frame(width: 58, height: 48)
}
.buttonStyle(.borderedProminent)
.tint(Theme.accent)
iconButton("goforward.15") { model.seekBy(seconds: 15) }
iconButton("forward.end.fill") { model.next() }
}
HStack(spacing: 8) {
actionButton("Mode", icon: "repeat") {
Task { await model.cyclePlaybackMode() }
}
actionButton("Queue", icon: "text.badge.plus") {
Task { await model.queueCurrent(playNext: false) }
}
actionButton("Next", icon: "text.line.first.and.arrowtriangle.forward") {
Task { await model.queueCurrent(playNext: true) }
}
actionButton("Stop", icon: "power") {
model.stopAndExit()
}
}
HStack(spacing: 12) {
meter("DRIFT", "\(model.driftMs)ms", model.sourceMode == .radio && abs(model.driftMs) > 1800 ? Theme.amber : Theme.ready)
meter("ROOMS", "\(model.channels.count)", Theme.text)
meter("QUEUE", "\(model.queue.count)", Theme.text)
}
}
.panel()
}
private func iconButton(_ systemName: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
Image(systemName: systemName)
.frame(maxWidth: .infinity, minHeight: 44)
}
.buttonStyle(.bordered)
}
private func actionButton(_ title: String, icon: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
Label(title, systemImage: icon)
.labelStyle(.iconOnly)
.frame(maxWidth: .infinity, minHeight: 38)
}
.buttonStyle(.bordered)
.accessibilityLabel(title)
}
private func meter(_ label: String, _ value: String, _ color: Color) -> some View {
VStack(alignment: .leading, spacing: 2) {
Text(label)
.font(Theme.microFont)
.foregroundStyle(Theme.muted)
Text(value)
.font(Theme.mono(13, weight: .bold))
.foregroundStyle(color)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(8)
.background(Theme.panel2)
.clipShape(RoundedRectangle(cornerRadius: Theme.corner))
}
}

View File

@ -1,30 +0,0 @@
# Blastoise iOS Sketch
Native SwiftUI sketch for the Blastoise/MusicRoom server.
## What It Does
- Defaults to `http://mhsgroove.peterino.com:3001`.
- Signs in or signs up with the server.
- Loads rooms, queue state, people, library, and playlists.
- Connects to a room WebSocket and streams `/api/tracks/:id` through `AVPlayer`.
- Applies server timestamp sync and drift correction.
- Supports local library playback, queue/play-next actions, queue jumps/removes, and playback mode cycling.
- Uses one compact broadcast-console theme.
## Code Layout
- `BlastoisePingApp.swift` - app entrypoint.
- `ContentView.swift` - signed-in/signed-out shell and tab routing.
- `Models/AppTypes.swift` - API response models and shared enums.
- `State/AppModel.swift` - app state, server requests, WebSocket sync, uploads, and playback coordination.
- `UI/Theme.swift` - pixel-art palette, typography, reusable view chrome, and time formatting.
- `Views/` - focused SwiftUI screens and reusable row/panel components.
## Open
```bash
open ios/BlastoisePing/BlastoisePing.xcodeproj
```
The app currently allows arbitrary HTTP loads in `Info.plist` so it can reach the existing plain-HTTP test server and local development servers. Narrow that before any public distribution.

View File

@ -1,2 +0,0 @@
[tools]
bun = "1.3.14"

View File

@ -13,9 +13,6 @@
if (M.currentUser && data.permissions) {
M.currentUser.permissions = data.permissions;
}
if (data.preferences) {
M.loadReplayGainPrefs && M.loadReplayGainPrefs(data.preferences);
}
M.updateAuthUI();
// Start slow queue polling if logged in
if (M.currentUser && !M.currentUser.isGuest && M.startSlowQueuePoll) {
@ -103,9 +100,6 @@
if (M.currentUser && data.permissions) {
M.currentUser.permissions = data.permissions;
}
if (data.preferences) {
M.loadReplayGainPrefs && M.loadReplayGainPrefs(data.preferences);
}
M.updateAuthUI();
if (M.currentUser) M.loadStreams();
} catch (e) {

View File

@ -159,7 +159,7 @@
counts[name] = (counts[name] || 0) + 1;
}
const listenersHtml = Object.entries(counts).map(([name, count]) =>
`<div class="listener">${M.escapeHtml(name)}${count > 1 ? ` <span class="listener-mult">x${count}</span>` : ""}</div>`
`<div class="listener">${name}${count > 1 ? ` <span class="listener-mult">x${count}</span>` : ""}</div>`
).join("");
// Show delete button for non-default channels if user is admin or creator
@ -173,8 +173,8 @@
div.innerHTML = `
<div class="channel-header">
<span class="channel-name">${M.escapeHtml(ch.name)}</span>
<input class="channel-name-input" type="text" value="${M.escapeHtml(ch.name)}" style="display:none;">
<span class="channel-name">${ch.name}</span>
<input class="channel-name-input" type="text" value="${ch.name.replace(/"/g, '&quot;')}" style="display:none;">
${renameBtn}
${deleteBtn}
<span class="listener-count">${ch.listenerCount}</span>
@ -498,8 +498,7 @@
const isNewTrack = trackId !== M.currentTrackId;
if (isNewTrack) {
M.currentTrackId = trackId;
M.setTrackTitle(M.trackComponent.getTitle(data.track));
M.applyReplayGain && M.applyReplayGain(data.track);
M.setTrackTitle(data.track.title);
M.loadingSegments.clear();
// Auto-scroll queue to current track

3
public/controls.js vendored
View File

@ -71,8 +71,7 @@
M.currentIndex = newIndex;
M.currentTrackId = trackId;
M.serverTrackDuration = track.duration;
M.setTrackTitle(M.trackComponent.getTitle(track));
M.applyReplayGain && M.applyReplayGain(track);
M.setTrackTitle(track.title?.trim() || track.filename?.replace(/\.[^.]+$/, "") || "Unknown");
M.loadingSegments.clear();
const cachedUrl = await M.loadTrackBlob(trackId);
M.audio.src = cachedUrl || M.getTrackUrl(trackId);

View File

@ -15,9 +15,6 @@ window.MusicRoom = {
lastServerUpdate: 0,
serverPaused: true,
// Current track cache (for ReplayGain re-application across graph init)
currentTrack: null,
// Channels list
channels: [],

View File

@ -207,20 +207,6 @@
</div>
<div id="volume-controls">
<span id="btn-stream-only" title="Toggle stream-only mode (no caching)">stream</span>
<div id="replaygain-wrap">
<span id="btn-replaygain" title="ReplayGain loudness normalization">rg</span>
<div id="replaygain-popover" class="hidden">
<div class="rg-row">
<span>Normalize</span>
<input type="checkbox" id="rg-enabled">
</div>
<div class="rg-row">
<span>Pre-amp</span>
<input type="range" id="rg-preamp">
<span id="rg-preamp-value">0 dB</span>
</div>
</div>
</div>
<span id="btn-mute" title="Toggle mute">🔊</span>
<input type="range" id="volume" min="0" max="1" step="0.01" value="1">
</div>
@ -242,7 +228,6 @@
<script src="/themes.js"></script>
<script src="/utils.js"></script>
<script src="/visualizer.js"></script>
<script src="/replayGain.js"></script>
<script src="/trackComponent.js"></script>
<script src="/trackContainer.js"></script>
<script src="/audioCache.js"></script>

View File

@ -37,8 +37,7 @@
// Set up and play track
M.currentTrackId = trackId;
M.serverTrackDuration = track.duration;
M.setTrackTitle(M.trackComponent.getTitle(track));
M.applyReplayGain && M.applyReplayGain(track);
M.setTrackTitle(track.title || track.filename);
M.loadingSegments.clear();
const cachedUrl = await M.loadTrackBlob(trackId);

View File

@ -41,7 +41,7 @@
} else {
myContainer.innerHTML = myPlaylists.map(p => `
<div class="playlist-item${p.id === selectedPlaylistId ? ' selected' : ''}" data-id="${p.id}">
<span class="playlist-name">${M.escapeHtml(p.name)}</span>
<span class="playlist-name">${escapeHtml(p.name)}</span>
${p.isPublic ? '<span class="playlist-public-icon" title="Public">🌐</span>' : ''}
<span class="playlist-count">${p.trackIds.length}</span>
</div>
@ -54,8 +54,8 @@
} else {
sharedContainer.innerHTML = sharedPlaylists.map(p => `
<div class="playlist-item${p.id === selectedPlaylistId ? ' selected' : ''}" data-id="${p.id}">
<span class="playlist-name">${M.escapeHtml(p.name)}</span>
<span class="playlist-owner">by ${M.escapeHtml(p.ownerName || 'Unknown')}</span>
<span class="playlist-name">${escapeHtml(p.name)}</span>
<span class="playlist-owner">by ${escapeHtml(p.ownerName || 'Unknown')}</span>
<span class="playlist-count">${p.trackIds.length}</span>
</div>
`).join('');
@ -478,6 +478,13 @@
}));
}
function escapeHtml(str) {
if (!str) return '';
return str.replace(/[&<>"']/g, c => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
}[c]));
}
function initPlaylists() {
// New playlist button
const btnNew = $('#btn-new-playlist');

View File

@ -338,8 +338,8 @@
return;
}
const title = M.trackComponent.getTitle(track);
bar.innerHTML = `<span class="label">Now playing:</span> ${M.escapeHtml(title)}`;
const title = track.title?.trim() || (track.id || track.filename || "Unknown").replace(/\.[^.]+$/, "");
bar.innerHTML = `<span class="label">Now playing:</span> ${title}`;
bar.title = title;
bar.classList.remove("hidden");
};

View File

@ -1,185 +0,0 @@
// MusicRoom - ReplayGain module
// Applies per-track loudness normalization using server-provided rsgain metadata.
// Gain is applied client-side via the shared Web Audio gain node (M.gainNode),
// so it only affects this listener's playback. Preferences are persisted
// per-account via /api/auth/me/preferences (localStorage fallback).
(function() {
const M = window.MusicRoom;
const LS_ENABLED = "blastoise_replaygain_enabled";
const LS_PREAMP = "blastoise_replaygain_preamp";
const PREAMP_MIN = -12;
const PREAMP_MAX = 12;
const PREAMP_STEP = 0.5;
const MAX_LINEAR = 10; // +20 dB hard cap to avoid extreme boosts
M.replayGain = {
enabled: localStorage.getItem(LS_ENABLED) !== "false", // default true
preampDb: clampPreamp(Number.parseFloat(localStorage.getItem(LS_PREAMP)) || 0),
};
M.currentTrack = null;
function clampPreamp(v) {
if (!Number.isFinite(v)) return 0;
return Math.max(PREAMP_MIN, Math.min(PREAMP_MAX, Math.round(v / PREAMP_STEP) * PREAMP_STEP));
}
// linear gain factor for a track, honoring enable flag, preamp, and peak clipping
function computeLinearGain(track) {
if (!M.replayGain.enabled) return 1.0;
const preamp = M.replayGain.preampDb || 0;
let gainDb = preamp;
const rgDb = track ? track.replayGainDb : null;
if (Number.isFinite(rgDb)) gainDb += rgDb;
let linear = Math.pow(10, gainDb / 20);
const peak = track ? track.replayPeak : null;
if (Number.isFinite(peak) && peak > 0 && peak * linear > 1) {
linear = 1 / peak;
}
return Math.min(linear, MAX_LINEAR);
}
function setGain(node, linear) {
const ctx = node.context;
if (ctx.state === "running") {
const t = ctx.currentTime;
node.gain.cancelScheduledValues(t);
node.gain.setTargetAtTime(linear, t, 0.02); // ~20ms ramp, avoids clicks
} else {
node.gain.value = linear; // context suspended; apply directly
}
}
// Apply gain for the current (or given) track. Safe to call before the graph
// exists — the value is re-applied when the graph initializes.
M.applyReplayGain = function(track) {
if (track) M.currentTrack = track;
const t = M.currentTrack;
const hasData = Number.isFinite(t && t.replayGainDb) || Number.isFinite(t && t.replayPeak);
// Only build the audio graph when there's actually something to apply (or it
// already exists), preserving default behavior for libraries without RG.
if (M.replayGain.enabled && (hasData || M.gainNode || M.replayGain.preampDb)) {
M.ensureAudioGraph && M.ensureAudioGraph();
}
const node = M.gainNode;
if (!node) return;
setGain(node, computeLinearGain(t));
};
M.setReplayGainEnabled = function(enabled) {
M.replayGain.enabled = !!enabled;
localStorage.setItem(LS_ENABLED, M.replayGain.enabled ? "true" : "false");
M.applyReplayGain();
M.updateReplayGainUI && M.updateReplayGainUI();
M.saveReplayGainPrefs && M.saveReplayGainPrefs();
};
M.setReplayGainPreamp = function(db) {
M.replayGain.preampDb = clampPreamp(db);
localStorage.setItem(LS_PREAMP, String(M.replayGain.preampDb));
M.applyReplayGain();
M.updateReplayGainUI && M.updateReplayGainUI();
M.saveReplayGainPrefs && M.saveReplayGainPrefs();
};
// Debounced persistence to the server (per-account). localStorage is the
// immediate fallback for guests/offline.
let saveTimer = null;
M.saveReplayGainPrefs = function() {
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
saveTimer = null;
const body = {
replaygain_enabled: M.replayGain.enabled ? "true" : "false",
replaygain_preamp: String(M.replayGain.preampDb),
};
fetch("/api/auth/me/preferences", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}).catch(() => {});
}, 400);
};
// Hydrate from the /api/auth/me preferences object (called by auth.js).
M.loadReplayGainPrefs = function(prefs) {
if (!prefs) return;
if (prefs.replaygain_enabled != null) {
M.replayGain.enabled = prefs.replaygain_enabled === "true";
localStorage.setItem(LS_ENABLED, M.replayGain.enabled ? "true" : "false");
}
if (prefs.replaygain_preamp != null) {
const v = Number.parseFloat(prefs.replaygain_preamp);
if (Number.isFinite(v)) {
M.replayGain.preampDb = clampPreamp(v);
localStorage.setItem(LS_PREAMP, String(M.replayGain.preampDb));
}
}
M.applyReplayGain();
M.updateReplayGainUI && M.updateReplayGainUI();
};
// ---- UI ----
function initReplayGainUI() {
const btn = M.$("#btn-replaygain");
const popover = M.$("#replaygain-popover");
const enabledCheckbox = M.$("#rg-enabled");
const preampSlider = M.$("#rg-preamp");
const preampValue = M.$("#rg-preamp-value");
if (!btn) return;
function open() {
if (!popover) return;
popover.classList.remove("hidden");
document.addEventListener("pointerdown", onOutside, true);
document.addEventListener("keydown", onKey);
}
function close() {
if (!popover) return;
popover.classList.add("hidden");
document.removeEventListener("pointerdown", onOutside, true);
document.removeEventListener("keydown", onKey);
}
function toggle() {
if (popover && popover.classList.contains("hidden")) open();
else close();
}
function onOutside(e) {
if (popover && !popover.contains(e.target) && e.target !== btn) close();
}
function onKey(e) {
if (e.key === "Escape") close();
}
btn.onclick = (e) => {
e.stopPropagation();
toggle();
};
if (enabledCheckbox) {
enabledCheckbox.onchange = () => M.setReplayGainEnabled(enabledCheckbox.checked);
}
if (preampSlider) {
preampSlider.min = String(PREAMP_MIN);
preampSlider.max = String(PREAMP_MAX);
preampSlider.step = String(PREAMP_STEP);
preampSlider.oninput = () => M.setReplayGainPreamp(Number.parseFloat(preampSlider.value));
}
M.updateReplayGainUI = function() {
if (btn) btn.classList.toggle("active", M.replayGain.enabled);
if (enabledCheckbox) enabledCheckbox.checked = M.replayGain.enabled;
if (preampSlider) preampSlider.value = String(M.replayGain.preampDb);
if (preampValue) {
const db = M.replayGain.preampDb;
preampValue.textContent = (db > 0 ? "+" : "") + (Number.isInteger(db) ? db : db.toFixed(1)) + " dB";
}
};
M.updateReplayGainUI();
}
document.addEventListener("DOMContentLoaded", initReplayGainUI);
})();

View File

@ -267,33 +267,6 @@ h3 { font-size: 0.8rem; color: #999; margin-bottom: 0.3rem; text-transform: uppe
#btn-mute:hover { opacity: 1; }
#volume { width: 120px; accent-color: #4e8; }
/* ReplayGain control */
#replaygain-wrap { position: relative; }
#btn-replaygain { font-size: 0.7rem; cursor: pointer; color: #666; transition: color 0.2s, text-shadow 0.2s; letter-spacing: 0.05em; user-select: none; }
#btn-replaygain:hover { color: #888; }
#btn-replaygain.active { color: #4e8; text-shadow: 0 0 6px #4e8; }
#replaygain-popover {
position: absolute;
bottom: calc(100% + 0.5rem);
right: 0;
background: #1a1a1a;
border: 1px solid #333;
border-radius: 6px;
padding: 0.6rem 0.75rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 210px;
z-index: 50;
box-shadow: 0 4px 16px rgba(0,0,0,0.5);
font-size: 0.8rem;
}
.rg-row { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; }
.rg-row > span:first-child { color: #aaa; }
#rg-preamp { width: 90px; accent-color: #4e8; }
#rg-preamp-value { font-size: 0.7rem; color: #888; min-width: 3rem; text-align: right; }
#rg-enabled { accent-color: #4e8; width: 16px; height: 16px; }
/* Common */
button { background: #222; color: #eee; border: 1px solid #333; padding: 0.4rem 1rem; border-radius: 4px; cursor: pointer; font-size: 0.85rem; }
button:hover { background: #333; }
@ -714,14 +687,6 @@ button:hover { background: #333; }
justify-content: center;
}
#volume { width: min(160px, 55vw); height: 44px; }
#btn-replaygain {
min-width: 44px;
min-height: 44px;
display: flex;
align-items: center;
justify-content: center;
}
#replaygain-popover { right: auto; left: 50%; transform: translateX(-50%); }
.track-actions .track-menu-btn {
opacity: 1;
width: 44px;

View File

@ -4,11 +4,6 @@
(function() {
const M = window.MusicRoom;
// Single source of truth for a track's display title
function getTitle(track) {
return track?.title?.trim() || (track?.filename || track?.id || "Unknown").replace(/\.[^.]+$/, "");
}
/**
* Render a track row element (pure rendering, no handlers)
* @param {Object} track - Track object with id, title, filename, duration
@ -50,7 +45,7 @@
div.dataset.view = view;
// Build title
const title = getTitle(track);
const title = track.title?.trim() || (track.filename || trackId || "Unknown").replace(/\.[^.]+$/, "");
div.title = title;
// Build HTML
@ -61,7 +56,7 @@
${checkmark}
<span class="cache-indicator"></span>
${trackNum}
<span class="track-title">${M.escapeHtml(title)}</span>
<span class="track-title">${escapeHtml(title)}</span>
<span class="track-actions">
<span class="duration">${M.fmt(track.duration)}</span>
<button type="button" class="track-menu-btn" title="Track actions" aria-label="Track actions"></button>
@ -75,10 +70,17 @@
return div;
}
// HTML escape helper
function escapeHtml(str) {
if (!str) return '';
return str.replace(/[&<>"']/g, c => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
})[c]);
}
// Export
M.trackComponent = {
render,
getTitle,
escapeHtml: M.escapeHtml
escapeHtml
};
})();

View File

@ -597,7 +597,7 @@
async function playTrack(track, index) {
const trackId = track.id || track.filename;
const title = M.trackComponent.getTitle(track);
const title = track.title?.trim() || (track.filename || trackId || "Unknown").replace(/\.[^.]+$/, "");
if (type === 'queue') {
// Jump to track in queue
@ -619,7 +619,6 @@
M.currentTrackId = trackId;
M.serverTrackDuration = track.duration;
M.setTrackTitle(title);
M.applyReplayGain && M.applyReplayGain(track);
M.loadingSegments.clear();
const cachedUrl = await M.loadTrackBlob(trackId);
M.audio.src = cachedUrl || M.getTrackUrl(trackId);
@ -633,12 +632,11 @@
async function previewTrack(track) {
const trackId = track.id || track.filename;
const title = M.trackComponent.getTitle(track);
const title = track.title?.trim() || (track.filename || trackId || "Unknown").replace(/\.[^.]+$/, "");
M.currentTrackId = trackId;
M.serverTrackDuration = track.duration;
M.setTrackTitle(title);
M.applyReplayGain && M.applyReplayGain(track);
M.loadingSegments.clear();
const cachedUrl = await M.loadTrackBlob(trackId);
@ -658,7 +656,7 @@
function showContextMenu(e, track, index, canEditQueue) {
const trackId = track.id || track.filename;
const title = M.trackComponent.getTitle(track);
const title = track.title?.trim() || (track.filename || trackId || "Unknown").replace(/\.[^.]+$/, "");
const sel = selection[type];
const hasSelection = sel.size > 0;

View File

@ -304,14 +304,14 @@
for (const [playlistId, group] of byPlaylist) {
if (group.name) {
html += `<div class="slow-queue-playlist-header">📁 ${M.escapeHtml(group.name)}</div>`;
html += `<div class="slow-queue-playlist-header">📁 ${group.name}</div>`;
}
html += group.items.map((item, i) => {
const isNext = queuedItems.indexOf(item) === 0;
return `
<div class="slow-queue-item${isNext ? ' next' : ''}" data-id="${item.id}">
<span class="slow-queue-item-icon">${isNext ? '⏳' : '·'}</span>
<span class="slow-queue-item-title">${M.escapeHtml(item.title)}</span>
<span class="slow-queue-item-title">${item.title}</span>
<button class="slow-queue-cancel" title="Cancel"></button>
</div>
`;

View File

@ -7,18 +7,6 @@
// DOM selector helper
M.$ = (s) => document.querySelector(s);
// Shared HTML escaping helper - use for any server-controlled string
// interpolated into innerHTML (text and attribute contexts)
M.escapeHtml = function(str) {
if (str == null) return "";
return String(str)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
};
// Format seconds as m:ss
M.fmt = function(sec) {
if (!sec || !isFinite(sec)) return "0:00";
@ -122,7 +110,7 @@
const div = document.createElement("div");
div.className = "history-item history-" + item.type;
const time = item.time.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
div.innerHTML = `<span class="history-time">${time}</span> ${M.escapeHtml(item.message)}`;
div.innerHTML = `<span class="history-time">${time}</span> ${item.message}`;
list.appendChild(div);
}
};
@ -158,7 +146,7 @@
document.title = title ? `${title} - MusicRoom` : "MusicRoom";
// First set simple content to measure
marqueeEl.innerHTML = `<span id="track-title">${M.escapeHtml(title)}</span>`;
marqueeEl.innerHTML = `<span id="track-title">${title}</span>`;
// Check if title overflows and needs scrolling
requestAnimationFrame(() => {
@ -168,7 +156,7 @@
// Duplicate text for seamless wrap-around scrolling
if (needsScroll) {
marqueeEl.innerHTML = `<span id="track-title">${M.escapeHtml(title)}</span><span class="marquee-spacer">&nbsp;&nbsp;&nbsp;•&nbsp;&nbsp;&nbsp;</span><span>${M.escapeHtml(title)}</span><span class="marquee-spacer">&nbsp;&nbsp;&nbsp;•&nbsp;&nbsp;&nbsp;</span>`;
marqueeEl.innerHTML = `<span id="track-title">${title}</span><span class="marquee-spacer">&nbsp;&nbsp;&nbsp;•&nbsp;&nbsp;&nbsp;</span><span>${title}</span><span class="marquee-spacer">&nbsp;&nbsp;&nbsp;•&nbsp;&nbsp;&nbsp;</span>`;
}
});
};

View File

@ -17,7 +17,6 @@
let fullscreenButton = null;
let audioContext = null;
let source = null;
let gainNode = null;
let analyser = null;
let frequencyData = null;
let waveformData = null;
@ -157,20 +156,11 @@
analyser.smoothingTimeConstant = 0.68;
source = audioContext.createMediaElementSource(M.audio);
// Topology: source -> gainNode -> analyser -> destination.
// gainNode is shared with ReplayGain (M.gainNode); analyser is a
// transparent pass-through, so visualizer-off is unaffected.
gainNode = audioContext.createGain();
source.connect(gainNode);
gainNode.connect(analyser);
source.connect(analyser);
analyser.connect(audioContext.destination);
M.gainNode = gainNode;
frequencyData = new Uint8Array(analyser.frequencyBinCount);
waveformData = new Uint8Array(analyser.fftSize);
// Graph may be built after the first track arrives; re-apply current gain.
M.applyReplayGain?.(M.currentTrack);
return true;
} catch (error) {
graphUnavailable = true;
@ -179,16 +169,6 @@
}
}
// Build the audio graph (if not already) and resume the context if needed.
// Used by ReplayGain so the gain node exists even with the visualizer off.
M.ensureAudioGraph = function() {
if (!initAudioGraph()) return false;
if (audioContext && audioContext.state === "suspended") {
audioContext.resume().catch(() => {});
}
return true;
};
function startVisualizer() {
if (animationId || mode === "off") return;
animationId = requestAnimationFrame(draw);
@ -787,12 +767,10 @@
});
M.audio.addEventListener("play", () => {
// Resume context whenever the graph exists (visualizer or replaygain path),
// since routing through it requires a running context to produce sound.
if (mode !== "off") {
if (audioContext && audioContext.state === "suspended") {
audioContext.resume().catch(() => {});
}
if (mode !== "off") {
startVisualizer();
}
});

View File

@ -9,8 +9,6 @@ import {
getAllUsers,
grantPermission,
revokePermission,
getAllUserPreferences,
setUserPreference,
} from "../db";
import {
getUser,
@ -95,17 +93,6 @@ export function handleLogout(req: Request): Response {
);
}
// Whitelisted per-account preference keys (key -> parser/normalizer).
// Add new keys here as features need per-account persistence.
const PREFERENCE_KEYS: Record<string, (raw: unknown) => string | null> = {
replaygain_enabled: (raw) => (raw === true || raw === "true" ? "true" : raw === false || raw === "false" ? "false" : null),
replaygain_preamp: (raw) => {
const n = typeof raw === "number" ? raw : Number.parseFloat(String(raw));
if (!Number.isFinite(n)) return null;
return String(Math.max(-24, Math.min(24, n)));
},
};
// Auth: get current user
export function handleGetMe(req: Request, server: any): Response {
const { user, headers } = getOrCreateUser(req, server);
@ -129,38 +116,9 @@ export function handleGetMe(req: Request, server: any): Response {
return Response.json({
user: { id: user.id, username: user.username, isAdmin: user.is_admin, isGuest: user.is_guest },
permissions: effectivePermissions,
preferences: getAllUserPreferences(user.id),
}, { headers });
}
// Preferences: update per-account preferences (whitelisted keys only)
export async function handleUpdatePreferences(req: Request, server: any): Promise<Response> {
const { user } = getOrCreateUser(req, server);
if (!user) {
return Response.json({ error: "Not authenticated" }, { status: 401 });
}
let body: any;
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON" }, { status: 400 });
}
if (!body || typeof body !== "object" || Array.isArray(body)) {
return Response.json({ error: "Expected an object" }, { status: 400 });
}
const applied: Record<string, string> = {};
for (const [key, raw] of Object.entries(body)) {
const normalize = PREFERENCE_KEYS[key];
if (!normalize) continue; // ignore unknown keys
const value = normalize(raw);
if (value == null) continue; // ignore invalid values
setUserPreference(user.id, key, value);
applied[key] = value;
}
return Response.json({ success: true, preferences: applied });
}
// Kick all other clients for current user
export function handleKickOthers(req: Request, server: any): Response {
const { user } = getOrCreateUser(req, server);

View File

@ -9,7 +9,6 @@ import {
handleLogin,
handleLogout,
handleGetMe,
handleUpdatePreferences,
handleKickOthers,
handleListUsers,
handleGrantPermission,
@ -213,9 +212,6 @@ export function createRouter() {
if (path === "/api/auth/me") {
return handleGetMe(req, server);
}
if (path === "/api/auth/me/preferences" && req.method === "PUT") {
return handleUpdatePreferences(req, server);
}
if (path === "/api/auth/kick-others" && req.method === "POST") {
return handleKickOthers(req, server);
}

View File

@ -3,27 +3,22 @@ import { join } from "path";
import { PUBLIC_DIR } from "../config";
// Serve static files
// Defense-in-depth CSP: no inline scripts, same-origin + ws(s) connections,
// blob: media for cached audio, data:/blob: images, inline styles allowed
// (style attributes are used throughout the client).
const CSP = "default-src 'self'; script-src 'self'; connect-src 'self' ws: wss:; media-src 'self' blob:; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'";
export async function handleStatic(path: string): Promise<Response | null> {
if (path === "/" || path === "/index.html" || path.startsWith("/listen/")) {
return new Response(file(join(PUBLIC_DIR, "index.html")), {
headers: { "Content-Type": "text/html", "Content-Security-Policy": CSP },
headers: { "Content-Type": "text/html" },
});
}
if (path === "/styles.css") {
return new Response(file(join(PUBLIC_DIR, "styles.css")), {
headers: { "Content-Type": "text/css", "Content-Security-Policy": CSP },
headers: { "Content-Type": "text/css" },
});
}
if (path === "/favicon.ico") {
return new Response(file(join(PUBLIC_DIR, "favicon.ico")), {
headers: { "Content-Type": "image/x-icon", "Content-Security-Policy": CSP },
headers: { "Content-Type": "image/x-icon" },
});
}
@ -31,7 +26,7 @@ export async function handleStatic(path: string): Promise<Response | null> {
const jsFile = file(join(PUBLIC_DIR, path.slice(1)));
if (await jsFile.exists()) {
return new Response(jsFile, {
headers: { "Content-Type": "application/javascript", "Content-Security-Policy": CSP },
headers: { "Content-Type": "application/javascript" },
});
}
}

View File

@ -4,7 +4,6 @@ import { init } from "./init";
import { createRouter } from "./routes";
import { websocketHandlers } from "./websocket";
await init();
serve({

View File

@ -1,36 +0,0 @@
# TODO — Implementation Plans
Eight plans derived from the architecture assessment, ordered by priority and with
effort/risk so you can sequence the work. Each lives in `todo/<topic>/overview.md`.
## Critical / High — do first (all low effort, low risk)
| # | Topic | Priority | Effort | Depends on |
|---|-------|----------|--------|------------|
| 1 | [xss-fixes](xss-fixes/overview.md) — escape server data at `innerHTML`; add CSP | Critical | Low | — |
| 2 | [websocket-robustness](websocket-robustness/overview.md) — try/catch parse, reconnect backoff, dead-channel fallback | High | LowMed | — |
| 3 | [ws-guest-control-permission](ws-guest-control-permission/overview.md) — route WS control through `userHasPermission` | High | Trivial | — |
| 4 | [channel-get-auth](channel-get-auth/overview.md) — add auth to `GET /api/channels/:id` | High | Trivial | — |
Items 14 are independent and can be done in parallel. Each is a small, isolated change.
## Medium — correctness and efficiency
| # | Topic | Priority | Effort | Depends on |
|---|-------|----------|--------|------------|
| 5 | [fetch-response-validation](fetch-response-validation/overview.md) — `res.ok` checks before `res.json()` | Medium | Low | — |
| 6 | [duplicate-download-race](duplicate-download-race/overview.md) — synchronous check-and-claim for bulk downloads | Medium | Low | — |
| 7 | [client-cache-correctness](client-cache-correctness/overview.md) — revoke blob URLs, LRU prune, real `streamOnly` | Medium | Medium | #6 (shares `downloadAndCacheTrack`) |
## Strategic — refactor, do last
| # | Topic | Priority | Effort | Depends on |
|---|-------|----------|--------|------------|
| 8 | [client-store-and-windowing](client-store-and-windowing/overview.md) — virtualize list + minimal store + decompose god module | Strategic | High | #1, #6, #7 (inherit correct behavior first) |
## Suggested order
1, 3, 4 (one-line/server-side, ship immediately) → 2 → 5 → 6 → 7 → 8.
All plans include affected file:line references, a step-by-step implementation
sketch, validation steps, and rollback notes.

View File

@ -1,74 +0,0 @@
# Add Authentication to `GET /api/channels/:id`
Priority: **High** · Effort: **Trivial (3 lines)** · Risk: **Low**
## Problem
Every sibling channel endpoint calls `getOrCreateUser(req, server)` and returns 401 if there is no user. The GET-state endpoint does not:
```ts
// routes/channels.ts:167-171
export function handleGetChannel(channelId: string): Response {
const channel = state.channels.get(channelId);
if (!channel) return new Response("Not found", { status: 404 });
return Response.json(channel.getState());
}
```
`Channel.getState()` (`channel.ts:142-159`) returns the queue, `currentIndex`, listener count, the `isDefault` flag, and (when requested) the full track list. Any unauthenticated caller can enumerate and read the state of every channel.
## Affected Location
- `routes/channels.ts:167-171``handleGetChannel`, missing auth.
Also note: this handler's signature differs from its siblings (it takes only `channelId`, not `req, server, channelId`). The router call at `routes/index.ts:111-114` reflects this. Both must be updated.
## Implementation Plan
### Step 1 — Update the handler signature and add the auth check
```ts
// routes/channels.ts
import { getOrCreateUser } from "./helpers";
// GET /api/channels/:id - get channel state
export function handleGetChannel(req: Request, server: any, channelId: string): Response {
const { user } = getOrCreateUser(req, server);
if (!user) {
return Response.json({ error: "Authentication required" }, { status: 401 });
}
const channel = state.channels.get(channelId);
if (!channel) return new Response("Not found", { status: 404 });
return Response.json(channel.getState());
}
```
### Step 2 — Update the router call site
`routes/index.ts:111-114`:
```ts
const channelGetMatch = path.match(/^\/api\/channels\/([^/]+)$/);
if (channelGetMatch && req.method === "GET") {
return handleGetChannel(req, server, channelGetMatch[1]);
}
```
(Pass `req` and `server` through, matching the DELETE/PATCH handlers above.)
### Step 3 — Consider whether state should be filtered by listener
Today `getState()` does not return the `listeners` array (only `listenerCount`) — good. Confirm this remains true; if `listeners` is ever added to `getState()`, also gate it behind the same ownership/permission rules used by `getListInfo()` (`channel.ts:377-389`), which *does* expose usernames. (Out of scope for this fix, but worth a note: the channel *list* endpoint exposes listener usernames to any authenticated user — acceptable for a listen-along app, but verify it matches the product intent.)
## Validation
- **Unauthenticated request is rejected**: `curl -i http://localhost:3001/api/channels/main` → expect `401` (previously `200` with full state).
- **Authenticated request still works**: `curl -i -b cookies.txt http://localhost:3001/api/channels/main` → expect `200` with state JSON.
- **Guest access**: with `allowGuests: true`, an unauthenticated curl should now receive a `Set-Cookie` guest session *and* still be able to read state on the next request (guests can listen). Confirm the second request returns 200.
- **Client still works**: load the app, switch channels, confirm no regression (the client always sends the session cookie).
## Risk / Rollback
- The client already authenticates every request via cookie, so legitimate UI is unaffected.
- If any external/SSR/integration consumer relied on the open endpoint, they will now get 401 — re-grant via a real session. This was never intended public surface.
- Rollback = revert the handler signature and the router call.

View File

@ -1,155 +0,0 @@
# Client Cache Correctness: Revoke Blob URLs, LRU Pruning, Real `streamOnly`
Priority: **Medium** · Effort: **Medium** · Risk: **Low**
## Problem
Three independent correctness/efficiency bugs in the client caching layer:
1. **Blob URL leak.** `URL.createObjectURL(blob)` results stored in `M.trackBlobs` (`public/audioCache.js:80,127`) are never revoked. `M.trackBlobs.clear()` (`queue.js:188`) drops the references but the URLs stay live in the document until unload — a slow memory leak over long sessions with many cached tracks.
2. **`pruneCache` is expensive and non-LRU.** `public/audioCache.js:27-54` calls `TrackStorage.get(key)` for every cached track (pulling each blob out of IndexedDB) just to read `.size`, and evicts oldest-first by Map iteration order — *not* by the `cachedAt` timestamp that is actually written at `public/trackStorage.js:86`. So eviction is arbitrary, not least-recently-used.
3. **`streamOnly` doesn't do what it says.** The flag is stored (`audioCache.js:8-15`) and checked by exactly one context-menu item (`trackContainer.js:752`), but the background prefetch loop (`audioCache.js:226`) never consults it — so "stream-only mode" still fetches every segment in the background and still triggers bulk caching.
## Affected Locations
- `public/audioCache.js:27-54``pruneCache`
- `public/audioCache.js:80,127` — blob URL creation
- `public/audioCache.js:224-262` — prefetch loop (no `streamOnly` check)
- `public/trackStorage.js:139-155``getStats` (loads all blobs)
- `public/trackStorage.js:86``cachedAt` is written but unused
- `public/queue.js:188``M.trackBlobs.clear()` without revoke
## Implementation Plan
### Part A — Track and revoke blob URLs
**Step A1: Track blob URLs in a single Map with a revocation helper.**
`M.trackBlobs` is already `Map<trackId, blobUrl>`. Add:
```js
// public/audioCache.js
M.revokeTrackBlob = function (trackId) {
const url = M.trackBlobs.get(trackId);
if (url) {
URL.revokeObjectURL(url);
M.trackBlobs.delete(trackId);
}
};
```
**Step A2: Revoke on eviction and on explicit clear.**
- In `pruneCache` (after Part B), when a track is evicted from IndexedDB, also call `M.revokeTrackBlob(trackId)` so the in-memory URL is released.
- In `queue.js:188` (`clearAllCaches`), revoke every entry before clearing:
```js
for (const url of M.trackBlobs.values()) URL.revokeObjectURL(url);
M.trackBlobs.clear();
```
- When a track is removed from the library (`track_removed` handler in `channelSync.js`), revoke its blob if present (it can't be played anymore).
**Step A3: Don't double-revoke.** `URL.revokeObjectURL` is safe to call on an already-revoked URL, but guard with the Map check anyway to keep state clean.
### Part B — Make pruning LRU and cheap
**Step B1: Store size at write time, avoid loading blobs at prune time.**
Extend the IndexedDB record to carry `size` (the blob already has `.size` — store it alongside). In `trackStorage.js`:
```js
// in set(): store { filename (keyPath), blob, size, cachedAt }
const record = { filename: trackId, blob, size: blob.size, cachedAt: Date.now() };
```
Add a lightweight metadata accessor that uses a cursor and reads only `size`/`cachedAt`, not the blob:
```js
// trackStorage.js
getMetaList: function () {
return new Promise((resolve) => {
const result = [];
const tx = db.transaction(STORE, "readonly");
const store = tx.objectStore(STORE);
const req = store.openCursor();
req.onsuccess = (e) => {
const cursor = e.target.result;
if (cursor) {
const v = cursor.value;
result.push({ id: v.filename, size: v.size || 0, cachedAt: v.cachedAt || 0 });
cursor.continue();
} else {
resolve(result);
}
};
req.onerror = () => resolve([]);
});
}
```
**Step B2: Rewrite `pruneCache` to be LRU and blob-free.**
```js
// audioCache.js
async function pruneCache() {
const limit = M.cacheLimitBytes ?? 500 * 1024 * 1024; // tune as needed
const meta = await TrackStorage.getMetaList();
let total = meta.reduce((s, m) => s + m.size, 0);
if (total <= limit) return;
// Evict least-recently-used first.
meta.sort((a, b) => a.cachedAt - b.cachedAt);
for (const m of meta) {
if (total <= limit) break;
await TrackStorage.delete(m.id);
M.revokeTrackBlob(m.id);
M.cachedTracks.delete(m.id);
total -= m.size;
}
}
```
**Step B3: Update `cachedAt` on access** (optional, makes LRU reflect actual use). When a cached track is played (`loadTrackBlob` returns a URL), bump its `cachedAt`. If skipped, the policy becomes "first-in-first-out", which is still better than today's arbitrary order.
**Step B4: Rewrite `getStats`** to use `getMetaList` so the settings/stats panel doesn't load every blob either.
### Part C — Make `streamOnly` actually disable background fetching
**Step C1: Consult the flag in the prefetch loop.**
In `audioCache.js:226` (top of the prefetch loop):
```js
M.prefetchSegments = async function () {
if (prefetching) return;
if (M.streamOnly) return; // <-- new
prefetching = true;
try {
// ... existing logic ...
} finally {
prefetching = false;
}
};
```
**Step C2: Also short-circuit the buffered-range-scan-triggered bulk download when in stream-only mode**, since streaming clients don't want IndexedDB writes. Easiest: have `maybeStartBulkDownload` (see `todo/duplicate-download-race/overview.md`) check `M.streamOnly` and return `false`.
**Step C3: Decide intent for the already-playing track.** Even in stream-only mode the *current* track is being buffered by the browser's own media element — that's fine and desirable. The flag is about suppressing *additional* segment prefetching ahead of the playhead and *bulk* caching. Confirm the UX label reflects this ("Don't pre-cache ahead" rather than "stream nothing").
## Validation
- **Blob revoke**: open DevTools → Memory, take a snapshot; play and fully cache ~10 tracks; confirm `trackBlobs` grows by 10 and the document's blob URL count grows accordingly. Trigger a prune (or set a tiny `cacheLimitBytes`) and confirm the count drops as tracks are evicted. Run `clearAllCaches()` and confirm all blob URLs are revoked.
- **LRU**: with a small cache limit, cache tracks A, B, C; play A again (bump cachedAt if Part B3 is implemented); cache D. Confirm B (not A) is evicted.
- **Prune performance**: with a large cache (e.g. 200 tracks), instrument `pruneCache` and confirm it no longer reads blob payloads — wall time should drop from "loads every blob" to a cheap cursor scan.
- **streamOnly**: toggle the flag on, play a track, seek around, and confirm via DevTools Network that only the media element's own range requests fire (no `/api/tracks/:id` segment prefetches), and IndexedDB write count stays flat. Toggle off and confirm prefetching resumes.
- **Regression**: with streamOnly off, confirm normal caching behavior (green indicators, blob swap, IndexedDB entries) is unchanged.
## Risk / Rollback
- **IndexedDB schema change** (adding `size`/`cachedAt` fields to the record): old records written before this change will lack those fields. `getMetaList` must default missing fields to `0` (shown above), and `pruneCache` must handle `size === 0` gracefully (skip eviction of unknown-size entries rather than evicting everything). Consider a one-time migration that deletes records lacking `size`, or simply let them age out.
- Revoking a blob URL that is *currently* the `src` of the audio element will break playback. Only revoke blobs for tracks that are not the currently-playing track, or that have just been removed from the library. Add a guard: `if (trackId === M.currentTrackId) return;` in `revokeTrackBlob` callers that run during playback.
- streamOnly is additive; default stays off.
- Rollback per part is independent — A, B, C can land separately.

View File

@ -1,154 +0,0 @@
# Client Store & List Windowing (Strategic Refactor)
Priority: **Medium (strategic)** · Effort: **High** · Risk: **Medium**
This is the largest item of the eight. Unlike the others, it is a refactor rather than a bug fix. It should be sequenced *after* the XSS, cache, and WS work so the new structure inherits correct behavior. It can ship incrementally.
## Problem
The client is a pre-module vanilla-JS app that has outgrown its structure:
1. **One mutable global** (`window.MusicRoom` / `M`, `public/core.js:4-73`) holds *all* state — audio element, WS, current track, queue, library, cache maps, permission flags, and UI bookkeeping (`lastProgressPct`, etc.). Every IIFE mutates `M` directly and calls `M.render*()`. There is no contract between modules; forward references are sometimes guarded with `M.foo && M.foo()` (`channelSync.js:502`), often not.
2. **Full re-render of every row on every change.** `trackContainer.js:101-165` clears `innerHTML` and rebuilds every track row — triggered by every WS state update, every 5s cache poll (`ui.js:175-182`), and every prefetch completion. No windowing/virtualization: a 10k-track library renders 10k `.track` divs with fresh closures each time. Search (`queue.js:196-204`) filters the full array synchronously per keystroke.
3. **God module.** `public/trackContainer.js` (972 lines) fuses rendering, drag state, selection, drop-zones, and context-menu DOM.
4. **Duplicated logic**: local-playback setup (4×), cookie get/set/clear (3×), `escapeHtml` (2×), segment-availability scan (3×).
## Affected Locations
- `public/core.js:4-73` — global state
- `public/trackContainer.js` (972 lines) — render + drag + selection + context menu
- `public/trackContainer.js:101-165``render()` full clear+rebuild
- `public/ui.js:175-182` — 5s cache-poll re-render trigger
- `public/queue.js:196-204` — synchronous per-keystroke filter
- All IIFEs in `public/*.js` — module pattern
## Goals (in priority order)
1. **Virtualize the library list** so 10k+ tracks render smoothly.
2. **Introduce a tiny reactive store** so state changes are explicit and modules subscribe rather than mutate globals.
3. **Decompose `trackContainer.js`** into focused modules.
4. **De-duplicate** playback setup, cookie helpers, escaping.
Non-goals: adopting a framework (React/Vue/etc.). Bun serves static files with no build step; introducing one is out of scope unless explicitly desired. This plan stays vanilla.
## Implementation Plan
The plan is staged so each phase ships value independently.
### Phase 1 — Virtualize the list (highest standalone value)
Even without a store refactor, windowing fixes the worst performance problem.
**1.1 Add a windowed renderer** for the library (and queue when long). Only render rows visible in the viewport plus a small overscan buffer (e.g. 10 rows above/below). Use a sentinel/spacer div with the full scroll height so the scrollbar stays accurate.
Sketch (`trackContainer.js`):
```js
const ROW_HEIGHT = 44; // measure actual rendered row height
const OVERSCAN = 10;
function renderWindow(container, items, scrollTop, viewportHeight) {
const totalHeight = items.length * ROW_HEIGHT;
const firstVisible = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - OVERSCAN);
const visibleCount = Math.ceil(viewportHeight / ROW_HEIGHT) + OVERSCAN * 2;
const slice = items.slice(firstVisible, firstVisible + visibleCount);
container.innerHTML = ""; // or keep a stable spacer + content wrapper
const spacerTop = document.createElement("div");
spacerTop.style.height = `${firstVisible * ROW_HEIGHT}px`;
const spacerBottom = document.createElement("div");
spacerBottom.style.height = `${(items.length - firstVisible - slice.length) * ROW_HEIGHT}px`;
container.appendChild(spacerTop);
for (let i = 0; i < slice.length; i++) {
container.appendChild(renderRow(slice[i], firstVisible + i));
}
container.appendChild(spacerBottom);
}
```
**1.2 Drive renders from `scroll` events** (passive listener) and `requestAnimationFrame`-throttled. Debounce on resize. Do *not* re-render on every WS update — instead mark rows dirty and only update the visible slice.
**1.3 Index rows by track id** so targeted updates (e.g. a single track's cache status changes) patch a specific DOM node instead of rebuilding the list.
**1.4 Move search filtering to the model layer**: maintain `M.libraryFiltered` as a computed array; the filter runs once per query (debounced ~150ms), and the windowed renderer reads from it. Never re-filter on every keystroke synchronously.
Deliverable: a library that scrolls smoothly at 10k tracks.
### Phase 2 — Introduce a minimal reactive store
Replace ad-hoc `M.x = …; M.render()` with a store that notifies subscribers.
**2.1 Store shape** (new file `public/store.js`):
```js
(function () {
const M = window.MusicRoom;
const state = {}; // the actual values
const subs = new Map(); // key -> Set<callback>
M.store = {
get(key) { return state[key]; },
set(key, value) {
if (Object.is(state[key], value)) return; // skip no-op
state[key] = value;
subs.get(key)?.forEach((cb) => cb(value));
},
update(key, fn) { M.store.set(key, fn(state[key])); },
on(key, cb) {
if (!subs.has(key)) subs.set(key, new Set());
subs.get(key).add(cb);
return () => subs.get(key)?.delete(cb); // unsubscribe
},
};
})();
```
**2.2 Migrate state field by field.** Don't do a big-bang rewrite. Start with the fields that change most and drive renders: `M.library`, `M.queue`, `M.cachedTracks`, `M.currentTrackId`. Each becomes `M.store.set("library", …)` and the renderer subscribes via `M.store.on("library", renderLibrary)`.
Keep the `M.library` getter as a compatibility shim (`Object.defineProperty(M, "library", { get: () => M.store.get("library") })`) so unmigrated callers keep working during the transition.
**2.3 Decouple renders from setters.** Today `audioCache.js` calls `M.renderQueue()` directly. After migration it just `M.store.set("cachedTracks", …)` and the queue renderer — which subscribed once — decides whether and what to re-render.
Deliverable: a single source of truth per field, explicit update points, and the ability to add per-field logging/invariants cheaply.
### Phase 3 — Decompose `trackContainer.js`
Split the 972-line file along its existing seams:
- `trackList.js` — the windowed renderer (from Phase 1) + list-level keyboard nav.
- `trackSelection.js` — the `selection`/`lastSelected` state (`trackContainer.js:11-22`) and click/shift-click range logic.
- `trackDrag.js` — drag state (`trackContainer.js:8,24-31`), drop-zone rendering, queue reorder calls.
- `trackContextMenu.js` — menu construction + DOM (`showContextMenuUI` at `:880-949`), built on top of the row events.
Each becomes a small module that subscribes to the store (Phase 2) and exposes a narrow API on `M.tracks.*`.
Deliverable: no file over ~400 lines in the client.
### Phase 4 — De-duplicate
- **Playback setup**: extract a single `M.loadAndPlay(track, { seek: 0 })` used by `init.js`, `controls.js`, and both call sites in `trackContainer.js`. Today it's copy-pasted 4× (see assessment).
- **Cookie helpers**: one `M.prefs.get/set/clear` (with `Secure` added — see XSS plan) replacing the three copies in `core.js`, `themes.js`, `visualizer.js`.
- **`escapeHtml`**: single `M.escapeHtml` (already part of the XSS plan).
- **Segment scan**: one `M.getBufferedSegments(audio, trackId)` used by `audioCache.js`, `ui.js`, `controls.js`.
Deliverable: fewer copies, clearer ownership.
## Validation
- **List performance**: load a fixture library of 10k tracks (synthesize or copy metadata rows). Measure initial render time, scroll FPS, and keystroke-to-render latency in DevTools Performance. Target: 60fps scroll, <100ms keystroke response.
- **Correctness parity**: after each phase, verify against a manual checklist — play, pause, seek, jump, add-to-queue, remove-from-queue, drag-reorder, multi-select, context-menu actions, cache indicator updates, search filter, channel switch. Each phase must preserve all of these.
- **Store**: add a temporary `M.store.on("library", (v) => console.count("library"))` and confirm the count matches expected update frequency (not 5× per WS message).
- **No regressions in cache behavior**: the windowed render must still update a row's cache indicator when its blob completes — verify by playing a track and watching its row in a scrolled-out list update without a full re-render.
- **Decomposition**: confirm no module exceeds ~400 lines and that each can be reasoned about in isolation.
## Risk / Rollback
- This is the highest-risk item because it touches the most code. Mitigate by:
- Shipping phases in order; each is independently mergeable and each is a checkpoint.
- Keeping `M.library`-style getters as shims during Phase 2 so partial migrations don't break.
- Behind a fallback: if windowing introduces scroll glitches, the non-windowed path can be kept as `M.renderLegacyList` and re-enabled until fixed.
- No server or DB changes; rollback is purely client-side file reversion.
- Do **not** attempt this before the XSS, cache-race, and WS plans land — those fix correctness bugs that a refactor would otherwise carry forward or obscure.

View File

@ -1,111 +0,0 @@
# Fix Duplicate Full-Track Download Race in Client Cache
Priority: **Medium** · Effort: **Low** · Risk: **Low**
## Problem
`M.bulkDownloadStarted` is a per-track flag meant to ensure `downloadAndCacheTrack` runs at most once per track. But the flag is **set inside `downloadAndCacheTrack` after an `await`**, while multiple callers check it **before** that await resolves. When the last two segments complete near-simultaneously — one from the browser's buffered-range scan in `ui.js`, one from the explicit `fetchSegment` in `audioCache.js` — both callers observe `trackCache.size >= SEGMENTS` and both pass the `bulkDownloadStarted` guard before the first caller sets the flag. Result: the same track is fetched in full **twice**, wasting bandwidth and racing on the IndexedDB write.
## Affected Locations
The check+call pattern appears in three places, all racy:
- `public/audioCache.js:99-107``checkAndCacheComplete`
- `public/ui.js:148-150` — buffer-segment scan
- `public/audioCache.js:183-187` — inside `fetchSegment`
And the flag is set here:
- `public/audioCache.js:110-112` — inside `downloadAndCacheTrack`, **after** `await M.loadTrackBlob(trackId)`.
## Root Cause
Guard-then-do where the guard write is not atomic with respect to the awaits surrounding it. JavaScript's single-threaded execution means a synchronous "check-and-set" is race-free, but here the set happens after the first `await` inside the function being guarded, so a second caller can enter the function and pass the check before the first caller reaches the set.
## Implementation Plan
### Step 1 — Move the flag set to be synchronous with the check
Refactor so the check and the set happen in the same synchronous tick, before any `await`. Create a single entry point:
```js
// public/audioCache.js
M.maybeStartBulkDownload = function (trackId) {
if (M.bulkDownloadStarted.get(trackId)) return false; // already started
if (M.cachedTracks.has(trackId)) return false; // already cached
const trackCache = M.trackCaches.get(trackId);
if (!trackCache || trackCache.size < SEGMENTS) return false; // not fully buffered
// All conditions met — claim the slot synchronously:
M.bulkDownloadStarted.set(trackId, true);
// Fire the async work without awaiting here:
M.downloadAndCacheTrack(trackId).catch((err) => {
console.warn("[audioCache] bulk download failed for", trackId, err);
M.bulkDownloadStarted.delete(trackId); // allow a later retry
});
return true;
};
```
Then make `downloadAndCacheTrack` **assume the flag is already set** (remove the guard inside it):
```js
M.downloadAndCacheTrack = async function (trackId) {
// Precondition: M.bulkDownloadStarted.get(trackId) === true (set by maybeStartBulkDownload)
const cachedUrl = await M.loadTrackBlob(trackId);
if (cachedUrl) { // already cached under us
M.cachedTracks.add(trackId);
M.bulkDownloadStarted.delete(trackId);
return cachedUrl;
}
// ... existing download + TrackStorage.set + URL.createObjectURL logic ...
M.cachedTracks.add(trackId);
M.bulkDownloadStarted.delete(trackId); // clear after success
M.renderQueue && M.renderQueue();
M.renderLibrary && M.renderLibrary();
return blobUrl;
};
```
### Step 2 — Replace all three call sites
Each caller becomes a single synchronous call:
**`audioCache.js` `checkAndCacheComplete`:**
```js
M.maybeStartBulkDownload(trackId);
```
(remove the old `if (...size >= SEGMENTS)` + `downloadAndCacheTrack` block.)
**`ui.js:148-150`** (buffered-range scan, after a segment is marked present):
```js
M.maybeStartBulkDownload(M.currentTrackId);
```
**`audioCache.js:183-187`** (inside `fetchSegment`, after marking the segment):
```js
M.maybeStartBulkDownload(trackId);
```
Because the check-and-claim is now synchronous, even if all three callers fire in the same tick, only the first will start the download.
### Step 3 — Guard the blob-URL swap during playback
`downloadAndCacheTrack` swaps `M.audio.src` to the blob URL mid-playback (`audioCache.js:213-220`). After the refactor, confirm this swap still checks `M.currentTrackId === trackId` and that `wasPlaying` is captured at the moment of the swap (not earlier). Keep the existing `play().catch(()=>{})`.
### Step 4 — (Related, recommended in same pass) Revoke blob URLs
While in this file, address the related memory leak: every `URL.createObjectURL` stored in `M.trackBlobs` is never revoked. See `todo/client-cache-correctness/overview.md` — that plan covers it. If doing both together, the `downloadAndCacheTrack` success path is the natural place to track the URL for later revocation.
## Validation
- **Race reproduction**: this is hard to trigger deterministically. Add a temporary `console.log("[bulk]", trackId)` at the top of the download body and another in `maybeStartBulkDownload` when it returns `true`. Play a track, let it fully buffer, and confirm exactly **one** "started" log and one completion per track — even when forcing the buffered-range scan and `fetchSegment` to both fire (e.g. seek near the end then back).
- **Error path**: temporarily make the download throw (e.g. point the track URL at a 404) and confirm `bulkDownloadStarted` is cleared so a later attempt can retry, rather than permanently preventing caching.
- **Already-cached path**: if a track is already in IndexedDB (`loadTrackBlob` returns a URL on the first line), confirm no full download is triggered and `cachedTracks` is updated.
- **UI**: confirm the buffer bar fills, the cache indicator turns green, and queue/library re-render exactly once per completed cache (not twice).
## Risk / Rollback
- The refactor centralizes three near-duplicate code paths into one — net simplification.
- Risk: if `downloadAndCacheTrack` is called from anywhere else that relied on the internal guard, that caller must be migrated to `maybeStartBulkDownload`. Grep for `downloadAndCacheTrack(` before merging.
- If a download fails after the flag is set and the catch handler fails to clear it, the track becomes uncachable until reload. The `.catch` in `maybeStartBulkDownload` is the safety net — confirm it clears the flag on all rejection paths.
- Rollback = revert `audioCache.js` and the two call-site edits in `ui.js`.

View File

@ -1,87 +0,0 @@
# Validate `fetch()` Responses Before Parsing JSON
Priority: **Medium** · Effort: **Low** · Risk: **Low**
## Problem
Several client `fetch` call sites parse the response body as JSON **without checking `res.ok`** (or `res.status`). When the server returns an error envelope (e.g. `{ error: "Authentication required" }` with 401) or a non-JSON body (proxy 502, HTML error page), the parsed object is then **assigned directly to application state** and immediately rendered — silently corrupting the UI.
## Affected Locations
| File:Line | Call | Current behavior on error |
|-----------|------|---------------------------|
| `public/queue.js:382` | `M.library = await res.json();` then `M.renderLibrary()` | The entire library silently becomes the error object; render runs on garbage. |
| `public/auth.js:11` | guest session bootstrap | Error body used as the user object. |
| `public/auth.js:101` | `/api/auth/me` | Error body used as the current user. |
| `public/channelSync.js:11` | `/api/channels` list | Error body assigned to `M.channels`; `channels.length === 0` check then behaves confusingly. |
(Other call sites in `playlists.js`, `upload.js`, etc. already do `if (!res.ok)` correctly — follow those as the model.)
## Implementation Plan
### Step 1 — Add a shared helper in `public/utils.js`
Centralize the check so it can't be forgotten again:
```js
M.apiJson = async function (res) {
if (!res.ok) {
let detail = "";
try { detail = (await res.clone().json()).error ?? ""; } catch { /* non-JSON body */ }
const err = new Error(`Request failed (${res.status})${detail ? ": " + detail : ""}`);
err.status = res.status;
err.detail = detail;
throw err;
}
return res.json();
};
```
(`res.clone()` so the original body remains readable if the caller wants it.)
### Step 2 — Update each affected call site
**`queue.js:~380`** (library load):
```js
const res = await fetch("/api/library", { credentials: "include" });
if (res.status === 401) { M.handleAuthRequired?.(); return; } // or surface login UI
M.library = await M.apiJson(res);
M.renderLibrary();
```
Wrap the surrounding logic in `try/catch` and show a toast on failure (e.g. `M.showToast("Couldn't load library", "error")`) rather than leaving the UI empty/silent. Keep `M.library` as its previous value on failure rather than overwriting with garbage.
**`auth.js:11`** (guest bootstrap) and **`auth.js:101`** (`/api/auth/me`):
```js
const res = await fetch("/api/auth/me", { credentials: "include" });
if (res.status === 401) { /* not logged in / guest expired — drive login UI */ return; }
const user = await M.apiJson(res);
```
**`channelSync.js:11`** (channel list):
```js
const res = await fetch("/api/channels", { credentials: "include" });
if (!res.ok) { M.showToast("Couldn't load channels", "error"); return; }
const channels = await M.apiJson(res);
M.channels = channels;
```
### Step 3 — Audit remaining call sites
Grep for `await res.json()` and `await response.json()` across `public/`. Convert any that lack a preceding `res.ok` / status check to use `M.apiJson`. The ones already guarded can be left or migrated for consistency.
## Validation
- **Simulate 401**: clear the session cookie in DevTools, reload. Confirm the library view does **not** render an error object as tracks, and a login prompt / toast appears instead.
- **Simulate 500/502**: stop the server mid-session and trigger a library reload (e.g. via the refresh path). Confirm a toast shows and the previous library remains visible.
- **Happy path**: confirm normal load of library, channels, and `/api/auth/me` still works after the change.
- **Guest expiry**: let a guest session lapse (or delete it from the DB) and reload; confirm graceful handling rather than a broken render.
## Risk / Rollback
- Behavior change only on the error path; success path is identical.
- One subtlety: previously-silent failures will now surface as toasts. That is the desired behavior, but verify the messages are user-friendly and not noisy in normal flaky-network conditions.
- Rollback = revert the helper and the four call sites; no data or schema impact.

View File

@ -1,121 +0,0 @@
# WebSocket Client Robustness: Parse Guard, Reconnect Backoff, Dead-Channel Fallback
Priority: **High** · Effort: **LowMedium** · Risk: **Low**
## Problem
The WebSocket client in `public/channelSync.js` is brittle in three ways that can leave the UI silently desynced or hammering a dead server/channel:
1. **`JSON.parse(e.data)` has no try/catch** (`channelSync.js:262`). A single malformed or partial frame throws, the `onmessage` handler aborts, and the client stops processing all further state updates while the socket appears "open."
2. **Reconnect has no backoff, no jitter, no max-retries** (`channelSync.js:353-369`). A down server produces a fixed 23s reconnect storm with no cap.
3. **No fallback to the default channel**. If the current channel is deleted server-side while the client is disconnected, every reconnect 404s and the client loops forever against a dead channel ID.
Separately, the message dispatcher falls through to `M.handleUpdate(data)` for any unknown `data.type` (`channelSync.js:346`), so a new server message type silently corrupts state. Worth hardening in the same pass.
## Affected Locations
- `public/channelSync.js:262` — unguarded `JSON.parse`
- `public/channelSync.js:346``handleUpdate` fallback for unknown types
- `public/channelSync.js:353-369` — reconnect logic
- `public/channelSync.js:245-261` — socket setup (reference for structure)
## Implementation Plan
### Step 1 — Wrap `JSON.parse` in try/catch
```js
M.ws.onmessage = (e) => {
let data;
try {
data = JSON.parse(e.data);
} catch (err) {
console.warn("[channelSync] Dropping malformed WS frame:", err);
return;
}
// ... existing dispatch ...
};
```
Keep behavior: a bad frame is dropped, the socket stays open, subsequent good frames still process.
### Step 2 — Strict dispatch with explicit unknown-type handling
Replace the implicit fall-through to `M.handleUpdate(data)`. Make the dispatch explicit:
```js
switch (data.type) {
case "channel_list": /* ... */ break;
case "switched": /* ... */ break;
case "track": /* fallthrough */
case "state": M.handleUpdate(data); break; // explicit state-shape types only
// ... all other known types ...
default:
console.warn("[channelSync] Unknown WS message type:", data.type, data);
}
```
(If the server currently sends `type` values other than the ones handled, gather the full set first via `grep` for `"type":` / `type: "` in the server broadcast paths and list them in this switch.)
### Step 3 — Reconnect with exponential backoff + jitter + max attempts
Track reconnect state on `M` (e.g. `M.wsReconnect = { attempts: 0, timer: null }`). On close:
```js
M.ws.onclose = () => {
M.ws = null;
// clear any user-facing "connected" state
if (!M.wantSync) return;
const recon = M.wsReconnect;
recon.attempts++;
const base = 1000; // 1s
const cap = 30000; // 30s max
const exp = Math.min(cap, base * 2 ** recon.attempts);
const jitter = Math.random() * 500; // 0500ms
const delay = exp + jitter;
recon.timer = setTimeout(() => {
connectChannel(M.currentChannelId);
}, delay);
};
```
Reset `recon.attempts = 0` on a successful `open`. Cancel `recon.timer` on any explicit/manual `connectChannel` call to avoid double-connects.
**On max attempts**: rather than giving up entirely (a music app should keep trying), cap the delay at 30s but keep retrying. Optionally surface a "reconnecting…" indicator after the first few failures so the user knows the stream is stale.
### Step 4 — Dead-channel fallback
In `connectChannel`, if the upgrade/open fails or the server responds with a channel-not-found error message (the server already sends `{ type: "error", message: "Channel not found" }` per `websocket.ts:50`), fall back to the default channel:
```js
// inside onmessage error handler:
if (data.type === "error" && /not found/i.test(data.message)) {
console.warn(`[channelSync] Channel ${M.currentChannelId} not found, falling back to default`);
// fetch default channel id from /api/channels (isDefault === true)
const def = await fetchDefaultChannelId();
if (def && def !== M.currentChannelId) {
M.currentChannelId = def;
M.saveChannelId(def);
connectChannel(def);
M.showToast("This channel no longer exists — switched to the default channel.");
return;
}
}
```
Add a small helper `fetchDefaultChannelId()` that GETs `/api/channels` and returns the `id` where `isDefault === true`. Cache it on `M.defaultChannelId` after first successful list load so we don't re-fetch on every failure.
## Validation
- **Malformed frame**: from server console or a test, `ws.send("not json")` to a client — confirm the client logs a warning and continues processing subsequent valid frames (state still updates).
- **Server kill / restart**: stop the server, confirm reconnect attempts grow with backoff (log each attempt + delay) rather than firing every 2s. Restart, confirm the client reconnects and `attempts` resets.
- **Channel deletion while disconnected**: note a non-default channel ID, stop server, delete the channel row from `blastoise.db`, restart server, ensure the client reconnects → gets "not found" → falls back to the default channel and shows the toast.
- **Dispatch**: inject an unknown `{ type: "future_thing" }` message server-side (or via a debug WS send) and confirm it logs a warning and does **not** call `handleUpdate`.
## Risk / Rollback
- All changes are additive hardening; normal-path behavior is preserved.
- Backoff introduces up to a 30s worst-case reconnect delay — acceptable and better than a tight loop. If a deployment wants faster recovery, tune `base`/`cap`.
- Default-channel fallback adds one HTTP fetch on the error path only; cache the result to avoid repeats.
- Rollback = revert the file; no schema or wire-protocol change.

View File

@ -1,74 +0,0 @@
# Fix WS Control-Permission Bypass for Guests
Priority: **High** · Effort: **Trivial (one location)** · Risk: **Low**
## Problem
Guests are *intended* to be unable to control playback (`routes/helpers.ts:30`:
```ts
if (user.is_guest && permission === "control") return false;
```
) but the **WebSocket message handler** does not route through `userHasPermission`. It re-implements the check inline and **omits the guest guard**:
```ts
// websocket.ts:87-93
const canControl = user.is_admin
|| config.defaultPermissions?.includes("control")
|| hasPermission(userId, "channel", ws.data.channelId, "control");
if (!canControl) { ... return; }
```
Because the default config ships `defaultPermissions: ["listen", "control"]` (`config.json:5-8`), **any guest can `pause`, `unpause`, `seek`, and `jump` on any channel**, affecting all listeners.
The HTTP control endpoints (`routes/channels.ts:176, 196, 216, 261`) correctly use `userHasPermission`, so this is an inconsistency between the two code paths that reach the same `Channel` mutators.
## Affected Location
- `websocket.ts:86-93` — inline permission check, guest-unaware.
## Root Cause
Duplicated permission logic in two places. The WS handler was written before / diverged from `helpers.userHasPermission`.
## Implementation Plan
### Step 1 — Import `userHasPermission`
At the top of `websocket.ts`:
```ts
import { userHasPermission } from "./routes/helpers";
```
### Step 2 — Replace the inline check
Replace `websocket.ts:86-93` with:
```ts
if (!userHasPermission(user, "channel", ws.data.channelId, "control")) {
console.log("[WS] User lacks control permission:", user.username, "(guest=" + user.is_guest + ")");
return;
}
```
`userHasPermission` already encapsulates: admin bypass, the guest `control` denial (`helpers.ts:30`), the `defaultPermissions` config check, and the DB permission lookup. Routing through it makes WS and HTTP behavior identical.
### Step 3 — Verify no other call sites rely on the old behavior
`grep` the repo for the inline pattern (`config.defaultPermissions?.includes("control")`) — it should now appear only in `helpers.ts:33` (the canonical check). Any other duplicate should be replaced the same way.
## Validation
- **Guest cannot control**: sign in as a guest (or hit the server unauthenticated with `allowGuests: true`), open a channel WS, send `{"action":"pause"}`. Confirm the channel does **not** pause and the server logs the "lacks control permission" line.
- **Non-guest user still controls**: sign in as `test`/`testuser`, send the same action, confirm the channel pauses.
- **Admin controls**: sign in as admin, confirm control works on channels the admin does not own.
- **Guest still receives state**: confirm the guest client still gets `track`/state broadcasts (i.e. the *listen* path is unaffected — only `control` is denied).
- **Config matrix**: temporarily set `defaultPermissions` to `["listen"]` only and confirm a *non-guest* non-admin user is now also denied control via WS (matches the HTTP path).
## Risk / Rollback
- The only behavioral change is denying control to guests (and, if `defaultPermissions` lacks `"control"`, to non-admin users) — which is the documented intent. If any deployment currently relies on guests controlling playback, that was an unintentional privilege and should be re-granted explicitly via the permissions table, not by reverting.
- No schema or DB change.
- Rollback = revert the single edit.

View File

@ -1,98 +0,0 @@
# XSS Sweep: Escape Server-Controlled Data at `innerHTML` Boundaries
Priority: **Critical** · Effort: **Low** · Risk: **Low**
## Problem
The client injects server-controlled strings into the DOM via `innerHTML` **without escaping** in several high-traffic render paths. Because the server broadcasts channel names, listener usernames, toast messages, and track titles over WebSocket to *every* connected client, a single malicious payload is a **stored/reflected XSS propagated peer-to-peer**.
There is also **no Content-Security-Policy** header set on the document or by the server, so once injected, script runs with full page privilege (same-origin as the session cookie).
## Affected Locations
| File:Line | Sink | Source |
|-----------|------|--------|
| `public/channelSync.js:174-183` | channel list `<span class="channel-name">${ch.name}</span>` and `<input value="${ch.name.replace(/"/g,'&quot;')}">` | channel name (server) |
| `public/channelSync.js:161-163` | `listenersHtml` (listener usernames) | `ch.listeners` (server) |
| `public/utils.js:113` | toast history `... ${item.message}` | WS `toast` message (server) |
| `public/utils.js:149,159` | track title marquee | `track.title` (file metadata / yt-dlp) |
| `public/queue.js:342` | now-playing bar `${title}` | `track.title` (server) |
| `public/upload.js:307` | slow-queue list `${group.name}` | playlist name (server) |
| `public/upload.js:330` | slow-queue list `${item.title}` | `/api/fetch` response (server) |
Note: `trackComponent.js:59` and `playlists.js:44,57,58` **do** escape correctly today. The codebase is internally inconsistent — those are the model to follow.
## Root Cause
- No single shared escaping utility. `escapeHtml` is defined **twice** (`public/playlists.js:481-486` and `public/trackComponent.js:74-79`) as local copies.
- No lint rule or review guard preventing raw `${serverData}` inside template literals feeding `innerHTML`.
- No CSP as defense-in-depth.
## Implementation Plan
### Step 1 — Create one shared `escapeHtml` in `public/utils.js`
Move/deduplicate the existing helper into `utils.js` and expose it on `M`:
```js
M.escapeHtml = function (str) {
if (str == null) return "";
return String(str)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
};
```
Delete the two local copies in `playlists.js:481` and `trackComponent.js:74`; replace callers with `M.escapeHtml(...)`.
### Step 2 — Escape every server-sourced value at each sink above
For each location, wrap the interpolated value in `M.escapeHtml(...)`. For attribute contexts (e.g. `value="${...}"`), escaping with the helper above is sufficient since it includes `"`.
Worked example for `channelSync.js:174-183`:
```js
div.innerHTML = `
<div class="channel-header">
<span class="channel-name">${M.escapeHtml(ch.name)}</span>
<input ... value="${M.escapeHtml(ch.name)}" ...>
...
<div class="channel-listeners">${listenersHtml}</div>
</div>
`;
```
And `listenersHtml` itself (built at `channelSync.js:161-163`) must escape each username before joining.
### Step 3 — Add a defense-in-depth CSP header
In the static file route handler (`routes/static.ts`) — or centrally where index.html is served — add:
```
Content-Security-Policy: default-src 'self'; script-src 'self'; connect-src 'self' ws: wss:; media-src 'self' blob:; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'
```
(`'unsafe-inline'` for styles only — needed until stylesheets are consolidated. No `'unsafe-inline'` for scripts.)
Confirm this does not break the blob-URL audio playback (`media-src 'self' blob:`) or WebSocket (`connect-src ... ws: wss:`).
### Step 4 — (Optional, recommended) Centralize user-visible rendering
Longer-term, every track row / title render should go through `trackComponent.js`'s pure renderer which already escapes. Route now-playing-bar and marquee titles through the same path so escaping can't be forgotten again.
## Validation
- **Manual payload test**: create a channel named `<img src=x onerror="alert(document.cookie)">`, connect a second client, confirm no alert fires and the name renders literally.
- **Username payload**: set a username (or guest) containing `<script>` and verify the channel-list `listenersHtml` shows it escaped.
- **Toast payload**: trigger a server toast containing markup (e.g. via yt-dlp add with a crafted title) and confirm toast history (`utils.js:113`) shows literal text.
- **Track-title payload**: upload an audio file whose metadata title is `<svg/onload=alert(1)>`; confirm queue and now-playing bar render it literally.
- **CSP**: open DevTools → Network → confirm the CSP header is present on the document response and the console shows no CSP violations during normal use (play, cache, switch channel).
## Risk / Rollback
- Escaping is additive and behavior-preserving for well-formed data. Only risk is over-escaping if a value is already HTML-safe by construction — review each call site to confirm the raw string is plain text (it is, in all listed cases).
- A too-strict CSP could break blob audio or an inline event handler. If so, loosen the specific directive per the violation report rather than reverting.
- Rollback = revert the commit; no schema or data migration involved.