commit
Add public stuf
diff --git a/apps/server/src/db/index.ts b/apps/server/src/db/index.ts
index e444806..26746b8 100644
--- a/apps/server/src/db/index.ts
+++ b/apps/server/src/db/index.ts
@@ -36,6 +36,7 @@ export type Song = {
explicit: boolean;
normalized_title: string | null;
uploaded_by: string | null;
+ status: "pending" | "approved" | "rejected";
created_at: Date;
};
@@ -76,6 +77,20 @@ export type ArtistLinkRequest = {
decided_by: string | null;
};
+export type SongEditRequest = {
+ id: string;
+ song_id: string;
+ requested_by: string | null;
+ title: string | null;
+ artist: string | null;
+ album: string | null;
+ explicit: boolean | null;
+ status: "pending" | "approved" | "rejected";
+ created_at: Date;
+ decided_at: Date | null;
+ decided_by: string | null;
+};
+
export type SongSnapshot = {
title: string;
artist: string;
diff --git a/apps/server/src/db/schema.sql b/apps/server/src/db/schema.sql
index 7e98ae8..facaa14 100644
--- a/apps/server/src/db/schema.sql
+++ b/apps/server/src/db/schema.sql
@@ -184,4 +184,56 @@ CREATE INDEX IF NOT EXISTS song_duplicate_reviews_status_idx
CREATE UNIQUE INDEX IF NOT EXISTS song_duplicate_reviews_pair_uniq
ON song_duplicate_reviews (new_song_id, existing_song_id)
- WHERE new_song_id IS NOT NULL AND existing_song_id IS NOT NULL;
\ No newline at end of file
+ WHERE new_song_id IS NOT NULL AND existing_song_id IS NOT NULL;
+
+-- --- Approval gate ----------------------------------------------------------
+--
+-- Streaming/browsing is open to everyone (no account), but uploading and
+-- editing metadata require an account AND admin confirmation. Non-admin
+-- uploads land as 'pending' and stay hidden from the public library until an
+-- admin approves them (the uploader still sees their own). Existing rows and
+-- admin uploads are 'approved'. See routes/songs.ts.
+
+ALTER TABLE songs ADD COLUMN IF NOT EXISTS status text NOT NULL DEFAULT 'approved';
+CREATE INDEX IF NOT EXISTS songs_status_idx ON songs (status);
+
+-- --- Liked songs ----------------------------------------------------------
+--
+-- Per-user favourites. The "Liked Songs" section is just this join ordered by
+-- when the like happened. Cascades on both user and song delete.
+
+CREATE TABLE IF NOT EXISTS liked_songs (
+ user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+ song_id uuid NOT NULL REFERENCES songs (id) ON DELETE CASCADE,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (user_id, song_id)
+);
+
+CREATE INDEX IF NOT EXISTS liked_songs_user_idx
+ ON liked_songs (user_id, created_at DESC);
+
+-- --- Song metadata edit requests ---------------------------------------
+--
+-- Non-admins can propose a metadata fix; an admin approves or rejects it,
+-- mirroring artist_link_requests above. Admins still edit directly (PATCH).
+-- One open request per song at a time.
+
+CREATE TABLE IF NOT EXISTS song_edit_requests (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ song_id uuid NOT NULL REFERENCES songs (id) ON DELETE CASCADE,
+ requested_by uuid REFERENCES users (id) ON DELETE SET NULL,
+ title text,
+ artist text,
+ album text,
+ explicit boolean,
+ status text NOT NULL DEFAULT 'pending', -- pending | approved | rejected
+ created_at timestamptz NOT NULL DEFAULT now(),
+ decided_at timestamptz,
+ decided_by uuid REFERENCES users (id) ON DELETE SET NULL
+);
+
+CREATE INDEX IF NOT EXISTS song_edit_requests_status_idx
+ ON song_edit_requests (status);
+
+CREATE UNIQUE INDEX IF NOT EXISTS song_edit_requests_pending_uniq
+ ON song_edit_requests (song_id) WHERE status = 'pending';
\ No newline at end of file
diff --git a/apps/server/src/lib/media.ts b/apps/server/src/lib/media.ts
index f0a44e8..683dc1c 100644
--- a/apps/server/src/lib/media.ts
+++ b/apps/server/src/lib/media.ts
@@ -4,6 +4,7 @@ import {
mkdir,
writeFile,
rm,
+ stat,
} from "node:fs/promises";
import {
join,
@@ -198,6 +199,82 @@ export async function transcodeToOpus(
}
}
+// Serve a stored audio file as an HTTP response: HTTP Range (seek/scrub),
+// nginx X-Accel offload when configured, hard caching, and — when
+// `attachmentName` is set — a Content-Disposition that makes the browser save
+// it instead of playing it (used by the /song/:id?download=1 share link).
+//
+// Shared by the auth-gated /api/songs/:id/stream endpoint and the public
+// download route so the byte-serving logic lives in exactly one place.
+export async function serveAudioFile(
+ rangeHeader: string | undefined,
+ opts: {
+ absPath: string;
+ servePath: string; // stored relative path, for X-Accel-Redirect
+ mime: string;
+ cacheControl?: string;
+ attachmentName?: string;
+ },
+): Promise<Response> {
+ const { absPath, servePath, mime, attachmentName } = opts;
+ const cacheControl = opts.cacheControl ?? "private, max-age=31536000, immutable";
+
+ const info = await stat(absPath).catch(() => null);
+ if (!info) return new Response("Not found", { status: 404 });
+ const total = info.size;
+
+ const disposition = attachmentName
+ ? `attachment; filename="${attachmentName.replace(/["\\\r\n]/g, "")}"; ` +
+ `filename*=UTF-8''${encodeURIComponent(attachmentName)}`
+ : undefined;
+
+ // Offload to nginx if configured: we've already done any auth check, so hand
+ // the file off by internal redirect and let nginx do sendfile + range.
+ if (config.xaccelPrefix) {
+ const headers: Record<string, string> = {
+ "content-type": mime,
+ "cache-control": cacheControl,
+ "accept-ranges": "bytes",
+ "x-accel-redirect": `${config.xaccelPrefix}/${encodeURI(servePath)}`,
+ };
+ if (disposition) headers["content-disposition"] = disposition;
+ return new Response(null, { headers });
+ }
+
+ if (!rangeHeader) {
+ const headers: Record<string, string> = {
+ "content-type": mime,
+ "content-length": String(total),
+ "accept-ranges": "bytes",
+ "cache-control": cacheControl,
+ };
+ if (disposition) headers["content-disposition"] = disposition;
+ return new Response(Bun.file(absPath), { headers });
+ }
+
+ const match = /bytes=(\d*)-(\d*)/.exec(rangeHeader);
+ const start = match?.[1] ? Number(match[1]) : 0;
+ const end = match?.[2] ? Number(match[2]) : total - 1;
+
+ if (start >= total || end >= total || start > end) {
+ return new Response("Range Not Satisfiable", {
+ status: 416,
+ headers: { "content-range": `bytes */${total}` },
+ });
+ }
+
+ const chunk = Bun.file(absPath).slice(start, end + 1);
+ const headers: Record<string, string> = {
+ "content-type": mime,
+ "content-length": String(end - start + 1),
+ "content-range": `bytes ${start}-${end}/${total}`,
+ "accept-ranges": "bytes",
+ "cache-control": cacheControl,
+ };
+ if (disposition) headers["content-disposition"] = disposition;
+ return new Response(chunk, { status: 206, headers });
+}
+
// Persist a cover image. Returns the relative path stored in the DB.
export async function saveCover(
bytes: Uint8Array,
diff --git a/apps/server/src/routes/artists.ts b/apps/server/src/routes/artists.ts
index fbc805a..4cbed6f 100644
--- a/apps/server/src/routes/artists.ts
+++ b/apps/server/src/routes/artists.ts
@@ -24,7 +24,9 @@ import { ensureMediaDirs, resolveMedia, saveCover } from "../lib/media.ts";
export const artistRoutes = new Hono<AppEnv>();
-artistRoutes.use("*", requireAuth);
+// Browsing artist pages is open to everyone (like the rest of the library);
+// creating pages, editing, merging, and deciding link requests all require an
+// account — `requireAuth` is applied per-route below.
// --- search / browse -------------------------------------------------------
// Used both for the "Artists" browse page and for the "link song to artist"
@@ -64,7 +66,7 @@ artistRoutes.get("/", async (c) => {
// Pending link requests, for the admin queue. Declared before "/:id" so
// "link-requests" isn't captured as an artist id.
-artistRoutes.get("/link-requests", async (c) => {
+artistRoutes.get("/link-requests", requireAuth, async (c) => {
if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
const status = c.req.query("status") ?? "pending";
@@ -110,7 +112,7 @@ artistRoutes.get("/link-requests", async (c) => {
// Merge a near-duplicate artist page into the canonical one. Admin-only
// cleanup for pages that slipped past the search-before-create check.
-artistRoutes.post("/merge", async (c) => {
+artistRoutes.post("/merge", requireAuth, async (c) => {
if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
const body = await c.req
@@ -166,11 +168,15 @@ artistRoutes.get("/:id", async (c) => {
)[0];
if (!artist) return c.json({ error: "not_found" }, 404);
+ const me = c.get("user")?.id ?? null;
+ const visible = me
+ ? sql`(s.status = 'approved' OR s.uploaded_by = ${me})`
+ : sql`s.status = 'approved'`;
const songs = await sql<Array<Song & { role: string }>>`
SELECT s.*, sa.role
FROM song_artists sa
JOIN songs s ON s.id = sa.song_id
- WHERE sa.artist_id = ${id}
+ WHERE sa.artist_id = ${id} AND ${visible}
ORDER BY s.created_at DESC
`;
@@ -210,7 +216,7 @@ artistRoutes.get("/:id/avatar", async (c) => {
});
// Admin-only, mirroring the rest of "editing an existing page".
-artistRoutes.post("/:id/avatar", async (c) => {
+artistRoutes.post("/:id/avatar", requireAuth, async (c) => {
if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
const id = c.req.param("id")!;
const artist = (await sql<Artist[]>`SELECT * FROM artists WHERE id = ${id}`)[0];
@@ -240,7 +246,7 @@ artistRoutes.post("/:id/avatar", async (c) => {
// match (409, with the existing page so the UI can offer "link to this
// instead") — near-duplicate prevention is primarily the caller's job via
// GET / before showing a "create new" option.
-artistRoutes.post("/", async (c) => {
+artistRoutes.post("/", requireAuth, async (c) => {
const user = c.get("user")!;
const body = await c.req
.json<{ name?: string; bio?: string }>()
@@ -273,7 +279,7 @@ artistRoutes.post("/", async (c) => {
});
// Edit an existing page. Admin-only.
-artistRoutes.patch("/:id", async (c) => {
+artistRoutes.patch("/:id", requireAuth, async (c) => {
if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
const id = c.req.param("id")!;
@@ -316,7 +322,7 @@ artistRoutes.patch("/:id", async (c) => {
// Request that a song be linked to this artist. Anyone signed in may ask;
// an admin decides (see the approve/reject routes below).
-artistRoutes.post("/:id/link-requests", async (c) => {
+artistRoutes.post("/:id/link-requests", requireAuth, async (c) => {
const user = c.get("user")!;
const artistId = c.req.param("id")!;
@@ -353,7 +359,7 @@ artistRoutes.post("/:id/link-requests", async (c) => {
return c.json({ ok: true, requestId: rows[0].id }, 201);
});
-artistRoutes.post("/link-requests/:id/approve", async (c) => {
+artistRoutes.post("/link-requests/:id/approve", requireAuth, async (c) => {
if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
const user = c.get("user")!;
const id = c.req.param("id")!;
@@ -381,7 +387,7 @@ artistRoutes.post("/link-requests/:id/approve", async (c) => {
return c.json({ ok: true });
});
-artistRoutes.post("/link-requests/:id/reject", async (c) => {
+artistRoutes.post("/link-requests/:id/reject", requireAuth, async (c) => {
if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
const user = c.get("user")!;
const id = c.req.param("id")!;
diff --git a/apps/server/src/routes/playlists.ts b/apps/server/src/routes/playlists.ts
index 6883577..2099821 100644
--- a/apps/server/src/routes/playlists.ts
+++ b/apps/server/src/routes/playlists.ts
@@ -20,10 +20,12 @@ import { normalizeTitle, tightTitleKey, diceCoefficient } from "../lib/text.ts";
export const playlistRoutes = new Hono<AppEnv>();
-playlistRoutes.use("*", requireAuth);
+// Viewing shared playlists (and their covers) is open to everyone; everything
+// that creates or mutates a playlist requires an account — `requireAuth` is
+// applied per-route below.
// My own playlists.
-playlistRoutes.get("/", async (c) => {
+playlistRoutes.get("/", requireAuth, async (c) => {
const user = c.get("user")!;
const rows = await sql<Playlist[]>`
SELECT * FROM playlists
@@ -96,7 +98,7 @@ playlistRoutes.get("/public", async (c) => {
);
});
-playlistRoutes.post("/", async (c) => {
+playlistRoutes.post("/", requireAuth, async (c) => {
const user = c.get("user")!;
const body = await c.req
.json<{ name?: string }>()
@@ -114,7 +116,7 @@ playlistRoutes.post("/", async (c) => {
// Viewable by the owner, or by anyone if the playlist is public.
playlistRoutes.get("/:id", async (c) => {
- const user = c.get("user")!;
+ const user = c.get("user");
const rows = await sql<
Array<Playlist & { owner_name: string | null; owner_avatar: string | null }>
>`
@@ -126,11 +128,15 @@ playlistRoutes.get("/:id", async (c) => {
const pl = rows[0];
if (!pl) return c.json({ error: "not_found" }, 404);
- const isOwner = pl.user_id === user.id;
+ const isOwner = Boolean(user) && pl.user_id === user!.id;
if (!isOwner && !pl.is_public) {
return c.json({ error: "not_found" }, 404);
}
+ const me = user?.id ?? null;
+ const visible = me
+ ? sql`(s.status = 'approved' OR s.uploaded_by = ${me})`
+ : sql`s.status = 'approved'`;
const songs = await sql<
Array<Song & { position: number; resolved_artist_id: string | null }>
>`
@@ -139,7 +145,7 @@ playlistRoutes.get("/:id", async (c) => {
ORDER BY (sa.role = 'primary') DESC, sa.role LIMIT 1) AS resolved_artist_id
FROM playlist_songs ps
JOIN songs s ON s.id = ps.song_id
- WHERE ps.playlist_id = ${pl.id}
+ WHERE ps.playlist_id = ${pl.id} AND ${visible}
ORDER BY ps.position ASC, ps.song_id ASC
`;
@@ -166,7 +172,7 @@ playlistRoutes.get("/:id", async (c) => {
});
// Rename and/or toggle sharing. Owner only.
-playlistRoutes.patch("/:id", async (c) => {
+playlistRoutes.patch("/:id", requireAuth, async (c) => {
const pl = await owned(c);
if (!pl) return c.json({ error: "not_found" }, 404);
@@ -187,7 +193,7 @@ playlistRoutes.patch("/:id", async (c) => {
return c.json(toPublicPlaylist(rows[0]!));
});
-playlistRoutes.delete("/:id", async (c) => {
+playlistRoutes.delete("/:id", requireAuth, async (c) => {
const pl = await owned(c);
if (!pl) return c.json({ error: "not_found" }, 404);
@@ -198,12 +204,12 @@ playlistRoutes.delete("/:id", async (c) => {
// Cover image. Viewable by anyone who can view the playlist itself
// (owner, or anyone if it's public); replacing it is owner-only.
playlistRoutes.get("/:id/cover", async (c) => {
- const user = c.get("user")!;
+ const user = c.get("user");
const pl = (
await sql<Playlist[]>`SELECT * FROM playlists WHERE id = ${c.req.param("id")!}`
)[0];
if (!pl?.cover_path) return c.json({ error: "not_found" }, 404);
- if (pl.user_id !== user.id && !pl.is_public) {
+ if (pl.user_id !== user?.id && !pl.is_public) {
return c.json({ error: "not_found" }, 404);
}
@@ -219,7 +225,7 @@ playlistRoutes.get("/:id/cover", async (c) => {
});
});
-playlistRoutes.post("/:id/cover", async (c) => {
+playlistRoutes.post("/:id/cover", requireAuth, async (c) => {
const pl = await owned(c);
if (!pl) return c.json({ error: "not_found" }, 404);
@@ -243,7 +249,7 @@ playlistRoutes.post("/:id/cover", async (c) => {
return c.json(toPublicPlaylist(rows[0]!));
});
-playlistRoutes.post("/:id/songs", async (c) => {
+playlistRoutes.post("/:id/songs", requireAuth, async (c) => {
const pl = await owned(c);
if (!pl) return c.json({ error: "not_found" }, 404);
@@ -268,7 +274,7 @@ playlistRoutes.post("/:id/songs", async (c) => {
return c.json({ ok: true });
});
-playlistRoutes.delete("/:id/songs/:songId", async (c) => {
+playlistRoutes.delete("/:id/songs/:songId", requireAuth, async (c) => {
const pl = await owned(c);
if (!pl) return c.json({ error: "not_found" }, 404);
diff --git a/apps/server/src/routes/songs.ts b/apps/server/src/routes/songs.ts
index 0efb6d5..a0be81d 100644
--- a/apps/server/src/routes/songs.ts
+++ b/apps/server/src/routes/songs.ts
@@ -4,7 +4,12 @@ import { Hono } from "hono";
import { stat, unlink } from "node:fs/promises";
import { config } from "../config.ts";
-import { sql, type Song } from "../db/index.ts";
+import {
+ sql,
+ type Song,
+ type SongEditRequest,
+ type User,
+} from "../db/index.ts";
import {
requireAuth,
isAdmin,
@@ -29,18 +34,26 @@ import {
mimeForCoverPath,
isLosslessMaster,
transcodeToOpus,
+ serveAudioFile,
} from "../lib/media.ts";
export const songRoutes = new Hono<AppEnv>();
-// Everyone authenticated sees the whole shared library.
-songRoutes.get("/", requireAuth, async (c) => {
+// Open to everyone: the shared library streams without an account. Signed-in
+// users additionally see their own not-yet-approved uploads; anonymous callers
+// (and other users) only see approved songs.
+songRoutes.get("/", async (c) => {
const q = c.req.query("q")?.trim();
+ const me = c.get("user")?.id ?? null;
+ const visible = me
+ ? sql`(s.status = 'approved' OR s.uploaded_by = ${me})`
+ : sql`s.status = 'approved'`;
const rows = await sql<Array<Song & { resolved_artist_id: string | null }>>`
SELECT s.*,
(SELECT sa.artist_id FROM song_artists sa WHERE sa.song_id = s.id
ORDER BY (sa.role = 'primary') DESC, sa.role LIMIT 1) AS resolved_artist_id
FROM songs s
+ WHERE ${visible}
ORDER BY s.created_at DESC
`;
if (!q) return c.json(rows.map((s) => toPublicSong(s, s.resolved_artist_id)));
@@ -71,9 +84,139 @@ songRoutes.get("/", requireAuth, async (c) => {
return c.json(scored.map((r) => toPublicSong(r.song, r.song.resolved_artist_id)));
});
-songRoutes.get("/:id", requireAuth, async (c) => {
+// --- liked songs (per-user favourites) ---------------------------------
+// Declared before "/:id" so "liked" isn't captured as a song id.
+
+songRoutes.get("/liked", requireAuth, async (c) => {
+ const user = c.get("user")!;
+ const rows = await sql<Array<Song & { resolved_artist_id: string | null }>>`
+ SELECT s.*,
+ (SELECT sa.artist_id FROM song_artists sa WHERE sa.song_id = s.id
+ ORDER BY (sa.role = 'primary') DESC, sa.role LIMIT 1) AS resolved_artist_id
+ FROM liked_songs l
+ JOIN songs s ON s.id = l.song_id
+ WHERE l.user_id = ${user.id}
+ AND (s.status = 'approved' OR s.uploaded_by = ${user.id})
+ ORDER BY l.created_at DESC
+ `;
+ return c.json(rows.map((s) => toPublicSong(s, s.resolved_artist_id)));
+});
+
+// --- admin: pending uploads ------------------------------------------------
+
+songRoutes.get("/pending", requireAuth, async (c) => {
+ if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
+ const rows = await sql<
+ Array<Song & { resolved_artist_id: string | null; uploader_name: string | null }>
+ >`
+ SELECT s.*,
+ (SELECT sa.artist_id FROM song_artists sa WHERE sa.song_id = s.id
+ ORDER BY (sa.role = 'primary') DESC, sa.role LIMIT 1) AS resolved_artist_id,
+ u.name AS uploader_name
+ FROM songs s
+ LEFT JOIN users u ON u.id = s.uploaded_by
+ WHERE s.status = 'pending'
+ ORDER BY s.created_at ASC
+ `;
+ return c.json(
+ rows.map((s) => ({
+ ...toPublicSong(s, s.resolved_artist_id),
+ uploaderName: s.uploader_name,
+ })),
+ );
+});
+
+// --- admin: song metadata edit requests ---------------------------------
+
+songRoutes.get("/edit-requests", requireAuth, async (c) => {
+ if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
+ const status = c.req.query("status") ?? "pending";
+ const rows = await sql<
+ Array<
+ SongEditRequest & {
+ cur_title: string;
+ cur_artist: string;
+ cur_album: string | null;
+ cur_explicit: boolean;
+ requested_by_name: string | null;
+ }
+ >
+ >`
+ SELECT r.*,
+ s.title AS cur_title,
+ s.artist AS cur_artist,
+ s.album AS cur_album,
+ s.explicit AS cur_explicit,
+ u.name AS requested_by_name
+ FROM song_edit_requests r
+ JOIN songs s ON s.id = r.song_id
+ LEFT JOIN users u ON u.id = r.requested_by
+ WHERE r.status = ${status}
+ ORDER BY r.created_at ASC
+ `;
+ return c.json(rows.map(toPublicEditRequest));
+});
+
+songRoutes.post("/edit-requests/:reqId/approve", requireAuth, async (c) => {
+ const user = c.get("user")!;
+ if (!isAdmin(user)) return c.json({ error: "forbidden" }, 403);
+
+ const req = (
+ await sql<SongEditRequest[]>`
+ SELECT * FROM song_edit_requests WHERE id = ${c.req.param("reqId")!} AND status = 'pending'
+ `
+ )[0];
+ if (!req) return c.json({ error: "not_found" }, 404);
+
+ const song = await getSong(req.song_id);
+ if (!song) {
+ await sql`
+ UPDATE song_edit_requests
+ SET status = 'rejected', decided_at = now(), decided_by = ${user.id}
+ WHERE id = ${req.id}
+ `;
+ return c.json({ error: "song_not_found" }, 404);
+ }
+
+ const title = (req.title ?? song.title).trim();
+ const artist = (req.artist ?? song.artist).trim();
+ const album = req.album !== null ? req.album : song.album;
+ const explicit = req.explicit !== null ? req.explicit : song.explicit;
+
+ await sql.begin(async (tx) => {
+ await tx`
+ UPDATE songs
+ SET title = ${title}, artist = ${artist}, album = ${album},
+ explicit = ${explicit}, normalized_title = ${normalizeTitle(title)}
+ WHERE id = ${song.id}
+ `;
+ await tx`DELETE FROM song_lyrics WHERE song_id = ${song.id}`;
+ await tx`
+ UPDATE song_edit_requests
+ SET status = 'approved', decided_at = now(), decided_by = ${user.id}
+ WHERE id = ${req.id}
+ `;
+ });
+ return c.json({ ok: true });
+});
+
+songRoutes.post("/edit-requests/:reqId/reject", requireAuth, async (c) => {
+ const user = c.get("user")!;
+ if (!isAdmin(user)) return c.json({ error: "forbidden" }, 403);
+ const rows = await sql<SongEditRequest[]>`
+ UPDATE song_edit_requests
+ SET status = 'rejected', decided_at = now(), decided_by = ${user.id}
+ WHERE id = ${c.req.param("reqId")!} AND status = 'pending'
+ RETURNING *
+ `;
+ if (!rows[0]) return c.json({ error: "not_found" }, 404);
+ return c.json({ ok: true });
+});
+
+songRoutes.get("/:id", async (c) => {
const song = await getSong(c.req.param("id")!);
if (!song) return c.json({ error: "not_found" }, 404);
+ if (!canSee(song, c.get("user"))) return c.json({ error: "not_found" }, 404);
return c.json(toPublicSong(song, await getPrimaryArtistId(song.id)));
});
@@ -125,14 +268,18 @@ songRoutes.post(
coverPath = await saveCover(tags.cover.data, tags.cover.ext);
}
+ // Admin uploads go live immediately; everyone else's wait for admin review
+ // (hidden from the public library, visible to the uploader) — see GET "/".
+ const status = isAdmin(user) ? "approved" : "pending";
+
const rows = await sql<Song[]>`
INSERT INTO songs
(title, artist, album, cover_path, file_path, mime, duration_s,
- size_bytes, explicit, normalized_title, uploaded_by)
+ size_bytes, explicit, normalized_title, uploaded_by, status)
VALUES
(${title}, ${artist}, ${album ?? null}, ${coverPath}, ${filePath},
${file.type || null}, ${tags.durationS}, ${file.size}, ${explicit},
- ${normalizeTitle(title)}, ${user.id})
+ ${normalizeTitle(title)}, ${user.id}, ${status})
RETURNING *
`;
const song = rows[0]!;
@@ -161,106 +308,31 @@ songRoutes.post(
return c.json(toPublicSong(song), 201);
});
-// Audio streaming with HTTP Range support (seek/scrub).
-songRoutes.get("/:id/stream", requireAuth, async (c) => {
+// Audio streaming with HTTP Range support (seek/scrub). Open to everyone —
+// streaming needs no account.
+songRoutes.get("/:id/stream", async (c) => {
const song = await getSong(c.req.param("id")!);
- if (!song) return c.json({ error: "not_found" }, 404);
-
- // Prefer the transcoded Opus copy when it exists (smaller = far better on
- // mobile); otherwise stream the original master. If the Opus file is somehow
- // missing on disk, fall back to the master rather than 404.
- let servePath = song.stream_path ?? song.file_path;
- let abs = resolveMedia(servePath);
- let info = await stat(abs).catch(() => null);
- if (!info && song.stream_path) {
- servePath = song.file_path;
- abs = resolveMedia(servePath);
- info = await stat(abs).catch(() => null);
+ if (!song || !canSee(song, c.get("user"))) {
+ return c.json({ error: "not_found" }, 404);
}
- if (!info) return c.json({ error: "file_missing" }, 404);
-
- const total = info.size;
- // Prefer the curated extension->MIME map over the browser-reported upload
- // type (song.mime is often "audio/x-flac", "application/ogg", or empty,
- // which can make players refuse or mis-handle FLAC/OGG). Fall back to the
- // stored type only if the extension is unrecognised.
- const extMime = mimeForAudioPath(servePath);
- const mime =
- extMime !== "application/octet-stream"
- ? extMime
- : song.mime && song.mime.startsWith("audio/")
- ? song.mime
- : extMime;
- const range = c.req.header("range");
-
- // The audio bytes for a given song id never change (an edit only touches
- // metadata; re-uploading makes a new id), so let the browser cache them
- // hard. Without this the stream had no cache headers at all, so every
- // scrub, replay, or revisit re-downloaded the whole file — the main cause
- // of "taking forever to load", especially on mobile where media buffers
- // get dropped aggressively. `private` because the endpoint is auth-gated.
- const cacheControl = "private, max-age=31536000, immutable";
-
- // Offload to nginx if configured: we've authenticated, so hand the file off
- // by internal redirect and let nginx do sendfile + range + caching. The app
- // never touches the bytes — the big win for a large, multi-user library.
- if (config.xaccelPrefix) {
- return new Response(null, {
- headers: {
- "content-type": mime,
- "cache-control": cacheControl,
- "accept-ranges": "bytes",
- "x-accel-redirect": `${config.xaccelPrefix}/${encodeURI(servePath)}`,
- },
- });
- }
-
- if (!range) {
- // Pass the BunFile directly (not .stream()): Bun then sends a real
- // Content-Length via efficient file streaming. With .stream() the response
- // went out chunked with no length, so the browser couldn't size the file,
- // couldn't range-seek, reported duration as Infinity (broken timer), and
- // progressively downloaded the whole track before playing.
- return new Response(Bun.file(abs), {
- headers: {
- "content-type": mime,
- "content-length": String(total),
- "accept-ranges": "bytes",
- "cache-control": cacheControl,
- },
- });
- }
-
- const match = /bytes=(\d*)-(\d*)/.exec(range);
- const start = match?.[1] ? Number(match[1]) : 0;
- const end = match?.[2] ? Number(match[2]) : total - 1;
+ return serveSongStream(c.req.header("range"), song);
+});
- if (start >= total || end >= total || start > end) {
- return new Response("Range Not Satisfiable", {
- status: 416,
- headers: { "content-range": `bytes */${total}` },
- });
+// Download the ORIGINAL uploaded master (never the Opus transcode) as a file.
+// Backs the /song/:id?download=1 share link. Open to everyone.
+songRoutes.get("/:id/download", async (c) => {
+ const song = await getSong(c.req.param("id")!);
+ if (!song || !canSee(song, c.get("user"))) {
+ return c.json({ error: "not_found" }, 404);
}
-
- // The sliced BunFile is a Blob backed by the file; passing it directly lets
- // Bun stream exactly those bytes with a correct Content-Length (see note
- // above on why .stream() was wrong).
- const chunk = Bun.file(abs).slice(start, end + 1);
- return new Response(chunk, {
- status: 206,
- headers: {
- "content-type": mime,
- "content-length": String(end - start + 1),
- "content-range": `bytes ${start}-${end}/${total}`,
- "accept-ranges": "bytes",
- "cache-control": cacheControl,
- },
- });
+ return serveSongDownload(c.req.header("range"), song);
});
-songRoutes.get("/:id/lyrics", requireAuth, async (c) => {
+songRoutes.get("/:id/lyrics", async (c) => {
const song = await getSong(c.req.param("id")!);
- if (!song) return c.json({ error: "not_found" }, 404);
+ if (!song || !canSee(song, c.get("user"))) {
+ return c.json({ error: "not_found" }, 404);
+ }
const lyrics = await getLyrics({
id: song.id,
@@ -306,6 +378,88 @@ songRoutes.get("/:id/cover", async (c) => {
});
});
+// --- like / unlike -------------------------------------------------------
+
+songRoutes.put("/:id/like", requireAuth, async (c) => {
+ const user = c.get("user")!;
+ const song = await getSong(c.req.param("id")!);
+ if (!song || !canSee(song, user)) return c.json({ error: "not_found" }, 404);
+ await sql`
+ INSERT INTO liked_songs (user_id, song_id)
+ VALUES (${user.id}, ${song.id})
+ ON CONFLICT (user_id, song_id) DO NOTHING
+ `;
+ return c.json({ liked: true });
+});
+
+songRoutes.delete("/:id/like", requireAuth, async (c) => {
+ const user = c.get("user")!;
+ await sql`
+ DELETE FROM liked_songs
+ WHERE user_id = ${user.id} AND song_id = ${c.req.param("id")!}
+ `;
+ return c.json({ liked: false });
+});
+
+// --- admin: approve / reject a pending upload ---------------------------
+
+songRoutes.post("/:id/approve", requireAuth, async (c) => {
+ if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
+ const rows = await sql<Song[]>`
+ UPDATE songs SET status = 'approved'
+ WHERE id = ${c.req.param("id")!} AND status = 'pending'
+ RETURNING *
+ `;
+ if (!rows[0]) return c.json({ error: "not_found" }, 404);
+ return c.json({ ok: true });
+});
+
+songRoutes.post("/:id/reject", requireAuth, async (c) => {
+ if (!isAdmin(c.get("user"))) return c.json({ error: "forbidden" }, 403);
+ const song = await getSong(c.req.param("id")!);
+ if (!song || song.status !== "pending") {
+ return c.json({ error: "not_found" }, 404);
+ }
+ // Reject == unwanted upload: remove it and its files (mirrors DELETE /:id
+ // and the duplicate queue's "mark duplicate" behaviour).
+ await sql`DELETE FROM songs WHERE id = ${song.id}`;
+ await unlink(resolveMedia(song.file_path)).catch(() => {});
+ if (song.stream_path) await unlink(resolveMedia(song.stream_path)).catch(() => {});
+ if (song.cover_path) await unlink(resolveMedia(song.cover_path)).catch(() => {});
+ return c.json({ ok: true });
+});
+
+// Non-admins propose a metadata fix; an admin approves it (see the
+// /edit-requests routes above). Admins use PATCH below instead.
+songRoutes.post("/:id/edit-requests", requireAuth, async (c) => {
+ const user = c.get("user")!;
+ const song = await getSong(c.req.param("id")!);
+ if (!song || !canSee(song, user)) return c.json({ error: "not_found" }, 404);
+
+ const body = await c.req
+ .json<{ title?: string; artist?: string; album?: string; explicit?: boolean }>()
+ .catch(() => ({}) as Record<string, never>);
+
+ const title = body.title?.trim() || null;
+ const artist = body.artist?.trim() || null;
+ const album = typeof body.album === "string" ? body.album.trim() : null;
+ const explicit = typeof body.explicit === "boolean" ? body.explicit : null;
+ if (!title && !artist && album === null && explicit === null) {
+ return c.json({ error: "nothing_to_change" }, 400);
+ }
+
+ await sql`
+ INSERT INTO song_edit_requests
+ (song_id, requested_by, title, artist, album, explicit)
+ VALUES (${song.id}, ${user.id}, ${title}, ${artist}, ${album}, ${explicit})
+ ON CONFLICT (song_id) WHERE status = 'pending' DO UPDATE
+ SET title = EXCLUDED.title, artist = EXCLUDED.artist,
+ album = EXCLUDED.album, explicit = EXCLUDED.explicit,
+ requested_by = EXCLUDED.requested_by, created_at = now()
+ `;
+ return c.json({ ok: true }, 201);
+});
+
// Admin-only edit: fix metadata / apply the explicit tag on ANY song after
// upload. Multipart so the cover can optionally be replaced.
songRoutes.patch("/:id", requireAuth, async (c) => {
@@ -356,12 +510,12 @@ songRoutes.patch("/:id", requireAuth, async (c) => {
return c.json(toPublicSong(rows[0]!, await getPrimaryArtistId(song.id)));
});
-// Only the uploader may delete.
+// The uploader may delete their own upload; an admin may delete any song.
songRoutes.delete("/:id", requireAuth, async (c) => {
const user = c.get("user")!;
const song = await getSong(c.req.param("id")!);
if (!song) return c.json({ error: "not_found" }, 404);
- if (song.uploaded_by !== user.id) {
+ if (song.uploaded_by !== user.id && !isAdmin(user)) {
return c.json({ error: "forbidden" }, 403);
}
@@ -378,9 +532,107 @@ songRoutes.delete("/:id", requireAuth, async (c) => {
// --- helpers --------------------------------------------------------------
-async function getSong(id: string): Promise<Song | undefined> {
- const rows = await sql<Song[]>`SELECT * FROM songs WHERE id = ${id}`;
- return rows[0];
+export async function getSong(id: string): Promise<Song | undefined> {
+ // A malformed (non-uuid) id would make Postgres throw; treat as "not found".
+ try {
+ const rows = await sql<Song[]>`SELECT * FROM songs WHERE id = ${id}`;
+ return rows[0];
+ } catch {
+ return undefined;
+ }
+}
+
+// Who may see a given song: anyone for approved songs; the uploader or an
+// admin for pending/rejected ones.
+export function canSee(song: Song, user: User | null): boolean {
+ if (song.status === "approved") return true;
+ if (!user) return false;
+ return song.uploaded_by === user.id || isAdmin(user);
+}
+
+// Pick the bytes to stream: the Opus transcode when present (smaller — better
+// on mobile), else the master; fall back to the master if the Opus vanished.
+async function resolvePlayable(
+ song: Song,
+ preferMaster: boolean,
+): Promise<{ servePath: string; absPath: string; mime: string } | null> {
+ let servePath = preferMaster ? song.file_path : song.stream_path ?? song.file_path;
+ let absPath = resolveMedia(servePath);
+ let info = await stat(absPath).catch(() => null);
+ if (!info && servePath !== song.file_path) {
+ servePath = song.file_path;
+ absPath = resolveMedia(servePath);
+ info = await stat(absPath).catch(() => null);
+ }
+ if (!info) return null;
+
+ const extMime = mimeForAudioPath(servePath);
+ const mime =
+ extMime !== "application/octet-stream"
+ ? extMime
+ : song.mime && song.mime.startsWith("audio/")
+ ? song.mime
+ : extMime;
+ return { servePath, absPath, mime };
+}
+
+export async function serveSongStream(
+ rangeHeader: string | undefined,
+ song: Song,
+): Promise<Response> {
+ const t = await resolvePlayable(song, false);
+ if (!t) return new Response("file_missing", { status: 404 });
+ return serveAudioFile(rangeHeader, {
+ absPath: t.absPath,
+ servePath: t.servePath,
+ mime: t.mime,
+ });
+}
+
+export async function serveSongDownload(
+ rangeHeader: string | undefined,
+ song: Song,
+): Promise<Response> {
+ const t = await resolvePlayable(song, true); // always the original master
+ if (!t) return new Response("file_missing", { status: 404 });
+ const ext = t.servePath.slice(t.servePath.lastIndexOf(".")) || "";
+ const safe = (s: string) => s.replace(/[\/\\:*?"<>|]+/g, " ").trim();
+ return serveAudioFile(rangeHeader, {
+ absPath: t.absPath,
+ servePath: t.servePath,
+ mime: t.mime,
+ attachmentName: `${safe(song.artist)} - ${safe(song.title)}${ext}`,
+ });
+}
+
+function toPublicEditRequest(
+ r: SongEditRequest & {
+ cur_title: string;
+ cur_artist: string;
+ cur_album: string | null;
+ cur_explicit: boolean;
+ requested_by_name: string | null;
+ },
+) {
+ return {
+ id: r.id,
+ songId: r.song_id,
+ current: {
+ title: r.cur_title,
+ artist: r.cur_artist,
+ album: r.cur_album,
+ explicit: r.cur_explicit,
+ },
+ proposed: {
+ title: r.title,
+ artist: r.artist,
+ album: r.album,
+ explicit: r.explicit,
+ },
+ requestedByName: r.requested_by_name,
+ status: r.status,
+ createdAt: r.created_at,
+ };
}
// A song can be linked to several artists (song_artists is many-to-many);
@@ -411,7 +663,9 @@ function toPublicSong(s: Song, artistId: string | null = null) {
hasCover: Boolean(s.cover_path),
coverUrl: s.cover_path ? `/api/songs/${s.id}/cover` : null,
streamUrl: `/api/songs/${s.id}/stream`,
+ downloadUrl: `/song/${s.id}?download=1`,
uploadedBy: s.uploaded_by,
+ status: s.status,
createdAt: s.created_at,
};
}
\ No newline at end of file
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 271f85a..8a7a62e 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -19,7 +19,12 @@ import {
import { ensureMediaDirs } from "./lib/media.ts";
import { startPocketIdGuard } from "./lib/pocketid-guard.ts";
import { authRoutes } from "./routes/auth.ts";
-import { songRoutes } from "./routes/songs.ts";
+import {
+ songRoutes,
+ getSong,
+ canSee,
+ serveSongDownload,
+} from "./routes/songs.ts";
import { playlistRoutes } from "./routes/playlists.ts";
import { artistRoutes } from "./routes/artists.ts";
import { duplicateRoutes } from "./routes/duplicates.ts";
@@ -131,10 +136,69 @@ app.get("/download", (c) => {
}
});
+// Shareable per-song link. Must sit before the SPA catch-all.
+//
+// /song/<id> -> the SPA, with song-specific unfurl metadata
+// injected so Discord/Slack/iMessage previews show
+// the track (the SPA then routes to the song view)
+// /song/<id>?download=1 -> downloads the ORIGINAL uploaded master as a file
+//
+// Open to everyone: streaming and downloading need no account. Pending/rejected
+// uploads are only visible to their uploader or an admin.
+app.get("/song/:id", async (c) => {
+ const song = await getSong(c.req.param("id"));
+
+ if (c.req.query("download") != null && song && canSee(song, c.get("user"))) {
+ return serveSongDownload(c.req.header("range"), song);
+ }
+
+ const file = Bun.file(join(webSrc, "index.html"));
+ if (!(await file.exists())) return new Response("Not found", { status: 404 });
+ let html = await file.text();
+ if (song && canSee(song, c.get("user"))) {
+ html = injectSongMeta(html, song);
+ }
+ return new Response(html, {
+ headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" },
+ });
+});
+
// SPA fallback: any non-API route returns index.html. Also no-cache, so a
// stale shell can't keep pointing the webview at an old asset.
app.get("*", () => serveFile(join(webSrc, "index.html"), "no-cache"));
+// Rewrite the static unfurl tags in index.html for a specific song. Bots don't
+// run JS, so this has to happen server-side; humans still boot the SPA normally.
+function injectSongMeta(
+ html: string,
+ song: { id: string; title: string; artist: string; cover_path: string | null },
+): string {
+ const esc = (s: string) =>
+ s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
+ const title = esc(`${song.title} — ${song.artist}`);
+ const desc = esc(`Listen to ${song.title} by ${song.artist} on Doughmination Music.`);
+ const url = `${config.appUrl}/song/${song.id}`;
+ const image = song.cover_path
+ ? `${config.appUrl}/api/songs/${song.id}/cover`
+ : `${config.appUrl}/favicon.png`;
+
+ return html
+ .replace(/<title>[^<]*<\/title>/, `<title>${title}</title>`)
+ .replace(
+ /(<meta (?:property|name)="(?:og:title|twitter:title)" content=")[^"]*(")/g,
+ `$1${title}$2`,
+ )
+ .replace(
+ /(<meta (?:property|name)="(?:og:description|twitter:description|description)" content=")[^"]*(")/g,
+ `$1${desc}$2`,
+ )
+ .replace(/(<meta property="og:url" content=")[^"]*(")/g, `$1${url}$2`)
+ .replace(
+ /(<meta (?:property|name)="(?:og:image|twitter:image)" content=")[^"]*(")/g,
+ `$1${image}$2`,
+ );
+}
+
console.log(`Music server on ${config.appUrl} (port ${config.port})`);
export default {
diff --git a/apps/web/src/app.ts b/apps/web/src/app.ts
index d740a3b..ec9b1ee 100644
--- a/apps/web/src/app.ts
+++ b/apps/web/src/app.ts
@@ -4,6 +4,8 @@
import {
api,
type Song,
+ type PendingSong,
+ type SongEditRequest,
type Playlist,
type Me,
type Lyrics,
@@ -37,14 +39,33 @@ initNative(player);
type View =
| { kind: "library" }
+ | { kind: "liked" }
+ | { kind: "song"; id: string }
| { kind: "browse" }
| { kind: "playlist"; id: string }
| { kind: "artists" }
| { kind: "artist"; id: string }
| { kind: "duplicates" }
| { kind: "linkRequests" }
+ | { kind: "pendingSongs" }
+ | { kind: "editRequests" }
| { kind: "settings" };
+// Admin-only views, and views that need any account, gated in boot()/popstate.
+const ADMIN_VIEWS = new Set<View["kind"]>([
+ "duplicates",
+ "linkRequests",
+ "pendingSongs",
+ "editRequests",
+]);
+const ACCOUNT_VIEWS = new Set<View["kind"]>(["liked", "settings"]);
+
+function allowedView(v: View): View {
+ if (ADMIN_VIEWS.has(v.kind) && !state.me?.isAdmin) return { kind: "library" };
+ if (ACCOUNT_VIEWS.has(v.kind) && !state.me) return { kind: "library" };
+ return v;
+}
+
// --- URL routing ------------------------------------------------------------
// Every view maps to a real, hotlinkable path (the server's catch-all route
// serves index.html for any of these, so a deep link works on first load too
@@ -54,24 +75,32 @@ type View =
function viewToPath(view: View): string {
switch (view.kind) {
case "library": return "/";
+ case "liked": return "/liked";
+ case "song": return `/song/${view.id}`;
case "browse": return "/browse";
case "artists": return "/artists";
case "artist": return `/artist/${view.id}`;
case "playlist": return `/playlist/${view.id}`;
case "duplicates": return "/admin/duplicates";
case "linkRequests": return "/admin/link-requests";
+ case "pendingSongs": return "/admin/pending";
+ case "editRequests": return "/admin/edit-requests";
case "settings": return "/settings";
}
}
function pathToView(pathname: string): View {
const [head, id] = pathname.split("/").filter(Boolean);
+ if (head === "liked") return { kind: "liked" };
+ if (head === "song" && id) return { kind: "song", id };
if (head === "browse") return { kind: "browse" };
if (head === "artists") return { kind: "artists" };
if (head === "artist" && id) return { kind: "artist", id };
if (head === "playlist" && id) return { kind: "playlist", id };
if (head === "admin" && id === "duplicates") return { kind: "duplicates" };
if (head === "admin" && id === "link-requests") return { kind: "linkRequests" };
+ if (head === "admin" && id === "pending") return { kind: "pendingSongs" };
+ if (head === "admin" && id === "edit-requests") return { kind: "editRequests" };
if (head === "settings") return { kind: "settings" };
return { kind: "library" };
}
@@ -90,9 +119,11 @@ const state = {
me: null as Me | null,
songs: [] as Song[],
playlists: [] as Playlist[],
+ likedSongs: [] as Song[],
+ likedIds: new Set<string>(),
view: { kind: "library" } as View,
visibleSongs: [] as Song[],
- adminCounts: { duplicates: 0, linkRequests: 0 },
+ adminCounts: { duplicates: 0, linkRequests: 0, pendingSongs: 0, editRequests: 0 },
};
// Discord presence is refreshed whenever the *song* or the *play/pause* state
@@ -253,17 +284,13 @@ document.addEventListener("keydown", (e) => {
// --- boot -----------------------------------------------------------------
async function boot(): Promise<void> {
+ // Streaming/browsing is open to everyone: a null `me` is a valid anonymous
+ // session, not a reason to show a login wall.
state.me = await api.me();
- if (!state.me) {
- renderLogin();
- return;
- }
- await Promise.all([loadSongs(), loadPlaylists()]);
- if (state.me.isAdmin) await refreshAdminCounts();
+ await Promise.all([loadSongs(), loadPlaylists(), loadLiked()]);
+ if (state.me?.isAdmin) await refreshAdminCounts();
- const initialView = pathToView(window.location.pathname);
- const adminOnly = initialView.kind === "duplicates" || initialView.kind === "linkRequests";
- state.view = adminOnly && !state.me.isAdmin ? { kind: "library" } : initialView;
+ state.view = allowedView(pathToView(window.location.pathname));
restoreNowPlaying();
handleLastfmRedirect();
@@ -273,13 +300,7 @@ async function boot(): Promise<void> {
// Back/forward: the URL is already correct, so just re-derive the view from
// it and render — no history.pushState (that would double up entries).
window.addEventListener("popstate", () => {
- if (!state.me) {
- renderLogin();
- return;
- }
- const view = pathToView(window.location.pathname);
- const adminOnly = view.kind === "duplicates" || view.kind === "linkRequests";
- state.view = adminOnly && !state.me.isAdmin ? { kind: "library" } : view;
+ state.view = allowedView(pathToView(window.location.pathname));
render();
});
@@ -303,16 +324,37 @@ async function loadSongs(): Promise<void> {
}
async function loadPlaylists(): Promise<void> {
+ if (!state.me) {
+ state.playlists = [];
+ return;
+ }
state.playlists = await api.listPlaylists();
}
+async function loadLiked(): Promise<void> {
+ if (!state.me) {
+ state.likedSongs = [];
+ state.likedIds = new Set();
+ return;
+ }
+ state.likedSongs = await api.listLiked();
+ state.likedIds = new Set(state.likedSongs.map((s) => s.id));
+}
+
async function refreshAdminCounts(): Promise<void> {
if (!state.me?.isAdmin) return;
- const [dupes, reqs] = await Promise.all([
+ const [dupes, reqs, pending, edits] = await Promise.all([
api.listDuplicates("pending"),
api.listLinkRequests("pending"),
+ api.listPendingSongs(),
+ api.listSongEditRequests("pending"),
]);
- state.adminCounts = { duplicates: dupes.length, linkRequests: reqs.length };
+ state.adminCounts = {
+ duplicates: dupes.length,
+ linkRequests: reqs.length,
+ pendingSongs: pending.length,
+ editRequests: edits.length,
+ };
}
// --- top-level render ------------------------------------------------------
@@ -320,6 +362,7 @@ async function refreshAdminCounts(): Promise<void> {
function render(): void {
root.innerHTML = `
<button class="hamburger" id="hamburger" aria-label="Menu"><i class="bi bi-list"></i></button>
+ <img class="app-logo-corner" src="/favicon.png" alt="Doughmination Music" />
<div class="layout">
<aside class="sidebar" id="sidebar"></aside>
<div class="scrim" id="scrim"></div>
@@ -347,43 +390,39 @@ function render(): void {
.forEach((b) => b.addEventListener("click", closeDrawer));
}
-function renderLogin(): void {
- // Web navigates the same tab straight to the login route (cookie flow).
- // Desktop can't: SSO/passkeys don't work in the embedded webview and the
- // cookie would land in the wrong jar. Instead it opens the system browser
- // and comes back via the doughmination:// deeplink (see startDesktopLogin).
- // Web-only: carry the deep link the user landed on (or was bounced to
- // from an expired session) through the SSO round trip, so e.g. a shared
- // /artist/<id> link still opens that page after signing in, instead of
- // always dropping back to the library. Server validates this is a
- // same-origin path before honoring it — see routes/auth.ts.
+// Web navigates the same tab straight to the login route (cookie flow).
+// Desktop can't: SSO/passkeys don't work in the embedded webview and the cookie
+// would land in the wrong jar — it opens the system browser and returns via the
+// doughmination:// deeplink (see startDesktopLogin). Web carries the deep link
+// the user is on through the SSO round trip so a shared /song/<id> etc. still
+// opens after signing in. Server validates it's a same-origin path — see
+// routes/auth.ts.
+function loginHref(): string {
const returnPath = window.location.pathname + window.location.search;
- const loginHref =
+ return (
"/api/auth/login" +
(returnPath && returnPath !== "/"
? `?redirect=${encodeURIComponent(returnPath)}`
- : "");
-
- const button = isDesktop
- ? `<button class="btn btn-primary" id="login-btn">🔑 Sign in with SSO</button>`
- : `<a class="btn btn-primary" href="${loginHref}">🔑 Sign in with SSO</a>`;
+ : "")
+ );
+}
- root.innerHTML = `
- <div class="login">
- <h1>Music</h1>
- <p>Sign in with your passkey to continue.</p>
- ${button}
- </div>
- `;
+// A "Sign in" control that does the right thing on web vs desktop. `id` must be
+// unique in the document; call wireSignIn(id) after inserting it.
+function signInControlHtml(id: string, label = "Sign in", cls = "btn btn-primary"): string {
+ return isDesktop
+ ? `<button class="${cls}" id="${id}">${label}</button>`
+ : `<a class="${cls}" id="${id}" href="${loginHref()}">${label}</a>`;
+}
- if (isDesktop) {
- document.getElementById("login-btn")?.addEventListener("click", () => {
- startDesktopLogin().catch((err) => {
- console.error("failed to start login", err);
- flash("Couldn't open the sign-in page. Try again?");
- });
+function wireSignIn(id: string): void {
+ if (!isDesktop) return;
+ document.getElementById(id)?.addEventListener("click", () => {
+ startDesktopLogin().catch((err) => {
+ console.error("failed to start login", err);
+ flash("Couldn't open the sign-in page. Try again?");
});
- }
+ });
}
// --- sidebar --------------------------------------------------------------
@@ -414,48 +453,57 @@ function renderSidebar(): void {
)
.join("");
+ const badge = (n: number) => (n ? ` <span class="pl-badge">${n}</span>` : "");
+ const adminNav = (kind: View["kind"], label: string, n: number) => `
+ <button class="nav-link ${state.view.kind === kind ? "active" : ""}" data-view="${kind}">
+ ${label}${badge(n)}
+ </button>`;
+
el.innerHTML = `
- <div class="brand">Doughmination Music</div>
+ <div class="brand"><img class="brand-logo" src="/favicon.png" alt="" /> Doughmination Music</div>
${nav("library", "Library")}
- <button class="nav-link" id="upload-btn">
- <i class="bi bi-cloud-arrow-up"></i> Upload
- </button>
+ ${state.me ? nav("liked", `<i class="bi bi-heart-fill"></i> Liked Songs`) : ""}
+ ${
+ state.me
+ ? `<button class="nav-link" id="upload-btn"><i class="bi bi-cloud-arrow-up"></i> Upload</button>`
+ : ""
+ }
${nav("browse", "Browse shared")}
${nav("artists", "Artists")}
${
state.me?.isAdmin
? `
<div class="section-head"><span>Admin</span></div>
- <button class="nav-link ${state.view.kind === "duplicates" ? "active" : ""}" data-view="duplicates">
- Duplicates${
- state.adminCounts.duplicates
- ? ` <span class="pl-badge">${state.adminCounts.duplicates}</span>`
- : ""
- }
- </button>
- <button class="nav-link ${state.view.kind === "linkRequests" ? "active" : ""}" data-view="linkRequests">
- Artist requests${
- state.adminCounts.linkRequests
- ? ` <span class="pl-badge">${state.adminCounts.linkRequests}</span>`
- : ""
- }
- </button>`
+ ${adminNav("duplicates", "Duplicates", state.adminCounts.duplicates)}
+ ${adminNav("linkRequests", "Artist requests", state.adminCounts.linkRequests)}
+ ${adminNav("pendingSongs", "Upload approvals", state.adminCounts.pendingSongs)}
+ ${adminNav("editRequests", "Edit requests", state.adminCounts.editRequests)}`
: ""
}
+ ${
+ state.me
+ ? `
<div class="section-head">
<span>Playlists</span>
<button class="icon-btn" id="new-playlist" title="New playlist"><i class="bi bi-plus-lg"></i></button>
</div>
- <ul class="playlists">${items}</ul>
+ <ul class="playlists">${items}</ul>`
+ : ""
+ }
<div class="sidebar-foot">
- ${avatarHtml(state.me?.avatarUrl ?? null, state.me?.name ?? null, "sm")}
- <span class="me-name">${escapeHtml(
- state.me?.name ?? state.me?.email ?? "You",
- )}</span>
- <button class="icon-btn" data-view="settings" title="Settings"><i class="bi bi-gear"></i></button>
- <button class="link" id="logout">Log out</button>
+ ${
+ state.me
+ ? `
+ ${avatarHtml(state.me.avatarUrl ?? null, state.me.name ?? null, "sm")}
+ <span class="me-name">${escapeHtml(state.me.name ?? state.me.email ?? "You")}</span>
+ <button class="icon-btn" data-view="settings" title="Settings"><i class="bi bi-gear"></i></button>
+ <button class="link" id="logout">Log out</button>`
+ : `
+ <span class="me-name">Browsing as guest</span>
+ ${signInControlHtml("sidebar-signin", "Sign in", "btn btn-primary btn-sm")}`
+ }
</div>
`;
@@ -463,16 +511,20 @@ function renderSidebar(): void {
btn.addEventListener("click", () => {
const kind = (btn as HTMLElement).dataset.view as
| "library"
+ | "liked"
| "browse"
| "artists"
| "duplicates"
| "linkRequests"
+ | "pendingSongs"
+ | "editRequests"
| "settings";
navigate({ kind });
});
});
document.getElementById("upload-btn")?.addEventListener("click", openUploadModal);
+ wireSignIn("sidebar-signin");
el.querySelectorAll("[data-playlist]").forEach((btn) => {
btn.addEventListener("click", () => {
@@ -486,10 +538,11 @@ function renderSidebar(): void {
const res = await api.logout();
const data = (await res.json()) as { endSession: string | null };
if (isDesktop) {
- // No cookie / no navigation: drop the stored token and show login.
+ // No cookie / no navigation: drop the token and drop back to guest view.
clearDesktopToken();
state.me = null;
- renderLogin();
+ await Promise.all([loadSongs(), loadPlaylists(), loadLiked()]);
+ navigate({ kind: "library" });
return;
}
window.location.href = data.endSession ?? "/";
@@ -504,15 +557,93 @@ async function renderMain(): Promise<void> {
const view = state.view;
if (view.kind === "library") renderLibrary(el);
+ else if (view.kind === "liked") renderLikedView(el);
+ else if (view.kind === "song") await renderSongView(el, view.id);
else if (view.kind === "browse") await renderBrowse(el);
else if (view.kind === "artists") await renderArtists(el);
else if (view.kind === "artist") await renderArtistView(el, view.id);
else if (view.kind === "duplicates") await renderDuplicates(el);
else if (view.kind === "linkRequests") await renderLinkRequests(el);
+ else if (view.kind === "pendingSongs") await renderPendingSongs(el);
+ else if (view.kind === "editRequests") await renderEditRequests(el);
else if (view.kind === "settings") await renderSettings(el);
else await renderPlaylistView(el, view.id);
}
+function renderLikedView(el: HTMLElement): void {
+ const shown = filterExplicit(state.likedSongs);
+ state.visibleSongs = shown;
+ el.innerHTML = `
+ <header class="main-head">
+ <h2><i class="bi bi-heart-fill accent"></i> Liked Songs</h2>
+ <span class="song-dur">${shown.length} song${shown.length === 1 ? "" : "s"}</span>
+ </header>
+ <div id="songlist">${
+ shown.length
+ ? songTableHtml(shown)
+ : `<p class="empty">Songs you like show up here. Tap the heart on any track.</p>`
+ }</div>
+ `;
+ wireSongList();
+}
+
+async function renderSongView(el: HTMLElement, id: string): Promise<void> {
+ el.innerHTML = `<p class="empty">Loading…</p>`;
+ let song: Song;
+ try {
+ song = await api.getSong(id);
+ } catch {
+ el.innerHTML = `<p class="empty">That song isn't here anymore.</p>`;
+ return;
+ }
+ state.visibleSongs = [song];
+
+ const cover = song.coverUrl
+ ? `<img class="song-page-cover" src="${song.coverUrl}" alt="" />`
+ : `<div class="song-page-cover cover-empty"><i class="bi bi-music-note-beamed"></i></div>`;
+ const artist = song.artistId
+ ? `<button class="song-artist artist-link" id="song-page-artist">${escapeHtml(song.artist)}</button>`
+ : `<span class="song-artist">${escapeHtml(song.artist)}</span>`;
+ const bits = [
+ song.album ? escapeHtml(song.album) : "",
+ song.durationS ? formatTime(song.durationS) : "",
+ ].filter(Boolean).join(" · ");
+
+ el.innerHTML = `
+ <div class="song-page">
+ ${cover}
+ <div class="song-page-meta">
+ <span class="song-title">${escapeHtml(song.title)}${
+ song.explicit ? ` <span class="tag-e" title="Explicit">E</span>` : ""
+ }</span>
+ ${artist}
+ ${bits ? `<span class="song-dur">${bits}</span>` : ""}
+ <div class="song-page-actions">
+ <button class="btn btn-primary" id="song-page-play"><i class="bi bi-play-fill"></i> Play</button>
+ ${state.me ? `<button class="btn" id="song-page-like"><i class="bi bi-heart${
+ state.likedIds.has(song.id) ? "-fill" : ""
+ }"></i> ${state.likedIds.has(song.id) ? "Liked" : "Like"}</button>` : ""}
+ <button class="btn" id="song-page-copy"><i class="bi bi-link-45deg"></i> Copy link</button>
+ <a class="btn" href="/song/${song.id}?download=1"><i class="bi bi-download"></i> Download</a>
+ </div>
+ </div>
+ </div>
+ `;
+
+ document.getElementById("song-page-play")?.addEventListener("click", () => {
+ if (player.current?.id === song.id) player.toggle();
+ else player.playQueue([song], 0);
+ });
+ document.getElementById("song-page-copy")?.addEventListener("click", () => copySongLink(song.id));
+ document.getElementById("song-page-like")?.addEventListener("click", () => {
+ void toggleLike(song.id);
+ renderMain();
+ });
+ document.getElementById("song-page-artist")?.addEventListener("click", () => {
+ if (song.artistId) openArtist(song.artistId);
+ });
+}
+
function renderLibrary(el: HTMLElement): void {
const shown = filterExplicit(state.songs);
state.visibleSongs = shown;
@@ -897,17 +1028,24 @@ function sleep(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
-// Admin-only: fix metadata / apply the explicit tag on any song.
+// Admins fix metadata directly; everyone else signed in submits it as a
+// request an admin approves (mirrors the artist-link request flow).
function openEditModal(song: Song): void {
+ const asRequest = !state.me?.isAdmin;
const overlay = document.createElement("div");
overlay.className = "modal-overlay";
overlay.innerHTML = `
<div class="modal" role="dialog" aria-modal="true">
<div class="modal-head">
- <h2>Edit details</h2>
+ <h2>${asRequest ? "Suggest an edit" : "Edit details"}</h2>
<button class="icon-btn" id="modal-close" title="Close"><i class="bi bi-x-lg"></i></button>
</div>
<form id="edit" class="upload-card">
+ ${
+ asRequest
+ ? `<p class="dz-hint">Your changes go to an admin for review before they go live.</p>`
+ : ""
+ }
<label class="field">
<span>Song name <em>(required)</em></span>
<input name="title" value="${escapeHtml(song.title)}" required />
@@ -924,15 +1062,19 @@ function openEditModal(song: Song): void {
<input type="checkbox" name="explicit" value="true" ${song.explicit ? "checked" : ""} />
<span>Explicit content</span>
</label>
- <div class="field">
+ ${
+ asRequest
+ ? ""
+ : `<div class="field">
<span>Replace cover <em>(optional)</em></span>
<label class="file-chip">
<i class="bi bi-image"></i>
<span id="cover-name">Choose image</span>
<input type="file" name="cover" accept="image/*" hidden />
</label>
- </div>
- <button class="btn btn-primary" type="submit">Save</button>
+ </div>`
+ }
+ <button class="btn btn-primary" type="submit">${asRequest ? "Send for review" : "Save"}</button>
<span id="edit-status" class="upload-status"></span>
</form>
</div>
@@ -952,10 +1094,10 @@ function openEditModal(song: Song): void {
});
overlay.querySelector("#modal-close")?.addEventListener("click", close);
- const coverInput = overlay.querySelector('input[name="cover"]') as HTMLInputElement;
- const coverName = overlay.querySelector("#cover-name") as HTMLElement;
- coverInput.addEventListener("change", () => {
- coverName.textContent = coverInput.files?.[0]?.name ?? "Choose image";
+ const coverInput = overlay.querySelector('input[name="cover"]') as HTMLInputElement | null;
+ const coverName = overlay.querySelector("#cover-name") as HTMLElement | null;
+ coverInput?.addEventListener("change", () => {
+ if (coverName) coverName.textContent = coverInput.files?.[0]?.name ?? "Choose image";
});
// Ensure explicit is always sent (unchecked box would otherwise be omitted).
@@ -964,20 +1106,31 @@ function openEditModal(song: Song): void {
form.addEventListener("submit", async (e) => {
e.preventDefault();
const btn = form.querySelector("button")!;
- btn.textContent = "Saving...";
+ const explicit = Boolean(form.querySelector<HTMLInputElement>('[name="explicit"]')?.checked);
+ const title = (form.querySelector('[name="title"]') as HTMLInputElement).value.trim();
+ const artist = (form.querySelector('[name="artist"]') as HTMLInputElement).value.trim();
+ const album = (form.querySelector('[name="album"]') as HTMLInputElement).value.trim();
+ btn.textContent = asRequest ? "Sending..." : "Saving...";
btn.setAttribute("disabled", "true");
if (status) status.textContent = "";
- const fd = new FormData(form);
- fd.set("explicit", form.querySelector<HTMLInputElement>('[name="explicit"]')?.checked ? "true" : "false");
try {
- const updated = await api.updateSong(song.id, fd);
- await loadSongs();
- renderMain();
- close();
- flash(`Updated "${updated.title}".`);
+ if (asRequest) {
+ const res = await api.requestSongEdit(song.id, { title, artist, album, explicit });
+ if (!res.ok) throw new Error(String(res.status));
+ close();
+ flash("Edit sent for review.");
+ } else {
+ const fd = new FormData(form);
+ fd.set("explicit", explicit ? "true" : "false");
+ const updated = await api.updateSong(song.id, fd);
+ await Promise.all([loadSongs(), loadLiked()]);
+ renderMain();
+ close();
+ flash(`Updated "${updated.title}".`);
+ }
} catch (err) {
- if (status) status.textContent = `Save failed: ${(err as Error).message}`;
- btn.textContent = "Save";
+ if (status) status.textContent = `${asRequest ? "Send" : "Save"} failed: ${(err as Error).message}`;
+ btn.textContent = asRequest ? "Send for review" : "Save";
btn.removeAttribute("disabled");
}
});
@@ -992,6 +1145,144 @@ function flash(msg: string): void {
setTimeout(() => el.remove(), 3000);
}
+// --- shared song actions ------------------------------------------------
+
+// The public, hotlinkable URL for a song. Opening it cold hits the server's
+// /song/:id route (unfurl metadata), which then boots the SPA into the song
+// view; appending ?download=1 downloads the original master. See server.ts.
+function songLink(id: string): string {
+ return `${location.origin}/song/${id}`;
+}
+
+function copySongLink(id: string): void {
+ const link = songLink(id);
+ const done = () => flash("Link copied");
+ if (navigator.clipboard?.writeText) {
+ navigator.clipboard.writeText(link).then(done, () => fallbackCopy(link, done));
+ } else {
+ fallbackCopy(link, done);
+ }
+}
+
+function fallbackCopy(text: string, done: () => void): void {
+ const ta = document.createElement("textarea");
+ ta.value = text;
+ ta.style.position = "fixed";
+ ta.style.opacity = "0";
+ document.body.appendChild(ta);
+ ta.select();
+ try {
+ document.execCommand("copy");
+ done();
+ } catch {
+ flash("Couldn't copy — here's the link: " + text);
+ }
+ ta.remove();
+}
+
+// Optimistic like toggle: flip local state + every heart button for this song
+// in the DOM, then persist. Reverts on failure.
+async function toggleLike(songId: string): Promise<void> {
+ if (!state.me) {
+ flash("Sign in to like songs.");
+ return;
+ }
+ const nowLiked = !state.likedIds.has(songId);
+ if (nowLiked) state.likedIds.add(songId);
+ else state.likedIds.delete(songId);
+ paintLikeButtons(songId, nowLiked);
+
+ const song = state.songs.find((s) => s.id === songId) ?? state.likedSongs.find((s) => s.id === songId);
+ if (nowLiked && song && !state.likedSongs.some((s) => s.id === songId)) {
+ state.likedSongs = [song, ...state.likedSongs];
+ } else if (!nowLiked) {
+ state.likedSongs = state.likedSongs.filter((s) => s.id !== songId);
+ }
+
+ try {
+ const res = nowLiked ? await api.likeSong(songId) : await api.unlikeSong(songId);
+ if (!res.ok) throw new Error(String(res.status));
+ } catch {
+ // Revert.
+ if (nowLiked) state.likedIds.delete(songId);
+ else state.likedIds.add(songId);
+ paintLikeButtons(songId, !nowLiked);
+ await loadLiked();
+ flash("Couldn't update Liked Songs.");
+ }
+ if (state.view.kind === "liked") renderMain();
+}
+
+function paintLikeButtons(songId: string, liked: boolean): void {
+ document.querySelectorAll<HTMLElement>(`[data-like="${CSS.escape(songId)}"]`).forEach((btn) => {
+ btn.classList.toggle("liked", liked);
+ btn.setAttribute("title", liked ? "Remove from Liked Songs" : "Add to Liked Songs");
+ const i = btn.querySelector("i");
+ if (i) i.className = liked ? "bi bi-heart-fill" : "bi bi-heart";
+ });
+}
+
+type MenuItem = {
+ label: string;
+ icon: string;
+ danger?: boolean;
+ onClick: () => void;
+};
+
+// Lightweight popup menu anchored to a button. Closes on outside click, Escape,
+// scroll, or resize. There's no menu primitive in the app otherwise — the "⋯"
+// on every song row and the player bar both use this.
+function openContextMenu(anchor: HTMLElement, items: MenuItem[]): void {
+ document.querySelector(".ctx-menu")?.remove();
+
+ const menu = document.createElement("div");
+ menu.className = "ctx-menu";
+ menu.innerHTML = items
+ .map(
+ (it, i) =>
+ `<button class="ctx-item ${it.danger ? "danger" : ""}" data-i="${i}">
+ <i class="bi ${it.icon}"></i> ${escapeHtml(it.label)}
+ </button>`,
+ )
+ .join("");
+ document.body.appendChild(menu);
+
+ const r = anchor.getBoundingClientRect();
+ const mw = menu.offsetWidth;
+ const mh = menu.offsetHeight;
+ let left = Math.min(r.right - mw, window.innerWidth - mw - 8);
+ let top = r.bottom + 4;
+ if (top + mh > window.innerHeight - 8) top = r.top - mh - 4;
+ menu.style.left = `${Math.max(8, left)}px`;
+ menu.style.top = `${Math.max(8, top)}px`;
+
+ const close = () => {
+ menu.remove();
+ document.removeEventListener("pointerdown", onOutside, true);
+ document.removeEventListener("keydown", onKey, true);
+ window.removeEventListener("scroll", close, true);
+ window.removeEventListener("resize", close);
+ };
+ const onOutside = (e: Event) => {
+ if (!menu.contains(e.target as Node)) close();
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") close();
+ };
+ document.addEventListener("pointerdown", onOutside, true);
+ document.addEventListener("keydown", onKey, true);
+ window.addEventListener("scroll", close, true);
+ window.addEventListener("resize", close);
+
+ menu.querySelectorAll<HTMLElement>(".ctx-item").forEach((btn) => {
+ btn.addEventListener("click", () => {
+ const it = items[Number(btn.dataset.i)];
+ close();
+ it?.onClick();
+ });
+ });
+}
+
// --- browse shared playlists ----------------------------------------------
async function renderBrowse(el: HTMLElement): Promise<void> {
@@ -1043,7 +1334,7 @@ async function renderArtists(el: HTMLElement): Promise<void> {
<h2>Artists</h2>
<div class="head-actions">
<input id="artist-search" class="search" placeholder="Search artists" />
- <button class="btn btn-primary" id="new-artist-btn">+ New artist</button>
+ ${state.me ? `<button class="btn btn-primary" id="new-artist-btn">+ New artist</button>` : ""}
</div>
</header>
<div id="artist-results"></div>
@@ -1468,6 +1759,133 @@ function wireLinkRequestActions(): void {
});
}
+// --- admin: pending uploads -------------------------------------------
+
+async function renderPendingSongs(el: HTMLElement): Promise<void> {
+ const rows = await api.listPendingSongs();
+ state.adminCounts.pendingSongs = rows.length;
+ state.visibleSongs = rows; // so the preview play buttons queue correctly
+
+ el.innerHTML = `
+ <header class="main-head"><h2>Upload approvals</h2></header>
+ <div id="pending-list">${
+ rows.length
+ ? `<div class="songs">${rows.map(pendingRowHtml).join("")}</div>`
+ : `<p class="empty">No uploads waiting for review.</p>`
+ }</div>
+ `;
+
+ // Reuse the song-row play wiring for the cover buttons.
+ el.querySelectorAll(".cover-play").forEach((btn) => {
+ btn.addEventListener("click", () => playFromList(Number((btn as HTMLElement).dataset.play)));
+ });
+ el.querySelectorAll("[data-approve]").forEach((btn) => {
+ btn.addEventListener("click", async () => {
+ await api.decidePendingSong((btn as HTMLElement).dataset.approve!, "approve");
+ await Promise.all([refreshAdminCounts(), loadSongs()]);
+ renderSidebar();
+ renderMain();
+ });
+ });
+ el.querySelectorAll("[data-reject]").forEach((btn) => {
+ btn.addEventListener("click", async () => {
+ if (!confirm("Reject and delete this upload?")) return;
+ await api.decidePendingSong((btn as HTMLElement).dataset.reject!, "reject");
+ await refreshAdminCounts();
+ renderSidebar();
+ renderMain();
+ });
+ });
+ highlightPlayingRow();
+}
+
+function pendingRowHtml(s: PendingSong, i: number): string {
+ const art = s.coverUrl
+ ? `<img class="cover" src="${s.coverUrl}" alt="" />`
+ : `<div class="cover cover-empty"><i class="bi bi-music-note-beamed"></i></div>`;
+ return `
+ <div class="song" data-index="${i}" data-song-id="${s.id}">
+ <div class="song-cover">
+ ${art}
+ <div class="np-bars" aria-hidden="true"><span></span><span></span><span></span><span></span></div>
+ <button class="cover-play" data-play="${i}" title="Preview"><i class="bi bi-play-fill"></i></button>
+ </div>
+ <div class="song-meta">
+ <span class="song-title">${escapeHtml(s.title)}${
+ s.explicit ? ` <span class="tag-e" title="Explicit">E</span>` : ""
+ }</span>
+ <span class="song-artist">${escapeHtml(s.artist)}${
+ s.album ? ` · ${escapeHtml(s.album)}` : ""
+ }${s.uploaderName ? ` · uploaded by ${escapeHtml(s.uploaderName)}` : ""}</span>
+ </div>
+ <span class="song-dur">${s.durationS ? formatTime(s.durationS) : ""}</span>
+ <div class="dupe-actions">
+ <button class="btn" data-reject="${s.id}">Reject</button>
+ <button class="btn btn-primary" data-approve="${s.id}">Approve</button>
+ </div>
+ </div>`;
+}
+
+// --- admin: song metadata edit requests -------------------------------
+
+async function renderEditRequests(el: HTMLElement): Promise<void> {
+ const rows = await api.listSongEditRequests("pending");
+ state.adminCounts.editRequests = rows.length;
+
+ el.innerHTML = `
+ <header class="main-head"><h2>Edit requests</h2></header>
+ <div id="edit-req-list">${
+ rows.length
+ ? rows.map(editReqRowHtml).join("")
+ : `<p class="empty">No pending edit requests.</p>`
+ }</div>
+ `;
+
+ el.querySelectorAll("[data-approve]").forEach((btn) => {
+ btn.addEventListener("click", async () => {
+ await api.decideSongEditRequest((btn as HTMLElement).dataset.approve!, "approve");
+ await Promise.all([refreshAdminCounts(), loadSongs()]);
+ renderSidebar();
+ renderMain();
+ });
+ });
+ el.querySelectorAll("[data-reject]").forEach((btn) => {
+ btn.addEventListener("click", async () => {
+ await api.decideSongEditRequest((btn as HTMLElement).dataset.reject!, "reject");
+ await refreshAdminCounts();
+ renderSidebar();
+ renderMain();
+ });
+ });
+}
+
+function editReqRowHtml(r: SongEditRequest): string {
+ const field = (label: string, cur: unknown, next: unknown) => {
+ const changed = next !== null && next !== undefined && String(next) !== String(cur);
+ return `<li${changed ? ' class="changed"' : ""}>
+ <span class="er-label">${label}</span>
+ <span class="er-cur">${escapeHtml(String(cur ?? "—"))}</span>
+ ${changed ? `<i class="bi bi-arrow-right"></i> <span class="er-next">${escapeHtml(String(next))}</span>` : ""}
+ </li>`;
+ };
+ return `
+ <div class="dupe-row" data-req="${r.id}">
+ <div class="dupe-score">Edit request${
+ r.requestedByName ? ` · ${escapeHtml(r.requestedByName)}` : ""
+ }</div>
+ <ul class="er-fields">
+ ${field("Title", r.current.title, r.proposed.title)}
+ ${field("Artist", r.current.artist, r.proposed.artist)}
+ ${field("Album", r.current.album, r.proposed.album)}
+ ${field("Explicit", r.current.explicit, r.proposed.explicit)}
+ </ul>
+ <div class="dupe-actions">
+ <button class="btn" data-reject="${r.id}">Reject</button>
+ <button class="btn btn-primary" data-approve="${r.id}">Approve</button>
+ </div>
+ </div>`;
+}
+
// --- playlist view ---------------------------------------------------------
async function renderPlaylistView(el: HTMLElement, id: string): Promise<void> {
@@ -1610,23 +2028,26 @@ function songTableHtml(songs: Song[], editablePlaylistId?: string): string {
</button>
</div>`;
- const action = editablePlaylistId
- ? `<button class="icon-btn" data-remove="${s.id}" title="Remove"><i class="bi bi-x-lg"></i></button>`
- : `<button class="icon-btn" data-add="${s.id}" title="Add to playlist"><i class="bi bi-plus-lg"></i></button>`;
-
- const linkArtist = `<button class="icon-btn" data-link-artist="${s.id}" title="Link artist"><i class="bi bi-person-plus"></i></button>`;
-
- const edit = state.me?.isAdmin
- ? `<button class="icon-btn" data-edit="${s.id}" title="Edit details"><i class="bi bi-pencil-fill"></i></button>`
+ // Only the heart and the +/× stay on the row; everything else moves into
+ // the "⋯" menu wired up in wireSongList().
+ const heart = state.me
+ ? `<button class="icon-btn like ${state.likedIds.has(s.id) ? "liked" : ""}" data-like="${s.id}"
+ title="${state.likedIds.has(s.id) ? "Remove from Liked Songs" : "Add to Liked Songs"}">
+ <i class="bi bi-heart${state.likedIds.has(s.id) ? "-fill" : ""}"></i></button>`
: "";
- const del =
- s.uploadedBy && s.uploadedBy === state.me?.id
- ? `<button class="icon-btn" data-del="${s.id}" title="Delete song"><i class="bi bi-trash-fill"></i></button>`
- : "";
+ const plus = !state.me
+ ? ""
+ : editablePlaylistId
+ ? `<button class="icon-btn" data-remove="${s.id}" title="Remove"><i class="bi bi-x-lg"></i></button>`
+ : `<button class="icon-btn" data-add="${s.id}" title="Add to playlist"><i class="bi bi-plus-lg"></i></button>`;
+ const menu = `<button class="icon-btn" data-menu="${s.id}" title="More"><i class="bi bi-three-dots-vertical"></i></button>`;
const badge = s.explicit
? `<span class="tag-e" title="Explicit">E</span>`
: "";
+ const pending = s.status === "pending"
+ ? `<span class="tag-pending" title="Waiting for admin approval">pending</span>`
+ : "";
const artist = s.artistId
? `<button class="song-artist artist-link" data-open-artist="${s.artistId}">${escapeHtml(s.artist)}</button>`
@@ -1636,11 +2057,11 @@ function songTableHtml(songs: Song[], editablePlaylistId?: string): string {
<div class="song" data-index="${i}" data-song-id="${s.id}">
${cover}
<div class="song-meta">
- <span class="song-title">${escapeHtml(s.title)}${badge}</span>
+ <span class="song-title">${escapeHtml(s.title)}${badge}${pending}</span>
${artist}
</div>
<span class="song-dur">${s.durationS ? formatTime(s.durationS) : ""}</span>
- <div class="song-actions">${action}${linkArtist}${edit}${del}</div>
+ <div class="song-actions">${heart}${plus}${menu}</div>
</div>`;
})
.join("");
@@ -1690,31 +2111,19 @@ function wireSongList(editablePlaylistId?: string): void {
});
});
- document.querySelectorAll("[data-edit]").forEach((btn) => {
+ document.querySelectorAll("[data-like]").forEach((btn) => {
btn.addEventListener("click", (e) => {
e.stopPropagation();
- const id = (btn as HTMLElement).dataset.edit!;
- const song = state.visibleSongs.find((s) => s.id === id);
- if (song) openEditModal(song);
+ void toggleLike((btn as HTMLElement).dataset.like!);
});
});
- document.querySelectorAll("[data-link-artist]").forEach((btn) => {
+ document.querySelectorAll("[data-menu]").forEach((btn) => {
btn.addEventListener("click", (e) => {
e.stopPropagation();
- const songId = (btn as HTMLElement).dataset.linkArtist!;
- const song = state.visibleSongs.find((s) => s.id === songId);
- openLinkArtistModal(songId, song?.title ?? "");
- });
- });
-
- document.querySelectorAll("[data-del]").forEach((btn) => {
- btn.addEventListener("click", async (e) => {
- e.stopPropagation();
- if (!confirm("Delete this song for everyone?")) return;
- await api.deleteSong((btn as HTMLElement).dataset.del!);
- await loadSongs();
- renderMain();
+ const id = (btn as HTMLElement).dataset.menu!;
+ const song = state.visibleSongs.find((s) => s.id === id);
+ if (song) openContextMenu(btn as HTMLElement, songMenuItems(song));
});
});
@@ -1722,6 +2131,57 @@ function wireSongList(editablePlaylistId?: string): void {
highlightPlayingRow();
}
+// The "⋯" menu for one song row: link + download for everyone; the account-only
+// bits (link artist, edit/suggest edit, delete) appear per role.
+function songMenuItems(song: Song): MenuItem[] {
+ const items: MenuItem[] = [];
+ if (song.artistId) {
+ items.push({
+ label: "Go to artist",
+ icon: "bi-person",
+ onClick: () => openArtist(song.artistId!),
+ });
+ }
+ items.push({ label: "Copy song link", icon: "bi-link-45deg", onClick: () => copySongLink(song.id) });
+ items.push({
+ label: "Download original",
+ icon: "bi-download",
+ onClick: () => {
+ window.location.href = `/song/${song.id}?download=1`;
+ },
+ });
+ if (state.me) {
+ items.push({
+ label: "Link artist",
+ icon: "bi-person-plus",
+ onClick: () => openLinkArtistModal(song.id, song.title),
+ });
+ items.push({
+ label: state.me.isAdmin ? "Edit details" : "Suggest an edit",
+ icon: "bi-pencil",
+ onClick: () => openEditModal(song),
+ });
+ }
+ const isUploader = Boolean(song.uploadedBy) && song.uploadedBy === state.me?.id;
+ if (isUploader || state.me?.isAdmin) {
+ items.push({
+ label: "Delete song",
+ icon: "bi-trash",
+ danger: true,
+ onClick: async () => {
+ const msg = isUploader
+ ? "Delete this song for everyone?"
+ : `Delete "${song.title}" by ${song.artist} for everyone? This removes the file.`;
+ if (!confirm(msg)) return;
+ await api.deleteSong(song.id);
+ await Promise.all([loadSongs(), loadLiked()]);
+ renderMain();
+ },
+ });
+ }
+ return items;
+}
+
// Play a song from the visible list — but if it's already the current track,
// toggle play/pause instead of restarting it from the top.
function playFromList(index: number): void {
@@ -1848,6 +2308,17 @@ function mountPlayerBar(el: HTMLElement, song: Song): void {
: `<span class="song-artist">${escapeHtml(song.artist)}</span>`
}
</div>
+ <div class="pb-song-actions">
+ ${
+ state.me
+ ? `<button class="icon-btn like ${state.likedIds.has(song.id) ? "liked" : ""}" id="pb-like"
+ data-like="${song.id}" title="Like"><i class="bi bi-heart${
+ state.likedIds.has(song.id) ? "-fill" : ""
+ }"></i></button>`
+ : ""
+ }
+ <button class="icon-btn" id="pb-menu" title="More"><i class="bi bi-three-dots-vertical"></i></button>
+ </div>
</div>
<div class="pb-controls">
@@ -1915,6 +2386,23 @@ function mountPlayerBar(el: HTMLElement, song: Song): void {
if (song.artistId) {
el.querySelector("#pb-artist")?.addEventListener("click", () => openArtist(song.artistId!));
}
+
+ el.querySelector("#pb-like")?.addEventListener("click", () => void toggleLike(song.id));
+ el.querySelector("#pb-menu")?.addEventListener("click", (e) => {
+ openContextMenu(e.currentTarget as HTMLElement, [
+ { label: "Copy song link", icon: "bi-link-45deg", onClick: () => copySongLink(song.id) },
+ {
+ label: "Download original",
+ icon: "bi-download",
+ onClick: () => {
+ window.location.href = `/song/${song.id}?download=1`;
+ },
+ },
+ ...(song.artistId
+ ? [{ label: "Go to artist", icon: "bi-person", onClick: () => openArtist(song.artistId!) }]
+ : []),
+ ]);
+ });
}
// Update only the changing pieces — never rebuild (keeps sliders draggable).
@@ -1950,6 +2438,14 @@ function updatePlayerBar(): void {
el.querySelector("#lyrics-btn")?.classList.toggle("on", lyricsState.open);
+ const pbLike = el.querySelector("#pb-like");
+ if (pbLike && player.current) {
+ const liked = state.likedIds.has(player.current.id);
+ pbLike.classList.toggle("liked", liked);
+ const i = pbLike.querySelector("i");
+ if (i) i.className = liked ? "bi bi-heart-fill" : "bi bi-heart";
+ }
+
updateVolumeIcon();
}
diff --git a/apps/web/src/styles.css b/apps/web/src/styles.css
index 1e03795..161b31e 100644
--- a/apps/web/src/styles.css
+++ b/apps/web/src/styles.css
@@ -1377,4 +1377,197 @@ button {
.pb-song .song-meta {
max-width: 40vw;
}
+}
+
+/* --- app icon / brand --- */
+
+.brand {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.brand-logo {
+ width: 26px;
+ height: 26px;
+ border-radius: 7px;
+ flex-shrink: 0;
+}
+
+/* Persistent corner mark on mobile, where there's no always-visible sidebar
+ brand. Hidden on desktop — the sidebar brand carries it there. */
+.app-logo-corner {
+ display: none;
+ position: fixed;
+ top: 0.6rem;
+ right: 0.9rem;
+ width: 2rem;
+ height: 2rem;
+ border-radius: 8px;
+ z-index: 46;
+}
+
+@media (max-width: 768px) {
+ .app-logo-corner {
+ display: block;
+ }
+}
+
+/* --- heart / like --- */
+
+.icon-btn.like.liked,
+.icon-btn.like.liked:hover {
+ color: var(--accent);
+}
+
+.accent {
+ color: var(--accent);
+}
+
+.tag-pending {
+ font-size: 0.6rem;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ background: var(--panel-2);
+ color: var(--muted);
+ padding: 0.05rem 0.3rem;
+ border-radius: 5px;
+ margin-left: 0.4rem;
+ vertical-align: middle;
+}
+
+/* --- context (⋯) menu --- */
+
+.ctx-menu {
+ position: fixed;
+ z-index: 60;
+ min-width: 190px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ padding: 0.3rem;
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5);
+ display: flex;
+ flex-direction: column;
+}
+
+.ctx-item {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ width: 100%;
+ text-align: left;
+ background: none;
+ border: none;
+ color: var(--text);
+ padding: 0.5rem 0.6rem;
+ border-radius: 7px;
+ font-size: 0.9rem;
+}
+
+.ctx-item:hover {
+ background: var(--panel-2);
+}
+
+.ctx-item i {
+ color: var(--muted);
+ width: 1rem;
+ text-align: center;
+}
+
+.ctx-item.danger {
+ color: var(--danger);
+}
+
+.ctx-item.danger i {
+ color: var(--danger);
+}
+
+/* --- single song page (/song/:id) --- */
+
+.song-page {
+ display: flex;
+ gap: 1.5rem;
+ align-items: flex-end;
+ flex-wrap: wrap;
+}
+
+.song-page-cover {
+ width: 200px;
+ height: 200px;
+ border-radius: var(--radius);
+ object-fit: cover;
+ flex-shrink: 0;
+}
+
+.song-page-cover.cover-empty {
+ display: grid;
+ place-items: center;
+ font-size: 2.5rem;
+ color: var(--muted);
+ background: var(--panel-2);
+}
+
+.song-page-meta {
+ display: flex;
+ flex-direction: column;
+ gap: 0.4rem;
+ min-width: 0;
+}
+
+.song-page-meta .song-title {
+ font-size: 1.8rem;
+ font-weight: 700;
+}
+
+.song-page-actions {
+ display: flex;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+ margin-top: 0.75rem;
+}
+
+/* --- player bar: heart + ⋯ --- */
+
+.pb-song-actions {
+ display: flex;
+ align-items: center;
+ gap: 0.1rem;
+ flex-shrink: 0;
+}
+
+/* --- admin: edit requests --- */
+
+.er-fields {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.3rem;
+ font-size: 0.85rem;
+}
+
+.er-fields li {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ color: var(--muted);
+}
+
+.er-fields li.changed {
+ color: var(--text);
+}
+
+.er-label {
+ width: 4.5rem;
+ flex-shrink: 0;
+ color: var(--muted);
+ text-transform: uppercase;
+ font-size: 0.7rem;
+ letter-spacing: 0.05em;
+}
+
+.er-next {
+ color: var(--accent);
}
\ No newline at end of file
diff --git a/packages/shared/src/api-client.ts b/packages/shared/src/api-client.ts
index c464324..e6f9837 100644
--- a/packages/shared/src/api-client.ts
+++ b/packages/shared/src/api-client.ts
@@ -4,6 +4,8 @@
import type {
Song,
+ PendingSong,
+ SongEditRequest,
Playlist,
PlaylistDetail,
PublicPlaylist,
@@ -157,6 +159,10 @@ export const api = {
return fetch(url(`/api/songs${qs}`)).then(json<Song[]>);
},
+ getSong(id: string): Promise<Song> {
+ return fetch(url(`/api/songs/${id}`)).then(json<Song>);
+ },
+
uploadSong(form: FormData): Promise<Song> {
return fetch(url("/api/songs"), { method: "POST", body: form }).then(json<Song>);
},
@@ -171,6 +177,53 @@ export const api = {
return fetch(url(`/api/songs/${id}`), { method: "DELETE" });
},
+ // --- liked songs -----------------------------------------------------
+
+ listLiked(): Promise<Song[]> {
+ return fetch(url("/api/songs/liked")).then(json<Song[]>);
+ },
+
+ likeSong(id: string): Promise<Response> {
+ return fetch(url(`/api/songs/${id}/like`), { method: "PUT" });
+ },
+
+ unlikeSong(id: string): Promise<Response> {
+ return fetch(url(`/api/songs/${id}/like`), { method: "DELETE" });
+ },
+
+ // --- admin: upload approval ----------------------------------------
+
+ listPendingSongs(): Promise<PendingSong[]> {
+ return fetch(url("/api/songs/pending")).then(json<PendingSong[]>);
+ },
+
+ decidePendingSong(id: string, action: "approve" | "reject"): Promise<Response> {
+ return fetch(url(`/api/songs/${id}/${action}`), { method: "POST" });
+ },
+
+ // --- metadata edit requests --------------------------------------
+
+ requestSongEdit(
+ id: string,
+ patch: { title?: string; artist?: string; album?: string; explicit?: boolean },
+ ): Promise<Response> {
+ return fetch(url(`/api/songs/${id}/edit-requests`), {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(patch),
+ });
+ },
+
+ listSongEditRequests(status = "pending"): Promise<SongEditRequest[]> {
+ return fetch(url(`/api/songs/edit-requests?status=${status}`)).then(
+ json<SongEditRequest[]>,
+ );
+ },
+
+ decideSongEditRequest(id: string, action: "approve" | "reject"): Promise<Response> {
+ return fetch(url(`/api/songs/edit-requests/${id}/${action}`), { method: "POST" });
+ },
+
getLyrics(songId: string): Promise<Lyrics> {
return fetch(url(`/api/songs/${songId}/lyrics`)).then(json<Lyrics>);
},
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index 19c0240..cd8064e 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -13,6 +13,29 @@ export type Song = {
coverUrl: string | null;
streamUrl: string;
uploadedBy: string | null;
+ // Present on library / liked / single-song responses; omitted from the
+ // trimmed song shape inside playlist + artist detail payloads.
+ downloadUrl?: string;
+ status?: "pending" | "approved" | "rejected";
+};
+
+// A pending upload awaiting admin approval, with who uploaded it.
+export type PendingSong = Song & { uploaderName: string | null };
+
+// A non-admin's proposed metadata fix, awaiting admin approval.
+export type SongEditRequest = {
+ id: string;
+ songId: string;
+ current: { title: string; artist: string; album: string | null; explicit: boolean };
+ proposed: {
+ title: string | null;
+ artist: string | null;
+ album: string | null;
+ explicit: boolean | null;
+ };
+ requestedByName: string | null;
+ status: string;
+ createdAt: string;
};
export type Playlist = {