import { createInfiniteQuery, createQuery } from '@tanstack/svelte-query'; import { api } from './client'; import { qk } from './queries'; import type { ActionResult, AdminMissingResponse, AdminSuspectResponse, SuspectVerdict, AdminDuplicatesResponse, DuplicatesView, MergeDuplicateResult, ResolvedDuplicatesResponse, AdminPlaybackError, AdminQuarantineRow, LidarrConfig, LidarrMetadataProfile, LidarrQualityProfile, LidarrQuarantineActionRow, MusicRequest, RequestStatus, LidarrRootFolder, LidarrTestResult, PlaybackErrorResolution } from './types'; // Admin Lidarr config ----------------------------------------------------- export async function getLidarrConfig(): Promise { return api.get('/api/admin/lidarr/config'); } export async function putLidarrConfig(cfg: LidarrConfig): Promise { return api.put('/api/admin/lidarr/config', cfg); } // testLidarrConnection always returns 200 with a discriminated-union body — // callers branch on `result.ok`. We do NOT throw on `ok:false`; the SPA wants // to render either branch (e.g. "connected to Lidarr X.Y.Z" vs "auth failed"). export async function testLidarrConnection( body: { base_url?: string; api_key?: string } = {} ): Promise { return api.post('/api/admin/lidarr/test', body); } export async function listQualityProfiles(): Promise { return api.get('/api/admin/lidarr/quality-profiles'); } export async function listMetadataProfiles(): Promise { return api.get('/api/admin/lidarr/metadata-profiles'); } export async function listRootFolders(): Promise { return api.get('/api/admin/lidarr/root-folders'); } // Admin request queue ----------------------------------------------------- export async function listAdminRequests( status?: RequestStatus, limit?: number ): Promise { const params = new URLSearchParams(); if (status) params.set('status', status); if (limit !== undefined) params.set('limit', String(limit)); const qs = params.toString(); return api.get( qs ? `/api/admin/requests?${qs}` : '/api/admin/requests' ); } // Approving puts the request on the wanted list (M502 #5520). An artist // request is followed on profileId, or the default profile when omitted. export async function approveRequest(id: string, profileId?: string): Promise { return api.post( `/api/admin/requests/${id}/approve`, profileId ? { profile_id: profileId } : {} ); } export async function rejectRequest( id: string, notes?: string ): Promise { const body = notes !== undefined ? { notes } : {}; return api.post(`/api/admin/requests/${id}/reject`, body); } // Query factories --------------------------------------------------------- export function createLidarrConfigQuery() { return createQuery({ queryKey: qk.lidarrConfig(), queryFn: getLidarrConfig, staleTime: 60_000 }); } // `enabled` is passed in by the caller — typically derived from // LidarrConfig.enabled — so the query only fires once Lidarr is configured. // Keeping it as a prop (vs. reading config inside this factory) preserves // purity and lets the caller choose its own gating logic. export function createQualityProfilesQuery(enabled: boolean = true) { return createQuery({ queryKey: qk.lidarrQualityProfiles(), queryFn: listQualityProfiles, enabled }); } export function createMetadataProfilesQuery(enabled: boolean = true) { return createQuery({ queryKey: qk.lidarrMetadataProfiles(), queryFn: listMetadataProfiles, enabled }); } export function createRootFoldersQuery(enabled: boolean = true) { return createQuery({ queryKey: qk.lidarrRootFolders(), queryFn: listRootFolders, enabled }); } export function createAdminRequestsQuery(status?: RequestStatus) { return createQuery({ queryKey: qk.adminRequests(status), queryFn: () => listAdminRequests(status), // Only the 'approved' tab needs polling — that's where in-flight // ingests live. Other tabs (pending/rejected/completed) are static // until the operator acts on them. refetchInterval: (query) => { if (status !== 'approved') return false; const rows = query.state.data as MusicRequest[] | undefined; return hasInFlightRequest(rows) ? 12_000 : false; } }); } function hasInFlightRequest(rows: readonly MusicRequest[] | undefined): boolean { return rows?.some((r) => r.status === 'approved') ?? false; } // Admin quarantine -------------------------------------------------------- export async function listAdminQuarantine(): Promise { return api.get('/api/admin/quarantine'); } export async function resolveQuarantine(trackID: string): Promise { return api.post(`/api/admin/quarantine/${trackID}/resolve`, {}); } export async function deleteQuarantineFile(trackID: string): Promise { return api.post(`/api/admin/quarantine/${trackID}/delete-file`, {}); } export async function deleteQuarantineViaLidarr(trackID: string): Promise { return api.post(`/api/admin/quarantine/${trackID}/delete-via-lidarr`, {}); } export async function listQuarantineActions( limit: number = 50 ): Promise { return api.get( `/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 { return api.get( `/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 { return api.post(`/api/admin/albums/${albumId}/cover/refetch`, {}); } export type RefetchMissingResponse = { started: boolean; }; export async function refetchMissingCovers(): Promise { return api.post('/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 { return api.get('/api/admin/scan/status'); } export type TriggerScanResp = { id?: string }; export async function triggerScan(): Promise { return api.post('/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 { return api.get('/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 (#3908) -------------------------------------------- export type FingerprintCoverage = { total: number; fingerprinted: number; rejected: number; pending: number; // False when the operator has switched fingerprinting off (#3913): pending // then never shrinks, and nothing should read as progress. enabled: boolean; }; export async function getFingerprintCoverage(): Promise { return api.get('/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 (#3913) ------------------------------------------ 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 (M498): merge copies Lidarr // doesn't need and change a Lidarr release that lists songs twice. auto_resolve: boolean; }; export async function getFingerprintSettings(): Promise { return api.get('/api/admin/library/fingerprint-settings'); } export async function updateFingerprintSettings( s: FingerprintSettings ): Promise { return api.put('/api/admin/library/fingerprint-settings', s); } // Loudness analysis (#4995) ------------------------------------------------- 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 the operator has switched analysis off: pending then never // shrinks, and nothing should read as progress. enabled: boolean; }; export async function getLoudnessCoverage(): Promise { return api.get('/api/admin/library/loudness'); } export type LoudnessSettings = { enabled: boolean; backfill_concurrency: number; /** Disk for the leveled copies rendered for Sonos/UPnP speakers (#5001). */ leveled_cache_mb: number; }; export async function getLoudnessSettings(): Promise { return api.get('/api/admin/library/loudness-settings'); } export async function updateLoudnessSettings(s: LoudnessSettings): Promise { return api.put('/api/admin/library/loudness-settings', s); } // AcoustID recording-id lookup (M401) --------------------------------------- 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 { return api.get('/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 { return api.put('/api/admin/library/acoustid-settings', s); } export async function runAcoustIDLookup(): Promise { await api.post('/api/admin/library/acoustid/run', {}); } export async function listUnsettledAcoustID(): Promise { return api.get('/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 { return api.get('/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 { return api.patch(`/api/admin/cover-sources/${id}`, patch); } export type TestCoverProviderResponse = { ok: boolean; duration_ms?: number; error?: string; }; export async function testCoverProvider(id: string): Promise { return api.post(`/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 { return api.post('/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 (#1490). 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 { return api.get('/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 { return api.patch(`/api/admin/tag-sources/${id}`, patch); } export type TestTagProviderResponse = { ok: boolean; duration_ms?: number; error?: string; }; export async function testTagProvider(id: string): Promise { return api.post(`/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; auto_approve_requests: 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 { const res = await api.get<{ users: AdminUser[] }>('/api/admin/users'); return res.users; } export async function updateUserAdmin(id: string, isAdmin: boolean): Promise { return api.put(`/api/admin/users/${id}/admin`, { is_admin: isAdmin }); } export async function listInvites(): Promise { const res = await api.get<{ invites: AdminInvite[] }>('/api/admin/invites'); return res.invites; } export async function createInvite(note?: string): Promise { return api.post('/api/admin/invites', note ? { note } : {}); } export async function deleteInvite(token: string): Promise { 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 { return api.post('/api/admin/users', input); } export async function deleteUser(id: string): Promise { await api.del(`/api/admin/users/${id}`); } export async function resetUserPassword(id: string, password: string): Promise { await api.post(`/api/admin/users/${id}/reset-password`, { password }); } export async function updateUserAutoApprove(id: string, autoApprove: boolean): Promise { return api.put(`/api/admin/users/${id}/auto-approve`, { auto_approve: autoApprove }); } // Flip an account's diagnostics/debug-reporting opt-in (M9). Admin-set; // the client obeys it (with a local per-device OFF switch). export async function updateUserDebugMode(id: string, enabled: boolean): Promise { return api.put(`/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 { return api.get('/api/admin/smtp-config'); } export async function updateSMTPConfig(input: SMTPConfig): Promise { await api.put('/api/admin/smtp-config', input); } export async function testSMTPConfig(): Promise { await api.post('/api/admin/smtp-config/test', {}); } export function createSMTPConfigQuery() { return createQuery({ queryKey: qk.smtpConfig(), queryFn: getSMTPConfig, staleTime: 60_000 }); } // Device diagnostics (M9) --------------------------------------------------- // 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; 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 { 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(qs ? `/api/admin/diagnostics?${qs}` : '/api/admin/diagnostics'); } export async function listDiagnosticDevices(userId?: string): Promise { const qs = userId ? `?user_id=${userId}` : ''; return api.get(`/api/admin/diagnostics/devices${qs}`); } export function createAdminDiagnosticsQuery(f: DiagnosticsFilter) { return createQuery({ queryKey: qk.adminDiagnostics(f as Record), queryFn: () => listAdminDiagnostics(f), // The operator 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 (#2453) --------------------------------------------- // 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 { return api.get('/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 { return api.put('/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 { return api.put('/api/admin/network-settings', { public_url: publicUrl }); } // Duplicates report (#3912) ------------------------------------------------- export const DUPLICATES_PAGE_SIZE = 25; export async function listDuplicates( view: DuplicatesView = 'review', offset: number = 0, limit: number = DUPLICATES_PAGE_SIZE ): Promise { return api.get( `/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 (rule 172), one tab at a time. Polls so a sweep // or resolver pass finishing shows up while the operator 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 { return api.get( `/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 (M498), 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 the operator's choice; the server checks it belongs to // the group. export async function mergeDuplicateGroup( id: string, body: { survivor_track_id: string; unmonitor: boolean } ): Promise { return api.post( `/api/admin/library/duplicates/${encodeURIComponent(id)}/merge`, body ); } export async function dismissDuplicateGroup(id: string): Promise { await api.post(`/api/admin/library/duplicates/${encodeURIComponent(id)}/dismiss`, {}); } // Missing files (#2527) ----------------------------------------------------- export async function listMissingFiles( offset: number = 0, limit: number = 50 ): Promise { return api.get( `/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 and requests pages do for their 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 }); } // Suspect sources (#5410) -------------------------------------------------- export const SUSPECT_SOURCES_PAGE_SIZE = 50; export async function listSuspectSources(offset: number = 0): Promise { return api.get( `/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 (rule 172). 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 (M498 #5439). export async function setSuspectVerdict(trackId: string, verdict: SuspectVerdict): Promise { await api.put(`/api/admin/library/suspect-sources/${encodeURIComponent(trackId)}`, { verdict }); } // Missing-file re-acquisition (#2527 / milestone #290) ---------------------- export type ReacquisitionSettings = { enabled: boolean; grace_hours: number; max_per_pass: number; // Albums with missing files that can never be wanted automatically because // neither they nor their artist carries an MBID. Read-only; the server // computes it, and the card states it so the gap isn't a mystery. unnameable_albums: number; }; export async function getReacquisitionSettings(): Promise { return api.get('/api/admin/library/reacquisition'); } export async function updateReacquisitionSettings( s: ReacquisitionSettings ): Promise { return api.put('/api/admin/library/reacquisition', s); } // Notification emails (M489 #5346): when the grouped emails go out. export type NotificationEmailSettings = { summary_hour: number; batch_window_minutes: number; }; export async function getNotificationEmailSettings(): Promise { return api.get('/api/admin/notification-email'); } export async function updateNotificationEmailSettings( s: NotificationEmailSettings ): Promise { return api.put('/api/admin/notification-email', s); } // Indexers and download clients (M502 #5518) ------------------------------- export type AcquisitionProtocol = 'prowlarr' | 'torznab' | 'qbittorrent' | 'exchange'; /** One indexer or download client. Secrets never come back, only whether set. */ export type AcquisitionService = { code: string; kind: 'search' | 'download'; protocol: AcquisitionProtocol; label: string; enabled: boolean; base_url: string; has_api_key: boolean; has_password: boolean; username: string; category: string; timeout_ms: number; /** The three switches mean something on an exchange row only. */ serves_search: boolean; serves_downloads: boolean; serves_enrichment: boolean; local_path: string; remote_path: string; searches_per_hour: number; /** Switched on and addressed. */ usable: boolean; }; export type AcquisitionUpdate = Omit< AcquisitionService, 'code' | 'kind' | 'protocol' | 'has_api_key' | 'has_password' | 'usable' >; export type AcquisitionTestResult = { ok: boolean; detail: string }; const acquisitionBase = '/api/admin/acquisition/services'; export async function listAcquisitionServices(): Promise { const res = await api.get<{ services: AcquisitionService[] }>(acquisitionBase); return res.services; } export async function addAcquisitionService( protocol: AcquisitionProtocol ): Promise { return api.post(acquisitionBase, { protocol }); } export async function updateAcquisitionService( code: string, u: AcquisitionUpdate ): Promise { return api.put(`${acquisitionBase}/${encodeURIComponent(code)}`, u); } export async function removeAcquisitionService(code: string): Promise { await api.del(`${acquisitionBase}/${encodeURIComponent(code)}`); } export async function testAcquisitionService(code: string): Promise { return api.post(`${acquisitionBase}/${encodeURIComponent(code)}/test`, {}); } /** Stores a key or password. Write-only: nothing comes back. */ export async function setAcquisitionSecret( code: string, which: 'api-key' | 'password', value: string ): Promise { await api.put(`${acquisitionBase}/${encodeURIComponent(code)}/${which}`, { value }); } export async function clearAcquisitionSecret( code: string, which: 'api-key' | 'password' ): Promise { await api.del(`${acquisitionBase}/${encodeURIComponent(code)}/${which}`); }