Skip to content

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

Handle better error if file edited on save on S3 (#1892)

Stanimircfe8a6f1ccd0
diff --git a/app/components/EntryContainer.tsx b/app/components/EntryContainer.tsx
index 88e14c7cf..bdf6f30b9 100644
--- a/app/components/EntryContainer.tsx
+++ b/app/components/EntryContainer.tsx
@@ -103,6 +103,7 @@ import { actions as LocationActions, getLocations } from '-/reducers/locations';
import Revisions from '-/components/Revisions';
import { Switch } from '@mui/material';
import useFirstRender from '-/utils/useFirstRender';
+import ResolveConflictDialog from '-/components/dialogs/ResolveConflictDialog';
const defaultSplitSize = '7.86%'; // '7.2%'; // 103;
// const openedSplitSize = AppConfig.isElectron ? 560 : 360;
@@ -254,6 +255,9 @@ function EntryContainer(props: Props) {
const [isEditTagsModalOpened, setEditTagsModalOpened] = useState<boolean>(
false
);
+ const [isConflictDialogOpen, setConflictDialogOpen] = useState<boolean>(
+ false
+ );
const [isDeleteEntryModalOpened, setDeleteEntryModalOpened] = useState<
boolean
>(false);
@@ -597,12 +601,10 @@ function EntryContainer(props: Props) {
fileViewer.current.contentWindow.getContent
) {
try {
- // @ts-ignore
- const textContent = fileViewer.current.contentWindow.getContent();
//check if file is changed
if (fileChanged.current) {
setSavingInProgress(true);
- saveFile(textContent).then(success => {
+ saveFile().then(success => {
if (success) {
fileChanged.current = false;
// showNotification(
@@ -621,65 +623,110 @@ function EntryContainer(props: Props) {
}
};
- const saveFile = (textContent: string): Promise<boolean> => {
+ const override = (): Promise<boolean> => {
return props
.switchLocationType(openedFile.locationId)
- .then(async currentLocationId => {
- if (Pro && props.revisionsEnabled) {
- const id = await Pro.MetaOperations.getMetadataID(
- openedFile.path,
- openedFile.uuid
- );
- const targetPath = getBackupFileLocation(
- openedFile.path,
- id,
- PlatformIO.getDirSeparator()
- );
- await PlatformIO.copyFilePromiseOverwrite(
- openedFile.path,
- targetPath
+ .then(currentLocationId =>
+ PlatformIO.getPropertiesPromise(
+ openedFile.path
+ ).then((entryProp: TS.FileSystemEntry) =>
+ save({ ...openedFile, lmdt: entryProp.lmdt }).then(() =>
+ props.switchCurrentLocationType(currentLocationId)
+ )
+ )
+ );
+ };
+
+ const saveAs = (newFilePath: string): Promise<boolean> => {
+ return props
+ .switchLocationType(openedFile.locationId)
+ .then(currentLocationId =>
+ PlatformIO.copyFilePromise(openedFile.path, newFilePath).then(() =>
+ PlatformIO.getPropertiesPromise(newFilePath).then(
+ (entryProp: TS.FileSystemEntry) =>
+ save({
+ ...openedFile,
+ path: entryProp.path,
+ lmdt: entryProp.lmdt
+ }).then(() => {
+ const openedFileDir = extractContainingDirectoryPath(
+ entryProp.path
+ );
+ if (currentDirectoryPath === openedFileDir) {
+ props.loadDirectoryContent(
+ openedFileDir,
+ true,
+ true
+ ); /*
+ updateOpenedFile(openedFile.path, {
+ ...openedFile,
+ editMode: false,
+ shouldReload: !openedFile.shouldReload
+ });*/
+ }
+ return props.switchCurrentLocationType(currentLocationId);
+ })
+ )
+ )
+ );
+ };
+
+ const saveFile = (): Promise<boolean> => {
+ return props
+ .switchLocationType(openedFile.locationId)
+ .then(currentLocationId =>
+ save(openedFile).then(() =>
+ props.switchCurrentLocationType(currentLocationId)
+ )
+ );
+ };
+
+ async function save(fileOpen: OpenedEntry): Promise<boolean> {
+ // @ts-ignore
+ const textContent = fileViewer.current.contentWindow.getContent();
+ if (Pro && props.revisionsEnabled) {
+ const id = await Pro.MetaOperations.getMetadataID(
+ fileOpen.path,
+ fileOpen.uuid
+ );
+ const targetPath = getBackupFileLocation(
+ fileOpen.path,
+ id,
+ PlatformIO.getDirSeparator()
+ );
+ await PlatformIO.copyFilePromiseOverwrite(fileOpen.path, targetPath);
+ }
+ return PlatformIO.saveTextFilePromise(
+ { path: fileOpen.path, lmdt: fileOpen.lmdt },
+ textContent,
+ true
+ )
+ .then(() => {
+ if (Pro) {
+ Pro.history.saveHistory(
+ historyKeys.fileEditKey,
+ {
+ path: fileOpen.path,
+ url: fileOpen.url,
+ lid: fileOpen.locationId
+ },
+ settings[historyKeys.fileEditKey]
);
}
- // TODO check for timestamp on filesystem and ask to overwrite the changes there
- return PlatformIO.saveTextFilePromise(
- { path: openedFile.path, lmdt: openedFile.lmdt },
- textContent,
- true
- )
- .then(result => {
- if (Pro) {
- Pro.history.saveHistory(
- historyKeys.fileEditKey,
- {
- path: openedFile.path,
- url: openedFile.url,
- lid: openedFile.locationId
- },
- settings[historyKeys.fileEditKey]
- );
- }
- return updateOpenedFile(openedFile.path, {
- ...openedFile,
- editMode: true,
- changed: false,
- shouldReload: undefined
- }).then(() => props.switchCurrentLocationType(currentLocationId));
- })
- .catch(error => {
- // setSavingInProgress(false);
- showNotification(
- i18n.t('core:errorSavingFile') + ': ' + error.message,
- NotificationTypes.error,
- false
- );
- console.log('Error saving file ' + openedFile.path + ' - ' + error);
- return props
- .switchCurrentLocationType(currentLocationId)
- .then(() => false);
- });
+ return updateOpenedFile(fileOpen.path, {
+ ...fileOpen,
+ editMode: true,
+ changed: false,
+ shouldReload: undefined
+ }).then(() => true);
+ })
+ .catch(error => {
+ setConflictDialogOpen(true);
+ console.log('Error saving file ' + fileOpen.path + ' - ' + error);
+ return false;
});
- };
+ }
const editFile = () => {
props.switchLocationType(openedFile.locationId).then(currentLocationId => {
@@ -1569,6 +1616,13 @@ function EntryContainer(props: Props) {
selectedEntries={openedFile ? [openedFile] : []}
/>
)}
+ <ResolveConflictDialog
+ open={isConflictDialogOpen}
+ onClose={() => setConflictDialogOpen(false)}
+ file={openedFile}
+ saveAs={saveAs}
+ override={override}
+ />
{/* eslint-disable-next-line jsx-a11y/anchor-has-content,jsx-a11y/anchor-is-valid */}
<a href="#" id="downloadFile" />
{renderPanels()}
diff --git a/app/components/dialogs/ResolveConflictDialog.tsx b/app/components/dialogs/ResolveConflictDialog.tsx
new file mode 100644
index 000000000..0c93259a4
--- /dev/null
+++ b/app/components/dialogs/ResolveConflictDialog.tsx
@@ -0,0 +1,160 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License (version 3) as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+import React from 'react';
+import Button from '@mui/material/Button';
+import DialogActions from '@mui/material/DialogActions';
+import DialogContent from '@mui/material/DialogContent';
+import DialogTitle from '@mui/material/DialogTitle';
+import TextField from '@mui/material/TextField';
+import Dialog from '@mui/material/Dialog';
+import i18n from '-/services/i18n';
+import DialogCloseButton from '-/components/dialogs/DialogCloseButton';
+import useMediaQuery from '@mui/material/useMediaQuery';
+import useTheme from '@mui/styles/useTheme';
+import { OpenedEntry } from '-/reducers/app';
+import {
+ extractContainingDirectoryPath,
+ extractFileExtension,
+ extractFileName
+} from '@tagspaces/tagspaces-common/paths';
+import PlatformFacade from '-/services/platform-facade';
+import AppConfig from '-/AppConfig';
+
+interface Props {
+ open: boolean;
+ onClose: () => void;
+ file: OpenedEntry;
+ saveAs: (newFilePath: string) => Promise<boolean>;
+ override: () => Promise<boolean>;
+}
+
+function ResolveConflictDialog(props: Props) {
+ const { open, onClose } = props;
+ const copyFileName = React.useRef<string>(getFileName());
+ const [isSaveAs, setSaveAs] = React.useState<boolean>(false);
+
+ const theme = useTheme();
+ const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
+
+ function getFileName() {
+ const fileName = extractFileName(props.file.path);
+ const ext = extractFileExtension(props.file.path);
+ return fileName.slice(0, -(ext.length + 1)) + '-copy.' + ext;
+ }
+
+ return (
+ <Dialog
+ open={open}
+ onClose={onClose}
+ fullScreen={fullScreen}
+ keepMounted
+ scroll="paper"
+ aria-labelledby="draggable-dialog-title"
+ >
+ <DialogTitle style={{ cursor: 'move' }} id="draggable-dialog-title">
+ {i18n.t('core:resolveConflictTitle')}
+ <DialogCloseButton onClose={onClose} />
+ </DialogTitle>
+ <DialogContent
+ style={{
+ overflow: AppConfig.isFirefox ? 'auto' : 'overlay',
+ minWidth: 400
+ }}
+ >
+ {isSaveAs ? (
+ <TextField
+ label={i18n.t('core:newFileName')}
+ margin="dense"
+ name="name"
+ fullWidth={true}
+ data-tid="newFileNameTID"
+ defaultValue={copyFileName.current}
+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
+ copyFileName.current = event.target.value;
+ }}
+ />
+ ) : (
+ i18n.t('core:resolveConflictDesc')
+ )}
+ </DialogContent>
+ <DialogActions>
+ {isSaveAs ? (
+ <>
+ <Button
+ data-tid="backTID"
+ title={i18n.t('core:cancel')}
+ onClick={() => {
+ setSaveAs(false);
+ onClose();
+ }}
+ color="primary"
+ >
+ {i18n.t('core:cancel')}
+ </Button>
+ <Button
+ data-tid="saveTID"
+ title={i18n.t('core:save')}
+ onClick={() => {
+ props
+ .saveAs(
+ extractContainingDirectoryPath(props.file.path) +
+ PlatformFacade.getDirSeparator() +
+ copyFileName.current
+ )
+ .then(() => {
+ onClose();
+ });
+ }}
+ color="primary"
+ >
+ {i18n.t('core:save')}
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button
+ data-tid="saveas"
+ title={i18n.t('core:saveAs')}
+ onClick={() => {
+ setSaveAs(true);
+ }}
+ color="primary"
+ >
+ {i18n.t('core:saveAs')}
+ </Button>
+ <Button
+ data-tid="overrideTID"
+ title={i18n.t('core:override')}
+ onClick={() => {
+ props.override().then(() => {
+ onClose();
+ });
+ }}
+ color="primary"
+ >
+ {i18n.t('core:override')}
+ </Button>
+ </>
+ )}
+ </DialogActions>
+ </Dialog>
+ );
+}
+
+export default ResolveConflictDialog;
diff --git a/app/locales/en/core.json b/app/locales/en/core.json
index 1756369aa..0a5b5b124 100644
--- a/app/locales/en/core.json
+++ b/app/locales/en/core.json
@@ -755,5 +755,9 @@
"removeExtension": "Remove Extension",
"removeExtensionTooltip": "Are you sure you want to remove '{{extensionName}}' extension?",
"resetFileType": "Reset File Types",
+ "override": "Override",
+ "saveAs": "Save As",
+ "resolveConflictTitle": "File was modified externally",
+ "resolveConflictDesc": "For saving your changes as new file click on 'Save As' button, for override the external changes click the 'Override' button.",
"-": "-"
}