Adding selection to the Downloads page, user can delete or retry multiple downloads at once.

This commit is contained in:
Roland 2025-12-26 10:16:12 -07:00
parent d4f1cfb859
commit 6a9ffcaadc
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
8 changed files with 706 additions and 187 deletions

View file

@ -1284,6 +1284,33 @@ export async function retryOnceDownloads() {
return response
}
export async function batchDeleteDownloads(downloadIds) {
const response = await apiPost(`${API_URI}/download/batch/delete`, {download_ids: downloadIds});
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not delete downloads! See server logs.');
toast({type: 'error', title: 'Downloads Error', description: message, time: 5000});
}
return response
}
export async function batchRetryDownloads(downloadIds) {
const response = await apiPost(`${API_URI}/download/batch/retry`, {download_ids: downloadIds});
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not retry downloads! See server logs.');
toast({type: 'error', title: 'Downloads Error', description: message, time: 5000});
}
return response
}
export async function batchClearDownloads(downloadIds) {
const response = await apiPost(`${API_URI}/download/batch/clear`, {download_ids: downloadIds});
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not clear downloads! See server logs.');
toast({type: 'error', title: 'Downloads Error', description: message, time: 5000});
}
return response
}
export async function getStatistics() {
const response = await apiGet(`${API_URI}/statistics`);
if (response.ok) {

View file

@ -1,5 +1,8 @@
import React from "react";
import {
batchClearDownloads,
batchDeleteDownloads,
batchRetryDownloads,
clearCompletedDownloads,
deleteDownload,
deleteOnceDownloads,
@ -20,6 +23,7 @@ import {
import {
Button as SButton,
ButtonGroup,
Checkbox,
Label,
Loader,
PlaceholderLine,
@ -41,11 +45,19 @@ import {
EditZimDownloadForm
} from "../Download";
import {Downloaders} from "../Vars";
import {SortableTable} from "../SortableTable";
function ClearDownloadsButton({callback, selectedIds, clearSelection}) {
const hasSelection = selectedIds && selectedIds.length > 0;
function ClearDownloadsButton({callback}) {
async function localClearDownloads() {
try {
await clearCompletedDownloads();
if (hasSelection) {
await batchClearDownloads(selectedIds);
if (clearSelection) clearSelection();
} else {
await clearCompletedDownloads();
}
} finally {
if (callback) {
callback()
@ -53,19 +65,28 @@ function ClearDownloadsButton({callback}) {
}
}
const label = hasSelection ? `Clear (${selectedIds.length})` : 'Clear';
return <>
<APIButton
onClick={localClearDownloads}
color='violet'
obeyWROLMode={true}
>Clear</APIButton>
>{label}</APIButton>
</>
}
function RetryDownloadsButton({callback}) {
function RetryDownloadsButton({callback, selectedIds, clearSelection}) {
const hasSelection = selectedIds && selectedIds.length > 0;
async function localRetryOnce() {
try {
await retryOnceDownloads();
if (hasSelection) {
await batchRetryDownloads(selectedIds);
if (clearSelection) clearSelection();
} else {
await retryOnceDownloads();
}
} finally {
if (callback) {
callback()
@ -73,17 +94,26 @@ function RetryDownloadsButton({callback}) {
}
}
const label = hasSelection ? `Retry (${selectedIds.length})` : 'Retry';
return <APIButton
color='green'
onClick={localRetryOnce}
obeyWROLMode={true}
>Retry</APIButton>
>{label}</APIButton>
}
function DeleteOnceDownloadsButton({callback}) {
function DeleteOnceDownloadsButton({callback, selectedIds, clearSelection}) {
const hasSelection = selectedIds && selectedIds.length > 0;
async function localDeleteOnce() {
try {
await deleteOnceDownloads();
if (hasSelection) {
await batchDeleteDownloads(selectedIds);
if (clearSelection) clearSelection();
} else {
await deleteOnceDownloads();
}
} finally {
if (callback) {
callback()
@ -91,13 +121,18 @@ function DeleteOnceDownloadsButton({callback}) {
}
}
const label = hasSelection ? `Delete (${selectedIds.length})` : 'Delete';
const confirmContent = hasSelection
? `Are you sure you want to delete ${selectedIds.length} download(s)?`
: 'Are you sure you want to delete all downloads? Some may be retried!';
return <APIButton
color='red'
onClick={localDeleteOnce}
confirmContent='Are you sure you want to delete all downloads? Some may be retried!'
confirmContent={confirmContent}
confirmButton='Delete'
obeyWROLMode={true}
>Delete</APIButton>
>{label}</APIButton>
}
@ -246,213 +281,267 @@ function RecurringDownloadRow({download, fetchDownloads, onDelete}) {
</TableRow>
}
class OnceDownloadRow extends React.Component {
constructor(props) {
super(props);
this.state = {
editModalOpen: false
};
}
function OnceDownloadRow({download, fetchDownloads, isSelected, onSelect}) {
const [editModalOpen, setEditModalOpen] = React.useState(false);
handleDelete = async () => {
const {url, last_successful_download, status, location, error, downloader, settings, id} = download;
const handleDelete = async () => {
try {
await deleteDownload(this.props.id);
await deleteDownload(id);
} finally {
await this.props.fetchDownloads();
await fetchDownloads();
}
};
handleStop = async () => {
const handleStop = async () => {
try {
await killDownload(this.props.id);
await killDownload(id);
} finally {
await this.props.fetchDownloads();
await fetchDownloads();
}
};
handleRestart = async () => {
const handleRestart = async () => {
try {
await restartDownload(this.props.id);
await restartDownload(id);
} finally {
await this.props.fetchDownloads();
await fetchDownloads();
}
};
handleEditOpen = () => {
this.setState({editModalOpen: true});
const handleEditOpen = () => setEditModalOpen(true);
const handleEditClose = () => setEditModalOpen(false);
const handleEditSuccess = async () => {
await fetchDownloads();
handleEditClose();
};
handleEditClose = () => {
this.setState({editModalOpen: false});
};
// Open downloads (/download), or external links in an anchor.
const link = location && !location.startsWith('/download') ?
(text) => <Link to={location}>{text}</Link> :
(text) => <a href={location || url} target='_blank' rel='noopener noreferrer'>{text}</a>;
handleEditSuccess = async () => {
await this.props.fetchDownloads();
this.handleEditClose();
};
render() {
let {url, last_successful_download, status, location, error, downloader, settings, id} = this.props;
// Open downloads (/download), or external links in an anchor.
const link = location && !location.startsWith('/download') ?
(text) => <Link to={location}>{text}</Link> :
(text) => <a href={location || url} target='_blank' rel='noopener noreferrer'>{text}</a>;
let completedAtCell = last_successful_download ? isoDatetimeToElapsedPopup(last_successful_download) : null;
let buttonCell = <TableCell/>;
if (status === 'pending' || status === 'new') {
buttonCell = (
<TableCell>
let completedAtCell = last_successful_download ? isoDatetimeToElapsedPopup(last_successful_download) : null;
let buttonCell = <TableCell/>;
if (status === 'pending' || status === 'new') {
buttonCell = (
<TableCell>
<APIButton
color='red'
onClick={handleStop}
confirmContent='Are you sure you want to stop this download? It will not be retried.'
confirmButton='Stop'
obeyWROLMode={true}
>Stop</APIButton>
</TableCell>
);
} else if (status === 'failed' || status === 'deferred') {
buttonCell = (
<TableCell>
<ButtonGroup>
<APIButton
color='red'
onClick={this.handleStop}
confirmContent='Are you sure you want to stop this download? It will not be retried.'
confirmButton='Stop'
icon='trash'
onClick={handleDelete}
confirmContent='Are you sure you want to delete this download?'
confirmButton='Delete'
obeyWROLMode={true}
>Stop</APIButton>
</TableCell>
);
} else if (status === 'failed' || status === 'deferred') {
buttonCell = (
<TableCell>
<ButtonGroup>
<APIButton
color='red'
icon='trash'
onClick={this.handleDelete}
confirmContent='Are you sure you want to delete this download?'
confirmButton='Delete'
obeyWROLMode={true}
/>
{(downloader === Downloaders.Video || downloader === Downloaders.Archive) && status !== 'pending' && (
<Button
icon='edit'
color='blue'
onClick={handleEditOpen}
/>
{(downloader === Downloaders.Video || downloader === Downloaders.Archive) && status !== 'pending' && (
<Button
icon='edit'
color='blue'
onClick={this.handleEditOpen}
/>
)}
<APIButton
color='green'
icon='redo'
confirmContent='Are you sure you want to restart this download?'
confirmButton='Start'
onClick={this.handleRestart}
obeyWROLMode={true}
/>
</ButtonGroup>
</TableCell>
);
} else if (status === 'complete' && location) {
buttonCell = (
<TableCell>
{link('View')}
</TableCell>
);
}
if (error) {
completedAtCell = (
<Modal
closeIcon
trigger={<Button icon='exclamation circle' color='red'/>}
>
<Modal.Header>Download Error</Modal.Header>
<Modal.Content>
<pre style={{overflowX: 'scroll'}}>{error}</pre>
</Modal.Content>
</Modal>
)
}
// Create edit modal for video or archive downloads
let editModal = null;
if (downloader === Downloaders.Video) {
editModal = (
<Modal
closeIcon
open={this.state.editModalOpen}
onClose={this.handleEditClose}
>
<Modal.Header>Edit Video Download</Modal.Header>
<Modal.Content>
<EditVideosDownloadForm
download={{
urls: url,
settings: settings || {},
id: id
}}
onCancel={this.handleEditClose}
onSuccess={this.handleEditSuccess}
onDelete={this.handleDelete}
/>
</Modal.Content>
</Modal>
);
} else if (downloader === Downloaders.Archive) {
editModal = (
<Modal
closeIcon
open={this.state.editModalOpen}
onClose={this.handleEditClose}
>
<Modal.Header>Edit Archive Download</Modal.Header>
<Modal.Content>
<EditArchiveDownloadForm
download={{
urls: url,
tag_names: settings?.tag_names || [],
id: id
}}
onCancel={this.handleEditClose}
onSuccess={this.handleEditSuccess}
onDelete={this.handleDelete}
/>
</Modal.Content>
</Modal>
);
}
return <TableRow>
<TableCell className='column-ellipsis'>
{link(url)}
)}
<APIButton
color='green'
icon='redo'
confirmContent='Are you sure you want to restart this download?'
confirmButton='Start'
onClick={handleRestart}
obeyWROLMode={true}
/>
</ButtonGroup>
</TableCell>
);
} else if (status === 'complete' && location) {
buttonCell = (
<TableCell>
{completedAtCell}
{status === 'pending' ? <Loader active inline size='tiny'/> : null}
{link('View')}
</TableCell>
{buttonCell}
{editModal}
</TableRow>
);
}
if (error) {
completedAtCell = (
<Modal
closeIcon
trigger={<Button icon='exclamation circle' color='red'/>}
>
<Modal.Header>Download Error</Modal.Header>
<Modal.Content>
<pre style={{overflowX: 'scroll'}}>{error}</pre>
</Modal.Content>
</Modal>
)
}
// Create edit modal for video or archive downloads
let editModal = null;
if (downloader === Downloaders.Video) {
editModal = (
<Modal
closeIcon
open={editModalOpen}
onClose={handleEditClose}
>
<Modal.Header>Edit Video Download</Modal.Header>
<Modal.Content>
<EditVideosDownloadForm
download={{
urls: url,
settings: settings || {},
id: id
}}
onCancel={handleEditClose}
onSuccess={handleEditSuccess}
onDelete={handleDelete}
/>
</Modal.Content>
</Modal>
);
} else if (downloader === Downloaders.Archive) {
editModal = (
<Modal
closeIcon
open={editModalOpen}
onClose={handleEditClose}
>
<Modal.Header>Edit Archive Download</Modal.Header>
<Modal.Content>
<EditArchiveDownloadForm
download={{
urls: url,
tag_names: settings?.tag_names || [],
id: id
}}
onCancel={handleEditClose}
onSuccess={handleEditSuccess}
onDelete={handleDelete}
/>
</Modal.Content>
</Modal>
);
}
return <TableRow>
<TableCell collapsing>
<Checkbox
checked={isSelected}
onChange={() => onSelect(id)}
/>
</TableCell>
<TableCell className='column-ellipsis'>
{link(url)}
</TableCell>
<TableCell>
{completedAtCell}
{status === 'pending' ? <Loader active inline size='tiny'/> : null}
</TableCell>
{buttonCell}
{editModal}
</TableRow>
}
export function OnceDownloadsTable({downloads, fetchDownloads}) {
const [selectedIds, setSelectedIds] = React.useState([]);
// Clear selection when downloads change (e.g., after deletion)
React.useEffect(() => {
if (downloads) {
// Remove any selected IDs that no longer exist
const downloadIds = new Set(downloads.map(d => d.id));
setSelectedIds(prev => prev.filter(id => downloadIds.has(id)));
}
}, [downloads]);
const onSelect = (id) => {
if (selectedIds.includes(id)) {
setSelectedIds(selectedIds.filter(i => i !== id));
} else {
setSelectedIds([...selectedIds, id]);
}
};
const clearSelection = () => setSelectedIds([]);
const toggleSelectAll = () => {
if (downloads && selectedIds.length === downloads.length) {
setSelectedIds([]);
} else if (downloads) {
setSelectedIds(downloads.map(d => d.id));
}
};
const tableHeaders = [
{
key: 'select',
text: <Checkbox
checked={downloads && downloads.length > 0 && selectedIds.length === downloads.length}
indeterminate={selectedIds.length > 0 && selectedIds.length < (downloads?.length || 0)}
onChange={toggleSelectAll}
/>,
sortBy: null
},
{key: 'url', text: 'URL', sortBy: i => i.url.toLowerCase()},
{key: 'completed_at', text: 'Completed At', sortBy: i => i.last_successful_download || ''},
{key: 'control', text: 'Control', sortBy: null},
];
const rowFunc = (download) => (
<OnceDownloadRow
key={download.id}
download={download}
fetchDownloads={fetchDownloads}
isSelected={selectedIds.includes(download.id)}
onSelect={onSelect}
/>
);
const footer = <TableFooter>
<TableRow>
<TableHeaderCell colSpan={4}>
<ClearDownloadsButton
callback={fetchDownloads}
selectedIds={selectedIds}
clearSelection={clearSelection}
/>
<RetryDownloadsButton
callback={fetchDownloads}
selectedIds={selectedIds}
clearSelection={clearSelection}
/>
<DeleteOnceDownloadsButton
callback={fetchDownloads}
selectedIds={selectedIds}
clearSelection={clearSelection}
/>
</TableHeaderCell>
</TableRow>
</TableFooter>;
if (downloads && downloads.length >= 1) {
return <>
<Table className='table-ellipsis'>
<TableHeader>
<TableRow>
<TableHeaderCell width={11}>URL</TableHeaderCell>
<TableHeaderCell width={2}>Completed At</TableHeaderCell>
<TableHeaderCell width={2}>Control</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{downloads.map(i => <OnceDownloadRow fetchDownloads={fetchDownloads} key={i.id} {...i}/>)}
</TableBody>
<TableFooter>
<TableRow>
<TableHeaderCell colSpan={3}>
<ClearDownloadsButton callback={fetchDownloads}/>
<RetryDownloadsButton callback={fetchDownloads}/>
<DeleteOnceDownloadsButton callback={fetchDownloads}/>
</TableHeaderCell>
</TableRow>
</TableFooter>
</Table>
</>
return <SortableTable
tableHeaders={tableHeaders}
data={downloads}
rowFunc={rowFunc}
rowKey='id'
footer={footer}
tableProps={{className: 'table-ellipsis'}}
/>
} else if (downloads) {
return <Segment>No downloads are scheduled.</Segment>
} else if (downloads === undefined) {

View file

@ -0,0 +1,169 @@
import React from 'react';
import {fireEvent, screen, waitFor} from '@testing-library/react';
import {OnceDownloadsTable} from './Downloads';
import {renderWithProviders} from '../../test-utils';
// Mock the API functions
jest.mock('../../api', () => ({
batchClearDownloads: jest.fn(() => Promise.resolve({ok: true})),
batchDeleteDownloads: jest.fn(() => Promise.resolve({ok: true})),
batchRetryDownloads: jest.fn(() => Promise.resolve({ok: true})),
clearCompletedDownloads: jest.fn(() => Promise.resolve({ok: true})),
deleteDownload: jest.fn(() => Promise.resolve({ok: true})),
deleteOnceDownloads: jest.fn(() => Promise.resolve({ok: true})),
killDownload: jest.fn(() => Promise.resolve({ok: true})),
restartDownload: jest.fn(() => Promise.resolve({ok: true})),
retryOnceDownloads: jest.fn(() => Promise.resolve({ok: true})),
}));
import {
batchClearDownloads,
batchDeleteDownloads,
batchRetryDownloads,
clearCompletedDownloads,
deleteOnceDownloads,
retryOnceDownloads,
} from '../../api';
describe('OnceDownloadsTable', () => {
const mockDownloads = [
{id: 1, url: 'https://example.com/1', status: 'complete', last_successful_download: '2024-01-01T00:00:00Z', location: '/videos/1'},
{id: 2, url: 'https://example.com/2', status: 'failed', error: 'Download failed'},
{id: 3, url: 'https://example.com/3', status: 'pending'},
];
const mockFetchDownloads = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
});
it('renders downloads table with checkboxes', () => {
renderWithProviders(
<OnceDownloadsTable downloads={mockDownloads} fetchDownloads={mockFetchDownloads}/>
);
// Should render all downloads
expect(screen.getByText('https://example.com/1')).toBeInTheDocument();
expect(screen.getByText('https://example.com/2')).toBeInTheDocument();
expect(screen.getByText('https://example.com/3')).toBeInTheDocument();
// Should have checkboxes (4 = 1 header + 3 rows)
const checkboxes = screen.getAllByRole('checkbox');
expect(checkboxes).toHaveLength(4);
});
it('renders empty state when no downloads', () => {
renderWithProviders(
<OnceDownloadsTable downloads={[]} fetchDownloads={mockFetchDownloads}/>
);
expect(screen.getByText('No downloads are scheduled.')).toBeInTheDocument();
});
it('toggles selection when checkbox clicked', async () => {
renderWithProviders(
<OnceDownloadsTable downloads={mockDownloads} fetchDownloads={mockFetchDownloads}/>
);
const checkboxes = screen.getAllByRole('checkbox');
// First checkbox is select-all, so click the second one (first row)
fireEvent.click(checkboxes[1]);
// Button labels should show count
await waitFor(() => {
expect(screen.getByText('Clear (1)')).toBeInTheDocument();
expect(screen.getByText('Retry (1)')).toBeInTheDocument();
expect(screen.getByText('Delete (1)')).toBeInTheDocument();
});
});
it('selects all when header checkbox clicked', async () => {
renderWithProviders(
<OnceDownloadsTable downloads={mockDownloads} fetchDownloads={mockFetchDownloads}/>
);
const checkboxes = screen.getAllByRole('checkbox');
// Click the select-all checkbox (first one)
fireEvent.click(checkboxes[0]);
// Button labels should show count of all downloads
await waitFor(() => {
expect(screen.getByText('Clear (3)')).toBeInTheDocument();
expect(screen.getByText('Retry (3)')).toBeInTheDocument();
expect(screen.getByText('Delete (3)')).toBeInTheDocument();
});
});
it('deselects all when header checkbox clicked again', async () => {
renderWithProviders(
<OnceDownloadsTable downloads={mockDownloads} fetchDownloads={mockFetchDownloads}/>
);
const checkboxes = screen.getAllByRole('checkbox');
// Click select-all twice
fireEvent.click(checkboxes[0]);
fireEvent.click(checkboxes[0]);
// Button labels should show no count
await waitFor(() => {
expect(screen.getByText('Clear')).toBeInTheDocument();
expect(screen.getByText('Retry')).toBeInTheDocument();
expect(screen.getByText('Delete')).toBeInTheDocument();
});
});
it('calls batch API when items selected and Clear clicked', async () => {
renderWithProviders(
<OnceDownloadsTable downloads={mockDownloads} fetchDownloads={mockFetchDownloads}/>
);
const checkboxes = screen.getAllByRole('checkbox');
// Select first two downloads
fireEvent.click(checkboxes[1]);
fireEvent.click(checkboxes[2]);
// Click Clear button
const clearButton = screen.getByText('Clear (2)');
fireEvent.click(clearButton);
await waitFor(() => {
expect(batchClearDownloads).toHaveBeenCalledWith([1, 2]);
expect(clearCompletedDownloads).not.toHaveBeenCalled();
});
});
it('calls all-downloads API when no items selected', async () => {
renderWithProviders(
<OnceDownloadsTable downloads={mockDownloads} fetchDownloads={mockFetchDownloads}/>
);
// Click Clear button without selecting any items
const clearButton = screen.getByText('Clear');
fireEvent.click(clearButton);
await waitFor(() => {
expect(clearCompletedDownloads).toHaveBeenCalled();
expect(batchClearDownloads).not.toHaveBeenCalled();
});
});
it('clears selection after successful operation', async () => {
renderWithProviders(
<OnceDownloadsTable downloads={mockDownloads} fetchDownloads={mockFetchDownloads}/>
);
const checkboxes = screen.getAllByRole('checkbox');
// Select first download
fireEvent.click(checkboxes[1]);
// Click Clear button
const clearButton = screen.getByText('Clear (1)');
fireEvent.click(clearButton);
await waitFor(() => {
// Button label should revert to no count
expect(screen.getByText('Clear')).toBeInTheDocument();
});
});
});

View file

@ -1,6 +1,15 @@
import {Accordion, Header, Progress, Segment, Statistic, Table} from "../Theme";
import React, {useContext} from "react";
import {humanBandwidth, humanFileSize, InfoHeader, LoadStatistic, useTitle} from "../Common";
import {
Duration,
humanBandwidth,
humanFileSize,
InfoHeader,
LoadStatistic,
secondsToHMS,
secondsToHumanElapsed,
useTitle
} from "../Common";
import {ProgressPlaceholder} from "../Placeholder";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Media, SettingsContext, StatusContext, ThemeContext} from "../../contexts/contexts";

View file

@ -1143,6 +1143,45 @@ class DownloadManager:
save_downloads_config.activate_switch()
return deleted_ids
def delete_downloads_by_ids(self, session: Session, download_ids: List[int]) -> List[int]:
"""Delete specific downloads by their IDs."""
if not download_ids:
return []
stmt = Download.__table__.delete().where(Download.id.in_(download_ids)).returning(Download.id)
deleted_ids = [i for i, in session.execute(stmt).fetchall()]
session.commit()
save_downloads_config.activate_switch()
return deleted_ids
def retry_downloads_by_ids(self, session: Session, download_ids: List[int]) -> int:
"""Retry specific downloads by their IDs. Returns the number of downloads renewed."""
if not download_ids:
return 0
downloads = session.query(Download).filter(Download.id.in_(download_ids)).all()
count = 0
for download in downloads:
if download.status in (DownloadStatus.failed, DownloadStatus.deferred):
download.renew(reset_attempts=True)
count += 1
session.commit()
return count
def clear_completed_by_ids(self, session: Session, download_ids: List[int]) -> List[int]:
"""Clear (delete) specific completed once-downloads by their IDs."""
if not download_ids:
return []
from sqlalchemy import and_
stmt = Download.__table__.delete().where(
and_(
Download.id.in_(download_ids),
Download.status == DownloadStatus.complete,
Download.frequency == None # noqa - only once-downloads
)
).returning(Download.id)
deleted_ids = [i for i, in session.execute(stmt).fetchall()]
session.commit()
return deleted_ids
@staticmethod
def is_skipped(*urls: str) -> bool:
if skip_list := get_download_manager_config().skip_urls:

View file

@ -401,6 +401,45 @@ async def delete_once(request: Request):
return response.empty()
@api_bp.post('/download/batch/delete')
@openapi.definition(
description='Delete specific downloads by their IDs',
body=schema.DownloadBatchRequest,
validate=True,
)
@wrol_mode_check
async def batch_delete_downloads(request: Request, body: schema.DownloadBatchRequest):
session = request.ctx.session
deleted_ids = download_manager.delete_downloads_by_ids(session, body.download_ids)
return json_response({'deleted_ids': deleted_ids})
@api_bp.post('/download/batch/retry')
@openapi.definition(
description='Retry specific downloads by their IDs',
body=schema.DownloadBatchRequest,
validate=True,
)
@wrol_mode_check
async def batch_retry_downloads(request: Request, body: schema.DownloadBatchRequest):
session = request.ctx.session
count = download_manager.retry_downloads_by_ids(session, body.download_ids)
return json_response({'retried_count': count})
@api_bp.post('/download/batch/clear')
@openapi.definition(
description='Clear specific completed downloads by their IDs',
body=schema.DownloadBatchRequest,
validate=True,
)
@wrol_mode_check
async def batch_clear_downloads(request: Request, body: schema.DownloadBatchRequest):
session = request.ctx.session
deleted_ids = download_manager.clear_completed_by_ids(session, body.download_ids)
return json_response({'deleted_ids': deleted_ids})
@api_bp.get('/downloaders')
@openapi.description('List all Downloaders that can be specified by the user.')
async def get_downloaders(_: Request):

View file

@ -285,6 +285,16 @@ class DownloadRequest:
self.settings = {k: v for k, v in DownloadSettings(**settings).__dict__.items() if v not in ([], None)}
@dataclass
class DownloadBatchRequest:
"""Request for batch operations on downloads."""
download_ids: List[int]
def __post_init__(self):
if not self.download_ids:
raise ValidationError('download_ids cannot be empty')
@dataclass
class JSONErrorResponse:
error: str

View file

@ -662,3 +662,140 @@ async def test_download_with_collection_id(test_session, test_download_manager,
assert download.id is not None
assert download.collection_id == collection.id
assert download.frequency == DownloadFrequency.weekly
@pytest.mark.asyncio
async def test_batch_delete_downloads(test_session, test_download_manager, test_downloader):
"""Test deleting specific downloads by their IDs."""
d1 = test_download_manager.create_download(test_session, 'https://example.com/1', test_downloader.name)
d2 = test_download_manager.create_download(test_session, 'https://example.com/2', test_downloader.name)
d3 = test_download_manager.create_download(test_session, 'https://example.com/3', test_downloader.name)
test_session.commit()
# Capture IDs before deletion (objects become detached after)
d1_id, d2_id, d3_id = d1.id, d2.id, d3.id
# Delete only d1 and d3
deleted_ids = test_download_manager.delete_downloads_by_ids(test_session, [d1_id, d3_id])
assert set(deleted_ids) == {d1_id, d3_id}
# Only d2 remains
downloads = test_session.query(Download).all()
assert len(downloads) == 1
assert downloads[0].id == d2_id
# Empty list returns empty
deleted_ids = test_download_manager.delete_downloads_by_ids(test_session, [])
assert deleted_ids == []
# Non-existent IDs are silently ignored
deleted_ids = test_download_manager.delete_downloads_by_ids(test_session, [9999, 8888])
assert deleted_ids == []
@pytest.mark.asyncio
async def test_batch_retry_downloads(test_session, test_download_manager, test_downloader):
"""Test retrying specific downloads by their IDs."""
d1 = test_download_manager.create_download(test_session, 'https://example.com/1', test_downloader.name)
d2 = test_download_manager.create_download(test_session, 'https://example.com/2', test_downloader.name)
d3 = test_download_manager.create_download(test_session, 'https://example.com/3', test_downloader.name)
# Set different statuses
d1.fail()
d1.attempts = 5
d2.defer()
d2.attempts = 3
d3.complete() # completed download should not be retried
test_session.commit()
# Retry d1 and d2 (not d3 since it's complete)
count = test_download_manager.retry_downloads_by_ids(test_session, [d1.id, d2.id, d3.id])
assert count == 2 # Only d1 and d2 were retried
# Verify statuses and attempts were reset
test_session.refresh(d1)
test_session.refresh(d2)
test_session.refresh(d3)
assert d1.status == 'new'
assert d1.attempts == 0
assert d2.status == 'new'
assert d2.attempts == 0
assert d3.status == 'complete' # unchanged
# Empty list returns 0
count = test_download_manager.retry_downloads_by_ids(test_session, [])
assert count == 0
@pytest.mark.asyncio
async def test_batch_clear_completed(test_session, test_download_manager, test_downloader):
"""Test clearing specific completed downloads by their IDs."""
d1 = test_download_manager.create_download(test_session, 'https://example.com/1', test_downloader.name)
d2 = test_download_manager.create_download(test_session, 'https://example.com/2', test_downloader.name)
d3 = test_download_manager.create_download(test_session, 'https://example.com/3', test_downloader.name)
d4 = test_download_manager.create_download(test_session, 'https://example.com/4', test_downloader.name)
# Set different statuses
d1.complete()
d2.complete()
d3.fail() # failed download should not be cleared by this method
# d4 stays as 'new'
test_session.commit()
# Capture IDs before deletion (objects become detached after)
d1_id, d2_id, d3_id, d4_id = d1.id, d2.id, d3.id, d4.id
# Clear only d1 (which is complete)
deleted_ids = test_download_manager.clear_completed_by_ids(test_session, [d1_id, d3_id, d4_id])
assert deleted_ids == [d1_id] # Only d1 was cleared (complete)
# d2, d3, d4 remain
downloads = test_session.query(Download).all()
assert len(downloads) == 3
assert {d.id for d in downloads} == {d2_id, d3_id, d4_id}
# Empty list returns empty
deleted_ids = test_download_manager.clear_completed_by_ids(test_session, [])
assert deleted_ids == []
@pytest.mark.asyncio
async def test_batch_api_endpoints(async_client, test_session, test_download_manager, test_downloader):
"""Test the batch API endpoints."""
d1 = test_download_manager.create_download(test_session, 'https://example.com/1', test_downloader.name)
d2 = test_download_manager.create_download(test_session, 'https://example.com/2', test_downloader.name)
d3 = test_download_manager.create_download(test_session, 'https://example.com/3', test_downloader.name)
d1.fail()
d2.complete()
test_session.commit()
# Capture IDs before operations (objects become detached after deletion)
d1_id, d2_id, d3_id = d1.id, d2.id, d3.id
# Test batch retry endpoint
body = dict(download_ids=[d1_id])
request, response = await async_client.post('/api/download/batch/retry', content=json.dumps(body))
assert response.status_code == HTTPStatus.OK
assert response.json['retried_count'] == 1
test_session.refresh(d1)
assert d1.status == 'new'
# Test batch clear endpoint
body = dict(download_ids=[d2_id])
request, response = await async_client.post('/api/download/batch/clear', content=json.dumps(body))
assert response.status_code == HTTPStatus.OK
assert response.json['deleted_ids'] == [d2_id]
assert test_session.query(Download).filter_by(id=d2_id).count() == 0
# Test batch delete endpoint
body = dict(download_ids=[d1_id, d3_id])
request, response = await async_client.post('/api/download/batch/delete', content=json.dumps(body))
assert response.status_code == HTTPStatus.OK
assert set(response.json['deleted_ids']) == {d1_id, d3_id}
assert test_session.query(Download).count() == 0
# Test validation - empty list should fail
body = dict(download_ids=[])
request, response = await async_client.post('/api/download/batch/delete', content=json.dumps(body))
assert response.status_code == HTTPStatus.BAD_REQUEST