v4: playlists have categories of their own — a set apart from the dumps', which admins manage on /manage under "Playlist categories", next to "Dump categories". Each category now has a kind, dump or playlist, its slug and name unique within its kind only; migration 0025 rebuilds categories with the column, every existing one becoming a dump category with its dumps, and adds playlist_categories. A playlist's owner files it under any of them in the create and edit forms, and it shows them as chips on its card and its page, each leading to /playlists/<slug>.

/playlists is the new page of every public playlist, newest first (GET /api/playlists), and /playlists/<slug> a playlist category's, with a menu of the categories, linked from the user menu as "All playlists"; `playlists` is reserved as a dump category's slug, and one that had it is renamed. A profile's Playlists tab narrows to a playlist category with the same menu as its Dumps tab (?category=), and so do the Dumps and Playlists tabs of /search, each with its own kind (category and playlistCategory for GET /api/search), another tab dropping it.

The category service takes the kind throughout, so a dump can't be filed under a playlist category nor the other way round, and categoryJoin is the one filter join the dump, follow and playlist services share. useCategories(kind) gives one kind's set from the one fetch, CategoryChips replaces the chips the dump card and page each drew, useCategoryFilter keeps a list to its category as the socket brings more, and useCategorySelection holds a form's picked categories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-09 21:53:16 +00:00
parent 681170a517
commit 53515ce46f
71 changed files with 2166 additions and 705 deletions

View File

@@ -28,14 +28,14 @@ Deno.test("runMigrations: a fresh database is left as schema.sql made it", () =>
.get() as {
n: number;
};
assertEquals(applied.n, 24);
assertEquals(applied.n, 25);
// Running again applies nothing.
runMigrations(db);
assertEquals(
(db.prepare(`SELECT COUNT(*) as n FROM schema_migrations;`).get() as {
n: number;
}).n,
24,
25,
);
db.close();
});

View File

@@ -0,0 +1,108 @@
import "../../setup.ts";
import { assertEquals, assertThrows } from "@std/assert";
import { DatabaseSync } from "node:sqlite";
import { up as up0025 } from "../../../db/migrations/0025_playlist_categories.ts";
/** Returns a database with the tables 0025 changes, as 0006 made them. */
function oldDb(): DatabaseSync {
const db = new DatabaseSync(":memory:");
db.exec(`PRAGMA foreign_keys = ON;`);
db.exec(`
CREATE TABLE dumps (id TEXT PRIMARY KEY);
CREATE TABLE playlists (id TEXT PRIMARY KEY);
CREATE TABLE categories (
id TEXT PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
name TEXT NOT NULL UNIQUE,
position INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT
);
CREATE TABLE dump_categories (
dump_id TEXT NOT NULL,
category_id TEXT NOT NULL,
PRIMARY KEY (dump_id, category_id),
FOREIGN KEY (dump_id) REFERENCES dumps(id) ON DELETE CASCADE,
FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE CASCADE
);
`);
return db;
}
Deno.test("migration 0025 keeps the categories as dump categories, with their dumps", () => {
const db = oldDb();
db.exec(`INSERT INTO dumps (id) VALUES ('d1'), ('d2');`);
db.exec(
`INSERT INTO categories (id, slug, name, position, created_at) VALUES
('c1', 'music', 'Music', 2, '2026-01-01T00:00:00.000Z'),
('c2', 'playlists', 'Playlists', 1, '2026-01-02T00:00:00.000Z');`,
);
db.exec(
`INSERT INTO dump_categories (dump_id, category_id) VALUES
('d1', 'c1'), ('d2', 'c1'), ('d2', 'c2');`,
);
db.exec("BEGIN;");
up0025(db);
db.exec("COMMIT;");
up0025(db); // idempotent
assertEquals(
db.prepare(
`SELECT id, kind, slug, name, position FROM categories ORDER BY id;`,
).all().map((r) => ({ ...r })),
[
{ id: "c1", kind: "dump", slug: "music", name: "Music", position: 2 },
// `playlists` is now the page of every playlist.
{
id: "c2",
kind: "dump",
slug: "playlists-2",
name: "Playlists",
position: 1,
},
],
);
assertEquals(
db.prepare(
`SELECT dump_id, category_id FROM dump_categories ORDER BY dump_id, category_id;`,
).all().map((r) => ({ ...r })),
[
{ dump_id: "d1", category_id: "c1" },
{ dump_id: "d2", category_id: "c1" },
{ dump_id: "d2", category_id: "c2" },
],
);
// A slug or name is unique within its kind only.
db.exec(
`INSERT INTO categories (id, kind, slug, name, created_at)
VALUES ('p1', 'playlist', 'music', 'Music', '2026-01-03T00:00:00.000Z');`,
);
assertThrows(() =>
db.exec(
`INSERT INTO categories (id, kind, slug, name, created_at)
VALUES ('p2', 'playlist', 'music', 'Other', '2026-01-03T00:00:00.000Z');`,
)
);
// The links still cascade.
db.exec(`INSERT INTO playlists (id) VALUES ('pl1');`);
db.exec(
`INSERT INTO playlist_categories (playlist_id, category_id) VALUES ('pl1', 'p1');`,
);
db.exec(`DELETE FROM categories WHERE id IN ('c1', 'p1');`);
assertEquals(
(db.prepare(`SELECT COUNT(*) as n FROM dump_categories;`).get() as {
n: number;
}).n,
1,
);
assertEquals(
(db.prepare(`SELECT COUNT(*) as n FROM playlist_categories;`).get() as {
n: number;
}).n,
0,
);
db.close();
});

