TagSpaces is an offline, open source, document manager with tagging support
use preload script
Stanimir9205f5f6f11d
diff --git a/.erb/configs/webpack.config.renderer.dev.ts b/.erb/configs/webpack.config.renderer.dev.tsindex 69ab0968c..87294fb88 100644--- a/.erb/configs/webpack.config.renderer.dev.ts+++ b/.erb/configs/webpack.config.renderer.dev.ts@@ -45,7 +45,7 @@ const configuration: webpack.Configuration = {mode: 'development',- target: 'electron-renderer',+ target: ['web', 'electron-renderer'],entry: [`webpack-dev-server/client?http://localhost:${port}/dist`,diff --git a/.erb/scripts/link-modules.ts b/.erb/scripts/link-modules.tsindex 1ca02cdf7..56aa129ab 100644--- a/.erb/scripts/link-modules.ts+++ b/.erb/scripts/link-modules.ts@@ -20,11 +20,19 @@ const targetEnv = path.join(srcPath, '.env');const appEnv = path.join(appPath, '.env');if (!fs.existsSync(targetEnv) && fs.existsSync(appEnv)) {- fs.symlinkSync(appEnv, targetEnv, 'junction');+ try {+ fs.symlinkSync(appEnv, targetEnv, 'file');+ } catch (e){+ console.log(appEnv+' exist');+ }}const distEnv = path.join(distPath, '.env');if (!fs.existsSync(distEnv) && fs.existsSync(appEnv)) {- fs.symlinkSync(appEnv, distEnv, 'junction');+ try {+ fs.symlinkSync(appEnv, distEnv, 'file');+ } catch (e){+ console.log(distEnv+' exist');+ }}diff --git a/.gitignore b/.gitignoreindex bd96b8e13..9149bf769 100644--- a/.gitignore+++ b/.gitignore@@ -83,6 +83,7 @@ web/sw-config.jsweb/EULA.txt.env+src/.envsrc/renderer/configsrc/renderer/extconfig*web/extconfig*@@ -125,4 +126,4 @@ playwright-report/*deploy.shdocker/*.zip-app/version.json\ No newline at end of file+app/version.jsondiff --git a/.prettierignore b/.prettierignoreindex 6008c0ed7..d16cb6065 100755--- a/.prettierignore+++ b/.prettierignore@@ -28,6 +28,7 @@ extensions/rtf-viewer/libs/*extensions/3d-viewer/libs/*extensions/slides-viewer/libs/*extensions/spreadsheet-viewer/libs/*+extensions/image-viewer/libs/*extensions/media-player/build/*extensions/pdf-viewer/generic/build/*extensions/text-editor-react/build/*diff --git a/app/app.html b/app/app.htmldeleted file mode 100644index a5697e1f5..000000000--- a/app/app.html+++ /dev/null@@ -1,92 +0,0 @@-<!DOCTYPE html>-<html>- <head>- <title>TagSpaces Desktop</title>- <meta- http-equiv="Content-Security-Policy"- content="connect-src files: *; default-src 'self' ; object-src 'none' ; script-src 'self' 'unsafe-inline' ; style-src 'self' 'unsafe-inline' data: blob: ; media-src * blob: ; img-src * blob: data: content:;"- />- <meta charset="utf-8" />- <meta name="format-detection" content="telephone=yes" />- <meta name="msapplication-tap-highlight" content="no" />- <meta- name="viewport"- content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width"- />- <link rel="stylesheet" type="text/css" href="./dist/style.css" />- <script type="text/javascript" src="./extconfig.js"></script>- <script defer type="text/javascript" src="./dist/renderer.prod.js"></script>- </head>- <body style="overflow: hidden; margin: 0; padding: 0;">- <div id="root">- <div- style="text-align: center; width: 100%; height: 100%; font-size: 1.4em; position:absolute; z-index: 999999; background-color: #F5F5F5; user-select: none; -webkit-user-select: none; -moz-user-select: none; -webkit-app-region: drag"- class="appBackgroundTile"- >- <div- style="top:45%; width: 100%; text-align: center; position:absolute;"- >- <svg- style="vertical-align: middle"- xmlns="http://www.w3.org/2000/svg"- version="1.1"- width="100"- height="100"- >- <g- id="layer1"- transform="matrix(0.33346217,0,0,0.33346217,-0.01300084,-250.91)"- >- <rect- style="fill:none;fill-opacity:1;stroke:none"- id="rect3052-8-1"- width="299.42227"- height="299.42227"- x="-0.019505024"- y="752.95935"- />- <path- style="fill:#ffffff;fill-opacity:1;stroke:none"- d="m 181.90177,787.75394 70.88695,43.53834 C 180.29225,977.67059 187.41436,950.59754 124.58989,989.154 L 65.05006,905.90077 Z"- id="rect3052-8-2-2"- />- <ellipse- style="fill:#616577;fill-opacity:1;stroke:none"- id="path4875-4-7-5-6-2"- cx="192.4187"- cy="851.11481"- rx="15.970615"- ry="15.782593"- />- <path- style="fill:none;stroke:#a466aa;stroke-width:27.50978279;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"- d="M 159.73623,964.91671 134.54529,941.61879"- id="path3108-5-39-8"- />- <path- style="fill:none;stroke:#ffffff;stroke-width:34.19813538;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"- d="m 162.16161,795.17204 90.03628,0.34544 0,86.1724 -115.50748,117.79375 -88.457192,-81.6665 z"- id="path3923-1-1-4-9-8"- />- <path- style="fill:#f7901e;fill-opacity:1;stroke:#33b5be;stroke-width:27.50978279;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"- d="m 204.81469,910.87834 -50.38182,-45.3016"- id="path3108-9-1-76-7"- />- <path- style="fill:#616577;fill-opacity:1;stroke:#f7901e;stroke-width:27.50978279;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"- d="M 182.93838,938.7066 144.48907,904.40668"- id="path3108-0-7-9-8"- />- <path- style="fill:none;stroke:#616577;stroke-width:31.96374702;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"- d="m 164.34385,800.70161 83.03644,0 0,79.10209 -110.49206,113.42316 -82.031957,-75.83333 z"- id="path3923-1-1-4-9"- />- </g>- </svg>- </div>- </div>- </div>- </body>-</html>diff --git a/app/index.tsx b/app/index.tsxdeleted file mode 100644index 2eada461b..000000000--- a/app/index.tsx+++ /dev/null@@ -1,53 +0,0 @@-/**- * 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 ReactDOM from 'react-dom/client';-// import { AppContainer } from 'react-hot-loader';-import Root from './containers/Root';-import configureStore from './store/configureStore';-import './app.global.css';--const { store, persistor } = configureStore({});--document.addEventListener('contextmenu', (event) => event.preventDefault());--if (process.env.NODE_ENV === 'production') {- console.log = () => {};- console.time = () => {};- console.timeEnd = () => {};-}--const root = ReactDOM.createRoot(document.getElementById('root'));-root.render(- /*<AppContainer>*/- <Root store={store} persistor={persistor} />,- /*</AppContainer>*/-);--/* if (module.hot) {- module.hot.accept('./containers/Root', () => {- const NextRoot = require('./containers/Root'); // eslint-disable-line global-require- render(- <AppContainer>- <NextRoot store={store} persistor={persistor} history={history} />- </AppContainer>,- document.getElementById('root')- );- });-} */diff --git a/app/package.json b/app/package.jsondeleted file mode 100644index 4671e377e..000000000--- a/app/package.json+++ /dev/null@@ -1,23 +0,0 @@-{- "name": "tagspaces",- "productName": "TagSpaces",- "version": "5.6.2",- "description": "Offline file organizer and browser with tagging support.",- "homepage": "https://www.tagspaces.org",- "main": "./main.prod.js",- "author": {- "name": "TagSpaces UG (haftungsbeschraenkt)",- "email": "[email protected]",- "url": "https://www.tagspaces.org"- },- "license": "AGPL-3.0",- "scripts": {},- "webDependencies": {- "@tagspaces/extensions": "1.0.90"- },- "nodeDependencies": {- "@tagspaces/tagspaces-ws": "3.0.21",- "@tagspaces/extensions": "1.0.90",- "sharp": "0.31.3"- }-}diff --git a/release/app/package.json b/release/app/package.jsonindex baea9ad10..dc3ca5681 100644--- a/release/app/package.json+++ b/release/app/package.json@@ -21,9 +21,11 @@"@tagspaces/extensions": "1.0.90"},"nodeDependencies": {+ "@tagspaces/tagspaces-common-node": "3.0.21","@tagspaces/tagspaces-ws": "3.0.21","@tagspaces/extensions": "1.0.90","sharp": "0.31.3",- "@elife/pm2": "^3.6.1"+ "@elife/pm2": "^3.6.1",+ "chokidar": "^3.5.2"}}diff --git a/scripts/generateExtensionsConfig.js b/scripts/generateExtensionsConfig.jsindex c6b6b0121..10e122d98 100644--- a/scripts/generateExtensionsConfig.js+++ b/scripts/generateExtensionsConfig.js@@ -1,6 +1,6 @@const fs = require('fs');const path = require('path');-const { getExtensions } = require('../src/renderer/utils/extension-utils');+const { getExtensions } = require('../src/main/extension-utils');// const os = require('os');let directoryPath = path.join(diff --git a/src/renderer/utils/extension-utils.js b/src/main/extension-utils.jssimilarity index 99%rename from src/renderer/utils/extension-utils.jsrename to src/main/extension-utils.jsindex 4ce76191c..66f78bf54 100644--- a/src/renderer/utils/extension-utils.js+++ b/src/main/extension-utils.js@@ -2,6 +2,7 @@ const fs = require('fs');const path = require('path');/**+ * todo move in common-node* @param directoryPath* @param isExternal* @returns {Promise<{ extensions, supportedFileTypes }>}diff --git a/src/main/main.ts b/src/main/main.tsindex 94df0120e..3138938bd 100644--- a/src/main/main.ts+++ b/src/main/main.ts@@ -26,10 +26,11 @@ import { resolveHtmlPath } from './util';import windowStateKeeper from 'electron-window-state';import findFreePorts from 'find-free-ports';import settings from '../renderer/settings';-import { getExtensions } from '../renderer/utils/extension-utils';+import { getExtensions } from './extension-utils';import i18nInit from '../renderer/services/i18nInit';import buildTrayIconMenu from './electron-tray-menu';import buildDesktopMenu from './electron-menus';+import loadMainEvents from './mainEvents';class AppUpdater {constructor() {@@ -283,11 +284,11 @@ function createNewWindowInstance(url?) {width: mainWindowState.width,height: mainWindowState.height,webPreferences: {- webSecurity: app.isPackaged, // todo https://www.electronjs.org/docs/latest/tutorial/security#6-do-not-disable-websecurity+ //webSecurity: app.isPackaged, // todo https://www.electronjs.org/docs/latest/tutorial/security#6-do-not-disable-websecurityspellcheck: true,- nodeIntegration: true,+ //nodeIntegration: true,webviewTag: true,- contextIsolation: false,+ //contextIsolation: false,},});@@ -455,11 +456,11 @@ const createWindow = async (i18n) => {height: mainWindowState.height,//icon: getAssetPath('icon.png'),webPreferences: {- webSecurity: app.isPackaged, // todo https://www.electronjs.org/docs/latest/tutorial/security#6-do-not-disable-websecurity+ //webSecurity: app.isPackaged, // todo https://www.electronjs.org/docs/latest/tutorial/security#6-do-not-disable-websecurityspellcheck: true,- nodeIntegration: true,+ //nodeIntegration: true,webviewTag: true,- contextIsolation: false,+ //contextIsolation: false,preload: app.isPackaged? path.join(__dirname, 'preload.js'): path.join(__dirname, '../../.erb/dll/preload.js'),@@ -602,6 +603,8 @@ appcreateNewWindowInstance(url);});+ loadMainEvents();+ipcMain.on('load-extensions', () => {getExtensions(path.join(app.getPath('userData'), 'tsplugins'), true).then(({ extensions, supportedFileTypes }) => {@@ -616,53 +619,12 @@ app.catch((err) => console.error('load-extensions', err));});- ipcMain.on('remove-extension', (e, extensionId) => {- try {- const extBuildIndex = extensionId.indexOf('/build');- fs.rmSync(- path.join(- app.getPath('userData'),- 'tsplugins',- extBuildIndex > -1- ? extensionId.substring(0, extBuildIndex)- : extensionId,- ),- {- recursive: true,- },- );- } catch (e) {- console.debug(e);- }- });-- ipcMain.handle('get-user-data', () => {- return app.getPath('userData');- });-ipcMain.on('focus-window', () => {if (mainWindow) {mainWindow.focus();}});- ipcMain.handle('get-device-paths', () => {- const paths: any = {- desktopFolder: app.getPath('desktop'),- documentsFolder: app.getPath('documents'),- downloadsFolder: app.getPath('downloads'),- musicFolder: app.getPath('music'),- picturesFolder: app.getPath('pictures'),- videosFolder: app.getPath('videos'),- };- if (process.platform === 'darwin') {- paths.iCloudFolder =- app.getPath('home') +- '/Library/Mobile Documents/com~apple~CloudDocs';- }- return paths;- });-ipcMain.on('get-user-home-path', (event) => {event.returnValue = app.getPath('home');});@@ -673,20 +635,6 @@ app}});- ipcMain.handle('select-directory-dialog', async () => {- const options = {- properties: ['openDirectory', 'createDirectory'],- };- // @ts-ignore- const resultObject = await dialog.showOpenDialog(options);-- if (resultObject.filePaths && resultObject.filePaths.length) {- // alert(JSON.stringify(resultObject.filePaths));- return resultObject.filePaths;- }- return false;- });-// end electron-ioipcMain.on('app-data-path-request', (event) => {@@ -697,7 +645,7 @@ appevent.returnValue = app.getVersion(); // eslint-disable-line});- ipcMain.handle('move-to-trash', async (event, files) => {+ /*ipcMain.handle('move-to-trash', async (event, files) => {const result = [];files.forEach((fullPath) => {// console.debug('Trash:' + fullPath);@@ -711,26 +659,16 @@ appconsole.error('moveToTrash ' + JSON.stringify(files) + 'error:', err);}return ret;- });-- /* ipcMain.on('move-to-trash', async (event, files) => {- const result = [];- files.forEach(fullPath => {- console.debug('Trash:' + fullPath);- result.push(shell.trashItem(fullPath));- });- try {- event.returnValue = await Promise.all(result);- } catch (err) {- console.error('moveToTrash error:', err);- event.returnValue = undefined;- }- }); */+ });*/ipcMain.on('set-language', (e, language) => {i18n.changeLanguage(language);});+ ipcMain.on('setZoomFactor', (event, zoomLevel) => {+ mainWindow.webContents.setZoomFactor(zoomLevel);+ });+ipcMain.on('global-shortcuts-enabled', (e, globalShortcutsEnabled) => {if (globalShortcutsEnabled) {globalShortcut.register('CommandOrControl+Shift+F', showSearch);@@ -749,11 +687,6 @@ appipcMain.on('relaunch-app', reloadApp);- ipcMain.on('quit-application', () => {- globalShortcut.unregisterAll();- app.quit();- });-process.on('uncaughtException', (error) => {if (error.stack) {console.error('error:', error.stack);diff --git a/src/main/mainEvents.ts b/src/main/mainEvents.tsnew file mode 100644index 000000000..95fdcae01--- /dev/null+++ b/src/main/mainEvents.ts@@ -0,0 +1,284 @@+import { app, dialog, globalShortcut, ipcMain, shell } from 'electron';+import {+ getPropertiesPromise,+ listDirectoryPromise,+ listMetaDirectoryPromise,+ createDirectoryPromise,+ copyFilePromiseOverwrite,+ renameFilePromise,+ renameDirectoryPromise,+ copyDirectoryPromise,+ moveDirectoryPromise,+ loadTextFilePromise,+ getFileContentPromise,+ getLocalFileContentPromise,+ saveFilePromise,+ saveTextFilePromise,+ saveBinaryFilePromise,+ deleteFilePromise,+ deleteDirectoryPromise,+ unZip,+ getDirProperties,+} from '@tagspaces/tagspaces-common-node/io-node';+import fs from 'fs-extra';+import path from 'path';+import chokidar, { FSWatcher } from 'chokidar';+import { postRequest, readMacOSTags } from './util';++let watcher: FSWatcher = undefined;++export default function loadMainEvents() {+ ipcMain.on('quitApp', () => {+ globalShortcut.unregisterAll();+ app.quit();+ });+ ipcMain.handle('getDevicePaths', () => {+ const paths: any = {+ desktopFolder: app.getPath('desktop'),+ documentsFolder: app.getPath('documents'),+ downloadsFolder: app.getPath('downloads'),+ musicFolder: app.getPath('music'),+ picturesFolder: app.getPath('pictures'),+ videosFolder: app.getPath('videos'),+ };+ if (process.platform === 'darwin') {+ paths.iCloudFolder =+ app.getPath('home') + '/Library/Mobile Documents/com~apple~CloudDocs';+ }+ return paths;+ });+ /*ipcMain.handle('isWorkerAvailable', async (event, wsPort) => {+ try {+ const res = fetch('http://127.0.0.1:' + wsPort, {+ method: 'HEAD',+ });+ return res.status === 200;+ } catch (e) {+ console.debug('isWorkerAvailable:', e);+ }+ return false;+ });*/+ ipcMain.handle('readMacOSTags', async (event, filename) => {+ 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, token, wsPort) => {+ const result = await postRequest(payload, endpoint, token, wsPort);+ return result;+ },+ );+ ipcMain.handle(+ 'listDirectoryPromise',+ async (event, path, mode, ignorePatterns, resultsLimit) => {+ const result = await listDirectoryPromise(+ path,+ mode,+ ignorePatterns,+ resultsLimit,+ );+ return result;+ },+ );+ ipcMain.handle('listMetaDirectoryPromise', async (event, path) => {+ const result = await listMetaDirectoryPromise(path);+ return result;+ });+ ipcMain.handle('getPropertiesPromise', async (event, path) => {+ const result = await getPropertiesPromise(path);+ return result;+ });+ ipcMain.handle('checkDirExist', async (event, dir) => {+ const stats = await getPropertiesPromise(dir);+ return stats && !stats.isFile;+ });+ ipcMain.handle('checkFileExist', async (event, file) => {+ const stats = await getPropertiesPromise(file);+ return stats && stats.isFile;+ });+ ipcMain.handle('createDirectoryPromise', async (event, dirPath) => {+ const result = await createDirectoryPromise(dirPath);+ return result;+ });+ ipcMain.handle(+ 'copyFilePromiseOverwrite',+ async (event, sourceFilePath, targetFilePath) => {+ const result = await copyFilePromiseOverwrite(+ sourceFilePath,+ targetFilePath,+ );+ return result;+ },+ );+ ipcMain.handle(+ 'renameFilePromise',+ async (event, filePath, newFilePath, onProgress) => {+ const result = await renameFilePromise(filePath, newFilePath, onProgress);+ return result;+ },+ );+ ipcMain.handle(+ 'renameDirectoryPromise',+ async (event, dirPath, newDirName) => {+ const result = await renameDirectoryPromise(dirPath, newDirName);+ return result;+ },+ );+ ipcMain.handle(+ 'copyDirectoryPromise',+ async (event, param, newDirPath, onProgress) => {+ const result = await copyDirectoryPromise(param, newDirPath, onProgress);+ return result;+ },+ );+ ipcMain.handle(+ 'moveDirectoryPromise',+ async (event, param, newDirPath, onProgress) => {+ const result = await moveDirectoryPromise(param, newDirPath, onProgress);+ return result;+ },+ );+ ipcMain.handle('loadTextFilePromise', async (event, path, isPreview) => {+ const result = await loadTextFilePromise(path, isPreview);+ return result;+ });+ ipcMain.handle('getFileContentPromise', async (event, filePath, type) => {+ const result = await getFileContentPromise(filePath, type);+ return result;+ });+ ipcMain.handle(+ 'getLocalFileContentPromise',+ async (event, filePath, type) => {+ const result = await getLocalFileContentPromise(filePath, type);+ return result;+ },+ );+ ipcMain.handle(+ 'saveFilePromise',+ async (event, param, content, overwrite) => {+ const result = await saveFilePromise(param, content, overwrite);+ return result;+ },+ );+ ipcMain.handle(+ 'saveTextFilePromise',+ async (event, param, content, overwrite) => {+ const result = await saveTextFilePromise(param, content, overwrite);+ return result;+ },+ );+ ipcMain.handle(+ 'saveBinaryFilePromise',+ async (event, param, content, overwrite, onUploadProgress) => {+ const result = await saveBinaryFilePromise(+ param,+ content,+ overwrite,+ onUploadProgress,+ ).then((succeeded) => {+ if (succeeded && onUploadProgress) {+ onUploadProgress({ key: param.path, loaded: 1, total: 1 }, undefined);+ }+ return succeeded;+ });+ return result;+ },+ );+ ipcMain.handle('deleteFilePromise', async (event, path, useTrash) => {+ if (useTrash) {+ let ret;+ try {+ ret = await shell.trashItem(path);+ } catch (err) {+ console.error('moveToTrash ' + path + 'error:', err);+ }+ return ret;+ } else {+ const result = await deleteFilePromise(path);+ return result;+ }+ });+ ipcMain.handle('deleteDirectoryPromise', async (event, path, useTrash) => {+ if (useTrash) {+ let ret;+ try {+ ret = await shell.trashItem(path);+ } catch (err) {+ console.error('moveToTrash ' + path + 'error:', err);+ }+ return ret;+ } else {+ const result = await deleteDirectoryPromise(path);+ return result;+ }+ });+ ipcMain.on('openDirectory', async (event, dirPath) => {+ shell.showItemInFolder(dirPath);+ });+ ipcMain.on('openFile', async (event, filePath) => {+ shell+ .openPath(filePath)+ .then(() => {+ console.log('File successfully opened ' + filePath);+ return true;+ })+ .catch((e) => {+ console.log('Opening path ' + filePath + ' failed with ' + e);+ });+ });+ ipcMain.on('openUrl', async (event, url) => {+ await shell.openExternal(url);+ });+ ipcMain.handle('selectDirectoryDialog', async () => {+ const options = {+ properties: ['openDirectory', 'createDirectory'],+ };+ // @ts-ignore+ const resultObject = await dialog.showOpenDialog(options);++ if (resultObject.filePaths && resultObject.filePaths.length) {+ // alert(JSON.stringify(resultObject.filePaths));+ return resultObject.filePaths;+ }+ return false;+ });++ ipcMain.on('removeExtension', (e, extensionId) => {+ try {+ const extBuildIndex = extensionId.indexOf('/build');+ fs.rmSync(+ path.join(+ app.getPath('userData'),+ 'tsplugins',+ extBuildIndex > -1+ ? extensionId.substring(0, extBuildIndex)+ : extensionId,+ ),+ {+ recursive: true,+ },+ );+ } catch (e) {+ console.debug(e);+ }+ });++ ipcMain.handle('getUserDataDir', () => {+ return app.getPath('userData');+ });++ ipcMain.handle('unZip', async (event, filePath, targetPath) => {+ const result = await unZip(filePath, targetPath);+ return result;+ });++ ipcMain.handle('getDirProperties', async (event, path) => {+ const result = await getDirProperties(path);+ return result;+ });+}diff --git a/src/main/preload.ts b/src/main/preload.tsindex 9133a7922..835a3bd2a 100644--- a/src/main/preload.ts+++ b/src/main/preload.ts@@ -2,7 +2,46 @@/* eslint no-unused-vars: off */import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';-export type Channels = 'ipc-example';+export type Channels =+ | 'set-language'+ | 'setZoomFactor'+ | 'global-shortcuts-enabled'+ | 'show-main-window'+ | 'create-new-window'+ | 'quitApp'+ | 'focus-window'+ | 'getDevicePaths'+ | 'readMacOSTags'+ | 'watchFolder'+ | 'postRequest'+ | 'listDirectoryPromise'+ | 'listMetaDirectoryPromise'+ | 'getPropertiesPromise'+ | 'checkDirExist'+ | 'checkFileExist'+ | 'createDirectoryPromise'+ | 'copyFilePromiseOverwrite'+ | 'renameFilePromise'+ | 'renameDirectoryPromise'+ | 'copyDirectoryPromise'+ | 'moveDirectoryPromise'+ | 'loadTextFilePromise'+ | 'getFileContentPromise'+ | 'getLocalFileContentPromise'+ | 'saveFilePromise'+ | 'saveTextFilePromise'+ | 'saveBinaryFilePromise'+ | 'deleteFilePromise'+ | 'deleteDirectoryPromise'+ | 'openDirectory'+ | 'openFile'+ | 'openUrl'+ | 'selectDirectoryDialog'+ | 'load-extensions'+ | 'removeExtension'+ | 'getUserDataDir'+ | 'unZip'+ | 'getDirProperties';const electronHandler = {ipcRenderer: {@@ -21,9 +60,11 @@ const electronHandler = {once(channel: Channels, func: (...args: unknown[]) => void) {ipcRenderer.once(channel, (_event, ...args) => func(...args));},+ invoke(command: Channels, ...args: unknown[]) {+ return ipcRenderer.invoke(command, ...args);+ },},};-contextBridge.exposeInMainWorld('electron', electronHandler);-+contextBridge.exposeInMainWorld('electronIO', electronHandler);export type ElectronHandler = typeof electronHandler;diff --git a/src/main/util.ts b/src/main/util.tsindex 4f10af6e7..5d1b5324e 100644--- a/src/main/util.ts+++ b/src/main/util.ts@@ -5,6 +5,7 @@ import webpackPaths from '../../.erb/configs/webpack.paths';import fs from 'fs';import chalk from 'chalk';import { execSync } from 'child_process';+import http from 'http';export function resolveHtmlPath(htmlFileName: string) {if (process.env.NODE_ENV === 'development') {@@ -56,8 +57,108 @@ export function generateJWT() {console.log(chalk.red.bgWhiteBright.bold("Don't forget to change this KEY!"),);- execSync('echo "KEY=testDevKey" > ' + env);+ execSync('echo KEY=testDevKey > ' + env);}execSync('npm run generate-jwt');}++/**+ * @param payload: string+ * @param endpoint: string+ * @param token: string+ * @param wsPort: number+ */+export function postRequest(payload, endpoint, token, wsPort) {+ return new Promise((resolve, reject) => {+ const option = {+ hostname: '127.0.0.1',+ port: wsPort,+ method: 'POST',+ path: endpoint,+ headers: {+ Authorization: 'Bearer ' + token,+ 'Content-Type': 'application/json',+ 'Content-Length': Buffer.byteLength(payload, 'utf8'),+ },+ };+ const reqPost = http+ .request(option, (resp) => {+ // .get('http://127.0.0.1:8888/thumb-gen?' + search.toString(), resp => {+ let data = '';++ // A chunk of data has been received.+ resp.on('data', (chunk) => {+ data += chunk;+ });++ // The whole response has been received. Print out the result.+ resp.on('end', () => {+ if (data) {+ try {+ resolve(JSON.parse(data));+ } catch (ex) {+ reject(ex);+ }+ } else {+ reject(new Error('Error: no data'));+ }+ });+ })+ .on('error', (err) => {+ console.log('Error: ' + err.message);+ reject(err);+ });+ reqPost.write(payload);+ reqPost.end();+ });+}++/**+ * @param filename+ * @returns {Promise<TS.Tag[]>}+ */+export function readMacOSTags(filename) {+ const cmdArr = [+ 'mdls',+ '-raw',+ '-name',+ 'kMDItemUserTags',+ '"' + filename + '"',+ ];+ const cmd = cmdArr.join(' ');++ return new Promise((resolve, reject) => {+ const foundTags = [];+ const { exec } = require('child_process');+ exec(cmd, (error, stdout, stderr) => {+ if (error) {+ console.error(error);+ reject(error);+ }+ if (stderr) {+ console.log(stderr);+ reject(stderr);+ }+ if (stdout && stdout !== '(null)') {+ stdout+ .toString()+ .replace(/^\(|\)$/g, '')+ .split(',')+ .map((item) => {+ const newTag = {+ // id: uuidv1(),+ title: item.trim(),+ };+ foundTags.push(newTag);+ return newTag;+ });++ resolve(foundTags);+ // console.log('Tags in file "' + filename + '": ' + JSON.stringify(foundTags));+ } else {+ resolve(foundTags);+ }+ });+ });+}diff --git a/src/renderer/components/EntryProperties.tsx b/src/renderer/components/EntryProperties.tsxindex d467147b5..3ab5d8fc3 100644--- a/src/renderer/components/EntryProperties.tsx+++ b/src/renderer/components/EntryProperties.tsx@@ -263,7 +263,11 @@ function EntryProperties(props: Props) {const firstRender = useFirstRender();useEffect(() => {- if (!currentEntry.current.isFile) {+ if (+ !currentEntry.current.isFile &&+ !PlatformIO.haveObjectStoreSupport() &&+ !PlatformIO.haveWebDavSupport()+ ) {PlatformIO.getDirProperties(currentEntry.current.path).then((dProps: TS.DirProp) => {dirProps.current = dProps;diff --git a/src/renderer/components/dialogs/MoveOrCopyFilesDialog.tsx b/src/renderer/components/dialogs/MoveOrCopyFilesDialog.tsxindex bc5b757eb..7910b8fab 100644--- a/src/renderer/components/dialogs/MoveOrCopyFilesDialog.tsx+++ b/src/renderer/components/dialogs/MoveOrCopyFilesDialog.tsx@@ -27,7 +27,6 @@ import Paper from '@mui/material/Paper';import List from '@mui/material/List';import ListItem from '@mui/material/ListItem';import ListItemIcon from '@mui/material/ListItemIcon';-import PlatformIO from '-/services/platform-facade';import FileIcon from '@mui/icons-material/InsertDriveFileOutlined';import DialogActions from '@mui/material/DialogActions';import DialogContent from '@mui/material/DialogContent';@@ -46,7 +45,7 @@ import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';interface Props {open: boolean;onClose: (clearSelection?: boolean) => void;- selectedFiles: Array<File>;+ selectedFiles: Array<any>;}function MoveOrCopyFilesDialog(props: Props) {@@ -60,7 +59,7 @@ function MoveOrCopyFilesDialog(props: Props) {// const dispatch: AppDispatch = useDispatch();const fullScreen = useMediaQuery(theme.breakpoints.down('md'));- const handleMoveCopyFiles = (files: Array<File>, move = false) => {+ const handleMoveCopyFiles = (files: Array<any>, move = false) => {const promises = [];for (const file of files) {if (move) {@@ -121,7 +120,7 @@ function MoveOrCopyFilesDialog(props: Props) {<List dense style={{ width: 550, marginLeft: -15 }}>{props.selectedFiles &&props.selectedFiles.length > 0 &&- props.selectedFiles.map((file: File) => (+ props.selectedFiles.map((file) => (<ListItem title={file.path} key={file.path}><ListItemIcon><FileIcon />diff --git a/src/renderer/components/menus/FileMenu.tsx b/src/renderer/components/menus/FileMenu.tsxindex ea4ddc7b6..f7d69b298 100644--- a/src/renderer/components/menus/FileMenu.tsx+++ b/src/renderer/components/menus/FileMenu.tsx@@ -382,7 +382,7 @@ function FileMenu(props: Props) {onClick={() => {onClose();if (selectedFilePath) {- PlatformIO.showInFileManager(selectedFilePath);+ PlatformIO.openDirectory(selectedFilePath);}}}>diff --git a/src/renderer/components/menus/LocationContextMenu.tsx b/src/renderer/components/menus/LocationContextMenu.tsxindex 5b53e4356..f38258002 100644--- a/src/renderer/components/menus/LocationContextMenu.tsx+++ b/src/renderer/components/menus/LocationContextMenu.tsx@@ -121,7 +121,7 @@ function LocationContextMenu(props: Props) {const showInFileManagerInt = () => {setLocationDirectoryContextMenuAnchorEl(null);- PlatformIO.showInFileManager(PlatformIO.getLocationPath(selectedLocation));+ PlatformIO.openDirectory(PlatformIO.getLocationPath(selectedLocation));};const closeLocationInt = () => {diff --git a/src/renderer/hooks/FSWatcherContextProvider.tsx b/src/renderer/hooks/FSWatcherContextProvider.tsxindex 1b0c7a16d..658cf3afc 100644--- a/src/renderer/hooks/FSWatcherContextProvider.tsx+++ b/src/renderer/hooks/FSWatcherContextProvider.tsx@@ -23,7 +23,6 @@ import React, {useRef,useState,} from 'react';-import { FSWatcher } from 'chokidar';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import PlatformIO from '-/services/platform-facade';import AppConfig from '-/AppConfig';@@ -40,7 +39,7 @@ import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';import { useDispatch } from 'react-redux';type FSWatcherContextData = {- watcher: FSWatcher;+ // watcher: FSWatcher;ignored: string[];stopWatching: () => void;isWatching: () => void;@@ -51,7 +50,7 @@ type FSWatcherContextData = {};export const FSWatcherContext = createContext<FSWatcherContextData>({- watcher: undefined,+ // watcher: undefined,ignored: undefined,stopWatching: undefined,isWatching: undefined,@@ -77,7 +76,7 @@ export const FSWatcherContextProvider = ({removeDirectoryEntries,} = useDirectoryContentContext();const { reflectDeleteEntry, reflectCreateEntry } = useLocationIndexContext();- const [watcher, setWatcher] = useState<FSWatcher>(undefined);+ //const [watcher, setWatcher] = useState<FSWatcher>(undefined);const ignored = useRef<string[]>([]);const dispatch: AppDispatch = useDispatch();@@ -89,32 +88,32 @@ export const FSWatcherContextProvider = ({) {const depth =currentDirectoryPerspective === PerspectiveIDs.KANBAN ? 3 : 1;- setWatcher(- watchFolder(PlatformIO.getLocationPath(currentLocation), depth),- );++ watchFolder(PlatformIO.getLocationPath(currentLocation), depth);} else {stopWatching();}}, [currentLocation]);useEffect(() => {- watchForEvents();+ // watchForEvents(listener);}, [addDirectoryEntries, removeDirectoryEntries, ignored.current]);- function watchForEvents() {+ /* todo impl in main+ function watchForEvents(listener) {if (watcher !== undefined) {// To remove the listenerwatcher.removeAllListeners();watcher.on('all', listener);- } /*else {+ } /!*else {console.log('Indexing not supported on this platform');- }*/- }+ }*!/+ }*/function watchFolder(locationPath, depth) {console.log('Start watching: ' + locationPath);stopWatching();- return PlatformIO.watchFolder(locationPath, {+ 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@@ -230,14 +229,14 @@ export const FSWatcherContextProvider = ({};function stopWatching() {- if (watcher && watcher.close) {+ /*if (watcher && watcher.close) {watcher.close();setWatcher(undefined);- }+ }*/}function isWatching() {- return watcher !== undefined; //&& !watcher.closed;+ return false; //watcher !== undefined; //&& !watcher.closed;}function addToIgnored(path: string) {@@ -282,7 +281,6 @@ export const FSWatcherContextProvider = ({const context = useMemo(() => {return {- watcher,ignored: ignored.current,stopWatching,isWatching,@@ -291,7 +289,7 @@ export const FSWatcherContextProvider = ({ignoreByWatcher,deignoreByWatcher,};- }, [watcher, ignored.current]);+ }, [ignored.current]);return (<FSWatcherContext.Provider value={context}>diff --git a/src/renderer/hooks/FsActionsContextProvider.tsx b/src/renderer/hooks/FsActionsContextProvider.tsxindex b451159bc..8feaabd47 100644--- a/src/renderer/hooks/FsActionsContextProvider.tsx+++ b/src/renderer/hooks/FsActionsContextProvider.tsx@@ -63,7 +63,7 @@ export const FsActionsContextProvider = ({const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();const { reflectRenameEntry } = useLocationIndexContext();const { showNotification } = useNotificationContext();- const { watcher } = useFSWatcherContext();+ //const { watcher } = useFSWatcherContext();const { renameFilePromise, renameFilesPromise, renameDirectoryPromise } =usePlatformFacadeContext();const dispatch: AppDispatch = useDispatch();@@ -200,7 +200,7 @@ export const FsActionsContextProvider = ({renameFile,openFileNatively,};- }, [openedEntries, watcher]);+ }, [openedEntries]); //watcherreturn (<FsActionsContext.Provider value={context}>diff --git a/src/renderer/hooks/IOActionsContextProvider.tsx b/src/renderer/hooks/IOActionsContextProvider.tsxindex ddd3d9680..da35de131 100644--- a/src/renderer/hooks/IOActionsContextProvider.tsx+++ b/src/renderer/hooks/IOActionsContextProvider.tsx@@ -95,7 +95,7 @@ type IOActionsContextData = {onDownloadProgress?: (progress: Progress, abort, fileName?) => void,) => Promise<TS.FileSystemEntry>;uploadFilesAPI: (- files: Array<File>,+ files: Array<any>,targetPath: string,onUploadProgress?: (progress: Progress, abort, fileName?) => void,uploadMeta?: boolean,@@ -648,7 +648,7 @@ export const IOActionsContextProvider = ({* reader.onload not work for multiple files https://stackoverflow.com/questions/56178918/react-upload-multiple-files-using-window-filereader*/function uploadFilesAPI(- files: Array<File>,+ files: Array<any>,targetPath: string,onUploadProgress?: (progress: Progress, abort, fileName?) => void,uploadMeta = true,diff --git a/src/renderer/hooks/PlatformFacadeContextProvider.tsx b/src/renderer/hooks/PlatformFacadeContextProvider.tsxindex 9d64aeb9b..d0615bacb 100644--- a/src/renderer/hooks/PlatformFacadeContextProvider.tsx+++ b/src/renderer/hooks/PlatformFacadeContextProvider.tsx@@ -120,8 +120,7 @@ export type PlatformFacadeContextProviderProps = {export const PlatformFacadeContextProvider = ({children,}: PlatformFacadeContextProviderProps) => {- const { ignoreByWatcher, deignoreByWatcher, ignored, watcher } =- useFSWatcherContext();+ const { ignoreByWatcher, deignoreByWatcher, ignored } = useFSWatcherContext(); //watcherconst { t } = useTranslation();const dispatch: AppDispatch = useDispatch();@@ -489,7 +488,7 @@ export const PlatformFacadeContextProvider = ({deleteDirectoryPromise,setFolderThumbnailPromise,};- }, [watcher, ignored]);+ }, [ignored]); //watcherreturn (<PlatformFacadeContext.Provider value={context}>diff --git a/src/renderer/preload.d.ts b/src/renderer/preload.d.tsindex 53cc2d7b1..2577f9a68 100644--- a/src/renderer/preload.d.ts+++ b/src/renderer/preload.d.ts@@ -3,7 +3,7 @@ import { ElectronHandler } from '../main/preload';declare global {// eslint-disable-next-line no-unused-varsinterface Window {- electron: ElectronHandler;+ electronIO: ElectronHandler;}}diff --git a/src/renderer/services/platform-facade.ts b/src/renderer/services/platform-facade.tsindex 74ed15e9c..53bc08729 100644--- a/src/renderer/services/platform-facade.ts+++ b/src/renderer/services/platform-facade.ts@@ -25,22 +25,13 @@ import {platformDisableObjectStoreSupport,platformEnableWebdavSupport,platformDisableWebdavSupport,- platformWatchDirectory,platformGetLocationPath,platformSetLanguage,- platformIsWorkerAvailable,- platformReadMacOSTags,- platformWatchFolder,- platformTiffJs,platformSetZoomFactorElectron,platformSetGlobalShortcuts,platformShowMainWindow,platformQuitApp,- platformFocusWindow,platformGetDevicePaths,- platformCreateDirectoryTree,- platformCreateDirectoryIndexInWorker,- platformCreateThumbnailsInWorker,platformGetURLforPath,platformListDirectoryPromise,platformListMetaDirectoryPromise,@@ -49,7 +40,6 @@ import {platformGetPropertiesPromise,platformLoadTextFilePromise,platformGetFileContentPromise,- platformGetLocalFileContentPromise,platformSaveTextFilePromise,platformSaveBinaryFilePromise,platformCreateDirectoryPromise,@@ -60,25 +50,13 @@ import {platformCopyDirectoryPromise,platformDeleteFilePromise,platformDeleteDirectoryPromise,- platformOpenDirectory,- platformShowInFileManager,- platformOpenFile,- // platformResolveFilePath,- platformOpenUrl,- platformSelectFileDialog,platformSelectDirectoryDialog,platformShareFiles,platformCreateIndex,platformCreateNewInstance,platformCheckFileExist,platformCheckDirExist,- platformLoadExtensions,- platformRemoveExtension,- platformGetUserDataDir,- platformUnZip,- platformDirProperties,} from '@tagspaces/tagspaces-platforms/platform-io';-import { cleanTrailingDirSeparator } from '@tagspaces/tagspaces-common/paths';import AppConfig from '-/AppConfig';import { TS } from '-/tagspaces.namespace';import settings from '-/settings';@@ -107,26 +85,43 @@ export default class PlatformFacade {static getDirSeparator = (): string => platformGetDirSeparator();+ /**+ * todo rethink this use node path module+ * @param location+ */static getLocationPath = (location: TS.Location): string =>platformGetLocationPath(location);static setLanguage = (language: string): void => {- platformSetLanguage(language);+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('set-language', language);+ }};static setZoomFactorElectron = (zoomLevel) => {- platformSetZoomFactorElectron(zoomLevel);+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('setZoomFactor', zoomLevel);+ }};static setGlobalShortcuts = (globalShortcutsEnabled) => {- platformSetGlobalShortcuts(globalShortcutsEnabled);+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage(+ 'global-shortcuts-enabled',+ globalShortcutsEnabled,+ );+ }};- static showMainWindow = (): void => platformShowMainWindow();+ static showMainWindow = (): void => {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('show-main-window');+ }+ };static createNewInstance = (url?: string): void => {if (AppConfig.isElectron) {- platformCreateNewInstance(url);+ window.electronIO.ipcRenderer.sendMessage('create-new-window', url);} else {if (url) {window.open(url, '_blank');@@ -136,84 +131,141 @@ export default class PlatformFacade {}};- static quitApp = (): void => platformQuitApp();-- static watchDirectory = (dirPath: string, listener): void =>- platformWatchDirectory(dirPath, listener);-- static focusWindow = (): void => platformFocusWindow();+ static quitApp = (): void => {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('quitApp');+ } else {+ platformQuitApp();+ }+ };- static getDevicePaths = (): Promise<any> => platformGetDevicePaths();+ /*static watchDirectory = (dirPath: string, listener): void =>+ platformWatchDirectory(dirPath, listener);*/- /* static getAppDataPath = (): string => nativeAPI.getAppDataPath();+ static focusWindow = (): void => {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('focus-window');+ }+ };- static getUserHomePath = (): string => nativeAPI.getUserHomePath(); */+ static getDevicePaths = (): Promise<any> => {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('getDevicePaths');+ }+ return platformGetDevicePaths();+ };+ /**+ * ObjectStore and webDav only+ * @param path+ * @param expirationInSeconds+ */static getURLforPath = (path: string, expirationInSeconds?: number): string =>platformGetURLforPath(path, expirationInSeconds);- static createDirectoryTree = (directoryPath: string): Object =>- platformCreateDirectoryTree(directoryPath);-+ /**+ * needs to run in init this function always return false first time+ */static isWorkerAvailable = (): boolean => {if (token !== undefined) {return token !== 'not';}- try {- // eslint-disable-next-line global-require- const config = require('-/config/config.json');- if (platformIsWorkerAvailable(settings.getUsedWsPort())) {- token = config.jwt;- }- } catch (e) {- if (e && e.code && e.code === 'MODULE_NOT_FOUND') {- console.debug('jwt token not available');- token = 'not';+ if (AppConfig.isElectron) {+ try {+ fetch('http://127.0.0.1:' + settings.getUsedWsPort(), {+ method: 'HEAD',+ }).then((res) => {+ if (res.status === 200) {+ const config = require('-/config/config.json');+ token = config.jwt;+ return true;+ }+ });+ } catch (e) {+ if (e && e.code && e.code === 'MODULE_NOT_FOUND') {+ console.debug('jwt token not available');+ token = 'not';+ }+ console.debug('isWorkerAvailable:', e);}}return false;};static readMacOSTags = (filename: string): Promise<TS.Tag[]> => {- return platformReadMacOSTags(filename);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('readMacOSTags', filename);+ }+ return Promise.resolve(undefined);};static watchFolder = (locationPath, options) => {- return platformWatchFolder(locationPath, options);+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage(+ 'watchFolder',+ locationPath,+ options,+ );+ }};- static tiffJs = () => {+ /*static watchForEvents = (listener) => {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage(+ 'watchForEvents',+ listener+ );+ }+ };*/++ /*static tiffJs = () => {return platformTiffJs();- };+ };*/static createDirectoryIndexInWorker = (directoryPath: string,extractText: boolean,ignorePatterns: Array<string>,): Promise<any> => {- if (!PlatformFacade.isWorkerAvailable()) {- return Promise.reject(new Error('no Worker Available!'));+ if (AppConfig.isElectron) {+ if (!PlatformFacade.isWorkerAvailable()) {+ return Promise.reject(new Error('no Worker Available!'));+ }+ const payload = JSON.stringify({+ directoryPath,+ extractText,+ ignorePatterns,+ });+ return window.electronIO.ipcRenderer.invoke(+ 'postRequest',+ payload,+ '/thumb-gen',+ token,+ settings.getUsedWsPort(),+ );}- return platformCreateDirectoryIndexInWorker(- token,- directoryPath,- extractText,- ignorePatterns,- settings.getUsedWsPort(),+ return Promise.reject(+ new Error('createDirectoryIndexInWorker not Electron!'),);};static createThumbnailsInWorker = (tmbGenerationList: Array<string>,): Promise<any> => {- if (!PlatformFacade.isWorkerAvailable()) {- return Promise.reject(new Error('no Worker Available!'));+ if (AppConfig.isElectron) {+ if (!PlatformFacade.isWorkerAvailable()) {+ return Promise.reject(new Error('no Worker Available!'));+ }+ const payload = JSON.stringify(tmbGenerationList);+ return window.electronIO.ipcRenderer.invoke(+ 'postRequest',+ payload,+ '/thumb-gen',+ token,+ settings.getUsedWsPort(),+ );}- return platformCreateThumbnailsInWorker(- token,- tmbGenerationList,- settings.getUsedWsPort(),- );+ return Promise.reject(new Error('createThumbnailsInWorker not Electron!'));};/**@@ -228,16 +280,33 @@ export default class PlatformFacade {mode = ['extractThumbPath'],ignorePatterns: Array<string> = [],resultsLimit: any = {},- ): Promise<Array<any>> =>- platformListDirectoryPromise(+ ): Promise<Array<any>> => {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'listDirectoryPromise',+ path,+ mode,+ ignorePatterns,+ resultsLimit,+ );+ }+ return platformListDirectoryPromise(path, // cleanTrailingDirSeparator(path),mode,ignorePatterns,resultsLimit,);+ };- static listMetaDirectoryPromise = (path: string): Promise<Array<any>> =>+ static listMetaDirectoryPromise = (path: string): Promise<Array<any>> => {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'listMetaDirectoryPromise',+ path,+ );+ }platformListMetaDirectoryPromise(path);+ };static listObjectStoreDir = (param: Object,@@ -246,17 +315,34 @@ export default class PlatformFacade {): Promise<Array<any>> =>platformListObjectStoreDir(param, mode, ignorePatterns);- static getPropertiesPromise = (path: string): Promise<any> =>- platformGetPropertiesPromise(path);+ static getPropertiesPromise = (path: string): Promise<any> => {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('getPropertiesPromise', path);+ }+ return platformGetPropertiesPromise(path);+ };- static checkDirExist = (dir: string): Promise<boolean> =>- platformCheckDirExist(dir);+ static checkDirExist = (dir: string): Promise<boolean> => {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('checkDirExist', dir);+ }+ return platformCheckDirExist(dir);+ };- static checkFileExist = (file: string): Promise<boolean> =>+ static checkFileExist = (file: string): Promise<boolean> => {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('checkFileExist', file);+ }platformCheckFileExist(file);+ };static createDirectoryPromise = (dirPath: string): Promise<any> => {- //PlatformFacade.ignoreByWatcher(dirPath);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'createDirectoryPromise',+ dirPath,+ );+ }return platformCreateDirectoryPromise(dirPath);};@@ -268,7 +354,13 @@ export default class PlatformFacade {sourceFilePath: string,targetFilePath: string,): Promise<any> => {- //PlatformFacade.ignoreByWatcher(targetFilePath);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'copyFilePromiseOverwrite',+ sourceFilePath,+ targetFilePath,+ );+ }return platformCopyFilePromise(sourceFilePath, targetFilePath);};@@ -277,7 +369,14 @@ export default class PlatformFacade {newFilePath: string,onProgress = undefined,): Promise<any> => {- //PlatformFacade.ignoreByWatcher(filePath, newFilePath);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'renameFilePromise',+ filePath,+ newFilePath,+ onProgress,+ );+ }return platformRenameFilePromise(filePath, newFilePath, onProgress);};@@ -285,7 +384,13 @@ export default class PlatformFacade {dirPath: string,newDirName: string,): Promise<any> => {- // PlatformFacade.ignoreByWatcher(dirPath, newDirName);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'renameDirectoryPromise',+ dirPath,+ newDirName,+ );+ }return platformRenameDirectoryPromise(dirPath, newDirName);};@@ -294,7 +399,14 @@ export default class PlatformFacade {newDirPath: string,onProgress = undefined,): Promise<any> => {- //PlatformFacade.ignoreByWatcher(param.path, newDirPath);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'copyDirectoryPromise',+ param,+ newDirPath,+ onProgress,+ );+ }return platformCopyDirectoryPromise(param, newDirPath, onProgress);};@@ -303,7 +415,14 @@ export default class PlatformFacade {newDirPath: string,onProgress = undefined,): Promise<any> => {- //PlatformFacade.ignoreByWatcher(param.path, newDirPath);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'moveDirectoryPromise',+ param,+ newDirPath,+ onProgress,+ );+ }return platformMoveDirectoryPromise(param, newDirPath, onProgress);};@@ -315,25 +434,54 @@ export default class PlatformFacade {try {path = decodeURIComponent(filePath);} catch (ex) {}+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'loadTextFilePromise',+ path,+ isPreview,+ );+ }return platformLoadTextFilePromise(path, isPreview);};static getFileContentPromise = (filePath: string,type?: string,- ): Promise<any> => platformGetFileContentPromise(filePath, type);+ ): Promise<any> => {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'getFileContentPromise',+ filePath,+ type,+ );+ }+ return platformGetFileContentPromise(filePath, type);+ };static getLocalFileContentPromise = (filePath: string,type?: string,- ): Promise<any> => platformGetLocalFileContentPromise(filePath, type);+ ): Promise<any> => {+ return window.electronIO.ipcRenderer.invoke(+ 'getLocalFileContentPromise',+ filePath,+ type,+ );+ };static saveFilePromise = (param: any,content: any,overwrite: boolean,): Promise<any> => {- //PlatformFacade.ignoreByWatcher(param.path);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'saveFilePromise',+ param,+ content,+ overwrite,+ );+ }return platformSaveFilePromise(param, content, overwrite);};@@ -342,7 +490,14 @@ export default class PlatformFacade {content: string,overwrite: boolean,): Promise<any> => {- //PlatformFacade.ignoreByWatcher(param.path);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'saveTextFilePromise',+ param,+ content,+ overwrite,+ );+ }return platformSaveTextFilePromise(param, content, overwrite);};@@ -355,7 +510,15 @@ export default class PlatformFacade {response: any, // AWS.Response<AWS.S3.PutObjectOutput, AWS.AWSError>) => void,): Promise<TS.FileSystemEntry> => {- //PlatformFacade.ignoreByWatcher(param.path);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'saveBinaryFilePromise',+ param,+ content,+ overwrite,+ onUploadProgress,+ );+ }return platformSaveBinaryFilePromise(param,@@ -369,23 +532,37 @@ export default class PlatformFacade {path: string,useTrash?: boolean,): Promise<any> => {- //PlatformFacade.ignoreByWatcher(path);- return platformDeleteFilePromise(path, useTrash);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'deleteFilePromise',+ path,+ useTrash,+ );+ }+ return platformDeleteFilePromise(path);};static deleteDirectoryPromise = (path: string,useTrash?: boolean,): Promise<any> => {- //PlatformFacade.ignoreByWatcher(path);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'deleteDirectoryPromise',+ path,+ useTrash,+ );+ }return platformDeleteDirectoryPromise(path, useTrash);};- static openDirectory = (dirPath: string): void =>- platformOpenDirectory(dirPath);-- static showInFileManager = (dirPath: string): void =>- platformShowInFileManager(dirPath);+ static openDirectory = (dirPath: string): void => {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('openDirectory', dirPath);+ } else {+ console.error('Is supported only in Electron');+ }+ };static openFile = (filePath: string,@@ -400,7 +577,11 @@ export default class PlatformFacade {'"? Execution of some files can be potentially dangerous!',)) {- platformOpenFile(filePath);+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('openFile', filePath);+ } else {+ console.error('Is supported only in Electron');+ }}};@@ -408,50 +589,91 @@ export default class PlatformFacade {static resolveFilePath = (filePath: string): string =>platformResolveFilePath(filePath);*/- static openUrl = (url: string): void => platformOpenUrl(url);-- static selectFileDialog = (): Promise<any> => platformSelectFileDialog();+ static openUrl = (url: string): void => {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('openUrl', url);+ } else {+ console.error('Is supported only in Electron');+ }+ };- static selectDirectoryDialog = (): Promise<any> =>- platformSelectDirectoryDialog();+ static selectDirectoryDialog = (): Promise<any> => {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('selectDirectoryDialog');+ }+ return platformSelectDirectoryDialog();+ };+ /**+ * cordova only+ * @param files+ */static shareFiles = (files: Array<string>): void => {platformShareFiles(files);};static createIndex(param: any,- mode: string[],- ignorePatterns: Array<string>,listDirectoryPromise,loadTextFilePromise,+ mode: string[],+ ignorePatterns: Array<string>,) {return platformCreateIndex(param,- mode,- ignorePatterns,listDirectoryPromise,loadTextFilePromise,+ mode,+ ignorePatterns,);}+ /**+ * Load extensions is supported only on Electron+ */static loadExtensions() {- return platformLoadExtensions();+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('load-extensions');+ }}static removeExtension(extensionId: string) {- return platformRemoveExtension(extensionId);+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('removeExtension', extensionId);+ } else {+ console.error('remove extensions is supported only on Electron.');+ }}static getUserDataDir(): Promise<string> {- return platformGetUserDataDir();+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('getUserDataDir');+ } else {+ return Promise.reject('getUserDataDir is supported only on Electron.');+ }}static unZip(filePath, targetPath): Promise<string> {- return platformUnZip(filePath, targetPath);+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'unZip',+ filePath,+ targetPath,+ );+ } else {+ console.log('UnZip is supported only on Electron.');+ }}- static getDirProperties(filePath): Promise<TS.DirProp> {- return platformDirProperties(filePath);+ static getDirProperties(path): Promise<TS.DirProp> {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('getDirProperties', path);+ } else {+ return Promise.reject(+ new Error(+ 'platformDirProperties is supported on Electron local storage.',+ ),+ );+ }}}diff --git a/src/renderer/services/utils-io.ts b/src/renderer/services/utils-io.tsindex 83cbd8fc3..ec0c52ccf 100644--- a/src/renderer/services/utils-io.ts+++ b/src/renderer/services/utils-io.ts@@ -533,10 +533,10 @@ export function createDirectoryIndex(}return PlatformIO.createIndex(param,- mode,- ignorePatterns,listDirectoryPromise,loadTextFilePromise,+ mode,+ ignorePatterns,).then((directoryIndex) =>persistIndex(param, directoryIndex).then((success) => {