diff --git a/app/src/api.js b/app/src/api.js
index 44e4091c..a0b98618 100644
--- a/app/src/api.js
+++ b/app/src/api.js
@@ -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) {
diff --git a/app/src/components/admin/Downloads.js b/app/src/components/admin/Downloads.js
index fa87f23e..43c6baa2 100644
--- a/app/src/components/admin/Downloads.js
+++ b/app/src/components/admin/Downloads.js
@@ -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 <>
Clear
+ >{label}
>
}
-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 Retry
+ >{label}
}
-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 Delete
+ >{label}
}
@@ -246,213 +281,267 @@ function RecurringDownloadRow({download, fetchDownloads, onDelete}) {
}
-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) => {text} :
+ (text) => {text};
- 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) => {text} :
- (text) => {text};
-
- let completedAtCell = last_successful_download ? isoDatetimeToElapsedPopup(last_successful_download) : null;
- let buttonCell = ;
- if (status === 'pending' || status === 'new') {
- buttonCell = (
-
+ let completedAtCell = last_successful_download ? isoDatetimeToElapsedPopup(last_successful_download) : null;
+ let buttonCell = ;
+ if (status === 'pending' || status === 'new') {
+ buttonCell = (
+
+ Stop
+
+ );
+ } else if (status === 'failed' || status === 'deferred') {
+ buttonCell = (
+
+
Stop
-
- );
- } else if (status === 'failed' || status === 'deferred') {
- buttonCell = (
-
-
-
-
+ {(downloader === Downloaders.Video || downloader === Downloaders.Archive) && status !== 'pending' && (
+
- {(downloader === Downloaders.Video || downloader === Downloaders.Archive) && status !== 'pending' && (
-
- )}
-
-
-
- );
- } else if (status === 'complete' && location) {
- buttonCell = (
-
- {link('View')}
-
- );
- }
- if (error) {
- completedAtCell = (
- }
- >
- Download Error
-
- {error}
-
-
- )
- }
-
- // Create edit modal for video or archive downloads
- let editModal = null;
-
- if (downloader === Downloaders.Video) {
- editModal = (
-
- Edit Video Download
-
-
-
-
- );
- } else if (downloader === Downloaders.Archive) {
- editModal = (
-
- Edit Archive Download
-
-
-
-
- );
- }
-
- return
-
- {link(url)}
+ )}
+
+
+ );
+ } else if (status === 'complete' && location) {
+ buttonCell = (
- {completedAtCell}
- {status === 'pending' ? : null}
+ {link('View')}
- {buttonCell}
- {editModal}
-
+ );
}
+ if (error) {
+ completedAtCell = (
+ }
+ >
+ Download Error
+
+ {error}
+
+
+ )
+ }
+
+ // Create edit modal for video or archive downloads
+ let editModal = null;
+
+ if (downloader === Downloaders.Video) {
+ editModal = (
+
+ Edit Video Download
+
+
+
+
+ );
+ } else if (downloader === Downloaders.Archive) {
+ editModal = (
+
+ Edit Archive Download
+
+
+
+
+ );
+ }
+
+ return
+
+ onSelect(id)}
+ />
+
+
+ {link(url)}
+
+
+ {completedAtCell}
+ {status === 'pending' ? : null}
+
+ {buttonCell}
+ {editModal}
+
}
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: 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) => (
+
+ );
+
+ const footer =
+
+
+
+
+
+
+
+ ;
+
if (downloads && downloads.length >= 1) {
- return <>
-
-
-
- URL
- Completed At
- Control
-
-
-
- {downloads.map(i => )}
-
-
-
-
-
-
-
-
-
-
-
- >
+ return
} else if (downloads) {
return No downloads are scheduled.
} else if (downloads === undefined) {
diff --git a/app/src/components/admin/Downloads.test.js b/app/src/components/admin/Downloads.test.js
new file mode 100644
index 00000000..1ba27cf3
--- /dev/null
+++ b/app/src/components/admin/Downloads.test.js
@@ -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(
+
+ );
+
+ // 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(
+
+ );
+
+ expect(screen.getByText('No downloads are scheduled.')).toBeInTheDocument();
+ });
+
+ it('toggles selection when checkbox clicked', async () => {
+ renderWithProviders(
+
+ );
+
+ 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(
+
+ );
+
+ 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(
+
+ );
+
+ 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(
+
+ );
+
+ 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(
+
+ );
+
+ // 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(
+
+ );
+
+ 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();
+ });
+ });
+});
diff --git a/app/src/components/admin/Status.js b/app/src/components/admin/Status.js
index edbffb83..7733b12c 100644
--- a/app/src/components/admin/Status.js
+++ b/app/src/components/admin/Status.js
@@ -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";
diff --git a/wrolpi/downloader.py b/wrolpi/downloader.py
index 45c4293b..0b584f9c 100644
--- a/wrolpi/downloader.py
+++ b/wrolpi/downloader.py
@@ -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:
diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py
index c819176b..dbcef6f7 100644
--- a/wrolpi/root_api.py
+++ b/wrolpi/root_api.py
@@ -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):
diff --git a/wrolpi/schema.py b/wrolpi/schema.py
index 3bdbb71d..370e65e8 100644
--- a/wrolpi/schema.py
+++ b/wrolpi/schema.py
@@ -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
diff --git a/wrolpi/test/test_downloader.py b/wrolpi/test/test_downloader.py
index 51927c35..bbfe1c2f 100644
--- a/wrolpi/test/test_downloader.py
+++ b/wrolpi/test/test_downloader.py
@@ -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