Skip to content

TagSpaces is an offline, open source, document manager with tagging support

Replace native file exist dialog on copy and add progress dialog (#1945)

Stanimir18742331bf67
diff --git a/app/components/DirectoryListView.tsx b/app/components/DirectoryListView.tsx
index a2d96ad11..5a7132148 100644
--- a/app/components/DirectoryListView.tsx
+++ b/app/components/DirectoryListView.tsx
@@ -125,6 +125,7 @@ function DirectoryListView(props: Props) {
if (directoryContent && directoryContent.length > 0) {
return directoryContent.map(entry => (
<ListItem
+ key={entry.path}
data-tid={'MoveTarget' + entry.name}
title={'Navigate to: ' + entry.path}
onClick={() => {
diff --git a/app/components/dialogs/MoveCopyFilesDialog.tsx b/app/components/dialogs/MoveCopyFilesDialog.tsx
index 47bf6273e..9d7e0727d 100644
--- a/app/components/dialogs/MoveCopyFilesDialog.tsx
+++ b/app/components/dialogs/MoveCopyFilesDialog.tsx
@@ -21,13 +21,11 @@ import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Progress } from 'aws-sdk/clients/s3';
import { formatBytes } from '@tagspaces/tagspaces-common/misc';
-import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Button from '@mui/material/Button';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
-import ListSubheader from '@mui/material/ListSubheader';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
@@ -50,22 +48,29 @@ import { TS } from '-/tagspaces.namespace';
import DirectoryListView from '-/components/DirectoryListView';
import AppConfig from '-/AppConfig';
import Tooltip from '-/components/Tooltip';
+import ConfirmDialog from '-/components/dialogs/ConfirmDialog';
+import {
+ checkDirsExistPromise,
+ checkFilesExistPromise
+} from '-/services/utils-io';
interface Props {
open: boolean;
onClose: (clearSelection?: boolean) => void;
currentDirectoryPath: string | null;
- copyFiles: (files: Array<string>, destination: string) => void;
+ copyFiles: (
+ files: Array<string>,
+ destination: string,
+ onUploadProgress?: (progress: Progress, abort: () => void) => void
+ ) => void;
copyDirs: (
- dirs: Array<string>,
- totalCount: number,
+ dirs: Array<any>,
destination: string,
onUploadProgress?: (progress: Progress, abort: () => void) => void
) => void;
moveFiles: (files: Array<string>, destination: string) => void;
moveDirs: (
- dirs: Array<string>,
- totalCount: number,
+ dirs: Array<any>,
destination: string,
onUploadProgress?: (progress: Progress, abort: () => void) => void
) => void;
@@ -81,6 +86,8 @@ function MoveCopyFilesDialog(props: Props) {
const [targetPath, setTargetPath] = useState(
props.currentDirectoryPath ? props.currentDirectoryPath : ''
);
+ const isCopy = useRef<boolean>(true);
+ const [entriesExistPath, setEntriesExistPath] = useState<string[]>(undefined);
const dirProp = useRef({});
const [ignored, forceUpdate] = useReducer(x => x + 1, 0);
@@ -135,26 +142,56 @@ function MoveCopyFilesDialog(props: Props) {
}
}*/
- function getEntriesCount(): number {
- let total = 0;
+ function getEntriesCount(dirPaths): Array<any> {
+ return dirPaths.map(path => {
+ const currDirProp = dirProp.current[path];
+ let count = 0;
+ if (currDirProp) {
+ count = currDirProp.filesCount + currDirProp.dirsCount;
+ }
+ return { path, count };
+ });
+ /*let total = 0;
const arr = Object.values(dirProp.current);
arr.forEach((n: TS.DirProp) => (total += n.filesCount + n.dirsCount));
- return total;
+ return total;*/
+ }
+
+ function handleCopyMove(copy = true) {
+ if (selectedFiles.length > 0) {
+ checkFilesExistPromise(selectedFiles, targetPath).then(exist =>
+ handleEntryExist(copy, exist)
+ );
+ }
+ if (selectedDirs.length > 0) {
+ checkDirsExistPromise(selectedDirs, targetPath).then(exist =>
+ handleEntryExist(copy, exist)
+ );
+ }
}
+ function handleEntryExist(copy: boolean, exist: string[]) {
+ if (exist && exist.length > 0) {
+ isCopy.current = copy;
+ setEntriesExistPath(exist);
+ } else if (copy) {
+ handleCopyFiles();
+ } else {
+ handleMoveFiles();
+ }
+ }
function handleCopyFiles() {
//if (!disableConfirmButton) {
+ props.resetProgress();
+ props.toggleUploadDialog('copyEntriesTitle');
if (selectedFiles.length > 0) {
- props.copyFiles(selectedFiles, targetPath);
+ props.copyFiles(selectedFiles, targetPath, props.onUploadProgress);
//setDisableConfirmButton(true);
setTargetPath('');
}
if (selectedDirs.length > 0) {
- props.resetProgress();
- props.toggleUploadDialog('copyEntriesTitle');
props.copyDirs(
- selectedDirs,
- getEntriesCount(),
+ getEntriesCount(selectedDirs),
targetPath,
props.onUploadProgress
);
@@ -173,8 +210,7 @@ function MoveCopyFilesDialog(props: Props) {
props.resetProgress();
props.toggleUploadDialog('moveEntriesTitle');
props.moveDirs(
- selectedDirs,
- getEntriesCount(),
+ getEntriesCount(selectedDirs),
targetPath,
props.onUploadProgress
);
@@ -197,6 +233,13 @@ function MoveCopyFilesDialog(props: Props) {
onClose();
}
+ function formatFileExist(entries) {
+ if (entries !== undefined) {
+ return entries.join(', ');
+ }
+ return '';
+ }
+
const theme = useTheme();
const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
return (
@@ -283,7 +326,7 @@ function MoveCopyFilesDialog(props: Props) {
AppConfig.isAndroid ||
targetPath === props.currentDirectoryPath
}
- onClick={handleMoveFiles}
+ onClick={() => handleCopyMove(false)}
color="primary"
variant="contained"
>
@@ -291,8 +334,33 @@ function MoveCopyFilesDialog(props: Props) {
</Button>
</span>
</Tooltip>
+ <ConfirmDialog
+ open={entriesExistPath !== undefined}
+ onClose={() => {
+ setEntriesExistPath(undefined);
+ }}
+ title={i18n.t('core:confirm')}
+ content={
+ formatFileExist(entriesExistPath) +
+ ' exist do you want to override it?'
+ }
+ confirmCallback={result => {
+ if (result) {
+ if (isCopy.current) {
+ handleCopyFiles();
+ } else {
+ handleMoveFiles();
+ }
+ } else {
+ setEntriesExistPath(undefined);
+ }
+ }}
+ cancelDialogTID="cancelSaveBeforeCloseDialog"
+ confirmDialogTID="confirmSaveBeforeCloseDialog"
+ confirmDialogContentTID="confirmDialogContent"
+ />
<Button
- onClick={handleCopyFiles}
+ onClick={() => handleCopyMove(true)}
data-tid="confirmCopyFiles"
disabled={!targetPath || targetPath === props.currentDirectoryPath}
color="primary"
diff --git a/app/package.json b/app/package.json
index 4f2ff0b45..543dcee58 100644
--- a/app/package.json
+++ b/app/package.json
@@ -16,7 +16,7 @@
"@tagspaces/extensions": "1.0.86"
},
"nodeDependencies": {
- "@tagspaces/tagspaces-ws": "2.1.43",
+ "@tagspaces/tagspaces-ws": "2.1.54",
"@tagspaces/extensions": "1.0.86",
"sharp": "0.31.3"
}
diff --git a/app/reducers/io-actions.ts b/app/reducers/io-actions.ts
index a597bb812..8fa542cb5 100644
--- a/app/reducers/io-actions.ts
+++ b/app/reducers/io-actions.ts
@@ -27,6 +27,7 @@ import {
getThumbFileLocationForFile,
getBackupFileDir,
normalizePath,
+ getMetaDirectoryPath,
extractDirectoryName,
joinPaths
} from '@tagspaces/tagspaces-common/paths';
@@ -74,24 +75,23 @@ const actions = {
);
},
moveDirs: (
- paths: Array<string>,
- totalCount: number,
+ dirPaths: Array<any>,
targetPath: string,
onProgress = undefined
) => (dispatch: (actions: Object) => void) => {
- const promises = paths.map(dirPath => {
+ const promises = dirPaths.map(({path, count}) => {
const dirName = extractDirectoryName(
- dirPath,
+ path,
PlatformIO.getDirSeparator()
);
return PlatformIO.moveDirectoryPromise(
- { path: dirPath, total: totalCount },
+ { path: path, total: count },
joinPaths(PlatformIO.getDirSeparator(), targetPath, dirName),
onProgress
)
.then(() => {
- console.log('Moving dir from ' + dirPath + ' to ' + targetPath);
- dispatch(AppActions.reflectDeleteEntry(dirPath));
+ console.log('Moving dir from ' + path + ' to ' + targetPath);
+ dispatch(AppActions.reflectDeleteEntry(path));
return true;
})
.catch(err => {
@@ -156,7 +156,9 @@ const actions = {
});
}
})
- .catch(e => console.debug('loadFileMetaDataPromise', e));
+ .catch(err => {
+ console.warn('loadFileMetaDataPromise', err);
+ });
// move meta
moveMetaJobs.push([
@@ -195,23 +197,22 @@ const actions = {
});
},
copyDirs: (
- paths: Array<string>,
- totalCount: number,
+ dirPaths: Array<any>,
targetPath: string,
onProgress = undefined
) => (dispatch: (actions: Object) => void) => {
- const promises = paths.map(dirPath => {
+ const promises = dirPaths.map(({path, count}) => {
const dirName = extractDirectoryName(
- dirPath,
+ path,
PlatformIO.getDirSeparator()
);
return PlatformIO.copyDirectoryPromise(
- { path: dirPath, total: totalCount },
+ { path: path, total: count },
joinPaths(PlatformIO.getDirSeparator(), targetPath, dirName),
onProgress
)
.then(() => {
- console.log('Copy dir from ' + dirPath + ' to ' + targetPath);
+ console.log('Copy dir from ' + path + ' to ' + targetPath);
return true;
})
.catch(err => {
@@ -223,58 +224,47 @@ const actions = {
});
return Promise.all(promises).then(() => true);
},
- copyFiles: (paths: Array<string>, targetPath: string) => (
+ copyFiles: (paths: Array<string>, targetPath: string, onProgress) => (
dispatch: (actions: Object) => void
) => {
- const copyJobs = paths.map(path => {
- const targetFile =
- normalizePath(targetPath) +
- PlatformIO.getDirSeparator() +
- extractFileName(path, PlatformIO.getDirSeparator());
- return [path, targetFile];
- });
-
- const targetFiles: string[] = copyJobs.map(job => job[1]);
-
- copyFilesPromise(copyJobs)
+ copyFilesPromise(paths, targetPath, onProgress)
.then(() => {
+ // todo return only copied paths
dispatch(
AppActions.showNotification(i18n.t('core:filesCopiedSuccessful'))
);
- const copyMetaJobs = copyJobs.flatMap(job => [
- [
- getMetaFileLocationForFile(job[0], PlatformIO.getDirSeparator()),
- getMetaFileLocationForFile(job[1], PlatformIO.getDirSeparator())
- ],
- [
- getThumbFileLocationForFile(
- job[0],
- PlatformIO.getDirSeparator(),
- false
- ),
- getThumbFileLocationForFile(
- job[1],
- PlatformIO.getDirSeparator(),
- false
- )
- ]
+ const metaPaths = paths.flatMap(path => [
+ getMetaFileLocationForFile(path, PlatformIO.getDirSeparator()),
+ getThumbFileLocationForFile(path, PlatformIO.getDirSeparator(), false)
]);
- copyFilesPromise(copyMetaJobs)
+
+ /*const targetFiles: string[] = paths.map(
+ path =>
+ normalizePath(targetPath) +
+ PlatformIO.getDirSeparator() +
+ extractFileName(path, PlatformIO.getDirSeparator())
+ );*/
+
+ copyFilesPromise(
+ metaPaths,
+ getMetaDirectoryPath(targetPath),
+ onProgress
+ )
.then(() => {
console.log('Copy meta and thumbs successful');
- dispatch(
+ /*dispatch(
AppActions.reflectCreateEntries(
targetFiles.map(filePath => toFsEntry(filePath, true))
)
- );
+ );*/
return true;
})
.catch(err => {
- dispatch(
+ /*dispatch(
AppActions.reflectCreateEntries(
targetFiles.map(filePath => toFsEntry(filePath, true))
)
- );
+ );*/
console.warn('At least one meta or thumb was not copied ' + err);
});
return true;
diff --git a/app/services/utils-io.ts b/app/services/utils-io.ts
index 58ddf9a3e..312add34d 100644
--- a/app/services/utils-io.ts
+++ b/app/services/utils-io.ts
@@ -42,6 +42,7 @@ import {
extractContainingDirectoryPath,
extractDirectoryName,
extractFileName,
+ normalizePath,
getThumbFileLocationForFile,
getThumbFileLocationForDirectory,
getBgndFileLocationForDirectory,
@@ -687,12 +688,161 @@ export function renameFilesPromise(
);
}
-export function copyFilesPromise(copyJobs: Array<Array<string>>) {
- const ioJobPromises = [];
- copyJobs.forEach(copyJob => {
- ioJobPromises.push(PlatformIO.copyFilePromise(copyJob[0], copyJob[1]));
+/*function getCommonFolder(paths: Array<string>) {
+ const rootFolders = paths.map(p =>
+ extractContainingDirectoryPath(p, PlatformIO.getDirSeparator())
+ );
+ const firstRootFolder = rootFolders[0];
+ if (rootFolders.every(rf => rf === firstRootFolder)) {
+ return firstRootFolder;
+ }
+ return false;
+}*/
+
+function trackProgress(promises, abortSignal, progress) {
+ const total = promises.length;
+ let completed = 0;
+ let aborted = false;
+
+ // Create an array of promises that resolve when the original promises resolve
+ const progressPromises = promises.map(({ promise, path }) =>
+ promise
+ .then(() => {
+ if (!aborted) {
+ completed++;
+ // console.log(`Progress: ${completed}/${total}`);
+ if (progress) {
+ progress(completed, path);
+ }
+ }
+ })
+ .catch(err => {
+ console.warn('Promise ' + path + ' error:', err);
+ completed++;
+ })
+ );
+
+ // Use Promise.race() to wait for all progress promises to resolve
+ return Promise.race(progressPromises)
+ .then(() => Promise.all(promises))
+ .catch(err => {
+ if (abortSignal.aborted) {
+ aborted = true;
+ console.warn('Promise execution aborted');
+ } else {
+ throw err;
+ }
+ });
+}
+
+export function isFulfilled<T>(
+ result: PromiseSettledResult<T>
+): result is PromiseFulfilledResult<T> {
+ return result.status === 'fulfilled';
+}
+
+export function isRejected<T>(
+ result: PromiseSettledResult<T>
+): result is PromiseRejectedResult {
+ return result.status === 'rejected';
+}
+
+export function getFulfilledResults<T>(
+ results: Array<PromiseSettledResult<T>>
+) {
+ return results.filter(isFulfilled).map(result => result.value);
+}
+
+interface FileExistenceCheck {
+ promise: Promise<boolean>;
+ path: string;
+}
+
+export function checkFilesExistPromise(
+ paths: string[],
+ targetPath: string
+): Promise<Array<string>> {
+ const promises: FileExistenceCheck[] = paths.map(path => {
+ const targetFile =
+ normalizePath(targetPath) +
+ PlatformIO.getDirSeparator() +
+ extractFileName(path, PlatformIO.getDirSeparator());
+ return { promise: PlatformIO.checkFileExist(targetFile), path };
+ });
+ const progressPromises: Array<Promise<string>> = promises.map(
+ ({ promise, path }) =>
+ promise
+ .then(exists => (exists ? path : ''))
+ .catch(err => {
+ console.warn(`Promise ${path} error:`, err);
+ return '';
+ })
+ );
+
+ return Promise.allSettled(progressPromises).then(results => {
+ return getFulfilledResults(results).filter(r => r);
+ });
+}
+
+export function checkDirsExistPromise(
+ paths: string[],
+ targetPath: string
+): Promise<Array<string>> {
+ const promises: FileExistenceCheck[] = paths.map(path => {
+ const targetDir =
+ normalizePath(targetPath) +
+ PlatformIO.getDirSeparator() +
+ extractDirectoryName(path, PlatformIO.getDirSeparator());
+ return { promise: PlatformIO.checkDirExist(targetDir), path };
+ });
+ const progressPromises: Array<Promise<string>> = promises.map(
+ ({ promise, path }) =>
+ promise
+ .then(exists => (exists ? path : ''))
+ .catch(err => {
+ console.warn(`Promise ${path} error:`, err);
+ return '';
+ })
+ );
+
+ return Promise.allSettled(progressPromises).then(results => {
+ return getFulfilledResults(results).filter(r => r);
});
- return Promise.all(ioJobPromises);
+}
+
+export function copyFilesPromise(
+ paths: Array<string>,
+ targetPath: string,
+ onProgress = undefined
+) {
+ const controller = new AbortController();
+ const signal = controller.signal;
+
+ const ioJobPromises = paths.map(path => {
+ const targetFile =
+ normalizePath(targetPath) +
+ PlatformIO.getDirSeparator() +
+ extractFileName(path, PlatformIO.getDirSeparator());
+ return {
+ promise: PlatformIO.copyFilePromiseOverwrite(path, targetFile),
+ path: path
+ };
+ });
+ const progress = (completed, path) => {
+ const progress = {
+ loaded: completed, //processedSize,
+ total: ioJobPromises.length,
+ key: targetPath
+ };
+ onProgress(
+ progress,
+ () => {
+ controller.abort();
+ },
+ path
+ );
+ };
+ return trackProgress(ioJobPromises, signal, progress);
}
export async function loadSubFolders(path: string, loadHidden = false) {
diff --git a/package-lock.json b/package-lock.json
index 40590ca51..0d102da53 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -21,7 +21,7 @@
"@mui/styles": "^5.13.7",
"@mui/x-date-pickers": "^5.0.20",
"@tagspaces/tagspaces-md": "2.1.6",
- "@tagspaces/tagspaces-platforms": "2.1.43",
+ "@tagspaces/tagspaces-platforms": "2.1.54",
"aws-amplify": "^4.3.8",
"aws-sdk": "^2.1036.0",
"babel-polyfill": "^6.26.0",
@@ -12655,9 +12655,9 @@
}
},
"node_modules/@tagspaces/tagspaces-platforms": {
- "version": "2.1.43",
- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-2.1.43.tgz",
- "integrity": "sha512-AvltagXCuyeOom3ckk1MQFGk19yAiJE7ZbLzNWxaUmfLS8o1Mba313xTQ9WNi1zfnNzaGMB2kMUfjoph9sNtHA==",
+ "version": "2.1.54",
+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-2.1.54.tgz",
+ "integrity": "sha512-LJcW2D/06o9uO+40vIJ6icyRKk8tGBmNzSZALY3clymvhD+Gt49JLAZ/8hE0boOKossR6VOtXU47YFrmQlHrYA==",
"hasInstallScript": true
},
"node_modules/@testim/chrome-version": {
@@ -53250,9 +53250,9 @@
}
},
"@tagspaces/tagspaces-platforms": {
- "version": "2.1.43",
- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-2.1.43.tgz",
- "integrity": "sha512-AvltagXCuyeOom3ckk1MQFGk19yAiJE7ZbLzNWxaUmfLS8o1Mba313xTQ9WNi1zfnNzaGMB2kMUfjoph9sNtHA=="
+ "version": "2.1.54",
+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-2.1.54.tgz",
+ "integrity": "sha512-LJcW2D/06o9uO+40vIJ6icyRKk8tGBmNzSZALY3clymvhD+Gt49JLAZ/8hE0boOKossR6VOtXU47YFrmQlHrYA=="
},
"@testim/chrome-version": {
"version": "1.1.3",
diff --git a/package.json b/package.json
index 8f821e2c7..800fb0091 100644
--- a/package.json
+++ b/package.json
@@ -150,7 +150,7 @@
"@mui/styles": "^5.13.7",
"@mui/x-date-pickers": "^5.0.20",
"@tagspaces/tagspaces-md": "2.1.6",
- "@tagspaces/tagspaces-platforms": "2.1.43",
+ "@tagspaces/tagspaces-platforms": "2.1.54",
"aws-amplify": "^4.3.8",
"aws-sdk": "^2.1036.0",
"babel-polyfill": "^6.26.0",
diff --git a/tests/e2e/folderprops.pw.e2e.js b/tests/e2e/folderprops.pw.e2e.js
index 1ad5b3f00..65e1b7188 100644
--- a/tests/e2e/folderprops.pw.e2e.js
+++ b/tests/e2e/folderprops.pw.e2e.js
@@ -237,6 +237,7 @@ test.describe('TST02 - Folder properties', () => {
);
await clickOn('[data-tid=MoveTargetempty_folder]');
await clickOn('[data-tid=confirmCopyFiles]');
+ await clickOn('[data-tid=uploadCloseAndClearTID]');
await clickOn('[data-tid=changePerspectiveTID]');
await clickOn('[data-value=gallery]');
diff --git a/tests/e2e/perspective-grid-right-button.pw.e2e.js b/tests/e2e/perspective-grid-right-button.pw.e2e.js
index 59c54166e..36f2d2a9e 100644
--- a/tests/e2e/perspective-grid-right-button.pw.e2e.js
+++ b/tests/e2e/perspective-grid-right-button.pw.e2e.js
@@ -352,6 +352,7 @@ test.describe('TST50** - Right button on a file', () => {
await clickOn('[data-tid=MoveTarget' + folderName + ']');
await clickOn('[data-tid=confirmMoveFiles]');
+
//await waitForNotification();
await expectElementExist(getGridFileSelector(fileName), false);
@@ -367,6 +368,7 @@ test.describe('TST50** - Right button on a file', () => {
// await setInputKeys('targetPathInput', defaultLocationPath);
await clickOn('[data-tid=navigateToParentTID]');
await clickOn('[data-tid=confirmCopyFiles]');
+ await clickOn('[data-tid=uploadCloseAndClearTID]');
await clickOn('[data-tid=gridPerspectiveOnBackButton]');
await expectElementExist(getGridFileSelector(fileName), true);
diff --git a/tests/e2e/perspective-grid.pw.e2e.js b/tests/e2e/perspective-grid.pw.e2e.js
index f3439d3c1..257272971 100644
--- a/tests/e2e/perspective-grid.pw.e2e.js
+++ b/tests/e2e/perspective-grid.pw.e2e.js
@@ -176,6 +176,7 @@ test.describe('TST50 - Perspective Grid', () => {
await clickOn('[data-tid=gridPerspectiveCopySelectedFiles]');
await clickOn('[data-tid=MoveTargetempty_folder]');
await clickOn('[data-tid=confirmCopyFiles]');
+ await clickOn('[data-tid=uploadCloseAndClearTID]');
await global.client.dblclick(getGridFileSelector('empty_folder'));
await expectElementExist(getGridFileSelector(fileName));