Files
minstrel/web/src/lib/api/admin.ts
T

1060 lines
32 KiB
TypeScript

import { createInfiniteQuery, createQuery } from '@tanstack/svelte-query';
import { api } from './client';
import { qk } from './queries';
import type {
ActionResult,
AdminMissingResponse,
AdminSuspectResponse,
SuspectVerdict,
AdminDuplicatesResponse,
DuplicatesView,
MergeDuplicateResult,
WrongSlotRemoval,
ResolvedDuplicatesResponse,
AdminPlaybackError,
AdminQuarantineRow,
AdminStatus,
AdminSummary,
QuarantineActionRow,
PlaybackErrorResolution
} from './types';
// Admin summary ---------------------------------------------------
export async function getAdminSummary(): Promise<AdminSummary> {
return api.get<AdminSummary>('/api/admin/summary');
}
// The admin rail's counts and the Overview's verdict. Refetched on every
// admin navigation by the layout and every 30s while an admin page is open,
// so a queue someone just cleared doesn't keep its count for long.
export function createAdminSummaryQuery() {
return createQuery({
queryKey: qk.adminSummary(),
queryFn: getAdminSummary,
refetchInterval: 30_000
});
}
// Admin status: who is listening, the library and disk,
// and the server, for the Overview below its verdict. Polled while open.
export async function getAdminStatus(): Promise<AdminStatus> {
return api.get<AdminStatus>('/api/admin/status');
}
export function createAdminStatusQuery() {
return createQuery({
queryKey: qk.adminStatus(),
queryFn: getAdminStatus,
refetchInterval: 15_000
});
}
// Admin quarantine --------------------------------------------------------
export async function listAdminQuarantine(): Promise<AdminQuarantineRow[]> {
return api.get<AdminQuarantineRow[]>('/api/admin/quarantine');
}
export async function resolveQuarantine(trackID: string): Promise<ActionResult> {
return api.post<ActionResult>(`/api/admin/quarantine/${trackID}/resolve`, {});
}
// Removes the reported file and keeps the track, which waits in Needs a file
// for a good copy. Its reports and playback errors are settled with it.
export async function removeQuarantineFile(trackID: string): Promise<ActionResult> {
return api.post<ActionResult>(`/api/admin/quarantine/${trackID}/remove-file`, {});
}
// Removes the track from the library with its file, history and all.
export async function deleteQuarantineFile(trackID: string): Promise<ActionResult> {
return api.post<ActionResult>(`/api/admin/quarantine/${trackID}/delete-file`, {});
}
export async function listQuarantineActions(
limit: number = 50
): Promise<QuarantineActionRow[]> {
return api.get<QuarantineActionRow[]>(
`/api/admin/quarantine/actions?limit=${limit}`
);
}
export function createAdminQuarantineQuery() {
return createQuery({
queryKey: qk.adminQuarantine(),
queryFn: listAdminQuarantine,
staleTime: 30_000
});
}
export function createQuarantineActionsQuery(limit: number = 50) {
return createQuery({
queryKey: qk.adminQuarantineActions(limit),
queryFn: () => listQuarantineActions(limit),
staleTime: 60_000
});
}
// Admin playback errors ---------------------------------------------------
export async function listAdminPlaybackErrors(
resolved: boolean = false
): Promise<AdminPlaybackError[]> {
return api.get<AdminPlaybackError[]>(
`/api/admin/playback-errors?resolved=${resolved}`
);
}
export async function resolvePlaybackError(
id: string,
resolution: PlaybackErrorResolution
): Promise<{ id: string }> {
return api.post<{ id: string }>(
`/api/admin/playback-errors/${id}/resolve`,
{ resolution }
);
}
export function createAdminPlaybackErrorsQuery(resolved: boolean = false) {
return createQuery({
queryKey: qk.adminPlaybackErrors(resolved),
queryFn: () => listAdminPlaybackErrors(resolved),
staleTime: 30_000
});
}
// Admin cover art ---------------------------------------------------------
export type RefetchAlbumCoverResponse = {
album_id: string;
cover_art_path: string | null;
cover_art_source: string | null;
};
export async function refetchAlbumCover(albumId: string): Promise<RefetchAlbumCoverResponse> {
return api.post<RefetchAlbumCoverResponse>(`/api/admin/albums/${albumId}/cover/refetch`, {});
}
export type RefetchMissingResponse = {
started: boolean;
};
export async function refetchMissingCovers(): Promise<RefetchMissingResponse> {
return api.post<RefetchMissingResponse>('/api/admin/covers/refetch-missing', {});
}
// Library scan -------------------------------------------------------------
export type ScanStageLibrary = {
scanned: number;
added: number;
updated: number;
skipped: number;
errored: number;
};
export type ScanStageMbidBackfill = {
processed: number;
healed: number;
skipped: number;
duplicates?: number;
};
export type ScanStageCoverEnrich = {
processed: number;
succeeded: number;
failed: number;
};
export type ScanStageArtistArtEnrich = {
processed: number;
succeeded: number;
failed: number;
};
export type ScanStatus = {
id: string;
started_at: string;
finished_at: string | null;
library?: ScanStageLibrary;
mbid_backfill?: ScanStageMbidBackfill;
cover_enrich?: ScanStageCoverEnrich;
artist_art_enrich?: ScanStageArtistArtEnrich;
error_message?: string;
in_flight: boolean;
};
export async function getScanStatus(): Promise<ScanStatus> {
return api.get<ScanStatus>('/api/admin/scan/status');
}
export type TriggerScanResp = { id?: string };
export async function triggerScan(): Promise<TriggerScanResp> {
return api.post<TriggerScanResp>('/api/admin/scan/run', {});
}
// Polls every 3s while a scan is in flight; falls back to a 30s stale-time
// when idle so the section auto-updates as workers complete each stage.
export function createScanStatusQuery() {
return createQuery({
queryKey: qk.scanStatus(),
queryFn: getScanStatus,
staleTime: 30_000,
refetchInterval: 3_000
});
}
// Library coverage --------------------------------------------------------
export type CoverageRollup = {
total: number;
with_art: number;
pending: number;
settled: number;
pending_no_mbid: number;
};
export async function getCoverageRollup(): Promise<CoverageRollup> {
return api.get<CoverageRollup>('/api/admin/library/coverage');
}
// Same pacing as scan-status — 3s while polling, 30s stale-time. The
// query is cheap server-side (one aggregate per call) and we want
// the gauge to tick during a scan.
export function createCoverageQuery() {
return createQuery({
queryKey: qk.coverage(),
queryFn: getCoverageRollup,
staleTime: 30_000,
refetchInterval: 3_000
});
}
// Fingerprint backfill --------------------------------------------
export type FingerprintCoverage = {
total: number;
fingerprinted: number;
rejected: number;
pending: number;
// False when an admin has switched fingerprinting off: pending
// then never shrinks, and nothing should read as progress.
enabled: boolean;
};
export async function getFingerprintCoverage(): Promise<FingerprintCoverage> {
return api.get<FingerprintCoverage>('/api/admin/library/fingerprints');
}
// Polled far less often than the cover gauge: the backfill decodes files two at
// a time, so the count moves by a few tracks a minute and a 3s poll is noise.
export function createFingerprintCoverageQuery() {
return createQuery({
queryKey: qk.fingerprintCoverage(),
queryFn: getFingerprintCoverage,
staleTime: 30_000,
refetchInterval: 30_000
});
}
// Fingerprinting settings ------------------------------------------
export type FingerprintSettings = {
enabled: boolean;
chromaprint_length_sec: number;
// The share of fingerprint bits two copies may disagree on and still be
// proposed as one recording. The card shows it as a match percentage.
acoustic_max_bit_error_rate: number;
backfill_concurrency: number;
sweep_interval_hours: number;
// Lets the duplicate resolver act on its own: merge copies no
// release needs.
auto_resolve: boolean;
};
export async function getFingerprintSettings(): Promise<FingerprintSettings> {
return api.get<FingerprintSettings>('/api/admin/library/fingerprint-settings');
}
export async function updateFingerprintSettings(
s: FingerprintSettings
): Promise<FingerprintSettings> {
return api.put<FingerprintSettings>('/api/admin/library/fingerprint-settings', s);
}
// Loudness analysis -------------------------------------------------
export type LoudnessCoverage = {
total: number;
measured: number;
// Read fine, but no part of the track was loud enough to measure: silence,
// or a file shorter than half a second.
silent: number;
unreadable: number;
pending: number;
// False when an admin has switched analysis off: pending then never
// shrinks, and nothing should read as progress.
enabled: boolean;
};
export async function getLoudnessCoverage(): Promise<LoudnessCoverage> {
return api.get<LoudnessCoverage>('/api/admin/library/loudness');
}
export type LoudnessSettings = {
enabled: boolean;
backfill_concurrency: number;
/** Disk for the leveled copies rendered for Sonos/UPnP speakers. */
leveled_cache_mb: number;
};
export async function getLoudnessSettings(): Promise<LoudnessSettings> {
return api.get<LoudnessSettings>('/api/admin/library/loudness-settings');
}
export async function updateLoudnessSettings(s: LoudnessSettings): Promise<LoudnessSettings> {
return api.put<LoudnessSettings>('/api/admin/library/loudness-settings', s);
}
// Outside lookups no metadata source covers ---------------------------
/** Switches for ListenBrainz's similar songs and artists (radio and the
* mixes) and MusicBrainz's album track lists (the duplicate resolver).
* Both are on unless an admin turns them off. */
export type LookupSettings = {
listenbrainz_similarity: boolean;
musicbrainz_track_lists: boolean;
};
export async function getLookupSettings(): Promise<LookupSettings> {
return api.get<LookupSettings>('/api/admin/lookup-settings');
}
export async function updateLookupSettings(s: LookupSettings): Promise<LookupSettings> {
return api.put<LookupSettings>('/api/admin/lookup-settings', s);
}
// The library's folders -----------------------------------------------
export type LibraryFolder = {
path: string;
/** Whether the server can see the folder right now. */
present: boolean;
tracks: number;
};
export type LibraryFolders = {
folders: LibraryFolder[];
/** False while the folders still come from MINSTREL_LIBRARY_SCAN_PATHS. */
saved: boolean;
/** How many tracks a save moved to a new folder. */
moved?: number;
};
/** One folder of a save. `was` is the folder it replaces, whose files are now
* at `path`; '' is a folder added. */
export type LibraryFolderChange = { path: string; was: string };
export async function getLibraryFolders(): Promise<LibraryFolders> {
return api.get<LibraryFolders>('/api/admin/library/folders');
}
export async function updateLibraryFolders(folders: LibraryFolderChange[]): Promise<LibraryFolders> {
return api.put<LibraryFolders>('/api/admin/library/folders', { folders });
}
// AcoustID recording-id lookup ---------------------------------------
export type AcoustIDSettings = {
enabled: boolean;
min_score: number;
/** The key itself is never sent back, only whether one is stored. */
api_key_set: boolean;
};
export type AcoustIDOverview = {
settings: AcoustIDSettings;
/** Switched on and holding a key: the worker will call AcoustID. */
ready: boolean;
status: { running: boolean; last_pass_at: string | null; problem: string };
/** from_tag + from_acoustid + tracks with no MBID = total. */
coverage: {
total: number;
from_tag: number;
from_acoustid: number;
ambiguous: number;
no_match: number;
failed: number;
pending: number;
};
};
export type AcoustIDUnsettled = {
track_id: string;
title: string;
artist: string;
album: string;
file_path: string;
state: 'ambiguous' | 'failed';
best_score: number | null;
candidates: number;
detail: string | null;
looked_up_at: string;
};
export async function getAcoustID(): Promise<AcoustIDOverview> {
return api.get<AcoustIDOverview>('/api/admin/library/acoustid');
}
/** api_key left out keeps the stored key; an empty string clears it. */
export async function updateAcoustIDSettings(s: {
enabled: boolean;
min_score: number;
api_key?: string;
}): Promise<AcoustIDSettings> {
return api.put<AcoustIDSettings>('/api/admin/library/acoustid-settings', s);
}
export async function runAcoustIDLookup(): Promise<void> {
await api.post<null>('/api/admin/library/acoustid/run', {});
}
export async function listUnsettledAcoustID(): Promise<AcoustIDUnsettled[]> {
return api.get<AcoustIDUnsettled[]>('/api/admin/library/acoustid/unsettled');
}
// Cover-art providers ------------------------------------------------------
export type CoverProviderCapability = 'album_cover' | 'artist_thumb' | 'artist_fanart';
export type CoverProvider = {
id: string;
display_name: string;
requires_api_key: boolean;
supports: CoverProviderCapability[];
enabled: boolean;
api_key_set: boolean;
display_order: number;
testable: boolean;
};
export type CoverProvidersResponse = {
providers: CoverProvider[];
sources_version: number;
};
export async function getCoverProviders(): Promise<CoverProvidersResponse> {
return api.get<CoverProvidersResponse>('/api/admin/cover-sources');
}
export type UpdateCoverProviderPatch = {
enabled?: boolean;
api_key?: string;
};
export type UpdateCoverProviderResponse = CoverProvider & {
version_bumped: boolean;
};
export async function updateCoverProvider(
id: string,
patch: UpdateCoverProviderPatch
): Promise<UpdateCoverProviderResponse> {
return api.patch<UpdateCoverProviderResponse>(`/api/admin/cover-sources/${id}`, patch);
}
export type TestCoverProviderResponse = {
ok: boolean;
duration_ms?: number;
error?: string;
};
export async function testCoverProvider(id: string): Promise<TestCoverProviderResponse> {
return api.post<TestCoverProviderResponse>(`/api/admin/cover-sources/${id}/test`, {});
}
// Re-search missing art --------------------------------------------------
export type ResearchMissingArtResponse = { version: number };
// Bumps cover_art_sources_meta.current_version. Every 'none' row becomes
// eligible for retry against the current provider chain on the next
// enrichment pass. Existing positively-sourced rows are not affected.
export async function researchMissingArt(): Promise<ResearchMissingArtResponse> {
return api.post<ResearchMissingArtResponse>('/api/admin/cover-sources/research', {});
}
// Settings rarely change in operator time. 60s staleTime; refetches
// on window focus + after any mutation rather than polling.
export function createCoverProvidersQuery() {
return createQuery({
queryKey: qk.coverProviders(),
queryFn: getCoverProviders,
staleTime: 60_000
});
}
// Tag-enrichment providers -------------------------------------------------
// Parallel to the cover-art providers surface, over /api/admin/tag-sources.
// Independent settings so a new folksonomy source is added without touching
// art config.
export type TagProviderCapability = 'track_tags';
export type TagProvider = {
id: string;
display_name: string;
requires_api_key: boolean;
supports: TagProviderCapability[];
enabled: boolean;
api_key_set: boolean;
display_order: number;
testable: boolean;
};
export type TagProvidersResponse = {
providers: TagProvider[];
sources_version: number;
};
export async function getTagProviders(): Promise<TagProvidersResponse> {
return api.get<TagProvidersResponse>('/api/admin/tag-sources');
}
export type UpdateTagProviderPatch = {
enabled?: boolean;
api_key?: string;
};
export type UpdateTagProviderResponse = TagProvider & {
version_bumped: boolean;
};
export async function updateTagProvider(
id: string,
patch: UpdateTagProviderPatch
): Promise<UpdateTagProviderResponse> {
return api.patch<UpdateTagProviderResponse>(`/api/admin/tag-sources/${id}`, patch);
}
export type TestTagProviderResponse = {
ok: boolean;
duration_ms?: number;
error?: string;
};
export async function testTagProvider(id: string): Promise<TestTagProviderResponse> {
return api.post<TestTagProviderResponse>(`/api/admin/tag-sources/${id}/test`, {});
}
export function createTagProvidersQuery() {
return createQuery({
queryKey: qk.tagProviders(),
queryFn: getTagProviders,
staleTime: 60_000
});
}
// Admin user-management ------------------------------------------------------
export type AdminUser = {
id: string;
username: string;
display_name: string | null;
is_admin: boolean;
debug_mode_enabled: boolean;
created_at: string;
};
export type AdminInvite = {
token: string;
invited_by: string;
note: string | null;
created_at: string;
expires_at: string;
redeemed_at: string | null;
redeemed_by: string | null;
};
export async function listUsers(): Promise<AdminUser[]> {
const res = await api.get<{ users: AdminUser[] }>('/api/admin/users');
return res.users;
}
export async function updateUserAdmin(id: string, isAdmin: boolean): Promise<AdminUser> {
return api.put<AdminUser>(`/api/admin/users/${id}/admin`, { is_admin: isAdmin });
}
export async function listInvites(): Promise<AdminInvite[]> {
const res = await api.get<{ invites: AdminInvite[] }>('/api/admin/invites');
return res.invites;
}
export async function createInvite(note?: string): Promise<AdminInvite> {
return api.post<AdminInvite>('/api/admin/invites', note ? { note } : {});
}
export async function deleteInvite(token: string): Promise<void> {
await api.del(`/api/admin/invites/${token}`);
}
// U2 user-management actions -----------------------------------------------
export type CreateUserInput = {
username: string;
password: string;
display_name?: string;
is_admin?: boolean;
};
export async function createUser(input: CreateUserInput): Promise<AdminUser> {
return api.post<AdminUser>('/api/admin/users', input);
}
export async function deleteUser(id: string): Promise<void> {
await api.del(`/api/admin/users/${id}`);
}
export async function resetUserPassword(id: string, password: string): Promise<void> {
await api.post(`/api/admin/users/${id}/reset-password`, { password });
}
// Flip an account's diagnostics/debug-reporting opt-in. Admin-set;
// the client obeys it (with a local per-device OFF switch).
export async function updateUserDebugMode(id: string, enabled: boolean): Promise<AdminUser> {
return api.put<AdminUser>(`/api/admin/users/${id}/debug-mode`, { enabled });
}
export function createAdminUsersQuery() {
return createQuery({
queryKey: qk.adminUsers(),
queryFn: listUsers
});
}
export function createAdminInvitesQuery() {
return createQuery({
queryKey: qk.adminInvites(),
queryFn: listInvites
});
}
// SMTP config (U3) ----------------------------------------------------------
export type SMTPConfig = {
enabled: boolean;
host: string;
port: number;
username: string;
password: string; // "***" when set, "" when unset
from_address: string;
from_name: string;
use_tls: boolean;
};
export async function getSMTPConfig(): Promise<SMTPConfig> {
return api.get<SMTPConfig>('/api/admin/smtp-config');
}
export async function updateSMTPConfig(input: SMTPConfig): Promise<void> {
await api.put('/api/admin/smtp-config', input);
}
export async function testSMTPConfig(): Promise<void> {
await api.post('/api/admin/smtp-config/test', {});
}
export function createSMTPConfigQuery() {
return createQuery({
queryKey: qk.smtpConfig(),
queryFn: getSMTPConfig,
staleTime: 60_000
});
}
// Device diagnostics ---------------------------------------------------
// Coarse event category. The finer event sub-type lives inside `payload`.
export type DiagnosticKind =
| 'connectivity'
| 'upnp_sync'
| 'power'
| 'lifecycle'
| 'heartbeat'
| 'http';
export type AdminDiagnostic = {
id: string;
user_id: string;
username: string;
client_id: string;
app_version?: string;
os_version?: string;
kind: DiagnosticKind | string;
payload: Record<string, unknown>;
occurred_at: string;
received_at: string;
};
export type AdminDiagnosticDevice = {
client_id: string;
user_id: string;
username: string;
app_version: string;
os_version: string;
last_seen: string;
event_count: number;
};
export type DiagnosticsFilter = {
userId?: string;
clientId?: string;
kind?: string;
from?: string; // RFC3339
to?: string; // RFC3339
limit?: number;
};
export async function listAdminDiagnostics(f: DiagnosticsFilter): Promise<AdminDiagnostic[]> {
const params = new URLSearchParams();
if (f.userId) params.set('user_id', f.userId);
if (f.clientId) params.set('client_id', f.clientId);
if (f.kind) params.set('kind', f.kind);
if (f.from) params.set('from', f.from);
if (f.to) params.set('to', f.to);
if (f.limit !== undefined) params.set('limit', String(f.limit));
const qs = params.toString();
return api.get<AdminDiagnostic[]>(qs ? `/api/admin/diagnostics?${qs}` : '/api/admin/diagnostics');
}
export async function listDiagnosticDevices(userId?: string): Promise<AdminDiagnosticDevice[]> {
const qs = userId ? `?user_id=${userId}` : '';
return api.get<AdminDiagnosticDevice[]>(`/api/admin/diagnostics/devices${qs}`);
}
export function createAdminDiagnosticsQuery(f: DiagnosticsFilter) {
return createQuery({
queryKey: qk.adminDiagnostics(f as Record<string, string | number | undefined>),
queryFn: () => listAdminDiagnostics(f),
// An admin enables debug then watches events stream in; a short
// poll keeps the timeline live without manual refresh.
refetchInterval: 10_000,
staleTime: 5_000
});
}
export function createDiagnosticDevicesQuery(userId?: string) {
return createQuery({
queryKey: qk.adminDiagnosticDevices(userId),
queryFn: () => listDiagnosticDevices(userId),
staleTime: 15_000
});
}
// Trusted-proxy depth ---------------------------------------------
// detected_client_ip / forwarded_chain / remote_addr describe THIS request
// under the current setting, so the admin card can be verified rather than
// reasoned about: change the number, see what address you resolve to.
export type NetworkSettings = {
trusted_proxy_hops: number;
max_hops: number;
detected_client_ip: string;
forwarded_chain: string;
remote_addr: string;
// Where users reach Minstrel. Password-reset emails link here and are not
// sent while it is empty.
public_url: string;
};
export async function getNetworkSettings(): Promise<NetworkSettings> {
return api.get<NetworkSettings>('/api/admin/network-settings');
}
// Returns the payload recomputed under the new value, so the card can show
// the effect immediately instead of requiring a reload.
export async function updateNetworkSettings(hops: number): Promise<NetworkSettings> {
return api.put<NetworkSettings>('/api/admin/network-settings', {
trusted_proxy_hops: hops
});
}
// Saves only the public address; the proxy depth is left as it is.
export async function updatePublicUrl(publicUrl: string): Promise<NetworkSettings> {
return api.put<NetworkSettings>('/api/admin/network-settings', {
public_url: publicUrl
});
}
// Duplicates report -------------------------------------------------
export const DUPLICATES_PAGE_SIZE = 25;
export async function listDuplicates(
view: DuplicatesView = 'review',
offset: number = 0,
limit: number = DUPLICATES_PAGE_SIZE
): Promise<AdminDuplicatesResponse> {
return api.get<AdminDuplicatesResponse>(
`/api/admin/library/duplicates?view=${view}&limit=${limit}&offset=${offset}`
);
}
export function duplicatesNextOffset(last: AdminDuplicatesResponse): number | undefined {
const loaded = last.offset + last.groups.length;
return last.groups.length === 0 || loaded >= last.total ? undefined : loaded;
}
// Loads as the page scrolls, one tab at a time. Polls so a sweep
// or resolver pass finishing shows up while an admin is on the page.
export function createDuplicatesQuery(view: DuplicatesView = 'review') {
return createInfiniteQuery({
queryKey: qk.adminDuplicates(view),
queryFn: ({ pageParam }) => listDuplicates(view, pageParam as number),
initialPageParam: 0,
getNextPageParam: duplicatesNextOffset,
staleTime: 30_000,
refetchInterval: 30_000
});
}
export async function listResolvedDuplicates(offset: number = 0): Promise<ResolvedDuplicatesResponse> {
return api.get<ResolvedDuplicatesResponse>(
`/api/admin/library/duplicates/resolved?limit=${DUPLICATES_PAGE_SIZE}&offset=${offset}`
);
}
export function resolvedDuplicatesNextOffset(last: ResolvedDuplicatesResponse): number | undefined {
const loaded = last.offset + last.items.length;
return last.items.length === 0 || loaded >= last.total ? undefined : loaded;
}
// What the resolver did by itself, newest first.
export function createResolvedDuplicatesQuery() {
return createInfiniteQuery({
queryKey: qk.adminResolvedDuplicates(),
queryFn: ({ pageParam }) => listResolvedDuplicates(pageParam as number),
initialPageParam: 0,
getNextPageParam: resolvedDuplicatesNextOffset,
staleTime: 60_000
});
}
export async function runDuplicateSweep(): Promise<{ started: boolean }> {
return api.post<{ started: boolean }>('/api/admin/library/duplicates/sweep', {});
}
// Merges a group into the copy chosen to keep, removing the other copies'
// files. survivor_track_id is an admin's choice; the server checks it belongs
// to the group.
export async function mergeDuplicateGroup(
id: string,
body: { survivor_track_id: string }
): Promise<MergeDuplicateResult> {
return api.post<MergeDuplicateResult>(
`/api/admin/library/duplicates/${encodeURIComponent(id)}/merge`,
body
);
}
// One recording in several of an album's slots: keep the copy whose title it
// is, or none (empty keep_track_id). The other copies' files go and their
// tracks wait in Needs a file for a good copy.
export async function removeWrongSlotFiles(
id: string,
body: { keep_track_id: string }
): Promise<WrongSlotRemoval> {
return api.post<WrongSlotRemoval>(
`/api/admin/library/duplicates/${encodeURIComponent(id)}/remove-files`,
body
);
}
export async function dismissDuplicateGroup(id: string): Promise<void> {
await api.post(`/api/admin/library/duplicates/${encodeURIComponent(id)}/dismiss`, {});
}
// Needs a file ------------------------------------------------------
export async function listMissingFiles(
offset: number = 0,
limit: number = 50
): Promise<AdminMissingResponse> {
return api.get<AdminMissingResponse>(
`/api/admin/library/missing?limit=${limit}&offset=${offset}`
);
}
// Takes a plain offset rather than a getter: callers wrap the call in
// $derived (as the playback-errors page does for its tab
// state), so changing the page re-creates the query with a new key. A
// getter would capture the key once and paging would silently not refetch.
//
// staleTime is generous because this list only changes when a scan runs —
// no point re-fetching on every focus like a live triage queue.
export function createMissingFilesQuery(offset: number = 0, limit: number = 50) {
return createQuery({
queryKey: qk.adminMissingFiles(offset),
queryFn: () => listMissingFiles(offset, limit),
staleTime: 120_000
});
}
// Forgets tracks waiting for a file, for good: each goes with its likes, plays
// and playlist places. All or nothing; a track whose file is back is refused.
export async function forgetMissingTracks(trackIds: string[]): Promise<{ forgotten: number }> {
return api.post<{ forgotten: number }>('/api/admin/library/missing/forget', { track_ids: trackIds });
}
// The whole list as a CSV, to hand to whatever finds music. A plain link
// downloads it: the session cookie goes with it.
export const MISSING_FILES_CSV_URL = '/api/admin/library/missing.csv';
// Suspect sources --------------------------------------------------
export const SUSPECT_SOURCES_PAGE_SIZE = 50;
export async function listSuspectSources(offset: number = 0): Promise<AdminSuspectResponse> {
return api.get<AdminSuspectResponse>(
`/api/admin/library/suspect-sources?limit=${SUSPECT_SOURCES_PAGE_SIZE}&offset=${offset}`
);
}
// The next offset counts tracks, not groups: limit and total are in tracks.
export function suspectSourcesNextOffset(last: AdminSuspectResponse): number | undefined {
const loaded = last.offset + last.groups.reduce((n, g) => n + g.tracks.length, 0);
return loaded >= last.total ? undefined : loaded;
}
// Loads as the page scrolls. Changes only when files are added or
// removed, so it is not re-fetched on every focus.
export function createSuspectSourcesQuery() {
return createInfiniteQuery({
queryKey: qk.adminSuspectSources(),
queryFn: ({ pageParam }) => listSuspectSources(pageParam as number),
initialPageParam: 0,
getNextPageParam: suspectSourcesNextOffset,
staleTime: 120_000
});
}
// 'fine' lets a flagged track back into radio and the mixes; 'suspect' holds
// it back again.
export async function setSuspectVerdict(trackId: string, verdict: SuspectVerdict): Promise<void> {
await api.put(`/api/admin/library/suspect-sources/${encodeURIComponent(trackId)}`, { verdict });
}
// Removes a suspect source's file and keeps its track, which waits in Needs a
// file for a clean copy.
export async function removeSuspectFile(trackId: string): Promise<void> {
await api.post(`/api/admin/library/suspect-sources/${encodeURIComponent(trackId)}/remove`, {});
}
// Notification emails: when the grouped emails go out.
export type NotificationEmailSettings = {
summary_hour: number;
batch_window_minutes: number;
};
export async function getNotificationEmailSettings(): Promise<NotificationEmailSettings> {
return api.get<NotificationEmailSettings>('/api/admin/notification-email');
}
export async function updateNotificationEmailSettings(
s: NotificationEmailSettings
): Promise<NotificationEmailSettings> {
return api.put<NotificationEmailSettings>('/api/admin/notification-email', s);
}
// The server's own backup ---------------------------------------------------
export type BackupDestination = 'folder' | 's3';
export type BackupConfig = {
enabled: boolean;
destination: BackupDestination;
folder: string;
endpoint: string;
bucket: string;
access_key: string;
/** The secret key itself never comes back. */
has_secret_key: boolean;
/** The hour of day the nightly backup starts, in UTC. */
run_hour: number;
/** KiB a second an upload to the bucket may use; 0 is no limit. */
upload_limit_kib: number;
/** Also send the library's music files, each once, to music/. */
include_music: boolean;
};
export type BackupState = 'off' | 'incomplete' | 'failing' | 'waiting' | 'overdue' | 'ok';
export type BackupRun = {
id: string;
trigger: 'schedule' | 'manual';
status: 'running' | 'succeeded' | 'failed';
started_at: string;
finished_at: string | null;
/** The file's path in the folder, or its key in the bucket. */
location: string;
bytes: number;
error: string;
/** What the run sent of the music, and why it stopped early, if it did. */
music_files: number;
music_bytes: number;
music_note: string;
};
/** A library file the destination wouldn't take; tried again once it changes. */
export type BackupRefusedFile = { path: string; error: string; at: string };
/** How much of the library the backup holds as it is now. */
export type BackupMusicProgress = {
total_files: number;
total_bytes: number;
sent_files: number;
sent_bytes: number;
refused_files: number;
refused: BackupRefusedFile[];
};
export type BackupStatus = {
config: BackupConfig;
/** Worked out by the server; the panel only words it. */
state: BackupState;
problems: string[];
running_since: string | null;
last_success: string | null;
failing_since: string | null;
next_run: string | null;
/** The longest a run may take; the panel stops polling a little after. */
run_limit_seconds: number;
runs: BackupRun[];
/** Present when the backup includes the music. */
music: BackupMusicProgress | null;
};
/** A save or test. An empty secret_key keeps the stored one. */
export type BackupUpdate = Omit<BackupConfig, 'has_secret_key'> & { secret_key: string };
export type BackupTestResult = { backups: number; latest: string | null };
export async function getBackups(): Promise<BackupStatus> {
return api.get<BackupStatus>('/api/admin/backups');
}
export async function saveBackups(u: BackupUpdate): Promise<BackupStatus> {
return api.put<BackupStatus>('/api/admin/backups', u);
}
/** Checks the destination in u without saving it; nothing is written there. */
export async function testBackups(u: BackupUpdate): Promise<BackupTestResult> {
return api.post<BackupTestResult>('/api/admin/backups/test', u);
}
export async function runBackup(): Promise<void> {
await api.post<null>('/api/admin/backups/run', {});
}