SPB Git

Repository Public

libraryroutes.ts 6.0 KB 82 lines typescript

1import { z } from "zod";2import { sql } from "../db";3import { env } from "../env";4import { ApiError, body } from "../http";5import { rateLimit } from "../ratelimit";6import type { UserContext } from "../auth";7import * as cat from "@/server/catalog";8import { getLyrics } from "@/server/lyrics";9import { assertPlaylistBase, librarySync, listPlays, playlistStamp, recordPlays, userSync } from "@/server/sync";10import { ids, oneOf, page, playbackState, playlistName, uuid } from "./schemas";11import type { RouteDef } from "./router";1213/** Listening surface, open to every signed-in account (admin or listener). Nothing here can change the library. */14export const libraryRoutes: RouteDef<UserContext>[] = [15  ["GET", "home", ({ ctx }) => cat.home(ctx.userId)],16  ["GET", "albums", ({ url, ctx }) => cat.listAlbums(ctx.userId, page(url, 60), oneOf(url, "sort", ["recent", "title", "artist", "year"] as const, "artist"))],17  ["GET", "albums/:id", ({ params, ctx }) => cat.getAlbum(ctx.userId, uuid.parse(params.id))],18  ["GET", "artists", ({ url }) => cat.listArtists(page(url, 60))],19  ["GET", "artists/:id", ({ params, ctx }) => cat.getArtist(ctx.userId, uuid.parse(params.id))],20  ["GET", "tracks", ({ url, ctx }) => cat.listTracks(ctx.userId, page(url, 100), oneOf(url, "sort", ["title", "recent", "artist"] as const, "artist"))],21  ["GET", "search", ({ url, ctx }) => cat.search(ctx.userId, (url.searchParams.get("q") ?? "").slice(0, 100))],2223  ["GET", "favorites", ({ url, ctx }) => cat.listFavorites(ctx.userId, page(url, 100))],24  ["PUT", "favorites/:kind/:id", ({ params, ctx }) => cat.setFavorite(ctx.userId, z.enum(["track", "album"]).parse(params.kind), uuid.parse(params.id), true)],25  ["DELETE", "favorites/:kind/:id", ({ params, ctx }) => cat.setFavorite(ctx.userId, z.enum(["track", "album"]).parse(params.kind), uuid.parse(params.id), false)],2627  ["GET", "playlists", async ({ ctx }) => ({ items: await cat.listPlaylists(ctx.userId) })],28  ["POST", "playlists", async ({ req, ctx }) => { const b = await body(req, z.object({ name: playlistName.shape.name, trackIds: z.array(uuid).max(500).optional() }).strict()); return cat.createPlaylist(ctx.userId, b.name, b.trackIds ?? []); }],29  ["GET", "playlists/:id", ({ params, ctx }) => cat.getPlaylist(ctx.userId, uuid.parse(params.id))],30  // baseUpdatedAt (optional, sent by clients that edit offline): the change is refused with 409 when the list moved on since.31  ["PATCH", "playlists/:id", async ({ req, params, ctx }) => {32    const id = uuid.parse(params.id);33    const b = await body(req, z.object({ name: playlistName.shape.name, baseUpdatedAt: z.string().max(40).optional() }).strict());34    await assertPlaylistBase(ctx.userId, id, b.baseUpdatedAt);35    await cat.renamePlaylist(ctx.userId, id, b.name);36    return playlistStamp(ctx.userId, id);37  }],38  ["DELETE", "playlists/:id", async ({ params, ctx }) => { await cat.deletePlaylist(ctx.userId, uuid.parse(params.id)); }],39  ["POST", "playlists/:id/tracks", async ({ req, params, ctx }) => {40    const id = uuid.parse(params.id);41    const b = await body(req, z.object({ trackIds: ids }).strict());42    const r = await cat.addToPlaylist(ctx.userId, id, b.trackIds);43    return { ...r, updatedAt: (await playlistStamp(ctx.userId, id)).updatedAt };44  }],45  ["PUT", "playlists/:id/order", async ({ req, params, ctx }) => {46    const id = uuid.parse(params.id);47    const b = await body(req, z.object({ entryIds: z.array(uuid).max(5000), baseUpdatedAt: z.string().max(40).optional() }).strict());48    await assertPlaylistBase(ctx.userId, id, b.baseUpdatedAt);49    await cat.reorderPlaylist(ctx.userId, id, b.entryIds);50    return playlistStamp(ctx.userId, id);51  }],5253  // Native clients: catalogue deltas, the account's own data in one answer, listening history.54  ["GET", "sync", ({ url }) => { const since = Number(url.searchParams.get("since") ?? 0); if (!Number.isSafeInteger(since) || since < 0) throw new ApiError(400, "invalid_input", "since must be a revision"); return librarySync(since); }],55  ["GET", "sync/me", ({ ctx }) => userSync(ctx.userId)],56  ["GET", "history", ({ url, ctx }) => listPlays(ctx.userId, page(url, 100, 500))],57  ["POST", "history", async ({ req, ctx }) => {58    const b = await body(req, z.object({ events: z.array(z.object({59      id: uuid, trackId: uuid, playedAt: z.string().max(40), listenedMs: z.number().int().min(0).max(86_400_000), completed: z.boolean(), source: z.enum(["stream", "local"]),60    }).strict()).max(500) }).strict());61    return recordPlays(ctx.userId, req.headers.get("user-agent") ?? "", b.events);62  }],6364  ["GET", "playback", ({ ctx }) => cat.getPlayback(ctx.userId)],65  ["PUT", "playback", async ({ req, ctx }) => { await cat.savePlayback(ctx.userId, await body(req, playbackState)); }],6667  // Fallback for a browser that cannot decode an original: any listener may ask for the AAC rendition of a track.68  ["POST", "tracks/:id/compat", async ({ params, ctx }) => {69    const id = uuid.parse(params.id);70    const [t] = await sql<{ compat_state: string; codec: string }[]>`SELECT compat_state, codec FROM tracks WHERE id = ${id}`;71    if (!t) throw new ApiError(404, "not_found");72    if (t.compat_state === "ready" || t.compat_state === "queued" || t.compat_state === "working") return { compatState: t.compat_state };73    if (env.renditions === "never") throw new ApiError(409, "renditions_disabled", "Compatibility renditions are disabled on this server");74    if (t.codec.startsWith("dsd") && !env.transcodeDsd) throw new ApiError(409, "renditions_disabled", "DSD conversion is not enabled on this server");75    await rateLimit(`compat:${ctx.userId}`, 60, 3600);76    await sql`UPDATE tracks SET compat_state = 'queued', compat_error = NULL WHERE id = ${id} AND compat_state IN ('none', 'error', 'disabled')`;77    return { compatState: "queued" };78  }],79  ["GET", "tracks/:id/lyrics", ({ params }) => getLyrics(uuid.parse(params.id))],80  ["GET", "tracks/:id", async ({ params, ctx }) => { const [t] = await cat.getTracks(ctx.userId, [uuid.parse(params.id)]); if (!t) throw new ApiError(404, "not_found"); return t; }],81];82
Files main
Menu

Theme