From 8fb9e35aefc339085ce739c6b058a45965b77f51 Mon Sep 17 00:00:00 2001 From: Roland Date: Tue, 14 Apr 2026 10:40:24 -0600 Subject: [PATCH] Displaying confirmation modal when deleting tagged files, rather than just refusing to delete them. --- app/src/api.js | 12 ++++- app/src/components/FileBrowser.js | 55 +++++++++++++++++++- wrolpi/files/api.py | 7 ++- wrolpi/files/lib.py | 85 +++++++++++++++++-------------- wrolpi/files/models.py | 6 +-- wrolpi/files/schema.py | 1 + wrolpi/files/test/test_lib.py | 22 ++++---- 7 files changed, 133 insertions(+), 55 deletions(-) diff --git a/app/src/api.js b/app/src/api.js index cb795d77..b4772a40 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -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', diff --git a/app/src/components/FileBrowser.js b/app/src/components/FileBrowser.js index 05014adf..f77aa791 100644 --- a/app/src/components/FileBrowser.js +++ b/app/src/components/FileBrowser.js @@ -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} /> + setTaggedFileGroups(null)} + closeIcon + > + Tagged Files Will Be Deleted + +

The following tagged files will be deleted:

+ + + + File + Tags + + + + {taggedFileGroups && taggedFileGroups.map((fg, idx) => ( + + {fg.primary_path || fg.name} + {(fg.tags || []).join(', ')} + + ))} + +
+
+ + + + +
; const onFolderClick = async (folder) => { diff --git a/wrolpi/files/api.py b/wrolpi/files/api.py index 2a397ed7..1539af13 100644 --- a/wrolpi/files/api.py +++ b/wrolpi/files/api.py @@ -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() diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index b187458d..b512ba96 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -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() diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index badc9c9d..1285ff8b 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -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(): diff --git a/wrolpi/files/schema.py b/wrolpi/files/schema.py index c9992557..84625f18 100644 --- a/wrolpi/files/schema.py +++ b/wrolpi/files/schema.py @@ -18,6 +18,7 @@ class FileRequest: @dataclass class DeleteRequest: paths: List[str] = field(default_factory=list) + force: bool = False @dataclass diff --git a/wrolpi/files/test/test_lib.py b/wrolpi/files/test/test_lib.py index 7d59635d..cfa92caf 100644 --- a/wrolpi/files/test/test_lib.py +++ b/wrolpi/files/test/test_lib.py @@ -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