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>
This commit is contained in:
khannurien
2026-10-10 08:51:37 +00:00
parent 350e945eb1
commit 561cdf98b0
41 changed files with 1198 additions and 387 deletions

View File

@@ -37,26 +37,51 @@ export function isMemberVisibleTo(
}
/**
* The `dump_count` column of a query on `playlists p`: how many of the
* playlist's dumps the viewer may see, by {@link isMemberVisibleTo}'s rule.
* Its `?` takes the viewer's id, or `""` for a signed-out one, and comes
* before the query's other parameters, the column being in its select list.
* The fields of a playlist's dump that {@link dumpFiguresFor} needs: those
* that tell who may see it, and when it was added. The playlist service reads
* them for its broadcasts.
*/
export const VISIBLE_DUMP_COUNT = `(SELECT COUNT(*) FROM playlist_dumps pd
export interface DatedPlaylistMember extends PlaylistMember {
addedAt: Date;
}
/** A figure of the dumps of `playlists p` that the viewer `?1` may see. */
const visibleDumps = (figure: string) =>
`(SELECT ${figure} FROM playlist_dumps pd
INNER JOIN dumps d ON d.id = pd.dump_id
WHERE pd.playlist_id = p.id
AND (d.is_private = 0 OR (d.user_id = p.user_id AND p.user_id = ?))
) as dump_count`;
AND (d.is_private = 0 OR (d.user_id = p.user_id AND p.user_id = ?1))
)`;
/**
* Returns how many of `members` the viewer may see in `playlist`, the
* `dumpCount` the playlist has for them.
* The `dump_count` and `last_dump_at` columns of a query on `playlists p`:
* how many of the playlist's dumps the viewer may see, by
* {@link isMemberVisibleTo}'s rule, and when the latest of them was added,
* null without any. Both read the viewer's id, or `""` for a signed-out one,
* as `?1`: it is the query's first parameter, and each `?` after it takes the
* next.
*/
export function countVisibleTo(
members: PlaylistMember[],
export const VISIBLE_DUMP_FIGURES = `${visibleDumps("COUNT(*)")} as dump_count,
${visibleDumps("MAX(pd.added_at)")} as last_dump_at`;
/**
* Returns what `playlist` says of its dumps to the viewer, `members` being
* all of them: the `dumpCount` and `lastDumpAt` that
* {@link VISIBLE_DUMP_FIGURES} reads in a query. The WebSocket service puts
* them on the playlist each socket is sent.
*/
export function dumpFiguresFor(
members: DatedPlaylistMember[],
playlist: Pick<Playlist, "userId">,
viewerId: string | null | undefined,
): number {
return members.filter((m) => isMemberVisibleTo(m, playlist, viewerId))
.length;
): Required<Pick<Playlist, "dumpCount">> & Pick<Playlist, "lastDumpAt"> {
const visible = members.filter((m) =>
isMemberVisibleTo(m, playlist, viewerId)
);
return {
dumpCount: visible.length,
lastDumpAt: visible.length
? new Date(Math.max(...visible.map((m) => m.addedAt.getTime())))
: undefined,
};
}

View File

@@ -10,9 +10,9 @@ import type { Playlist } from "../../shared/playlist.ts";
/**
* Returned by the playlist and follow services' `SELECT`s on `playlists`,
* which join the owner's name as `owner_username`. A query may add a
* `dump_count` column, which {@link playlistRowToApi} carries over when
* present.
* which join the owner's name as `owner_username`. A query may add the
* `dump_count` and `last_dump_at` columns (`VISIBLE_DUMP_FIGURES`), which
* {@link playlistRowToApi} carries over when present.
*/
export interface PlaylistRow {
id: string;
@@ -62,6 +62,9 @@ export function playlistRowToApi(row: PlaylistRow): Playlist {
updatedAt: row.updated_at ? new Date(row.updated_at) : undefined,
imageMime: row.image_mime ?? undefined,
dumpCount: typeof row.dump_count === "number" ? row.dump_count : undefined,
lastDumpAt: typeof row.last_dump_at === "string"
? new Date(row.last_dump_at)
: undefined,
ownerUsername: row.owner_username,
};
}

View File

@@ -3,9 +3,11 @@
* playlist's id; its page reads it by its path, through
* `GET /api/users/:key/playlists/:slug`.
*
* - `GET /api/playlists?category=&page=&limit=` — public. Answers a page of
* every public playlist, newest first, or only those in the playlist
* category at `category`, which 404s when there is none.
* - `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
@@ -44,7 +46,11 @@ import {
isReorderPlaylistRequest,
isUpdatePlaylistRequest,
} from "../validators/playlist.ts";
import type { Playlist, PlaylistWithDumps } from "../../shared/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 {
@@ -87,6 +93,7 @@ router.get("/", async (ctx) => {
requestingUserId,
page,
limit,
parsePlaylistSort(params.get("sort")),
categoryId,
);
const responseBody: APIResponse<PaginatedData<Playlist>> = {

View File

@@ -19,9 +19,10 @@
* - `GET /api/users/:key/upvoted?page=&limit=&category=` — optional sign-in.
* Answers a page of the dumps they upvoted, private ones only to
* themselves, optionally in one category.
* - `GET /api/users/:key/playlists?page=&limit=&category=` — optional
* - `GET /api/users/:key/playlists?page=&limit=&category=&sort=` — optional
* sign-in. Answers a page of the playlists they made, the private ones only
* to themselves, optionally in one playlist category.
* to themselves, optionally in one playlist category, in the order `sort`
* names, as `GET /api/playlists` does.
* - `GET /api/users/:key/playlists/:slug` — optional sign-in. Answers their
* playlist whose slug is or was `slug`, with its current slug and the dumps
* the caller may see; a private one 404s but for its owner.
@@ -56,7 +57,11 @@ import {
type UserSuggestion,
} from "../../shared/user.ts";
import type { Dump } from "../../shared/dump.ts";
import type { Playlist, PlaylistWithDumps } from "../../shared/playlist.ts";
import {
parsePlaylistSort,
type Playlist,
type PlaylistWithDumps,
} from "../../shared/playlist.ts";
import {
fieldOf,
isRegisterUserRequest,
@@ -210,7 +215,14 @@ router.get("/:key/playlists", async (ctx) => {
const categoryId = resolveCategoryFilter("playlist", params);
const { items, hasMore } = categoryId === "missing"
? { items: [], hasMore: false }
: listPlaylistsByUser(user.id, requestingUserId, page, limit, categoryId);
: listPlaylistsByUser(
user.id,
requestingUserId,
page,
limit,
parsePlaylistSort(params.get("sort")),
categoryId,
);
const responseBody: APIResponse<PaginatedData<Playlist>> = {
success: true,
data: { items, hasMore },
@@ -224,7 +236,7 @@ router.get("/:key/playlists/:slug", async (ctx) => {
const responseBody: APIResponse<PlaylistWithDumps> = {
success: true,
data: getPlaylist(
getPlaylistByPath(user.id, ctx.params.slug),
getPlaylistByPath(user.id, ctx.params.slug, requestingUserId),
requestingUserId,
),
};

View File

@@ -23,7 +23,7 @@ import {
} from "../model/dump.ts";
import { isFollowRow } from "../model/follow.ts";
import { isPlaylistRow, playlistRowToApi } from "../model/playlist.ts";
import { VISIBLE_DUMP_COUNT } from "../lib/playlist-members.ts";
import { VISIBLE_DUMP_FIGURES } from "../lib/playlist-members.ts";
import { type Page, pageOf } from "../lib/pagination.ts";
import { attachCategoryIds, categoryJoin } from "./category-service.ts";
import { sendToUser } from "./ws-service.ts";
@@ -248,7 +248,7 @@ export function getFollowedPlaylistsByUser(
const rawRows = db.prepare(
`SELECT p.*, u.username as owner_username,
${VISIBLE_DUMP_COUNT}
${VISIBLE_DUMP_FIGURES}
FROM playlists p
LEFT JOIN users u ON u.id = p.user_id
INNER JOIN follows f ON f.followed_playlist_id = p.id

View File

@@ -12,6 +12,7 @@ import type {
CreatePlaylistRequest,
Playlist,
PlaylistMembership,
PlaylistSort,
PlaylistWithDumps,
UpdatePlaylistRequest,
} from "../../shared/playlist.ts";
@@ -42,25 +43,36 @@ import {
setCategories,
} from "./category-service.ts";
import {
type DatedPlaylistMember,
isMemberVisibleTo,
type PlaylistMember,
VISIBLE_DUMP_COUNT,
VISIBLE_DUMP_FIGURES,
} from "../lib/playlist-members.ts";
import { LIKE, likePattern } from "../lib/like.ts";
import { parseRows } from "../model/rows.ts";
/**
* The select list and `FROM` clause of a playlist query, adding the owner's
* name and the count of the dumps the viewer may see. Callers append the
* `WHERE`, and pass the viewer's id first, as {@link viewerParam} gives it.
* name, the count of the dumps the viewer may see and when the latest was
* added. Callers append the `WHERE`, and pass the viewer's id first, as
* {@link viewerParam} gives it.
*/
const PLAYLIST_SELECT = `p.*, u.username as owner_username,
${VISIBLE_DUMP_COUNT}
${VISIBLE_DUMP_FIGURES}
FROM playlists p JOIN users u ON u.id = p.user_id`;
/**
* Returns what {@link VISIBLE_DUMP_COUNT}'s parameter takes for `viewerId`: a
* signed-out viewer matches no user.
* The `ORDER BY` of each of the `PLAYLIST_SORTS`, on a {@link PLAYLIST_SELECT}:
* `comparePlaylists` (`shared/playlist.ts`) in SQL, which a test holds to it.
*/
const PLAYLIST_ORDER: Record<PlaylistSort, string> = {
updated: "COALESCE(last_dump_at, p.created_at) DESC, p.created_at DESC",
new: "p.created_at DESC",
dumps: "dump_count DESC, p.created_at DESC",
};
/**
* Returns what {@link VISIBLE_DUMP_FIGURES}'s parameter takes for `viewerId`:
* a signed-out viewer matches no user.
*/
function viewerParam(viewerId: string | null | undefined): string {
return viewerId ?? "";
@@ -79,7 +91,8 @@ function playlistsOf(rows: unknown[]): Playlist[] {
/**
* Returns playlist `playlistId`, private or not. A caller that shows it to
* someone must check `isPublic` first, as the OG middleware does. Its
* `dumpCount` is `viewerId`'s, or a signed-out viewer's without one.
* `dumpCount` and `lastDumpAt` are `viewerId`'s, or a signed-out viewer's
* without one.
*
* @throws {APIException} 404 when there is no such playlist.
*/
@@ -99,13 +112,18 @@ export function getPlaylistById(
/**
* Returns the playlist of `userId`'s whose slug is or was `slug`, private or
* not, or throws a 404, as {@link getPlaylistById} does. Reached by a former
* slug, it comes with its current one.
* not, or throws a 404, as {@link getPlaylistById} does, counting its dumps
* for `viewerId` likewise. Reached by a former slug, it comes with its current
* one.
*/
export function getPlaylistByPath(userId: string, slug: string): Playlist {
export function getPlaylistByPath(
userId: string,
slug: string,
viewerId: string | null = null,
): Playlist {
const playlistId = resolveSlug("playlist", userId, slug);
if (!playlistId) throw new APIException(404, "Playlist not found");
return getPlaylistById(playlistId);
return getPlaylistById(playlistId, viewerId);
}
/**
@@ -157,8 +175,8 @@ export function createPlaylist(
* Returns a playlist with the dumps `requestingUserId` may see in it, in
* order, for `GET /api/playlists/:playlistId`, and for
* `GET /api/users/:key/playlists/:slug` once it has found the playlist by its
* path. A null `requestingUserId` is a signed-out viewer. Its `dumpCount` is
* the number of those dumps.
* path, for the same viewer. A null `requestingUserId` is a signed-out viewer.
* Its `dumpCount` is the number of those dumps.
*
* @throws {APIException} 404 when there is no such playlist, or it is private
* and not theirs.
@@ -168,7 +186,7 @@ export function getPlaylist(
requestingUserId: string | null,
): PlaylistWithDumps {
const playlist = typeof playlistId === "string"
? getPlaylistById(playlistId)
? getPlaylistById(playlistId, requestingUserId)
: playlistId;
if (!playlist.isPublic && requestingUserId !== playlist.userId) {
@@ -228,15 +246,17 @@ export function searchPlaylists(
}
/**
* Returns a page of every public playlist, newest first, for
* Returns a page of every public playlist, in the order `sort` names, for
* `GET /api/playlists`, optionally only those in the playlist category
* `categoryId`. The client's `/playlists` page lists them. Their dumps are
* counted for `requestingUserId`, null being a signed-out viewer.
* counted, and so ordered, for `requestingUserId`, null being a signed-out
* viewer.
*/
export function listPublicPlaylists(
requestingUserId: string | null,
page: number,
limit: number,
sort: PlaylistSort,
categoryId?: string,
): Page<Playlist> {
const offset = (page - 1) * limit;
@@ -244,7 +264,7 @@ export function listPublicPlaylists(
const rows = db.prepare(
`SELECT ${PLAYLIST_SELECT} ${catJoin}
WHERE p.is_public = 1
ORDER BY p.created_at DESC LIMIT ? OFFSET ?;`,
ORDER BY ${PLAYLIST_ORDER[sort]} LIMIT ? OFFSET ?;`,
).all(viewerParam(requestingUserId), ...catParams, limit + 1, offset);
return pageOf(playlistsOf(rows), limit);
}
@@ -259,13 +279,13 @@ export function listNewPublicPlaylists(from: Date, to: Date): Playlist[] {
const rows = db.prepare(
`SELECT ${PLAYLIST_SELECT}
WHERE p.is_public = 1 AND p.created_at >= ? AND p.created_at < ?
ORDER BY dump_count DESC, p.created_at DESC;`,
ORDER BY ${PLAYLIST_ORDER.dumps};`,
).all(viewerParam(null), from.toISOString(), to.toISOString());
return playlistsOf(rows);
}
/**
* Returns a page of `userId`'s playlists, newest first, for
* Returns a page of `userId`'s playlists, in the order `sort` names, for
* `GET /api/users/:key/playlists`, optionally only those in the playlist
* category `categoryId`. The private ones are listed only when
* `requestingUserId` is `userId`.
@@ -275,6 +295,7 @@ export function listPlaylistsByUser(
requestingUserId: string | null,
page: number,
limit: number,
sort: PlaylistSort,
categoryId?: string,
): Page<Playlist> {
const isOwner = requestingUserId === userId;
@@ -285,7 +306,7 @@ export function listPlaylistsByUser(
const rows = db.prepare(
`SELECT ${PLAYLIST_SELECT} ${catJoin}
WHERE p.user_id = ?${privacyFilter}
ORDER BY p.created_at DESC LIMIT ? OFFSET ?;`,
ORDER BY ${PLAYLIST_ORDER[sort]} LIMIT ? OFFSET ?;`,
).all(
viewerParam(requestingUserId),
...catParams,
@@ -620,7 +641,7 @@ export function getPlaylistMembershipsForDump(
): PlaylistMembership[] {
const rows = db.prepare(
`SELECT p.*, u.username as owner_username,
${VISIBLE_DUMP_COUNT},
${VISIBLE_DUMP_FIGURES},
EXISTS (SELECT 1 FROM playlist_dumps pd
WHERE pd.playlist_id = p.id AND pd.dump_id = ?) as has_dump
FROM playlists p JOIN users u ON u.id = p.user_id
@@ -690,18 +711,19 @@ export function getPlaylistImageInfo(
* Returns a playlist's dumps in order, all of them, for the callers to filter
* per viewer.
*/
function getCurrentMembers(playlistId: string): PlaylistMember[] {
function getCurrentMembers(playlistId: string): DatedPlaylistMember[] {
const rows = db.prepare(
`SELECT pd.dump_id, d.is_private, d.user_id
`SELECT pd.dump_id, pd.added_at, d.is_private, d.user_id
FROM playlist_dumps pd INNER JOIN dumps d ON d.id = pd.dump_id
WHERE pd.playlist_id = ? ORDER BY pd.position ASC;`,
).all(playlistId) as Array<
{ dump_id: string; is_private: number; user_id: string }
{ dump_id: string; added_at: string; is_private: number; user_id: string }
>;
return rows.map((r) => ({
id: r.dump_id,
isPrivate: Boolean(r.is_private),
userId: r.user_id,
addedAt: new Date(r.added_at),
}));
}

View File

@@ -18,9 +18,9 @@ import type { OnlineUser, ServerToClientMessage } from "../../shared/ws.ts";
import type { Playlist } from "../../shared/playlist.ts";
import type { PublicUser, Role } from "../../shared/user.ts";
import {
countVisibleTo,
type DatedPlaylistMember,
dumpFiguresFor,
isMemberVisibleTo,
type PlaylistMember,
} from "../lib/playlist-members.ts";
import type { Job } from "../lib/scheduler.ts";
@@ -298,21 +298,17 @@ export function broadcastCommentLikeUpdate(
* {@link broadcastChange} says, for the playlist service after every write to
* its details. A playlist turned private thus leaves the others' views without
* their learning what it became. `members` are the dumps of `after`: each
* socket gets the playlist with the count of those its user may see, the
* owner's private dumps being theirs alone to count.
* socket gets the playlist with the count of those its user may see and the
* date of the latest, the owner's private dumps being theirs alone to count.
*/
export function broadcastPlaylistChange(
before: Playlist | null,
after: Playlist | null,
members: PlaylistMember[],
members: DatedPlaylistMember[],
): void {
const counted = (playlist: Playlist, toOwner: boolean): Playlist => ({
...playlist,
dumpCount: countVisibleTo(
members,
playlist,
toOwner ? playlist.userId : null,
),
...dumpFiguresFor(members, playlist, toOwner ? playlist.userId : null),
});
broadcastChange(before, after, (playlist) => !playlist.isPublic, {
created: (playlist, toOwner) => ({
@@ -339,7 +335,7 @@ export function broadcastPlaylistChange(
*/
export function broadcastPlaylistDumpsUpdated(
playlist: Pick<Playlist, "id" | "isPublic" | "userId">,
members: PlaylistMember[],
members: DatedPlaylistMember[],
): void {
for (const client of clients) {
if (!playlist.isPublic && client.userId !== playlist.userId) continue;
@@ -349,6 +345,7 @@ export function broadcastPlaylistDumpsUpdated(
dumpIds: members
.filter((m) => isMemberVisibleTo(m, playlist, client.userId))
.map((m) => m.id),
lastDumpAt: dumpFiguresFor(members, playlist, client.userId).lastDumpAt,
});
}
}

View File

@@ -16,10 +16,12 @@ import {
TEST_DIR,
} from "../helpers.ts";
import type { PaginatedData } from "../../../shared/api.ts";
import type {
Playlist,
PlaylistMembership,
PlaylistWithDumps,
import {
comparePlaylists,
type Playlist,
PLAYLIST_SORTS,
type PlaylistMembership,
type PlaylistWithDumps,
} from "../../../shared/playlist.ts";
import { assert, assertEquals, assertMatch } from "@std/assert";
@@ -665,7 +667,7 @@ test("playlist categories: filed on creation, replaced on update, dump categorie
assertEquals(cleared.data.categoryIds, []);
});
test("GET /api/playlists: every public playlist, newest first, by category", async () => {
test("GET /api/playlists: every public playlist, by category", async () => {
const owner = await createUser();
const other = await createUser();
const mixes = insertCategory({ slug: "mixes", kind: "playlist" });
@@ -729,3 +731,110 @@ test("GET /api/users/:key/playlists?category=: their playlists in one category",
[],
);
});
test("?sort=: by the last dump added, by creation or by dumps, as the viewer sees them", async () => {
const owner = await createUser();
const made = (title: string, createdAt: string) => {
const { id } = insertPlaylist({ userId: owner.id, title });
db.prepare(`UPDATE playlists SET created_at = ? WHERE id = ?;`)
.run(createdAt, id);
return id;
};
const add = (playlistId: string, addedAt: string, isPrivate = false) =>
db.prepare(
`INSERT INTO playlist_dumps (playlist_id, dump_id, position, added_at)
VALUES (?, ?, 0, ?);`,
).run(playlistId, insertDump({ userId: owner.id, isPrivate }).id, addedAt);
const a = made("A", "2026-01-01T00:00:00.000Z");
const b = made("B", "2026-02-01T00:00:00.000Z");
const c = made("C", "2026-03-01T00:00:00.000Z");
add(a, "2026-04-01T00:00:00.000Z");
add(b, "2026-02-10T00:00:00.000Z");
add(b, "2026-02-11T00:00:00.000Z");
// Only the owner sees it: to anyone else, C is empty and as it was made.
add(c, "2026-05-01T00:00:00.000Z", true);
type Auth = typeof owner.auth;
const list = async (query: string, auth?: Auth) =>
(await get<PaginatedData<Playlist>>(query, { auth })).data.items;
const titles = async (query: string, auth?: Auth) =>
(await list(query, auth)).map((p) => p.title);
for (
const url of ["/api/playlists", `/api/users/${owner.id}/playlists`]
) {
assertEquals(await titles(`${url}?sort=updated`), ["A", "C", "B"], url);
assertEquals(await titles(`${url}?sort=new`), ["C", "B", "A"], url);
assertEquals(await titles(`${url}?sort=dumps`), ["B", "A", "C"], url);
assertEquals(
await titles(`${url}?sort=updated`, owner.auth),
["C", "A", "B"],
url,
);
// A and C hold one dump each to their owner: the newer goes first.
assertEquals(
await titles(`${url}?sort=dumps`, owner.auth),
["B", "C", "A"],
url,
);
// The first order is the default, which an unknown one falls back to.
assertEquals(await titles(url), ["A", "C", "B"], url);
assertEquals(await titles(`${url}?sort=nope`), ["A", "C", "B"], url);
assertEquals(await titles(`${url}?sort=new&limit=1&page=2`), ["B"], url);
}
const dates = (await list("/api/playlists?sort=new")).map((p) =>
p.lastDumpAt
);
assertEquals(dates, [
undefined,
"2026-02-11T00:00:00.000Z",
"2026-04-01T00:00:00.000Z",
] as unknown[]);
assertEquals(
(await get<PlaylistWithDumps>(`/api/playlists/${c}`, { auth: owner.auth }))
.data.lastDumpAt as unknown,
"2026-05-01T00:00:00.000Z",
);
assertEquals(
(await get<PlaylistWithDumps>(`/api/playlists/${c}`)).data.lastDumpAt,
undefined,
);
});
test("comparePlaylists orders playlists as the API's ?sort= pages them", async () => {
const owner = await createUser();
// Ties of every kind: dates and counts shared by several playlists.
for (let i = 0; i < 8; i++) {
const { id } = insertPlaylist({ userId: owner.id, title: `P${i}` });
db.prepare(`UPDATE playlists SET created_at = ? WHERE id = ?;`)
.run(`2026-01-0${1 + i}T00:00:00.000Z`, id);
for (let n = 0; n < i % 3; n++) {
db.prepare(
`INSERT INTO playlist_dumps (playlist_id, dump_id, position, added_at)
VALUES (?, ?, ?, ?);`,
).run(
id,
insertDump({ userId: owner.id }).id,
n,
`2026-02-0${1 + ((i * 5 + n) % 9)}T00:00:00.000Z`,
);
}
}
for (const sort of PLAYLIST_SORTS) {
const { items } = (await get<PaginatedData<Playlist>>(
`/api/playlists?sort=${sort}`,
)).data;
// The dates come as strings over the wire.
const playlists = items.map((p) => ({
...p,
createdAt: new Date(p.createdAt),
lastDumpAt: p.lastDumpAt && new Date(p.lastDumpAt),
}));
assertEquals(
playlists.toSorted(comparePlaylists(sort)).map((p) => p.title),
items.map((p) => p.title),
sort,
);
}
});

View File

@@ -744,6 +744,47 @@ wsTest("a password change closes the user's sockets", async (connect) => {
assertFalse(res.data.token === user.token);
});
wsTest(
"playlist_dumps_updated dates the latest dump each viewer can see",
async (connect) => {
const owner = await createUser();
const pl = insertPlaylist({ userId: owner.id });
const o = await connect(owner);
const anon = await connect();
const add = async (isPrivate: boolean) => {
const dump = insertDump({ userId: owner.id, isPrivate });
await post(`/api/playlists/${pl.id}/dumps/${dump.id}`, {
auth: owner.auth,
});
return [
(await o.next("playlist_dumps_updated")).lastDumpAt,
(await anon.next("playlist_dumps_updated")).lastDumpAt,
];
};
const [first, firstToAnon] = await add(false);
assert(first);
assertEquals(firstToAnon, first);
// The owner's private dump moves the date for them alone.
const [second, secondToAnon] = await add(true);
assert(second && second >= first);
assertEquals(secondToAnon, first);
await put(`/api/playlists/${pl.id}`, {
auth: owner.auth,
json: { title: "Renamed" },
});
assertEquals(
(await o.next("playlist_updated")).playlist.lastDumpAt,
second,
);
assertEquals(
(await anon.next("playlist_updated")).playlist.lastDumpAt,
first,
);
},
);
wsTest(
"playlist_dumps_updated lists only what each viewer can see",
async (connect) => {