View File

@@ -26,6 +26,7 @@ import {
} from "../services/email-service.ts";
import type { APIError, APIResponse } from "../../shared/api.ts";
import type { Role } from "../../shared/user.ts";
import type { CategoryKind } from "../../shared/category.ts";
export { app, db, TEST_DIR };
@@ -40,6 +41,7 @@ const TABLES = [
"federation_outbox",
"dump_backlinks",
"dump_categories",
"playlist_categories",
"playlist_dumps",
"comment_likes",
"comments",
@@ -268,13 +270,19 @@ export function insertComment(
}
export function insertCategory(
opts: { slug: string; name?: string; position?: number },
opts: {
slug: string;
name?: string;
position?: number;
kind?: CategoryKind;
},
): string {
const id = crypto.randomUUID();
db.prepare(
`INSERT INTO categories (id, slug, name, position, created_at) VALUES (?, ?, ?, ?, ?);`,
`INSERT INTO categories (id, kind, slug, name, position, created_at) VALUES (?, ?, ?, ?, ?, ?);`,
).run(
id,
opts.kind ?? "dump",
opts.slug,
opts.name ?? opts.slug,
opts.position ?? 0,

View File

@@ -10,6 +10,7 @@ Deno.test("category slugs: the feed tabs, app pages and server paths are reserve
"settings",
"manage",
"community",
"playlists",
"api",
"ws",
]
@@ -17,7 +18,7 @@ Deno.test("category slugs: the feed tabs, app pages and server paths are reserve
assert(isReservedSlug(word), word);
}
// v3's words are free again: nothing lives at /dumps or /users now.
for (const word of ["music", "dumps", "users", "playlists", "~"]) {
for (const word of ["music", "dumps", "users", "~"]) {
assertFalse(isReservedSlug(word), word);
}
});

View File

@@ -29,7 +29,7 @@ test("categories: listed by position, then slug", async () => {
test("categories: only category:manage may create, update or delete", async () => {
const admin = await createUser({ role: "admin" });
const mod = await createUser({ role: "moderator" });
const json = { slug: "music", name: "Music" };
const json = { kind: "dump", slug: "music", name: "Music" };
assertEquals((await post("/api/categories", { json })).status, 401);
assertEquals(
(await post("/api/categories", { auth: mod.auth, json })).status,
@@ -64,13 +64,17 @@ test("categories: only category:manage may create, update or delete", async () =
test("categories: slug and name rules, and friendly conflicts", async () => {
const admin = await createUser({ role: "admin" });
const create = (json: unknown) =>
post<Category>("/api/categories", { auth: admin.auth, json });
const create = (json: Record<string, unknown>) =>
post<Category>("/api/categories", {
auth: admin.auth,
json: { kind: "dump", ...json },
});
for (
const [json, message] of [
[{ slug: "Bad Slug", name: "x" }, "lowercase"],
[{ slug: "hot", name: "x" }, "reserved"],
[{ slug: "settings", name: "x" }, "reserved"],
[{ slug: "playlists", name: "x" }, "reserved"],
[{ slug: "a".repeat(51), name: "x" }, "at most 50"],
[{ slug: "ok", name: " " }, "Name is required"],
[{ slug: "ok", name: "x".repeat(51) }, "at most 50"],
@@ -144,3 +148,37 @@ test("GET /api/dumps?category=: members only, private for the owner", async () =
[],
);
});
test("categories: each kind is a set apart", async () => {
const admin = await createUser({ role: "admin" });
const create = (json: Record<string, unknown>) =>
post<Category>("/api/categories", { auth: admin.auth, json });
assertEquals((await create({ slug: "music", name: "Music" })).status, 400);
const dump = await create({ kind: "dump", slug: "music", name: "Music" });
assertEquals(dump.data.kind, "dump");
// The same slug and name are free in the other kind, taken in the same.
const playlist = await create({
kind: "playlist",
slug: "music",
name: "Music",
});
assertEquals(playlist.status, 201);
assertEquals(playlist.data.kind, "playlist");
assertEquals(
(await create({ kind: "playlist", slug: "music", name: "Other" })).status,
409,
);
// A playlist category's page lives under /playlists/: nothing is reserved.
assertEquals(
(await create({ kind: "playlist", slug: "hot", name: "Hot" })).status,
201,
);
const list = await get<Category[]>("/api/categories");
assertEquals(list.data.map((c) => [c.kind, c.slug]), [
["dump", "music"],
["playlist", "hot"],
["playlist", "music"],
]);
});

View File

@@ -130,6 +130,18 @@ test("POST /api/dumps: an unknown category is refused and nothing is left behind
assertEquals(count(`SELECT COUNT(*) as n FROM dumps;`), 0);
});
test("POST /api/dumps: a playlist category is refused", async () => {
const user = await createUser();
const lists = insertCategory({ slug: "mixes", kind: "playlist" });
using _ = stubNetwork(() => PAGE.clone());
const res = await post("/api/dumps", {
auth: user.auth,
json: { url: "https://example.com/e", categoryIds: [lists] },
});
assertEquals(res.status, 400);
assertEquals(count(`SELECT COUNT(*) as n FROM dumps;`), 0);
});
test("POST /api/dumps: a file dump is stored and served back", async () => {
const user = await createUser();
const res = await post<Dump>("/api/dumps", {

View File

@@ -6,6 +6,7 @@ import {
del,
formWithFile,
get,
insertCategory,
insertDump,
insertPlaylist,
PNG,
@@ -539,3 +540,126 @@ test("reorder: a moderator orders around the owner's private dumps", async () =>
b.id,
]);
});
test("playlist categories: filed on creation, replaced on update, dump categories refused", async () => {
const user = await createUser();
const mixes = insertCategory({ slug: "mixes", kind: "playlist" });
const live = insertCategory({ slug: "live", kind: "playlist" });
const music = insertCategory({ slug: "music" });
const refused = await post("/api/playlists", {
auth: user.auth,
json: { title: "Wrong", isPublic: true, categoryIds: [music] },
});
assertEquals(refused.status, 400);
assertEquals(count(`SELECT COUNT(*) as n FROM playlists;`), 0);
assertEquals(
(await post("/api/playlists", {
auth: user.auth,
json: { title: "Bad", isPublic: true, categoryIds: "mixes" },
})).status,
400,
);
const created = await post<Playlist>("/api/playlists", {
auth: user.auth,
json: { title: "Mix", isPublic: true, categoryIds: [mixes, mixes] },
});
assertEquals(created.status, 201);
assertEquals(created.data.categoryIds, [mixes]);
assertEquals(
(await get<Playlist>(`/api/playlists/${created.data.id}`)).data
.categoryIds,
[mixes],
);
const id = created.data.id;
assertEquals(
(await put(`/api/playlists/${id}`, {
auth: user.auth,
json: { categoryIds: [music] },
})).status,
400,
);
const updated = await put<Playlist>(`/api/playlists/${id}`, {
auth: user.auth,
json: { categoryIds: [live] },
});
assertEquals(updated.data.categoryIds, [live]);
// A change of anything else keeps them.
const renamed = await put<Playlist>(`/api/playlists/${id}`, {
auth: user.auth,
json: { title: "Live mix" },
});
assertEquals(renamed.data.categoryIds, [live]);
const cleared = await put<Playlist>(`/api/playlists/${id}`, {
auth: user.auth,
json: { categoryIds: [] },
});
assertEquals(cleared.data.categoryIds, []);
});
test("GET /api/playlists: every public playlist, newest first, by category", async () => {
const owner = await createUser();
const other = await createUser();
const mixes = insertCategory({ slug: "mixes", kind: "playlist" });
insertCategory({ slug: "music" });
const a = insertPlaylist({ userId: owner.id, title: "A" });
insertPlaylist({ userId: other.id, title: "B" });
const hidden = insertPlaylist({
userId: owner.id,
title: "Hidden",
isPublic: false,
});
db.prepare(`UPDATE playlists SET created_at = ? WHERE id = ?;`)
.run("2026-01-01T00:00:00.000Z", a.id);
for (const p of [a, hidden]) {
db.prepare(
`INSERT INTO playlist_categories (playlist_id, category_id) VALUES (?, ?);`,
).run(p.id, mixes);
}
const all = await get<PaginatedData<Playlist>>("/api/playlists", {
auth: owner.auth,
});
assertEquals(all.data.items.map((p) => p.title), ["B", "A"]);
assertEquals(all.data.items[1].categoryIds, [mixes]);
assertEquals(
(await get<PaginatedData<Playlist>>("/api/playlists?limit=1")).data
.hasMore,
true,
);
assertEquals(
(await get<PaginatedData<Playlist>>("/api/playlists?category=mixes")).data
.items.map((p) => p.id),
[a.id],
);
// A dump category's slug names no playlist category.
assertEquals((await get("/api/playlists?category=music")).status, 404);
assertEquals((await get("/api/playlists?category=nope")).status, 404);
});
test("GET /api/users/:key/playlists?category=: their playlists in one category", async () => {
const owner = await createUser();
const mixes = insertCategory({ slug: "mixes", kind: "playlist" });
const a = insertPlaylist({ userId: owner.id, title: "A" });
insertPlaylist({ userId: owner.id, title: "B" });
db.prepare(
`INSERT INTO playlist_categories (playlist_id, category_id) VALUES (?, ?);`,
).run(a.id, mixes);
const url = `/api/users/${owner.id}/playlists`;
assertEquals(
(await get<PaginatedData<Playlist>>(url)).data.items.length,
2,
);
assertEquals(
(await get<PaginatedData<Playlist>>(`${url}?category=mixes`)).data.items
.map((p) => p.id),
[a.id],
);
assertEquals(
(await get<PaginatedData<Playlist>>(`${url}?category=nope`)).data.items,
[],
);
});

View File

@@ -2,6 +2,7 @@ import {
createUser,
db,
get,
insertCategory,
insertDump,
insertPlaylist,
test,
@@ -62,3 +63,44 @@ test("GET /api/search: dumps, users and playlists, privacy-filtered", async () =
playlists: [],
});
});
test("GET /api/search: category and playlistCategory narrow each list", async () => {
const owner = await createUser();
const music = insertCategory({ slug: "music" });
const mixes = insertCategory({ slug: "mixes", kind: "playlist" });
const filed = insertDump({ userId: owner.id, title: "Banana song" });
insertDump({ userId: owner.id, title: "Banana bread" });
const list = insertPlaylist({ userId: owner.id, title: "Banana mix" });
insertPlaylist({ userId: owner.id, title: "Banana bin" });
db.prepare(
`INSERT INTO dump_categories (dump_id, category_id) VALUES (?, ?);`,
).run(filed.id, music);
db.prepare(
`INSERT INTO playlist_categories (playlist_id, category_id) VALUES (?, ?);`,
).run(list.id, mixes);
const all = (await get<SearchResults>("/api/search?q=banana")).data;
assertEquals(all.dumps.total, 2);
assertEquals(all.playlists.length, 2);
const dumps = (await get<SearchResults>(
"/api/search?q=banana&category=music",
)).data;
assertEquals(dumps.dumps.items.map((d) => d.id), [filed.id]);
assertEquals(dumps.dumps.total, 1);
assertEquals(dumps.playlists.length, 2);
const playlists = (await get<SearchResults>(
"/api/search?q=banana&playlistCategory=mixes",
)).data;
assertEquals(playlists.dumps.total, 2);
assertEquals(playlists.playlists.map((p) => p.id), [list.id]);
assertEquals(playlists.playlists[0].categoryIds, [mixes]);
// Each names a category of its own kind only.
const crossed = (await get<SearchResults>(
"/api/search?q=banana&category=mixes&playlistCategory=music",
)).data;
assertEquals(crossed.dumps.total, 0);
assertEquals(crossed.playlists, []);
});

View File

@@ -6,10 +6,27 @@ import {
} from "../../validators/category.ts";
Deno.test("category requests", () => {
assert(isCreateCategoryRequest({ slug: "a", name: "A" }));
assert(isCreateCategoryRequest({ slug: "a", name: "A", position: 2 }));
assertFalse(isCreateCategoryRequest({ slug: "a" }));
assertFalse(isCreateCategoryRequest({ slug: "a", name: "A", position: "2" }));
assert(isCreateCategoryRequest({ kind: "dump", slug: "a", name: "A" }));
assert(isCreateCategoryRequest({ kind: "playlist", slug: "a", name: "A" }));
assert(
isCreateCategoryRequest({
kind: "dump",
slug: "a",
name: "A",
position: 2,
}),
);
assertFalse(isCreateCategoryRequest({ slug: "a", name: "A" }));
assertFalse(isCreateCategoryRequest({ kind: "user", slug: "a", name: "A" }));
assertFalse(isCreateCategoryRequest({ kind: "dump", slug: "a" }));
assertFalse(
isCreateCategoryRequest({
kind: "dump",
slug: "a",
name: "A",
position: "2",
}),
);
assert(isUpdateCategoryRequest({}));
assertFalse(isUpdateCategoryRequest({ name: 1 }));
});