mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-20 06:56:18 -05:00
Displaying confirmation modal when deleting tagged files, rather than just refusing to delete them.
This commit is contained in:
parent
4380cab88c
commit
8fb9e35aef
7 changed files with 133 additions and 55 deletions
|
|
@ -1386,10 +1386,18 @@ export async function getFile(path, skipTracking = false) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function deleteFile(paths) {
|
||||
let body = {paths: paths};
|
||||
export async function deleteFile(paths, force = false) {
|
||||
let body = {paths: paths, force: force};
|
||||
const response = await apiPost(`${API_URI}/files/delete`, body);
|
||||
if (!response.ok) {
|
||||
try {
|
||||
const json = await response.clone().json();
|
||||
if (json.code === 'FILE_GROUP_IS_TAGGED' && json.file_groups) {
|
||||
return {tagged: true, file_groups: json.file_groups};
|
||||
}
|
||||
} catch (e) {
|
||||
// Not JSON, fall through to generic error.
|
||||
}
|
||||
const message = await getErrorMessage(response, 'Failed to delete file. See server logs.');
|
||||
toast({
|
||||
type: 'error',
|
||||
|
|
|
|||
|
|
@ -212,6 +212,8 @@ export function FileBrowser() {
|
|||
const [isDirectoryIgnored, setIsDirectoryIgnored] = React.useState(false);
|
||||
// Tracks folder that was opened while selected - its children will be auto-selected when they load
|
||||
const pendingAutoSelectRef = React.useRef(null);
|
||||
// Tagged file groups that would be deleted - shown in confirmation modal
|
||||
const [taggedFileGroups, setTaggedFileGroups] = React.useState(null);
|
||||
|
||||
const {settings, fetchSettings} = React.useContext(SettingsContext);
|
||||
const {inverted} = React.useContext(ThemeContext);
|
||||
|
|
@ -294,8 +296,7 @@ export function FileBrowser() {
|
|||
await fetchSettings();
|
||||
}
|
||||
|
||||
const onDelete = async () => {
|
||||
await deleteFile(selectedPaths);
|
||||
const handleDeleteComplete = async () => {
|
||||
// Remove deleted directories from openFolders to prevent fetching non-existent directories
|
||||
const deletedDirs = selectedPaths.filter(p => p.endsWith('/'));
|
||||
if (deletedDirs.length > 0 && openFolders && openFolders.length > 0) {
|
||||
|
|
@ -307,6 +308,24 @@ export function FileBrowser() {
|
|||
await reset();
|
||||
};
|
||||
|
||||
const onDelete = async () => {
|
||||
const result = await deleteFile(selectedPaths);
|
||||
if (result && result.tagged) {
|
||||
// Show modal with tagged file groups for user to confirm.
|
||||
setTaggedFileGroups(result.file_groups);
|
||||
return;
|
||||
}
|
||||
await handleDeleteComplete();
|
||||
};
|
||||
|
||||
const onForceDelete = async () => {
|
||||
setTaggedFileGroups(null);
|
||||
const result = await deleteFile(selectedPaths, true);
|
||||
if (result && result.tagged) return; // unexpected tagged response
|
||||
if (result && !result.ok) return; // error already toasted
|
||||
await handleDeleteComplete();
|
||||
};
|
||||
|
||||
const handleMakeDirectory = async () => {
|
||||
setMakeDirectoryOpen(false);
|
||||
await reset();
|
||||
|
|
@ -412,6 +431,38 @@ export function FileBrowser() {
|
|||
paths={selectedPaths}
|
||||
onComplete={reset}
|
||||
/>
|
||||
<Modal
|
||||
open={taggedFileGroups !== null}
|
||||
onClose={() => setTaggedFileGroups(null)}
|
||||
closeIcon
|
||||
>
|
||||
<Modal.Header><Icon name='warning sign'/> Tagged Files Will Be Deleted</Modal.Header>
|
||||
<Modal.Content>
|
||||
<p>The following tagged files will be deleted:</p>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHeaderCell>File</TableHeaderCell>
|
||||
<TableHeaderCell>Tags</TableHeaderCell>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{taggedFileGroups && taggedFileGroups.map((fg, idx) => (
|
||||
<TableRow key={idx}>
|
||||
<TableCell>{fg.primary_path || fg.name}</TableCell>
|
||||
<TableCell>{(fg.tags || []).join(', ')}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Modal.Content>
|
||||
<Modal.Actions>
|
||||
<Button onClick={() => setTaggedFileGroups(null)}>Cancel</Button>
|
||||
<Button color='red' onClick={onForceDelete}>
|
||||
<Icon name='trash'/> Delete
|
||||
</Button>
|
||||
</Modal.Actions>
|
||||
</Modal>
|
||||
</div>;
|
||||
|
||||
const onFolderClick = async (folder) => {
|
||||
|
|
|
|||
|
|
@ -66,7 +66,12 @@ async def delete_file(_: Request, body: schema.DeleteRequest):
|
|||
paths = [i for i in body.paths if i]
|
||||
if not paths:
|
||||
raise InvalidFile('paths cannot be empty')
|
||||
await lib.delete(*paths)
|
||||
tagged_file_groups = await lib.delete(*paths, force=body.force)
|
||||
if tagged_file_groups:
|
||||
return json_response(
|
||||
{'code': 'FILE_GROUP_IS_TAGGED', 'file_groups': tagged_file_groups},
|
||||
HTTPStatus.CONFLICT,
|
||||
)
|
||||
return response.empty()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -216,11 +216,12 @@ def list_directories_contents(session: Session, directories_: List[str]) -> Dict
|
|||
|
||||
|
||||
@wrol_mode_check
|
||||
async def delete(*paths: Union[str, pathlib.Path]):
|
||||
async def delete(*paths: Union[str, pathlib.Path], force: bool = False):
|
||||
"""
|
||||
Delete a file or directory in the media directory.
|
||||
|
||||
This will refuse to delete any files (or files in the directories) that have been tagged."""
|
||||
If any files are tagged and force is False, returns a list of tagged FileGroups without deleting.
|
||||
If force is True, deletes even tagged files."""
|
||||
media_directory = get_media_directory()
|
||||
paths = [media_directory / i for i in paths]
|
||||
if any(i == media_directory for i in paths):
|
||||
|
|
@ -235,33 +236,40 @@ async def delete(*paths: Union[str, pathlib.Path]):
|
|||
continue
|
||||
if p1 != p2 and p1 in p2.parents:
|
||||
raise InvalidFile(f'Cannot deleted nested paths')
|
||||
with get_db_session() as session:
|
||||
# Search for any files that have been tagged.
|
||||
for path in paths:
|
||||
query = session.query(FileGroup, TagFile) \
|
||||
.join(TagFile, TagFile.file_group_id == FileGroup.id)
|
||||
if path.is_file():
|
||||
# Could be deleting a file in a FileGroup that has been tagged.
|
||||
stem, _ = split_path_stem_and_suffix(path)
|
||||
query = query.filter(FileGroup.primary_path.like(f'{path.parent}/{stem}%'))
|
||||
else:
|
||||
# Search for any FileGroups that have been tagged under this directory.
|
||||
# Use indexed directory column for efficient lookup
|
||||
path_str = str(path)
|
||||
query = query.filter(or_(
|
||||
FileGroup.directory == path_str,
|
||||
FileGroup.directory.like(f'{path_str}/%')
|
||||
))
|
||||
for (file_group, tag_file) in query:
|
||||
if any(i for i in paths if i in file_group.my_paths()):
|
||||
# File that will be deleted is in a Tagged FileGroup.
|
||||
raise FileGroupIsTagged(f"Cannot delete {file_group} because it is tagged")
|
||||
if not force:
|
||||
tagged_file_groups = []
|
||||
seen_ids = set()
|
||||
with get_db_session() as session:
|
||||
# Search for any files that have been tagged.
|
||||
for path in paths:
|
||||
query = session.query(FileGroup, TagFile) \
|
||||
.join(TagFile, TagFile.file_group_id == FileGroup.id)
|
||||
if path.is_file():
|
||||
# Could be deleting a file in a FileGroup that has been tagged.
|
||||
stem, _ = split_path_stem_and_suffix(path)
|
||||
query = query.filter(FileGroup.primary_path.like(f'{path.parent}/{stem}%'))
|
||||
else:
|
||||
# Search for any FileGroups that have been tagged under this directory.
|
||||
# Use indexed directory column for efficient lookup
|
||||
path_str = str(path)
|
||||
query = query.filter(or_(
|
||||
FileGroup.directory == path_str,
|
||||
FileGroup.directory.like(f'{path_str}/%')
|
||||
))
|
||||
for (file_group, tag_file) in query:
|
||||
if path.is_dir() or any(i for i in paths if i in file_group.my_paths()):
|
||||
if file_group.id not in seen_ids:
|
||||
seen_ids.add(file_group.id)
|
||||
tagged_file_groups.append(file_group)
|
||||
if tagged_file_groups:
|
||||
# Serialize while session is still active.
|
||||
return [i.__json__() for i in tagged_file_groups]
|
||||
for path in paths:
|
||||
ignored_directories = get_wrolpi_config().ignored_directories
|
||||
if ignored_directories and str(path) in ignored_directories:
|
||||
remove_ignored_directory(path)
|
||||
if path.is_dir():
|
||||
delete_directory(path, recursive=True)
|
||||
delete_directory(path, recursive=True, force=force)
|
||||
elif path.exists():
|
||||
path.unlink()
|
||||
|
||||
|
|
@ -1490,26 +1498,27 @@ def _bulk_update_file_groups_reorganize(updates: List[dict]):
|
|||
session.expire_all()
|
||||
|
||||
|
||||
def delete_directory(directory: pathlib.Path, recursive: bool = False):
|
||||
def delete_directory(directory: pathlib.Path, recursive: bool = False, force: bool = False):
|
||||
"""Remove a directory, remove it's Directory record.
|
||||
|
||||
Will refuse to delete a directory if it contains Tagged Files.
|
||||
Will refuse to delete a directory if it contains Tagged Files, unless force is True.
|
||||
|
||||
This function is idempotent - safe to call even if the directory was already deleted."""
|
||||
if directory.exists():
|
||||
if recursive:
|
||||
with get_db_session() as session:
|
||||
# Use indexed directory column for efficient lookup
|
||||
directory_str = str(directory)
|
||||
tagged = session.query(FileGroup) \
|
||||
.filter(or_(
|
||||
FileGroup.directory == directory_str,
|
||||
FileGroup.directory.like(f'{directory_str}/%')
|
||||
)) \
|
||||
.join(TagFile, TagFile.file_group_id == FileGroup.id) \
|
||||
.limit(1).one_or_none()
|
||||
if tagged:
|
||||
raise FileGroupIsTagged(f'Cannot delete {tagged} because it is tagged')
|
||||
if not force:
|
||||
with get_db_session() as session:
|
||||
# Use indexed directory column for efficient lookup
|
||||
directory_str = str(directory)
|
||||
tagged = session.query(FileGroup) \
|
||||
.filter(or_(
|
||||
FileGroup.directory == directory_str,
|
||||
FileGroup.directory.like(f'{directory_str}/%')
|
||||
)) \
|
||||
.join(TagFile, TagFile.file_group_id == FileGroup.id) \
|
||||
.limit(1).one_or_none()
|
||||
if tagged:
|
||||
raise FileGroupIsTagged(f'Cannot delete {tagged} because it is tagged')
|
||||
shutil.rmtree(directory)
|
||||
else:
|
||||
directory.rmdir()
|
||||
|
|
|
|||
|
|
@ -451,11 +451,11 @@ class FileGroup(ModelHelper, Base):
|
|||
else:
|
||||
self.replace_info_json(contents)
|
||||
|
||||
def delete(self, add_to_skip_list: bool = True):
|
||||
def delete(self, add_to_skip_list: bool = True, force: bool = False):
|
||||
"""Delete this FileGroup record, and all of its files.
|
||||
|
||||
@raise FileGroupIsTagged: If any tags are related to me."""
|
||||
if self.tag_files:
|
||||
@raise FileGroupIsTagged: If any tags are related to me and force is False."""
|
||||
if self.tag_files and not force:
|
||||
raise FileGroupIsTagged(f'Cannot delete {self} because it has tags')
|
||||
|
||||
for path in self.my_paths():
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ class FileRequest:
|
|||
@dataclass
|
||||
class DeleteRequest:
|
||||
paths: List[str] = field(default_factory=list)
|
||||
force: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
|
|||
|
|
@ -118,8 +118,8 @@ async def test_delete_file_link(async_client, test_session, test_directory):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_tagged(await_switches, test_session, make_files_structure, tag_factory, video_bytes,
|
||||
refresh_files):
|
||||
async def test_delete_tagged(await_switches, test_session, test_directory, make_files_structure, tag_factory,
|
||||
video_bytes, refresh_files):
|
||||
"""Cannot delete a file that has been tagged."""
|
||||
tag = await tag_factory()
|
||||
make_files_structure({'foo/bar.txt': 'asdf', 'foo/bar.mp4': video_bytes})
|
||||
|
|
@ -130,13 +130,17 @@ async def test_delete_tagged(await_switches, test_session, make_files_structure,
|
|||
await await_switches()
|
||||
test_session.commit()
|
||||
|
||||
# Neither file can be deleted.
|
||||
with pytest.raises(FileGroupIsTagged):
|
||||
await lib.delete('foo/bar.txt')
|
||||
with pytest.raises(FileGroupIsTagged):
|
||||
await lib.delete('foo/bar.mp4')
|
||||
with pytest.raises(FileGroupIsTagged):
|
||||
await lib.delete('foo')
|
||||
# Neither file can be deleted without force; tagged file groups are returned.
|
||||
result = await lib.delete('foo/bar.txt')
|
||||
assert result and len(result) == 1
|
||||
result = await lib.delete('foo/bar.mp4')
|
||||
assert result and len(result) == 1
|
||||
result = await lib.delete('foo')
|
||||
assert result and len(result) == 1
|
||||
|
||||
# Force delete succeeds and actually removes the files.
|
||||
await lib.delete('foo', force=True)
|
||||
assert not (test_directory / 'foo').exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue