mirror of
https://github.com/kikootwo/ReadMeABook.git
synced 2026-06-03 04:40:09 +00:00
Add Deluge integration; revamp admin Jobs & Logs UI
Introduce Deluge download client service and tests, remove obsolete rdtclient service, and update qbittorrent integration/tests and download-client interfaces/manager. Large UI refactor for admin pages: Jobs and Logs were redesigned to be responsive (mobile card views + desktop tables), improved headers, dialogs, controls, and better status/detail rendering. Also updated DownloadClient components (card, management, modal), organize-files processor, audible-series integration, and related unit tests to align with integration changes. Minor UX and accessibility tweaks, cron handling/validation adjustments, and a few formatting/cleanup fixes throughout.
This commit is contained in:
@@ -152,8 +152,8 @@ describe('Admin settings core routes', () => {
|
||||
it('rejects invalid download client types', async () => {
|
||||
const request = {
|
||||
json: vi.fn().mockResolvedValue({
|
||||
type: 'deluge',
|
||||
url: 'http://deluge',
|
||||
type: 'rtorrent',
|
||||
url: 'http://rtorrent',
|
||||
}),
|
||||
};
|
||||
|
||||
|
||||
@@ -182,7 +182,7 @@ describe('Setup test routes', () => {
|
||||
it('rejects invalid download client type', async () => {
|
||||
const { POST } = await import('@/app/api/setup/test-download-client/route');
|
||||
const response = await POST({
|
||||
json: vi.fn().mockResolvedValue({ type: 'deluge', url: 'http://deluge' }),
|
||||
json: vi.fn().mockResolvedValue({ type: 'rtorrent', url: 'http://rtorrent' }),
|
||||
} as any);
|
||||
const payload = await response.json();
|
||||
|
||||
|
||||
@@ -55,9 +55,9 @@ describe('AdminJobsPage', () => {
|
||||
|
||||
render(<AdminJobsPage />);
|
||||
|
||||
expect(await screen.findByText('Library Scan')).toBeInTheDocument();
|
||||
expect((await screen.findAllByText('Library Scan'))[0]).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Trigger Now/i }));
|
||||
fireEvent.click(screen.getAllByRole('button', { name: /Trigger Now/i })[0]);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Trigger Job' }));
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -88,7 +88,7 @@ describe('AdminJobsPage', () => {
|
||||
|
||||
render(<AdminJobsPage />);
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));
|
||||
fireEvent.click((await screen.findAllByRole('button', { name: 'Edit' }))[0]);
|
||||
fireEvent.click(screen.getByRole('radio', { name: /Every 2 hours/i }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
|
||||
|
||||
|
||||
@@ -68,14 +68,14 @@ describe('AdminLogsPage', () => {
|
||||
render(<AdminLogsPage />);
|
||||
|
||||
expect(await screen.findByText('System Logs')).toBeInTheDocument();
|
||||
expect(screen.getByText('Search Book')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Search Book')[0]).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Show Details' }));
|
||||
expect(screen.getByText('Event Log')).toBeInTheDocument();
|
||||
expect(screen.getByText('Job Result')).toBeInTheDocument();
|
||||
expect(screen.getByText('Error')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Show Details' })[0]);
|
||||
expect(screen.getAllByText('Event Log')[0]).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Job Result')[0]).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Error')[0]).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Hide Details' }));
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Hide Details' })[0]);
|
||||
expect(screen.queryByText('Event Log')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -122,6 +122,6 @@ describe('AdminLogsPage', () => {
|
||||
|
||||
render(<AdminLogsPage />);
|
||||
|
||||
expect(await screen.findByText('No logs found')).toBeInTheDocument();
|
||||
expect((await screen.findAllByText('No logs found'))[0]).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -158,9 +158,9 @@ describe('AdminUsersPage', () => {
|
||||
|
||||
render(<AdminUsersPage />);
|
||||
|
||||
expect(await screen.findByText('Full Access')).toBeDefined();
|
||||
expect(screen.getByText('Manual')).toBeDefined();
|
||||
expect(screen.getByText('Auto-Approve')).toBeDefined();
|
||||
expect((await screen.findAllByText('Full Access'))[0]).toBeDefined();
|
||||
expect(screen.getAllByText('Manual')[0]).toBeDefined();
|
||||
expect(screen.getAllByText('Auto-Approve')[0]).toBeDefined();
|
||||
});
|
||||
|
||||
it('shows Global Default badge when global auto-approve is on', async () => {
|
||||
@@ -171,7 +171,7 @@ describe('AdminUsersPage', () => {
|
||||
|
||||
render(<AdminUsersPage />);
|
||||
|
||||
expect(await screen.findByText('Global Default')).toBeDefined();
|
||||
expect((await screen.findAllByText('Global Default'))[0]).toBeDefined();
|
||||
});
|
||||
|
||||
it('opens user permissions modal and shows admin lock state for both permissions', async () => {
|
||||
@@ -184,7 +184,7 @@ describe('AdminUsersPage', () => {
|
||||
render(<AdminUsersPage />);
|
||||
|
||||
// Click the permissions badge to open modal
|
||||
fireEvent.click(await screen.findByText('Full Access'));
|
||||
fireEvent.click((await screen.findAllByText('Full Access'))[0]);
|
||||
|
||||
// Modal should show user info and the locked state for both permissions
|
||||
expect(await screen.findByText('User Permissions')).toBeDefined();
|
||||
@@ -205,7 +205,7 @@ describe('AdminUsersPage', () => {
|
||||
render(<AdminUsersPage />);
|
||||
|
||||
// Click the Manual badge to open permissions modal
|
||||
fireEvent.click(await screen.findByText('Manual'));
|
||||
fireEvent.click((await screen.findAllByText('Manual'))[0]);
|
||||
|
||||
// Find and click the auto-approve toggle switch inside the modal
|
||||
const toggle = await screen.findByRole('switch', { name: 'Auto-Approve Requests' });
|
||||
@@ -231,7 +231,7 @@ describe('AdminUsersPage', () => {
|
||||
render(<AdminUsersPage />);
|
||||
|
||||
// Click the Manual badge to open permissions modal
|
||||
fireEvent.click(await screen.findByText('Manual'));
|
||||
fireEvent.click((await screen.findAllByText('Manual'))[0]);
|
||||
|
||||
// Find and click the interactive search toggle switch inside the modal
|
||||
const toggle = await screen.findByRole('switch', { name: 'Interactive Search Access' });
|
||||
@@ -255,7 +255,7 @@ describe('AdminUsersPage', () => {
|
||||
render(<AdminUsersPage />);
|
||||
|
||||
// Click the Global Default badge
|
||||
fireEvent.click(await screen.findByText('Global Default'));
|
||||
fireEvent.click((await screen.findAllByText('Global Default'))[0]);
|
||||
|
||||
// Modal should show the global override message for both
|
||||
expect(await screen.findByText('Controlled by global auto-approve setting')).toBeDefined();
|
||||
@@ -288,7 +288,7 @@ describe('AdminUsersPage', () => {
|
||||
|
||||
render(<AdminUsersPage />);
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Edit Role' }));
|
||||
fireEvent.click((await screen.findAllByRole('button', { name: 'Edit Role' }))[0]);
|
||||
fireEvent.click(screen.getByRole('radio', { name: /Admin/i }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
|
||||
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
/**
|
||||
* Component: Deluge Integration Service Tests
|
||||
* Documentation: documentation/phase3/download-clients.md
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { DelugeService, getDelugeService, invalidateDelugeService } from '@/lib/integrations/deluge.service';
|
||||
|
||||
const clientMock = vi.hoisted(() => ({
|
||||
post: vi.fn(),
|
||||
}));
|
||||
|
||||
const axiosMock = vi.hoisted(() => ({
|
||||
create: vi.fn(() => clientMock),
|
||||
get: vi.fn(),
|
||||
isAxiosError: (error: any) => Boolean(error?.isAxiosError),
|
||||
}));
|
||||
|
||||
const parseTorrentMock = vi.hoisted(() => vi.fn());
|
||||
const configServiceMock = vi.hoisted(() => ({
|
||||
get: vi.fn(),
|
||||
}));
|
||||
|
||||
const downloadClientManagerMock = vi.hoisted(() => ({
|
||||
getClientForProtocol: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('axios', () => ({ default: axiosMock, ...axiosMock }));
|
||||
vi.mock('parse-torrent', () => ({ default: parseTorrentMock }));
|
||||
vi.mock('@/lib/services/config.service', () => ({
|
||||
getConfigService: vi.fn(async () => configServiceMock),
|
||||
}));
|
||||
vi.mock('@/lib/services/download-client-manager.service', () => ({
|
||||
getDownloadClientManager: () => downloadClientManagerMock,
|
||||
}));
|
||||
|
||||
/** Helper: simulate a successful Deluge login + daemon connected response */
|
||||
function mockLoginSuccess() {
|
||||
// auth.login
|
||||
clientMock.post.mockResolvedValueOnce({
|
||||
data: { result: true, error: null, id: 1 },
|
||||
headers: { 'set-cookie': ['_session_id=abc123; Path=/;'] },
|
||||
});
|
||||
// web.connected (daemon already connected)
|
||||
clientMock.post.mockResolvedValueOnce({
|
||||
data: { result: true, error: null, id: 2 },
|
||||
headers: {},
|
||||
});
|
||||
}
|
||||
|
||||
/** Helper: simulate login + force daemon reconnection (get_hosts -> connect -> verify) */
|
||||
function mockLoginForceReconnect() {
|
||||
// auth.login
|
||||
clientMock.post.mockResolvedValueOnce({
|
||||
data: { result: true, error: null, id: 1 },
|
||||
headers: { 'set-cookie': ['_session_id=abc123; Path=/;'] },
|
||||
});
|
||||
// web.get_hosts
|
||||
mockRpc([['host-1', '127.0.0.1', 58846, '']]);
|
||||
// web.connect
|
||||
mockRpc(null);
|
||||
// web.connected (verify)
|
||||
mockRpc(true);
|
||||
}
|
||||
|
||||
/** Helper: simulate a Deluge RPC response */
|
||||
function mockRpc(result: any, error: any = null) {
|
||||
clientMock.post.mockResolvedValueOnce({
|
||||
data: { result, error, id: 1 },
|
||||
headers: {},
|
||||
});
|
||||
}
|
||||
|
||||
describe('DelugeService', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
clientMock.post.mockReset();
|
||||
axiosMock.get.mockReset();
|
||||
parseTorrentMock.mockReset();
|
||||
configServiceMock.get.mockReset();
|
||||
downloadClientManagerMock.getClientForProtocol.mockReset();
|
||||
invalidateDelugeService();
|
||||
});
|
||||
|
||||
it('authenticates and stores session cookie', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'mypass');
|
||||
|
||||
// Mock login (auth.login + web.connected check)
|
||||
mockLoginSuccess();
|
||||
|
||||
const result = await service.testConnection();
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('fails authentication with wrong password', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'bad');
|
||||
|
||||
clientMock.post.mockResolvedValueOnce({
|
||||
data: { result: false, error: null, id: 1 },
|
||||
headers: {},
|
||||
});
|
||||
|
||||
const result = await service.testConnection();
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('authenticate');
|
||||
});
|
||||
|
||||
it('force reconnects daemon on error code 2 (Unknown method)', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
// First RPC returns error code 2 (daemon disconnected)
|
||||
mockRpc(null, { code: 2, message: 'Unknown method' });
|
||||
// rpc() retries via login(true) -> force reconnect
|
||||
mockLoginForceReconnect();
|
||||
// Retried core.get_torrent_status succeeds
|
||||
mockRpc({
|
||||
name: 'Test Torrent', total_size: 1000, total_done: 1000, progress: 100,
|
||||
state: 'Seeding', download_payload_rate: 0, eta: 0,
|
||||
label: 'readmeabook', save_path: '/downloads', time_added: 1700000000,
|
||||
is_finished: true, seeding_time: 3600, ratio: 1.5, message: '',
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
expect(info).not.toBeNull();
|
||||
expect(info!.name).toBe('Test Torrent');
|
||||
expect(info!.status).toBe('seeding');
|
||||
});
|
||||
|
||||
it('does not retry error code 2 more than once', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
// First RPC returns error code 2
|
||||
mockRpc(null, { code: 2, message: 'Unknown method' });
|
||||
// Force reconnect succeeds
|
||||
mockLoginForceReconnect();
|
||||
// Retried RPC also returns error code 2 (persistent failure) — retried=true, so no more retries
|
||||
mockRpc(null, { code: 2, message: 'Unknown method' });
|
||||
|
||||
const result = await (service as any).rpc('core.get_torrent_status', ['abc123', ['name']]);
|
||||
expect(result.error).toEqual({ code: 2, message: 'Unknown method' });
|
||||
});
|
||||
|
||||
it('returns connection errors for refused connections', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
|
||||
clientMock.post.mockRejectedValueOnce({
|
||||
isAxiosError: true,
|
||||
code: 'ECONNREFUSED',
|
||||
message: 'refused',
|
||||
});
|
||||
|
||||
const result = await service.testConnection();
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('Connection refused');
|
||||
});
|
||||
|
||||
it('maps Deluge status strings to unified DownloadStatus', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
const states: Record<string, string> = {
|
||||
'Downloading': 'downloading',
|
||||
'Seeding': 'seeding',
|
||||
'Paused': 'paused',
|
||||
'Checking': 'checking',
|
||||
'Queued': 'queued',
|
||||
'Error': 'failed',
|
||||
'Moving': 'downloading',
|
||||
'UnknownState': 'downloading', // fallback
|
||||
};
|
||||
|
||||
for (const [delugeState, expectedStatus] of Object.entries(states)) {
|
||||
clientMock.post.mockResolvedValueOnce({
|
||||
data: {
|
||||
result: {
|
||||
name: 'Test', total_size: 1000, total_done: 500, progress: 50,
|
||||
state: delugeState, download_payload_rate: 100, eta: 60,
|
||||
label: 'readmeabook', save_path: '/downloads', time_added: 1700000000,
|
||||
is_finished: false, seeding_time: 0, ratio: 0, message: '',
|
||||
},
|
||||
error: null,
|
||||
id: 1,
|
||||
},
|
||||
headers: {},
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
expect(info).not.toBeNull();
|
||||
expect(info!.status).toBe(expectedStatus);
|
||||
}
|
||||
});
|
||||
|
||||
it('normalizes progress from 0-100 to 0-1', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
mockRpc({
|
||||
name: 'Audiobook', total_size: 1000, total_done: 420, progress: 42,
|
||||
state: 'Downloading', download_payload_rate: 50, eta: 120,
|
||||
label: 'readmeabook', save_path: '/downloads', time_added: 1700000000,
|
||||
is_finished: false, seeding_time: 0, ratio: 0, message: '',
|
||||
});
|
||||
|
||||
const info = await service.getDownload('hash1');
|
||||
expect(info).not.toBeNull();
|
||||
expect(info!.progress).toBeCloseTo(0.42);
|
||||
expect(info!.bytesDownloaded).toBe(420);
|
||||
});
|
||||
|
||||
it('returns null when torrent is not found (empty result)', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
// Mock 4 attempts (initial + 3 retries) returning empty results
|
||||
for (let i = 0; i < 4; i++) {
|
||||
mockRpc({});
|
||||
}
|
||||
|
||||
const info = await service.getDownload('missing-hash');
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects empty download URLs', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
await expect(service.addDownload('')).rejects.toThrow('Invalid download URL');
|
||||
});
|
||||
|
||||
it('extracts info hash from magnet links', () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
const hash = (service as any).extractHashFromMagnet(
|
||||
'magnet:?xt=urn:btih:0123456789ABCDEF0123456789ABCDEF01234567'
|
||||
);
|
||||
expect(hash).toBe('0123456789abcdef0123456789abcdef01234567');
|
||||
expect((service as any).extractHashFromMagnet('magnet:?xt=urn:btih:')).toBeNull();
|
||||
});
|
||||
|
||||
it('adds magnet links successfully', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
// Mock: check duplicate (not found)
|
||||
mockRpc({});
|
||||
// Mock: add_torrent_magnet
|
||||
mockRpc('0123456789abcdef0123456789abcdef01234567');
|
||||
// Mock: set_torrent_options (disable seed limits)
|
||||
mockRpc(null);
|
||||
// Mock: label.add (ensure label)
|
||||
mockRpc(null);
|
||||
// Mock: label.set_torrent
|
||||
mockRpc(null);
|
||||
|
||||
const hash = await service.addDownload(
|
||||
'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567'
|
||||
);
|
||||
expect(hash).toBe('0123456789abcdef0123456789abcdef01234567');
|
||||
});
|
||||
|
||||
it('skips adding duplicate magnet links', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
// Mock: duplicate found
|
||||
mockRpc({ name: 'Existing Audiobook' });
|
||||
|
||||
const hash = await service.addDownload(
|
||||
'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567'
|
||||
);
|
||||
expect(hash).toBe('0123456789abcdef0123456789abcdef01234567');
|
||||
// Only 1 RPC call (the duplicate check), no add call
|
||||
expect(clientMock.post).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('throws when Deluge rejects a magnet link', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
mockRpc({}); // not duplicate
|
||||
mockRpc(null, { message: 'rejected' }); // add returns null (failure)
|
||||
|
||||
await expect(service.addDownload(
|
||||
'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567'
|
||||
)).rejects.toThrow('Deluge rejected magnet link');
|
||||
});
|
||||
|
||||
it('adds torrent files after parsing', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
axiosMock.get.mockResolvedValueOnce({ data: Buffer.from('torrent-data') });
|
||||
parseTorrentMock.mockResolvedValueOnce({ infoHash: 'hash-1', name: 'Book' });
|
||||
|
||||
mockRpc({}); // not duplicate
|
||||
mockRpc('hash-1'); // add_torrent_file
|
||||
mockRpc(null); // set_torrent_options
|
||||
mockRpc(null); // label.add
|
||||
mockRpc(null); // label.set_torrent
|
||||
|
||||
const hash = await service.addDownload('http://example.com/file.torrent');
|
||||
expect(hash).toBe('hash-1');
|
||||
});
|
||||
|
||||
it('follows redirect to magnet link', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
axiosMock.get.mockRejectedValueOnce({
|
||||
isAxiosError: true,
|
||||
response: { status: 302, headers: { location: 'magnet:?xt=urn:btih:abcdef0123456789abcdef0123456789abcdef01' } },
|
||||
});
|
||||
|
||||
// Magnet duplicate check
|
||||
mockRpc({});
|
||||
mockRpc('abcdef0123456789abcdef0123456789abcdef01');
|
||||
mockRpc(null); // set_torrent_options
|
||||
mockRpc(null); // label.add
|
||||
mockRpc(null); // label.set_torrent
|
||||
|
||||
const hash = await service.addDownload('http://example.com/file.torrent');
|
||||
expect(hash).toBe('abcdef0123456789abcdef0123456789abcdef01');
|
||||
});
|
||||
|
||||
it('throws for invalid redirect locations', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
axiosMock.get.mockRejectedValueOnce({
|
||||
isAxiosError: true,
|
||||
response: { status: 302, headers: { location: 'ftp://bad' } },
|
||||
});
|
||||
|
||||
await expect(service.addDownload('http://example.com/file.torrent')).rejects.toThrow('Invalid redirect location');
|
||||
});
|
||||
|
||||
it('throws when torrent file parsing fails', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
axiosMock.get.mockResolvedValueOnce({ data: Buffer.from('bad-data') });
|
||||
parseTorrentMock.mockRejectedValueOnce(new Error('bad torrent'));
|
||||
|
||||
await expect(service.addDownload('http://example.com/file.torrent')).rejects.toThrow('Invalid .torrent file');
|
||||
});
|
||||
|
||||
it('pauses and resumes torrents', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
mockRpc(null);
|
||||
await service.pauseDownload('hash-1');
|
||||
|
||||
mockRpc(null);
|
||||
await service.resumeDownload('hash-1');
|
||||
|
||||
// Verify pause used array of hashes
|
||||
const pauseCall = clientMock.post.mock.calls[0];
|
||||
expect(pauseCall[1].method).toBe('core.pause_torrent');
|
||||
expect(pauseCall[1].params).toEqual([['hash-1']]);
|
||||
|
||||
// Verify resume used array of hashes
|
||||
const resumeCall = clientMock.post.mock.calls[1];
|
||||
expect(resumeCall[1].method).toBe('core.resume_torrent');
|
||||
expect(resumeCall[1].params).toEqual([['hash-1']]);
|
||||
});
|
||||
|
||||
it('deletes torrents with correct parameters', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
mockRpc(null);
|
||||
await service.deleteDownload('hash-1', true);
|
||||
|
||||
const deleteCall = clientMock.post.mock.calls[0];
|
||||
expect(deleteCall[1].method).toBe('core.remove_torrent');
|
||||
expect(deleteCall[1].params).toEqual(['hash-1', true]);
|
||||
});
|
||||
|
||||
it('returns labels from Label plugin', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
mockRpc(['readmeabook', 'movies', 'tv']);
|
||||
|
||||
const categories = await service.getCategories();
|
||||
expect(categories).toEqual(['readmeabook', 'movies', 'tv']);
|
||||
});
|
||||
|
||||
it('returns empty array when Label plugin is not available', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
(service as any).sessionCookie = '_session_id=abc';
|
||||
|
||||
clientMock.post.mockRejectedValueOnce(new Error('Unknown method'));
|
||||
|
||||
const categories = await service.getCategories();
|
||||
expect(categories).toEqual([]);
|
||||
});
|
||||
|
||||
it('postProcess is a no-op', async () => {
|
||||
const service = new DelugeService('http://deluge', '', 'pass');
|
||||
await expect(service.postProcess('hash-1')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
describe('singleton getDelugeService()', () => {
|
||||
it('throws when no Deluge client is configured', async () => {
|
||||
downloadClientManagerMock.getClientForProtocol.mockResolvedValue(null);
|
||||
await expect(getDelugeService()).rejects.toThrow('Deluge is not configured');
|
||||
});
|
||||
|
||||
it('throws when configured client is not deluge type', async () => {
|
||||
downloadClientManagerMock.getClientForProtocol.mockResolvedValue({
|
||||
id: 'c1', type: 'qbittorrent', name: 'qB', enabled: true,
|
||||
url: 'http://qb', password: 'pass', disableSSLVerify: false,
|
||||
remotePathMappingEnabled: false,
|
||||
});
|
||||
configServiceMock.get.mockResolvedValue('/downloads');
|
||||
|
||||
await expect(getDelugeService()).rejects.toThrow('Expected Deluge client but found qbittorrent');
|
||||
});
|
||||
|
||||
it('creates and caches instance on success', async () => {
|
||||
downloadClientManagerMock.getClientForProtocol.mockResolvedValue({
|
||||
id: 'c1', type: 'deluge', name: 'Deluge', enabled: true,
|
||||
url: 'http://deluge', password: 'pass', disableSSLVerify: false,
|
||||
remotePathMappingEnabled: false,
|
||||
});
|
||||
configServiceMock.get.mockResolvedValue('/downloads');
|
||||
|
||||
const testSpy = vi.spyOn(DelugeService.prototype, 'testConnection')
|
||||
.mockResolvedValue({ success: true, message: 'Connected' });
|
||||
|
||||
const first = await getDelugeService();
|
||||
const second = await getDelugeService();
|
||||
expect(first).toBe(second);
|
||||
expect(downloadClientManagerMock.getClientForProtocol).toHaveBeenCalledTimes(1);
|
||||
|
||||
testSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -180,7 +180,7 @@ describe('QBittorrentService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapState - pausedUP/stoppedUP as completion states (RDT-Client compatibility)', () => {
|
||||
describe('mapState - pausedUP/stoppedUP as completion states', () => {
|
||||
it('maps pausedUP to completed (download finished, paused on upload side)', () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
const progress = service.getDownloadProgress({
|
||||
@@ -254,7 +254,7 @@ describe('QBittorrentService', () => {
|
||||
expect(info!.status).toBe('seeding');
|
||||
});
|
||||
|
||||
it('maps pausedUP to seeding status (RDT-Client: download finished, paused on upload side)', async () => {
|
||||
it('maps pausedUP to seeding status (download finished, paused on upload side)', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=pausedup';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
@@ -770,6 +770,37 @@ describe('QBittorrentService', () => {
|
||||
await expect(service.getTorrent('hash-404')).rejects.toThrow('Torrent hash-404 not found');
|
||||
});
|
||||
|
||||
it('ignores unrelated torrents returned by RDTClient-like clients that ignore hash filter', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=rdtclient';
|
||||
// RDTClient ignores the hashes param and returns all torrents
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [
|
||||
{ hash: 'aaaa1111bbbb2222cccc3333dddd4444eeee5555', name: 'Other Book' },
|
||||
{ hash: 'ffff6666aaaa7777bbbb8888cccc9999dddd0000', name: 'Another Book' },
|
||||
],
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getTorrent('0f54898dc1b8e49d96e32827377f651ea6c935af')
|
||||
).rejects.toThrow('Torrent 0f54898dc1b8e49d96e32827377f651ea6c935af not found');
|
||||
});
|
||||
|
||||
it('finds the correct torrent when RDTClient returns all torrents including the match', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=rdtclient2';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [
|
||||
{ hash: 'aaaa1111bbbb2222cccc3333dddd4444eeee5555', name: 'Other Book' },
|
||||
{ hash: '0F54898DC1B8E49D96E32827377F651EA6C935AF', name: 'Target Book' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.getTorrent('0f54898dc1b8e49d96e32827377f651ea6c935af');
|
||||
|
||||
expect(result.name).toBe('Target Book');
|
||||
});
|
||||
|
||||
it('returns error when getTorrents fails', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=list';
|
||||
|
||||
@@ -343,9 +343,9 @@ describe('processMonitorDownload', () => {
|
||||
requestId: 'req-6',
|
||||
downloadHistoryId: 'dh-6',
|
||||
downloadClientId: 'id-6',
|
||||
downloadClient: 'deluge',
|
||||
downloadClient: 'rtorrent',
|
||||
jobId: 'job-6',
|
||||
})).rejects.toThrow(/Unknown download client type: deluge/);
|
||||
})).rejects.toThrow(/Unknown download client type: rtorrent/);
|
||||
|
||||
expect(prismaMock.request.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
|
||||
Reference in New Issue
Block a user