TagSpaces is an offline, open source, document manager with tagging support
refactor folder watching (#1996)
Stanimirbc741dee34c5
diff --git a/app/components/DirectoryListView.tsx b/app/components/DirectoryListView.tsxindex ace99fb7f..8ae1e1313 100644--- a/app/components/DirectoryListView.tsx+++ b/app/components/DirectoryListView.tsx@@ -18,10 +18,10 @@ import { actions as AppActions, AppDispatch } from '-/reducers/app';import { ParentFolderIcon } from '-/components/CommonIcons';import { getLocations } from '-/reducers/locations';import PlatformIO from '-/services/platform-facade';-import { Pro } from '-/pro';import { useTranslation } from 'react-i18next';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { useFSWatcherContext } from '-/hooks/useFSWatcherContext';interface Props {setTargetDir: (dirPath: string) => void;@@ -30,7 +30,6 @@ interface Props {function DirectoryListView(props: Props) {const { currentDirectoryPath, setTargetDir } = props;const { t } = useTranslation();- const { watchForChanges } = useLocationIndexContext();const { currentLocation } = useCurrentLocationContext();const locations: Array<TS.Location> = useSelector(getLocations);const showUnixHiddenEntries: boolean = useSelector(getShowUnixHiddenEntries);@@ -175,16 +174,14 @@ function DirectoryListView(props: Props) {style={{ margin: 5 }}data-tid="newSubdirectoryTID"onClick={() => {- if (Pro && Pro.Watcher) {- Pro.Watcher.stopWatching();- }+ //stopWatching();dispatch(AppActions.toggleCreateDirectoryDialog({rootDirPath: chosenDirectory.current,callback: newDirPath => {listDirectory(chosenDirectory.current);setTargetDir(newDirPath);- watchForChanges();+ //watchForChanges();},reflect: false})diff --git a/app/components/EntryContainer.tsx b/app/components/EntryContainer.tsxindex 7ca463c93..c6fb22dae 100644--- a/app/components/EntryContainer.tsx+++ b/app/components/EntryContainer.tsx@@ -69,6 +69,7 @@ import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { toFsEntry } from '-/services/utils-io';+import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';//const defaultSplitSize = '7.86%'; // '7.2%'; // 103;// const bufferedSplitResize = buffer({@@ -96,6 +97,11 @@ function EntryContainer() {switchCurrentLocationType} = useCurrentLocationContext();const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();+ const {+ copyFilePromiseOverwrite,+ copyFilePromise,+ saveTextFilePromise+ } = usePlatformFacadeContext();const { showNotification } = useNotificationContext();const tabIndex = useSelector(getEntryContainerTab);const fileEditHistoryKey = useSelector(@@ -534,7 +540,7 @@ function EntryContainer() {const saveAs = (newFilePath: string): Promise<boolean> => {return switchLocationTypeByID(openedFile.locationId).then(() =>- PlatformIO.copyFilePromise(openedFile.path, newFilePath).then(() =>+ copyFilePromise(openedFile.path, newFilePath).then(() =>PlatformIO.getPropertiesPromise(newFilePath).then((entryProp: TS.FileSystemEntry) =>save({@@ -581,12 +587,12 @@ function EntryContainer() {PlatformIO.getDirSeparator());try {- await PlatformIO.copyFilePromiseOverwrite(fileOpen.path, targetPath); // todo test what happened if remove await?+ await copyFilePromiseOverwrite(fileOpen.path, targetPath); // todo test what happened if remove await?} catch (error) {console.log('copyFilePromiseOverwrite', error);}}- return PlatformIO.saveTextFilePromise(+ return saveTextFilePromise({ path: fileOpen.path, lmdt: fileOpen.lmdt },textContent,truediff --git a/app/components/Revisions.tsx b/app/components/Revisions.tsxindex dc7f8a0b5..02f35e979 100644--- a/app/components/Revisions.tsx+++ b/app/components/Revisions.tsx@@ -45,6 +45,7 @@ import { Pro } from '-/pro';import FilePreviewDialog from '-/components/dialogs/FilePreviewDialog';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';const initialRowsPerPage = 10;@@ -52,6 +53,7 @@ function Revisions() {const { t } = useTranslation();// const dispatch: AppDispatch = useDispatch();const { openedEntries, updateOpenedFile } = useOpenedEntryContext();+ const { copyFilePromiseOverwrite } = usePlatformFacadeContext();const [rows, setRows] = useState<Array<TS.FileSystemEntry>>([]);const [page, setPage] = useState<number>(0);const [rowsPerPage, setRowsPerPage] = React.useState<number>(@@ -125,18 +127,14 @@ function Revisions() {openedFile.uuid,PlatformIO.getDirSeparator());- return PlatformIO.copyFilePromiseOverwrite(- openedFile.path,- targetPath- ).then(() =>- PlatformIO.copyFilePromiseOverwrite(revisionPath, openedFile.path).then(- () =>- updateOpenedFile(openedFile.path, {- id: '',- ...openedFile,- editMode: false,- shouldReload: !openedFile.shouldReload- })+ return copyFilePromiseOverwrite(openedFile.path, targetPath).then(() =>+ copyFilePromiseOverwrite(revisionPath, openedFile.path).then(() =>+ updateOpenedFile(openedFile.path, {+ id: '',+ ...openedFile,+ editMode: false,+ shouldReload: !openedFile.shouldReload+ })));}diff --git a/app/components/SearchAutocomplete.tsx b/app/components/SearchAutocomplete.tsxindex 55070f506..4102af851 100644--- a/app/components/SearchAutocomplete.tsx+++ b/app/components/SearchAutocomplete.tsx@@ -102,7 +102,7 @@ function SearchAutocomplete(props: Props) {setSearchQuery} = useDirectoryContentContext();const {- watchForChanges,+ // watchForChanges,isIndexing,searchAllLocations,searchLocationIndex@@ -450,7 +450,7 @@ function SearchAutocomplete(props: Props) {resetValues([]);setSearchQuery({});exitSearchMode();- watchForChanges();+ // watchForChanges();openCurrentDirectory();};diff --git a/app/components/dialogs/MoveOrCopyFilesDialog.tsx b/app/components/dialogs/MoveOrCopyFilesDialog.tsxindex 92c45d124..716bbc8c6 100644--- a/app/components/dialogs/MoveOrCopyFilesDialog.tsx+++ b/app/components/dialogs/MoveOrCopyFilesDialog.tsx@@ -41,6 +41,7 @@ import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import AppConfig from '-/AppConfig';import { useTranslation } from 'react-i18next';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';interface Props {open: boolean;@@ -54,6 +55,7 @@ function MoveOrCopyFilesDialog(props: Props) {const theme = useTheme();+ const { copyFilePromise, renameFilePromise } = usePlatformFacadeContext();const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();// const dispatch: AppDispatch = useDispatch();const fullScreen = useMediaQuery(theme.breakpoints.down('md'));@@ -63,7 +65,7 @@ function MoveOrCopyFilesDialog(props: Props) {for (const file of files) {if (move) {promises.push(- PlatformIO.renameFilePromise(+ renameFilePromise(file.path,currentDirectoryPath + AppConfig.dirSeparator + file.name)@@ -74,7 +76,7 @@ function MoveOrCopyFilesDialog(props: Props) {);} else {promises.push(- PlatformIO.copyFilePromise(+ copyFilePromise(file.path,currentDirectoryPath + AppConfig.dirSeparator + file.name)diff --git a/app/components/menus/DirectoryMenu.tsx b/app/components/menus/DirectoryMenu.tsxindex 73975d38d..6053790b7 100644--- a/app/components/menus/DirectoryMenu.tsx+++ b/app/components/menus/DirectoryMenu.tsx@@ -49,6 +49,7 @@ import { useNotificationContext } from '-/hooks/useNotificationContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';+import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';interface Props {open: boolean;@@ -79,6 +80,7 @@ function DirectoryMenu(props: Props) {openCurrentDirectory} = useDirectoryContentContext();const { reflectCreateEntry } = useLocationIndexContext();+ const { copyFilePromise, renameFilePromise } = usePlatformFacadeContext();const fileUploadContainerRef = useRef<FileUploadContainerRef>(null);const {open,@@ -315,7 +317,7 @@ Do you want to continue?`)const newFilePath =normalizePath(directoryPath) + PlatformIO.getDirSeparator() + fileName;- PlatformIO.renameFilePromise(filePath, newFilePath)+ renameFilePromise(filePath, newFilePath).then(() => {showNotification('File ' + newFilePath + ' successfully imported.',@@ -368,7 +370,7 @@ Do you want to continue?`)PlatformIO.getDirSeparator());- PlatformIO.copyFilePromise(+ copyFilePromise(getThumbFileLocationForDirectory(directoryPath,PlatformIO.getDirSeparator()diff --git a/app/components/menus/FileMenu.tsx b/app/components/menus/FileMenu.tsxindex 6c82f8d57..b649b8126 100644--- a/app/components/menus/FileMenu.tsx+++ b/app/components/menus/FileMenu.tsx@@ -47,11 +47,9 @@ import PlatformIO from '-/services/platform-facade';import {generateFileName,setFolderBackgroundPromise,- setFolderThumbnailPromise,getRelativeEntryPath} from '-/services/utils-io';import { Pro } from '-/pro';-import { TS } from '-/tagspaces.namespace';import { actions as AppActions, AppDispatch } from '-/reducers/app';import { useSelector, useDispatch } from 'react-redux';import { supportedImgs } from '-/services/thumbsgenerator';@@ -64,7 +62,6 @@ import {DeleteIcon,LinkIcon} from '-/components/CommonIcons';-import { getLocations } from '-/reducers/locations';import PropertiesIcon from '@mui/icons-material/Info';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';@@ -72,6 +69,7 @@ import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';+import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';interface Props {anchorEl: Element;@@ -114,8 +112,12 @@ function FileMenu(props: Props) {const { openEntry } = useOpenedEntryContext();const { openDirectory } = useDirectoryContentContext();const { showNotification } = useNotificationContext();+ const {+ copyFilePromise,+ setFolderThumbnailPromise+ } = usePlatformFacadeContext();const { currentLocation, readOnlyMode } = useCurrentLocationContext();- const locations: Array<TS.Location> = useSelector(getLocations);+ //const locations: Array<TS.Location> = useSelector(getLocations);const prefixTagContainer = useSelector(getPrefixTagContainer);const warningOpeningFilesExternally = useSelector(getWarningOpeningFilesExternally@@ -178,7 +180,7 @@ function FileMenu(props: Props) {function setFolderThumbnail() {onClose();- setFolderThumbnailPromise(selectedFilePath, t)+ setFolderThumbnailPromise(selectedFilePath).then((directoryPath: string) => {showNotification('Thumbnail created for: ' + directoryPath);return true;@@ -258,12 +260,12 @@ function FileMenu(props: Props) {prefixTagContainer);- PlatformIO.copyFilePromise(selectedFilePath, newFilePath)+ copyFilePromise(selectedFilePath, newFilePath).then(() => {if (onDuplicateFile) {onDuplicateFile(dirPath);} else {- openDirectory(dirPath);+ return openDirectory(dirPath);}return true;})diff --git a/app/containers/Root.tsx b/app/containers/Root.tsxindex 2dafcbcc2..1c8aec399 100644--- a/app/containers/Root.tsx+++ b/app/containers/Root.tsx@@ -38,6 +38,8 @@ import {SelectedEntryContext,SelectedEntryContextProvider} from '-/hooks/SelectedEntryContextProvider';+import { FSWatcherContextProvider } from '-/hooks/FSWatcherContextProvider';+import { PlatformFacadeContextProvider } from '-/hooks/PlatformFacadeContextProvider';type RootType = {store: Store<{}>;@@ -61,17 +63,21 @@ export default function Root({ store, persistor }: RootType) {<CurrentLocationContextProvider><SelectedEntryContextProvider><DirectoryContentContextProvider>- <LocationIndexContextProvider>- <OpenedEntryContextProvider>- <FsActionsContextProvider>- <IOActionsContextProvider>- <TaggingActionsContextProvider>- <MainPage />- </TaggingActionsContextProvider>- </IOActionsContextProvider>- </FsActionsContextProvider>- </OpenedEntryContextProvider>- </LocationIndexContextProvider>+ <FSWatcherContextProvider>+ <PlatformFacadeContextProvider>+ <LocationIndexContextProvider>+ <OpenedEntryContextProvider>+ <FsActionsContextProvider>+ <IOActionsContextProvider>+ <TaggingActionsContextProvider>+ <MainPage />+ </TaggingActionsContextProvider>+ </IOActionsContextProvider>+ </FsActionsContextProvider>+ </OpenedEntryContextProvider>+ </LocationIndexContextProvider>+ </PlatformFacadeContextProvider>+ </FSWatcherContextProvider></DirectoryContentContextProvider></SelectedEntryContextProvider></CurrentLocationContextProvider>diff --git a/app/hooks/CurrentLocationContextProvider.tsx b/app/hooks/CurrentLocationContextProvider.tsxindex 0c5067f8e..2ddfb4694 100644--- a/app/hooks/CurrentLocationContextProvider.tsx+++ b/app/hooks/CurrentLocationContextProvider.tsx@@ -40,6 +40,7 @@ import { locationType } from '@tagspaces/tagspaces-common/misc';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { useNotificationContext } from '-/hooks/useNotificationContext';import { getPersistTagsInSidecarFile } from '-/reducers/settings';+import { useFSWatcherContext } from '-/hooks/useFSWatcherContext';type CurrentLocationContextData = {currentLocation: TS.Location;@@ -215,6 +216,7 @@ export const CurrentLocationContextProvider = ({// disableWebdavSupport to revoke cached objectPlatformIO.disableWebdavSupport();}+ setCurrentLocation(location);if (openAfterEdit) {/** check if location uuid is changed@@ -300,9 +302,7 @@ export const CurrentLocationContextProvider = ({location: TS.Location,skipInitDirList: boolean = false) {- if (Pro && Pro.Watcher) {- Pro.Watcher.stopWatching();- }+ // stopWatching();skipInitialDirList.current = skipInitDirList;if (location.type === locationType.TYPE_CLOUD) {PlatformIO.enableObjectStoreSupport(location)diff --git a/app/hooks/DescriptionContextProvider.tsx b/app/hooks/DescriptionContextProvider.tsxindex b7b4f989e..4195aaefd 100644--- a/app/hooks/DescriptionContextProvider.tsx+++ b/app/hooks/DescriptionContextProvider.tsx@@ -35,6 +35,7 @@ import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';type DescriptionContextData = {description: string;@@ -72,6 +73,7 @@ export const DescriptionContextProvider = ({switchCurrentLocationType,readOnlyMode} = useCurrentLocationContext();+ const { updateCurrentDirEntry } = useDirectoryContentContext();const { showNotification } = useNotificationContext();const openedFile = useRef<OpenedEntry>(openedEntries[0]);const isChanged = useRef<boolean>(false);@@ -143,6 +145,10 @@ export const DescriptionContextProvider = ({return Pro.MetaOperations.saveFsEntryMeta(openedFile.current.path, {description: openedFile.current.description}).then(entryMeta => {+ // @ts-ignore+ updateCurrentDirEntry(openedFile.current.path, {+ description: entryMeta.description+ });openedFile.current.description = undefined;isChanged.current = false;return updateOpenedFile(openedFile.current.path, entryMeta);diff --git a/app/hooks/FSWatcherContextProvider.tsx b/app/hooks/FSWatcherContextProvider.tsxnew file mode 100644index 000000000..b2692443a--- /dev/null+++ b/app/hooks/FSWatcherContextProvider.tsx@@ -0,0 +1,283 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-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, {+ createContext,+ useEffect,+ useMemo,+ useRef,+ useState+} from 'react';+import { FSWatcher } from 'chokidar';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import PlatformIO from '-/services/platform-facade';+import AppConfig from '-/AppConfig';+import {+ extractContainingDirectoryPath,+ getFileLocationFromMetaFile+} from '@tagspaces/tagspaces-common/paths';+import { locationType } from '@tagspaces/tagspaces-common/misc';+import { PerspectiveIDs } from '-/perspectives';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { actions as AppActions, AppDispatch } from '-/reducers/app';+import { toFsEntry } from '-/services/utils-io';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { useDispatch } from 'react-redux';++type FSWatcherContextData = {+ watcher: FSWatcher;+ ignored: string[];+ stopWatching: () => void;+ isWatching: () => void;+ addToIgnored: (path: string) => void;+ removeFromIgnored: (path: string) => void;+ ignoreByWatcher: (...paths: string[]) => void;+ deignoreByWatcher: (...paths: string[]) => void;+};++export const FSWatcherContext = createContext<FSWatcherContextData>({+ watcher: undefined,+ ignored: undefined,+ stopWatching: undefined,+ isWatching: undefined,+ addToIgnored: undefined,+ removeFromIgnored: undefined,+ ignoreByWatcher: undefined,+ deignoreByWatcher: undefined+});++export type FSWatcherContextProviderProps = {+ children: React.ReactNode;+};++export const FSWatcherContextProvider = ({+ children+}: FSWatcherContextProviderProps) => {+ const { currentLocation } = useCurrentLocationContext();+ const {+ loadDirectoryContent,+ currentDirectoryPerspective,+ addDirectoryEntries,+ removeDirectoryEntries+ } = useDirectoryContentContext();+ const { reflectDeleteEntry, reflectCreateEntry } = useLocationIndexContext();+ const [watcher, setWatcher] = useState<FSWatcher>(undefined);+ const ignored = useRef<string[]>([]);+ const dispatch: AppDispatch = useDispatch();++ useEffect(() => {+ if (+ currentLocation &&+ currentLocation.watchForChanges &&+ currentLocation.type !== locationType.TYPE_CLOUD+ ) {+ const depth =+ currentDirectoryPerspective === PerspectiveIDs.KANBAN ? 3 : 1;+ setWatcher(+ watchFolder(PlatformIO.getLocationPath(currentLocation), depth)+ );+ } else {+ stopWatching();+ }+ }, [currentLocation]);++ useEffect(() => {+ watchForEvents();+ }, [addDirectoryEntries, removeDirectoryEntries]);++ function watchForEvents() {+ if (watcher !== undefined) {+ // To remove the listener+ watcher.removeAllListeners();+ watcher.on('all', listener);+ } /*else {+ console.log('Indexing not supported on this platform');+ }*/+ }++ function watchFolder(locationPath, depth) {+ console.log('Start watching: ' + locationPath);+ stopWatching();+ return PlatformIO.watchFolder(locationPath, {+ ignored: (path, stats) =>+ (/(^|[\/\\])\../.test(path) && !path.includes('.ts')) || // ignoring .dotfiles but not dirs like .ts+ (path.includes('.ts') && path.includes('tsi.json')), // ignoring .ts/tsi.json folder+ // /(^|[\/\\])\../.test(path) || path.includes('.ts'), // ignoring .dotfiles // ignoring .ts folder+ // (stats && stats.isDirectory()), // ignoring directories+ ignoreInitial: true,+ depth+ });+ }++ const listener = (event, path) => {+ console.log(`File ${path} has been ${event}`);+ if (path.endsWith(AppConfig.metaFolder)) {+ // .ts dir created+ return;+ }+ const pathParts = path.split(PlatformIO.getDirSeparator());+ for (let i = 0; i < ignored.current.length; i++) {+ if (path.startsWith(ignored[i]) || pathParts.includes(ignored[i])) {+ // ignored.current.splice(i, 1);+ return;+ }+ }+ /*const index = ignored.current.indexOf(path);+ if (index > -1) {+ ignored.current.splice(index, 1);+ return;+ }*/++ switch (event) {+ case 'unlink':+ case 'unlinkDir':+ if (!path.includes(AppConfig.metaFolder)) {+ removeDirectoryEntries([path]);+ reflectDeleteEntry(path);+ dispatch(AppActions.reflectDeleteEntry(path));+ }+ break;+ case 'add':+ if (!path.includes(AppConfig.metaFolder)) {+ const entry = toFsEntry(path, true);+ addDirectoryEntries([entry]);+ reflectCreateEntry(entry);+ dispatch(AppActions.reflectCreateEntry(path, true));+ }+ break;+ case 'addDir':+ if (!path.includes(AppConfig.metaFolder)) {+ const entry = toFsEntry(path, false);+ addDirectoryEntries([entry]);+ reflectCreateEntry(entry);+ dispatch(AppActions.reflectCreateEntry(path, false));+ }+ break;+ case 'change':+ console.log(`File ${path} has been changed`);++ // watching for changed sidecar files .ts/file.jpg.json+ if (path.includes(AppConfig.metaFolder)) {+ if (path.endsWith(AppConfig.metaFileExt)) {+ const directoryPath = getFileLocationFromMetaFile(+ path,+ PlatformIO.getDirSeparator()+ );+ loadDirectoryContent(+ extractContainingDirectoryPath(+ directoryPath,+ PlatformIO.getDirSeparator()+ ),+ false,+ true+ );+ }+ if (path.endsWith(AppConfig.metaFolderFile)) {+ const directoryPath = getFileLocationFromMetaFile(+ path,+ PlatformIO.getDirSeparator()+ );+ loadDirectoryContent(+ extractContainingDirectoryPath(+ directoryPath,+ PlatformIO.getDirSeparator()+ ),+ false,+ true+ );+ }+ }+ // } else { // TODO a separate watcher for the currently opened file should be created+ // // handle file content changed+ // dispatch(appActions.reflectUpdateOpenedFileContent(path));+ // }+ break;+ default:+ console.log(event, path);+ break;+ }+ };++ function stopWatching() {+ if (watcher && watcher.close) {+ watcher.close();+ setWatcher(undefined);+ }+ }++ function isWatching() {+ return watcher !== undefined; //&& !watcher.closed;+ }++ function addToIgnored(path: string) {+ const index = ignored.current.indexOf(path);+ if (index === -1) {+ ignored.current.push(path);+ }+ }++ function removeFromIgnored(path: string) {+ setTimeout(() => {+ for (let i = 0; i < ignored.current.length; i++) {+ const pathParts = ignored[i].split(PlatformIO.getDirSeparator());+ if (path.startsWith(ignored[i]) || pathParts.includes(path)) {+ ignored.current.splice(i, 1);+ }+ }+ /* const index = ignored.current.indexOf(path);+ if (index > -1) {+ ignored.current.splice(index, 1);+ }*/+ }, 1000);+ }++ function ignoreByWatcher(...paths) {+ if (isWatching()) {+ for (let i = 0; i < paths.length; i += 1) {+ addToIgnored(paths[i]);+ }+ }+ }++ function deignoreByWatcher(...paths) {+ if (isWatching()) {+ for (let i = 0; i < paths.length; i += 1) {+ removeFromIgnored(paths[i]);+ }+ }+ }++ const context = useMemo(() => {+ return {+ watcher,+ ignored: ignored.current,+ stopWatching,+ isWatching,+ addToIgnored,+ removeFromIgnored,+ ignoreByWatcher,+ deignoreByWatcher+ };+ }, [watcher, ignored.current]);++ return (+ <FSWatcherContext.Provider value={context}>+ {children}+ </FSWatcherContext.Provider>+ );+};diff --git a/app/hooks/FsActionsContextProvider.tsx b/app/hooks/FsActionsContextProvider.tsxindex 0c965f8eb..b5c794bf4 100644--- a/app/hooks/FsActionsContextProvider.tsx+++ b/app/hooks/FsActionsContextProvider.tsx@@ -29,10 +29,10 @@ import {import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { getWarningOpeningFilesExternally } from '-/reducers/settings';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';-import { renameFilesPromise } from '-/services/utils-io';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';+import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';type FsActionsContextData = {renameDirectory: (@@ -62,13 +62,18 @@ export const FsActionsContextProvider = ({const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();const { reflectRenameEntry } = useLocationIndexContext();const { showNotification } = useNotificationContext();+ const {+ renameFilePromise,+ renameFilesPromise,+ renameDirectoryPromise+ } = usePlatformFacadeContext();const dispatch: AppDispatch = useDispatch();const warningOpeningFilesExternally = useSelector(getWarningOpeningFilesExternally);function renameDirectory(directoryPath: string, newDirectoryName: string) {- return PlatformIO.renameDirectoryPromise(directoryPath, newDirectoryName)+ return renameDirectoryPromise(directoryPath, newDirectoryName).then(newDirPath => {if (currentDirectoryPath === directoryPath) {openDirectory(newDirPath).then(() => {@@ -106,7 +111,7 @@ export const FsActionsContextProvider = ({}function renameFile(filePath: string, newFilePath: string): Promise<boolean> {- return PlatformIO.renameFilePromise(filePath, newFilePath)+ return renameFilePromise(filePath, newFilePath).then(result => {const newFilePathFromPromise = result[1];console.info('File renamed ' + filePath + ' to ' + newFilePath);diff --git a/app/hooks/IOActionsContextProvider.tsx b/app/hooks/IOActionsContextProvider.tsxindex c7a6f7088..3ff1fb1dc 100644--- a/app/hooks/IOActionsContextProvider.tsx+++ b/app/hooks/IOActionsContextProvider.tsx@@ -37,11 +37,8 @@ import PlatformIO from '-/services/platform-facade';import { actions as AppActions, AppDispatch } from '-/reducers/app';import { useDispatch, useSelector } from 'react-redux';import {- copyFilesPromise,- deleteFilesPromise,getThumbPath,loadFileMetaDataPromise,- renameFilesPromise,toFsEntry} from '-/services/utils-io';import { TS } from '-/tagspaces.namespace';@@ -57,6 +54,7 @@ import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';import { getUseTrashCan } from '-/reducers/settings';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';type extractOptions = {EXIFGeo?: boolean;@@ -136,6 +134,20 @@ export const IOActionsContextProvider = ({const { t } = useTranslation();const dispatch: AppDispatch = useDispatch();const { showNotification, hideNotifications } = useNotificationContext();+ const {+ copyFilesWithProgress,+ deleteFilesPromise+ } = usePlatformFacadeContext();+ const {+ createDirectoryPromise,+ renameFilesPromise,+ copyDirectoryPromise,+ moveDirectoryPromise,+ saveFilePromise,+ saveBinaryFilePromise,+ deleteFilePromise,+ deleteDirectoryPromise+ } = usePlatformFacadeContext();const { reflectDeleteDirectory, reflectDeleteFile } = useOpenedEntryContext();const {currentDirectoryEntries,@@ -178,7 +190,7 @@ export const IOActionsContextProvider = ({const createDirectory = useMemo(() => {return (directoryPath: string, reflect = true) =>- PlatformIO.createDirectoryPromise(directoryPath)+ createDirectoryPromise(directoryPath).then(result => {if (result !== undefined && result.dirPath !== undefined) {// eslint-disable-next-line no-param-reassign@@ -258,7 +270,7 @@ export const IOActionsContextProvider = ({const deleteDirectory = useMemo(() => {return (directoryPath: string, reflect = true) =>- PlatformIO.deleteDirectoryPromise(directoryPath, useTrashCan)+ deleteDirectoryPromise(directoryPath, useTrashCan).then(() => {if (reflect) {if (directoryPath === currentDirectoryPath) {@@ -309,7 +321,7 @@ export const IOActionsContextProvider = ({const deleteFile = useMemo(() => {return (filePath: string, uuid: string, reflect = true) =>- PlatformIO.deleteFilePromise(filePath, useTrashCan)+ deleteFilePromise(filePath, useTrashCan).then(() => {if (reflect) {// close file opener if this file is opened@@ -380,7 +392,7 @@ export const IOActionsContextProvider = ({): Promise<boolean> {const promises = dirPaths.map(({ path, count }) => {const dirName = extractDirectoryName(path, PlatformIO.getDirSeparator());- return PlatformIO.moveDirectoryPromise(+ return moveDirectoryPromise({ path: path, total: count },joinPaths(PlatformIO.getDirSeparator(), targetPath, dirName),onProgress@@ -500,7 +512,7 @@ export const IOActionsContextProvider = ({): Promise<boolean> {const promises = dirPaths.map(({ path, count }) => {const dirName = extractDirectoryName(path, PlatformIO.getDirSeparator());- return PlatformIO.copyDirectoryPromise(+ return copyDirectoryPromise({ path: path, total: count },joinPaths(PlatformIO.getDirSeparator(), targetPath, dirName),onProgress@@ -522,7 +534,7 @@ export const IOActionsContextProvider = ({targetPath: string,onProgress): Promise<boolean> {- return copyFilesPromise(paths, targetPath, onProgress)+ return copyFilesWithProgress(paths, targetPath, onProgress).then(() => {// todo return only copied pathsshowNotification(t('core:filesCopiedSuccessful'));@@ -531,7 +543,7 @@ export const IOActionsContextProvider = ({getThumbFileLocationForFile(path, PlatformIO.getDirSeparator(), false)]);- return copyFilesPromise(+ return copyFilesWithProgress(metaPaths,getMetaDirectoryPath(targetPath),onProgress@@ -565,7 +577,7 @@ export const IOActionsContextProvider = ({): Promise<TS.FileSystemEntry> {function saveFile(response: Response): Promise<TS.FileSystemEntry> {if (AppConfig.isElectron && !PlatformIO.haveObjectStoreSupport()) {- return PlatformIO.saveBinaryFilePromise(+ return saveBinaryFilePromise({ path: targetPath },response.body,true,@@ -573,11 +585,7 @@ export const IOActionsContextProvider = ({);}return response.arrayBuffer().then(arrayBuffer => {- return PlatformIO.saveFilePromise(- { path: targetPath },- arrayBuffer,- true- );+ return saveFilePromise({ path: targetPath }, arrayBuffer, true);});}return fetch(url)@@ -590,7 +598,7 @@ export const IOActionsContextProvider = ({if (dataURL && dataURL.length > 6) {const baseString = dataURL.split(',').pop();const fileContent = base64ToArrayBuffer(baseString);- return PlatformIO.saveBinaryFilePromise(+ return saveBinaryFilePromise({path: getThumbFileLocationForFile(targetPath,@@ -689,7 +697,7 @@ export const IOActionsContextProvider = ({? event.currentTarget.result: event.target.result;try {- const fsEntry: TS.FileSystemEntry = await PlatformIO.saveBinaryFilePromise(+ const fsEntry: TS.FileSystemEntry = await saveBinaryFilePromise({ path: fileTargetPath },new Uint8Array(result),true,@@ -785,7 +793,7 @@ export const IOActionsContextProvider = ({dispatch(AppActions.setProgress(filePath, -1, undefined));} else {// dispatch(AppActions.setProgress(filePath, progress));- return PlatformIO.saveBinaryFilePromise(+ return saveBinaryFilePromise({ path: filePath },fileContent,true,diff --git a/app/hooks/LocationIndexContextProvider.tsx b/app/hooks/LocationIndexContextProvider.tsxindex 7c295a37f..687da68a9 100644--- a/app/hooks/LocationIndexContextProvider.tsx+++ b/app/hooks/LocationIndexContextProvider.tsx@@ -59,7 +59,6 @@ type LocationIndexContextData = {reflectRenameEntry: (path: string, newPath: string) => void;indexUpdateSidecarTags: (path: string, tags: Array<TS.Tag>) => void;reflectUpdateSidecarMeta: (path: string, entryMeta: Object) => void;- watchForChanges: () => void;};export const LocationIndexContext = createContext<LocationIndexContextData>({@@ -79,8 +78,7 @@ export const LocationIndexContext = createContext<LocationIndexContextData>({reflectCreateEntry: () => {},reflectRenameEntry: () => {},indexUpdateSidecarTags: () => {},- reflectUpdateSidecarMeta: () => {},- watchForChanges: () => {}+ reflectUpdateSidecarMeta: () => {}});export type LocationIndexContextProviderProps = {@@ -98,7 +96,9 @@ export const LocationIndexContextProvider = ({setSearchResults,appendSearchResults,loadDirectoryContent,- currentDirectoryPerspective+ currentDirectoryPerspective,+ addDirectoryEntries,+ removeDirectoryEntries} = useDirectoryContentContext();const { showNotification, hideNotifications } = useNotificationContext();@@ -112,13 +112,6 @@ export const LocationIndexContextProvider = ({useEffect(() => {clearDirectoryIndex();- if (currentLocation) {- watchForChanges();- } else {- if (Pro && Pro.Watcher) {- Pro.Watcher.stopWatching();- }- }}, [currentLocation]);function setIndex(i) {@@ -134,32 +127,16 @@ export const LocationIndexContextProvider = ({return index.current;}- function watchForChanges() {- if (- Pro &&- Pro.Watcher &&- currentLocation &&- currentLocation.watchForChanges &&- currentLocation.type !== locationType.TYPE_CLOUD- ) {- function deleteEntry(path: string) {- reflectDeleteEntry(path);- dispatch(AppActions.reflectDeleteEntry(path));- }- function createEntry(path: string, isFile: boolean) {- reflectCreateEntry(toFsEntry(path, isFile));- dispatch(AppActions.reflectCreateEntry(path, isFile));- }- const depth =- currentDirectoryPerspective === PerspectiveIDs.KANBAN ? 3 : 1;- Pro.Watcher.watchFolder(- PlatformIO.getLocationPath(currentLocation),- deleteEntry,- createEntry,- loadDirectoryContent,- depth- );- }+ function deleteEntry(path: string) {+ removeDirectoryEntries([path]);+ reflectDeleteEntry(path);+ dispatch(AppActions.reflectDeleteEntry(path));+ }+ function createEntry(path: string, isFile: boolean) {+ const entry = toFsEntry(path, isFile);+ addDirectoryEntries([entry]);+ reflectCreateEntry(entry);+ dispatch(AppActions.reflectCreateEntry(path, isFile));}function reflectDeleteEntry(path: string) {@@ -640,7 +617,6 @@ export const LocationIndexContextProvider = ({index: index.current,indexLoadedOn: indexLoadedOn.current,isIndexing: isIndexing.current,- watchForChanges,cancelDirectoryIndexing,createLocationIndex,createLocationsIndexes,@@ -656,7 +632,13 @@ export const LocationIndexContextProvider = ({indexUpdateSidecarTags,reflectUpdateSidecarMeta};- }, [currentLocation, index, isIndexing.current]);+ }, [+ currentLocation,+ index,+ isIndexing.current,+ addDirectoryEntries,+ removeDirectoryEntries+ ]);return (<LocationIndexContext.Provider value={context}>diff --git a/app/hooks/OpenedEntryContextProvider.tsx b/app/hooks/OpenedEntryContextProvider.tsxindex 8c3957399..dfefc0fe3 100644--- a/app/hooks/OpenedEntryContextProvider.tsx+++ b/app/hooks/OpenedEntryContextProvider.tsx@@ -73,6 +73,7 @@ import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';+import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';type OpenedEntryContextData = {openedEntries: OpenedEntry[];@@ -151,6 +152,8 @@ export const OpenedEntryContextProvider = ({const { showNotification } = useNotificationContext();const { openLocation, currentLocation } = useCurrentLocationContext();const { reflectCreateEntry } = useLocationIndexContext();+ const { saveFilePromise } = usePlatformFacadeContext();+const supportedFileTypes = useSelector(getSupportedFileTypes);const locations: TS.Location[] = useSelector(getLocations);const historyKeys = Pro && Pro.history ? Pro.history.historyKeys : {};@@ -872,7 +875,7 @@ export const OpenedEntryContextProvider = ({formatDateTime4Tag(new Date(), true) +AppConfig.endTagContainer +'.txt';- PlatformIO.saveFilePromise({ path: filePath }, '', true)+ saveFilePromise({ path: filePath }, '', true).then(() => {reflectCreateEntry(toFsEntry(filePath, true));dispatch(AppActions.reflectCreateEntry(filePath, true));@@ -922,7 +925,7 @@ export const OpenedEntryContextProvider = ({} else if (fileType === 'md') {fileContent = content + ' \n\n' + creationMeta + '\n';}- PlatformIO.saveFilePromise({ path: filePath }, fileContent, false)+ saveFilePromise({ path: filePath }, fileContent, false).then((fsEntry: TS.FileSystemEntry) => {addDirectoryEntries([fsEntry]);reflectCreateEntry(fsEntry); // toFsEntry(filePath, true);diff --git a/app/hooks/PlatformFacadeContextProvider.tsx b/app/hooks/PlatformFacadeContextProvider.tsxnew file mode 100644index 000000000..7f57206e0--- /dev/null+++ b/app/hooks/PlatformFacadeContextProvider.tsx@@ -0,0 +1,488 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-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, { createContext, useMemo } from 'react';+import PlatformFacade from '-/services/platform-facade';+import { TS } from '-/tagspaces.namespace';+import { useFSWatcherContext } from '-/hooks/useFSWatcherContext';+import {+ extractContainingDirectoryPath,+ extractDirectoryName,+ extractFileName,+ getThumbFileLocationForDirectory,+ getThumbFileLocationForFile,+ normalizePath+} from '@tagspaces/tagspaces-common/paths';+import PlatformIO from '-/services/platform-facade';+import { useTranslation } from 'react-i18next';++type PlatformFacadeContextData = {+ createDirectoryPromise: (path: string) => Promise<any>;+ copyFilePromise: (+ sourceFilePath: string,+ targetFilePath: string,+ confirmMessage?: string+ ) => Promise<any>;+ copyFilesWithProgress: (+ paths: Array<string>,+ targetPath: string,+ onProgress?+ ) => Promise<any>;+ copyFilePromiseOverwrite: (+ sourceFilePath: string,+ targetFilePath: string+ ) => Promise<any>;+ renameFilePromise: (+ filePath: string,+ newFilePath: string,+ onProgress?+ ) => Promise<any>;+ renameFilesPromise: (+ renameJobs: Array<Array<string>>,+ onProgress?+ ) => Promise<any>;+ renameDirectoryPromise: (dirPath: string, newDirName: string) => Promise<any>;+ copyDirectoryPromise: (+ param: any,+ newDirPath: string,+ onProgress?+ ) => Promise<any>;+ moveDirectoryPromise: (+ param: any,+ newDirPath: string,+ onProgress?+ ) => Promise<any>;+ saveFilePromise: (+ param: any,+ content: any,+ overwrite: boolean+ ) => Promise<any>;+ saveTextFilePromise: (+ param: any,+ content: string,+ overwrite: boolean+ ) => Promise<any>;+ saveBinaryFilePromise: (+ param: any,+ content: any,+ overwrite: boolean,+ onUploadProgress?: (+ progress: any, // ManagedUpload.Progress,+ response: any // AWS.Response<AWS.S3.PutObjectOutput, AWS.AWSError>+ ) => void+ ) => Promise<TS.FileSystemEntry>;+ deleteFilePromise: (path: string, useTrash?: boolean) => Promise<any>;+ deleteFilesPromise: (filePathList: Array<string>) => Promise<any>;+ deleteDirectoryPromise: (path: string, useTrash?: boolean) => Promise<any>;+ setFolderThumbnailPromise: (filePath: string) => Promise<string>;+};++export const PlatformFacadeContext = createContext<PlatformFacadeContextData>({+ createDirectoryPromise: undefined,+ copyFilePromise: undefined,+ copyFilesWithProgress: undefined,+ copyFilePromiseOverwrite: undefined,+ renameFilePromise: undefined,+ renameFilesPromise: undefined,+ renameDirectoryPromise: undefined,+ copyDirectoryPromise: undefined,+ moveDirectoryPromise: undefined,+ saveFilePromise: undefined,+ saveTextFilePromise: undefined,+ saveBinaryFilePromise: undefined,+ deleteFilePromise: undefined,+ deleteFilesPromise: undefined,+ deleteDirectoryPromise: undefined,+ setFolderThumbnailPromise: undefined+});++export type PlatformFacadeContextProviderProps = {+ children: React.ReactNode;+};++export const PlatformFacadeContextProvider = ({+ children+}: PlatformFacadeContextProviderProps) => {+ const { ignoreByWatcher, deignoreByWatcher, ignored } = useFSWatcherContext();++ const { t } = useTranslation();++ /*function enableObjectStoreSupport(objectStoreConfig: any): Promise<any> {+ return platformEnableObjectStoreSupport(objectStoreConfig);+ }+ function disableObjectStoreSupport() {+ platformDisableObjectStoreSupport();+ }+ function enableWebdavSupport(webDavConfig: any) {+ platformEnableWebdavSupport(webDavConfig);+ }+ function disableWebdavSupport() {+ platformDisableWebdavSupport();+ }+ function haveObjectStoreSupport(): boolean {+ return platformHaveObjectStoreSupport();+ }+ function haveWebDavSupport(): boolean {+ return platformHaveWebDavSupport();+ }+ function isMinio(): boolean {+ return platformIsMinio();+ }+ function getDirSeparator(): string {+ return platformGetDirSeparator();+ }+ function getLocationPath(location: TS.Location): string {+ return platformGetLocationPath(location);+ }*/++ function createDirectoryPromise(path: string): Promise<any> {+ ignoreByWatcher(path);++ return PlatformFacade.createDirectoryPromise(path).then(result => {+ deignoreByWatcher(path);+ return result;+ });+ }++ /**+ * @param filePath+ * return Promise<directoryPath> of directory in order to open Folder properties next+ */+ function setFolderThumbnailPromise(filePath: string): Promise<string> {+ const directoryPath = extractContainingDirectoryPath(+ filePath,+ PlatformIO.getDirSeparator()+ );+ const directoryName = extractDirectoryName(+ directoryPath,+ PlatformIO.getDirSeparator()+ );+ return copyFilePromise(+ getThumbFileLocationForFile(+ filePath,+ PlatformIO.getDirSeparator(),+ false+ ),+ getThumbFileLocationForDirectory(+ directoryPath,+ PlatformIO.getDirSeparator()+ ),+ t('core:thumbAlreadyExists', { directoryName })+ ).then(() => directoryPath);+ }++ function copyFilePromise(+ sourceFilePath: string,+ targetFilePath: string,+ confirmMessage: string = 'File ' ++ targetFilePath ++ ' exist do you want to override it?'+ ): Promise<any> {+ return PlatformFacade.getPropertiesPromise(targetFilePath).then(+ isTargetExist => {+ if (isTargetExist) {+ // eslint-disable-next-line no-alert+ const confirmOverwrite = window && window.confirm(confirmMessage);+ if (confirmOverwrite === true) {+ return copyFilePromiseOverwrite(sourceFilePath, targetFilePath);+ }+ // eslint-disable-next-line prefer-promise-reject-errors+ return Promise.reject(+ 'File "' + targetFilePath + '" exists. Copying failed.'+ );+ }+ return copyFilePromiseOverwrite(sourceFilePath, targetFilePath);+ }+ );+ }++ function copyFilesWithProgress(+ 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: 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);+ }++ 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 => {+ completed++;+ if (progress) {+ progress(completed, path);+ }+ console.warn('Promise ' + path + ' error:', err);+ })+ );++ // 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;+ }+ });+ }++ function copyFilePromiseOverwrite(+ sourceFilePath: string,+ targetFilePath: string+ ): Promise<any> {+ ignoreByWatcher(targetFilePath);+ return PlatformFacade.copyFilePromiseOverwrite(+ sourceFilePath,+ targetFilePath+ ).then(result => {+ deignoreByWatcher(targetFilePath);+ return result;+ });+ }++ function renameFilePromise(+ filePath: string,+ newFilePath: string,+ onProgress = undefined+ ): Promise<any> {+ ignoreByWatcher(filePath, newFilePath);+ return PlatformFacade.renameFilePromise(+ filePath,+ newFilePath,+ onProgress+ ).then(result => {+ deignoreByWatcher(filePath, newFilePath);+ return result;+ });+ }++ function renameFilesPromise(+ renameJobs: Array<Array<string>>,+ onProgress = undefined+ ): Promise<any> {+ return Promise.all(+ renameJobs.map(async renameJob => {+ try {+ return await PlatformIO.renameFilePromise(+ renameJob[0],+ renameJob[1],+ onProgress+ );+ } catch (err) {+ console.warn('Error rename file:', err);+ return false;+ }+ })+ );+ }++ function renameDirectoryPromise(+ dirPath: string,+ newDirName: string+ ): Promise<any> {+ ignoreByWatcher(dirPath, newDirName);+ return PlatformFacade.renameDirectoryPromise(dirPath, newDirName).then(+ result => {+ deignoreByWatcher(dirPath, newDirName);+ return result;+ }+ );+ }++ function copyDirectoryPromise(+ param: any,+ newDirPath: string,+ onProgress = undefined+ ): Promise<any> {+ ignoreByWatcher(param.path, newDirPath);+ return PlatformFacade.copyDirectoryPromise(+ param,+ newDirPath,+ onProgress+ ).then(result => {+ deignoreByWatcher(param.path, newDirPath);+ return result;+ });+ }++ function moveDirectoryPromise(+ param: any,+ newDirPath: string,+ onProgress = undefined+ ): Promise<any> {+ ignoreByWatcher(param.path, newDirPath);+ return PlatformFacade.moveDirectoryPromise(+ param,+ newDirPath,+ onProgress+ ).then(result => {+ deignoreByWatcher(param.path, newDirPath);+ return result;+ });+ }+ function saveFilePromise(+ param: any,+ content: any,+ overwrite: boolean+ ): Promise<any> {+ ignoreByWatcher(param.path);+ return PlatformFacade.saveFilePromise(param, content, overwrite).then(+ result => {+ deignoreByWatcher(param.path);+ return result;+ }+ );+ }++ function saveTextFilePromise(+ param: any,+ content: string,+ overwrite: boolean+ ): Promise<any> {+ ignoreByWatcher(param.path);+ return PlatformFacade.saveTextFilePromise(param, content, overwrite).then(+ result => {+ deignoreByWatcher(param.path);+ return result;+ }+ );+ }++ function saveBinaryFilePromise(+ param: any,+ content: any,+ overwrite: boolean,+ onUploadProgress?: (+ progress: any, // ManagedUpload.Progress,+ response: any // AWS.Response<AWS.S3.PutObjectOutput, AWS.AWSError>+ ) => void+ ): Promise<TS.FileSystemEntry> {+ ignoreByWatcher(param.path);+ return PlatformFacade.saveBinaryFilePromise(+ param,+ content,+ overwrite,+ onUploadProgress+ ).then(result => {+ deignoreByWatcher(param.path);+ return result;+ });+ }++ function deleteFilePromise(path: string, useTrash?: boolean): Promise<any> {+ ignoreByWatcher(path);++ return PlatformFacade.deleteFilePromise(path, useTrash).then(result => {+ deignoreByWatcher(path);+ return result;+ });+ }++ function deleteFilesPromise(filePathList: Array<string>) {+ const fileDeletionPromises = [];+ filePathList.forEach(filePath => {+ fileDeletionPromises.push(deleteFilePromise(filePath));+ });+ return Promise.all(fileDeletionPromises);+ }++ function deleteDirectoryPromise(+ path: string,+ useTrash?: boolean+ ): Promise<any> {+ ignoreByWatcher(path);++ return PlatformFacade.deleteDirectoryPromise(path, useTrash).then(+ result => {+ deignoreByWatcher(path);+ return result;+ }+ );+ }++ const context = useMemo(() => {+ return {+ createDirectoryPromise,+ copyFilePromise,+ copyFilesWithProgress,+ copyFilePromiseOverwrite,+ renameFilePromise,+ renameFilesPromise,+ renameDirectoryPromise,+ copyDirectoryPromise,+ moveDirectoryPromise,+ saveFilePromise,+ saveTextFilePromise,+ saveBinaryFilePromise,+ deleteFilePromise,+ deleteFilesPromise,+ deleteDirectoryPromise,+ setFolderThumbnailPromise+ };+ }, [ignored]);++ return (+ <PlatformFacadeContext.Provider value={context}>+ {children}+ </PlatformFacadeContext.Provider>+ );+};diff --git a/app/hooks/useFSWatcherContext.tsx b/app/hooks/useFSWatcherContext.tsxnew file mode 100644index 000000000..4115bf62e--- /dev/null+++ b/app/hooks/useFSWatcherContext.tsx@@ -0,0 +1,23 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-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 { useContext } from 'react';++import { FSWatcherContext } from '-/hooks/FSWatcherContextProvider';++export const useFSWatcherContext = () => useContext(FSWatcherContext);diff --git a/app/hooks/usePlatformFacadeContext.tsx b/app/hooks/usePlatformFacadeContext.tsxnew file mode 100644index 000000000..7a5224380--- /dev/null+++ b/app/hooks/usePlatformFacadeContext.tsx@@ -0,0 +1,23 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-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 { useContext } from 'react';++import { PlatformFacadeContext } from '-/hooks/PlatformFacadeContextProvider';++export const usePlatformFacadeContext = () => useContext(PlatformFacadeContext);diff --git a/app/reducers/app.ts b/app/reducers/app.tsindex 7a97c24ba..1f7a26511 100644--- a/app/reducers/app.ts+++ b/app/reducers/app.ts@@ -17,24 +17,9 @@*/import AppConfig from '-/AppConfig';-import {- extractFileExtension,- extractFileName,- getMetaFileLocationForFile,- getThumbFileLocationForFile,- extractParentDirectoryPath,- extractTagsAsObjects,- extractContainingDirectoryPath,- getBackupFileLocation-} from '@tagspaces/tagspaces-common/paths';-import { getURLParameter, clearAllURLParams } from '-/utils/dom';+import { getURLParameter } from '-/utils/dom';import PlatformIO from '../services/platform-facade';-import {- deleteFilesPromise,- renameFilesPromise,- mergeByProp,- toFsEntry-} from '-/services/utils-io';+import { mergeByProp, toFsEntry } from '-/services/utils-io';import i18n from '../services/i18n';import { actions as tagLibraryActions } from './taglibrary';import {diff --git a/app/services/platform-facade.ts b/app/services/platform-facade.tsindex 130cf5ebf..ebc44d3c2 100644--- a/app/services/platform-facade.ts+++ b/app/services/platform-facade.ts@@ -80,7 +80,6 @@ import {} from '@tagspaces/tagspaces-platforms/platform-io';import { cleanTrailingDirSeparator } from '@tagspaces/tagspaces-common/paths';import AppConfig from '-/AppConfig';-import { Pro } from '../pro';import { TS } from '-/tagspaces.namespace';import settings from '-/settings';@@ -256,59 +255,9 @@ export default class PlatformFacade {static checkFileExist = (file: string): Promise<boolean> =>platformCheckFileExist(file);- static ignoreByWatcher = (...paths) => {- if (Pro && Pro.Watcher && Pro.Watcher.isWatching()) {- for (let i = 0; i < paths.length; i += 1) {- Pro.Watcher.addToIgnored(paths[i]);- }- }- };-- static deignoreByWatcher = (...paths) => {- if (Pro && Pro.Watcher && Pro.Watcher.isWatching()) {- for (let i = 0; i < paths.length; i += 1) {- Pro.Watcher.removeFromIgnored(paths[i]);- }- }- };-static createDirectoryPromise = (dirPath: string): Promise<any> => {- PlatformFacade.ignoreByWatcher(dirPath);-- return platformCreateDirectoryPromise(dirPath).then(result => {- PlatformFacade.deignoreByWatcher(dirPath);- return result;- });- };-- static copyFilePromise = async (- sourceFilePath: string,- targetFilePath: string,- confirmMessage: string = 'File ' +- targetFilePath +- ' exist do you want to override it?'- ): Promise<any> => {- const isTargetExist = await PlatformFacade.getPropertiesPromise(- targetFilePath- ); // TODO rethink to create PlatformIO.isExistSync function- if (isTargetExist) {- // eslint-disable-next-line no-alert- const confirmOverwrite = window && window.confirm(confirmMessage);- if (confirmOverwrite === true) {- return PlatformFacade.copyFilePromiseOverwrite(- sourceFilePath,- targetFilePath- );- }- // eslint-disable-next-line prefer-promise-reject-errors- return Promise.reject(- 'File "' + targetFilePath + '" exists. Copying failed.'- );- }- return PlatformFacade.copyFilePromiseOverwrite(- sourceFilePath,- targetFilePath- );+ //PlatformFacade.ignoreByWatcher(dirPath);+ return platformCreateDirectoryPromise(dirPath);};/**@@ -319,14 +268,8 @@ export default class PlatformFacade {sourceFilePath: string,targetFilePath: string): Promise<any> => {- PlatformFacade.ignoreByWatcher(targetFilePath);-- return platformCopyFilePromise(sourceFilePath, targetFilePath).then(- result => {- PlatformFacade.deignoreByWatcher(targetFilePath);- return result;- }- );+ //PlatformFacade.ignoreByWatcher(targetFilePath);+ return platformCopyFilePromise(sourceFilePath, targetFilePath);};static renameFilePromise = (@@ -334,26 +277,16 @@ export default class PlatformFacade {newFilePath: string,onProgress = undefined): Promise<any> => {- PlatformFacade.ignoreByWatcher(filePath, newFilePath);-- return platformRenameFilePromise(filePath, newFilePath, onProgress).then(- result => {- PlatformFacade.deignoreByWatcher(filePath, newFilePath);- return result;- }- );+ //PlatformFacade.ignoreByWatcher(filePath, newFilePath);+ return platformRenameFilePromise(filePath, newFilePath, onProgress);};static renameDirectoryPromise = (dirPath: string,newDirName: string): Promise<any> => {- PlatformFacade.ignoreByWatcher(dirPath, newDirName);-- return platformRenameDirectoryPromise(dirPath, newDirName).then(result => {- PlatformFacade.deignoreByWatcher(dirPath, newDirName);- return result;- });+ // PlatformFacade.ignoreByWatcher(dirPath, newDirName);+ return platformRenameDirectoryPromise(dirPath, newDirName);};static copyDirectoryPromise = (@@ -361,14 +294,8 @@ export default class PlatformFacade {newDirPath: string,onProgress = undefined): Promise<any> => {- PlatformFacade.ignoreByWatcher(param.path, newDirPath);-- return platformCopyDirectoryPromise(param, newDirPath, onProgress).then(- result => {- PlatformFacade.deignoreByWatcher(param.path, newDirPath);- return result;- }- );+ //PlatformFacade.ignoreByWatcher(param.path, newDirPath);+ return platformCopyDirectoryPromise(param, newDirPath, onProgress);};static moveDirectoryPromise = (@@ -376,14 +303,8 @@ export default class PlatformFacade {newDirPath: string,onProgress = undefined): Promise<any> => {- PlatformFacade.ignoreByWatcher(param.path, newDirPath);-- return platformMoveDirectoryPromise(param, newDirPath, onProgress).then(- result => {- PlatformFacade.deignoreByWatcher(param.path, newDirPath);- return result;- }- );+ //PlatformFacade.ignoreByWatcher(param.path, newDirPath);+ return platformMoveDirectoryPromise(param, newDirPath, onProgress);};static loadTextFilePromise = (@@ -412,50 +333,17 @@ export default class PlatformFacade {content: any,overwrite: boolean): Promise<any> => {- PlatformFacade.ignoreByWatcher(param.path);-- return platformSaveFilePromise(param, content, overwrite).then(result => {- PlatformFacade.deignoreByWatcher(param.path);- return result;- });+ //PlatformFacade.ignoreByWatcher(param.path);+ return platformSaveFilePromise(param, content, overwrite);};- /**- * @deprecated use saveTextFilePromise instead- * @param param- * @param content- * @param overwrite- */- /*static saveTextFilePlatform = (- param: any,- content: string,- overwrite: boolean- ): Promise<any> => {- PlatformFacade.ignoreByWatcher(param.path);-- return PlatformFacade.saveTextFilePromise(- param,- content,- overwrite- ).then(result => {- PlatformFacade.deignoreByWatcher(param.path);- return result;- });- };*/-static saveTextFilePromise = (param: any,content: string,overwrite: boolean): Promise<any> => {- PlatformFacade.ignoreByWatcher(param.path);-- return platformSaveTextFilePromise(param, content, overwrite).then(- result => {- PlatformFacade.deignoreByWatcher(param.path);- return result;- }- );+ //PlatformFacade.ignoreByWatcher(param.path);+ return platformSaveTextFilePromise(param, content, overwrite);};static saveBinaryFilePromise = (@@ -467,41 +355,30 @@ export default class PlatformFacade {response: any // AWS.Response<AWS.S3.PutObjectOutput, AWS.AWSError>) => void): Promise<TS.FileSystemEntry> => {- PlatformFacade.ignoreByWatcher(param.path);+ //PlatformFacade.ignoreByWatcher(param.path);return platformSaveBinaryFilePromise(param,content,overwrite,onUploadProgress- ).then(succeeded => {- PlatformFacade.deignoreByWatcher(param.path);- return succeeded;- });+ );};static deleteFilePromise = (path: string,useTrash?: boolean): Promise<any> => {- PlatformFacade.ignoreByWatcher(path);-- return platformDeleteFilePromise(path, useTrash).then(result => {- PlatformFacade.deignoreByWatcher(path);- return result;- });+ //PlatformFacade.ignoreByWatcher(path);+ return platformDeleteFilePromise(path, useTrash);};static deleteDirectoryPromise = (path: string,useTrash?: boolean): Promise<any> => {- PlatformFacade.ignoreByWatcher(path);-- return platformDeleteDirectoryPromise(path, useTrash).then(result => {- PlatformFacade.deignoreByWatcher(path);- return result;- });+ //PlatformFacade.ignoreByWatcher(path);+ return platformDeleteDirectoryPromise(path, useTrash);};static openDirectory = (dirPath: string): void =>diff --git a/app/services/utils-io.ts b/app/services/utils-io.tsindex b3715004d..fbbc0696a 100644--- a/app/services/utils-io.ts+++ b/app/services/utils-io.ts@@ -582,34 +582,6 @@ export function saveAsTextFile(blob: any, filename: string) {saveAs(blob, filename);}-export function deleteFilesPromise(filePathList: Array<string>) {- const fileDeletionPromises = [];- filePathList.forEach(filePath => {- fileDeletionPromises.push(PlatformIO.deleteFilePromise(filePath));- });- return Promise.all(fileDeletionPromises);-}--export function renameFilesPromise(- renameJobs: Array<Array<string>>,- onProgress = undefined-) {- return Promise.all(- renameJobs.map(async renameJob => {- try {- return await PlatformIO.renameFilePromise(- renameJob[0],- renameJob[1],- onProgress- );- } catch (err) {- console.warn('Error rename file:', err);- return false;- }- })- );-}-/*function getCommonFolder(paths: Array<string>) {const rootFolders = paths.map(p =>extractContainingDirectoryPath(p, PlatformIO.getDirSeparator())@@ -621,45 +593,6 @@ export function renameFilesPromise(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 => {- completed++;- if (progress) {- progress(completed, path);- }- console.warn('Promise ' + path + ' error:', err);- })- );-- // 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> {@@ -735,41 +668,6 @@ export function checkDirsExistPromise(});}-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) {const folderContent = await PlatformIO.listDirectoryPromise(path, []); // 'extractThumbPath']);const subfolders = [];@@ -1215,33 +1113,6 @@ export async function saveMetaDataPromise(return Promise.reject(new Error('file not found' + path));}-/**- * @param filePath- * return Promise<directoryPath> of directory in order to open Folder properties next- * @param t translation- */-export function setFolderThumbnailPromise(- filePath: string,- t-): Promise<string> {- const directoryPath = extractContainingDirectoryPath(- filePath,- PlatformIO.getDirSeparator()- );- const directoryName = extractDirectoryName(- directoryPath,- PlatformIO.getDirSeparator()- );- return PlatformIO.copyFilePromise(- getThumbFileLocationForFile(filePath, PlatformIO.getDirSeparator(), false),- getThumbFileLocationForDirectory(- directoryPath,- PlatformIO.getDirSeparator()- ),- t('core:thumbAlreadyExists', { directoryName })- ).then(() => directoryPath);-}-/*** @param filePath* @param directoryPathdiff --git a/tests/e2e/fileopener.pw.e2e.js b/tests/e2e/fileopener.pw.e2e.jsindex 0c7b863df..2455a992b 100644--- a/tests/e2e/fileopener.pw.e2e.js+++ b/tests/e2e/fileopener.pw.e2e.js@@ -256,7 +256,7 @@ test.describe('TST08 - File folder properties', () => {* Description is Pro feature (if no Pro editDescription button is disabled)*/test('TST3001 - Description for files [web,minio,electron,_pro]', async () => {- const desc = 'testDecr';+ const desc = 'testDescription';const fileSelector = getGridFileSelector('sample.pdf');// open filePropertiesawait clickOn(fileSelector);@@ -269,7 +269,9 @@ test.describe('TST08 - File folder properties', () => {const editor = await global.client.waitForSelector('[data-tid=descriptionTID] [contenteditable=true]');- await editor.type(desc);+ await editor.type(desc, {+ delay: 0+ });await clickOn('[data-tid=editDescriptionTID]');await expectElementExist(