import { Book, StatusData, AppConfig, LoginCredentials, AuthResponse, ReleaseSource, ReleasesResponse } from '../types'; import { SettingsResponse, ActionResult, UpdateResult } from '../types/settings'; import { MetadataBookData, transformMetadataToBook } from '../utils/bookTransformers'; import { getApiBase } from '../utils/basePath'; const API_BASE = getApiBase(); // API endpoints const API = { search: `${API_BASE}/search`, metadataSearch: `${API_BASE}/metadata/search`, info: `${API_BASE}/info`, download: `${API_BASE}/download`, status: `${API_BASE}/status`, cancelDownload: `${API_BASE}/download`, setPriority: `${API_BASE}/queue`, clearCompleted: `${API_BASE}/queue/clear`, config: `${API_BASE}/config`, login: `${API_BASE}/auth/login`, logout: `${API_BASE}/auth/logout`, authCheck: `${API_BASE}/auth/check`, settings: `${API_BASE}/settings`, }; // Custom error class for authentication failures export class AuthenticationError extends Error { constructor(message: string) { super(message); this.name = 'AuthenticationError'; } } // Custom error class for request timeouts export class TimeoutError extends Error { constructor(message: string) { super(message); this.name = 'TimeoutError'; } } // Default request timeout in milliseconds (30 seconds) const DEFAULT_TIMEOUT_MS = 30000; // Utility function for JSON fetch with credentials and timeout async function fetchJSON( url: string, opts: RequestInit = {}, timeoutMs: number | null = DEFAULT_TIMEOUT_MS ): Promise { const controller = new AbortController(); const timeoutId = timeoutMs && timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : null; try { const res = await fetch(url, { ...opts, credentials: 'include', // Enable cookies for session signal: controller.signal, headers: { 'Content-Type': 'application/json', ...opts.headers, }, }); if (!res.ok) { // Try to parse error message from response body let errorMessage = `${res.status} ${res.statusText}`; let hasServerMessage = false; try { const errorData = await res.json(); // Prefer user-friendly 'message' field, fall back to 'error' if (errorData.message) { errorMessage = errorData.message; hasServerMessage = true; } else if (errorData.error) { errorMessage = errorData.error; hasServerMessage = true; } } catch (e) { // Log parse failure for debugging - server may have returned non-JSON (e.g., HTML error page) console.warn(`Failed to parse error response from ${url}:`, e instanceof Error ? e.message : e); } // Provide helpful message for gateway/proxy errors if (res.status === 502 || res.status === 503 || res.status === 504) { if (!hasServerMessage) { errorMessage = `Server unavailable (${res.status}). If using a reverse proxy, check its configuration.`; } } // Throw appropriate error based on status code if (res.status === 401) { throw new AuthenticationError(errorMessage); } throw new Error(errorMessage); } return res.json(); } catch (error) { // Handle abort/timeout errors if (error instanceof Error && error.name === 'AbortError') { throw new TimeoutError('Request timed out. Check your network connection or proxy configuration.'); } throw error; } finally { if (timeoutId) { clearTimeout(timeoutId); } } } // API functions export const searchBooks = async (query: string): Promise => { if (!query) return []; return fetchJSON(`${API.search}?${query}`); }; // Metadata search response type (internal) interface MetadataSearchResponse { books: MetadataBookData[]; provider: string; query: string; page?: number; total_found?: number; has_more?: boolean; } // Metadata search result with pagination info export interface MetadataSearchResult { books: Book[]; page: number; totalFound: number; hasMore: boolean; } // Search metadata providers and normalize to Book format export const searchMetadata = async ( query: string, limit: number = 40, sort: string = 'relevance', fields: Record = {}, page: number = 1, contentType: string = 'ebook' ): Promise => { const hasFields = Object.values(fields).some(v => v !== '' && v !== false); if (!query && !hasFields) { return { books: [], page: 1, totalFound: 0, hasMore: false }; } const params = new URLSearchParams(); if (query) { params.set('query', query); } params.set('limit', String(limit)); params.set('sort', sort); params.set('page', String(page)); params.set('content_type', contentType); // Add custom search field values Object.entries(fields).forEach(([key, value]) => { if (value !== '' && value !== false) { params.set(key, String(value)); } }); const response = await fetchJSON(`${API.metadataSearch}?${params.toString()}`); return { books: response.books.map(transformMetadataToBook), page: response.page || page, totalFound: response.total_found || 0, hasMore: response.has_more || false, }; }; export const getBookInfo = async (id: string): Promise => { return fetchJSON(`${API.info}?id=${encodeURIComponent(id)}`); }; // Get full book details from a metadata provider export const getMetadataBookInfo = async (provider: string, bookId: string): Promise => { const response = await fetchJSON( `${API_BASE}/metadata/book/${encodeURIComponent(provider)}/${encodeURIComponent(bookId)}` ); return transformMetadataToBook(response); }; export const downloadBook = async (id: string, emailRecipient?: string): Promise => { const params = new URLSearchParams(); params.set('id', id); if (emailRecipient) { params.set('email_recipient', emailRecipient); } await fetchJSON(`${API.download}?${params.toString()}`); }; // Download a specific release (from ReleaseModal) export const downloadRelease = async (release: { source: string; source_id: string; title: string; author?: string; // Author from metadata provider year?: string; // Year from metadata provider format?: string; size?: string; size_bytes?: number; download_url?: string; protocol?: string; indexer?: string; seeders?: number; extra?: Record; preview?: string; // Book cover from metadata provider content_type?: string; // "ebook" or "audiobook" - for directory routing series_name?: string; series_position?: number; subtitle?: string; search_author?: string; email_recipient?: string; }): Promise => { await fetchJSON(`${API_BASE}/releases/download`, { method: 'POST', body: JSON.stringify(release), }); }; export const getStatus = async (): Promise => { return fetchJSON(API.status); }; export const cancelDownload = async (id: string): Promise => { await fetchJSON(`${API.cancelDownload}/${encodeURIComponent(id)}/cancel`, { method: 'DELETE' }); }; export const clearCompleted = async (): Promise => { await fetchJSON(`${API_BASE}/queue/clear`, { method: 'DELETE' }); }; export const getConfig = async (): Promise => { return fetchJSON(API.config); }; // Authentication functions export const login = async (credentials: LoginCredentials): Promise => { return fetchJSON(API.login, { method: 'POST', body: JSON.stringify(credentials), }); }; export const logout = async (): Promise => { return fetchJSON(API.logout, { method: 'POST', }); }; export const checkAuth = async (): Promise => { return fetchJSON(API.authCheck); }; // Settings API functions export const getSettings = async (): Promise => { return fetchJSON(API.settings); }; export const updateSettings = async ( tabName: string, values: Record ): Promise => { return fetchJSON(`${API.settings}/${tabName}`, { method: 'PUT', body: JSON.stringify(values), }); }; export const executeSettingsAction = async ( tabName: string, actionKey: string, currentValues?: Record ): Promise => { return fetchJSON(`${API.settings}/${tabName}/action/${actionKey}`, { method: 'POST', body: currentValues ? JSON.stringify(currentValues) : undefined, }); }; // Onboarding API functions export interface OnboardingStepCondition { field: string; value: unknown; } export interface OnboardingStep { id: string; title: string; tab: string; fields: import('../types/settings').SettingsField[]; showWhen?: OnboardingStepCondition[]; // Array of conditions (all must be true) optional?: boolean; } export interface OnboardingConfig { steps: OnboardingStep[]; values: Record; complete: boolean; } export const getOnboarding = async (): Promise => { return fetchJSON(`${API_BASE}/onboarding`); }; export const saveOnboarding = async ( values: Record ): Promise<{ success: boolean; message: string }> => { return fetchJSON<{ success: boolean; message: string }>(`${API_BASE}/onboarding`, { method: 'POST', body: JSON.stringify(values), }); }; export const skipOnboarding = async (): Promise<{ success: boolean; message: string }> => { return fetchJSON<{ success: boolean; message: string }>(`${API_BASE}/onboarding/skip`, { method: 'POST', }); }; // Release source API functions // Get available release sources from plugin registry export const getReleaseSources = async (): Promise => { return fetchJSON(`${API_BASE}/release-sources`); }; // Search for releases of a book export const getReleases = async ( provider: string, bookId: string, source?: string, title?: string, author?: string, expandSearch?: boolean, languages?: string[], contentType?: string, manualQuery?: string, indexers?: string[] ): Promise => { const params = new URLSearchParams({ provider, book_id: bookId, }); if (source) { params.set('source', source); } if (title) { params.set('title', title); } if (author) { params.set('author', author); } if (expandSearch) { params.set('expand_search', 'true'); } if (languages && languages.length > 0) { params.set('languages', languages.join(',')); } if (contentType) { params.set('content_type', contentType); } if (manualQuery) { params.set('manual_query', manualQuery); } if (indexers && indexers.length > 0) { params.set('indexers', indexers.join(',')); } // Let the backend control timeouts for release searches (can be long-running). return fetchJSON(`${API_BASE}/releases?${params.toString()}`, {}, null); };