Skip to content

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

fix watcher

sytolk68c0c5920907
diff --git a/package.json b/package.json
index 20624f067..590315a1e 100644
--- a/package.json
+++ b/package.json
@@ -47,7 +47,7 @@
"browserslist:update": "npx browserslist@latest --update-db",
"bs": "npm run build && npm run run-electron",
"run-electron": "npx electron ./release/app/dist/main/main.js",
- "prebuild": "rimraf release/app/dist && npm run prepare-node && npm run generate-extensions && node -r ts-node/register ./.erb/scripts/link-modules.ts",
+ "prebuild": "rimraf release/app/dist && npm run prepare-node && npm run generate-extensions",
"bump-version": "cd release/app && yarn version && cd .. && npm run version-meta",
"clean": "npx rimraf node_modules && npx rimraf src/renderer/dist",
"clean-maps": "rimraf app/dist/**/*.map && rimraf web/dist/**/*.map",
diff --git a/src/main/chokidarWatcher.ts b/src/main/chokidarWatcher.ts
new file mode 100644
index 000000000..6f70c16d0
--- /dev/null
+++ b/src/main/chokidarWatcher.ts
@@ -0,0 +1,124 @@
+import { BrowserWindow } from 'electron';
+import Chokidar = require('chokidar');
+
+let watcher;
+
+const sendMessage = (
+ mainWindow: BrowserWindow,
+ nameMessage: string,
+ message: Changed,
+) => {
+ try {
+ mainWindow.webContents.send(nameMessage, message);
+ } catch (ex) {
+ console.error(ex);
+ stopWatching();
+ }
+};
+
+export function stopWatching() {
+ if (watcher && watcher.close) {
+ watcher.close();
+ }
+ watcher = undefined;
+}
+export function watchFolder(
+ mainWindow: BrowserWindow,
+ event: Electron.IpcMainEvent,
+ path: string,
+ depth,
+) {
+ console.log('Start watching: ' + path);
+ stopWatching();
+ watcher = Chokidar.watch(path, {
+ 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,
+ });
+
+ watcher.on('all', (event, path) =>
+ sendMessage(mainWindow, 'folderChanged', {
+ path,
+ eventName: event,
+ }),
+ );
+ /*watcher
+ .on('add', (path) =>
+ sendMessage(mainWindow, 'folderChanged', {
+ path,
+ eventName: 'add',
+ }),
+ )
+ .on('change', (path) =>
+ sendMessage(mainWindow, 'folderChanged', {
+ path,
+ eventName: 'change',
+ }),
+ )
+ .on('unlink', (path) =>
+ sendMessage(mainWindow, 'folderChanged', {
+ path,
+ eventName: 'unlink',
+ }),
+ )
+ .on('addDir', (path) =>
+ sendMessage(mainWindow, 'folderChanged', {
+ path,
+ eventName: 'addDir',
+ }),
+ )
+ .on('unlinkDir', (path) =>
+ sendMessage(mainWindow, 'folderChanged', {
+ path,
+ eventName: 'unlinkDir',
+ }),
+ );*/
+}
+
+/*export function watchFile(
+ mainWindow: BrowserWindow,
+ event: Electron.IpcMainEvent,
+ message: Message
+) {
+ const { filePath, nameWatcher } = message;
+ const watcher = Chokidar.watch(filePath, { ignoreInitial: true });
+
+ watcher
+ .on("add", (path) =>
+ sendMessage(watcher, mainWindow, "fileChanged", {
+ path,
+ eventName: "add",
+ nameWatcher,
+ })
+ )
+ .on("change", (path) =>
+ sendMessage(watcher, mainWindow, "fileChanged", {
+ path,
+ eventName: "change",
+ nameWatcher,
+ })
+ )
+ .on("unlink", (path) =>
+ sendMessage(watcher, mainWindow, "fileChanged", {
+ path,
+ eventName: "unlink",
+ nameWatcher,
+ })
+ );
+}*/
+
+export interface Message {
+ path: string;
+ depth?: number;
+}
+
+export interface Changed {
+ path: string;
+ eventName: 'add' | 'change' | 'unlink' | 'addDir' | 'unlinkDir';
+}
diff --git a/src/main/main.ts b/src/main/main.ts
index 8f378ae6c..70230169b 100644
--- a/src/main/main.ts
+++ b/src/main/main.ts
@@ -23,6 +23,8 @@ import i18nInit from '../renderer/services/i18nInit';
import buildTrayIconMenu from './electron-tray-menu';
import buildDesktopMenu from './electron-menus';
import loadMainEvents from './mainEvents';
+import { watchFolder } from './chokidarWatcher';
+import { Extensions } from './types';
class AppUpdater {
constructor() {
@@ -599,14 +601,22 @@ app
loadMainEvents();
+ ipcMain.on('watchFolder', (e, path: string, depth) => {
+ //locationPath, options) => {
+
+ watchFolder(mainWindow, e, path, depth);
+ //watcher = chokidar.watch(locationPath, options);
+ });
+
ipcMain.on('load-extensions', () => {
getExtensions(path.join(app.getPath('userData'), 'tsplugins'), true)
.then(({ extensions, supportedFileTypes }) => {
if (mainWindow) {
- mainWindow.webContents.send('set_extensions', {
+ const setExtensions: Extensions = {
extensions,
supportedFileTypes,
- });
+ };
+ mainWindow.webContents.send('set_extensions', setExtensions);
// mainWindow.webContents.send('set_supported_file_types', supportedFileTypes);
}
})
diff --git a/src/main/mainEvents.ts b/src/main/mainEvents.ts
index ab7e06308..c212cb2b8 100644
--- a/src/main/mainEvents.ts
+++ b/src/main/mainEvents.ts
@@ -24,6 +24,7 @@ import fs from 'fs-extra';
import path from 'path';
// import chokidar, { FSWatcher } from 'chokidar';
import { isWorkerAvailable, postRequest, readMacOSTags } from './util';
+import { watchFolder } from './chokidarWatcher';
//let watcher: FSWatcher;
@@ -69,10 +70,6 @@ export default function loadMainEvents() {
const results = await readMacOSTags(filename);
return results;
});
- /*ipcMain.on('watchFolder', (event, locationPath, options) => {
- //const chokidar = require('chokidar');
- watcher = chokidar.watch(locationPath, options);
- });*/
ipcMain.handle('postRequest', async (event, payload, endpoint) => {
try {
const result = await postRequest(payload, endpoint);
diff --git a/src/main/preload.ts b/src/main/preload.ts
index c05db6a91..3f87888e9 100644
--- a/src/main/preload.ts
+++ b/src/main/preload.ts
@@ -43,7 +43,11 @@ export type Channels =
| 'removeExtension'
| 'getUserDataDir'
| 'unZip'
- | 'getDirProperties';
+ | 'getDirProperties'
+ | 'folderChanged'
+ | 'set_extensions'
+ | 'play-pause'
+ | 'cmd';
const electronHandler = {
ipcRenderer: {
@@ -65,6 +69,9 @@ const electronHandler = {
invoke(command: Channels, ...args: unknown[]) {
return ipcRenderer.invoke(command, ...args);
},
+ removeAllListeners(channel: string) {
+ ipcRenderer.removeAllListeners(channel);
+ },
},
};
diff --git a/src/main/types.ts b/src/main/types.ts
new file mode 100644
index 000000000..68e78938f
--- /dev/null
+++ b/src/main/types.ts
@@ -0,0 +1,6 @@
+import { TS } from '-/tagspaces.namespace';
+
+export interface Extensions {
+ extensions: TS.Extension[];
+ supportedFileTypes: TS.FileTypes[];
+}
diff --git a/src/renderer/hooks/FSWatcherContextProvider.tsx b/src/renderer/hooks/FSWatcherContextProvider.tsx
index ad2a46398..022dbb07d 100644
--- a/src/renderer/hooks/FSWatcherContextProvider.tsx
+++ b/src/renderer/hooks/FSWatcherContextProvider.tsx
@@ -37,12 +37,13 @@ import { actions as AppActions, AppDispatch } from '-/reducers/app';
import { toFsEntry } from '-/services/utils-io';
import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';
import { useDispatch } from 'react-redux';
+import { Changed } from '../../main/chokidarWatcher';
type FSWatcherContextData = {
// watcher: FSWatcher;
ignored: string[];
stopWatching: () => void;
- isWatching: () => void;
+ folderChanged: (event: string, path: string) => void;
addToIgnored: (path: string) => void;
removeFromIgnored: (path: string) => void;
ignoreByWatcher: (...paths: string[]) => void;
@@ -52,8 +53,8 @@ type FSWatcherContextData = {
export const FSWatcherContext = createContext<FSWatcherContextData>({
// watcher: undefined,
ignored: undefined,
+ folderChanged: undefined,
stopWatching: undefined,
- isWatching: undefined,
addToIgnored: undefined,
removeFromIgnored: undefined,
ignoreByWatcher: undefined,
@@ -98,9 +99,9 @@ export const FSWatcherContextProvider = ({
}
}, [currentLocation, currentLocationPath]);
- useEffect(() => {
+ /*useEffect(() => {
// watchForEvents(listener);
- }, [addDirectoryEntries, removeDirectoryEntries, ignored.current]);
+ }, [addDirectoryEntries, removeDirectoryEntries, ignored.current]);*/
/* todo impl in main
function watchForEvents(listener) {
@@ -116,120 +117,125 @@ export const FSWatcherContextProvider = ({
function watchFolder(locationPath, depth) {
console.log('Start watching: ' + locationPath);
stopWatching();
- 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,
- });
+ PlatformIO.watchFolder(locationPath, 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.current[i]) ||
- pathParts.includes(ignored.current[i])
- ) {
- // ignored.current.splice(i, 1);
+ const folderChanged = useMemo(() => {
+ return (event, path): void => {
+ console.log(`File ${path} has been ${event}`);
+ if (path.endsWith(AppConfig.metaFolder)) {
+ // .ts dir created
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);
- const dirPath = extractContainingDirectoryPath(
- path,
- PlatformIO.getDirSeparator(),
- );
- if (currentDirectoryPath === dirPath) {
- addDirectoryEntries([entry]);
- }
- reflectCreateEntry(entry);
- dispatch(AppActions.reflectCreateEntry(path, true));
- }
- break;
- case 'addDir':
- if (!path.includes(AppConfig.metaFolder)) {
- const entry = toFsEntry(path, false);
- const dirPath = extractContainingDirectoryPath(
- path,
- PlatformIO.getDirSeparator(),
- );
- if (currentDirectoryPath === dirPath) {
- addDirectoryEntries([entry]);
- }
- reflectCreateEntry(entry);
- dispatch(AppActions.reflectCreateEntry(path, false));
+ const pathParts = path.split(PlatformIO.getDirSeparator());
+ for (let i = 0; i < ignored.current.length; i++) {
+ if (
+ path.startsWith(ignored.current[i]) ||
+ pathParts.includes(ignored.current[i])
+ ) {
+ // ignored.current.splice(i, 1);
+ return;
}
- break;
- case 'change':
- console.log(`File ${path} has been changed`);
+ }
+ /*const index = ignored.current.indexOf(path);
+ if (index > -1) {
+ ignored.current.splice(index, 1);
+ return;
+ }*/
- // watching for changed sidecar files .ts/file.jpg.json
- if (path.includes(AppConfig.metaFolder)) {
- if (path.endsWith(AppConfig.metaFileExt)) {
- const directoryPath = getFileLocationFromMetaFile(
+ 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);
+ const dirPath = extractContainingDirectoryPath(
path,
PlatformIO.getDirSeparator(),
);
- loadDirectoryContent(
- extractContainingDirectoryPath(
- directoryPath,
- PlatformIO.getDirSeparator(),
- ),
- false,
- true,
- );
+ if (currentDirectoryPath === dirPath) {
+ addDirectoryEntries([entry]);
+ }
+ reflectCreateEntry(entry);
+ dispatch(AppActions.reflectCreateEntry(path, true));
}
- if (path.endsWith(AppConfig.metaFolderFile)) {
- const directoryPath = getFileLocationFromMetaFile(
+ break;
+ case 'addDir':
+ if (!path.includes(AppConfig.metaFolder)) {
+ const entry = toFsEntry(path, false);
+ const dirPath = extractContainingDirectoryPath(
path,
PlatformIO.getDirSeparator(),
);
- loadDirectoryContent(
- extractContainingDirectoryPath(
- directoryPath,
+ if (currentDirectoryPath === dirPath) {
+ 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(),
- ),
- false,
- true,
- );
+ );
+ 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;
- }
- };
+ // } 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;
+ }
+ };
+ }, [addDirectoryEntries, removeDirectoryEntries, ignored.current]);
+
+ useEffect(() => {
+ window.electronIO.ipcRenderer.on('folderChanged', (message: Changed) => {
+ const { path, eventName } = message;
+ folderChanged(eventName, path);
+ });
+
+ return () => {
+ window.electronIO.ipcRenderer.removeAllListeners('folderChanged');
+ };
+ }, [folderChanged]);
function stopWatching() {
/*if (watcher && watcher.close) {
@@ -286,8 +292,8 @@ export const FSWatcherContextProvider = ({
return {
ignored: ignored.current,
stopWatching,
- isWatching,
addToIgnored,
+ folderChanged,
removeFromIgnored,
ignoreByWatcher,
deignoreByWatcher,
diff --git a/src/renderer/hooks/RendererListenerContextProvider.tsx b/src/renderer/hooks/RendererListenerContextProvider.tsx
index 9c27e9f64..cdc9db000 100644
--- a/src/renderer/hooks/RendererListenerContextProvider.tsx
+++ b/src/renderer/hooks/RendererListenerContextProvider.tsx
@@ -23,6 +23,7 @@ import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';
import AppConfig from '-/AppConfig';
import { actions as SettingsActions } from '-/reducers/settings';
+import { Extensions } from '../../main/types';
type RendererListenerContextData = {};
@@ -33,6 +34,11 @@ export type RendererListenerContextProviderProps = {
children: React.ReactNode;
};
+/**
+ * @deprecated find better places for this
+ * @param children
+ * @constructor
+ */
export const RendererListenerContextProvider = ({
children,
}: RendererListenerContextProviderProps) => {
@@ -42,13 +48,13 @@ export const RendererListenerContextProvider = ({
useOpenedEntryContext();
useEffect(() => {
- let ipcRenderer;
- if (AppConfig.isElectron && window.require) {
- const electron = window.require('electron');
- ({ ipcRenderer } = electron);
- destroy(ipcRenderer);
+ if (AppConfig.isElectron) {
+ //const electron = window.require('electron');
+ //({ ipcRenderer } = electron);
+
+ destroy();
- ipcRenderer.on('cmd', (event, arg) => {
+ window.electronIO.ipcRenderer.on('cmd', (arg) => {
// console.log('Global events: ' + arg);
switch (arg) {
case 'new-text-file':
@@ -154,13 +160,13 @@ export const RendererListenerContextProvider = ({
props.openURLExternally(url, skipConfirm);
});*/
- ipcRenderer.on('play-pause', (event, arg) => {
+ window.electronIO.ipcRenderer.on('play-pause', () => {
// Create the event.
const audioEvent = new CustomEvent('toggle-resume', { detail: '' });
window.dispatchEvent(audioEvent);
});
- ipcRenderer.on('set_extensions', (event, arg) => {
+ window.electronIO.ipcRenderer.on('set_extensions', (arg: Extensions) => {
const { extensions, supportedFileTypes } = arg;
dispatch(AppActions.addExtensions(extensions));
dispatch(SettingsActions.addSupportedFileTypes(supportedFileTypes));
@@ -175,16 +181,16 @@ export const RendererListenerContextProvider = ({
});*/
}
return () => {
- destroy(ipcRenderer);
+ destroy();
};
}, [openNextFile, openPrevFile]);
- function destroy(ipcRenderer) {
- if (ipcRenderer) {
- ipcRenderer.removeAllListeners('cmd');
- ipcRenderer.removeAllListeners('play-pause');
- ipcRenderer.removeAllListeners('set_extensions');
- ipcRenderer.removeAllListeners('start_ws');
+ function destroy() {
+ if (window.electronIO.ipcRenderer) {
+ window.electronIO.ipcRenderer.removeAllListeners('cmd');
+ window.electronIO.ipcRenderer.removeAllListeners('play-pause');
+ window.electronIO.ipcRenderer.removeAllListeners('set_extensions');
+ window.electronIO.ipcRenderer.removeAllListeners('start_ws');
}
}
diff --git a/src/renderer/services/platform-facade.ts b/src/renderer/services/platform-facade.ts
index d5dcbd06a..3ccd43133 100644
--- a/src/renderer/services/platform-facade.ts
+++ b/src/renderer/services/platform-facade.ts
@@ -170,12 +170,12 @@ export default class PlatformFacade {
return Promise.resolve(undefined);
};
- static watchFolder = (locationPath, options) => {
+ static watchFolder = (locationPath, depth) => {
if (AppConfig.isElectron) {
window.electronIO.ipcRenderer.sendMessage(
'watchFolder',
locationPath,
- options,
+ depth,
);
}
};