Files
gerbeur/api/routes/playlists.ts
khannurien 561cdf98b0 v4: playlists sort by their last dump, their creation or their size, and /playlists is a grid of covers — every list of playlists came newest first, so one fed every week sank under those made since and left empty. GET /api/playlists and /api/users/:key/playlists take ?sort=updated|new|dumps (PLAYLIST_SORTS, shared/playlist.ts), updated being the default: the last to take a dump first, or its creation while it holds none; a new title, cover or description doesn't bring it back up. A playlist carries that date as lastDumpAt, read with its dumpCount by isMemberVisibleTo's rule (VISIBLE_DUMP_FIGURES, the viewer's id as ?1), so the owner's private dumps date and count their playlists for them alone, in the lists and over the socket: playlist_created, playlist_updated and playlist_dumps_updated carry each socket's own. The /playlists page and a profile's playlists tab show the orders as tabs beside the category menu and keep the one picked in ?sort=, the default being the bare path; a tab takes the current history entry's place, and picking a category keeps the order. Live, usePlaylistListSync takes the list's order: a new playlist goes where it puts it, one that rises moves up to its place, as in the updated order when it takes a dump, and one that falls stays until the list is fetched again, its place being perhaps on a page not loaded. The lists in an order of their own, the followed playlists and the search's, pass none, and take no new playlist as before (noNewEntries goes). comparePlaylists is the order on the client, which a test holds to the API's.
/playlists lays its cards out as tiles, the cover across the top, four to a row and two on a phone, on the wide column: the same PlaylistCard, laid out by its list's class (.playlist-grid), so each theme's card skin carries over. It drops the "public" badge there, every playlist listed being public. On every card, a playlist without a cover shows a tile of its own colour with its initial (ThumbnailPlaceholder) in place of the 📋, and the date is "updated …" of its last dump, or "created …".

A middle, ctrl, cmd or shift click anywhere on a playlist card opens it in a new tab — only its title was a link, the rest navigating by a click handler. useCardLink (hooks/shared) is useDumpCardLink's handlers for any card, which the dump cards now get through it.

A profile tab's query stays with the tab — going from the playlists to the dumps kept the whole query, so a playlist category, and now ?sort=, landed on the dumps' URL. Only the dump lists pass their category to each other; any other change of tab drops the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:51:37 +00:00

243 lines
8.1 KiB
TypeScript

/**
* Serves playlists, their dumps and their covers. `:playlistId` is a
* playlist's id; its page reads it by its path, through
* `GET /api/users/:key/playlists/:slug`.
*
* - `GET /api/playlists?category=&sort=&page=&limit=` — public. Answers a
* page of every public playlist, in the order `sort` names
* (`PLAYLIST_SORTS`, the last to take a dump first by default), or only
* those in the playlist category at `category`, which 404s when there is
* none.
* - `POST /api/playlists` — signed in. Creates a playlist, filed under the
* playlist categories it names.
* - `GET /api/playlists/:playlistId` — optional sign-in. Answers a playlist
* with the dumps the caller may see in it. A private one 404s but for its
* owner.
* - `PUT /api/playlists/:playlistId` — signed in, as its owner or with
* `playlist:moderate`. Updates its title, slug, description, visibility and
* categories.
* A new slug keeps the old one as an alias, 3 times a day at most but for
* those with `playlist:moderate`.
* - `DELETE /api/playlists/:playlistId` — signed in, as its owner or with
* `playlist:moderate`. Deletes it.
* - `POST /api/playlists/:playlistId/dumps/:dumpId` — signed in, as its owner
* or with `playlist:moderate`. Adds a dump at the top.
* - `DELETE /api/playlists/:playlistId/dumps/:dumpId` — signed in, as its owner
* or with `playlist:moderate`. Removes a dump.
* - `PUT /api/playlists/:playlistId/cover` — signed in, as its owner or with
* `playlist:moderate`. Replaces its cover (multipart `file`, at most 5 MB).
* - `GET /api/playlists/:playlistId/cover?token=` — public, but a private
* playlist's cover needs its owner's media `token`. Serves its cover, or 404s
* without one.
* - `PUT /api/playlists/:playlistId/order` — signed in, as its owner or with
* `playlist:moderate`. Reorders the dumps the caller can see in it.
*
* Which of the caller's playlists hold a dump is `GET /api/me/playlists`'s.
*
* @module
*/
import { Router } from "@oak/oak";
import { authenticateMedia, parseOptionalAuth } from "../lib/auth.ts";
import { type APIResponse, type PaginatedData } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import {
isCreatePlaylistRequest,
isReorderPlaylistRequest,
isUpdatePlaylistRequest,
} from "../validators/playlist.ts";
import {
parsePlaylistSort,
type Playlist,
type PlaylistWithDumps,
} from "../../shared/playlist.ts";
import { authMiddleware, type AuthState } from "../middleware/auth.ts";
import { can } from "../lib/permissions.ts";
import {
addDumpToPlaylist,
createPlaylist,
deletePlaylist,
getEditablePlaylist,
getPlaylist,
getPlaylistImageInfo,
listPublicPlaylists,
removeDumpFromPlaylist,
reorderPlaylist,
setPlaylistImage,
updatePlaylist,
} from "../services/playlist-service.ts";
import {
replaceUploadedFile,
serveUploadedFile,
validateImageUpload,
} from "../lib/upload.ts";
import { PLAYLIST_IMAGES_DIR } from "../config.ts";
import { parsePagination } from "../lib/pagination.ts";
import { getCategoryBySlug } from "../services/category-service.ts";
/**
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
* An `APIException` thrown by a handler becomes the JSON error response there.
*/
const router: Router<AuthState> = new Router<AuthState>({
prefix: "/api/playlists",
});
router.get("/", async (ctx) => {
const requestingUserId = await parseOptionalAuth(ctx);
const params = ctx.request.url.searchParams;
const { page, limit } = parsePagination(params);
const slug = params.get("category");
const categoryId = slug ? getCategoryBySlug("playlist", slug).id : undefined;
const { items, hasMore } = listPublicPlaylists(
requestingUserId,
page,
limit,
parsePlaylistSort(params.get("sort")),
categoryId,
);
const responseBody: APIResponse<PaginatedData<Playlist>> = {
success: true,
data: { items, hasMore },
};
ctx.response.body = responseBody;
});
router.post("/", authMiddleware, async (ctx) => {
const body: unknown = await ctx.request.body.json();
if (!isCreatePlaylistRequest(body)) {
throw new APIException(400, "Invalid request");
}
const responseBody: APIResponse<Playlist> = {
success: true,
data: createPlaylist(body, ctx.state.user.userId),
};
ctx.response.status = 201;
ctx.response.body = responseBody;
});
router.get("/:playlistId", async (ctx) => {
const requestingUserId = await parseOptionalAuth(ctx);
const responseBody: APIResponse<PlaylistWithDumps> = {
success: true,
data: getPlaylist(ctx.params.playlistId, requestingUserId),
};
ctx.response.body = responseBody;
});
router.put("/:playlistId", authMiddleware, async (ctx) => {
const body: unknown = await ctx.request.body.json();
if (!isUpdatePlaylistRequest(body)) {
throw new APIException(400, "Invalid request");
}
const playlist = updatePlaylist(
ctx.params.playlistId,
body,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
const responseBody: APIResponse<Playlist> = { success: true, data: playlist };
ctx.response.body = responseBody;
});
router.delete("/:playlistId", authMiddleware, (ctx) => {
deletePlaylist(
ctx.params.playlistId,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
ctx.response.status = 204;
});
router.post("/:playlistId/dumps/:dumpId", authMiddleware, (ctx) => {
addDumpToPlaylist(
ctx.params.playlistId,
ctx.params.dumpId,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
ctx.response.status = 204;
});
router.delete("/:playlistId/dumps/:dumpId", authMiddleware, (ctx) => {
removeDumpFromPlaylist(
ctx.params.playlistId,
ctx.params.dumpId,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
ctx.response.status = 204;
});
router.put("/:playlistId/cover", authMiddleware, async (ctx) => {
const contentType = ctx.request.headers.get("content-type") ?? "";
if (!contentType.includes("multipart/form-data")) {
throw new APIException(400, "Expected multipart/form-data");
}
const body = await ctx.request.body.formData();
const file = body.get("file");
if (!(file instanceof File)) {
throw new APIException(400, "Missing file field");
}
const data = new Uint8Array(await file.arrayBuffer());
const mime = validateImageUpload(data);
// Written before setPlaylistImage announces it, or clients would fetch the
// new `?v=` URL too early and cache the old cover under it.
const { id } = getEditablePlaylist(
ctx.params.playlistId,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
await replaceUploadedFile(`${PLAYLIST_IMAGES_DIR}/${id}`, data);
const playlist = setPlaylistImage(
id,
mime,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
const responseBody: APIResponse<Playlist> = { success: true, data: playlist };
ctx.response.body = responseBody;
});
router.get("/:playlistId/cover", async (ctx) => {
// An <img> can't send an Authorization header, so a private playlist's owner
// is known by the media token in the query string, as for dump files.
const token = ctx.request.url.searchParams.get("token");
const viewerId = token ? await authenticateMedia(token) : null;
const info = getPlaylistImageInfo(ctx.params.playlistId, viewerId);
if (!info) {
ctx.response.status = 404;
return;
}
// The URL may carry a media token, which a Referer would leak.
ctx.response.headers.set("Referrer-Policy", "no-referrer");
await serveUploadedFile(
ctx,
`${PLAYLIST_IMAGES_DIR}/${info.id}`,
info.imageMime,
3600,
!info.isPublic,
);
});
router.put("/:playlistId/order", authMiddleware, async (ctx) => {
const body: unknown = await ctx.request.body.json();
if (!isReorderPlaylistRequest(body)) {
throw new APIException(400, "Invalid request");
}
reorderPlaylist(
ctx.params.playlistId,
body.dumpIds,
ctx.state.user.userId,
can(ctx.state.user, "playlist:moderate"),
);
const responseBody: APIResponse<null> = { success: true, data: null };
ctx.response.body = responseBody;
});
export default router;