v1 feature: added playlists
This commit is contained in:
@@ -7,6 +7,7 @@ import usersRouter from "./routes/users.ts";
|
||||
import avatarsRouter from "./routes/avatars.ts";
|
||||
import wsRouter from "./routes/ws.ts";
|
||||
import previewRouter from "./routes/preview.ts";
|
||||
import playlistsRouter from "./routes/playlists.ts";
|
||||
|
||||
import { BASE_URL, HOSTNAME, PORT } from "./config.ts";
|
||||
import { errorMiddleware } from "./middleware/error.ts";
|
||||
@@ -40,6 +41,10 @@ app.use(
|
||||
previewRouter.routes(),
|
||||
previewRouter.allowedMethods(),
|
||||
);
|
||||
app.use(
|
||||
playlistsRouter.routes(),
|
||||
playlistsRouter.allowedMethods(),
|
||||
);
|
||||
app.use(routeStaticFilesFrom([
|
||||
`${Deno.cwd()}/dist`,
|
||||
`${Deno.cwd()}/public`,
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { DatabaseSync, type SQLOutputValue } from "node:sqlite";
|
||||
import { Dump, type RichContent, type User } from "./interfaces.ts";
|
||||
import {
|
||||
Dump,
|
||||
type Playlist,
|
||||
type RichContent,
|
||||
type User,
|
||||
} from "./interfaces.ts";
|
||||
|
||||
export const db = new DatabaseSync("api/sql/gerbeur.db");
|
||||
db.exec("PRAGMA foreign_keys = ON;");
|
||||
@@ -133,3 +138,37 @@ export function userApiToRow(user: User): UserRow {
|
||||
avatar_mime: user.avatarMime ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface PlaylistRow {
|
||||
id: string;
|
||||
user_id: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
is_public: number;
|
||||
created_at: string;
|
||||
image_mime: string | null;
|
||||
[key: string]: SQLOutputValue;
|
||||
}
|
||||
|
||||
export function isPlaylistRow(
|
||||
obj: Record<string, SQLOutputValue>,
|
||||
): obj is PlaylistRow {
|
||||
return !!obj && typeof obj.id === "string" &&
|
||||
typeof obj.user_id === "string" &&
|
||||
typeof obj.title === "string" &&
|
||||
typeof obj.is_public === "number" &&
|
||||
typeof obj.created_at === "string";
|
||||
}
|
||||
|
||||
export function playlistRowToApi(row: PlaylistRow): Playlist {
|
||||
return {
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
title: row.title,
|
||||
description: row.description ?? undefined,
|
||||
isPublic: Boolean(row.is_public),
|
||||
createdAt: new Date(row.created_at),
|
||||
imageMime: row.image_mime ?? undefined,
|
||||
dumpCount: typeof row.dump_count === "number" ? row.dump_count : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -141,6 +141,74 @@ export class APIException extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Playlists
|
||||
*/
|
||||
|
||||
export interface Playlist {
|
||||
id: string;
|
||||
userId: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
isPublic: boolean;
|
||||
createdAt: Date;
|
||||
imageMime?: string;
|
||||
dumpCount?: number;
|
||||
}
|
||||
|
||||
export interface PlaylistWithDumps extends Playlist {
|
||||
dumps: Dump[];
|
||||
}
|
||||
|
||||
export interface PlaylistMembership {
|
||||
playlist: Playlist;
|
||||
hasDump: boolean;
|
||||
}
|
||||
|
||||
export interface CreatePlaylistRequest {
|
||||
title: string;
|
||||
description?: string;
|
||||
isPublic: boolean;
|
||||
}
|
||||
|
||||
export interface UpdatePlaylistRequest {
|
||||
title?: string;
|
||||
description?: string;
|
||||
isPublic?: boolean;
|
||||
}
|
||||
|
||||
export interface ReorderPlaylistRequest {
|
||||
dumpIds: string[];
|
||||
}
|
||||
|
||||
export function isCreatePlaylistRequest(
|
||||
obj: unknown,
|
||||
): obj is CreatePlaylistRequest {
|
||||
return !!obj && typeof obj === "object" &&
|
||||
"title" in obj && typeof obj.title === "string" &&
|
||||
(!("description" in obj) || typeof obj.description === "string" ||
|
||||
obj.description === null) &&
|
||||
"isPublic" in obj && typeof obj.isPublic === "boolean";
|
||||
}
|
||||
|
||||
export function isUpdatePlaylistRequest(
|
||||
obj: unknown,
|
||||
): obj is UpdatePlaylistRequest {
|
||||
return !!obj && typeof obj === "object" &&
|
||||
(!("title" in obj) || typeof obj.title === "string") &&
|
||||
(!("description" in obj) || typeof obj.description === "string" ||
|
||||
obj.description === null) &&
|
||||
(!("isPublic" in obj) || typeof obj.isPublic === "boolean");
|
||||
}
|
||||
|
||||
export function isReorderPlaylistRequest(
|
||||
obj: unknown,
|
||||
): obj is ReorderPlaylistRequest {
|
||||
return !!obj && typeof obj === "object" &&
|
||||
"dumpIds" in obj && Array.isArray(obj.dumpIds) &&
|
||||
(obj.dumpIds as unknown[]).every((id) => typeof id === "string");
|
||||
}
|
||||
|
||||
/**
|
||||
* Request DTOs
|
||||
*/
|
||||
|
||||
219
api/routes/playlists.ts
Normal file
219
api/routes/playlists.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
import { Router } from "@oak/oak";
|
||||
import { verifyJWT } from "../lib/jwt.ts";
|
||||
import {
|
||||
APIErrorCode,
|
||||
APIException,
|
||||
isCreatePlaylistRequest,
|
||||
isReorderPlaylistRequest,
|
||||
isUpdatePlaylistRequest,
|
||||
} from "../model/interfaces.ts";
|
||||
import { authMiddleware, type AuthState } from "../middleware/auth.ts";
|
||||
import {
|
||||
addDumpToPlaylist,
|
||||
createPlaylist,
|
||||
deletePlaylist,
|
||||
getPlaylist,
|
||||
getPlaylistImageMime,
|
||||
getPlaylistMembershipsForDump,
|
||||
removeDumpFromPlaylist,
|
||||
reorderPlaylist,
|
||||
setPlaylistImage,
|
||||
updatePlaylist,
|
||||
} from "../services/playlist-service.ts";
|
||||
|
||||
const PLAYLIST_IMAGES_DIR = "api/uploads/playlist-images";
|
||||
const MAX_IMAGE_SIZE = 5 * 1024 * 1024;
|
||||
const ALLOWED_IMAGE_MIMES = new Set([
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
]);
|
||||
|
||||
function checkImageMagicBytes(data: Uint8Array, mime: string): boolean {
|
||||
if (mime === "image/webp") {
|
||||
return data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 &&
|
||||
data[3] === 0x46 && data[8] === 0x57 && data[9] === 0x45 &&
|
||||
data[10] === 0x42 && data[11] === 0x50;
|
||||
}
|
||||
const magic: Record<string, number[]> = {
|
||||
"image/jpeg": [0xFF, 0xD8, 0xFF],
|
||||
"image/png": [0x89, 0x50, 0x4E, 0x47],
|
||||
"image/gif": [0x47, 0x49, 0x46, 0x38],
|
||||
};
|
||||
return (magic[mime] ?? []).every((b, i) => data[i] === b);
|
||||
}
|
||||
|
||||
const router = new Router<AuthState>({ prefix: "/api/playlists" });
|
||||
|
||||
// GET /api/playlists/by-dump/:dumpId/memberships — must be before /:playlistId
|
||||
router.get("/by-dump/:dumpId/memberships", authMiddleware, (ctx) => {
|
||||
const { dumpId } = ctx.params;
|
||||
const userId = ctx.state.user.userId;
|
||||
const memberships = getPlaylistMembershipsForDump(dumpId, userId);
|
||||
ctx.response.body = { success: true, data: memberships };
|
||||
});
|
||||
|
||||
// POST /api/playlists — create
|
||||
router.post("/", authMiddleware, async (ctx) => {
|
||||
const body = await ctx.request.body.json();
|
||||
if (!isCreatePlaylistRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
}
|
||||
const playlist = createPlaylist(body, ctx.state.user.userId);
|
||||
ctx.response.status = 201;
|
||||
ctx.response.body = { success: true, data: playlist };
|
||||
});
|
||||
|
||||
// GET /api/playlists/:playlistId — optional auth
|
||||
router.get("/:playlistId", async (ctx) => {
|
||||
let requestingUserId: string | null = null;
|
||||
const authHeader = ctx.request.headers.get("Authorization");
|
||||
if (authHeader?.startsWith("Bearer ")) {
|
||||
const payload = await verifyJWT(authHeader.substring(7));
|
||||
if (payload) requestingUserId = payload.userId;
|
||||
}
|
||||
const playlist = getPlaylist(ctx.params.playlistId, requestingUserId);
|
||||
ctx.response.body = { success: true, data: playlist };
|
||||
});
|
||||
|
||||
// PUT /api/playlists/:playlistId — update metadata
|
||||
router.put("/:playlistId", authMiddleware, async (ctx) => {
|
||||
const body = await ctx.request.body.json();
|
||||
if (!isUpdatePlaylistRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
}
|
||||
const playlist = updatePlaylist(
|
||||
ctx.params.playlistId,
|
||||
body,
|
||||
ctx.state.user.userId,
|
||||
);
|
||||
ctx.response.body = { success: true, data: playlist };
|
||||
});
|
||||
|
||||
// DELETE /api/playlists/:playlistId
|
||||
router.delete("/:playlistId", authMiddleware, (ctx) => {
|
||||
deletePlaylist(ctx.params.playlistId, ctx.state.user.userId);
|
||||
ctx.response.status = 204;
|
||||
});
|
||||
|
||||
// POST /api/playlists/:playlistId/dumps/:dumpId — add dump
|
||||
router.post("/:playlistId/dumps/:dumpId", authMiddleware, (ctx) => {
|
||||
addDumpToPlaylist(
|
||||
ctx.params.playlistId,
|
||||
ctx.params.dumpId,
|
||||
ctx.state.user.userId,
|
||||
);
|
||||
ctx.response.status = 204;
|
||||
});
|
||||
|
||||
// DELETE /api/playlists/:playlistId/dumps/:dumpId — remove dump
|
||||
router.delete("/:playlistId/dumps/:dumpId", authMiddleware, (ctx) => {
|
||||
removeDumpFromPlaylist(
|
||||
ctx.params.playlistId,
|
||||
ctx.params.dumpId,
|
||||
ctx.state.user.userId,
|
||||
);
|
||||
ctx.response.status = 204;
|
||||
});
|
||||
|
||||
// POST /api/playlists/:playlistId/image — upload playlist image
|
||||
router.post("/:playlistId/image", authMiddleware, async (ctx) => {
|
||||
const contentType = ctx.request.headers.get("content-type") ?? "";
|
||||
if (!contentType.includes("multipart/form-data")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.BAD_REQUEST,
|
||||
400,
|
||||
"Expected multipart/form-data",
|
||||
);
|
||||
}
|
||||
|
||||
const body = await ctx.request.body.formData();
|
||||
const file = body.get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file field");
|
||||
}
|
||||
|
||||
if (!ALLOWED_IMAGE_MIMES.has(file.type)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.BAD_REQUEST,
|
||||
400,
|
||||
"Only JPEG, PNG, GIF, WebP images are allowed",
|
||||
);
|
||||
}
|
||||
|
||||
if (file.size > MAX_IMAGE_SIZE) {
|
||||
throw new APIException(
|
||||
APIErrorCode.BAD_REQUEST,
|
||||
400,
|
||||
"File too large (max 5 MB)",
|
||||
);
|
||||
}
|
||||
|
||||
const data = new Uint8Array(await file.arrayBuffer());
|
||||
if (!checkImageMagicBytes(data, file.type)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.BAD_REQUEST,
|
||||
400,
|
||||
"File content does not match declared type",
|
||||
);
|
||||
}
|
||||
|
||||
await Deno.mkdir(PLAYLIST_IMAGES_DIR, { recursive: true });
|
||||
await Deno.writeFile(`${PLAYLIST_IMAGES_DIR}/${ctx.params.playlistId}`, data);
|
||||
const playlist = setPlaylistImage(
|
||||
ctx.params.playlistId,
|
||||
file.type,
|
||||
ctx.state.user.userId,
|
||||
);
|
||||
ctx.response.body = { success: true, data: playlist };
|
||||
});
|
||||
|
||||
// GET /api/playlists/:playlistId/image — serve playlist image
|
||||
router.get("/:playlistId/image", async (ctx) => {
|
||||
const imageMime = getPlaylistImageMime(ctx.params.playlistId);
|
||||
if (!imageMime) {
|
||||
ctx.response.status = 404;
|
||||
return;
|
||||
}
|
||||
|
||||
let data: Uint8Array;
|
||||
try {
|
||||
data = await Deno.readFile(
|
||||
`${PLAYLIST_IMAGES_DIR}/${ctx.params.playlistId}`,
|
||||
);
|
||||
} catch {
|
||||
ctx.response.status = 404;
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.response.headers.set("Content-Type", imageMime);
|
||||
ctx.response.headers.set("Content-Disposition", "inline");
|
||||
ctx.response.headers.set("Cache-Control", "public, max-age=3600");
|
||||
ctx.response.body = data;
|
||||
});
|
||||
|
||||
// PUT /api/playlists/:playlistId/order — reorder
|
||||
router.put("/:playlistId/order", authMiddleware, async (ctx) => {
|
||||
const body = await ctx.request.body.json();
|
||||
if (!isReorderPlaylistRequest(body)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
400,
|
||||
"Invalid request",
|
||||
);
|
||||
}
|
||||
reorderPlaylist(ctx.params.playlistId, body.dumpIds, ctx.state.user.userId);
|
||||
ctx.response.body = { success: true, data: null };
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
isRegisterUserRequest,
|
||||
} from "../model/interfaces.ts";
|
||||
|
||||
import { createJWT, verifyPassword } from "../lib/jwt.ts";
|
||||
import { createJWT, verifyJWT, verifyPassword } from "../lib/jwt.ts";
|
||||
import { type AuthContext, authMiddleware } from "../middleware/auth.ts";
|
||||
import {
|
||||
createUser,
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
getDumpsByUser,
|
||||
getVotedDumpsByUser,
|
||||
} from "../services/dump-service.ts";
|
||||
import { listPlaylistsByUser } from "../services/playlist-service.ts";
|
||||
|
||||
// Users router
|
||||
const router = new Router({ prefix: "/api/users" });
|
||||
@@ -140,6 +141,19 @@ router.get("/by-id/:userId", (ctx) => {
|
||||
ctx.response.body = { success: true, data: publicUser };
|
||||
});
|
||||
|
||||
// Playlists by user (optional auth: include private only if requester === owner)
|
||||
router.get("/:username/playlists", async (ctx) => {
|
||||
const user = getUserByUsername(ctx.params.username);
|
||||
let requestingUserId: string | null = null;
|
||||
const authHeader = ctx.request.headers.get("Authorization");
|
||||
if (authHeader?.startsWith("Bearer ")) {
|
||||
const payload = await verifyJWT(authHeader.substring(7));
|
||||
if (payload) requestingUserId = payload.userId;
|
||||
}
|
||||
const playlists = listPlaylistsByUser(user.id, requestingUserId);
|
||||
ctx.response.body = { success: true, data: playlists };
|
||||
});
|
||||
|
||||
// Public user profile by username (no passwordHash)
|
||||
router.get("/:username", (ctx) => {
|
||||
const user = getUserByUsername(ctx.params.username);
|
||||
|
||||
306
api/services/playlist-service.ts
Normal file
306
api/services/playlist-service.ts
Normal file
@@ -0,0 +1,306 @@
|
||||
import type { SQLOutputValue } from "node:sqlite";
|
||||
import {
|
||||
APIErrorCode,
|
||||
APIException,
|
||||
type CreatePlaylistRequest,
|
||||
type Dump,
|
||||
type Playlist,
|
||||
type PlaylistMembership,
|
||||
type PlaylistWithDumps,
|
||||
type UpdatePlaylistRequest,
|
||||
} from "../model/interfaces.ts";
|
||||
import {
|
||||
db,
|
||||
dumpRowToApi,
|
||||
isDumpRow,
|
||||
isPlaylistRow,
|
||||
playlistRowToApi,
|
||||
} from "../model/db.ts";
|
||||
import {
|
||||
broadcastPlaylistCreated,
|
||||
broadcastPlaylistDeleted,
|
||||
broadcastPlaylistDumpsUpdated,
|
||||
broadcastPlaylistUpdated,
|
||||
} from "./ws-service.ts";
|
||||
|
||||
const DUMP_SELECT_COLS =
|
||||
"id, kind, title, comment, user_id, created_at, url, rich_content, file_name, file_mime, file_size, vote_count";
|
||||
|
||||
function getPlaylistById(playlistId: string): Playlist {
|
||||
const row = db.prepare(`SELECT * FROM playlists WHERE id = ?;`).get(
|
||||
playlistId,
|
||||
);
|
||||
if (!row || !isPlaylistRow(row)) {
|
||||
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Playlist not found");
|
||||
}
|
||||
return playlistRowToApi(row);
|
||||
}
|
||||
|
||||
export function createPlaylist(
|
||||
req: CreatePlaylistRequest,
|
||||
userId: string,
|
||||
): Playlist {
|
||||
const id = crypto.randomUUID();
|
||||
const createdAt = new Date();
|
||||
db.prepare(
|
||||
`INSERT INTO playlists (id, user_id, title, description, is_public, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?);`,
|
||||
).run(
|
||||
id,
|
||||
userId,
|
||||
req.title,
|
||||
req.description ?? null,
|
||||
req.isPublic ? 1 : 0,
|
||||
createdAt.toISOString(),
|
||||
);
|
||||
const playlist: Playlist = {
|
||||
id,
|
||||
userId,
|
||||
title: req.title,
|
||||
description: req.description,
|
||||
isPublic: req.isPublic,
|
||||
createdAt,
|
||||
};
|
||||
broadcastPlaylistCreated(playlist);
|
||||
return playlist;
|
||||
}
|
||||
|
||||
export function getPlaylist(
|
||||
playlistId: string,
|
||||
requestingUserId: string | null,
|
||||
): PlaylistWithDumps {
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (!playlist.isPublic && requestingUserId !== playlist.userId) {
|
||||
throw new APIException(APIErrorCode.NOT_FOUND, 404, "Playlist not found");
|
||||
}
|
||||
|
||||
const rows = db.prepare(
|
||||
`SELECT ${DUMP_SELECT_COLS.split(", ").map((c) => `d.${c}`).join(", ")}
|
||||
FROM dumps d
|
||||
INNER JOIN playlist_dumps pd ON d.id = pd.dump_id
|
||||
WHERE pd.playlist_id = ?
|
||||
ORDER BY pd.position ASC;`,
|
||||
).all(playlistId);
|
||||
|
||||
const dumps: Dump[] = rows.filter(isDumpRow).map(dumpRowToApi);
|
||||
|
||||
return { ...playlist, dumps };
|
||||
}
|
||||
|
||||
export function listPlaylistsByUser(
|
||||
userId: string,
|
||||
requestingUserId: string | null,
|
||||
): Playlist[] {
|
||||
const isOwner = requestingUserId === userId;
|
||||
const sql = isOwner
|
||||
? `SELECT p.*, (SELECT COUNT(*) FROM playlist_dumps pd WHERE pd.playlist_id = p.id) as dump_count
|
||||
FROM playlists p WHERE p.user_id = ? ORDER BY p.created_at DESC;`
|
||||
: `SELECT p.*, (SELECT COUNT(*) FROM playlist_dumps pd WHERE pd.playlist_id = p.id) as dump_count
|
||||
FROM playlists p WHERE p.user_id = ? AND p.is_public = 1 ORDER BY p.created_at DESC;`;
|
||||
|
||||
const rows = db.prepare(sql).all(userId);
|
||||
return rows.filter(isPlaylistRow).map(playlistRowToApi);
|
||||
}
|
||||
|
||||
export function updatePlaylist(
|
||||
playlistId: string,
|
||||
req: UpdatePlaylistRequest,
|
||||
requestingUserId: string,
|
||||
): Playlist {
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
|
||||
}
|
||||
|
||||
const newTitle = req.title ?? playlist.title;
|
||||
const newDescription = "description" in req
|
||||
? (req.description ?? null)
|
||||
: (playlist.description ?? null);
|
||||
const newIsPublic = req.isPublic !== undefined
|
||||
? req.isPublic
|
||||
: playlist.isPublic;
|
||||
|
||||
db.prepare(
|
||||
`UPDATE playlists SET title = ?, description = ?, is_public = ? WHERE id = ?;`,
|
||||
).run(newTitle, newDescription, newIsPublic ? 1 : 0, playlistId);
|
||||
|
||||
const updated: Playlist = {
|
||||
...playlist,
|
||||
title: newTitle,
|
||||
description: newDescription ?? undefined,
|
||||
isPublic: newIsPublic,
|
||||
};
|
||||
broadcastPlaylistUpdated(updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
export function deletePlaylist(
|
||||
playlistId: string,
|
||||
requestingUserId: string,
|
||||
): void {
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
|
||||
}
|
||||
|
||||
db.prepare(`DELETE FROM playlists WHERE id = ?;`).run(playlistId);
|
||||
broadcastPlaylistDeleted(playlistId, playlist.userId, playlist.isPublic);
|
||||
}
|
||||
|
||||
export function setPlaylistImage(
|
||||
playlistId: string,
|
||||
imageMime: string,
|
||||
requestingUserId: string,
|
||||
): Playlist {
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
if (playlist.userId !== requestingUserId) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
|
||||
}
|
||||
db.prepare(`UPDATE playlists SET image_mime = ? WHERE id = ?;`).run(
|
||||
imageMime,
|
||||
playlistId,
|
||||
);
|
||||
const updated = getPlaylistById(playlistId);
|
||||
broadcastPlaylistUpdated(updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
export function addDumpToPlaylist(
|
||||
playlistId: string,
|
||||
dumpId: string,
|
||||
requestingUserId: string,
|
||||
): void {
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
|
||||
}
|
||||
|
||||
const maxRow = db.prepare(
|
||||
`SELECT MAX(position) as max_pos FROM playlist_dumps WHERE playlist_id = ?;`,
|
||||
).get(playlistId) as { max_pos: number | null } | undefined;
|
||||
|
||||
const nextPos = (maxRow?.max_pos ?? -1) + 1;
|
||||
const addedAt = new Date().toISOString();
|
||||
|
||||
try {
|
||||
db.prepare(
|
||||
`INSERT INTO playlist_dumps (playlist_id, dump_id, position, added_at)
|
||||
VALUES (?, ?, ?, ?);`,
|
||||
).run(playlistId, dumpId, nextPos, addedAt);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
if (msg.includes("UNIQUE") || msg.includes("unique")) {
|
||||
throw new APIException(
|
||||
APIErrorCode.VALIDATION_ERROR,
|
||||
409,
|
||||
"Dump already in playlist",
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const dumpIds = getCurrentDumpIds(playlistId);
|
||||
broadcastPlaylistDumpsUpdated(playlist, dumpIds);
|
||||
}
|
||||
|
||||
export function removeDumpFromPlaylist(
|
||||
playlistId: string,
|
||||
dumpId: string,
|
||||
requestingUserId: string,
|
||||
): void {
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
|
||||
}
|
||||
|
||||
db.prepare(
|
||||
`DELETE FROM playlist_dumps WHERE playlist_id = ? AND dump_id = ?;`,
|
||||
).run(playlistId, dumpId);
|
||||
|
||||
const dumpIds = getCurrentDumpIds(playlistId);
|
||||
broadcastPlaylistDumpsUpdated(playlist, dumpIds);
|
||||
}
|
||||
|
||||
export function reorderPlaylist(
|
||||
playlistId: string,
|
||||
dumpIds: string[],
|
||||
requestingUserId: string,
|
||||
): void {
|
||||
const playlist = getPlaylistById(playlistId);
|
||||
|
||||
if (playlist.userId !== requestingUserId) {
|
||||
throw new APIException(APIErrorCode.UNAUTHORIZED, 403, "Forbidden");
|
||||
}
|
||||
|
||||
const currentIds = getCurrentDumpIds(playlistId);
|
||||
const currentSet = new Set(currentIds);
|
||||
const newSet = new Set(dumpIds);
|
||||
|
||||
if (
|
||||
currentSet.size !== newSet.size ||
|
||||
!currentIds.every((id) => newSet.has(id))
|
||||
) {
|
||||
throw new APIException(
|
||||
APIErrorCode.BAD_REQUEST,
|
||||
400,
|
||||
"dumpIds must match current playlist members exactly",
|
||||
);
|
||||
}
|
||||
|
||||
const update = db.prepare(
|
||||
`UPDATE playlist_dumps SET position = ? WHERE playlist_id = ? AND dump_id = ?;`,
|
||||
);
|
||||
for (let i = 0; i < dumpIds.length; i++) {
|
||||
update.run(i, playlistId, dumpIds[i]);
|
||||
}
|
||||
|
||||
broadcastPlaylistDumpsUpdated(playlist, dumpIds);
|
||||
}
|
||||
|
||||
export function getPlaylistMembershipsForDump(
|
||||
dumpId: string,
|
||||
userId: string,
|
||||
): PlaylistMembership[] {
|
||||
const rows = db.prepare(
|
||||
`SELECT p.*, pd.dump_id IS NOT NULL as has_dump
|
||||
FROM playlists p
|
||||
LEFT JOIN playlist_dumps pd ON pd.playlist_id = p.id AND pd.dump_id = ?
|
||||
WHERE p.user_id = ?
|
||||
ORDER BY p.created_at DESC;`,
|
||||
).all(dumpId, userId) as Array<Record<string, SQLOutputValue>>;
|
||||
|
||||
return rows.map((row) => {
|
||||
if (!isPlaylistRow(row)) {
|
||||
throw new APIException(
|
||||
APIErrorCode.SERVER_ERROR,
|
||||
500,
|
||||
"Malformed playlist data",
|
||||
);
|
||||
}
|
||||
return {
|
||||
playlist: playlistRowToApi(row),
|
||||
hasDump: Boolean(row.has_dump),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function getPlaylistImageMime(playlistId: string): string | undefined {
|
||||
const row = db.prepare(`SELECT image_mime FROM playlists WHERE id = ?;`).get(
|
||||
playlistId,
|
||||
) as
|
||||
| { image_mime: string | null }
|
||||
| undefined;
|
||||
return row?.image_mime ?? undefined;
|
||||
}
|
||||
|
||||
function getCurrentDumpIds(playlistId: string): string[] {
|
||||
const rows = db.prepare(
|
||||
`SELECT dump_id FROM playlist_dumps WHERE playlist_id = ? ORDER BY position ASC;`,
|
||||
).all(playlistId) as Array<{ dump_id: string }>;
|
||||
return rows.map((r) => r.dump_id);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Dump, OnlineUser } from "../model/interfaces.ts";
|
||||
import type { Dump, OnlineUser, Playlist } from "../model/interfaces.ts";
|
||||
|
||||
export interface WsClient {
|
||||
socket: WebSocket;
|
||||
@@ -82,9 +82,50 @@ export function broadcastVoteUpdate(
|
||||
}
|
||||
}
|
||||
|
||||
function sendToPlaylistAudience(
|
||||
playlist: Pick<Playlist, "isPublic" | "userId">,
|
||||
data: unknown,
|
||||
): void {
|
||||
for (const client of clients) {
|
||||
if (playlist.isPublic || client.userId === playlist.userId) {
|
||||
send(client.socket, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function broadcastPlaylistCreated(playlist: Playlist): void {
|
||||
sendToPlaylistAudience(playlist, { type: "playlist_created", playlist });
|
||||
}
|
||||
|
||||
export function broadcastPlaylistUpdated(playlist: Playlist): void {
|
||||
sendToPlaylistAudience(playlist, { type: "playlist_updated", playlist });
|
||||
}
|
||||
|
||||
export function broadcastPlaylistDeleted(
|
||||
playlistId: string,
|
||||
userId: string,
|
||||
isPublic: boolean,
|
||||
): void {
|
||||
sendToPlaylistAudience({ isPublic, userId }, {
|
||||
type: "playlist_deleted",
|
||||
playlistId,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
export function broadcastPlaylistDumpsUpdated(
|
||||
playlist: Playlist,
|
||||
dumpIds: string[],
|
||||
): void {
|
||||
sendToPlaylistAudience(playlist, {
|
||||
type: "playlist_dumps_updated",
|
||||
playlistId: playlist.id,
|
||||
dumpIds,
|
||||
});
|
||||
}
|
||||
|
||||
// Keepalive: ping all clients every 30s, remove non-responsive ones
|
||||
const PING_INTERVAL = 30_000;
|
||||
const _PONG_TIMEOUT = 5_000;
|
||||
|
||||
setInterval(() => {
|
||||
for (const client of clients) {
|
||||
|
||||
@@ -11,7 +11,7 @@ CREATE TABLE dumps (
|
||||
file_mime TEXT,
|
||||
file_size INTEGER,
|
||||
vote_count INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
@@ -31,3 +31,26 @@ CREATE TABLE votes (
|
||||
FOREIGN KEY (dump_id) REFERENCES dumps(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- v2: playlists
|
||||
CREATE TABLE playlists (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
is_public INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
image_mime TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE playlist_dumps (
|
||||
playlist_id TEXT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
|
||||
dump_id TEXT NOT NULL REFERENCES dumps(id) ON DELETE CASCADE,
|
||||
position INTEGER NOT NULL,
|
||||
added_at TEXT NOT NULL,
|
||||
PRIMARY KEY (playlist_id, dump_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_dumps_user ON dumps(user_id);
|
||||
CREATE INDEX idx_playlist_dumps_order ON playlist_dumps(playlist_id, position);
|
||||
CREATE INDEX idx_playlists_user ON playlists(user_id);
|
||||
|
||||
Reference in New Issue
Block a user