Add series fields to audiobooks and update related logic

Introduces 'series' and 'seriesPart' fields to the Audiobook model and database schema. Updates API routes, file organization, and path template utilities to support series metadata. Enhances chapter merging logic, improves notification backend testing, and expands test coverage for admin and API routes.
This commit is contained in:
kikootwo
2026-01-22 15:56:55 -05:00
parent dc7e557694
commit 31bca0052f
105 changed files with 10384 additions and 75 deletions
+109
View File
@@ -0,0 +1,109 @@
/**
* Component: Audiobooks Hooks Tests
* Documentation: documentation/frontend/components.md
*/
// @vitest-environment jsdom
import React from 'react';
import { render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const useSWRMock = vi.hoisted(() => vi.fn());
const authenticatedFetcherMock = vi.hoisted(() => vi.fn());
vi.mock('swr', () => ({
default: useSWRMock,
}));
vi.mock('@/lib/utils/api', () => ({
authenticatedFetcher: authenticatedFetcherMock,
}));
const HookProbe = ({ label, value }: { label: string; value: any }) => (
<div data-testid={label}>{JSON.stringify(value)}</div>
);
describe('useAudiobooks hooks', () => {
beforeEach(() => {
useSWRMock.mockReset();
authenticatedFetcherMock.mockReset();
vi.resetModules();
});
it('builds the popular audiobooks endpoint and returns data', async () => {
useSWRMock.mockReturnValue({
data: { audiobooks: [{ asin: 'a1' }], totalPages: 3, totalCount: 30, hasMore: true },
error: null,
isLoading: false,
});
const { useAudiobooks } = await import('@/lib/hooks/useAudiobooks');
const Probe = () => {
const result = useAudiobooks('popular', 10, 2);
return <HookProbe label="popular" value={result} />;
};
render(<Probe />);
expect(useSWRMock).toHaveBeenCalledWith(
'/api/audiobooks/popular?page=2&limit=10',
authenticatedFetcherMock,
expect.objectContaining({ dedupingInterval: 60000 })
);
const parsed = JSON.parse(screen.getByTestId('popular').textContent || '{}');
expect(parsed.audiobooks).toHaveLength(1);
expect(parsed.totalPages).toBe(3);
expect(parsed.hasMore).toBe(true);
});
it('skips search when the query is empty', async () => {
useSWRMock.mockReturnValue({ data: null, error: null, isLoading: false });
const { useSearch } = await import('@/lib/hooks/useAudiobooks');
const Probe = () => {
const result = useSearch('', 1);
return <HookProbe label="search" value={result} />;
};
render(<Probe />);
expect(useSWRMock).toHaveBeenCalledWith(
null,
authenticatedFetcherMock,
expect.objectContaining({ dedupingInterval: 30000 })
);
const parsed = JSON.parse(screen.getByTestId('search').textContent || '{}');
expect(parsed.isLoading).toBeFalsy();
});
it('requests audiobook details when an ASIN is provided', async () => {
useSWRMock.mockReturnValue({
data: { audiobook: { asin: 'a2', title: 'Details' } },
error: null,
isLoading: false,
});
const { useAudiobookDetails } = await import('@/lib/hooks/useAudiobooks');
const Probe = () => {
const result = useAudiobookDetails('a2');
return <HookProbe label="details" value={result} />;
};
render(<Probe />);
expect(useSWRMock).toHaveBeenCalledWith(
'/api/audiobooks/a2',
authenticatedFetcherMock,
expect.objectContaining({ dedupingInterval: 300000 })
);
const parsed = JSON.parse(screen.getByTestId('details').textContent || '{}');
expect(parsed.audiobook.asin).toBe('a2');
});
});
+220
View File
@@ -0,0 +1,220 @@
/**
* Component: Requests Hooks Tests
* Documentation: documentation/frontend/components.md
*/
// @vitest-environment jsdom
import React from 'react';
import { act, render } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const useAuthMock = vi.hoisted(() => vi.fn());
const useSWRMock = vi.hoisted(() => vi.fn());
const mutateMock = vi.hoisted(() => vi.fn());
const fetchWithAuthMock = vi.hoisted(() => vi.fn());
vi.mock('@/contexts/AuthContext', () => ({
useAuth: () => useAuthMock(),
}));
vi.mock('swr', () => ({
default: useSWRMock,
mutate: mutateMock,
}));
vi.mock('@/lib/utils/api', () => ({
fetchWithAuth: fetchWithAuthMock,
}));
const renderHookValue = <T,>(hook: () => T) => {
let value: T;
function Probe() {
value = hook();
return null;
}
render(<Probe />);
return value!;
};
const makeResponse = (body: any, ok = true) => ({
ok,
json: async () => body,
});
describe('useRequests hooks', () => {
beforeEach(() => {
useAuthMock.mockReset();
useSWRMock.mockReset();
mutateMock.mockReset();
fetchWithAuthMock.mockReset();
vi.resetModules();
});
it('builds request list endpoints when authenticated', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
useSWRMock.mockReturnValue({ data: { requests: [] }, error: null, isLoading: false });
const { useRequests } = await import('@/lib/hooks/useRequests');
renderHookValue(() => useRequests('pending', 25, true));
expect(useSWRMock).toHaveBeenCalledWith(
'/api/requests?status=pending&limit=25&myOnly=true',
expect.any(Function),
expect.objectContaining({ refreshInterval: 5000 })
);
});
it('builds request detail endpoints when authenticated', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
useSWRMock.mockReturnValue({ data: { request: { id: 'req-1' } }, error: null, isLoading: false });
const { useRequest } = await import('@/lib/hooks/useRequests');
renderHookValue(() => useRequest('req-1'));
expect(useSWRMock).toHaveBeenCalledWith(
'/api/requests/req-1',
expect.any(Function),
expect.objectContaining({ refreshInterval: 3000 })
);
});
it('creates requests and triggers revalidation', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
fetchWithAuthMock.mockResolvedValueOnce(makeResponse({ request: { id: 'req-1' } }));
const { useCreateRequest } = await import('@/lib/hooks/useRequests');
const hook = renderHookValue(() => useCreateRequest());
await act(async () => {
const result = await hook.createRequest({ asin: 'a1', title: 'Book', author: 'Author' } as any);
expect(result.id).toBe('req-1');
});
expect(fetchWithAuthMock).toHaveBeenCalledWith(
'/api/requests',
expect.objectContaining({ method: 'POST' })
);
expect(mutateMock).toHaveBeenCalled();
});
it('surfaces specific create request errors', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
fetchWithAuthMock.mockResolvedValueOnce(makeResponse({ error: 'AlreadyAvailable' }, false));
const { useCreateRequest } = await import('@/lib/hooks/useRequests');
const hook = renderHookValue(() => useCreateRequest());
await act(async () => {
await expect(
hook.createRequest({ asin: 'a1', title: 'Book', author: 'Author' } as any)
).rejects.toThrow('already in your Plex library');
});
});
it('cancels requests via the API', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
fetchWithAuthMock.mockResolvedValueOnce(makeResponse({ request: { id: 'req-2' } }));
const { useCancelRequest } = await import('@/lib/hooks/useRequests');
const hook = renderHookValue(() => useCancelRequest());
await act(async () => {
await hook.cancelRequest('req-2');
});
expect(fetchWithAuthMock).toHaveBeenCalledWith(
'/api/requests/req-2',
expect.objectContaining({ method: 'PATCH' })
);
});
it('triggers manual search for requests', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
fetchWithAuthMock.mockResolvedValueOnce(makeResponse({ request: { id: 'req-3' } }));
const { useManualSearch } = await import('@/lib/hooks/useRequests');
const hook = renderHookValue(() => useManualSearch());
await act(async () => {
await hook.triggerManualSearch('req-3');
});
expect(fetchWithAuthMock).toHaveBeenCalledWith(
'/api/requests/req-3/manual-search',
expect.objectContaining({ method: 'POST' })
);
});
it('searches torrents interactively for a request', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
fetchWithAuthMock.mockResolvedValueOnce(makeResponse({ results: [{ guid: 't1' }] }));
const { useInteractiveSearch } = await import('@/lib/hooks/useRequests');
const hook = renderHookValue(() => useInteractiveSearch());
await act(async () => {
const results = await hook.searchTorrents('req-4', 'Custom');
expect(results).toHaveLength(1);
});
expect(fetchWithAuthMock).toHaveBeenCalledWith(
'/api/requests/req-4/interactive-search',
expect.objectContaining({ method: 'POST' })
);
});
it('selects torrents for existing requests', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
fetchWithAuthMock.mockResolvedValueOnce(makeResponse({ request: { id: 'req-5' } }));
const { useSelectTorrent } = await import('@/lib/hooks/useRequests');
const hook = renderHookValue(() => useSelectTorrent());
await act(async () => {
await hook.selectTorrent('req-5', { title: 'Torrent' });
});
expect(fetchWithAuthMock).toHaveBeenCalledWith(
'/api/requests/req-5/select-torrent',
expect.objectContaining({ method: 'POST' })
);
});
it('searches torrents for new requests', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
fetchWithAuthMock.mockResolvedValueOnce(makeResponse({ results: [{ guid: 't2' }] }));
const { useSearchTorrents } = await import('@/lib/hooks/useRequests');
const hook = renderHookValue(() => useSearchTorrents());
await act(async () => {
const results = await hook.searchTorrents('Title', 'Author', 'asin');
expect(results).toHaveLength(1);
});
expect(fetchWithAuthMock).toHaveBeenCalledWith(
'/api/audiobooks/search-torrents',
expect.objectContaining({ method: 'POST' })
);
});
it('requests torrents with audiobook payloads', async () => {
useAuthMock.mockReturnValue({ accessToken: 'token' });
fetchWithAuthMock.mockResolvedValueOnce(makeResponse({ request: { id: 'req-6' } }));
const { useRequestWithTorrent } = await import('@/lib/hooks/useRequests');
const hook = renderHookValue(() => useRequestWithTorrent());
await act(async () => {
await hook.requestWithTorrent({ asin: 'a1', title: 'Book', author: 'Author' } as any, { title: 'Torrent' });
});
expect(fetchWithAuthMock).toHaveBeenCalledWith(
'/api/audiobooks/request-with-torrent',
expect.objectContaining({ method: 'POST' })
);
});
});
+107
View File
@@ -0,0 +1,107 @@
/**
* Component: API Utility Tests
* Documentation: documentation/frontend/routing-auth.md
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const isTokenExpiredMock = vi.hoisted(() => vi.fn());
vi.mock('@/lib/utils/jwt-client', () => ({
isTokenExpired: isTokenExpiredMock,
}));
describe('fetchWithAuth', () => {
let locationStub: { href: string; pathname: string };
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
isTokenExpiredMock.mockReturnValue(false);
locationStub = { href: 'http://localhost/', pathname: '/' };
vi.stubGlobal('location', locationStub);
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('adds Authorization header when access token is available', async () => {
const fetchMock = vi.fn().mockResolvedValue({ status: 200, ok: true });
vi.stubGlobal('fetch', fetchMock);
localStorage.setItem('accessToken', 'access-token');
const { fetchWithAuth } = await import('@/lib/utils/api');
await fetchWithAuth('/api/test');
expect(fetchMock).toHaveBeenCalledWith(
'/api/test',
expect.objectContaining({
headers: expect.objectContaining({
Authorization: 'Bearer access-token',
}),
})
);
});
it('refreshes the access token and retries after a 401 response', async () => {
const fetchMock = vi.fn().mockImplementation((url: string) => {
if (url === '/api/auth/refresh') {
return Promise.resolve({
ok: true,
status: 200,
json: async () => ({ accessToken: 'new-token' }),
});
}
return Promise.resolve({
ok: url !== '/api/test' || fetchMock.mock.calls.length > 1,
status: url === '/api/test' && fetchMock.mock.calls.length === 1 ? 401 : 200,
});
});
vi.stubGlobal('fetch', fetchMock);
localStorage.setItem('accessToken', 'old-token');
localStorage.setItem('refreshToken', 'refresh-token');
const { fetchWithAuth } = await import('@/lib/utils/api');
await fetchWithAuth('/api/test');
expect(fetchMock).toHaveBeenCalledTimes(3);
expect(fetchMock).toHaveBeenNthCalledWith(
3,
'/api/test',
expect.objectContaining({
headers: expect.objectContaining({
Authorization: 'Bearer new-token',
}),
})
);
expect(localStorage.getItem('accessToken')).toBe('new-token');
});
it('logs out when refresh fails', async () => {
const fetchMock = vi.fn().mockResolvedValue({ status: 401, ok: false });
vi.stubGlobal('fetch', fetchMock);
localStorage.setItem('accessToken', 'old-token');
localStorage.setItem('refreshToken', 'expired-refresh');
localStorage.setItem('user', JSON.stringify({ id: 'user-1' }));
isTokenExpiredMock.mockImplementation((token: string) => token.startsWith('expired'));
locationStub.pathname = '/requests';
locationStub.href = 'http://localhost/requests';
const { fetchWithAuth } = await import('@/lib/utils/api');
await fetchWithAuth('/api/test');
expect(localStorage.getItem('accessToken')).toBeNull();
expect(localStorage.getItem('refreshToken')).toBeNull();
expect(localStorage.getItem('user')).toBeNull();
expect(window.location.href).toContain('/login?redirect=%2Frequests');
});
});
+3 -1
View File
@@ -316,7 +316,9 @@ describe('getValidVariables', () => {
expect(variables).toContain('narrator');
expect(variables).toContain('asin');
expect(variables).toContain('year');
expect(variables).toHaveLength(5);
expect(variables).toContain('series');
expect(variables).toContain('seriesPart');
expect(variables).toHaveLength(7);
});
it('should return a new array each time (not mutate original)', () => {