Files
ersatztv/web/src/api/collections.ts
T
timothyandClaude Opus 4.8 ef2bd65c27
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 10s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 10s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 1m12s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 3m4s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m17s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 10m36s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
feat(api): #286 — mount the whole /api surface at /api/v1
Version every /api route to /api/v1 (251 controller routes + ~24 Location
headers + the scanner callback URL + the Startup request-log literal),
uniform across the machine API, auth, scanner and scripted-build surfaces.

Add ApiVersionRewriteMiddleware: a legacy unversioned /api/* request is
rewritten (NOT redirected) to /api/v1/* in-pipeline — method, body, auth
headers and query survive — carrying RFC 8594 Deprecation/Sunset headers,
so curl / the future MCP server / bookmarks keep working. An already-
versioned path passes through; a future /api/v2 is never forced to v1.

Standardize the route convention (leading-slash absolute route per method,
no class-[Route] — except the two Scanner/Scripted controllers whose ~all
actions share a parametrized {id} prefix), enforced by ApiRouteVersioningTests
(^/api/v\d+/ over the whole Controllers.Api surface; browser-nav
/auth/oidc/login is out of scope).

Regenerate v1.json (160 paths, all /api/v1)/endpoint-index/v1.d.ts; sweep 945
SPA request literals + the test mocks (regex + positional URL parsers). /api/v1
is additive-only after freeze; the legacy-rewrite shim sunsets in ~2 releases
(owner decision) with removal tracked as a Phase-3 follow-up.

Docs: decisions.md 2026-07-13, api-conventions §1/§9, rest-api/spa-conventions/
blazor-route-parity/e2e-local/domain-model.

fixes #286
refs #197

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 00:30:20 +02:00

196 lines
7.5 KiB
TypeScript

import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
import type { LibraryBrowseItem, PagedLibraryBrowseItems } from './libraryBrowse';
export type MediaCollection = components['schemas']['MediaCollectionResponseModel'];
export type SmartCollection = components['schemas']['SmartCollectionResponseModel'];
export type CreateCollectionRequest = components['schemas']['CreateCollectionRequest'];
export type UpdateCollectionRequest = components['schemas']['UpdateCollectionRequest'];
export type AddItemsToCollectionRequest = components['schemas']['AddItemsToCollectionRequest'];
export type UpdateCollectionCustomOrderRequest = components['schemas']['UpdateCollectionCustomOrderRequest'];
export type CreateSmartCollectionRequest = components['schemas']['CreateSmartCollectionRequest'];
export type UpdateSmartCollectionRequest = components['schemas']['UpdateSmartCollectionRequest'];
/* ---------- manual collections ---------- */
export function getCollections(): Promise<MediaCollection[]> {
return request<MediaCollection[]>('/api/v1/collections');
}
export function getCollection(id: number): Promise<MediaCollection> {
return request<MediaCollection>(`/api/v1/collections/${id}`);
}
export function createCollection(body: CreateCollectionRequest): Promise<MediaCollection> {
return request<MediaCollection>('/api/v1/collections', { body, method: 'POST' });
}
export function updateCollection(id: number, body: UpdateCollectionRequest): Promise<MediaCollection> {
return request<MediaCollection>(`/api/v1/collections/${id}`, { body, method: 'PUT' });
}
export function deleteCollection(id: number): Promise<void> {
return request<void>(`/api/v1/collections/${id}`, { method: 'DELETE' });
}
export function addItemsToCollection(id: number, body: AddItemsToCollectionRequest): Promise<void> {
return request<void>(`/api/v1/collections/${id}/items`, { body, method: 'POST' });
}
export function removeItemFromCollection(id: number, mediaItemId: number): Promise<void> {
return request<void>(`/api/v1/collections/${id}/items/${mediaItemId}`, { method: 'DELETE' });
}
// Lists a manual collection's full contents (all media kinds), paged. Backed by
// GET /api/v1/collections/{id}/items (#155), which reuses the library-browse item shape. When the
// collection's useCustomPlaybackOrder is true, items come back ordered by CustomIndex (nulls
// last, then title); otherwise title order.
export function getCollectionItems(
id: number,
pageNum = 0,
pageSize = 100
): Promise<PagedLibraryBrowseItems> {
const params = new URLSearchParams({
pageNum: String(pageNum),
pageSize: String(pageSize)
});
return request<PagedLibraryBrowseItems>(`/api/v1/collections/${id}/items?${params.toString()}`);
}
/** Load a page of collection items together with the collection's concurrency ETag (issue #253). */
export function getCollectionItemsWithMeta(
id: number,
pageNum = 0,
pageSize = 100
): Promise<ResponseWithMeta<PagedLibraryBrowseItems>> {
const params = new URLSearchParams({
pageNum: String(pageNum),
pageSize: String(pageSize)
});
return requestWithMeta<PagedLibraryBrowseItems>(`/api/v1/collections/${id}/items?${params.toString()}`);
}
// Replaces a manual collection's custom order wholesale: the CustomIndex of each media item is
// derived from its position in `mediaItemIds`, so a partial array silently drops the items left
// out of it (#211). Callers must submit the full ordered id list.
//
// Pass the last-seen ETag as `If-Match` to reject a stale overwrite with 412; the resolved
// value carries the new ETag for a subsequent save (issue #253).
export function updateCollectionCustomOrder(
id: number,
mediaItemIds: number[],
ifMatch?: string | null
): Promise<ResponseWithMeta<void>> {
const body: UpdateCollectionCustomOrderRequest = { mediaItemIds };
return requestWithMeta<void>(`/api/v1/collections/${id}/custom-order`, {
body,
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
/* ---------- smart collections ---------- */
export function getSmartCollections(): Promise<SmartCollection[]> {
return request<SmartCollection[]>('/api/v1/smart-collections');
}
export function getSmartCollection(id: number): Promise<SmartCollection> {
return request<SmartCollection>(`/api/v1/smart-collections/${id}`);
}
export function createSmartCollection(body: CreateSmartCollectionRequest): Promise<SmartCollection> {
return request<SmartCollection>('/api/v1/smart-collections', { body, method: 'POST' });
}
export function updateSmartCollection(id: number, body: UpdateSmartCollectionRequest): Promise<SmartCollection> {
return request<SmartCollection>(`/api/v1/smart-collections/${id}`, { body, method: 'PUT' });
}
export function deleteSmartCollection(id: number): Promise<void> {
return request<void>(`/api/v1/smart-collections/${id}`, { method: 'DELETE' });
}
/* ---------- add-items bucket mapping ---------- */
// The add-items request buckets media-item ids by kind. All 10 addable kinds (Movie /
// TelevisionShow / TelevisionSeason / Artist / Episode / MusicVideo / Song / OtherVideo /
// Image / RemoteStream) are reachable from the picker via `toAddItemsRequest` below — the
// default "All" fan-out only searches Movie/TelevisionShow/Artist (see CollectionsScreen's
// DEFAULT_SEARCH_KINDS), but every kind can be found by picking its specific filter.
export function emptyAddItemsRequest(): AddItemsToCollectionRequest {
return {
artistIds: [],
episodeIds: [],
imageIds: [],
movieIds: [],
musicVideoIds: [],
otherVideoIds: [],
remoteStreamIds: [],
seasonIds: [],
showIds: [],
songIds: []
};
}
// Buckets a set of browse results into an AddItemsToCollectionRequest. Each addable kind
// carries its media-item id in `id` (which equals `mediaItemId` for these types, since they
// are all MediaItem subclasses). Ids must go into their type-specific bucket, since the
// server validates each bucket against that entity type (a Show id in movieIds fails
// validation). Any other kind (collections, smart/multi/rerun collections, playlists) is
// not an addable media item and is skipped.
export function toAddItemsRequest(items: LibraryBrowseItem[]): AddItemsToCollectionRequest {
const requestBody = emptyAddItemsRequest();
for (const item of items) {
switch (item.mediaType) {
case 'Movie':
requestBody.movieIds?.push(item.id);
break;
case 'TelevisionShow':
requestBody.showIds?.push(item.id);
break;
case 'TelevisionSeason':
requestBody.seasonIds?.push(item.id);
break;
case 'Artist':
requestBody.artistIds?.push(item.id);
break;
case 'Episode':
requestBody.episodeIds?.push(item.id);
break;
case 'MusicVideo':
requestBody.musicVideoIds?.push(item.id);
break;
case 'Song':
requestBody.songIds?.push(item.id);
break;
case 'OtherVideo':
requestBody.otherVideoIds?.push(item.id);
break;
case 'Image':
requestBody.imageIds?.push(item.id);
break;
case 'RemoteStream':
requestBody.remoteStreamIds?.push(item.id);
break;
default:
break;
}
}
return requestBody;
}
export function messageFromCollectionError(error: unknown, fallback = 'Unable to load collections'): string {
if (error instanceof ApiError) {
return error.detail ?? error.message;
}
if (error instanceof Error) {
return error.message;
}
return fallback;
}