Multiple archives can be deleted using Archive list view.

This commit is contained in:
Roland 2022-09-23 16:22:57 -06:00
parent 5cc15c9328
commit 69e899e032
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
7 changed files with 106 additions and 26 deletions

View file

@ -385,8 +385,19 @@ export async function deleteItems(itemIds) {
await apiDelete(`${API_URI}/inventory/item/${i}`);
}
export async function deleteArchive(archive_id) {
return await apiDelete(`${API_URI}/archive/${archive_id}`);
export async function deleteArchives(archiveIds) {
let i = archiveIds.join(',');
try {
return await apiDelete(`${API_URI}/archive/${i}`);
} catch (e) {
console.error(e);
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Unable to delete archives',
time: 5000,
});
}
}
export async function searchArchives(offset, limit, domain, searchStr, order) {

View file

@ -26,7 +26,7 @@ import {
textEllipsis,
uploadDate
} from "./Common";
import {deleteArchive, postDownload} from "../api";
import {deleteArchives, postDownload} from "../api";
import {Link, Route, Routes, useNavigate, useParams} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {useArchive, useDomains, useQuery, useSearchArchives} from "../hooks/customHooks";
@ -74,7 +74,8 @@ function ArchivePage() {
const localDeleteArchive = async () => {
setDeleteOpen(false);
await deleteArchive(archive.id);
await deleteArchives([archive.id]);
navigate(-1);
}
const localSyncArchive = async () => {
setSyncOpen(false);
@ -254,6 +255,9 @@ export function Domains() {
function Archives() {
const [domains] = useDomains();
const [selectedArchives, setSelectedArchives] = useState([]);
const [deleteOpen, setDeleteOpen] = useState(false);
let filterOptions = [];
if (domains && domains.length > 0) {
domains.forEach(i => {
@ -272,7 +276,18 @@ function Archives() {
}
const domain = searchParams.get('domain');
const {archives, limit, setLimit, totalPages, activePage, setPage, searchStr, setSearchStr, setOrderBy} =
const {
archives,
limit,
setLimit,
totalPages,
activePage,
setPage,
searchStr,
setSearchStr,
setOrderBy,
fetchArchives
} =
useSearchArchives(24, domain, searchOrder);
const setView = (value) => updateQuery({view: value});
const view = searchParams.get('view');
@ -301,6 +316,45 @@ function Archives() {
</Grid.Column>
</>);
const onSelect = (path, checked) => {
let archiveId;
if (archives) {
archives.forEach(i => {
if (i && i['archive'] && i['path'] === path) {
archiveId = i['archive']['id'];
}
});
}
if (checked && archiveId) {
setSelectedArchives([...selectedArchives, archiveId]);
} else {
setSelectedArchives(selectedArchives.filter(i => i !== archiveId));
}
}
const onDelete = async (e) => {
setDeleteOpen(false);
e.preventDefault();
await deleteArchives(selectedArchives);
await fetchArchives();
setSelectedArchives([]);
}
const selectElm = <div style={{marginTop: '0.5em'}}>
<Button
color='red'
disabled={!selectedArchives || selectedArchives.length === 0}
onClick={() => setDeleteOpen(true)}
>Delete</Button>
<Confirm
open={deleteOpen}
content='Are you sure you want to delete these archives files? This cannot be undone.'
confirmButton='Delete'
onCancel={() => setDeleteOpen(false)}
onConfirm={onDelete}
/>
</div>;
return <FilesView
files={archives}
limit={limit}
@ -309,6 +363,8 @@ function Archives() {
totalPages={totalPages}
showLimit={true}
showSelect={true}
onSelect={onSelect}
selectElem={selectElm}
view={view}
setView={setView}
setPage={setPage}

View file

@ -6,7 +6,8 @@ import {
Confirm,
Divider,
Dropdown,
Image, PlaceholderLine,
Image,
PlaceholderLine,
TableBody,
TableCell,
TableHeader,
@ -226,16 +227,16 @@ function ImageRow({file, checkbox}) {
return (
<Table.Row>
{checkbox}
<Table.Cell>
<TableCell>
<center>
{poster}
</center>
</Table.Cell>
<Table.Cell>
</TableCell>
<TableCell>
<ExternalCardLink to={url}>
<p>{textEllipsis(file.title || file.stem || file.path, 100)}</p>
</ExternalCardLink>
</Table.Cell>
</TableCell>
</Table.Row>
)
}
@ -250,9 +251,9 @@ function FileRow({file, selectOn, onSelect}) {
console.error('No onSelect declared');
}
};
checkbox = <Table.Cell>
checkbox = <TableCell>
<Checkbox onChange={localOnSelect}/>
</Table.Cell>
</TableCell>
}
if (file.model === 'video' && 'video' in file) {
@ -314,6 +315,7 @@ export function FilesView({
setView,
showView = true,
showSelect = false,
selectElem,
onSelect,
setPage,
menuColumnsCount,
@ -394,6 +396,7 @@ export function FilesView({
</Grid.Column>
{menuColumns}
</Grid>
{selectOn && selectElem}
{body}
{paginator}
</>

View file

@ -179,6 +179,7 @@ export const useSearchArchives = (defaultLimit, domain, order_by) => {
setPage,
searchStr,
setSearchStr,
fetchArchives: localSearchArchives,
}
}

View file

@ -5,6 +5,7 @@ from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.common import logger, wrol_mode_check, api_param_limiter
from wrolpi.errors import ValidationError
from wrolpi.root_api import get_blueprint, json_response
from wrolpi.schema import JSONErrorResponse
from . import lib, schema
@ -26,12 +27,17 @@ async def get_archive(_: Request, archive_id: int):
return json_response({'file': archive_file, 'alternatives': alternatives})
@bp.delete('/<archive_id:int>')
@bp.delete('/<archive_ids:int>')
@bp.delete('/<archive_ids:[0-9,]+>')
@openapi.description('Delete an individual archive')
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@wrol_mode_check
async def delete_archive(_: Request, archive_id: int):
lib.delete_archive(archive_id)
async def delete_archive(_: Request, archive_ids: str):
try:
archive_ids = [int(i) for i in str(archive_ids).split(',')]
except ValueError:
raise ValidationError('Could not parse archive ids')
lib.delete_archives(*archive_ids)
return response.empty()

View file

@ -332,15 +332,16 @@ def get_archive(session, archive_id: int) -> Archive:
return archive
def delete_archive(archive_id: int):
def delete_archives(*archive_ids: List[int]):
"""Delete an Archive and all of it's files."""
with get_db_session(commit=True) as session:
archive: Archive = session.query(Archive).filter_by(id=archive_id).one_or_none()
if not archive:
raise UnknownArchive(f'Unknown Archive with id: {archive_id}')
archives: List[Archive] = list(session.query(Archive).filter(Archive.id.in_(archive_ids)))
if not archives:
raise UnknownArchive(f'Unknown Archives with IDs: {", ".join(map(str, archive_ids))}')
# Delete any files associated with this URL.
archive.delete()
for archive in archives:
archive.delete()
def archive_strptime(dt: str) -> datetime:

View file

@ -7,7 +7,7 @@ import mock
import pytest
from modules.archive import lib
from modules.archive.lib import get_or_create_domain, get_new_archive_files, delete_archive, do_archive, get_domains, \
from modules.archive.lib import get_or_create_domain, get_new_archive_files, delete_archives, do_archive, get_domains, \
group_archive_files, ArchiveFiles
from modules.archive.models import Archive, Domain
from wrolpi.dates import local_timezone
@ -174,18 +174,20 @@ def test_fills_contents_with_refresh(test_client, test_session, archive_factory)
def test_delete_archive(test_session, archive_factory):
"""Archives can be deleted."""
archive1 = archive_factory('example.com', 'https://example.com/1')
archive2 = archive_factory('example.com', 'https://example.com/1')
archive3 = archive_factory('example.com', 'https://example.com/1')
test_session.commit()
assert test_session.query(Archive).count() == 3
# Delete the oldest.
delete_archive(archive1.id)
# Delete the latest.
delete_archive(archive3.id)
delete_archives(archive1.id, archive3.id)
assert test_session.query(Archive).count() == 1
# Delete the last archive. The Domain should also be deleted.
delete_archive(archive2.id)
delete_archives(archive2.id)
domain = test_session.query(Domain).one_or_none()
assert domain is None