TagSpaces is an offline, open source, document manager with tagging support
Change location type to contains io api object (#2086)
Stanimir2c847c811ae1
diff --git a/package-lock.json b/package-lock.jsonindex d732306bb..69a6231cd 100644--- a/package-lock.json+++ b/package-lock.json@@ -19,10 +19,10 @@"@mui/lab": "5.0.0-alpha.160","@mui/material": "^5.15.4","@mui/x-date-pickers": "^5.0.20",- "@tagspaces/tagspaces-common": "4.2.4",- "@tagspaces/tagspaces-common-aws": "4.2.4",- "@tagspaces/tagspaces-common-cordova": "4.2.4",- "@tagspaces/tagspaces-indexer": "4.2.4",+ "@tagspaces/tagspaces-common": "4.3.3",+ "@tagspaces/tagspaces-common-aws3": "4.3.3",+ "@tagspaces/tagspaces-common-cordova": "4.3.3",+ "@tagspaces/tagspaces-indexer": "4.3.3","@tagspaces/tagspaces-md": "4.1.14","aws-amplify": "^4.3.8","aws-sdk": "^2.1036.0",@@ -197,7 +197,7 @@"yarn": "please-use-npm"},"optionalDependencies": {- "@tagspacespro/tagspacespro": "5.0.31"+ "@tagspacespro/tagspacespro": "5.0.33"}},"node_modules/@aashutoshrathi/word-wrap": {@@ -13449,96 +13449,30 @@}},"node_modules/@tagspaces/tagspaces-common": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common/-/tagspaces-common-4.2.4.tgz",- "integrity": "sha512-fTjAMECkLfrNXECZTWmA3AV+Ay7/v8bdRD5nGgT73hYgkfO2JL156wZO6l2Feq33zCShQ9VrmeRHZLQxBc0yCw==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common/-/tagspaces-common-4.3.3.tgz",+ "integrity": "sha512-9z1LWcTY9OuyTC3OqQLgfwttMJP6qbqwDYsnyRH8faBWhoVjK+Km5cK1c8WfMBRAACkokww/LGnOZl32ayyA2g==","dependencies": {"dotenv": "^16.0.2","picomatch": "^3.0.1","uuid": "^8.3.2"}},- "node_modules/@tagspaces/tagspaces-common-aws": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-aws/-/tagspaces-common-aws-4.2.4.tgz",- "integrity": "sha512-MFgbtI1C4tO5/E7dZgbxdZqJ6jHsV4C5MjrW9p+/XffuC8u0Wk4Iv1RH90zPZy0I9HEVxfJPqTHhfvmJtQYkhw==",- "dependencies": {- "@tagspaces/tagspaces-common": "^4.2.4",- "aws-sdk": "2.1161.0"- }- },- "node_modules/@tagspaces/tagspaces-common-aws/node_modules/aws-sdk": {- "version": "2.1161.0",- "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.1161.0.tgz",- "integrity": "sha512-qpOtPovj3xJhdTFBkJgqmSuy5rc7vDu2HtM+S3sLiP8Uhkb3Pn3z7LtTZt5YUnY2lV1DDR9H1aWuRlRDK96k1w==",- "dependencies": {- "buffer": "4.9.2",- "events": "1.1.1",- "ieee754": "1.1.13",- "jmespath": "0.16.0",- "querystring": "0.2.0",- "sax": "1.2.1",- "url": "0.10.3",- "uuid": "8.0.0",- "xml2js": "0.4.19"- },- "engines": {- "node": ">= 10.0.0"- }- },- "node_modules/@tagspaces/tagspaces-common-aws/node_modules/events": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz",- "integrity": "sha512-kEcvvCBByWXGnZy6JUlgAp2gBIUjfCAV6P6TgT1/aaQKcmuAEC4OZTV1I4EWQLz2gxZw76atuVyvHhTxvi0Flw==",- "engines": {- "node": ">=0.4.x"- }- },- "node_modules/@tagspaces/tagspaces-common-aws/node_modules/punycode": {- "version": "1.3.2",- "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz",- "integrity": "sha512-RofWgt/7fL5wP1Y7fxE7/EmTLzQVnB0ycyibJ0OOHIlJqTNzglYFxVwETOcIoJqJmpDXJ9xImDv+Fq34F/d4Dw=="- },- "node_modules/@tagspaces/tagspaces-common-aws/node_modules/url": {- "version": "0.10.3",- "resolved": "https://registry.npmjs.org/url/-/url-0.10.3.tgz",- "integrity": "sha512-hzSUW2q06EqL1gKM/a+obYHLIO6ct2hwPuviqTTOcfFVc61UbfJ2Q32+uGL/HCPxKqrdGB5QUwIe7UqlDgwsOQ==",- "dependencies": {- "punycode": "1.3.2",- "querystring": "0.2.0"- }- },- "node_modules/@tagspaces/tagspaces-common-aws/node_modules/uuid": {- "version": "8.0.0",- "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.0.0.tgz",- "integrity": "sha512-jOXGuXZAWdsTH7eZLtyXMqUb9EcWMGZNbL9YcGBJl4MH4nrxHmZJhEHvyLFrkxo+28uLb/NYRcStH48fnD0Vzw==",- "bin": {- "uuid": "dist/bin/uuid"- }- },- "node_modules/@tagspaces/tagspaces-common-aws/node_modules/xml2js": {- "version": "0.4.19",- "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz",- "integrity": "sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q==",+ "node_modules/@tagspaces/tagspaces-common-aws3": {+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-aws3/-/tagspaces-common-aws3-4.3.3.tgz",+ "integrity": "sha512-0GUngRH9S304vcTkJaz3fLbLyxmwHdfyH7wRnDdPFpuA1D9b03///e7j6iOIeOE7NsdU0WGmg2/8F9HYesMQqg==","dependencies": {- "sax": ">=0.6.0",- "xmlbuilder": "~9.0.1"- }- },- "node_modules/@tagspaces/tagspaces-common-aws/node_modules/xmlbuilder": {- "version": "9.0.7",- "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz",- "integrity": "sha512-7YXTQc3P2l9+0rjaUbLwMKRhtmwg1M1eDf6nag7urC7pIPYLD9W/jmzQ4ptRSUbodw5S0jfoGTflLemQibSpeQ==",- "engines": {- "node": ">=4.0"+ "@tagspaces/tagspaces-common": "^4.3.3",+ "aws-sdk": "2.1605.0"}},"node_modules/@tagspaces/tagspaces-common-cordova": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-cordova/-/tagspaces-common-cordova-4.2.4.tgz",- "integrity": "sha512-zNidqDugqxCW915ukZBOO2gDtxp9E2HEUeXAXW1p8kLushE4GYpDXlTss4jm797fR4sS9Tji/m3C/olZx3Z2gw==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-cordova/-/tagspaces-common-cordova-4.3.3.tgz",+ "integrity": "sha512-p+aGuZkgdbEbHtlGHsGy2v5CsL7izr0ku+35+7RLqPt5TO8eT6A/C57UgBLc+ZOT/0rjYXEXSYEts07MgJc4/Q==","dependencies": {- "@tagspaces/tagspaces-common": "^4.2.4"+ "@tagspaces/tagspaces-common": "^4.3.3"}},"node_modules/@tagspaces/tagspaces-common/node_modules/uuid": {@@ -13550,11 +13484,11 @@}},"node_modules/@tagspaces/tagspaces-indexer": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-indexer/-/tagspaces-indexer-4.2.4.tgz",- "integrity": "sha512-fkBRN9tYnFCbFzw8/gpx9j9Y+UdoOXjX65FdU54jJyLyy/wMOpLwjr1FyzuYCB2i1N7p/lxmpymIa4HXurk0zA==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-indexer/-/tagspaces-indexer-4.3.3.tgz",+ "integrity": "sha512-IGUt8dlhuKWkz9fbGFqEnzJYMqiMwBARkn2BH3DXesK83Hah+GOO2pLnYok1SzHzoX+Tz58rgLOVwD2TLsUwuA==","dependencies": {- "@tagspaces/tagspaces-common": "^4.2.4"+ "@tagspaces/tagspaces-common": "^4.3.3"}},"node_modules/@tagspaces/tagspaces-md": {@@ -13596,9 +13530,9 @@}},"node_modules/@tagspacespro/tagspacespro": {- "version": "5.0.31",- "resolved": "https://npm.pkg.github.com/download/@tagspacespro/tagspacespro/5.0.31/59eb00bc53e3af2384a5559b5fe6741b01a27a93",- "integrity": "sha512-E33+UpPwsQEjznH8xsVuvOauQB6W/YKR8HNM9xQIFl86wIsmz+BrI8jDHGLwagPI/4HgzE8BNlPN8NPvEAq7Aw==",+ "version": "5.0.33",+ "resolved": "https://npm.pkg.github.com/download/@tagspacespro/tagspacespro/5.0.33/bd28bd4106917b4cd37039960bb33eac8fe4d6ca",+ "integrity": "sha512-/WupbWWAzZvZwu/zk0xDORTsaBcNqfRDouHx8RkDmNh07VGxWIfzeisW33t7aW70LEhQ+YlxIPIULhWN2kpkjA==","license": "Proprietary","optional": true},@@ -16125,9 +16059,10 @@}},"node_modules/aws-sdk": {- "version": "2.1560.0",- "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.1560.0.tgz",- "integrity": "sha512-nakTZHytnhKWZpwu9d1crqjoegBRG+j1/rflsVnckXxoIwlKM0D/v/NIe+BJmRnCA2aCdwuMx3dtkgLz/AB6VA==",+ "version": "2.1605.0",+ "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.1605.0.tgz",+ "integrity": "sha512-/wtOuF7WgkbN6YL3xJ+FB54kvIAfnP/DQVDaE6rSYv6ft0xr01Si94NgQWhb5OcFkFfRAC4auZX8PiFNtOi9xQ==",+ "hasInstallScript": true,"dependencies": {"buffer": "4.9.2","events": "1.1.1",@@ -59107,9 +59042,9 @@}},"@tagspaces/tagspaces-common": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common/-/tagspaces-common-4.2.4.tgz",- "integrity": "sha512-fTjAMECkLfrNXECZTWmA3AV+Ay7/v8bdRD5nGgT73hYgkfO2JL156wZO6l2Feq33zCShQ9VrmeRHZLQxBc0yCw==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common/-/tagspaces-common-4.3.3.tgz",+ "integrity": "sha512-9z1LWcTY9OuyTC3OqQLgfwttMJP6qbqwDYsnyRH8faBWhoVjK+Km5cK1c8WfMBRAACkokww/LGnOZl32ayyA2g==","requires": {"dotenv": "^16.0.2","picomatch": "^3.0.1",@@ -59123,85 +59058,29 @@}}},- "@tagspaces/tagspaces-common-aws": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-aws/-/tagspaces-common-aws-4.2.4.tgz",- "integrity": "sha512-MFgbtI1C4tO5/E7dZgbxdZqJ6jHsV4C5MjrW9p+/XffuC8u0Wk4Iv1RH90zPZy0I9HEVxfJPqTHhfvmJtQYkhw==",+ "@tagspaces/tagspaces-common-aws3": {+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-aws3/-/tagspaces-common-aws3-4.3.3.tgz",+ "integrity": "sha512-0GUngRH9S304vcTkJaz3fLbLyxmwHdfyH7wRnDdPFpuA1D9b03///e7j6iOIeOE7NsdU0WGmg2/8F9HYesMQqg==","requires": {- "@tagspaces/tagspaces-common": "^4.2.4",- "aws-sdk": "2.1161.0"- },- "dependencies": {- "aws-sdk": {- "version": "2.1161.0",- "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.1161.0.tgz",- "integrity": "sha512-qpOtPovj3xJhdTFBkJgqmSuy5rc7vDu2HtM+S3sLiP8Uhkb3Pn3z7LtTZt5YUnY2lV1DDR9H1aWuRlRDK96k1w==",- "requires": {- "buffer": "4.9.2",- "events": "1.1.1",- "ieee754": "1.1.13",- "jmespath": "0.16.0",- "querystring": "0.2.0",- "sax": "1.2.1",- "url": "0.10.3",- "uuid": "8.0.0",- "xml2js": "0.4.19"- }- },- "events": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz",- "integrity": "sha512-kEcvvCBByWXGnZy6JUlgAp2gBIUjfCAV6P6TgT1/aaQKcmuAEC4OZTV1I4EWQLz2gxZw76atuVyvHhTxvi0Flw=="- },- "punycode": {- "version": "1.3.2",- "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz",- "integrity": "sha512-RofWgt/7fL5wP1Y7fxE7/EmTLzQVnB0ycyibJ0OOHIlJqTNzglYFxVwETOcIoJqJmpDXJ9xImDv+Fq34F/d4Dw=="- },- "url": {- "version": "0.10.3",- "resolved": "https://registry.npmjs.org/url/-/url-0.10.3.tgz",- "integrity": "sha512-hzSUW2q06EqL1gKM/a+obYHLIO6ct2hwPuviqTTOcfFVc61UbfJ2Q32+uGL/HCPxKqrdGB5QUwIe7UqlDgwsOQ==",- "requires": {- "punycode": "1.3.2",- "querystring": "0.2.0"- }- },- "uuid": {- "version": "8.0.0",- "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.0.0.tgz",- "integrity": "sha512-jOXGuXZAWdsTH7eZLtyXMqUb9EcWMGZNbL9YcGBJl4MH4nrxHmZJhEHvyLFrkxo+28uLb/NYRcStH48fnD0Vzw=="- },- "xml2js": {- "version": "0.4.19",- "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz",- "integrity": "sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q==",- "requires": {- "sax": ">=0.6.0",- "xmlbuilder": "~9.0.1"- }- },- "xmlbuilder": {- "version": "9.0.7",- "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz",- "integrity": "sha512-7YXTQc3P2l9+0rjaUbLwMKRhtmwg1M1eDf6nag7urC7pIPYLD9W/jmzQ4ptRSUbodw5S0jfoGTflLemQibSpeQ=="- }+ "@tagspaces/tagspaces-common": "^4.3.3",+ "aws-sdk": "2.1605.0"}},"@tagspaces/tagspaces-common-cordova": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-cordova/-/tagspaces-common-cordova-4.2.4.tgz",- "integrity": "sha512-zNidqDugqxCW915ukZBOO2gDtxp9E2HEUeXAXW1p8kLushE4GYpDXlTss4jm797fR4sS9Tji/m3C/olZx3Z2gw==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-cordova/-/tagspaces-common-cordova-4.3.3.tgz",+ "integrity": "sha512-p+aGuZkgdbEbHtlGHsGy2v5CsL7izr0ku+35+7RLqPt5TO8eT6A/C57UgBLc+ZOT/0rjYXEXSYEts07MgJc4/Q==","requires": {- "@tagspaces/tagspaces-common": "^4.2.4"+ "@tagspaces/tagspaces-common": "^4.3.3"}},"@tagspaces/tagspaces-indexer": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-indexer/-/tagspaces-indexer-4.2.4.tgz",- "integrity": "sha512-fkBRN9tYnFCbFzw8/gpx9j9Y+UdoOXjX65FdU54jJyLyy/wMOpLwjr1FyzuYCB2i1N7p/lxmpymIa4HXurk0zA==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-indexer/-/tagspaces-indexer-4.3.3.tgz",+ "integrity": "sha512-IGUt8dlhuKWkz9fbGFqEnzJYMqiMwBARkn2BH3DXesK83Hah+GOO2pLnYok1SzHzoX+Tz58rgLOVwD2TLsUwuA==","requires": {- "@tagspaces/tagspaces-common": "^4.2.4"+ "@tagspaces/tagspaces-common": "^4.3.3"}},"@tagspaces/tagspaces-md": {@@ -59235,9 +59114,9 @@}},"@tagspacespro/tagspacespro": {- "version": "5.0.31",- "resolved": "https://npm.pkg.github.com/download/@tagspacespro/tagspacespro/5.0.31/59eb00bc53e3af2384a5559b5fe6741b01a27a93",- "integrity": "sha512-E33+UpPwsQEjznH8xsVuvOauQB6W/YKR8HNM9xQIFl86wIsmz+BrI8jDHGLwagPI/4HgzE8BNlPN8NPvEAq7Aw==",+ "version": "5.0.33",+ "resolved": "https://npm.pkg.github.com/download/@tagspacespro/tagspacespro/5.0.33/bd28bd4106917b4cd37039960bb33eac8fe4d6ca",+ "integrity": "sha512-/WupbWWAzZvZwu/zk0xDORTsaBcNqfRDouHx8RkDmNh07VGxWIfzeisW33t7aW70LEhQ+YlxIPIULhWN2kpkjA==","optional": true},"@teamsupercell/typings-for-css-modules-loader": {@@ -61280,9 +61159,9 @@}},"aws-sdk": {- "version": "2.1560.0",- "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.1560.0.tgz",- "integrity": "sha512-nakTZHytnhKWZpwu9d1crqjoegBRG+j1/rflsVnckXxoIwlKM0D/v/NIe+BJmRnCA2aCdwuMx3dtkgLz/AB6VA==",+ "version": "2.1605.0",+ "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.1605.0.tgz",+ "integrity": "sha512-/wtOuF7WgkbN6YL3xJ+FB54kvIAfnP/DQVDaE6rSYv6ft0xr01Si94NgQWhb5OcFkFfRAC4auZX8PiFNtOi9xQ==","requires": {"buffer": "4.9.2","events": "1.1.1",diff --git a/package.json b/package.jsonindex 0503ebe99..fc42fb888 100644--- a/package.json+++ b/package.json@@ -159,10 +159,10 @@"@mui/lab": "5.0.0-alpha.160","@mui/material": "^5.15.4","@mui/x-date-pickers": "^5.0.20",- "@tagspaces/tagspaces-common": "4.2.4",- "@tagspaces/tagspaces-common-aws": "4.2.4",- "@tagspaces/tagspaces-common-cordova": "4.2.4",- "@tagspaces/tagspaces-indexer": "4.2.4",+ "@tagspaces/tagspaces-common": "4.3.3",+ "@tagspaces/tagspaces-common-aws3": "4.3.3",+ "@tagspaces/tagspaces-common-cordova": "4.3.3",+ "@tagspaces/tagspaces-indexer": "4.3.3","@tagspaces/tagspaces-md": "4.1.14","aws-amplify": "^4.3.8","aws-sdk": "^2.1036.0",@@ -228,7 +228,7 @@"uuid": "^9.0.0"},"optionalDependencies": {- "@tagspacespro/tagspacespro": "5.0.31"+ "@tagspacespro/tagspacespro": "5.0.33"},"devDependencies": {"@electron/notarize": "^2.2.0",diff --git a/release/app/package-lock.json b/release/app/package-lock.jsonindex bb8600d1d..c5cf994f1 100644--- a/release/app/package-lock.json+++ b/release/app/package-lock.json@@ -1,19 +1,19 @@{"name": "tagspaces",- "version": "5.8.1",+ "version": "5.8.2","lockfileVersion": 2,"requires": true,"packages": {"": {"name": "tagspaces",- "version": "5.8.1",+ "version": "5.8.2","hasInstallScript": true,"license": "AGPL-3.0","dependencies": {"@elife/pm2": "3.6.1","@tagspaces/extensions": "1.0.104",- "@tagspaces/tagspaces-common-node": "4.2.4",- "@tagspaces/tagspaces-ws": "4.2.4",+ "@tagspaces/tagspaces-common-node": "4.3.3",+ "@tagspaces/tagspaces-ws": "4.3.3","sharp": "0.32.6","ws": "8.16.0"},@@ -43,9 +43,9 @@}},"node_modules/@tagspaces/tagspaces-common": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common/-/tagspaces-common-4.2.4.tgz",- "integrity": "sha512-fTjAMECkLfrNXECZTWmA3AV+Ay7/v8bdRD5nGgT73hYgkfO2JL156wZO6l2Feq33zCShQ9VrmeRHZLQxBc0yCw==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common/-/tagspaces-common-4.3.3.tgz",+ "integrity": "sha512-9z1LWcTY9OuyTC3OqQLgfwttMJP6qbqwDYsnyRH8faBWhoVjK+Km5cK1c8WfMBRAACkokww/LGnOZl32ayyA2g==","dependencies": {"dotenv": "^16.0.2","picomatch": "^3.0.1",@@ -53,21 +53,21 @@}},"node_modules/@tagspaces/tagspaces-common-node": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-node/-/tagspaces-common-node-4.2.4.tgz",- "integrity": "sha512-XH2ntg1QrmTmPVZUV3Ucb8jxER+SOhI8Rs5nadRVyh+pNiw9SVSM9gazpF4qUE16a5bG+CLDkrjr7J/C+GbeYw==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-node/-/tagspaces-common-node-4.3.3.tgz",+ "integrity": "sha512-kquQnIfw8ae3RAlhSFkKHy4p0HNMHGekznF07bKGWV8KWOLVVVdtQKCY00LmvZITOyx8sZ/Ri+uQVxurcIsu1Q==","dependencies": {- "@tagspaces/tagspaces-common": "^4.2.4",- "adm-zip": "^0.5.10",+ "@tagspaces/tagspaces-common": "^4.3.3",+ "adm-zip": "0.5.10","fs-extra": "^10.0.0","klaw": "^4.1.0","marked": "^3.0.8"}},"node_modules/@tagspaces/tagspaces-platforms": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-4.2.4.tgz",- "integrity": "sha512-RRGi8pHLCzHIRt0yPsPVqT93x52Rshq7MCKdKY4Xu1oT5DRXOECx5p0Dtky7APraXVLOqufW5AFq0RufrnwQXA==",+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-4.3.2.tgz",+ "integrity": "sha512-dYgUKte4nliQexDX9HlSV4mb7p5B2EhsLFeuTn9HRSiErPeaTqScxEyl+Yg7fmStJYSFzI/B7oV1GLyMvMiRxQ==","hasInstallScript": true},"node_modules/@tagspaces/tagspaces-thumbgen-image": {@@ -80,22 +80,22 @@}},"node_modules/@tagspaces/tagspaces-workers": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-workers/-/tagspaces-workers-4.2.4.tgz",- "integrity": "sha512-rcHsFNyOfHN4cuds45XMndQhXx6ZHc6SwuLm9voZ9j25nRe26wzgTPimQaTE2XYcUp65rpy765B5TRO8N1rvzA==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-workers/-/tagspaces-workers-4.3.3.tgz",+ "integrity": "sha512-ykvXDFZ30nCl9K63Ey5XVukXqhwTWGkRErFJHsCkeI/N/voL1vIW0Wcomh8SNy/kbHFAjYobHCJu7z+hU84mUA==","dependencies": {- "@tagspaces/tagspaces-common": "^4.2.4",- "@tagspaces/tagspaces-common-node": "^4.2.4",- "@tagspaces/tagspaces-platforms": "^4.2.4",+ "@tagspaces/tagspaces-common": "^4.3.3",+ "@tagspaces/tagspaces-common-node": "^4.3.3",+ "@tagspaces/tagspaces-platforms": "^4.3.2","@tagspaces/tagspaces-thumbgen-image": "^4.2.3"}},"node_modules/@tagspaces/tagspaces-ws": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-ws/-/tagspaces-ws-4.2.4.tgz",- "integrity": "sha512-HmJILTzaswqTUPXxdn3x7vVEqf8ZC6BeqedbPJ0nCSIzt5bvAesHuI9tBOwxpd1+DuhuREvDPzPKEDhWhiOyVQ==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-ws/-/tagspaces-ws-4.3.3.tgz",+ "integrity": "sha512-8TD6SA86h9No9Kj/hhwVYmNZDvCrPblgP+1nqoQaHP8Qvm1iojmSHlLGkPWsblHzc1Hr+G0NB0KjKs7TzUpvBw==","dependencies": {- "@tagspaces/tagspaces-workers": "^4.2.4",+ "@tagspaces/tagspaces-workers": "^4.3.3","find-free-ports": "^3.1.1","jsonwebtoken": "^8.5.1","ws": "^8.15.1"@@ -1102,9 +1102,9 @@}},"@tagspaces/tagspaces-common": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common/-/tagspaces-common-4.2.4.tgz",- "integrity": "sha512-fTjAMECkLfrNXECZTWmA3AV+Ay7/v8bdRD5nGgT73hYgkfO2JL156wZO6l2Feq33zCShQ9VrmeRHZLQxBc0yCw==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common/-/tagspaces-common-4.3.3.tgz",+ "integrity": "sha512-9z1LWcTY9OuyTC3OqQLgfwttMJP6qbqwDYsnyRH8faBWhoVjK+Km5cK1c8WfMBRAACkokww/LGnOZl32ayyA2g==","requires": {"dotenv": "^16.0.2","picomatch": "^3.0.1",@@ -1112,21 +1112,21 @@}},"@tagspaces/tagspaces-common-node": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-node/-/tagspaces-common-node-4.2.4.tgz",- "integrity": "sha512-XH2ntg1QrmTmPVZUV3Ucb8jxER+SOhI8Rs5nadRVyh+pNiw9SVSM9gazpF4qUE16a5bG+CLDkrjr7J/C+GbeYw==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-common-node/-/tagspaces-common-node-4.3.3.tgz",+ "integrity": "sha512-kquQnIfw8ae3RAlhSFkKHy4p0HNMHGekznF07bKGWV8KWOLVVVdtQKCY00LmvZITOyx8sZ/Ri+uQVxurcIsu1Q==","requires": {- "@tagspaces/tagspaces-common": "^4.2.4",- "adm-zip": "^0.5.10",+ "@tagspaces/tagspaces-common": "^4.3.3",+ "adm-zip": "0.5.10","fs-extra": "^10.0.0","klaw": "^4.1.0","marked": "^3.0.8"}},"@tagspaces/tagspaces-platforms": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-4.2.4.tgz",- "integrity": "sha512-RRGi8pHLCzHIRt0yPsPVqT93x52Rshq7MCKdKY4Xu1oT5DRXOECx5p0Dtky7APraXVLOqufW5AFq0RufrnwQXA=="+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-4.3.2.tgz",+ "integrity": "sha512-dYgUKte4nliQexDX9HlSV4mb7p5B2EhsLFeuTn9HRSiErPeaTqScxEyl+Yg7fmStJYSFzI/B7oV1GLyMvMiRxQ=="},"@tagspaces/tagspaces-thumbgen-image": {"version": "4.2.3",@@ -1138,22 +1138,22 @@}},"@tagspaces/tagspaces-workers": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-workers/-/tagspaces-workers-4.2.4.tgz",- "integrity": "sha512-rcHsFNyOfHN4cuds45XMndQhXx6ZHc6SwuLm9voZ9j25nRe26wzgTPimQaTE2XYcUp65rpy765B5TRO8N1rvzA==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-workers/-/tagspaces-workers-4.3.3.tgz",+ "integrity": "sha512-ykvXDFZ30nCl9K63Ey5XVukXqhwTWGkRErFJHsCkeI/N/voL1vIW0Wcomh8SNy/kbHFAjYobHCJu7z+hU84mUA==","requires": {- "@tagspaces/tagspaces-common": "^4.2.4",- "@tagspaces/tagspaces-common-node": "^4.2.4",- "@tagspaces/tagspaces-platforms": "^4.2.4",+ "@tagspaces/tagspaces-common": "^4.3.3",+ "@tagspaces/tagspaces-common-node": "^4.3.3",+ "@tagspaces/tagspaces-platforms": "^4.3.2","@tagspaces/tagspaces-thumbgen-image": "^4.2.3"}},"@tagspaces/tagspaces-ws": {- "version": "4.2.4",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-ws/-/tagspaces-ws-4.2.4.tgz",- "integrity": "sha512-HmJILTzaswqTUPXxdn3x7vVEqf8ZC6BeqedbPJ0nCSIzt5bvAesHuI9tBOwxpd1+DuhuREvDPzPKEDhWhiOyVQ==",+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-ws/-/tagspaces-ws-4.3.3.tgz",+ "integrity": "sha512-8TD6SA86h9No9Kj/hhwVYmNZDvCrPblgP+1nqoQaHP8Qvm1iojmSHlLGkPWsblHzc1Hr+G0NB0KjKs7TzUpvBw==","requires": {- "@tagspaces/tagspaces-workers": "^4.2.4",+ "@tagspaces/tagspaces-workers": "^4.3.3","find-free-ports": "^3.1.1","jsonwebtoken": "^8.5.1","ws": "^8.15.1"diff --git a/release/app/package.json b/release/app/package.jsonindex 28faa4785..2885dc1b7 100644--- a/release/app/package.json+++ b/release/app/package.json@@ -1,7 +1,7 @@{"name": "tagspaces","productName": "TagSpaces",- "version": "5.8.1",+ "version": "5.8.2","description": "Offline file organizer and browser with tagging support.","homepage": "https://www.tagspaces.org","author": {@@ -19,8 +19,8 @@"dependencies": {"@elife/pm2": "3.6.1","@tagspaces/extensions": "1.0.104",- "@tagspaces/tagspaces-common-node": "4.2.4",- "@tagspaces/tagspaces-ws": "4.2.4",+ "@tagspaces/tagspaces-common-node": "4.3.3",+ "@tagspaces/tagspaces-ws": "4.3.3","sharp": "0.32.6","ws": "8.16.0"},diff --git a/src/renderer/components/DirectoryListView.tsx b/src/renderer/components/DirectoryListView.tsxindex 472ca177c..76512b3e4 100644--- a/src/renderer/components/DirectoryListView.tsx+++ b/src/renderer/components/DirectoryListView.tsx@@ -19,14 +19,10 @@ import {NewFolderIcon,FolderOutlineIcon as FolderIcon,} from '-/components/CommonIcons';-import { getLocations } from '-/reducers/locations';-import PlatformIO from '-/services/platform-facade';import { useTranslation } from 'react-i18next';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';-import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';-import { useFSWatcherContext } from '-/hooks/useFSWatcherContext';-import i18n from '-/services/i18n';import Typography from '@mui/material/Typography';+import { CommonLocation } from '-/utils/CommonLocation';interface Props {setTargetDir: (dirPath: string) => void;@@ -35,8 +31,9 @@ interface Props {function DirectoryListView(props: Props) {const { currentDirectoryPath, setTargetDir } = props;const { t } = useTranslation();- const { currentLocation } = useCurrentLocationContext();- const locations: Array<TS.Location> = useSelector(getLocations);+ const { currentLocation, findLocation, locations } =+ useCurrentLocationContext();+ // const locations: Array<CommonLocation> = useSelector(getLocations);const showUnixHiddenEntries: boolean = useSelector(getShowUnixHiddenEntries);const chosenLocationId = useRef<string>(currentLocation ? currentLocation.uuid : undefined,@@ -47,9 +44,7 @@ function DirectoryListView(props: Props) {>([]);useEffect(() => {- const chosenLocation = locations.find(- (location) => location.uuid === chosenLocationId.current,- );+ const chosenLocation = findLocation(chosenLocationId.current);if (chosenLocation) {const path =currentLocation &&@@ -65,9 +60,7 @@ function DirectoryListView(props: Props) {const handleLocationChange = (event: React.ChangeEvent<HTMLInputElement>) => {chosenLocationId.current = event.target.value;- const chosenLocation = locations.find(- (location) => location.uuid === chosenLocationId.current,- );+ const chosenLocation = findLocation(chosenLocationId.current);if (chosenLocation) {listDirectory(chosenLocation.path);setTargetDir(chosenLocation.path);@@ -75,9 +68,7 @@ function DirectoryListView(props: Props) {};function getDirLocations() {- const chosenLocation = locations.find(- (location) => location.uuid === chosenLocationId.current,- );+ const chosenLocation = findLocation(chosenLocationId.current);if (chosenLocation.type !== locationType.TYPE_LOCAL) {return null;}@@ -101,7 +92,7 @@ function DirectoryListView(props: Props) {>{locations.filter((loc) => loc.type === locationType.TYPE_LOCAL)- .map((location: TS.Location) => (+ .map((location: CommonLocation) => (<MenuItem key={location.uuid} value={location.uuid}><span style={{ width: '100%' }}>{location.name}</span></MenuItem>@@ -113,11 +104,12 @@ function DirectoryListView(props: Props) {function listDirectory(directoryPath) {chosenDirectory.current = directoryPath;- PlatformIO.listDirectoryPromise(- directoryPath,- [], // mode,- [],- )+ currentLocation+ .listDirectoryPromise(+ directoryPath,+ [], // mode,+ [],+ ).then((results) => {if (results !== undefined) {setDirectoryContent(@@ -175,7 +167,7 @@ function DirectoryListView(props: Props) {onClick={() => {if (chosenDirectory.current) {let currentPath = chosenDirectory.current;- if (currentPath.endsWith(PlatformIO.getDirSeparator())) {+ if (currentPath.endsWith(currentLocation?.getDirSeparator())) {currentPath = currentPath.slice(0, -1);}const parentDir = extractContainingDirectoryPath(currentPath);diff --git a/src/renderer/components/DirectoryTreeView.tsx b/src/renderer/components/DirectoryTreeView.tsxindex 311e70e2a..3d6bc0997 100644--- a/src/renderer/components/DirectoryTreeView.tsx+++ b/src/renderer/components/DirectoryTreeView.tsx@@ -23,22 +23,21 @@ import FolderIcon from '@mui/icons-material/FolderOpen';import { locationType } from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';import DragItemTypes from '-/components/DragItemTypes';-import PlatformIO from '-/services/platform-facade';import TargetTableMoveFileBox from '-/components/TargetTableMoveFileBox';-import { TS } from '-/tagspaces.namespace';import { getShowUnixHiddenEntries } from '-/reducers/settings';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { CommonLocation } from '-/utils/CommonLocation';interface Props {classes: any;- location: TS.Location;+ location: CommonLocation;//data?: any;handleFileMoveDrop: (item, monitor) => void;}export interface DirectoryTreeViewRef {- changeLocation: (location: TS.Location) => void;+ changeLocation: (location: CommonLocation) => void;closeLocation: () => void;// removeLocation: () => void;}@@ -47,7 +46,8 @@ const DirectoryTreeView = forwardRef((props: Props, ref: Ref<DirectoryTreeViewRef>) => {const { classes, location, handleFileMoveDrop } = props;const { openDirectory } = useDirectoryContentContext();- const { changeLocation, getLocationPath } = useCurrentLocationContext();+ const { findLocation, changeLocation, getLocationPath } =+ useCurrentLocationContext();const [data, setData] = useState(undefined);const [isExpanded, setExpanded] = useState(false);@@ -55,24 +55,11 @@ const DirectoryTreeView = forwardRef(//const dispatch: AppDispatch = useDispatch();useImperativeHandle(ref, () => ({- changeLocation(location: TS.Location) {+ changeLocation(location: CommonLocation) {if (isExpanded && data[location.uuid] !== undefined) {setData(undefined); // comment this to use cached data after expandsetExpanded(false);- } else if (location.type === locationType.TYPE_CLOUD) {- PlatformIO.enableObjectStoreSupport(location)- .then(() => {- loadSubDirectories(location);- })- .catch((error) => {- console.log('enableObjectStoreSupport', error);- });- } else if (location.type === locationType.TYPE_WEBDAV) {- PlatformIO.enableWebdavSupport(location);- loadSubDirectories(location);- } else if (location.type === locationType.TYPE_LOCAL) {- PlatformIO.disableObjectStoreSupport();- PlatformIO.disableWebdavSupport();+ } else {loadSubDirectories(location);}},@@ -140,21 +127,11 @@ const DirectoryTreeView = forwardRef(};const onRowClick = (subDir) => {- if (subDir.type === locationType.TYPE_CLOUD) {- PlatformIO.enableObjectStoreSupport(subDir)- .then(() => {- loadSubDirectories(subDir);- changeLocation(subDir);- return openDirectory(subDir.path, subDir.uuid);- })- .catch((error) => {- console.log('enableObjectStoreSupport', error);- });- } else if (subDir.type === locationType.TYPE_LOCAL) {- PlatformIO.disableObjectStoreSupport();- loadSubDirectories(subDir);- changeLocation(subDir);- openDirectory(subDir.path, subDir.uuid);+ const location = findLocation(subDir.uuid);+ if (location) {+ //loadSubDirectories(location);+ changeLocation(location, true);+ openDirectory(subDir.path, undefined, location);}};@@ -169,7 +146,7 @@ const DirectoryTreeView = forwardRef(},];- const loadSubDirectories = (location: TS.Location) => {+ const loadSubDirectories = (location: CommonLocation) => {getLocationPath(location).then((locationPath) => {const subFolder = {...(location.accessKeyId && { accessKeyId: location.accessKeyId }),@@ -233,7 +210,8 @@ const DirectoryTreeView = forwardRef(const getDirectoriesTree = (subFolder: SubFolder) =>// const { settings } = getState();new Promise((resolve, reject) => {- PlatformIO.listDirectoryPromise(subFolder.path, [])+ findLocation(subFolder.uuid)+ .listDirectoryPromise(subFolder.path, []).then((dirEntries) => {if (dirEntries !== undefined) {// console.debug('listDirectoryPromise resolved:' + dirEntries.length);diff --git a/src/renderer/components/EntryContainer.tsx b/src/renderer/components/EntryContainer.tsxindex 0020e3317..fcf312e8d 100644--- a/src/renderer/components/EntryContainer.tsx+++ b/src/renderer/components/EntryContainer.tsx@@ -42,7 +42,6 @@ import {generateSharingLink,} from '@tagspaces/tagspaces-common/paths';import ConfirmDialog from '-/components/dialogs/ConfirmDialog';-import PlatformIO from '-/services/platform-facade';import AddRemoveTagsDialog from '-/components/dialogs/AddRemoveTagsDialog';import {isDesktopMode,@@ -66,7 +65,7 @@ import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useNotificationContext } from '-/hooks/useNotificationContext';-import { getRelativeEntryPath, toFsEntry } from '-/services/utils-io';+import { getRelativeEntryPath } from '-/services/utils-io';import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';import { SaveIcon, EditIcon } from '-/components/CommonIcons';import { useIOActionsContext } from '-/hooks/useIOActionsContext';@@ -87,8 +86,7 @@ function EntryContainer() {} = useOpenedEntryContext();const { saveDescription, description } = useDescriptionContext();const { setAutoSave, getMetadataID } = useIOActionsContext();- const { readOnlyMode, switchLocationTypeByID, switchCurrentLocationType } =- useCurrentLocationContext();+ const { findLocation } = useCurrentLocationContext();const { openDirectory, currentDirectoryPath, currentLocationPath } =useDirectoryContentContext();const { copyFilePromiseOverwrite, copyFilePromise, saveTextFilePromise } =@@ -136,6 +134,7 @@ function EntryContainer() {useRef<HTMLDivElement>(null);const fileChanged = useRef<boolean>(false);const eventID = useRef<string>(getUuid());+ const cLocation = findLocation(openedEntry.locationID);useEventListener('message', (e) => {if (typeof e.data === 'string') {@@ -274,7 +273,8 @@ function EntryContainer() {: true;*/const editingSupported: boolean =- !readOnlyMode &&+ cLocation &&+ !cLocation.isReadOnly &&openedEntry &&openedEntry.editingExtensionId !== undefined &&openedEntry.editingExtensionId.length > 3;@@ -326,53 +326,51 @@ function EntryContainer() {// if (!this.state.currentEntry.isFile) {// textFilePath += '/index.html';// }- switchLocationTypeByID(openedEntry.locationId).then(() => {- PlatformIO.loadTextFilePromise(+ cLocation+ .loadTextFilePromise(textFilePath,data.preview ? data.preview : false,)- .then((content) => {- const UTF8_BOM = '\ufeff';- if (content.indexOf(UTF8_BOM) === 0) {- // eslint-disable-next-line no-param-reassign- content = content.substr(1);- }- let fileDirectory = extractContainingDirectoryPath(- textFilePath,- PlatformIO.getDirSeparator(),+ .then((content) => {+ const UTF8_BOM = '\ufeff';+ if (content.indexOf(UTF8_BOM) === 0) {+ // eslint-disable-next-line no-param-reassign+ content = content.substr(1);+ }+ let fileDirectory = extractContainingDirectoryPath(+ textFilePath,+ cLocation?.getDirSeparator(),+ );+ if (AppConfig.isWeb) {+ fileDirectory =+ extractContainingDirectoryPath(+ // eslint-disable-next-line no-restricted-globals+ location.href,+ cLocation?.getDirSeparator(),+ ) ++ '/' ++ fileDirectory;+ }+ if (+ fileViewer &&+ fileViewer.current &&+ fileViewer.current.contentWindow &&+ // @ts-ignore+ fileViewer.current.contentWindow.setContent+ ) {+ // @ts-ignore call setContent from iframe+ fileViewer.current.contentWindow.setContent(+ content,+ fileDirectory,+ !openedEntry.editMode,+ theme.palette.mode,);- if (AppConfig.isWeb) {- fileDirectory =- extractContainingDirectoryPath(- // eslint-disable-next-line no-restricted-globals- location.href,- PlatformIO.getDirSeparator(),- ) +- '/' +- fileDirectory;- }- if (- fileViewer &&- fileViewer.current &&- fileViewer.current.contentWindow &&- // @ts-ignore- fileViewer.current.contentWindow.setContent- ) {- // @ts-ignore call setContent from iframe- fileViewer.current.contentWindow.setContent(- content,- fileDirectory,- !openedEntry.editMode,- theme.palette.mode,- );- }- return switchCurrentLocationType();- })- .catch((err) => {- console.warn('Error loading text content ' + err);- return switchCurrentLocationType();- });- });+ }+ return true;+ })+ .catch((err) => {+ console.log('Error loading text content ' + err);+ });break;case 'contentChangedInEditor': {if (!fileChanged.current) {@@ -396,9 +394,7 @@ function EntryContainer() {// openedEntry.changed) {setSaveBeforeReloadConfirmDialogOpened(true);} else {- return switchLocationTypeByID(openedEntry.locationId).then(() =>- reloadOpenedFile().then(() => switchCurrentLocationType()),- );+ reloadOpenedFile();}}};@@ -441,7 +437,7 @@ function EntryContainer() {//check if file is changedif (fileChanged.current || force) {setSavingInProgress(true);- saveFile().then((success) => {+ save(openedEntry).then((success) => {if (success) {fileChanged.current = false;// showNotification(@@ -461,103 +457,99 @@ function EntryContainer() {};const override = (): Promise<boolean> => {- return switchLocationTypeByID(openedEntry.locationId).then(() =>- PlatformIO.getPropertiesPromise(openedEntry.path).then(- (entryProp: TS.FileSystemEntry) =>- save({ ...openedEntry, lmdt: entryProp.lmdt }).then(() =>- switchCurrentLocationType(),- ),- ),- );+ return cLocation+ .getPropertiesPromise(openedEntry.path)+ .then((entryProp: TS.FileSystemEntry) =>+ save({ ...openedEntry, lmdt: entryProp.lmdt }),+ );};const saveAs = (newFilePath: string): Promise<boolean> => {- return switchLocationTypeByID(openedEntry.locationId).then(() =>- copyFilePromise(openedEntry.path, newFilePath).then(() =>- PlatformIO.getPropertiesPromise(newFilePath).then(- (entryProp: TS.FileSystemEntry) =>- save({- ...openedEntry,- path: entryProp.path,- lmdt: entryProp.lmdt,- }).then(() => {- const openedEntryDir = extractContainingDirectoryPath(- entryProp.path,- );- if (currentDirectoryPath === openedEntryDir) {- openDirectory(openedEntryDir, openedEntry.locationId);- /*- updateOpenedFile(openedEntry.path, {- ...openedEntry,- editMode: false,- shouldReload: !openedEntry.shouldReload- });*/- }- return switchCurrentLocationType();- }),+ return copyFilePromise(openedEntry.path, newFilePath).then(() =>+ cLocation+ .getPropertiesPromise(newFilePath)+ .then((entryProp: TS.FileSystemEntry) =>+ save({+ ...openedEntry,+ path: entryProp.path,+ lmdt: entryProp.lmdt,+ }).then(() => {+ const openedEntryDir = extractContainingDirectoryPath(+ entryProp.path,+ );+ if (currentDirectoryPath === openedEntryDir) {+ openDirectory(openedEntryDir);+ }+ return true;+ }),),- ),- );- };-- const saveFile = (): Promise<boolean> => {- return switchLocationTypeByID(openedEntry.locationId).then(() =>- save(openedEntry).then(() => switchCurrentLocationType()),);};async function save(fileOpen: TS.OpenedEntry): Promise<boolean> {// @ts-ignoreconst textContent = fileViewer.current.contentWindow.getContent();- if (Pro && revisionsEnabled) {- const id = await getMetadataID(fileOpen.path, fileOpen.uuid);- const targetPath = getBackupFileLocation(- fileOpen.path,- id,- PlatformIO.getDirSeparator(),- );- try {- await copyFilePromiseOverwrite(fileOpen.path, targetPath, false); // todo test what happened if remove await?- } catch (error) {- console.log('copyFilePromiseOverwrite', error);- }- }- return saveTextFilePromise(- { path: fileOpen.path, lmdt: fileOpen.lmdt },- textContent,- true,- )- .then((entry) => {- reflectUpdateOpenedFileContent(entry);- if (Pro) {- const relativePath = getRelativeEntryPath(- currentLocationPath,+ const location = findLocation(fileOpen.locationID);+ if (location) {+ if (Pro && revisionsEnabled) {+ const id = await getMetadataID(fileOpen.path, fileOpen.uuid, location);+ const targetPath = getBackupFileLocation(+ fileOpen.path,+ id,+ location.getDirSeparator(),+ );+ try {+ await copyFilePromiseOverwrite(fileOpen.path,- );- Pro.history.saveHistory(- historyKeys.fileEditKey,- {- path: relativePath,- url: generateSharingLink(fileOpen.locationId, relativePath),- lid: fileOpen.locationId,- },- fileEditHistoryKey,- );+ targetPath,+ fileOpen.locationID,+ false,+ ); // todo test what happened if remove await?+ } catch (error) {+ console.log('copyFilePromiseOverwrite', error);}- return true;- /*return updateOpenedFile(fileOpen.path, {- id: '',- ...fileOpen,- editMode: true,- //changed: false,- shouldReload: undefined,- }).then(() => true);*/- })- .catch((error) => {- setConflictDialogOpen(true);- console.log('Error saving file ' + fileOpen.path + ' - ' + error);- return false;- });+ }+ return saveTextFilePromise(+ {+ path: fileOpen.path,+ lmdt: fileOpen.lmdt,+ locationID: fileOpen.locationID,+ },+ textContent,+ true,+ )+ .then((entry) => {+ reflectUpdateOpenedFileContent(entry);+ if (Pro) {+ const relativePath = getRelativeEntryPath(+ currentLocationPath,+ fileOpen.path,+ );+ Pro.history.saveHistory(+ historyKeys.fileEditKey,+ {+ path: relativePath,+ url: generateSharingLink(fileOpen.locationID, relativePath),+ lid: fileOpen.locationID,+ },+ fileEditHistoryKey,+ );+ }+ return true;+ /*return updateOpenedFile(fileOpen.path, {+ id: '',+ ...fileOpen,+ editMode: true,+ //changed: false,+ shouldReload: undefined,+ }).then(() => true);*/+ })+ .catch((error) => {+ setConflictDialogOpen(true);+ console.log('Error saving file ' + fileOpen.path + ' - ' + error);+ return false;+ });+ }}const editOpenedFile = () => {@@ -613,7 +605,7 @@ function EntryContainer() {const fileExtension =openedEntry &&- extractFileExtension(openedEntry.path, PlatformIO.getDirSeparator());+ extractFileExtension(openedEntry.path, cLocation?.getDirSeparator());const isEditable =openedEntry &&openedEntry.isFile &&@@ -621,8 +613,8 @@ function EntryContainer() {const toggleAutoSave = (event: React.ChangeEvent<HTMLInputElement>) => {const autoSave = event.target.checked;- if (Pro && Pro.MetaOperations) {- setAutoSave(openedEntry, autoSave, openedEntry.locationId);+ if (Pro) {+ setAutoSave(openedEntry, autoSave, openedEntry.locationID);/*switchLocationTypeByID(openedEntry.locationId).then((currentLocationId) => {Pro.MetaOperations.saveFsEntryMeta(openedEntry.path, {@@ -940,7 +932,9 @@ function EntryContainer() {open={isEditTagsModalOpened}onClose={() => setEditTagsModalOpened(false)}selected={- openedEntry ? [toFsEntry(openedEntry.path, openedEntry.isFile)] : []+ openedEntry+ ? [cLocation.toFsEntry(openedEntry.path, openedEntry.isFile)]+ : []}/>)}diff --git a/src/renderer/components/EntryContainerMenu.tsx b/src/renderer/components/EntryContainerMenu.tsxindex 05a1d69d6..db5983d42 100644--- a/src/renderer/components/EntryContainerMenu.tsx+++ b/src/renderer/components/EntryContainerMenu.tsx@@ -4,7 +4,6 @@ import {extractFileName,extractDirectoryName,} from '@tagspaces/tagspaces-common/paths';-import PlatformIO from '-/services/platform-facade';import {ListItemIcon,ListItemText,@@ -40,6 +39,11 @@ import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import {+ createNewInstance,+ openDirectoryMessage,+ openFileMessage,+} from '-/services/utils-io';interface Props {anchorEl: null | HTMLElement;@@ -67,7 +71,7 @@ function EntryContainerMenu(props: Props) {sharingParentFolderLink,} = useOpenedEntryContext();const keyBindings = useSelector(getKeyBindingObject);- const { readOnlyMode } = useCurrentLocationContext();+ const { currentLocation, readOnlyMode } = useCurrentLocationContext();const { deleteFile } = useIOActionsContext();const { showNotification } = useNotificationContext();const desktopMode = useSelector(isDesktopMode);@@ -114,9 +118,12 @@ function EntryContainerMenu(props: Props) {function downloadFile() {const entryName = `${baseName(openedEntry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),)}`;- const fileName = extractFileName(entryName, PlatformIO.getDirSeparator());+ const fileName = extractFileName(+ entryName,+ currentLocation?.getDirSeparator(),+ );if (AppConfig.isCordova) {if (openedEntry.url) {@@ -166,22 +173,21 @@ function EntryContainerMenu(props: Props) {};const openInNewWindow = () => {- PlatformIO.createNewInstance(window.location.href);+ createNewInstance(window.location.href);handleClose();};const shareFile = (filePath: string) => {- PlatformIO.shareFiles([filePath]);+ currentLocation.shareFiles([filePath]);handleClose();};const openNatively = () => {if (openedEntry.path) {if (openedEntry.isFile) {- PlatformIO.openFile(openedEntry.path, warningOpeningFilesExternally);- //dispatch(AppActions.openFileNatively(openedEntry.path));+ openFileMessage(openedEntry.path, warningOpeningFilesExternally);} else {- PlatformIO.openDirectory(openedEntry.path);+ openDirectoryMessage(openedEntry.path);}}handleClose();@@ -321,8 +327,8 @@ function EntryContainerMenu(props: Props) {}if (!(- PlatformIO.haveObjectStoreSupport() ||- PlatformIO.haveWebDavSupport() ||+ currentLocation?.haveObjectStoreSupport() ||+ currentLocation?.haveWebDavSupport() ||AppConfig.isWeb)) {@@ -390,8 +396,8 @@ function EntryContainerMenu(props: Props) {}if (!(- PlatformIO.haveObjectStoreSupport() ||- PlatformIO.haveWebDavSupport() ||+ currentLocation?.haveObjectStoreSupport() ||+ currentLocation?.haveWebDavSupport() ||AppConfig.isWeb)) {@@ -467,7 +473,7 @@ function EntryContainerMenu(props: Props) {);const entryName = openedEntry.path- ? extractDirectoryName(openedEntry.path, PlatformIO.getDirSeparator())+ ? extractDirectoryName(openedEntry.path, currentLocation?.getDirSeparator()): '';return (diff --git a/src/renderer/components/EntryContainerTitle.tsx b/src/renderer/components/EntryContainerTitle.tsxindex af261e163..d1dea0526 100644--- a/src/renderer/components/EntryContainerTitle.tsx+++ b/src/renderer/components/EntryContainerTitle.tsx@@ -25,12 +25,9 @@ import {extractDirectoryName,} from '@tagspaces/tagspaces-common/paths';import Tooltip from '-/components/Tooltip';-import PlatformIO from '-/services/platform-facade';import { FolderIcon, MoreMenuIcon } from '-/components/CommonIcons';import AppConfig from '-/AppConfig';import EntryContainerMenu from '-/components/EntryContainerMenu';-import { useSelector } from 'react-redux';-import { getLocations } from '-/reducers/locations';import Box from '@mui/material/Box';import { dataTidFormat } from '-/services/test';import { ProTooltip } from '-/components/HelperComponents';@@ -43,6 +40,7 @@ import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { getAllTags } from '-/services/utils-io';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';const FileBadge = styled('span')(({ theme }) => ({color: 'white',@@ -74,10 +72,10 @@ function EntryContainerTitle(props: Props) {} = props;const { t } = useTranslation();const theme = useTheme();- const { openedEntry, sharingLink, sharingParentFolderLink } =- useOpenedEntryContext();+ const { openedEntry, sharingLink } = useOpenedEntryContext();+ const { findLocation } = useCurrentLocationContext();const { showNotification } = useNotificationContext();- const locations = useSelector(getLocations);+ //const locations = useSelector(getLocations);const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);@@ -101,11 +99,12 @@ function EntryContainerTitle(props: Props) {}};+ const currentLocation = findLocation(openedEntry.locationID);let fileTitle: string = openedEntry.path? extractTitle(openedEntry.path,!openedEntry.isFile,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),): '';@@ -114,19 +113,16 @@ function EntryContainerTitle(props: Props) {if (openedEntry.isFile) {fileName = extractFileName(openedEntry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);} else {fileName = extractDirectoryName(openedEntry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);}}if (!fileName) {- const currentLocation = locations.find(- (location) => location.uuid === openedEntry.locationId,- );if (currentLocation) {fileName = currentLocation.name;}@@ -189,7 +185,7 @@ function EntryContainerTitle(props: Props) {//'.' +extractFileExtension(openedEntry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),)}<MoreMenuIcon style={{ fontSize: 20 }} />diff --git a/src/renderer/components/EntryProperties.tsx b/src/renderer/components/EntryProperties.tsxindex 16ebaa364..91ad6700f 100644--- a/src/renderer/components/EntryProperties.tsx+++ b/src/renderer/components/EntryProperties.tsx@@ -73,14 +73,12 @@ import MoveCopyFilesDialog from './dialogs/MoveCopyFilesDialog';import {fileNameValidation,dirNameValidation,- getFolderBgndPath,- getThumbPath,getAllTags,+ openUrl,} from '-/services/utils-io';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { parseGeoLocation } from '-/utils/geo';import { Pro } from '../pro';-import PlatformIO from '../services/platform-facade';import TagsSelect from './TagsSelect';import TransparentBackground from './TransparentBackground';import MarkerIcon from '-/assets/icons/marker-icon.png';@@ -236,8 +234,7 @@ function EntryProperties(props: Props) {saveDirectoryPerspective,} = useIOActionsContext();const { addTags, removeTags, removeAllTags } = useTaggingActionsContext();- const { switchLocationTypeByID, switchCurrentLocationType, readOnlyMode } =- useCurrentLocationContext();+ const { findLocation, readOnlyMode } = useCurrentLocationContext();const { showNotification } = useNotificationContext();const dirProps = useRef<TS.DirProp>(undefined);@@ -245,11 +242,12 @@ function EntryProperties(props: Props) {const sharingLinkRef = useRef<HTMLInputElement>(null);const disableConfirmButton = useRef<boolean>(true);const fileNameError = useRef<boolean>(false);+ const location = findLocation(openedEntry.locationID);const entryName = openedEntry? openedEntry.isFile- ? extractFileName(openedEntry.path, PlatformIO.getDirSeparator())- : extractDirectoryName(openedEntry.path, PlatformIO.getDirSeparator())+ ? extractFileName(openedEntry.path, location?.getDirSeparator())+ : extractDirectoryName(openedEntry.path, location?.getDirSeparator()): '';const [editName, setEditName] = useState<string>(undefined);@@ -291,27 +289,25 @@ function EntryProperties(props: Props) {if (editName !== undefined) {const path = extractContainingDirectoryPath(openedEntry.path,- PlatformIO.getDirSeparator(),+ location?.getDirSeparator(),);- const nextPath = path + PlatformIO.getDirSeparator() + editName;+ const nextPath = path + location.getDirSeparator() + editName;- switchLocationTypeByID(openedEntry.locationId).then(() => {- if (openedEntry.isFile) {- renameFile(openedEntry.path, nextPath)- .then(() => switchCurrentLocationType())- .catch(() => {- switchCurrentLocationType();- fileNameRef.current.value = entryName;- });- } else {- renameDirectory(openedEntry.path, editName)- .then((newDirPath) => switchCurrentLocationType())- .catch(() => {- switchCurrentLocationType();- fileNameRef.current.value = entryName;- });- }- });+ if (openedEntry.isFile) {+ renameFile(openedEntry.path, nextPath, openedEntry.locationID).catch(+ () => {+ fileNameRef.current.value = entryName;+ },+ );+ } else {+ renameDirectory(+ openedEntry.path,+ editName,+ openedEntry.locationID,+ ).catch(() => {+ fileNameRef.current.value = entryName;+ });+ }setEditName(undefined);}@@ -366,7 +362,7 @@ function EntryProperties(props: Props) {} else if (dirProps.current) {return formatBytes(dirProps.current.totalSize);}- return t(PlatformIO.haveObjectStoreSupport() ? 'core:notAvailable' : '?');+ return t(location.haveObjectStoreSupport() ? 'core:notAvailable' : '?');};const toggleBackgroundColorPicker = () => {@@ -377,10 +373,10 @@ function EntryProperties(props: Props) {showNotification(t('core:thisFunctionalityIsAvailableInPro'));return;}- if (!Pro.MetaOperations) {+ /*if (!Pro.MetaOperations) {showNotification(t('Saving color not supported'));return;- }+ }*/setDisplayColorPicker(!displayColorPicker);};@@ -416,36 +412,24 @@ function EntryProperties(props: Props) {};const handleChange = (name: string, value: Array<TS.Tag>, action: string) => {- switchLocationTypeByID(openedEntry.locationId)- .then(() => {- if (action === 'remove-value') {- if (!value) {- // no tags left in the select element- return removeAllTags([openedEntry.path]); /*.then(() =>- updateOpenedFile(openedEntry.path, {- id: '',- tags: [],- }),- );*/- } else {- return removeTags([openedEntry.path], value);- }- } else if (action === 'clear') {- return removeAllTags([openedEntry.path]);- }- // create-option or select-option- const tags =- openedEntry.tags === undefined- ? value- : value.filter(- (tag) =>- !openedEntry.tags.some((obj) => obj.title === tag.title),- );- return addTags([openedEntry.path], tags);- })- .then(() => {- switchCurrentLocationType();- });+ if (action === 'remove-value') {+ if (!value) {+ // no tags left in the select element+ return removeAllTags([openedEntry.path]);+ } else {+ return removeTags([openedEntry.path], value);+ }+ } else if (action === 'clear') {+ return removeAllTags([openedEntry.path]);+ }+ // create-option or select-option+ const tags =+ openedEntry.tags === undefined+ ? value+ : value.filter(+ (tag) => !openedEntry.tags.some((obj) => obj.title === tag.title),+ );+ return addTags([openedEntry.path], tags);};if (!openedEntry || !openedEntry.path || openedEntry.path === '') {@@ -466,7 +450,7 @@ function EntryProperties(props: Props) {...(openedEntry.meta && openedEntry.meta),perspective,};- saveDirectoryPerspective(openedEntry, perspective, openedEntry.locationId);+ saveDirectoryPerspective(openedEntry, perspective, openedEntry.locationID);/*.then((entryMeta: TS.FileSystemEntryMeta) => {openedEntry.meta = entryMeta;//return updateOpenedFile(openedEntry.path, entryMeta);@@ -517,7 +501,7 @@ function EntryProperties(props: Props) {const showLinkForDownloading = isCloudLocation && openedEntry.isFile;- const thumbUrl = getThumbPath(+ const thumbUrl = location.getThumbPath(openedEntry.meta?.thumbPath,openedEntry.meta?.lastUpdated,);@@ -663,7 +647,7 @@ function EntryProperties(props: Props) {color="primary"variant="outlined"onClick={() => {- PlatformIO.openUrl(+ openUrl('https://www.openstreetmap.org/?mlat=' +geoLocation.lat +'&mlon=' +@@ -685,7 +669,7 @@ function EntryProperties(props: Props) {color="primary"variant="outlined"onClick={() => {- PlatformIO.openUrl(+ openUrl('https://maps.google.com/?q=' +geoLocation.lat +',' +@@ -726,7 +710,7 @@ function EntryProperties(props: Props) {<Grid item xs={6}><Tooltiptitle={- !PlatformIO.haveObjectStoreSupport() &&+ !location.haveObjectStoreSupport() &&dirProps.current &&!openedEntry.isFile &&dirProps.current.dirsCount +@@ -847,7 +831,7 @@ function EntryProperties(props: Props) {const entryTitle = extractTitle(openedEntry.name,!openedEntry.isFile,- PlatformIO.getDirSeparator(),+ location?.getDirSeparator(),);const clibboardItem = generateClipboardLink(sharingLink,@@ -1120,7 +1104,7 @@ function EntryProperties(props: Props) {backgroundRepeat: 'no-repeat',backgroundImage:'url("' +- getFolderBgndPath(+ location.getFolderBgndPath(openedEntry.path,openedEntry.meta?.lastUpdated,) +@@ -1188,8 +1172,6 @@ function EntryProperties(props: Props) {<LinkGeneratorDialogopen={showSharingLinkDialog}onClose={() => setShowSharingLinkDialog(false)}- path={openedEntry.path}- locationId={openedEntry.locationId}/>)}{BgndImgChooserDialog && (diff --git a/src/renderer/components/FileUploadContainer.tsx b/src/renderer/components/FileUploadContainer.tsxindex e7891c95b..a8a774dc8 100644--- a/src/renderer/components/FileUploadContainer.tsx+++ b/src/renderer/components/FileUploadContainer.tsx@@ -21,6 +21,7 @@ import { useDispatch } from 'react-redux';import { TS } from '-/tagspaces.namespace';import { actions as AppActions, AppDispatch } from '-/reducers/app';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';interface Props {id: string;@@ -37,6 +38,7 @@ const FileUploadContainer = forwardRef(const dispatch: AppDispatch = useDispatch();const { id, directoryPath } = props;const { uploadFilesAPI } = useIOActionsContext();+ const { setReflectMetaActions } = useEditedEntryMetaContext();const onUploadProgress = (progress, abort, fileName) => {dispatch(AppActions.onUploadProgress(progress, abort, fileName));@@ -93,11 +95,11 @@ const FileUploadContainer = forwardRef(onUploadProgress,).then((fsEntries: Array<TS.FileSystemEntry>) => {- /*if (directoryPath === currentDirectoryPath) {- addDirectoryEntries(fsEntries);- dispatch(AppActions.reflectCreateEntries(fsEntries));- setSelectedEntries(fsEntries);- }*/+ const actions: TS.EditMetaAction[] = fsEntries.map((entry) => ({+ action: 'thumbGenerate',+ entry: entry,+ }));+ setReflectMetaActions(...actions);return true;}).catch((error) => {diff --git a/src/renderer/components/LocationManager.tsx b/src/renderer/components/LocationManager.tsxindex 9625ec7a1..ec6b6953c 100644--- a/src/renderer/components/LocationManager.tsx+++ b/src/renderer/components/LocationManager.tsx@@ -16,19 +16,17 @@**/-import React, { useEffect, useRef, useState } from 'react';-import { useDispatch, useSelector } from 'react-redux';+import React, { useRef, useState } from 'react';+import { useDispatch } from 'react-redux';import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';import { List } from '@mui/material';import LocationManagerMenu from '-/components/menus/LocationManagerMenu';import ConfirmDialog from '-/components/dialogs/ConfirmDialog';-import { actions as LocationActions, getLocations } from '-/reducers/locations';+import { actions as LocationActions } from '-/reducers/locations';import { actions as AppActions, AppDispatch } from '-/reducers/app';import LoadingLazy from '-/components/LoadingLazy';import LocationView from '-/components/LocationView';import { Pro } from '-/pro';-import { TS } from '-/tagspaces.namespace';-import PlatformIO from '-/services/platform-facade';import { classes, SidePanel } from '-/components/SidePanels.css';import { useTranslation } from 'react-i18next';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';@@ -58,6 +56,8 @@ function LocationManager(props: Props) {const { t } = useTranslation();const dispatch: AppDispatch = useDispatch();const {+ locations,+ currentLocation,addLocations,editLocation,selectedLocation,@@ -65,7 +65,7 @@ function LocationManager(props: Props) {locationDirectoryContextMenuAnchorEl,} = useCurrentLocationContext();- const locations: Array<TS.Location> = useSelector(getLocations);+ //const locations: Array<CommonLocation> = useSelector(getLocations);// const loading: boolean = useSelector(isLoading);//const language: string = useSelector(getCurrentLanguage);const fileInputRef = useRef<HTMLInputElement>(null);@@ -114,11 +114,12 @@ function LocationManager(props: Props) {>{//loading &&- (PlatformIO.haveObjectStoreSupport() ||- PlatformIO.haveWebDavSupport()) && (- <>- <style>- {`+ currentLocation &&+ (currentLocation.haveObjectStoreSupport() ||+ currentLocation.haveWebDavSupport()) && (+ <>+ <style>+ {`@keyframes hide {to {width: 0;@@ -126,22 +127,22 @@ function LocationManager(props: Props) {}}`}- </style>- <div- style={{- position: 'absolute',- zIndex: 1000,- height: 'calc(100% - 150px)',- width: 310,- backdropFilter: 'grayscale(1)',- animation: 'hide 1ms linear 5s 1 forwards',- // backgroundColor: 'red'- // backdropFilter: 'blur(2px)',- // backgroundColor: '#fafafaAA' // red: '#eb585882' '#d9d9d980'- }}- />- </>- )+ </style>+ <div+ style={{+ position: 'absolute',+ zIndex: 1000,+ height: 'calc(100% - 150px)',+ width: 310,+ backdropFilter: 'grayscale(1)',+ animation: 'hide 1ms linear 5s 1 forwards',+ // backgroundColor: 'red'+ // backdropFilter: 'blur(2px)',+ // backgroundColor: '#fafafaAA' // red: '#eb585882' '#d9d9d980'+ }}+ />+ </>+ )}<LocationManagerMenuimportLocations={() => {diff --git a/src/renderer/components/LocationView.tsx b/src/renderer/components/LocationView.tsxindex df6f852eb..65bf8d95c 100644--- a/src/renderer/components/LocationView.tsx+++ b/src/renderer/components/LocationView.tsx@@ -30,14 +30,11 @@ import DefaultLocationIcon from '@mui/icons-material/Highlight';import { locationType } from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';import { actions as AppActions, AppDispatch } from '../reducers/app';-import PlatformIO from '../services/platform-facade';import TargetMoveFileBox from './TargetMoveFileBox';import DragItemTypes from './DragItemTypes';import DirectoryTreeView, {DirectoryTreeViewRef,} from '-/components/DirectoryTreeView';-import LocationContextMenu from '-/components/menus/LocationContextMenu';-import { TS } from '-/tagspaces.namespace';import { classes, SidePanel } from '-/components/SidePanels.css';import { useTranslation } from 'react-i18next';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';@@ -45,9 +42,10 @@ import { useNotificationContext } from '-/hooks/useNotificationContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { CommonLocation } from '-/utils/CommonLocation';interface Props {- location: TS.Location;+ location: CommonLocation;hideDrawer?: () => void;setEditLocationDialogOpened: (open: boolean) => void;setDeleteLocationDialogOpened: (open: boolean) => void;@@ -92,7 +90,7 @@ function LocationView(props: Props) {const handleLocationClick = () => {if (currentLocation && location.uuid === currentLocation.uuid) {// the same location click- openDirectory(currentLocationPath, location.uuid); //PlatformIO.getLocationPath(location));+ openDirectory(currentLocationPath);} else {// this.directoryTreeRef[location.uuid].loadSubDir(location, 1);// setSelectedEntries([]);@@ -157,30 +155,22 @@ function LocationView(props: Props) {// TODO handle monitor -> isOver and change folder iconconsole.log('Dropped files: ' + path);if (targetLocation.type === locationType.TYPE_CLOUD) {- // TODO Webdav- PlatformIO.enableObjectStoreSupport(targetLocation)- .then(() => {- dispatch(AppActions.resetProgress());- dispatch(AppActions.toggleUploadDialog());- return uploadFiles(arrPath, targetPath, onUploadProgress).catch(- (error) => {- console.log('uploadFiles', error);- },- );- })- .catch((error) => {- console.log('enableObjectStoreSupport', error);- });+ dispatch(AppActions.resetProgress());+ dispatch(AppActions.toggleUploadDialog());+ return uploadFiles(arrPath, targetPath, onUploadProgress).catch(+ (error) => {+ console.log('uploadFiles', error);+ },+ );} else if (targetLocation.type === locationType.TYPE_LOCAL) {- PlatformIO.disableObjectStoreSupport();- moveFiles(arrPath, targetPath);+ moveFiles(arrPath, targetPath, targetLocation.uuid);}setSelectedEntries([]);}}};- let locationNameTitle = currentLocationPath; //PlatformIO.getLocationPath(location);+ let locationNameTitle = currentLocationPath;if (isCloudLocation && location.bucketName) {if (location.endpointURL) {locationNameTitle = location.endpointURL + ' - ' + location.bucketName;@@ -272,7 +262,7 @@ function LocationView(props: Props) {<TargetMoveFileBoxaccepts={[DragItemTypes.FILE]}onDrop={handleFileMoveDrop}- targetPath={currentLocationPath} //PlatformIO.getLocationPath(location)}+ targetPath={currentLocationPath}targetLocation={location}>{LocationTitle}diff --git a/src/renderer/components/MobileNavigation.tsx b/src/renderer/components/MobileNavigation.tsxindex dd48b04e2..81ffb278a 100644--- a/src/renderer/components/MobileNavigation.tsx+++ b/src/renderer/components/MobileNavigation.tsx@@ -71,11 +71,11 @@ import { BetaLabel, ProLabel } from '-/components/HelperComponents';import { actions as SettingsActions } from '-/reducers/settings';import StoredSearches from '-/components/StoredSearches';import UserDetailsPopover from '-/components/UserDetailsPopover';-import PlatformIO from '-/services/platform-facade';import AppConfig from '-/AppConfig';import { useTranslation } from 'react-i18next';import { getKeyBindingObject } from '-/reducers/settings';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { createNewInstance } from '-/services/utils-io';const PREFIX = 'MobileNavigation';@@ -236,7 +236,7 @@ function MobileNavigation(props: Props) {key="createWindowTID"ata-tid="createWindowTID"onClick={() => {- PlatformIO.createNewInstance();+ createNewInstance();setOpenCreateMenu(false);}}>diff --git a/src/renderer/components/PathBreadcrumbs.tsx b/src/renderer/components/PathBreadcrumbs.tsxindex f280fb18d..8478be342 100644--- a/src/renderer/components/PathBreadcrumbs.tsx+++ b/src/renderer/components/PathBreadcrumbs.tsx@@ -23,7 +23,6 @@ import Breadcrumbs from '@mui/material/Breadcrumbs';import Tooltip from '-/components/Tooltip';import Chip from '@mui/material/Chip';import ExpandMoreIcon from '@mui/icons-material/MoreVert';-import PlatformIO from '../services/platform-facade';import {normalizePath,extractShortDirectoryName,@@ -115,7 +114,8 @@ function PathBreadcrumbs(props: Props) {if (currentDirectoryPath) {// Make the path unix like ending always with /- const addSlash = PlatformIO.haveObjectStoreSupport() ? '//' : '/';+ const addSlash =+ currentLocation && currentLocation.haveObjectStoreSupport() ? '//' : '/';let normalizedCurrentPath =addSlash + normalizePath(currentDirectoryPath.split('\\').join('/'));@@ -126,14 +126,15 @@ function PathBreadcrumbs(props: Props) {}while (+ currentLocation &&normalizedCurrentPath.lastIndexOf('/') > 0 &&normalizedCurrentPath.startsWith(normalizedCurrentLocationPath)) {pathParts.push(normalizedCurrentPath- .substring(PlatformIO.haveObjectStoreSupport() ? 2 : 1)+ .substring(currentLocation.haveObjectStoreSupport() ? 2 : 1).split('/')- .join(PlatformIO.getDirSeparator()),+ .join(currentLocation.getDirSeparator()),); // TODO: optimization needednormalizedCurrentPath = normalizedCurrentPath.substring(0,@@ -163,7 +164,7 @@ function PathBreadcrumbs(props: Props) {breadcrumbs = pathParts.map((pathPart, index) => {const folderName = extractShortDirectoryName(pathPart,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);return (<Tooltip key={pathPart} title={t('core:navigateTo') + ' ' + pathPart}>@@ -172,7 +173,7 @@ function PathBreadcrumbs(props: Props) {href="#"label={folderName}icon={index === 0 && locationTypeIcon}- onClick={() => openDirectory(pathPart, currentLocation.uuid)}+ onClick={() => openDirectory(pathPart)}/></Tooltip>);diff --git a/src/renderer/components/RenderHistory.tsx b/src/renderer/components/RenderHistory.tsxindex 24e812e7d..f543866f5 100644--- a/src/renderer/components/RenderHistory.tsx+++ b/src/renderer/components/RenderHistory.tsx@@ -21,7 +21,6 @@ import Grid from '@mui/material/Grid';import React from 'react';import Button from '@mui/material/Button';import ListItem from '@mui/material/ListItem';-import PlatformIO from '-/services/platform-facade';import { Tooltip } from '@mui/material';import { Pro } from '-/pro';import BookmarkTwoToneIcon from '@mui/icons-material/BookmarkTwoTone';@@ -52,13 +51,16 @@ function RenderHistory(props: Props) {const openLinkDispatch = (link) => openLink(link, { fullWidth: false });+ if (!currentLocation) {+ return null;+ }return (<>{items &&items.slice(0, maxItems || items.length).map((item) => {- const itemName = item.path.endsWith(PlatformIO.getDirSeparator())- ? extractDirectoryName(item.path, PlatformIO.getDirSeparator())- : extractFileName(item.path, PlatformIO.getDirSeparator());+ const itemName = item.path.endsWith(currentLocation.getDirSeparator())+ ? extractDirectoryName(item.path, currentLocation.getDirSeparator())+ : extractFileName(item.path, currentLocation.getDirSeparator());return (<ListItemdensediff --git a/src/renderer/components/Revisions.tsx b/src/renderer/components/Revisions.tsxindex fe2e3f9ee..b28327dea 100644--- a/src/renderer/components/Revisions.tsx+++ b/src/renderer/components/Revisions.tsx@@ -23,7 +23,6 @@ import {extractFileNameWithoutExt,} from '@tagspaces/tagspaces-common/paths';import Tooltip from '-/components/Tooltip';-import PlatformIO from '-/services/platform-facade';import { TS } from '-/tagspaces.namespace';import { format, formatDistanceToNow } from 'date-fns';import DeleteIcon from '@mui/icons-material/Delete';@@ -53,8 +52,7 @@ const initialRowsPerPage = 10;function Revisions() {const { t } = useTranslation();- const { switchLocationTypeByID, switchCurrentLocationType } =- useCurrentLocationContext();+ const { findLocation } = useCurrentLocationContext();const { getMetadataID } = useIOActionsContext();const { openedEntry } = useOpenedEntryContext();const { copyFilePromiseOverwrite } = usePlatformFacadeContext();@@ -80,30 +78,26 @@ function Revisions() {function loadHistoryItems(openedFile: TS.OpenedEntry) {if (Pro) {- getMetadataID(openedFile.path, openedFile.uuid).then((id) => {- openedFile.uuid = id;- const backupFilePath = getBackupFileLocation(- openedFile.path,- openedFile.uuid,- PlatformIO.getDirSeparator(),- );- const backupPath = extractContainingDirectoryPath(- backupFilePath,- PlatformIO.getDirSeparator(),- );- switchLocationTypeByID(openedFile.locationId)- .then(() => {- PlatformIO.listDirectoryPromise(backupPath, []).then((h) => {- setRows(- h.sort((a, b) => (getLmdt(a.name) < getLmdt(b.name) ? 1 : -1)),- );- return switchCurrentLocationType();- });- })- .catch(() => {- return switchCurrentLocationType();+ const location = findLocation(openedFile.locationID);+ if (location) {+ getMetadataID(openedFile.path, openedFile.uuid, location).then((id) => {+ openedFile.uuid = id;+ const backupFilePath = getBackupFileLocation(+ openedFile.path,+ openedFile.uuid,+ location.getDirSeparator(),+ );+ const backupPath = extractContainingDirectoryPath(+ backupFilePath,+ location.getDirSeparator(),+ );+ location.listDirectoryPromise(backupPath, []).then((h) => {+ setRows(+ h.sort((a, b) => (getLmdt(a.name) < getLmdt(b.name) ? 1 : -1)),+ );});- });+ });+ }}}@@ -119,25 +113,28 @@ function Revisions() {};function deleteRevision(path) {- PlatformIO.deleteFilePromise(path, true).then(() =>- loadHistoryItems(openedEntry),- );+ const location = findLocation(openedEntry.locationID);+ location+ .deleteFilePromise(path, true)+ .then(() => loadHistoryItems(openedEntry));}function deleteRevisions() {if (rows.length > 0) {+ const location = findLocation(openedEntry.locationID);const promises = rows.map((row) =>- PlatformIO.deleteFilePromise(row.path, true),+ location.deleteFilePromise(row.path, true),);Promise.all(promises).then(() => loadHistoryItems(openedEntry));}}function restoreRevision(revisionPath) {+ const location = findLocation(openedEntry.locationID);const targetPath = getBackupFileLocation(openedEntry.path,openedEntry.uuid,- PlatformIO.getDirSeparator(),+ location.getDirSeparator(),);return copyFilePromiseOverwrite(openedEntry.path, targetPath).then(() =>copyFilePromiseOverwrite(revisionPath, openedEntry.path).then(() => {diff --git a/src/renderer/components/SearchAutocomplete.tsx b/src/renderer/components/SearchAutocomplete.tsxindex a8db60291..9690ca2af 100644--- a/src/renderer/components/SearchAutocomplete.tsx+++ b/src/renderer/components/SearchAutocomplete.tsx@@ -53,7 +53,6 @@ import {SearchOptionType,SearchQueryComposition,} from '-/components/SearchOptions';-import { getLocations } from '-/reducers/locations';import CloseIcon from '@mui/icons-material/Close';import { getTagLibrary } from '-/services/taglibrary-utils';import { getSearches } from '-/reducers/searches';@@ -65,6 +64,7 @@ import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { CommonLocation } from '-/utils/CommonLocation';interface Props {style?: any;@@ -87,12 +87,8 @@ function SearchAutocomplete(props: Props) {const { t } = useTranslation();const theme = useTheme();const { openEntry, openLink } = useOpenedEntryContext();- const {- currentLocation,- changeLocationByID,- switchLocationTypeByID,- openLocationById,- } = useCurrentLocationContext();+ const { locations, currentLocation, changeLocationByID, openLocationById } =+ useCurrentLocationContext();const {currentDirectoryPath,exitSearchMode,@@ -109,7 +105,7 @@ function SearchAutocomplete(props: Props) {const dispatch: AppDispatch = useDispatch();const maxSearchResults = useSelector(getMaxSearchResults);const showUnixHiddenEntries = useSelector(getShowUnixHiddenEntries);- const locations: TS.Location[] = useSelector(getLocations);+ //const locations: CommonLocation[] = useSelector(getLocations);const searches: Array<TS.SearchQuery> = useSelector(getSearches);const openLinkDispatch = (link, options) => openLink(link, options);@@ -879,10 +875,8 @@ function SearchAutocomplete(props: Props) {} else if (option.action === ExecActions.OPEN_HISTORY) {if (option.searchQuery) {if (option.id) {- switchLocationTypeByID(option.id).then(() => {- changeLocationByID(option.id);- setSearchQuery(option.searchQuery);- });+ changeLocationByID(option.id);+ setSearchQuery(option.searchQuery);} else {}} else if (Pro && Pro.history) {diff --git a/src/renderer/components/TagContainerDnd.tsx b/src/renderer/components/TagContainerDnd.tsxindex f01f16b73..8f6800d3a 100644--- a/src/renderer/components/TagContainerDnd.tsx+++ b/src/renderer/components/TagContainerDnd.tsx@@ -25,7 +25,7 @@ import AppConfig from '-/AppConfig';import DragItemTypes from './DragItemTypes';import TagContainer from './TagContainer';import { TS } from '-/tagspaces.namespace';-import PlatformIO from '-/services/platform-facade';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {tag: TS.Tag;@@ -76,6 +76,7 @@ const TagContainerDnd = (props: Props) => {selectedEntries,} = props;+ const { currentLocation } = useCurrentLocationContext();const tagContainerRef = useRef<HTMLSpanElement>(null);const endDrag = (item, monitor) => {@@ -194,7 +195,7 @@ const TagContainerDnd = (props: Props) => {const extractedTags = extractTags(entryPath,AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);if (extractedTags.length > 0 &&diff --git a/src/renderer/components/TagGroupTitleDnD.tsx b/src/renderer/components/TagGroupTitleDnD.tsxindex 32fa2eb58..3ef30c9fb 100644--- a/src/renderer/components/TagGroupTitleDnD.tsx+++ b/src/renderer/components/TagGroupTitleDnD.tsx@@ -27,6 +27,8 @@ import Grid from '@mui/material/Grid';import { TS } from '-/tagspaces.namespace';import DragItemTypes from '-/components/DragItemTypes';import { classes, SidePanel } from '-/components/SidePanels.css';+import { CommonLocation } from '-/utils/CommonLocation';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {index: number;@@ -37,7 +39,6 @@ interface Props {) => void;toggleTagGroup: (uuid: string) => void;moveTagGroup: (tagGroupUuid: TS.Uuid, position: number) => void;- locations: Array<TS.Location>;tagGroupCollapsed: Array<string>;isReadOnly: boolean;}@@ -49,9 +50,9 @@ function TagGroupTitleDnD(props: Props) {handleTagGroupMenu,moveTagGroup,toggleTagGroup,- locations,isReadOnly,} = props;+ const { findLocation } = useCurrentLocationContext();const tagGroupRef = useRef<HTMLSpanElement>(null);const [, drag] = useDrag({@@ -113,9 +114,7 @@ function TagGroupTitleDnD(props: Props) {function getLocationName(locationId: string) {if (locationId) {- const location: TS.Location = locations.find(- (l) => l.uuid === locationId,- );+ const location: CommonLocation = findLocation(locationId);if (location) {return ' (' + location.name + ')';}diff --git a/src/renderer/components/TagLibrary.tsx b/src/renderer/components/TagLibrary.tsxindex ce089f599..df9bae8a7 100644--- a/src/renderer/components/TagLibrary.tsx+++ b/src/renderer/components/TagLibrary.tsx@@ -44,7 +44,6 @@ import { AppDispatch } from '-/reducers/app';import SmartTags from '../reducers/smart-tags';import EditTagDialog from '-/components/dialogs/EditTagDialog';import { TS } from '-/tagspaces.namespace';-import { getLocations } from '-/reducers/locations';import TagGroupTitleDnD from '-/components/TagGroupTitleDnD';import { getAllTags } from '-/services/taglibrary-utils';import { classes, SidePanel } from '-/components/SidePanels.css';@@ -53,6 +52,7 @@ import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';import { useEditedTagLibraryContext } from '-/hooks/useEditedTagLibraryContext';+import { CommonLocation } from '-/utils/CommonLocation';interface Props {style?: any;@@ -67,19 +67,17 @@ function TagLibrary(props: Props) {removeTagGroup,deleteTag,changeTagOrder,- importTagGroups,moveTag,moveTagGroup,} = useTaggingActionsContext();const { selectedEntries } = useSelectedEntriesContext();- const { switchLocationTypeByID, switchCurrentLocationType, readOnlyMode } =- useCurrentLocationContext();+ const { readOnlyMode, findLocation } = useCurrentLocationContext();const { tagGroups } = useEditedTagLibraryContext();const dispatch: AppDispatch = useDispatch();const tagBackgroundColor = useSelector(getTagColor);const tagTextColor = useSelector(getTagTextColor);const tagGroupCollapsed: Array<string> = useSelector(getTagGroupCollapsed);- const locations: Array<TS.Location> = useSelector(getLocations);+ //const locations: Array<CommonLocation> = useSelector(getLocations);const toggleTagGroupDispatch = (uuid) =>dispatch(SettingsActions.toggleTagGroup(uuid));@@ -194,7 +192,6 @@ function TagLibrary(props: Props) {}}handleTagGroupMenu={handleTagGroupMenu}toggleTagGroup={toggleTagGroupDispatch}- locations={locations}tagGroupCollapsed={tagGroupCollapsed}isReadOnly={tagGroup.readOnly || isTagLibraryReadOnly}/>@@ -316,14 +313,9 @@ function TagLibrary(props: Props) {open={isCreateTagGroupDialogOpened}onClose={() => setIsCreateTagGroupDialogOpened(false)}createTagGroup={(entry: TS.TagGroup) => {- const location: TS.Location = locations.find(- (l) => l.uuid === entry.locationId,- );+ const location: CommonLocation = findLocation(entry.locationId);if (location) {- switchLocationTypeByID(location.uuid).then(() => {- createTagGroup(entry, location);- switchCurrentLocationType();- });+ createTagGroup(entry, location);} else {createTagGroup(entry);}diff --git a/src/renderer/components/TargetFileBox.tsx b/src/renderer/components/TargetFileBox.tsxindex c0c4d8867..c33da4d40 100644--- a/src/renderer/components/TargetFileBox.tsx+++ b/src/renderer/components/TargetFileBox.tsx@@ -21,7 +21,6 @@ import { DropTargetMonitor, useDrop } from 'react-dnd';import { classes, DnD } from '-/components/DnD.css';import { useTranslation } from 'react-i18next';import AppConfig from '-/AppConfig';-import PlatformIO from '-/services/platform-facade';import { useDispatch, useSelector } from 'react-redux';import { actions as AppActions, AppDispatch } from '-/reducers/app';import { TS } from '-/tagspaces.namespace';@@ -30,6 +29,7 @@ import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';type DragItem = { files: File[]; items: DataTransferItemList };type DragProps = { isActive: boolean; handlerId: Identifier | null };@@ -43,9 +43,10 @@ interface Props {function TargetFileBox(props: Props) {const { t } = useTranslation();const dispatch: AppDispatch = useDispatch();- const { readOnlyMode } = useCurrentLocationContext();+ const { currentLocation, readOnlyMode } = useCurrentLocationContext();const { uploadFilesAPI } = useIOActionsContext();const { showNotification } = useNotificationContext();+ const { setReflectMetaActions } = useEditedEntryMetaContext();const { currentDirectoryPath } = useDirectoryContentContext();const ref = useRef<HTMLDivElement>(null);const { setMoveCopyDialogOpened } = props;@@ -83,9 +84,11 @@ function TargetFileBox(props: Props) {false,).then((fsEntries: Array<TS.FileSystemEntry>) => {- /*addDirectoryEntries(fsEntries);- dispatch(AppActions.reflectCreateEntries(fsEntries));- setSelectedEntries(fsEntries);*/+ const actions: TS.EditMetaAction[] = fsEntries.map((entry) => ({+ action: 'thumbGenerate',+ entry: entry,+ }));+ setReflectMetaActions(...actions);return true;}).catch((error) => {@@ -102,8 +105,8 @@ function TargetFileBox(props: Props) {if (files && files.length) {if (AppConfig.isElectron &&- !PlatformIO.haveObjectStoreSupport() &&- !PlatformIO.haveWebDavSupport()+ !currentLocation.haveObjectStoreSupport() &&+ !currentLocation.haveWebDavSupport()) {return setMoveCopyDialogOpened(files);} else {diff --git a/src/renderer/components/TargetMoveFileBox.tsx b/src/renderer/components/TargetMoveFileBox.tsxindex 77d48b709..f44df907d 100644--- a/src/renderer/components/TargetMoveFileBox.tsx+++ b/src/renderer/components/TargetMoveFileBox.tsx@@ -20,6 +20,7 @@ import React from 'react';import { useDrop } from 'react-dnd';import { TS } from '-/tagspaces.namespace';import { classes, DnD } from '-/components/DnD.css';+import { CommonLocation } from '-/utils/CommonLocation';/*const styles: any = () => ({dropzone: {@@ -41,7 +42,7 @@ interface Props {onDrop: (item: any, monitor: any) => void;children: any;targetPath?: string;- targetLocation?: TS.Location;+ targetLocation?: CommonLocation;}const TargetMoveFileBox = (props: Props) => {diff --git a/src/renderer/components/TargetTableMoveFileBox.tsx b/src/renderer/components/TargetTableMoveFileBox.tsxindex fa4a7ce5c..7c3ef60e3 100644--- a/src/renderer/components/TargetTableMoveFileBox.tsx+++ b/src/renderer/components/TargetTableMoveFileBox.tsx@@ -19,11 +19,12 @@import React from 'react';import { useDrop } from 'react-dnd';import { TS } from '-/tagspaces.namespace';+import { CommonLocation } from '-/utils/CommonLocation';interface Props {accepts: string[];onDrop: (item: any, monitor: any) => void;- location: TS.Location;+ location: CommonLocation;className: string;}diff --git a/src/renderer/components/dialogs/AboutDialog.tsx b/src/renderer/components/dialogs/AboutDialog.tsxindex 7975a8667..a4a2b0ca1 100644--- a/src/renderer/components/dialogs/AboutDialog.tsx+++ b/src/renderer/components/dialogs/AboutDialog.tsx@@ -82,7 +82,7 @@ function AboutDialog(props: Props) {return true;}).catch((error) => {- console.warn('Error while checking for update: ' + error);+ console.log('Error while checking for update: ' + error);});}}diff --git a/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx b/src/renderer/components/dialogs/AddRemoveTagsDialog.tsxindex d8d3fbf16..9b5525445 100644--- a/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx+++ b/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx@@ -34,9 +34,7 @@ import TagsSelect from '../TagsSelect';import {extractFileName,extractDirectoryName,- getMetaFileLocationForFile,} from '@tagspaces/tagspaces-common/paths';-import PlatformIO from '-/services/platform-facade';import { TS } from '-/tagspaces.namespace';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import { useTheme } from '@mui/material/styles';@@ -44,7 +42,7 @@ import useMediaQuery from '@mui/material/useMediaQuery';import { useTranslation } from 'react-i18next';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';-import { useFSWatcherContext } from '-/hooks/useFSWatcherContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {open: boolean;@@ -54,9 +52,10 @@ interface Props {function AddRemoveTagsDialog(props: Props) {const { t } = useTranslation();-const { selectedEntries } = useSelectedEntriesContext();const selected = props.selected ? props.selected : selectedEntries;++ const { currentLocation } = useCurrentLocationContext();const { addTags, removeTags, removeAllTags } = useTaggingActionsContext();const [newlyAddedTags, setNewlyAddedTags] = useState<Array<TS.Tag>>([]);@@ -155,11 +154,11 @@ function AddRemoveTagsDialog(props: Props) {{entry.isFile? extractFileName(entry.path || '',- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),): extractDirectoryName(entry.path || '',- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),)}</Typography></ListItem>diff --git a/src/renderer/components/dialogs/CreateDirectoryDialog.tsx b/src/renderer/components/dialogs/CreateDirectoryDialog.tsxindex e6c122c73..f2b735bb0 100644--- a/src/renderer/components/dialogs/CreateDirectoryDialog.tsx+++ b/src/renderer/components/dialogs/CreateDirectoryDialog.tsx@@ -27,10 +27,10 @@ import FormHelperText from '@mui/material/FormHelperText';import Dialog from '@mui/material/Dialog';import { joinPaths } from '@tagspaces/tagspaces-common/paths';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';-import PlatformIO from '-/services/platform-facade';import { useTranslation } from 'react-i18next';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {open: boolean;@@ -42,6 +42,7 @@ interface Props {function CreateDirectoryDialog(props: Props) {const { t } = useTranslation();const { createDirectory } = useIOActionsContext();+ const { currentLocation } = useCurrentLocationContext();const { currentDirectoryPath } = useDirectoryContentContext();const [inputError, setInputError] = useState(false);@@ -73,7 +74,7 @@ function CreateDirectoryDialog(props: Props) {function onConfirm() {if (!disableConfirmButton && name) {const dirPath = joinPaths(- PlatformIO.getDirSeparator(),+ currentLocation.getDirSeparator(),selectedDirectoryPath !== undefined? selectedDirectoryPath: currentDirectoryPath,diff --git a/src/renderer/components/dialogs/CreateEditLocationDialog.tsx b/src/renderer/components/dialogs/CreateEditLocationDialog.tsxindex e6c25fe13..267df77d0 100644--- a/src/renderer/components/dialogs/CreateEditLocationDialog.tsx+++ b/src/renderer/components/dialogs/CreateEditLocationDialog.tsx@@ -61,7 +61,6 @@ import { TS } from '-/tagspaces.namespace';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import InfoIcon from '-/components/InfoIcon';import { ProLabel, BetaLabel, ProTooltip } from '-/components/HelperComponents';-import { getLocations } from '-/reducers/locations';import { getPersistTagsInSidecarFile, isDevMode } from '-/reducers/settings';import ConfirmDialog from '-/components/dialogs/ConfirmDialog';import WebdavForm from '-/components/dialogs/WebdavForm';@@ -75,6 +74,7 @@ import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';import { useTagGroupsLocationContext } from '-/hooks/useTagGroupsLocationContext';+import { CommonLocation } from '-/utils/CommonLocation';const PREFIX = 'CreateEditLocationDialog';@@ -92,7 +92,7 @@ const StyledDialog = styled(Dialog)(({ theme }) => ({interface Props {open: boolean;onClose: () => void;- editLocation?: (location: TS.Location) => void;+ editLocation?: (location: CommonLocation) => void;}function CreateEditLocationDialog(props: Props) {@@ -101,9 +101,10 @@ function CreateEditLocationDialog(props: Props) {const { showNotification } = useNotificationContext();const { createLocationIndex } = useLocationIndexContext();const { loadLocationDataPromise } = useTagGroupsLocationContext();- const { addLocation, selectedLocation } = useCurrentLocationContext();+ const { addLocation, selectedLocation, findLocation } =+ useCurrentLocationContext();const isPersistTagsInSidecar = useSelector(getPersistTagsInSidecarFile);- const locations: Array<TS.Location> = useSelector(getLocations);+ //const locations: Array<CommonLocation> = useSelector(getLocations);const devMode: boolean = useSelector(isDevMode);const IgnorePatternDialog =Pro && Pro.UI ? Pro.UI.IgnorePatternDialog : false;@@ -264,22 +265,28 @@ function CreateEditLocationDialog(props: Props) {}}, [name, path]);- function setLocationId(path: string) {- loadLocationDataPromise(path, AppConfig.metaFolderFile)+ function getMetaLocationId(+ location: CommonLocation,+ ): Promise<string | undefined> {+ return loadLocationDataPromise(location, AppConfig.metaFolderFile).then((meta: TS.FileSystemEntryMeta) => {if (meta && meta.id) {- if (!locations.some((ln) => ln.uuid === meta.id)) {- setNewUuid(meta.id);+ const location = findLocation(meta.id);+ if (!location) {+ return meta.id;}}- return true;+ return undefined;}).catch((err) => {- console.debug('no meta in location:' + path);+ console.debug('no meta in location:' + location.path);+ return undefined;});}+function setNewLocationID(newId: string) {- if (!locations.some((ln) => ln.uuid === newId)) {+ const location = findLocation(newId);+ if (!location) {setNewUuid(newId);} else {showNotification('Location with this ID already exists', 'error');@@ -434,10 +441,16 @@ function CreateEditLocationDialog(props: Props) {}if (!selectedLocation) {- addLocation(loc);+ const commonLocation = new CommonLocation(loc);+ getMetaLocationId(commonLocation).then((uuid) => {+ if (uuid) {+ commonLocation.uuid = uuid;+ }+ addLocation(commonLocation);+ });} else if (props.editLocation) {loc.newuuid = newuuid;- props.editLocation(loc);+ props.editLocation(new CommonLocation(loc));} else {console.log('No addLocation or editLocation props exist');}@@ -467,10 +480,7 @@ function CreateEditLocationDialog(props: Props) {region={region}endpointURL={endpointURL}setStoreName={setStoreName}- setStorePath={(path) => {- setStorePath(path);- setLocationId(path);- }}+ setStorePath={setStorePath}setAccessKeyId={setAccessKeyId}setSecretAccessKey={setSecretAccessKey}setSessionToken={setSessionToken}@@ -506,10 +516,7 @@ function CreateEditLocationDialog(props: Props) {errorTextPath={errorTextPath}errorTextName={errorTextName}setName={setName}- setPath={(path) => {- setPath(path);- setLocationId(path);- }}+ setPath={setPath}path={path}name={name}/>diff --git a/src/renderer/components/dialogs/CreateTagGroupDialog.tsx b/src/renderer/components/dialogs/CreateTagGroupDialog.tsxindex 353875428..9ab1c5229 100644--- a/src/renderer/components/dialogs/CreateTagGroupDialog.tsx+++ b/src/renderer/components/dialogs/CreateTagGroupDialog.tsx@@ -31,11 +31,11 @@ import Select from '@mui/material/Select';import ColorPickerDialog from './ColorPickerDialog';import TransparentBackground from '../TransparentBackground';import { TS } from '-/tagspaces.namespace';-import { getLocations } from '-/reducers/locations';import { getSaveTagInLocation } from '-/reducers/settings';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {open: boolean;@@ -49,7 +49,8 @@ const defaultTagGroupLocation = 'TAG_LIBRARY';function CreateTagGroupDialog(props: Props) {const { t } = useTranslation();- const locations = useSelector(getLocations);+ const { locations } = useCurrentLocationContext();+ //const locations = useSelector(getLocations);const saveTagsInLocation = useSelector(getSaveTagInLocation);const [displayColorPicker, setDisplayColorPicker] = useState<boolean>(false);diff --git a/src/renderer/components/dialogs/EditTagGroupDialog.tsx b/src/renderer/components/dialogs/EditTagGroupDialog.tsxindex 80d35b1a2..0e04af0d6 100644--- a/src/renderer/components/dialogs/EditTagGroupDialog.tsx+++ b/src/renderer/components/dialogs/EditTagGroupDialog.tsx@@ -32,12 +32,14 @@ import { useSelector } from 'react-redux';import ColorPickerDialog from './ColorPickerDialog';import TransparentBackground from '../TransparentBackground';import { TS } from '-/tagspaces.namespace';-import { getLocations } from '-/reducers/locations';import { Pro } from '-/pro';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import { getSaveTagInLocation } from '-/reducers/settings';import { useTranslation } from 'react-i18next';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';+import { CommonLocation } from '-/utils/CommonLocation';+import { useTagGroupsLocationContext } from '-/hooks/useTagGroupsLocationContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';const defaultTagGroupLocation = 'TAG_LIBRARY';@@ -50,9 +52,11 @@ interface Props {function EditTagGroupDialog(props: Props) {const { selectedTagGroupEntry, open, onClose } = props;+ const { locations, findLocation } = useCurrentLocationContext();const { updateTagGroup } = useTaggingActionsContext();+ const { removeLocationTagGroup } = useTagGroupsLocationContext();const { t } = useTranslation();- const locations: Array<TS.Location> = useSelector(getLocations);+ //const locations: Array<CommonLocation> = useSelector(getLocations);const saveTagInLocation: boolean = useSelector(getSaveTagInLocation);const [displayColorPicker, setDisplayColorPicker] = useState<boolean>(false);const [displayTextColorPicker, setDisplayTextColorPicker] =@@ -100,14 +104,11 @@ function EditTagGroupDialog(props: Props) {if (selectedTagGroupEntry && selectedTagGroupEntry.children) {if (Pro && locationId !== selectedTagGroupEntry.locationId) {- const location: TS.Location = locations.find(- (l) => l.uuid === selectedTagGroupEntry.locationId,+ const location: CommonLocation = findLocation(+ selectedTagGroupEntry.locationId,);if (location) {- Pro.MetaOperations.removeTagGroup(- location.path,- selectedTagGroupEntry.uuid,- );+ removeLocationTagGroup(location, selectedTagGroupEntry.uuid);}}updateTagGroup({diff --git a/src/renderer/components/dialogs/FilePreviewDialog.tsx b/src/renderer/components/dialogs/FilePreviewDialog.tsxindex fc6b16a63..59a59f3c0 100644--- a/src/renderer/components/dialogs/FilePreviewDialog.tsx+++ b/src/renderer/components/dialogs/FilePreviewDialog.tsx@@ -29,7 +29,6 @@ import { getCurrentTheme } from '-/reducers/settings';import { useSelector } from 'react-redux';import FileView from '-/components/FileView';import useEventListener from '-/utils/useEventListener';-import PlatformIO from '-/services/platform-facade';import AppConfig from '-/AppConfig';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';@@ -42,9 +41,7 @@ interface Props {function FilePreviewDialog(props: Props) {const { open = false, onClose, fsEntry } = props;- //const dispatch: AppDispatch = useDispatch();- const { switchLocationTypeByID, switchCurrentLocationType } =- useCurrentLocationContext();+ const { currentLocation } = useCurrentLocationContext();const { openedEntry } = useOpenedEntryContext();// const supportedFileTypes = useSelector(getSupportedFileTypes);const currentTheme = useSelector(getCurrentTheme);@@ -104,52 +101,49 @@ function FilePreviewDialog(props: Props) {fileViewer.current.contentWindow.setTheme(currentTheme);}*/- switchLocationTypeByID(openedFile.locationId).then(() => {- PlatformIO.loadTextFilePromise(+ currentLocation+ .loadTextFilePromise(textFilePath,data.preview ? data.preview : false,)- .then((content) => {- const UTF8_BOM = '\ufeff';- if (content.indexOf(UTF8_BOM) === 0) {- content = content.substr(1);- }- let fileDirectory = extractContainingDirectoryPath(- textFilePath,- PlatformIO.getDirSeparator(),+ .then((content) => {+ const UTF8_BOM = '\ufeff';+ if (content.indexOf(UTF8_BOM) === 0) {+ content = content.substr(1);+ }+ let fileDirectory = extractContainingDirectoryPath(+ textFilePath,+ currentLocation?.getDirSeparator(),+ );+ if (AppConfig.isWeb) {+ fileDirectory =+ extractContainingDirectoryPath(+ // eslint-disable-next-line no-restricted-globals+ location.href,+ currentLocation?.getDirSeparator(),+ ) ++ '/' ++ fileDirectory;+ }+ if (+ fileViewer &&+ fileViewer.current &&+ fileViewer.current.contentWindow &&+ // @ts-ignore+ fileViewer.current.contentWindow.setContent+ ) {+ // @ts-ignore call setContent from iframe+ fileViewer.current.contentWindow.setContent(+ content,+ fileDirectory,+ !openedFile.editMode,+ currentTheme,);- if (AppConfig.isWeb) {- fileDirectory =- extractContainingDirectoryPath(- // eslint-disable-next-line no-restricted-globals- location.href,- PlatformIO.getDirSeparator(),- ) +- '/' +- fileDirectory;- }- if (- fileViewer &&- fileViewer.current &&- fileViewer.current.contentWindow &&- // @ts-ignore- fileViewer.current.contentWindow.setContent- ) {- // @ts-ignore call setContent from iframe- fileViewer.current.contentWindow.setContent(- content,- fileDirectory,- !openedFile.editMode,- currentTheme,- );- }- return switchCurrentLocationType();- })- .catch((err) => {- console.warn('Error loading text content ' + err);- return switchCurrentLocationType();- });- });+ }+ })+ .catch((err) => {+ console.log('Error loading text content ' + err);+ });break;}};diff --git a/src/renderer/components/dialogs/FileUploadDialog.tsx b/src/renderer/components/dialogs/FileUploadDialog.tsxindex 0fcfdd2e1..59e890c19 100644--- a/src/renderer/components/dialogs/FileUploadDialog.tsx+++ b/src/renderer/components/dialogs/FileUploadDialog.tsx@@ -29,7 +29,6 @@ import Typography from '@mui/material/Typography';import Box from '@mui/material/Box';import { LinearProgress, Grid, Tooltip } from '@mui/material';import WarningIcon from '@mui/icons-material/Warning';-import PlatformIO from '-/services/platform-facade';import DraggablePaper from '-/components/DraggablePaper';import {actions as AppActions,@@ -42,6 +41,7 @@ import { useTranslation } from 'react-i18next';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import AppConfig from '-/AppConfig';+import { uploadAbort } from '-/services/utils-io';interface Props {open: boolean;@@ -93,14 +93,7 @@ function FileUploadDialog(props: Props) {const stopAll = () => {if (progress) {- return PlatformIO.uploadAbort();- /*progress.map((fileProgress) => {- const { abort } = fileProgress;- if (abort !== undefined && typeof abort === 'function') {- abort();- }- return true;- });*/+ return uploadAbort();}};@@ -214,7 +207,7 @@ function FileUploadDialog(props: Props) {? filePath: extractFileName(targetPath.current,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),)}{percentage === -1 && (<Tooltipdiff --git a/src/renderer/components/dialogs/IsTruncatedConfirmDialog.tsx b/src/renderer/components/dialogs/IsTruncatedConfirmDialog.tsxindex 09be0e902..7e0566ade 100644--- a/src/renderer/components/dialogs/IsTruncatedConfirmDialog.tsx+++ b/src/renderer/components/dialogs/IsTruncatedConfirmDialog.tsx@@ -31,7 +31,6 @@ import AppConfig from '-/AppConfig';import Typography from '@mui/material/Typography';import InfoIcon from '-/components/InfoIcon';import FormControlLabel from '@mui/material/FormControlLabel';-import PlatformIO from '-/services/platform-facade';import { useTranslation } from 'react-i18next';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';@@ -71,7 +70,7 @@ function IsTruncatedConfirmDialog(props: Props) {);onClose();if (currentLocation.type === locationType.TYPE_CLOUD) {- openDirectory(currentDirectoryPath, currentLocation.uuid);+ openDirectory(currentDirectoryPath);}}}diff --git a/src/renderer/components/dialogs/LicenseDialog.tsx b/src/renderer/components/dialogs/LicenseDialog.tsxindex 758454804..c464e2cac 100644--- a/src/renderer/components/dialogs/LicenseDialog.tsx+++ b/src/renderer/components/dialogs/LicenseDialog.tsx@@ -24,10 +24,10 @@ import DialogTitle from '@mui/material/DialogTitle';import Dialog from '@mui/material/Dialog';import { Pro } from '-/pro';import LicenseContent from '-/LICENSE.txt';-import PlatformIO from '-/services/platform-facade';import { useTheme } from '@mui/material/styles';import useMediaQuery from '@mui/material/useMediaQuery';import { useTranslation } from 'react-i18next';+import { quitApp } from '-/services/utils-io';// import DialogCloseButton from '-/components/dialogs/DialogCloseButton';@@ -91,7 +91,7 @@ function LicenseDialog(props: Props) {</Button> */}<Buttondata-tid="confirmLicenseDialog"- onClick={PlatformIO.quitApp}+ onClick={quitApp}color="primary">{t('core:quit')}diff --git a/src/renderer/components/dialogs/LinkGeneratorDialog.tsx b/src/renderer/components/dialogs/LinkGeneratorDialog.tsxindex f05620a58..6a6058337 100644--- a/src/renderer/components/dialogs/LinkGeneratorDialog.tsx+++ b/src/renderer/components/dialogs/LinkGeneratorDialog.tsx@@ -17,7 +17,6 @@*/import React, { ChangeEvent, useRef, useReducer, useEffect } from 'react';-import { styled } from '@mui/material/styles';import Button from '@mui/material/Button';import DialogActions from '@mui/material/DialogActions';import DialogContent from '@mui/material/DialogContent';@@ -31,46 +30,49 @@ import InfoIcon from '-/components/InfoIcon';import InputAdornment from '@mui/material/InputAdornment';import TextField from '@mui/material/TextField';import MenuItem from '@mui/material/MenuItem';-import PlatformIO from '-/services/platform-facade';import Links from 'assets/links';import { extractTitle } from '@tagspaces/tagspaces-common/paths';import { useTranslation } from 'react-i18next';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { generateClipboardLink } from '-/utils/dom';+import { openUrl } from '-/services/utils-io';+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';interface Props {open: boolean;+ path?: string;onClose: () => void;- path: string;- locationId?: string;}function LinkGeneratorDialog(props: Props) {const { open, onClose, path } = props;const { t } = useTranslation();+ const { findLocation, currentLocation } = useCurrentLocationContext();+ const { openedEntry } = useOpenedEntryContext();const { showNotification } = useNotificationContext();- const { switchLocationTypeByID, switchCurrentLocationType } =- useCurrentLocationContext();const linkValidityDuration = useRef<number>(60 * 15);const signedLink = useRef<string>(undefined);- const [ignored, forceUpdate] = useReducer((x) => x + 1, 0);+ const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);const theme = useTheme();const fullScreen = useMediaQuery(theme.breakpoints.down('md'));+ let location = findLocation(openedEntry?.locationID);+ if (!location) {+ location = currentLocation;+ }+ const gPath = path || openedEntry.path;+useEffect(() => {setSignedLink();}, []);function setSignedLink() {- switchLocationTypeByID(props.locationId).then((currentLocationId) => {- signedLink.current = PlatformIO.generateURLforPath(- path,- linkValidityDuration.current,- );- forceUpdate();- return switchCurrentLocationType();- });+ signedLink.current = location.generateURLforPath(+ gPath,+ linkValidityDuration.current,+ );+ forceUpdate();}return (@@ -121,9 +123,9 @@ function LinkGeneratorDialog(props: Props) {data-tid="copySharingLinkTID"onClick={() => {const entryTitle = extractTitle(- path,+ gPath,true,- PlatformIO.getDirSeparator(),+ location.getDirSeparator(),);const clipboardItem = generateClipboardLink(signedLink.current,@@ -178,7 +180,7 @@ function LinkGeneratorDialog(props: Props) {variant="text"data-tid="helpSearchButtonTID"onClick={() => {- PlatformIO.openUrl(Links.documentationLinks.sharing);+ openUrl(Links.documentationLinks.sharing);}}>{t('help')}diff --git a/src/renderer/components/dialogs/LocalForm.tsx b/src/renderer/components/dialogs/LocalForm.tsxindex 9a83821fc..5a073a219 100644--- a/src/renderer/components/dialogs/LocalForm.tsx+++ b/src/renderer/components/dialogs/LocalForm.tsx@@ -27,8 +27,10 @@ import FormHelperText from '@mui/material/FormHelperText';import Grid from '@mui/material/Grid';import { extractDirectoryName } from '@tagspaces/tagspaces-common/paths';import AppConfig from '-/AppConfig';-import PlatformIO from '-/services/platform-facade';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { selectDirectoryDialog } from '-/services/utils-io';+import { CommonLocation } from '-/utils/CommonLocation';interface Props {errorTextPath: boolean;@@ -42,16 +44,17 @@ interface Props {function LocalForm(props: Props) {const { errorTextPath, errorTextName, setName, setPath, path, name } = props;const { t } = useTranslation();+ const { currentLocation } = useCurrentLocationContext();const openDirectory = () => {- PlatformIO.selectDirectoryDialog()+ selectDirectoryDialog().then((selectedPaths) => {const selectedPath = decodeURI(selectedPaths[0]);setPath(selectedPath);if (name.length < 1 && selectedPath.length > 0) {const dirName = extractDirectoryName(selectedPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);setName(dirName.charAt(0).toUpperCase() + dirName.slice(1));}diff --git a/src/renderer/components/dialogs/MoveCopyFilesDialog.tsx b/src/renderer/components/dialogs/MoveCopyFilesDialog.tsxindex 59d83715d..bef4746e1 100644--- a/src/renderer/components/dialogs/MoveCopyFilesDialog.tsx+++ b/src/renderer/components/dialogs/MoveCopyFilesDialog.tsx@@ -1,5 +1,5 @@import React, { useState, useRef, useReducer, useEffect } from 'react';-import { useDispatch, useSelector } from 'react-redux';+import { useDispatch } from 'react-redux';import { formatBytes } from '@tagspaces/tagspaces-common/misc';import Paper from '@mui/material/Paper';import Button from '@mui/material/Button';@@ -14,7 +14,6 @@ import Typography from '@mui/material/Typography';import Dialog from '@mui/material/Dialog';import { FolderIcon, FileIcon } from '-/components/CommonIcons';import DraggablePaper from '-/components/DraggablePaper';-import PlatformIO from '-/services/platform-facade';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import { useTheme } from '@mui/material/styles';import useMediaQuery from '@mui/material/useMediaQuery';@@ -22,16 +21,13 @@ import { actions as AppActions, AppDispatch } from '-/reducers/app';import { TS } from '-/tagspaces.namespace';import DirectoryListView from '-/components/DirectoryListView';import AppConfig from '-/AppConfig';-import Tooltip from '-/components/Tooltip';import ConfirmDialog from '-/components/dialogs/ConfirmDialog';-import {- checkDirsExistPromise,- checkFilesExistPromise,-} from '-/services/utils-io';import { useTranslation } from 'react-i18next';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { getDirProperties } from '-/services/utils-io';interface Props {open: boolean;@@ -43,6 +39,7 @@ interface Props {function MoveCopyFilesDialog(props: Props) {const { t } = useTranslation();const dispatch: AppDispatch = useDispatch();+ const { currentLocation } = useCurrentLocationContext();const { currentDirectoryPath } = useDirectoryContentContext();const { copyFiles, copyDirs, moveFiles, moveDirs } = useIOActionsContext();const { selectedEntries } = useSelectedEntriesContext();@@ -80,12 +77,12 @@ function MoveCopyFilesDialog(props: Props) {if (selectedDirs.length > 0 &&AppConfig.isElectron &&- !PlatformIO.haveObjectStoreSupport() &&- !PlatformIO.haveWebDavSupport()+ !currentLocation.haveObjectStoreSupport() &&+ !currentLocation.haveWebDavSupport()) {const promises = selectedDirs.map((dirPath) => {try {- return PlatformIO.getDirProperties(dirPath).then((prop) => {+ return getDirProperties(dirPath).then((prop) => {dirProp.current[dirPath] = prop;return true;});@@ -126,14 +123,14 @@ function MoveCopyFilesDialog(props: Props) {function handleCopyMove(copy = true) {if (selectedFiles.length > 0) {- checkFilesExistPromise(selectedFiles, targetPath).then((exist) =>- handleEntryExist(copy, exist),- );+ currentLocation+ .checkFilesExistPromise(selectedFiles, targetPath)+ .then((exist) => handleEntryExist(copy, exist));}if (selectedDirs.length > 0) {- checkDirsExistPromise(selectedDirs, targetPath).then((exist) =>- handleEntryExist(copy, exist),- );+ currentLocation+ .checkDirsExistPromise(selectedDirs, targetPath)+ .then((exist) => handleEntryExist(copy, exist));}}@@ -156,7 +153,12 @@ function MoveCopyFilesDialog(props: Props) {setTargetPath('');}if (selectedDirs.length > 0) {- copyDirs(getEntriesCount(selectedDirs), targetPath, onUploadProgress);+ copyDirs(+ getEntriesCount(selectedDirs),+ targetPath,+ currentLocation.uuid,+ onUploadProgress,+ );}onClose(true);}@@ -167,28 +169,27 @@ function MoveCopyFilesDialog(props: Props) {function handleMoveFiles() {if (selectedFiles.length > 0) {- moveFiles(selectedFiles, targetPath, onUploadProgress);+ moveFiles(+ selectedFiles,+ targetPath,+ currentLocation.uuid,+ onUploadProgress,+ );setTargetPath('');}if (selectedDirs.length > 0) {dispatch(AppActions.resetProgress());dispatch(AppActions.toggleUploadDialog('moveEntriesTitle'));- moveDirs(getEntriesCount(selectedDirs), targetPath, onUploadProgress);+ moveDirs(+ getEntriesCount(selectedDirs),+ targetPath,+ currentLocation.uuid,+ onUploadProgress,+ );}onClose(true);}- /*function selectDirectory() {- PlatformIO.selectDirectoryDialog()- .then(selectedPaths => {- setTargetPath(selectedPaths[0]);- return true;- })- .catch(err => {- console.log('selectDirectoryDialog failed with: ' + err);- });- }*/-function formatFileExist(entries) {if (entries !== undefined) {return entries.join(', ');diff --git a/src/renderer/components/dialogs/MoveOrCopyFilesDialog.tsx b/src/renderer/components/dialogs/MoveOrCopyFilesDialog.tsxindex e4714efa7..8dcb5dd60 100644--- a/src/renderer/components/dialogs/MoveOrCopyFilesDialog.tsx+++ b/src/renderer/components/dialogs/MoveOrCopyFilesDialog.tsx@@ -22,6 +22,7 @@*/import React from 'react';+import { joinPaths, extractFileName } from '@tagspaces/tagspaces-common/paths';import Button from '@mui/material/Button';import Paper from '@mui/material/Paper';import List from '@mui/material/List';@@ -40,6 +41,11 @@ import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import { useTranslation } from 'react-i18next';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { TS } from '-/tagspaces.namespace';+import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';+import { executePromisesInBatches } from '-/services/utils-io';+import AppConfig from '-/AppConfig';interface Props {open: boolean;@@ -53,10 +59,24 @@ function MoveOrCopyFilesDialog(props: Props) {const theme = useTheme();+ const { setReflectMetaActions } = useEditedEntryMetaContext();+ const { currentLocation } = useCurrentLocationContext();const { moveFiles, copyFiles } = useIOActionsContext();const { currentDirectoryPath } = useDirectoryContentContext();const fullScreen = useMediaQuery(theme.breakpoints.down('md'));+ function generateThumbs(filePaths: string[]) {+ const promises: Promise<TS.EditMetaAction>[] = filePaths.map((filePath) =>+ currentLocation.getPropertiesPromise(filePath).then((entry) => ({+ action: 'thumbGenerate',+ entry: entry,+ })),+ );+ executePromisesInBatches(promises).then((actions) => {+ setReflectMetaActions(...actions);+ });+ }+return (<Dialogopen={open}@@ -105,10 +125,28 @@ function MoveOrCopyFilesDialog(props: Props) {<ButtononClick={() => {if (selectedFiles) {+ const filePaths = selectedFiles.map((file) => file.path);moveFiles(- selectedFiles.map((file) => file.path),+ filePaths,currentDirectoryPath,- );+ currentLocation.uuid,+ ).then((success) => {+ if (success) {+ generateThumbs(+ filePaths.map((targetPath) =>+ joinPaths(+ currentLocation?.getDirSeparator(),+ currentDirectoryPath,+ extractFileName(+ targetPath,+ currentLocation?.getDirSeparator(),+ ),+ ),+ ),+ );+ }+ return true;+ });}onClose();}}@@ -121,10 +159,24 @@ function MoveOrCopyFilesDialog(props: Props) {<ButtononClick={() => {if (selectedFiles) {- copyFiles(- selectedFiles.map((file) => file.path),- currentDirectoryPath,- );+ const filePaths = selectedFiles.map((file) => file.path);+ copyFiles(filePaths, currentDirectoryPath).then((success) => {+ if (success) {+ generateThumbs(+ filePaths.map((targetPath) =>+ joinPaths(+ currentLocation?.getDirSeparator(),+ currentDirectoryPath,+ extractFileName(+ targetPath,+ currentLocation?.getDirSeparator(),+ ),+ ),+ ),+ );+ }+ return true;+ });}onClose();}}diff --git a/src/renderer/components/dialogs/RenameEntryDialog.tsx b/src/renderer/components/dialogs/RenameEntryDialog.tsxindex dd3b8d4ab..39d4894df 100644--- a/src/renderer/components/dialogs/RenameEntryDialog.tsx+++ b/src/renderer/components/dialogs/RenameEntryDialog.tsx@@ -33,13 +33,13 @@ import {} from '@tagspaces/tagspaces-common/paths';import DraggablePaper from '-/components/DraggablePaper';import AppConfig from '-/AppConfig';-import PlatformIO from '-/services/platform-facade';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import { dirNameValidation, fileNameValidation } from '-/services/utils-io';import { useTranslation } from 'react-i18next';import { useIOActionsContext } from '-/hooks/useIOActionsContext';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {open: boolean;@@ -50,6 +50,7 @@ function RenameEntryDialog(props: Props) {const { open, onClose } = props;const { t } = useTranslation();const { renameDirectory, renameFile } = useIOActionsContext();+ const { currentLocation } = useCurrentLocationContext();const { currentDirectoryPath } = useDirectoryContentContext();const { selectedEntries } = useSelectedEntriesContext();const lastSelectedEntry = selectedEntries[selectedEntries.length - 1];@@ -64,12 +65,12 @@ function RenameEntryDialog(props: Props) {if (isFile) {defaultName = extractFileName(lastSelectedEntry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);} else {defaultName = extractDirectoryName(lastSelectedEntry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);}originPath = lastSelectedEntry.path;@@ -77,7 +78,7 @@ function RenameEntryDialog(props: Props) {isFile = false;defaultName = extractDirectoryName(currentDirectoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);originPath = currentDirectoryPath;} else {@@ -139,13 +140,13 @@ function RenameEntryDialog(props: Props) {if (isFile) {const fileDirectory = extractContainingDirectoryPath(lastSelectedEntry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const newFilePath =- fileDirectory + PlatformIO.getDirSeparator() + name.current;- return renameFile(originPath, newFilePath);+ fileDirectory + currentLocation.getDirSeparator() + name.current;+ return renameFile(originPath, newFilePath, currentLocation.uuid);} else {- return renameDirectory(originPath, name.current);+ return renameDirectory(originPath, name.current, currentLocation.uuid);}}};diff --git a/src/renderer/components/dialogs/ResolveConflictDialog.tsx b/src/renderer/components/dialogs/ResolveConflictDialog.tsxindex 985cbae03..7e17e9480 100644--- a/src/renderer/components/dialogs/ResolveConflictDialog.tsx+++ b/src/renderer/components/dialogs/ResolveConflictDialog.tsx@@ -31,7 +31,6 @@ import {extractFileExtension,extractFileName,} from '@tagspaces/tagspaces-common/paths';-import PlatformFacade from '-/services/platform-facade';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';@@ -115,7 +114,7 @@ function ResolveConflictDialog(props: Props) {props.saveAs(extractContainingDirectoryPath(openedEntry.path) +- PlatformFacade.getDirSeparator() ++ '/' +copyFileName.current,).then(() => {diff --git a/src/renderer/components/dialogs/components/CreateDirectory.tsx b/src/renderer/components/dialogs/components/CreateDirectory.tsxindex 7a365f48f..dee0c4a16 100644--- a/src/renderer/components/dialogs/components/CreateDirectory.tsx+++ b/src/renderer/components/dialogs/components/CreateDirectory.tsx@@ -25,7 +25,6 @@ import ButtonGroup from '@mui/material/ButtonGroup';import Grid from '@mui/material/Grid';import AppConfig from '-/AppConfig';import { actions as AppActions, AppDispatch } from '-/reducers/app';-import PlatformIO from '-/services/platform-facade';import Tooltip from '-/components/Tooltip';import TextField from '@mui/material/TextField';import { useTargetPathContext } from '-/components/dialogs/hooks/useTargetPathContext';@@ -38,6 +37,7 @@ import { useIOActionsContext } from '-/hooks/useIOActionsContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { Pro } from '-/pro';import { BetaLabel, ProLabel } from '-/components/HelperComponents';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';const PREFIX = 'CreateDirectory';@@ -60,6 +60,7 @@ interface Props {function CreateDirectory(props: Props) {const { onClose, tidPrefix } = props;const { t } = useTranslation();+ const { currentLocation } = useCurrentLocationContext();const { downloadFile } = useIOActionsContext();const { showNotification } = useNotificationContext();const fileUploadContainerRef = useRef<FileUploadContainerRef>(null);@@ -119,18 +120,16 @@ function CreateDirectory(props: Props) {} else if (fileName.indexOf('.') === -1) {fileName = url.hostname + '-' + fileName + '.html';}- if (PlatformIO.haveObjectStoreSupport() || AppConfig.isElectron) {+ if (currentLocation?.haveObjectStoreSupport() || AppConfig.isElectron) {dispatch(AppActions.resetProgress());dispatch(AppActions.toggleUploadDialog());downloadFile(fileUrl.current,- targetDirectoryPath +- PlatformIO.getDirSeparator() +- decodeURIComponent(fileName),+ targetDirectoryPath + '/' + decodeURIComponent(fileName),onUploadProgress,).then(() => {- if (PlatformIO.haveObjectStoreSupport()) {+ if (currentLocation.haveObjectStoreSupport()) {// currently objectStore location in downloadFile use saveFilePromise and this function not have progress handlingdispatch(AppActions.setProgress(fileUrl.current, 100));}diff --git a/src/renderer/components/dialogs/settings/SettingsExtensions.tsx b/src/renderer/components/dialogs/settings/SettingsExtensions.tsxindex a042dff5d..9c409563b 100644--- a/src/renderer/components/dialogs/settings/SettingsExtensions.tsx+++ b/src/renderer/components/dialogs/settings/SettingsExtensions.tsx@@ -36,16 +36,22 @@ import {getExtensions,} from '-/reducers/app';import { TS } from '-/tagspaces.namespace';-import PlatformIO from '-/services/platform-facade';import ConfirmDialog from '-/components/dialogs/ConfirmDialog';import InfoIcon from '-/components/InfoIcon';import { useTranslation } from 'react-i18next';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import {+ getUserDataDir,+ loadExtensions,+ removeExtension,+ unZip,+} from '-/services/utils-io';+import AppConfig from '-/AppConfig';function SettingsExtensions() {const { t } = useTranslation();- const { switchCurrentLocationType } = useCurrentLocationContext();+ const { currentLocation } = useCurrentLocationContext();const { uploadFilesAPI } = useIOActionsContext();const fileInputRef = useRef<HTMLInputElement>(null);const [removeExtDialogOpened, setRemoveExtDialogOpened] =@@ -61,33 +67,30 @@ function SettingsExtensions() {const handleFileInputChange = (selection: any) => {const files: File[] = Array.from(selection.currentTarget.files);- PlatformIO.getUserDataDir().then((dataDir) => {+ getUserDataDir().then((dataDir) => {dispatch(AppActions.resetProgress());dispatch(AppActions.toggleUploadDialog());- PlatformIO.disableObjectStoreSupport();- PlatformIO.disableWebdavSupport();- const destinationPath =- dataDir + PlatformIO.getDirSeparator() + 'tsplugins';+ const destinationPath = dataDir + AppConfig.dirSeparator + 'tsplugins';uploadFilesAPI(files, destinationPath, onUploadProgress, false).then((fsEntries: Array<TS.FileSystemEntry>) => {const targetPath =destinationPath +- PlatformIO.getDirSeparator() ++ AppConfig.dirSeparator +'@tagspaces' +- PlatformIO.getDirSeparator() ++ AppConfig.dirSeparator +'extensions';const promises = fsEntries.map((fsEntry) =>- PlatformIO.unZip(fsEntry.path, targetPath),+ unZip(fsEntry.path, targetPath),);return Promise.all(promises).then((paths) => {- PlatformIO.loadExtensions();- paths.forEach((path) => PlatformIO.deleteFilePromise(path));- return switchCurrentLocationType();+ loadExtensions();+ paths.forEach((path) => currentLocation.deleteFilePromise(path));+ return true;});}).catch((error) => {console.log('uploadFiles', error);- return switchCurrentLocationType();+ return true;});});};@@ -157,7 +160,7 @@ function SettingsExtensions() {true,),);- PlatformIO.loadExtensions();+ loadExtensions();} else {dispatch(AppActions.updateExtension({@@ -213,7 +216,7 @@ function SettingsExtensions() {removeExtDialogOpened.extensionId,),);- PlatformIO.removeExtension(removeExtDialogOpened.extensionId);+ removeExtension(removeExtDialogOpened.extensionId);}}}cancelDialogTID="cancelRemoveExtDialogTID"diff --git a/src/renderer/components/dialogs/settings/SettingsFileTypes.tsx b/src/renderer/components/dialogs/settings/SettingsFileTypes.tsxindex c28737086..dd5e5d644 100644--- a/src/renderer/components/dialogs/settings/SettingsFileTypes.tsx+++ b/src/renderer/components/dialogs/settings/SettingsFileTypes.tsx@@ -49,11 +49,12 @@ import {isDevMode,} from '-/reducers/settings';import ConfirmDialog from '-/components/dialogs/ConfirmDialog';-import PlatformFacade from '-/services/platform-facade';import { AppDispatch, getExtensions } from '-/reducers/app';import { supportedFileTypes as defaultSupportedFileTypes } from '-/extension-config';import useFirstRender from '-/utils/useFirstRender';import { useTranslation } from 'react-i18next';+import { getUserDataDir } from '-/services/utils-io';+import AppConfig from '-/AppConfig';const PREFIX = 'SettingsFileTypes';@@ -95,7 +96,7 @@ function SettingsFileTypes() {useState<boolean>(false);const settingsFileTypeRef = useRef<TableVirtuosoHandle>(null);- const [ignored, forceUpdate] = useReducer((x) => x + 1, 0);+ const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);const firstRender = useFirstRender();const extensions = useSelector(getExtensions);@@ -373,9 +374,9 @@ function SettingsFileTypes() {(ext) => ext.extensionId === event.target.value,);if (extension.extensionExternal) {- PlatformFacade.getUserDataDir().then((dataDir) => {+ getUserDataDir().then((dataDir) => {const externalExtensionPath =- dataDir + PlatformFacade.getDirSeparator() + 'tsplugins';+ dataDir + AppConfig.dirSeparator + 'tsplugins';updateItems(item,'extensionExternalPath',diff --git a/src/renderer/components/dialogs/settings/SettingsGeneral.tsx b/src/renderer/components/dialogs/settings/SettingsGeneral.tsxindex 86834fb27..4a6863a49 100644--- a/src/renderer/components/dialogs/settings/SettingsGeneral.tsx+++ b/src/renderer/components/dialogs/settings/SettingsGeneral.tsx@@ -44,12 +44,12 @@ import ColorPickerDialog from '-/components/dialogs/ColorPickerDialog';import PerspectiveSelector from '-/components/PerspectiveSelector';import TransparentBackground from '-/components/TransparentBackground';import { BetaLabel } from '-/components/HelperComponents';-import PlatformIO from '-/services/platform-facade';import { PerspectiveIDs } from '-/perspectives';import { AppDispatch } from '-/reducers/app';import { styled } from '@mui/material/styles';import { useTranslation } from 'react-i18next';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { setLanguage } from '-/services/utils-io';const PREFIX = 'SettingsGeneral';@@ -128,7 +128,7 @@ function SettingsGeneral() {onChange={(event: any) => {return i18n.changeLanguage(event.target.value).then(() => {dispatch(SettingsActions.setLanguage(event.target.value));- PlatformIO.setLanguage(event.target.value);+ setLanguage(event.target.value);return true;});}}diff --git a/src/renderer/components/dialogs/settings/SettingsKeyBindings.tsx b/src/renderer/components/dialogs/settings/SettingsKeyBindings.tsxindex 261c66e98..6d5ae1f9d 100644--- a/src/renderer/components/dialogs/settings/SettingsKeyBindings.tsx+++ b/src/renderer/components/dialogs/settings/SettingsKeyBindings.tsx@@ -24,7 +24,6 @@ import Switch from '@mui/material/Switch';import ListItem from '@mui/material/ListItem';import ListItemText from '@mui/material/ListItemText';import { isStr } from '@tagspaces/tagspaces-common/misc';-import PlatformIO from '-/services/platform-facade';import {actions as SettingsActions,getKeyBindings,@@ -34,6 +33,8 @@ import DefaultSettings from '-/reducers/settings-default';import { AppDispatch } from '-/reducers/app';import { useTranslation } from 'react-i18next';import Typography from '@mui/material/Typography';+import { setGlobalShortcuts } from '-/services/utils-io';+import AppConfig from '-/AppConfig';const PREFIX = 'SettingsKeyBindings';@@ -60,12 +61,12 @@ function SettingsKeyBindings() {const setGlobalKeyBinding = (value) => {dispatch(SettingsActions.setGlobalKeyBinding(value));- PlatformIO.setGlobalShortcuts(value);+ setGlobalShortcuts(value);};return (<Root className={classes.keyBinding} noValidate autoComplete="off">- <Typography variant="body2">+ <Typography variant="body2" style={{ marginBottom: 10 }}>The following key names can be used for defining key bindings:{' '}<Typography variant="overline">ctrl, command, alt, option, shift, space, backspace, escape, enter,@@ -73,15 +74,17 @@ function SettingsKeyBindings() {</Typography>{' '}plus letters and digits from your keyboard.</Typography>- <ListItem style={{ paddingLeft: 0, paddingRight: 0 }}>- <ListItemText primary={t('core:enableGlobalKeyboardShortcuts')} />- <Switch- onClick={() => {- setGlobalKeyBinding(!globalKeyBindingEnabled);- }}- checked={globalKeyBindingEnabled}- />- </ListItem>+ {AppConfig.isElectron && (+ <ListItem style={{ paddingLeft: 0, paddingRight: 0 }}>+ <ListItemText primary={t('core:enableGlobalKeyboardShortcuts')} />+ <Switch+ onClick={() => {+ setGlobalKeyBinding(!globalKeyBindingEnabled);+ }}+ checked={globalKeyBindingEnabled}+ />+ </ListItem>+ )}{keyBindings.map((keyBinding) => {const defaultBinding = DefaultSettings.keyBindings.filter((kb) => kb.name === keyBinding.name,diff --git a/src/renderer/components/menus/DirectoryMenu.tsx b/src/renderer/components/menus/DirectoryMenu.tsxindex 46fa36473..ede3cdc9a 100644--- a/src/renderer/components/menus/DirectoryMenu.tsx+++ b/src/renderer/components/menus/DirectoryMenu.tsx@@ -17,7 +17,7 @@*/import React, { useRef } from 'react';-import { useSelector, useDispatch } from 'react-redux';+import { useDispatch } from 'react-redux';import Menu from '@mui/material/Menu';import { formatDateTime4Tag } from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';@@ -29,17 +29,18 @@ import {generateSharingLink,} from '@tagspaces/tagspaces-common/paths';import { Pro } from '-/pro';-import PlatformIO from '-/services/platform-facade';import { actions as AppActions, AppDispatch } from '-/reducers/app';import FileUploadContainer, {FileUploadContainerRef,} from '-/components/FileUploadContainer';-import { TS } from '-/tagspaces.namespace';-import { getRelativeEntryPath, toFsEntry } from '-/services/utils-io';+import {+ createNewInstance,+ getRelativeEntryPath,+ openDirectoryMessage,+ readMacOSTags,+} from '-/services/utils-io';import { PerspectiveIDs } from '-/perspectives';-import PlatformFacade from '-/services/platform-facade';import { getDirectoryMenuItems } from '-/perspectives/common/DirectoryMenuItems';-import { getLocations } from '-/reducers/locations';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';@@ -72,7 +73,7 @@ function DirectoryMenu(props: Props) {const { openEntry } = useOpenedEntryContext();const { selectedEntries, setSelectedEntries } = useSelectedEntriesContext();const { addTags } = useTaggingActionsContext();- const { currentLocation, readOnlyMode, getLocationPath } =+ const { currentLocation, readOnlyMode, getLocationPath, findLocation } =useCurrentLocationContext();const { showNotification } = useNotificationContext();const {@@ -99,7 +100,7 @@ function DirectoryMenu(props: Props) {perspectiveMode,} = props;const directoryPath = props.directoryPath || currentDirectoryPath;- const locations: Array<TS.Location> = useSelector(getLocations);+ //const locations: Array<CommonLocation> = useSelector(getLocations);const dispatch: AppDispatch = useDispatch();const toggleCreateDirectoryDialog = () => {@@ -131,12 +132,12 @@ function DirectoryMenu(props: Props) {}entryPath = selectedEntries[0].path;}- const tmpLoc = locations.find((location) => location.uuid === locationID);+ const tmpLoc = findLocation(locationID);return getLocationPath(tmpLoc).then((locationPath) => {const relativePath = getRelativeEntryPath(locationPath, entryPath);const folderName = extractDirectoryName(selectedEntries[0].name,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);return {url: generateSharingLink(locationID, undefined, relativePath),@@ -164,7 +165,7 @@ function DirectoryMenu(props: Props) {}function openDir() {- return openDirectory(directoryPath, currentLocation.uuid);+ return openDirectory(directoryPath);}function showProperties() {@@ -193,16 +194,7 @@ function DirectoryMenu(props: Props) {function showDeleteDirectoryDialog() {if (!selectedEntries.some((entry) => entry.path === directoryPath)) {- setSelectedEntries([- {- isFile: false,- name: directoryPath,- path: directoryPath,- tags: [],- size: 0,- lmdt: 0,- },- ]);+ setSelectedEntries([currentLocation.toFsEntry(directoryPath, false)]);}toggleDeleteMultipleEntriesDialog();}@@ -216,14 +208,14 @@ function DirectoryMenu(props: Props) {}function showInFileManager() {- PlatformIO.openDirectory(directoryPath);+ openDirectoryMessage(directoryPath);}function openInNewWindow() {generateFolderLink().then((sharingLink) => {const newInstanceLink =window.location.href.split('?')[0] + '?' + sharingLink.split('?')[1];- PlatformIO.createNewInstance(newInstanceLink);+ createNewInstance(newInstanceLink);});}@@ -243,7 +235,7 @@ Do you want to continue?`)toggleProgressDialog();const entryCallback = (entry) => {- PlatformFacade.readMacOSTags(entry.path)+ readMacOSTags(entry.path).then((tags) => {if (tags.length > 0) {addTags([entry.path], tags);@@ -251,10 +243,14 @@ Do you want to continue?`)return tags;}).catch((err) => {- console.warn('Error creating tags: ' + err);+ console.log('Error creating tags: ' + err);});};- Pro.MacTagsImport.importTags(directoryPath, entryCallback)+ Pro.MacTagsImport.importTags(+ directoryPath,+ currentLocation.listDirectoryPromise,+ entryCallback,+ ).then(() => {toggleProgressDialog();console.log('Import tags succeeded ' + directoryPath);@@ -266,7 +262,7 @@ Do you want to continue?`)return true;}).catch((err) => {- console.warn('Error importing tags: ' + err);+ console.log('Error importing tags: ' + err);toggleProgressDialog();});} else {@@ -303,9 +299,17 @@ Do you want to continue?`)AppConfig.endTagContainer +'.jpg';const newFilePath =- normalizePath(directoryPath) + PlatformIO.getDirSeparator() + fileName;-- renameFilePromise(filePath, newFilePath, undefined, false)+ normalizePath(directoryPath) ++ currentLocation.getDirSeparator() ++ fileName;++ renameFilePromise(+ filePath,+ newFilePath,+ currentLocation.uuid,+ undefined,+ false,+ ).then((newEntry) => {setReflectActions({action: 'add',@@ -353,21 +357,21 @@ Do you want to continue?`)function setFolderThumbnail() {const parentDirectoryPath = extractContainingDirectoryPath(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const parentDirectoryName = extractDirectoryName(parentDirectoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);copyFilePromise(getThumbFileLocationForDirectory(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),),getThumbFileLocationForDirectory(parentDirectoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),),t('core:thumbAlreadyExists', { directoryName: parentDirectoryName }),)@@ -381,7 +385,7 @@ Do you want to continue?`)}).catch((error) => {showNotification('Thumbnail creation failed.', 'default', true);- console.warn('Error setting Thumb for entry: ' + directoryPath, error);+ console.log('Error setting Thumb for entry: ' + directoryPath, error);return true;});}diff --git a/src/renderer/components/menus/FileMenu.tsx b/src/renderer/components/menus/FileMenu.tsxindex 9a4dfdfa3..0cba242f5 100644--- a/src/renderer/components/menus/FileMenu.tsx+++ b/src/renderer/components/menus/FileMenu.tsx@@ -41,8 +41,11 @@ import {generateSharingLink,extractTitle,} from '@tagspaces/tagspaces-common/paths';-import PlatformIO from '-/services/platform-facade';-import { getRelativeEntryPath, toFsEntry } from '-/services/utils-io';+import {+ createNewInstance,+ getRelativeEntryPath,+ openDirectoryMessage,+} from '-/services/utils-io';import { getKeyBindingObject } from '-/reducers/settings';import { Pro } from '-/pro';import { useSelector } from 'react-redux';@@ -62,7 +65,6 @@ import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';import MenuKeyBinding from '-/components/menus/MenuKeyBinding';-import PlatformFacade from '-/services/platform-facade';import { TS } from '-/tagspaces.namespace';import { generateClipboardLink } from '-/utils/dom';@@ -136,7 +138,7 @@ function FileMenu(props: Props) {const entryTitle = extractTitle(selectedEntries[0].name,!selectedEntries[0].isFile,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const clibboardItem = generateClipboardLink(sharingLink, entryTitle);@@ -178,10 +180,10 @@ function FileMenu(props: Props) {onClose();setFolderThumbnailPromise(selectedEntries[0].path) //selectedFilePath).then((thumbPath: string) => {- const entry: TS.FileSystemEntry = toFsEntry(+ const entry: TS.FileSystemEntry = currentLocation.toFsEntry(extractContainingDirectoryPath(selectedEntries[0].path,- PlatformFacade.getDirSeparator(),+ currentLocation?.getDirSeparator(),),false,);@@ -194,7 +196,7 @@ function FileMenu(props: Props) {}).catch((error) => {showNotification('Thumbnail creation failed.');- console.warn(+ console.log('Error setting Thumb for entry: ' + selectedEntries[0].path,error,);@@ -205,18 +207,22 @@ function FileMenu(props: Props) {function setFolderBackground() {onClose();let path =- PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()- ? PlatformIO.generateURLforPath(selectedFilePath, 604800) // 7 days+ currentLocation &&+ (currentLocation.haveObjectStoreSupport() ||+ currentLocation.haveWebDavSupport())+ ? currentLocation.generateURLforPath(selectedFilePath, 604800) // 7 days: selectedFilePath;const directoryPath = extractContainingDirectoryPath(selectedFilePath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);setFolderBackgroundPromise(path, directoryPath).then((directoryPath: string) => {- setBackgroundImageChange(toFsEntry(directoryPath, false));+ setBackgroundImageChange(+ currentLocation.toFsEntry(directoryPath, false),+ );/*dispatch(AppActions.setLastBackgroundImageChange(path, new Date().getTime()),);*/@@ -225,7 +231,7 @@ function FileMenu(props: Props) {}).catch((error) => {showNotification('Background creation failed.');- console.warn(+ console.log('Error setting Background for entry: ' + selectedFilePath,error,);@@ -248,9 +254,9 @@ function FileMenu(props: Props) {if (selectedFilePath) {const parentFolder = extractParentDirectoryPath(selectedFilePath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);- return openDirectory(parentFolder, currentLocation.uuid);+ return openDirectory(parentFolder);}}@@ -267,7 +273,7 @@ function FileMenu(props: Props) {const sharingLink = generateFileLink();const newInstanceLink =window.location.href.split('?')[0] + '?' + sharingLink.split('?')[1];- PlatformIO.createNewInstance(newInstanceLink);+ createNewInstance(newInstanceLink);}}@@ -326,8 +332,9 @@ function FileMenu(props: Props) {}if (!(- PlatformIO.haveObjectStoreSupport() ||- PlatformIO.haveWebDavSupport() ||+ (currentLocation &&+ (currentLocation.haveObjectStoreSupport() ||+ currentLocation.haveWebDavSupport())) ||AppConfig.isWeb) &&selectedEntries.length < 2@@ -352,7 +359,7 @@ function FileMenu(props: Props) {onClick={() => {onClose();if (selectedFilePath) {- PlatformIO.openDirectory(selectedFilePath);+ openDirectoryMessage(selectedFilePath);}}}>diff --git a/src/renderer/components/menus/LocationContextMenu.tsx b/src/renderer/components/menus/LocationContextMenu.tsxindex 620d80475..d84f45f38 100644--- a/src/renderer/components/menus/LocationContextMenu.tsx+++ b/src/renderer/components/menus/LocationContextMenu.tsx@@ -36,11 +36,11 @@ import { OpenNewWindowIcon, CloseIcon } from '-/components/CommonIcons';import { locationType } from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';import { actions as LocationActions } from '-/reducers/locations';-import { actions as AppActions, AppDispatch } from '-/reducers/app';-import PlatformIO from '-/services/platform-facade';+import { AppDispatch } from '-/reducers/app';import { useTranslation } from 'react-i18next';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { createNewInstance, openDirectoryMessage } from '-/services/utils-io';interface Props {setEditLocationDialogOpened: (open: boolean) => void;@@ -123,7 +123,7 @@ function LocationContextMenu(props: Props) {const showInFileManagerInt = () => {setLocationDirectoryContextMenuAnchorEl(null);getLocationPath(selectedLocation).then((path) =>- PlatformIO.openDirectory(path),+ openDirectoryMessage(path),);};@@ -138,7 +138,7 @@ function LocationContextMenu(props: Props) {const openInNewWindow = () => {setLocationDirectoryContextMenuAnchorEl(null);const sharingLink = generateSharingLink(selectedLocation.uuid);- PlatformIO.createNewInstance(+ createNewInstance(window.location.href.split('?')[0] + '?' + sharingLink.split('?')[1],);};diff --git a/src/renderer/components/menus/LocationMenu.tsx b/src/renderer/components/menus/LocationMenu.tsxindex 164470371..749f9c81e 100644--- a/src/renderer/components/menus/LocationMenu.tsx+++ b/src/renderer/components/menus/LocationMenu.tsx@@ -17,7 +17,6 @@*/import React, { useState } from 'react';-import { useSelector } from 'react-redux';import Menu from '@mui/material/Menu';import MenuItem from '@mui/material/MenuItem';import { LocalLocationIcon, CloudLocationIcon } from '-/components/CommonIcons';@@ -28,11 +27,10 @@ import Tooltip from '-/components/Tooltip';import IconButton from '@mui/material/IconButton';import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';import { locationType } from '@tagspaces/tagspaces-common/misc';-import { getLocations } from '-/reducers/locations';-import { TS } from '-/tagspaces.namespace';import { useTheme } from '@mui/material/styles';import { useTranslation } from 'react-i18next';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { CommonLocation } from '-/utils/CommonLocation';interface Props {menuAnchorEl?: Element;@@ -41,9 +39,10 @@ interface Props {function LocationMenu(props: Props) {const { t } = useTranslation();const theme = useTheme();- const { openLocation, currentLocation } = useCurrentLocationContext();+ const { locations, openLocation, currentLocation } =+ useCurrentLocationContext();//const dispatch: AppDispatch = useDispatch();- const locations: Array<TS.Location> = useSelector(getLocations);+ //const locations: Array<CommonLocation> = useSelector(getLocations);const [locationChooserMenuAnchorEl, setLocationChooserMenuAnchorEl] =useState<null | HTMLElement>(null);@@ -104,7 +103,7 @@ function LocationMenu(props: Props) {>{t('core:chooseLocation')}</ListSubHeader>- {locations.map((location: TS.Location) => (+ {locations.map((location: CommonLocation) => (<MenuItemdata-tid="folderContainerMenuOpenLocation"key={location.uuid}diff --git a/src/renderer/hooks/CurrentLocationContextProvider.tsx b/src/renderer/hooks/CurrentLocationContextProvider.tsxindex 7d7edc9f3..d377cc9fc 100644--- a/src/renderer/hooks/CurrentLocationContextProvider.tsx+++ b/src/renderer/hooks/CurrentLocationContextProvider.tsx@@ -20,20 +20,18 @@ import React, {createContext,useEffect,useMemo,+ useReducer,useRef,useState,} from 'react';import { useDispatch, useSelector } from 'react-redux';import { AppDispatch } from '-/reducers/app';-import { TS } from '-/tagspaces.namespace';import { useTranslation } from 'react-i18next';import {actions as LocationActions,getDefaultLocationId,getLocations,} from '-/reducers/locations';-import PlatformIO from '-/services/platform-facade';-import { setLocationType } from '-/services/utils-io';import { clearAllURLParams, getURLParameter } from '-/utils/dom';import { locationType } from '@tagspaces/tagspaces-common/misc';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';@@ -41,30 +39,38 @@ import { useNotificationContext } from '-/hooks/useNotificationContext';import { getPersistTagsInSidecarFile } from '-/reducers/settings';import AppConfig from '../AppConfig';import versionMeta from '-/version.json';+import { CommonLocation } from '-/utils/CommonLocation';+import { getDevicePaths } from '-/services/utils-io';type CurrentLocationContextData = {- currentLocation: TS.Location;+ locations: CommonLocation[];+ currentLocation: CommonLocation;readOnlyMode: boolean;skipInitialDirList: boolean;persistTagsInSidecarFile: boolean;- getLocationPath: (location: TS.Location) => Promise<string>;- changeLocation: (location: TS.Location) => void;- editLocation: (location: TS.Location, openAfterEdit?: boolean) => void;+ getLocationPath: (location: CommonLocation) => Promise<string>;+ findLocation: (locationID: string) => CommonLocation;+ changeLocation: (location: CommonLocation, skipInitDirList?: boolean) => void;+ editLocation: (location: CommonLocation, openAfterEdit?: boolean) => void;addLocation: (- location: TS.Location,+ location: CommonLocation,openAfterCreate?: boolean,locationPosition?: number,) => void;- addLocations: (arrLocations: Array<TS.Location>, override?: boolean) => void;- openLocation: (location: TS.Location, skipInitialDirList?: boolean) => void;+ addLocations: (+ arrLocations: Array<CommonLocation>,+ override?: boolean,+ ) => void;+ openLocation: (+ location: CommonLocation,+ skipInitialDirList?: boolean,+ ) => void;closeLocation: (locationId: string) => void;closeAllLocations: () => void;- switchCurrentLocationType: () => Promise<boolean>;- switchLocationTypeByID: (locationId: string) => Promise<boolean>;changeLocationByID: (locationId: string) => void;openLocationById: (locationId: string, skipInitialDirList?: boolean) => void;- selectedLocation: TS.Location;- setSelectedLocation: (location: TS.Location) => void;+ selectedLocation: CommonLocation;+ setSelectedLocation: (location: CommonLocation) => void;getLocationPosition: (locationId: string) => number;locationDirectoryContextMenuAnchorEl: null | HTMLElement;setLocationDirectoryContextMenuAnchorEl: (el: HTMLElement) => void;@@ -72,11 +78,13 @@ type CurrentLocationContextData = {export const CurrentLocationContext = createContext<CurrentLocationContextData>({+ locations: undefined,currentLocation: undefined,readOnlyMode: false,skipInitialDirList: false,persistTagsInSidecarFile: true,getLocationPath: undefined,+ findLocation: undefined,changeLocation: () => {},editLocation: () => {},addLocation: () => {},@@ -84,12 +92,10 @@ export const CurrentLocationContext = createContext<CurrentLocationContextData>(openLocation: () => {},closeLocation: () => {},closeAllLocations: () => {},- switchCurrentLocationType: () => Promise.resolve(false),- switchLocationTypeByID: () => Promise.resolve(false),changeLocationByID: () => {},openLocationById: () => {},selectedLocation: undefined,- setSelectedLocation: () => {},+ setSelectedLocation: undefined,getLocationPosition: () => 0,locationDirectoryContextMenuAnchorEl: undefined,setLocationDirectoryContextMenuAnchorEl: () => {},@@ -106,24 +112,28 @@ export const CurrentLocationContextProvider = ({const dispatch: AppDispatch = useDispatch();const { t } = useTranslation();const { showNotification } = useNotificationContext();- const [currentLocation, setCurrentLocation] =- useState<TS.Location>(undefined);- const [selectedLocation, setSelectedLocation] =- useState<TS.Location>(undefined);+ const currentLocation = useRef<CommonLocation>(undefined);+ const selectedLocation = useRef<CommonLocation>(undefined);const skipInitialDirList = useRef<boolean>(false);+ const initLocations = useRef<boolean>(false);const [locationDirectoryContextMenuAnchorEl,setLocationDirectoryContextMenuAnchorEl,] = useState<null | HTMLElement>(null);- const locations: TS.Location[] = useSelector(getLocations);+ const locations: CommonLocation[] = useSelector(getLocations);const defaultLocationId = useSelector(getDefaultLocationId);const settingsPersistTagsInSidecarFile: boolean = useSelector(getPersistTagsInSidecarFile,);+ const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);useEffect(() => {- if (!currentLocation && defaultLocationId && defaultLocationId.length > 0) {+ if (+ !currentLocation.current &&+ defaultLocationId &&+ defaultLocationId.length > 0+ ) {const openDefaultLocation =!getURLParameter('tslid') &&!getURLParameter('tsdpath') &&@@ -141,18 +151,19 @@ export const CurrentLocationContextProvider = ({setDefaultLocations();} else {// check if current location exist (or is removed)- if (currentLocation) {+ if (currentLocation.current) {const location = locations.find(- (location) => location.uuid === currentLocation.uuid,+ (location) => location.uuid === currentLocation.current.uuid,);if (!location) {- closeLocation(currentLocation.uuid);+ setCurrentLocation(undefined);+ //closeLocation(currentLocation.current.uuid);}}}}, [locations]);- function getLocationPath(location: TS.Location): Promise<string> {+ function getLocationPath(location: CommonLocation): Promise<string> {let locationPath = '';if (location) {if (location.path) {@@ -181,13 +192,25 @@ export const CurrentLocationContextProvider = ({return Promise.resolve(locationPath);}+ function findLocation(locationID: string): CommonLocation {+ if (!locationID) {+ return currentLocation.current;+ }+ const loc = locations.find((l) => l.uuid === locationID);+ if (loc) {+ return loc;+ }+ return currentLocation.current;+ }+function setDefaultLocations() {- PlatformIO.getDevicePaths()- .then((devicePaths) => {- if (devicePaths) {- Object.keys(devicePaths).forEach((key) => {- addLocation(- {+ if (!initLocations.current) {+ initLocations.current = true;+ getDevicePaths()+ .then((devicePaths) => {+ if (devicePaths) {+ Object.keys(devicePaths).forEach((key) => {+ const location = new CommonLocation({uuid: getUuid(),type: locationType.TYPE_LOCAL,name: t(('core:' + key) as any) as string,@@ -195,18 +218,18 @@ export const CurrentLocationContextProvider = ({isDefault: false, // AppConfig.isWeb && devicePaths[key] === '/files/', // Used for the web ts demoisReadOnly: false,disableIndexing: false,- },- false,- );- });- }- return true;- })- .catch((ex) => console.log(ex));+ });+ addLocation(location, false);+ });+ }+ return true;+ })+ .catch((ex) => console.log(ex));+ }}function addLocation(- location: TS.Location,+ location: CommonLocation,openAfterCreate = true,locationPosition: number = undefined,) {@@ -219,8 +242,8 @@ export const CurrentLocationContextProvider = ({* @param arrLocations* @param override = true - if location exist override else skip*/- function addLocations(arrLocations: Array<TS.Location>, override = true) {- arrLocations.forEach((newLocation: TS.Location, idx, array) => {+ function addLocations(arrLocations: Array<CommonLocation>, override = true) {+ arrLocations.forEach((newLocation: CommonLocation, idx, array) => {const locationExist: boolean = locations.some((location) => location.uuid === newLocation.uuid,);@@ -233,16 +256,18 @@ export const CurrentLocationContextProvider = ({});}- function editLocation(location: TS.Location, openAfterEdit = true) {+ function setCurrentLocation(location) {+ currentLocation.current = location;+ forceUpdate();+ }++ function setSelectedLocation(location) {+ selectedLocation.current = location;+ forceUpdate();+ }++ function editLocation(location: CommonLocation, openAfterEdit = true) {dispatch(LocationActions.changeLocation(location));- if (PlatformIO.haveObjectStoreSupport()) {- // disableObjectStoreSupport to revoke objectStoreAPI cached object- PlatformIO.disableObjectStoreSupport();- }- if (PlatformIO.haveWebDavSupport()) {- // disableWebdavSupport to revoke cached object- PlatformIO.disableWebdavSupport();- }setCurrentLocation(location);if (openAfterEdit) {/*@@ -261,21 +286,29 @@ export const CurrentLocationContextProvider = ({}const readOnlyMode: boolean = useMemo(- () => currentLocation && currentLocation.isReadOnly,- [currentLocation],+ () => currentLocation.current && currentLocation.current.isReadOnly,+ [currentLocation.current],);const persistTagsInSidecarFile: boolean = useMemo(() => {const locationPersistTagsInSidecarFile =- currentLocation && currentLocation.persistTagsInSidecarFile;+ currentLocation.current &&+ currentLocation.current.persistTagsInSidecarFile;if (locationPersistTagsInSidecarFile !== undefined) {return locationPersistTagsInSidecarFile;}return settingsPersistTagsInSidecarFile;- }, [currentLocation, settingsPersistTagsInSidecarFile]);+ }, [currentLocation.current, settingsPersistTagsInSidecarFile]);- function changeLocation(location: TS.Location) {- if (!currentLocation || location.uuid !== currentLocation.uuid) {+ function changeLocation(+ location: CommonLocation,+ skipInitDirList: boolean = false,+ ) {+ skipInitialDirList.current = skipInitDirList;+ if (+ !currentLocation.current ||+ location.uuid !== currentLocation.current.uuid+ ) {if (location && location.name) {document.title = location.name + ' | ' + versionMeta.name;}@@ -284,95 +317,44 @@ export const CurrentLocationContextProvider = ({}function changeLocationByID(locationId: string) {- if (!currentLocation || locationId !== currentLocation.uuid) {- const location = locations.find(- (location) => location.uuid === locationId,- );+ if (+ !currentLocation.current ||+ locationId !== currentLocation.current.uuid+ ) {+ const location = findLocation(locationId);if (location) {setCurrentLocation(location);}}}- function switchLocationTypeByID(locationId: string) {- const location = locations.find((location) => location.uuid === locationId);- return setLocationType(location);- //return switchLocationType(location);- }-- /**- * @param location- * return Promise<currentLocationId> if location is changed or null if location and type is changed- */- /*function switchLocationType(location: TS.Location) {- if (location !== undefined) {- if (currentLocation === undefined) {- return setLocationType(location).then(() => null);- }- if (location.uuid !== currentLocation.uuid) {- if (location.type !== currentLocation.type) {- return setLocationType(location).then(() => null);- } else {- // handle the same location type but different location- return setLocationType(location).then(() => currentLocation.uuid);- }- }- }- return Promise.resolve(null);- }*/-- function switchCurrentLocationType() {- return setLocationType(currentLocation);- }-function openLocationById(locationId: string, skipInitDirList?: boolean) {- const location = locations.find((location) => location.uuid === locationId);+ const location = findLocation(locationId);if (location) {openLocation(location, skipInitDirList);}}function openLocation(- location: TS.Location,+ location: CommonLocation,skipInitDirList: boolean = false,) {- // stopWatching();skipInitialDirList.current = skipInitDirList;if (location.type === locationType.TYPE_CLOUD) {- PlatformIO.enableObjectStoreSupport(location)- .then(() => {- showNotification(- t('core:connectedtoObjectStore' as any) as string,- 'default',- true,- );- //dispatch(AppActions.setReadOnlyMode(location.isReadOnly || false));- changeLocation(location);- return true;- })- .catch((e) => {- console.log('connectedtoObjectStoreFailed', e);- showNotification(- t('core:connectedtoObjectStoreFailed' as any) as string,- 'warning',- true,- );- PlatformIO.disableObjectStoreSupport();- });- } else {- if (location.type === locationType.TYPE_WEBDAV) {- PlatformIO.enableWebdavSupport(location);- } else {- PlatformIO.disableObjectStoreSupport();- PlatformIO.disableWebdavSupport();- }- //dispatch(AppActions.setReadOnlyMode(location.isReadOnly || false));- changeLocation(location);+ showNotification(+ t('core:connectedtoObjectStore' as any) as string,+ 'default',+ true,+ );}+ changeLocation(location);}function closeLocation(locationId: string) {- if (currentLocation && currentLocation.uuid === locationId) {+ if (+ currentLocation.current &&+ currentLocation.current.uuid === locationId+ ) {locations.map((location) => {if (location.uuid === locationId) {// location needed evtl. to unwatch many loc. root folders if available@@ -398,16 +380,18 @@ export const CurrentLocationContextProvider = ({}function isCurrentLocation(uuid: string) {- return currentLocation && currentLocation.uuid === uuid;+ return currentLocation.current && currentLocation.current.uuid === uuid;}const context = useMemo(() => {return {- currentLocation,+ locations,+ currentLocation: currentLocation.current,readOnlyMode,skipInitialDirList: skipInitialDirList.current,persistTagsInSidecarFile,getLocationPath,+ findLocation,changeLocation,addLocation,addLocations,@@ -415,19 +399,18 @@ export const CurrentLocationContextProvider = ({openLocation,closeLocation,closeAllLocations,- switchCurrentLocationType,- switchLocationTypeByID,changeLocationByID,openLocationById,- selectedLocation,+ selectedLocation: selectedLocation.current,setSelectedLocation,locationDirectoryContextMenuAnchorEl,setLocationDirectoryContextMenuAnchorEl,getLocationPosition,};}, [- currentLocation,- selectedLocation,+ locations,+ currentLocation.current,+ selectedLocation.current,persistTagsInSidecarFile,skipInitialDirList.current,locationDirectoryContextMenuAnchorEl,diff --git a/src/renderer/hooks/DescriptionContextProvider.tsx b/src/renderer/hooks/DescriptionContextProvider.tsxindex 5e9e55969..4e5f0a3f9 100644--- a/src/renderer/hooks/DescriptionContextProvider.tsx+++ b/src/renderer/hooks/DescriptionContextProvider.tsx@@ -61,7 +61,7 @@ export const DescriptionContextProvider = ({}: DescriptionContextProviderProps) => {const { t } = useTranslation();const { openedEntry } = useOpenedEntryContext();- const { readOnlyMode } = useCurrentLocationContext();+ const { findLocation } = useCurrentLocationContext();const { showNotification } = useNotificationContext();const { setDescriptionChange } = useIOActionsContext();//const description = useRef<string>(openedEntry.meta?.description);@@ -95,18 +95,15 @@ export const DescriptionContextProvider = ({}, [openedEntry]);const saveDescription = () => {- if (readOnlyMode) {- return;- }- if (!Pro) {- showNotification(t('core:thisFunctionalityIsAvailableInPro'));- return;- }- if (!Pro.MetaOperations) {- showNotification(t('Saving description not supported'));- return;- }if (lastOpenedFile.current !== undefined) {+ const location = findLocation(lastOpenedFile.current.locationID);+ if (!location || location.isReadOnly) {+ return;+ }+ if (!Pro) {+ showNotification(t('core:thisFunctionalityIsAvailableInPro'));+ return;+ }// to reload descriptionlastOpenedFile.current = { ...lastOpenedFile.current };isChanged.current = false;@@ -115,7 +112,7 @@ export const DescriptionContextProvider = ({setDescriptionChange(lastOpenedFile.current,lastOpenedFile.current.meta?.description,- lastOpenedFile.current.locationId,+ lastOpenedFile.current.locationID,).then(() => {if (lastOpenedFile.current.path !== openedEntry.path) {lastOpenedFile.current = { ...openedEntry };diff --git a/src/renderer/hooks/DirectoryContentContextProvider.tsx b/src/renderer/hooks/DirectoryContentContextProvider.tsxindex 7dde64bef..8d33afe2c 100644--- a/src/renderer/hooks/DirectoryContentContextProvider.tsx+++ b/src/renderer/hooks/DirectoryContentContextProvider.tsx@@ -33,13 +33,12 @@ import {cleanFrontDirSeparator,extractContainingDirectoryPath,extractParentDirectoryPath,+ getMetaFileLocationForDir,+ getMetaFileLocationForFile,+ getThumbFileLocationForDirectory,+ getThumbFileLocationForFile,} from '@tagspaces/tagspaces-common/paths';-import PlatformIO from '-/services/platform-facade';-import {- getAllPropertiesPromise,- toFsEntry,- updateFsEntries,-} from '-/services/utils-io';+import { executePromisesInBatches, updateFsEntries } from '-/services/utils-io';import AppConfig from '-/AppConfig';import { PerspectiveIDs } from '-/perspectives';import { updateHistory } from '-/utils/dom';@@ -60,9 +59,9 @@ import { Pro } from '-/pro';import { defaultSettings as defaultGridSettings } from '-/perspectives/grid';import { defaultSettings as defaultListSettings } from '-/perspectives/list';import { useEditedEntryContext } from '-/hooks/useEditedEntryContext';-import { getDirMeta, loadCurrentDirMeta } from '-/services/meta-loader';import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';import { useEditedKanBanMetaContext } from '-/hooks/useEditedKanBanMetaContext';+import { CommonLocation } from '-/utils/CommonLocation';type DirectoryContentContextData = {currentLocationPath: string;@@ -94,7 +93,7 @@ type DirectoryContentContextData = {) => Promise<TS.FileSystemEntry[]>;enhanceDirectoryContent: (dirEntries,- isCloudLocation,+ location: CommonLocation,showDirs?: boolean,limit?: number,getDirMeta?: boolean,@@ -102,8 +101,8 @@ type DirectoryContentContextData = {) => any;openDirectory: (dirPath: string,- locationID?: string,showHiddenEntries?: boolean,+ location?: CommonLocation,) => Promise<boolean>;openCurrentDirectory: (showHiddenEntries?: boolean) => Promise<boolean>;clearDirectoryContent: () => void;@@ -126,6 +125,15 @@ type DirectoryContentContextData = {findFromSavedSearch: (uuid: string) => void;getDefaultPerspectiveSettings: (perspective: string) => TS.FolderSettings;getPerspective: () => TS.PerspectiveType;+ getAllPropertiesPromise: (+ entryPath: string,+ locationID?: string,+ ) => Promise<TS.FileSystemEntry>;+ loadCurrentDirMeta: (+ directoryPath: string,+ dirEntries: TS.FileSystemEntry[],+ pageFiles?: TS.FileSystemEntry[],+ ) => Promise<TS.FileSystemEntry[]>;};export const DirectoryContentContext =@@ -147,7 +155,7 @@ export const DirectoryContentContext =setSearchQuery: () => {},loadParentDirectoryContent: () => {},loadDirectoryContent: undefined,- enhanceDirectoryContent: () => {},+ enhanceDirectoryContent: undefined,openDirectory: undefined,openCurrentDirectory: undefined,clearDirectoryContent: () => {},@@ -167,6 +175,8 @@ export const DirectoryContentContext =findFromSavedSearch: () => {},getDefaultPerspectiveSettings: undefined,getPerspective: undefined,+ getAllPropertiesPromise: undefined,+ loadCurrentDirMeta: undefined,});export type DirectoryContentContextProviderProps = {@@ -181,9 +191,9 @@ export const DirectoryContentContextProvider = ({const {closeAllLocations,currentLocation,+ findLocation,skipInitialDirList,getLocationPath,- switchLocationTypeByID,} = useCurrentLocationContext();const { actions } = useEditedEntryContext();const { metaActions, setReflectMetaActions } = useEditedEntryMetaContext();@@ -230,7 +240,7 @@ export const DirectoryContentContextProvider = ({getLocationPath(currentLocation).then((locationPath) => {currentLocationPath.current = locationPath;if (!skipInitialDirList) {- return openDirectory(locationPath, currentLocation.uuid);+ return openDirectory(locationPath);}});manualPerspective.current = 'unspecified';@@ -306,45 +316,6 @@ export const DirectoryContentContextProvider = ({...action.entry,};}- // update ordered entries (KanBan) todo find better place for this- /*if (Pro && Pro.MetaOperations && action.oldEntryPath) {- const dirPath = extractContainingDirectoryPath(- action.entry.path,- PlatformIO.getDirSeparator(),- );- if (- cleanTrailingDirSeparator(- cleanFrontDirSeparator(currentDirectoryPath.current),- ) === cleanTrailingDirSeparator(cleanFrontDirSeparator(dirPath))- ) {- const oldName = extractFileName(- action.oldEntryPath,- PlatformIO.getDirSeparator(),- );- const dirMeta: TS.FileSystemEntryMeta =- await Pro.MetaOperations.getOrderEntryRenamed(- dirPath,- oldName,- action.entry.name,- );- if (dirMeta) {- await saveMetaDataPromise(dirPath, dirMeta);- directoryMeta.current = { ...dirMeta };- if (directoryMeta.current.customOrder) {- if (directoryMeta.current.customOrder.files) {- currentDirectoryFiles.current = [- ...directoryMeta.current.customOrder.files,- ];- }- if (directoryMeta.current.customOrder.folders) {- currentDirectoryDirs.current = [- ...directoryMeta.current.customOrder.folders,- ];- }- }- }- }- }*/if (cleanTrailingDirSeparator(currentDirectoryPath.current) ===cleanTrailingDirSeparator(action.entry.path)@@ -357,7 +328,7 @@ export const DirectoryContentContextProvider = ({} else if (action.action === 'move') {await reflectAddAction(action.entry);reflectDeleteAction(- toFsEntry(action.oldEntryPath, action.entry.isFile),+ currentLocation.toFsEntry(action.oldEntryPath, action.entry.isFile),);}}@@ -372,36 +343,42 @@ export const DirectoryContentContextProvider = ({if (actions && actions.length > 0) {let selected = [];for (const action of actions) {- if (action.action === 'add') {- if (- currentDirectoryEntries.current.some(- (entry) => entry.path === action.entry.path,- )- ) {- if (selectedEntries.length > 0) {- selected = [...selectedEntries, action.entry];- } else {- selected.push(action.entry);+ if (+ action.entry.path.indexOf(+ currentLocation?.getDirSeparator() + AppConfig.metaFolder,+ ) === -1+ ) {+ if (action.action === 'add') {+ if (+ currentDirectoryEntries.current.some(+ (entry) => entry.path === action.entry.path,+ )+ ) {+ if (selectedEntries.length > 0) {+ selected = [...selectedEntries, action.entry];+ } else {+ selected.push(action.entry);+ }+ updated = true;+ }+ } else if (action.action === 'delete') {+ let index = selectedEntries.findIndex(+ (e) => e.path === action.entry.path,+ );+ if (index !== -1) {+ selectedEntries.splice(index, 1);+ selected = [...selectedEntries];+ updated = true;+ }+ } else if (action.action === 'update') {+ let index = selectedEntries.findIndex(+ (e) => e.path === action.oldEntryPath,+ );+ if (index !== -1) {+ selectedEntries[index] = action.entry;+ selected = [...selectedEntries];+ updated = true;}- updated = true;- }- } else if (action.action === 'delete') {- let index = selectedEntries.findIndex(- (e) => e.path === action.entry.path,- );- if (index !== -1) {- selectedEntries.splice(index, 1);- selected = [...selectedEntries];- updated = true;- }- } else if (action.action === 'update') {- let index = selectedEntries.findIndex(- (e) => e.path === action.oldEntryPath,- );- if (index !== -1) {- selectedEntries[index] = action.entry;- selected = [...selectedEntries];- updated = true;}}}@@ -422,7 +399,7 @@ export const DirectoryContentContextProvider = ({} else {const dirPath = extractContainingDirectoryPath(entry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);if (cleanTrailingDirSeparator(@@ -539,7 +516,7 @@ export const DirectoryContentContextProvider = ({if (currentDirectoryPath.current !== undefined) {const parentDirectory = extractParentDirectoryPath(currentDirectoryPath.current,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);console.log('parentDirectory: ' +@@ -552,7 +529,7 @@ export const DirectoryContentContextProvider = ({cleanTrailingDirSeparator(currentLocationPath.current),)) {- openDirectory(parentDirectory, currentLocation.uuid);+ openDirectory(parentDirectory);} else {showNotification(t('core:parentDirNotInLocation'), 'warning', true);// dispatch(actions.setIsLoading(false));@@ -653,69 +630,71 @@ export const DirectoryContentContextProvider = ({}}- /*function updateThumbnailUrl(filePath: string, thumbUrl: string) {- const dirEntries = currentDirectoryEntries.current.map((entry) => {- if (entry.path === filePath) {- return { ...entry, thumbPath: thumbUrl };+ function loadMetaDirectoryContent(+ directoryPath: string,+ location: CommonLocation,+ showHiddenEntries = undefined,+ ): Promise<TS.FileSystemEntry[]> {+ if (selectedEntries.length > 0) {+ setSelectedEntries([]);+ }+ return getDirMeta(directoryPath, location).then((meta) => {+ if (meta) {+ directoryMeta.current = meta;+ } else {+ directoryMeta.current = getDefaultDirMeta();}- return entry;+ return loadDirectoryContentInt(+ directoryPath,+ location,+ showHiddenEntries,+ );});- setCurrentDirectoryEntries(dirEntries);- }*/+ }+ /**+ * @deprecated for loadDirMeta=true use loadMetaDirectoryContent instead+ * @param directoryPath+ * @param loadDirMeta+ * @param showHiddenEntries+ */function loadDirectoryContent(directoryPath: string,loadDirMeta = false,showHiddenEntries = undefined,): Promise<TS.FileSystemEntry[]> {- // console.debug('loadDirectoryContent:' + directoryPath);- //window.walkCanceled = false;-// dispatch(actions.setIsLoading(true));if (selectedEntries.length > 0) {setSelectedEntries([]);}if (loadDirMeta) {- return getDirMeta(directoryPath).then((meta) => {+ return getDirMeta(directoryPath, currentLocation).then((meta) => {if (meta) {directoryMeta.current = meta;} else {directoryMeta.current = getDefaultDirMeta();}- return loadDirectoryContentInt(directoryPath, showHiddenEntries);+ return loadDirectoryContentInt(+ directoryPath,+ currentLocation,+ showHiddenEntries,+ );});- /*const metaDirectory = getMetaDirectoryPath(directoryPath);- return PlatformIO.checkDirExist(metaDirectory).then((exist) => {- if (exist) {- //isMetaFolderExist.current = true;- const metaFilePath = getMetaFileLocationForDir(- directoryPath,- PlatformIO.getDirSeparator(),- );- return loadJSONFile(metaFilePath).then((fsEntryMeta) => {- isMetaLoaded.current = true;- if (fsEntryMeta) {- directoryMeta.current = fsEntryMeta;- } else {- directoryMeta.current = getDefaultDirMeta();- }- return loadDirectoryContentInt(directoryPath, showHiddenEntries);- });- } else {- directoryMeta.current = getDefaultDirMeta();- return loadDirectoryContentInt(directoryPath, showHiddenEntries);- }- });*/} else {isMetaLoaded.current = false;directoryMeta.current = getDefaultDirMeta();- return loadDirectoryContentInt(directoryPath, showHiddenEntries);+ return loadDirectoryContentInt(+ directoryPath,+ currentLocation,+ showHiddenEntries,+ );}}function loadDirectoryContentInt(directoryPath: string,+ location: CommonLocation,showHiddenEntries = undefined,): Promise<TS.FileSystemEntry[]> {showNotification(t('core:loading'), 'info', false);@@ -726,12 +705,13 @@ export const DirectoryContentContextProvider = ({: AppConfig.maxLoops,IsTruncated: false,};- return PlatformIO.listDirectoryPromise(- directoryPath,- [],- currentLocation ? currentLocation.ignorePatternPaths : [],- resultsLimit,- )+ return location+ .listDirectoryPromise(+ directoryPath,+ [],+ currentLocation ? currentLocation.ignorePatternPaths : [],+ resultsLimit,+ ).then((results) => {if (resultsLimit.IsTruncated) {//OPEN ISTRUNCATED dialog@@ -742,6 +722,7 @@ export const DirectoryContentContextProvider = ({return loadDirectorySuccess(directoryPath,results,+ location,showHiddenEntries,);}@@ -762,36 +743,33 @@ export const DirectoryContentContextProvider = ({showHiddenEntries = undefined,): Promise<boolean> {if (currentDirectoryPath.current !== undefined) {- return openDirectory(- currentDirectoryPath.current,- currentLocation.uuid,- showHiddenEntries,- );+ return openDirectory(currentDirectoryPath.current, showHiddenEntries);}return Promise.resolve(false);}function openDirectory(dirPath: string,- locationID: string = undefined,showHiddenEntries = undefined,+ location: CommonLocation = undefined,): Promise<boolean> {if (dirPath !== undefined) {- const currentLocationID = locationID ? locationID : currentLocation.uuid;- return switchLocationTypeByID(currentLocationID).then(() => {- const reloadMeta = currentDirectoryPath.current === dirPath;- return loadDirectoryContent(dirPath, true, showHiddenEntries).then(- (dirEntries) => {- if (dirEntries && reloadMeta) {- // load meta files (reload of the same directory is not handled from ThumbGenerationContextProvider)- return loadCurrentDirMeta(dirPath, dirEntries).then((entries) => {- updateCurrentDirEntries(entries);- return true;- });- }+ const reloadMeta =+ cleanTrailingDirSeparator(currentDirectoryPath.current) ===+ cleanTrailingDirSeparator(dirPath);+ return loadMetaDirectoryContent(+ dirPath,+ location || currentLocation,+ showHiddenEntries,+ ).then((dirEntries) => {+ if (dirEntries && reloadMeta) {+ // load meta files (reload of the same directory is not handled from ThumbGenerationContextProvider)+ return loadCurrentDirMeta(dirPath, dirEntries).then((entries) => {+ updateCurrentDirEntries(entries);return true;- },- );+ });+ }+ return true;});}return Promise.resolve(false);@@ -800,6 +778,7 @@ export const DirectoryContentContextProvider = ({function loadDirectorySuccess(directoryPath: string,dirEntries: TS.FileSystemEntry[],+ location: CommonLocation,showHiddenEntries = undefined,): TS.FileSystemEntry[] {hideNotifications(['error']);@@ -821,12 +800,11 @@ export const DirectoryContentContextProvider = ({directoryMeta.current.customOrder.folders;}}- } /*else {- currentPerspective.current = 'unspecified';- }*/+ }+const directoryContent = enhanceDirectoryContent(dirEntries,- currentLocation && currentLocation.type === locationType.TYPE_CLOUD,+ location,true,undefined,showHiddenEntries,@@ -837,7 +815,7 @@ export const DirectoryContentContextProvider = ({setCurrentDirectoryEntries(directoryContent);currentDirectoryPath.current = cleanTrailingDirSeparator(directoryPath);updateHistory(- { ...currentLocation, path: currentLocationPath.current },+ { ...location, path: currentLocationPath.current },directoryPath,);return directoryContent;@@ -862,44 +840,42 @@ export const DirectoryContentContextProvider = ({}}- const enhanceDirectoryContent = useMemo(() => {- return (- dirEntries,- isCloudLocation,- showDirs = true,- limit = undefined,- showHiddenEntries = undefined,- ) => {- const directoryContent = [];- const showHidden =- showHiddenEntries !== undefined- ? showHiddenEntries- : showUnixHiddenEntries;- dirEntries.map((entry) => {- if (!showHidden && entry.name.startsWith('.')) {- return true;- }-- if (!showDirs && !entry.isFile) {- return true;- }+ function enhanceDirectoryContent(+ dirEntries: TS.FileSystemEntry[],+ location: CommonLocation,+ showDirs = true,+ limit = undefined,+ showHiddenEntries = undefined,+ ): TS.FileSystemEntry[] {+ const directoryContent: TS.FileSystemEntry[] = [];+ const showHidden =+ showHiddenEntries !== undefined+ ? showHiddenEntries+ : showUnixHiddenEntries;+ dirEntries.map((entry) => {+ if (!showHidden && entry.name.startsWith('.')) {+ return true;+ }- if (limit !== undefined && directoryContent.length >= limit) {- return true;- }+ if (!showDirs && !entry.isFile) {+ return true;+ }- const enhancedEntry: TS.FileSystemEntry = enhanceEntry(- entry,- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),- );- directoryContent.push(enhancedEntry);+ if (limit !== undefined && directoryContent.length >= limit) {return true;- });+ }- return directoryContent;- };- }, [showUnixHiddenEntries]);+ const enhancedEntry: TS.FileSystemEntry = enhanceEntry(+ entry,+ AppConfig.tagDelimiter,+ location?.getDirSeparator(),+ );+ directoryContent.push({ ...enhancedEntry, locationID: location.uuid });+ return true;+ });++ return directoryContent;+ }const perspective = useMemo(() => getPerspective(),@@ -939,7 +915,7 @@ export const DirectoryContentContextProvider = ({setReflectMetaActions(action);}).catch((error) => {- console.warn(+ console.log('Error getting properties for entry: ' + directory + ' - ' + error,);});@@ -1059,32 +1035,312 @@ export const DirectoryContentContextProvider = ({});}- /*function toggleDirVisibility(- dir: TS.OrderVisibilitySettings,- parentDirPath: string = undefined,- update: boolean = true,+ /**+ * get full entry properties - with full description+ */+ function getAllPropertiesPromise(+ entryPath: string,+ locationID: string = undefined,+ ): Promise<TS.FileSystemEntry> {+ const location = locationID ? findLocation(locationID) : currentLocation;+ return location+ .getPropertiesPromise(entryPath)+ .then((entryProps: TS.FileSystemEntry) => {+ if (entryProps) {+ const entry = { ...entryProps, locationID: location.uuid };+ if (!entryProps.isFile) {+ return getEnhancedDir(entry);+ }+ return getEnhancedFile(entry);+ }+ console.log('Error getting props for ' + entryPath);+ return undefined;+ });+ }++ // meta-loader+ function getMetaForEntry(+ entry: TS.FileSystemEntry,+ ): Promise<TS.FileSystemEntry> {+ const location = findLocation(entry.locationID);+ if (!location) {+ return Promise.resolve(entry);+ }+ const metaPromise = entry.isFile+ ? loadMetaForFile(entry.path, location, entry.meta)+ : loadMetaForDir(entry.path, location, entry.meta);+ return metaPromise.then((meta) => {+ if (meta) {+ return enhanceEntry(+ {+ ...entry,+ meta: {+ ...(entry.meta && entry.meta),+ ...meta,+ // description: getDescriptionPreview(meta.description, 200),+ },+ },+ AppConfig.tagDelimiter,+ location?.getDirSeparator(),+ );+ }+ });+ }++ function loadMetaForDir(+ dirPath: string,+ location: CommonLocation,+ metaAdd?,): Promise<TS.FileSystemEntryMeta> {- if (Pro && Pro.MetaOperations) {- return Pro.MetaOperations.toggleDirectoryVisibility(- parentDirPath ? parentDirPath : currentDirectoryPath.current,- {- name: dir.name,- uuid: dir.uuid,- },- ).then((meta: TS.FileSystemEntryMeta) => {+ return location+ .loadJSONFile(+ getMetaFileLocationForDir(dirPath, location.getDirSeparator()),+ )+ .then((meta: TS.FileSystemEntryMeta) => {if (meta) {- directoryMeta.current = meta;- currentDirectoryDirs.current = [- ...directoryMeta.current.customOrder.folders,- ];- if (update) {- forceUpdate();- }+ return {+ ...(metaAdd && metaAdd),+ ...meta,+ // description: getDescriptionPreview(meta.description, 200),+ };+ }+ return undefined;+ });+ }++ function loadMetaForFile(+ filePath: string,+ location: CommonLocation,+ metaAdd?,+ ): Promise<TS.FileSystemEntryMeta> {+ return location+ .loadJSONFile(+ getMetaFileLocationForFile(filePath, location.getDirSeparator()),+ )+ .then((meta: TS.FileSystemEntryMeta) => {+ if (meta) {+ return {+ ...(metaAdd && metaAdd),+ ...meta,+ // description: getDescriptionPreview(meta.description, 200),+ };}- return meta;+ return undefined;});+ }++ function loadCurrentDirMeta(+ directoryPath: string,+ dirEntries: TS.FileSystemEntry[],+ pageFiles?: TS.FileSystemEntry[],+ ): Promise<TS.FileSystemEntry[]> {+ return currentLocation+ .listMetaDirectoryPromise(directoryPath)+ .then((meta) => {+ const dirEntriesPromises = dirEntries+ .filter((entry) => !entry.isFile)+ .map((entry) => getEnhancedDir(entry));+ const files = pageFiles+ ? pageFiles+ : dirEntries.filter((entry) => entry.isFile);+ const fileEntriesPromises = getFileEntriesPromises(files, meta);+ const thumbs = getThumbs(files, meta);+ return getEntries([+ ...dirEntriesPromises,+ ...fileEntriesPromises,+ ...thumbs,+ ]);+ })+ .catch((ex) => {+ console.log(ex);+ return undefined;+ });+ }++ function getFileEntriesPromises(+ pageFiles: TS.FileSystemEntry[],+ meta: Array<any>,+ ): Promise<TS.FileSystemEntry>[] {+ return pageFiles.map((entry) => {+ const metaFilePath = getMetaFileLocationForFile(+ entry.path,+ currentLocation?.getDirSeparator(),+ );+ if (+ // check if metaFilePath exist in listMetaDirectory content+ meta.some((metaFile) => metaFilePath.endsWith(metaFile.path)) &&+ // !checkEntryExist(entry.path) &&+ entry.path.indexOf(+ AppConfig.metaFolder + currentLocation?.getDirSeparator(),+ ) === -1+ ) {+ return getMetaForEntry(entry);+ }+ return Promise.resolve(entry); //Promise.resolve({ [entry.path]: undefined });+ });+ }++ function getEntries(metaPromises): Promise<TS.FileSystemEntry[]> {+ // const catchHandler = (error) => undefined;+ //return Promise.all(metaPromises.map((promise) => promise.catch(catchHandler)))+ return executePromisesInBatches(metaPromises, 100)+ .then((entries: TS.FileSystemEntry[]) => {+ return entries;+ })+ .catch((err) => {+ console.log('err updateEntries:', err);+ return undefined;+ });+ }++ function getThumbs(+ pageFiles: TS.FileSystemEntry[],+ meta: Array<any>,+ ): Promise<TS.FileSystemEntry>[] {+ return pageFiles.map((entry) =>+ Promise.resolve(setThumbForEntry(entry, meta)),+ );+ }++ function setThumbForEntry(+ entry: TS.FileSystemEntry,+ meta: Array<any>, //TS.FileSystemEntryMeta[], -> todo extra path in meta+ ): TS.FileSystemEntry {+ const thumbEntry = { ...entry, tags: [] };+ let thumbPath = getThumbFileLocationForFile(+ entry.path,+ currentLocation?.getDirSeparator(),+ false,+ );+ const metaFile = meta.find((m) => thumbPath && thumbPath.endsWith(m.path));+ if (thumbPath && metaFile) {+ thumbEntry.meta = { id: getUuid(), thumbPath }; //{ ...metaFile, thumbPath };+ if (+ currentLocation?.haveObjectStoreSupport() ||+ currentLocation?.haveWebDavSupport()+ ) {+ if (thumbPath && thumbPath.startsWith('/')) {+ thumbPath = thumbPath.substring(1);+ }++ thumbPath = currentLocation.generateURLforPath(thumbPath, 604800);+ if (thumbPath) {+ thumbEntry.meta = { id: getUuid(), thumbPath };+ }+ }+ }+ return thumbEntry;+ }++ function getEnhancedDir(+ entry: TS.FileSystemEntry,+ ): Promise<TS.FileSystemEntry> {+ if (!entry) {+ return Promise.resolve(undefined);+ }+ if (entry.isFile) {+ return Promise.reject(+ new Error('getEnhancedDir accept dir only:' + entry.path),+ );}- }*/+ if (entry.name === AppConfig.metaFolder) {+ return Promise.resolve(undefined);+ }+ const location = findLocation(entry.locationID);+ return getDirMeta(entry.path, location).then((meta) => ({+ ...entry,+ meta,+ }));+ }++ function getEnhancedFile(+ entry: TS.FileSystemEntry,+ ): Promise<TS.FileSystemEntry> {+ if (!entry) {+ return Promise.resolve(undefined);+ }+ if (!entry.isFile) {+ return Promise.reject(+ new Error('getEnhancedFile accept file only:' + entry.path),+ );+ }++ const location = findLocation(entry.locationID);++ const thumbFilePath = getThumbFileLocationForFile(+ entry.path,+ location.getDirSeparator(),+ false,+ );++ return location.checkFileExist(thumbFilePath).then((exist) => {+ const metaProps = exist ? { thumbPath: thumbFilePath } : {};++ const metaFilePath = getMetaFileLocationForFile(+ entry.path,+ location.getDirSeparator(),+ );++ try {+ return location+ .loadJSONFile(metaFilePath)+ .then((meta: TS.FileSystemEntryMeta) => {+ if (meta) {+ return enhanceEntry(+ { ...entry, meta: { ...meta, ...metaProps } },+ AppConfig.tagDelimiter,+ location.getDirSeparator(),+ );+ }+ return enhanceEntry(+ { ...entry, meta: { ...metaProps } },+ AppConfig.tagDelimiter,+ location.getDirSeparator(),+ );+ });+ } catch (e) {+ return enhanceEntry(+ { ...entry, meta: { ...metaProps } },+ AppConfig.tagDelimiter,+ location.getDirSeparator(),+ );+ }+ });+ }++ function getDirMeta(+ dirPath: string,+ location: CommonLocation,+ ): Promise<TS.FileSystemEntryMeta> {+ return location.listMetaDirectoryPromise(dirPath).then((meta) => {+ const metaFilePath = getMetaFileLocationForDir(+ dirPath,+ location?.getDirSeparator(),+ );+ const thumbDirPath = getThumbFileLocationForDirectory(+ dirPath,+ location?.getDirSeparator(),+ );+ let thumbPath;+ if (meta.some((metaFile) => thumbDirPath.endsWith(metaFile.path))) {+ thumbPath =+ location.haveObjectStoreSupport() || location.haveWebDavSupport()+ ? location.getURLforPath(thumbDirPath)+ : thumbDirPath;+ }+ if (+ meta.some((metaFile) => metaFilePath.endsWith(metaFile.path)) &&+ dirPath.indexOf(AppConfig.metaFolder + location?.getDirSeparator()) ===+ -1+ ) {+ return loadMetaForDir(dirPath, location, { thumbPath });+ }+ if (thumbPath) {+ return { id: '', thumbPath, lastUpdated: new Date().getTime() };+ }+ return undefined;+ });+ }const context = useMemo(() => {return {@@ -1125,6 +1381,8 @@ export const DirectoryContentContextProvider = ({exitSearchMode,findFromSavedSearch,getDefaultPerspectiveSettings,+ getAllPropertiesPromise,+ loadCurrentDirMeta,};}, [currentLocation,diff --git a/src/renderer/hooks/EditedEntryContextProvider.tsx b/src/renderer/hooks/EditedEntryContextProvider.tsxindex c476e9e66..af6d9caeb 100644--- a/src/renderer/hooks/EditedEntryContextProvider.tsx+++ b/src/renderer/hooks/EditedEntryContextProvider.tsx@@ -20,15 +20,16 @@ import React, { createContext, useMemo, useReducer, useRef } from 'react';import { extractTagsAsObjects } from '@tagspaces/tagspaces-common/paths';import { TS } from '-/tagspaces.namespace';import AppConfig from '-/AppConfig';-import PlatformIO from '-/services/platform-facade';-import { getAllPropertiesPromise } from '-/services/utils-io';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';type EditedEntryContextData = {actions: TS.EditAction[];- reflectUpdateMeta: (...path: string[]) => void;+ reflectUpdateMeta: (...entries: TS.FileSystemEntry[]) => void;setReflectActions: (...actionsArray: TS.EditAction[]) => void;reflectDeleteEntries: (...entries: TS.FileSystemEntry[]) => void;- reflectAddEntryPath: (...paths: string[]) => Promise<boolean>;+ reflectAddEntryPath: (+ ...entriesPromises: Promise<TS.FileSystemEntry>[]+ ) => Promise<boolean>;reflectAddEntry: (entry: TS.FileSystemEntry, open?: boolean) => void;};@@ -49,6 +50,7 @@ export const EditedEntryContextProvider = ({children,}: EditedEntryContextProviderProps) => {const actions = useRef<TS.EditAction[]>(undefined);+ //const { getAllPropertiesPromise } = useDirectoryContentContext(); // cannot be injected here!const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);@@ -70,39 +72,31 @@ export const EditedEntryContextProvider = ({forceUpdate();}- function reflectUpdateMeta(...path: string[]) {- const promises: Promise<TS.EditAction>[] = [];- for (let i = 0; i < path.length; i++) {- promises.push(- getAllPropertiesPromise(path[i]).then((fsEntry: TS.FileSystemEntry) => {- const currentAction: TS.EditAction = {- action: 'update',- entry: fsEntry,- oldEntryPath: fsEntry.path,- };- return currentAction;- }),- );- }- Promise.all(promises).then((actionsArray) => {- actions.current = actionsArray;- forceUpdate();- });+ function reflectUpdateMeta(...entries: TS.FileSystemEntry[]) {+ actions.current = entries.map((fsEntry) => ({+ action: 'update',+ entry: fsEntry,+ oldEntryPath: fsEntry.path,+ }));+ forceUpdate();}- function reflectAddEntryPath(...paths: string[]): Promise<boolean> {- const entriesPromises = paths.map((path) => getAllPropertiesPromise(path));+ function reflectAddEntryPath(+ ...entriesPromises: Promise<TS.FileSystemEntry>[]+ ): Promise<boolean> {+ //const entriesPromises = paths.map((path) => getAllPropertiesPromise(path));return Promise.all(entriesPromises).then((entries) => {- const actions: TS.EditAction[] = entries.map((entry) => ({- action: 'add',- entry: entry,- }));- setReflectActions(...actions);+ const actions: TS.EditAction[] = entries+ .filter((entry) => entry)+ .map((entry) => ({+ action: 'add',+ entry: entry,+ }));+ if (actions.length > 0) {+ setReflectActions(...actions);+ }return true;});- /*getAllPropertiesPromise(path).then((fsEntry: TS.FileSystemEntry) =>- reflectAddEntry(fsEntry),- );*/}/**@@ -112,11 +106,7 @@ export const EditedEntryContextProvider = ({*/function reflectAddEntry(entry: TS.FileSystemEntry, open = true) {if (!entry.tags || entry.tags.length === 0) {- entry.tags = extractTagsAsObjects(- entry.name,- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),- );+ entry.tags = extractTagsAsObjects(entry.name, AppConfig.tagDelimiter);}const currentAction: TS.EditAction = {action: 'add',diff --git a/src/renderer/hooks/FSWatcherContextProvider.tsx b/src/renderer/hooks/FSWatcherContextProvider.tsxindex ef97533d0..e898c49b9 100644--- a/src/renderer/hooks/FSWatcherContextProvider.tsx+++ b/src/renderer/hooks/FSWatcherContextProvider.tsx@@ -18,7 +18,6 @@import React, { createContext, useEffect, useMemo, useRef } from 'react';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';-import PlatformIO from '-/services/platform-facade';import AppConfig from '-/AppConfig';import {extractContainingDirectoryPath,@@ -27,10 +26,11 @@ import {import { locationType } from '@tagspaces/tagspaces-common/misc';import { PerspectiveIDs } from '-/perspectives';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';-import { toFsEntry } from '-/services/utils-io';import { Changed } from '../../main/chokidarWatcher';import { useEditedEntryContext } from '-/hooks/useEditedEntryContext';import { TS } from '-/tagspaces.namespace';+import { watchFolderMessage } from '-/services/utils-io';+import { Pro } from '-/pro';type FSWatcherContextData = {ignored: string[];@@ -61,6 +61,7 @@ export const FSWatcherContextProvider = ({}: FSWatcherContextProviderProps) => {const { currentLocation } = useCurrentLocationContext();const {+ getAllPropertiesPromise,currentDirectoryEntries,loadDirectoryContent,currentDirectoryPath,@@ -89,10 +90,16 @@ export const FSWatcherContextProvider = ({}, [currentLocation, currentDirectoryPath]);function watchFolder(locationPath, depth) {- console.log('Start watching: ' + locationPath);- stopWatching();- watchingFolderPath.current = locationPath;- PlatformIO.watchFolder(locationPath, depth);+ if (+ Pro &&+ !currentLocation.haveObjectStoreSupport() &&+ !currentLocation.haveWebDavSupport()+ ) {+ console.log('Start watching: ' + locationPath);+ stopWatching();+ watchingFolderPath.current = locationPath;+ watchFolderMessage(locationPath, depth);+ }}function executeBatchActions() {@@ -114,7 +121,11 @@ export const FSWatcherContextProvider = ({return;}// console.log(`ignored list:` + JSON.stringify(ignored.current));- const pathParts = path.split(PlatformIO.getDirSeparator());+ const pathParts = path.split(+ currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator,+ );for (let i = 0; i < ignored.current.length; i++) {if (path.startsWith(ignored.current[i]) ||@@ -142,29 +153,29 @@ export const FSWatcherContextProvider = ({) {actionsQueue.push({action: 'delete',- entry: toFsEntry(path, false),+ entry: currentLocation.toFsEntry(path, false),});- //reflectDeleteEntries(toFsEntry(path, false));+ //reflectDeleteEntries(toFsEntry(path, false, currentLocation.uuid));}break;case 'add':if (!path.includes(AppConfig.metaFolder)) {actionsQueue.push({action: 'add',- entry: toFsEntry(path, true),+ entry: currentLocation.toFsEntry(path, true),open: false,});- // reflectAddEntry(toFsEntry(path, true));+ // reflectAddEntry(toFsEntry(path, true, currentLocation.uuid));}break;case 'addDir':if (!path.includes(AppConfig.metaFolder)) {actionsQueue.push({action: 'add',- entry: toFsEntry(path, false),+ entry: currentLocation.toFsEntry(path, false),open: false,});- //reflectAddEntry(toFsEntry(path, false));+ //reflectAddEntry(toFsEntry(path, false, currentLocation.uuid));}break;case 'change':@@ -177,20 +188,22 @@ export const FSWatcherContextProvider = ({// endsWith jsonconst filePath = getFileLocationFromMetaFile(path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),+ );+ getAllPropertiesPromise(filePath).then((entry) =>+ reflectUpdateMeta(entry),);- reflectUpdateMeta(filePath);}if (path.endsWith(AppConfig.metaFolderFile)) {// endsWith tsm.jsonconst directoryPath = getFileLocationFromMetaFile(path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);loadDirectoryContent(extractContainingDirectoryPath(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),),false,true,@@ -241,7 +254,9 @@ export const FSWatcherContextProvider = ({setTimeout(() => {for (let i = 0; i < ignored.current.length; i++) {const pathParts = ignored.current[i].split(- PlatformIO.getDirSeparator(),+ currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator,);if (path.startsWith(ignored.current[i]) || pathParts.includes(path)) {ignored.current.splice(i, 1);diff --git a/src/renderer/hooks/IOActionsContextProvider.tsx b/src/renderer/hooks/IOActionsContextProvider.tsxindex 1ede2a9ce..3f7e4e88a 100644--- a/src/renderer/hooks/IOActionsContextProvider.tsx+++ b/src/renderer/hooks/IOActionsContextProvider.tsx@@ -38,21 +38,18 @@ import {extractTags,cleanTrailingDirSeparator,cleanFrontDirSeparator,+ extractFileExtension,} from '@tagspaces/tagspaces-common/paths';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';-import PlatformIO from '-/services/platform-facade';import { actions as AppActions, AppDispatch } from '-/reducers/app';import { useDispatch, useSelector } from 'react-redux';import {cleanMetaData,executePromisesInBatches,generateFileName,- getAllPropertiesPromise,- getThumbPath,- loadFileMetaDataPromise,- loadMetaDataPromise,mergeFsEntryMeta,- toFsEntry,+ openDirectoryMessage,+ openFileMessage,} from '-/services/utils-io';import { TS } from '-/tagspaces.namespace';import { Progress } from 'aws-sdk/clients/s3';@@ -77,6 +74,7 @@ import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { Pro } from '-/pro';import { useEditedKanBanMetaContext } from '-/hooks/useEditedKanBanMetaContext';+import { CommonLocation } from '-/utils/CommonLocation';type IOActionsContextData = {createDirectory: (directoryPath: string) => Promise<boolean>;@@ -86,17 +84,20 @@ type IOActionsContextData = {moveDirs: (dirPaths: Array<string>,targetPath: string,+ locationID: string,onProgress?,) => Promise<boolean>;moveFiles: (paths: Array<string>,targetPath: string,+ locationID: string,onProgress?,reflect?: boolean,) => Promise<boolean>;copyDirs: (dirPaths: Array<any>,targetPath: string,+ locationID: string,onProgress?,) => Promise<boolean>;copyFiles: (@@ -126,23 +127,39 @@ type IOActionsContextData = {renameDirectory: (directoryPath: string,newDirectoryName: string,+ locationID: string,) => Promise<string>;renameFile: (filePath: string,newFilePath: string,+ locationID: string,reflect?: boolean,) => Promise<boolean>;openFileNatively: (selectedFile?: string) => void;duplicateFile: (selectedFilePath: string) => void;- saveMetaDataPromise: (+ saveCurrentLocationMetaData: (path: string,metaData: any,) => Promise<TS.FileSystemEntryMeta>;- getMetadataID: (path: string, id: string) => Promise<string>;- createFsEntryMeta: (path: string, props?: any) => Promise<string>;- saveFsEntryMeta: (path: string, meta: any) => Promise<TS.FileSystemEntryMeta>;- savePerspective: (+ saveMetaDataPromise: (+ entry: TS.FileSystemEntry,+ metaData: any,+ ) => Promise<TS.FileSystemEntryMeta>;+ getMetadataID: (path: string,+ id: string,+ location: CommonLocation,+ ) => Promise<string>;+ createFsEntryMeta: (+ entry: TS.FileSystemEntry,+ props?: any,+ ) => Promise<string>;+ saveFsEntryMeta: (+ entry: TS.FileSystemEntry,+ meta: any,+ ) => Promise<TS.FileSystemEntryMeta>;+ savePerspective: (+ entry: TS.FileSystemEntry,perspective: TS.PerspectiveType,) => Promise<TS.FileSystemEntryMeta>;removeFolderCustomSettings: (@@ -152,23 +169,23 @@ type IOActionsContextData = {setAutoSave: (entry: TS.FileSystemEntry,autoSave: boolean,- locationId?,+ locationID?,) => Promise<boolean>;setDescriptionChange: (entry: TS.FileSystemEntry,description: string,- locationId?,+ locationID?,) => Promise<boolean>;saveDirectoryPerspective: (entry: TS.FileSystemEntry,perspective: TS.PerspectiveType,- locationId?,+ locationID?,) => Promise<boolean>;setBackgroundImageChange: (entry: TS.FileSystemEntry) => void;setBackgroundColorChange: (entry: TS.FileSystemEntry,color: string,- locationId?,+ locationID?,) => Promise<boolean>;setThumbnailImageChange: (entry: TS.FileSystemEntry) => void;setFolderBackgroundPromise: (@@ -179,6 +196,19 @@ type IOActionsContextData = {dir: TS.OrderVisibilitySettings,parentDirPath?,) => void;+ getDirectoryOrder: (+ path: string,+ dirs: Array<TS.FileSystemEntry>,+ ) => Promise<TS.FileSystemEntryMeta>;+ getFilesOrder: (+ entry: TS.FileSystemEntry,+ filesArray: Array<TS.FileSystemEntry>,+ ) => Promise<TS.FileSystemEntryMeta>;+ pushFileOrder: (+ path: string,+ file: TS.OrderVisibilitySettings,+ files?: Array<TS.OrderVisibilitySettings>,+ ) => Promise<TS.FileSystemEntryMeta>;};export const IOActionsContext = createContext<IOActionsContextData>({@@ -197,6 +227,7 @@ export const IOActionsContext = createContext<IOActionsContextData>({renameFile: undefined,openFileNatively: undefined,duplicateFile: undefined,+ saveCurrentLocationMetaData: undefined,saveMetaDataPromise: undefined,getMetadataID: undefined,createFsEntryMeta: undefined,@@ -211,6 +242,9 @@ export const IOActionsContext = createContext<IOActionsContextData>({setThumbnailImageChange: undefined,setFolderBackgroundPromise: undefined,toggleDirVisibility: undefined,+ getDirectoryOrder: undefined,+ getFilesOrder: undefined,+ pushFileOrder: undefined,});export type IOActionsContextProviderProps = {@@ -243,9 +277,9 @@ export const IOActionsContextProvider = ({const { actions, setReflectActions } = useEditedEntryContext();const { setReflectMetaActions } = useEditedEntryMetaContext();const { setReflectKanBanActions } = useEditedKanBanMetaContext();- const { currentDirectoryPath, openDirectory } = useDirectoryContentContext();- const { switchLocationTypeByID, switchCurrentLocationType } =- useCurrentLocationContext();+ const { currentDirectoryPath, openDirectory, getAllPropertiesPromise } =+ useDirectoryContentContext();+ const { currentLocation, findLocation } = useCurrentLocationContext();const warningOpeningFilesExternally = useSelector(getWarningOpeningFilesExternally,);@@ -259,7 +293,7 @@ export const IOActionsContextProvider = ({if (!action.entry.isFile) {const dirPath = extractContainingDirectoryPath(action.entry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);if (cleanTrailingDirSeparator(@@ -288,7 +322,7 @@ export const IOActionsContextProvider = ({showNotification(`Creating directory ${extractDirectoryName(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),)} successful.`,'default',true,@@ -296,11 +330,11 @@ export const IOActionsContextProvider = ({return true;}).catch((error) => {- console.warn('Error creating directory: ' + error);+ console.log('Error creating directory: ' + error);showNotification(`Error creating directory '${extractDirectoryName(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),)}'`,'error',true,@@ -315,7 +349,12 @@ export const IOActionsContextProvider = ({return deleteEntriesPromise(...entries).then((success) => {if (success) {- const fileNames = entries.map((e) => e.name).join(' ');+ const fileNames = entries+ .map((e) => {+ deleteMeta(e.path, e.uuid);+ return e.name;+ })+ .join(' ');showNotification(t('deletingEntriesSuccessful', {dirPath: fileNames,@@ -335,7 +374,7 @@ export const IOActionsContextProvider = ({}function deleteDirectory(directoryPath: string) {- return deleteEntriesPromise(toFsEntry(directoryPath, false))+ return deleteEntriesPromise(currentLocation.toFsEntry(directoryPath, false)).then(() => {showNotification(t(@@ -343,7 +382,7 @@ export const IOActionsContextProvider = ({{dirPath: extractDirectoryName(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),),} as any,) as string,@@ -353,14 +392,14 @@ export const IOActionsContextProvider = ({return true;}).catch((error) => {- console.warn('Error while deleting directory: ' + error);+ console.log('Error while deleting directory: ' + error);showNotification(t('errorDeletingDirectoryAlert' as any,{dirPath: extractDirectoryName(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),),} as any,) as string,@@ -372,60 +411,69 @@ export const IOActionsContextProvider = ({});}+ function deleteMeta(filePath: string, uuid: string): Promise<boolean> {+ if (+ !filePath.endsWith(+ (currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator) + AppConfig.metaFolder,+ )+ ) {+ // Delete revisions path+ const backupFilePath = getBackupFileLocation(+ filePath,+ uuid,+ currentLocation?.getDirSeparator(),+ );+ const backupPath = extractContainingDirectoryPath(+ backupFilePath,+ currentLocation?.getDirSeparator(),+ );+ // Delete revisions, sidecar file and thumb+ return deleteEntriesPromise(+ currentLocation.toFsEntry(backupPath, false),+ currentLocation.toFsEntry(+ getMetaFileLocationForFile(+ filePath,+ currentLocation?.getDirSeparator(),+ ),+ true,+ ),+ currentLocation.toFsEntry(+ getThumbFileLocationForFile(+ filePath,+ currentLocation?.getDirSeparator(),+ false,+ ),+ true,+ ),+ )+ .then(() => {+ console.log(+ 'Cleaning revisions meta file and thumb successful for ' + filePath,+ );+ return true;+ })+ .catch((err) => {+ console.log('Cleaning meta file and thumb failed with ' + err);+ return false;+ });+ }+ return Promise.resolve(false);+ }+function deleteFile(filePath: string, uuid: string) {- return deleteEntriesPromise(toFsEntry(filePath, true))+ return deleteEntriesPromise(currentLocation.toFsEntry(filePath, true)).then(() => {showNotification(`Deleting file ${filePath} successful.`,'default',true,);- // Delete revisions- const backupFilePath = getBackupFileLocation(- filePath,- uuid,- PlatformIO.getDirSeparator(),- );- const backupPath = extractContainingDirectoryPath(- backupFilePath,- PlatformIO.getDirSeparator(),- );- PlatformIO.deleteDirectoryPromise(backupPath)- .then(() => {- console.log('Cleaning revisions successful for ' + filePath);- return true;- })- .catch((err) => {- console.warn('Cleaning revisions failed ', err);- });- // Delete sidecar file and thumb- deleteEntriesPromise(- toFsEntry(- getMetaFileLocationForFile(filePath, PlatformIO.getDirSeparator()),- true,- ),- toFsEntry(- getThumbFileLocationForFile(- filePath,- PlatformIO.getDirSeparator(),- false,- ),- true,- ),- )- .then(() => {- console.log(- 'Cleaning meta file and thumb successful for ' + filePath,- );- return true;- })- .catch((err) => {- console.warn('Cleaning meta file and thumb failed with ' + err);- });- return true;+ return deleteMeta(filePath, uuid).then(() => true);}).catch((error) => {- console.warn('Error while deleting file: ' + error);+ console.log('Error while deleting file: ' + error);showNotification(`Error while deleting file ${filePath}`,'error',@@ -438,14 +486,18 @@ export const IOActionsContextProvider = ({function moveDirs(dirPaths: Array<any>,targetPath: string,+ locationID: string,onProgress = undefined,): Promise<boolean> {const progress = dirPaths.length > 10 ? undefined : onProgress;const promises = dirPaths.map(({ path, count }) => {- const dirName = extractDirectoryName(path, PlatformIO.getDirSeparator());+ const dirName = extractDirectoryName(+ path,+ currentLocation?.getDirSeparator(),+ );return moveDirectoryPromise(- { path: path, total: count },- joinPaths(PlatformIO.getDirSeparator(), targetPath, dirName),+ { path: path, total: count, locationID },+ joinPaths(currentLocation?.getDirSeparator(), targetPath, dirName),progress,false,)@@ -453,13 +505,13 @@ export const IOActionsContextProvider = ({// console.log('Moving dir from ' + path + ' to ' + targetPath);const action: TS.EditAction = {action: 'move',- entry: toFsEntry(newDirPath, false),+ entry: currentLocation.toFsEntry(newDirPath, false),oldEntryPath: path,};return action;}).catch((err) => {- console.warn('Moving dirs failed ', err);+ console.log('Moving dirs failed ', err);showNotification(t('core:copyingFoldersFailed'));return undefined;});@@ -487,17 +539,20 @@ export const IOActionsContextProvider = ({function moveFiles(paths: Array<string>,targetPath: string,+ locationID: string,onProgress = undefined,reflect = true,): Promise<boolean> {+ const location = findLocation(locationID);const moveJobs = paths.map((path) => [path,normalizePath(targetPath) +- PlatformIO.getDirSeparator() +- extractFileName(path, PlatformIO.getDirSeparator()),+ location.getDirSeparator() ++ extractFileName(path, location.getDirSeparator()),]);return moveFilesPromise(moveJobs,+ location.uuid,paths.length > 10 ? undefined : onProgress,false,)@@ -507,18 +562,19 @@ export const IOActionsContextProvider = ({const moveMetaJobs = [];moveJobs.map((job) => {// Move revisions- loadFileMetaDataPromise(job[0])+ location+ .loadFileMetaDataPromise(job[0]).then((fsEntryMeta: TS.FileSystemEntryMeta) => {if (fsEntryMeta.id) {const backupDir = getBackupFileDir(job[0],fsEntryMeta.id,- PlatformIO.getDirSeparator(),+ location.getDirSeparator(),);const newBackupDir = getBackupFileDir(job[1],fsEntryMeta.id,- PlatformIO.getDirSeparator(),+ location.getDirSeparator(),);return moveDirectoryPromise({ path: backupDir }, newBackupDir).then(() => {@@ -531,40 +587,40 @@ export const IOActionsContextProvider = ({return true;}).catch((err) => {- console.warn('Moving revisions failed ', err);+ console.log('Moving revisions failed ', err);});}}).catch((err) => {- console.warn('loadFileMetaDataPromise', err);+ console.log('loadFileMetaDataPromise', err);});// move metamoveMetaJobs.push([- getMetaFileLocationForFile(job[0], PlatformIO.getDirSeparator()),- getMetaFileLocationForFile(job[1], PlatformIO.getDirSeparator()),+ getMetaFileLocationForFile(job[0], location.getDirSeparator()),+ getMetaFileLocationForFile(job[1], location.getDirSeparator()),]);moveMetaJobs.push([getThumbFileLocationForFile(job[0],- PlatformIO.getDirSeparator(),+ location.getDirSeparator(),false,),getThumbFileLocationForFile(job[1],- PlatformIO.getDirSeparator(),+ location.getDirSeparator(),false,),]);return true;});- return moveFilesPromise(moveMetaJobs, undefined, false)+ return moveFilesPromise(moveMetaJobs, location.uuid, undefined, false).then(() => {console.log('Moving meta and thumbs successful');return reflect && reflectMoveFiles(moveJobs);}).catch((err) => {- console.warn('At least one meta or thumb was not moved ' + err);+ console.log('At least one meta or thumb was not moved ' + err);return reflect && reflectMoveFiles(moveJobs);});} else {@@ -573,7 +629,7 @@ export const IOActionsContextProvider = ({}}).catch((err) => {- console.warn('Moving files failed with ' + err);+ console.log('Moving files failed with ' + err);showNotification(t('core:copyingFilesFailed'));return false;});@@ -582,14 +638,18 @@ export const IOActionsContextProvider = ({function copyDirs(dirPaths: Array<any>,targetPath: string,+ locationID: string,onProgress = undefined,): Promise<boolean> {const progress = dirPaths.length > 10 ? undefined : onProgress;const promises = dirPaths.map(({ path, count }) => {- const dirName = extractDirectoryName(path, PlatformIO.getDirSeparator());+ const dirName = extractDirectoryName(+ path,+ currentLocation?.getDirSeparator(),+ );return copyDirectoryPromise(- { path: path, total: count },- joinPaths(PlatformIO.getDirSeparator(), targetPath, dirName),+ { path: path, total: count, locationID },+ joinPaths(currentLocation?.getDirSeparator(), targetPath, dirName),progress,false,)@@ -606,7 +666,7 @@ export const IOActionsContextProvider = ({);}).catch((err) => {- console.warn('Copy dirs failed ', err);+ console.log('Copy dirs failed ', err);showNotification(t('core:copyingFoldersFailed'));return undefined;});@@ -639,16 +699,20 @@ export const IOActionsContextProvider = ({return copyFilesWithProgress(paths,targetPath,+ undefined,paths.length > 10 ? undefined : onProgress,).then((success) => {if (success) {showNotification(t('core:filesCopiedSuccessful'));const metaPaths = paths.flatMap((path) => [- getMetaFileLocationForFile(path, PlatformIO.getDirSeparator()),+ getMetaFileLocationForFile(+ path,+ currentLocation?.getDirSeparator(),+ ),getThumbFileLocationForFile(path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),false,),]);@@ -664,14 +728,14 @@ export const IOActionsContextProvider = ({return true;}).catch((err) => {- console.warn('At least one meta or thumb was not copied ' + err);+ console.log('At least one meta or thumb was not copied ' + err);return true;});}return false;}).catch((err) => {- console.warn('Moving files failed with ' + err);+ console.log('Moving files failed with ' + err);showNotification(t('core:copyingFilesFailed'));return false;});@@ -689,7 +753,7 @@ export const IOActionsContextProvider = ({onDownloadProgress?: (progress: Progress, abort, fileName?) => void,): Promise<TS.FileSystemEntry> {function saveFile(response: Response): Promise<TS.FileSystemEntry> {- if (AppConfig.isElectron && !PlatformIO.haveObjectStoreSupport()) {+ if (AppConfig.isElectron && !currentLocation.haveObjectStoreSupport()) {return saveBinaryFilePromise({ path: targetPath },response.body,@@ -705,8 +769,11 @@ export const IOActionsContextProvider = ({.then((response) => saveFile(response)).then((fsEntry: TS.FileSystemEntry) => {return generateThumbnailPromise(- PlatformIO.haveObjectStoreSupport() ? url : fsEntry.path,+ currentLocation.haveObjectStoreSupport() ? url : fsEntry.path,fsEntry.size,+ currentLocation.loadTextFilePromise,+ currentLocation.getFileContentPromise,+ currentLocation?.getDirSeparator(),).then((dataURL) => {if (dataURL && dataURL.length > 6) {const baseString = dataURL.split(',').pop();@@ -715,7 +782,7 @@ export const IOActionsContextProvider = ({{path: getThumbFileLocationForFile(targetPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),false,),},@@ -723,7 +790,7 @@ export const IOActionsContextProvider = ({true,).then((thumb: TS.FileSystemEntry) => ({...fsEntry,- thumbPath: getThumbPath(thumb.path),+ thumbPath: currentLocation.getThumbPath(thumb.path),}));}return fsEntry;@@ -773,10 +840,13 @@ export const IOActionsContextProvider = ({try {fileName = decodeURIComponent(file.name);} catch (ex) {}- let filePath =- normalizePath(targetPath) + PlatformIO.getDirSeparator() + fileName;+ let filePath = joinPaths(+ currentLocation?.getDirSeparator(),+ targetPath,+ fileName,+ );if (- PlatformIO.haveObjectStoreSupport() &&+ currentLocation?.haveObjectStoreSupport() &&(filePath.startsWith('\\') || filePath.startsWith('/'))) {filePath = filePath.substr(1);@@ -789,7 +859,7 @@ export const IOActionsContextProvider = ({async function readerLoaded(event, index, fileTargetPath) {const entryProps =- await PlatformIO.getPropertiesPromise(fileTargetPath);+ await currentLocation.getPropertiesPromise(fileTargetPath);if (entryProps) {showNotification('File with the same name already exist, importing skipped!',@@ -810,8 +880,11 @@ export const IOActionsContextProvider = ({if (fsEntry) {// Generate Thumbnailconst thumbPath = await generateThumbnailPromise(- PlatformIO.getURLforPath(fileTargetPath),+ currentLocation.getURLforPath(fileTargetPath),fsEntry.size,+ currentLocation.loadTextFilePromise,+ currentLocation.getFileContentPromise,+ currentLocation?.getDirSeparator(),).then((dataURL) => {if (dataURL && dataURL.length > 6) {@@ -819,7 +892,7 @@ export const IOActionsContextProvider = ({const fileContent = base64ToBlob(baseString);const thumbPath = getThumbFileLocationForFile(fileTargetPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),false,);return saveBinaryFilePromise(@@ -834,7 +907,8 @@ export const IOActionsContextProvider = ({console.log('error generateThumbnail:', err);});if (thumbPath) {- fsEntry.meta.thumbPath = PlatformIO.getURLforPath(thumbPath);+ fsEntry.meta.thumbPath =+ currentLocation.getURLforPath(thumbPath);}fsEntries.push(fsEntry);showNotification(@@ -874,7 +948,8 @@ export const IOActionsContextProvider = ({onUploadProgress?: (progress: Progress, response: any) => void,reflect: boolean = true,) {- return PlatformIO.getPropertiesPromise(filePath)+ return currentLocation+ .getPropertiesPromise(filePath).then((entryProps) => {if (entryProps) {showNotification(@@ -896,14 +971,15 @@ export const IOActionsContextProvider = ({// handle meta filesif (fileType === 'meta') {try {- // eslint-disable-next-line no-param-reassignfsEntry.meta = loadJSONString(fileContent.toString());} catch (e) {console.debug('cannot parse entry meta');}} else if (fileType === 'thumb') {- // eslint-disable-next-line no-param-reassign- fsEntry.meta.thumbPath = fsEntry.path;+ fsEntry.meta = {+ ...(fsEntry.meta && fsEntry.meta),+ thumbPath: fsEntry.path,+ };}return fsEntry;@@ -943,13 +1019,14 @@ export const IOActionsContextProvider = ({return new Promise((resolve, reject) => {const uploadJobs = [];paths.map((path) => {- let target =- normalizePath(targetPath) +- AppConfig.dirSeparator +- extractFileName(path, AppConfig.dirSeparator); // PlatformIO.getDirSeparator()); // with "/" dir separator cannot extractFileName on Win+ let target = joinPaths(+ currentLocation?.getDirSeparator(),+ targetPath,+ extractFileName(path, AppConfig.dirSeparator),+ ); // with "/" dir separator cannot extractFileName on Win// fix for Winif (- PlatformIO.haveObjectStoreSupport() &&+ currentLocation.haveObjectStoreSupport() &&(target.startsWith('\\') || target.startsWith('/'))) {target = target.substr(1);@@ -959,12 +1036,18 @@ export const IOActionsContextProvider = ({// copy metauploadJobs.push([getMetaFileLocationForFile(path, AppConfig.dirSeparator),- getMetaFileLocationForFile(target, AppConfig.dirSeparator),+ getMetaFileLocationForFile(+ target,+ currentLocation?.getDirSeparator(),+ ),'meta',]);uploadJobs.push([getThumbFileLocationForFile(path, AppConfig.dirSeparator),- getThumbFileLocationForFile(target, AppConfig.dirSeparator),+ getThumbFileLocationForFile(+ target,+ currentLocation?.getDirSeparator(),+ ),'thumb',path,]);@@ -980,7 +1063,8 @@ export const IOActionsContextProvider = ({// TODO try to replace this with <input type="file"if (AppConfig.isElectron) {// for AWS location getFileContentPromise cannot load with io-objectore- return PlatformIO.getLocalFileContentPromise(job[0])+ return currentLocation+ .getLocalFileContentPromise(job[0]).then((fileContent) =>uploadFile(filePath,@@ -993,7 +1077,13 @@ export const IOActionsContextProvider = ({.catch((err) => {// console.log('Error getting file:' + job[0] + ' ' + err);if (fileType === 'thumb' && job[3]) {- return generateThumbnailPromise(job[3], 0).then((dataURL) => {+ return generateThumbnailPromise(+ job[3],+ 0,+ currentLocation.loadTextFilePromise,+ currentLocation.getFileContentPromise,+ currentLocation?.getDirSeparator(),+ ).then((dataURL) => {if (dataURL && dataURL.length > 6) {const baseString = dataURL.split(',').pop();const fileContent = base64ToBlob(baseString);@@ -1017,7 +1107,6 @@ export const IOActionsContextProvider = ({.then((filesProm) => {const arrFiles: Array<TS.FileSystemEntry> = [];const arrMeta: Array<TS.FileSystemEntry> = [];- const arrThumb: Array<TS.FileSystemEntry> = [];filesProm.map((result) => {if (result.status !== 'rejected') {@@ -1025,8 +1114,6 @@ export const IOActionsContextProvider = ({if (file) {if (file.meta) {arrMeta.push(file);- } else if (file.thumbPath) {- arrThumb.push(file);} else {arrFiles.push(file);}@@ -1051,33 +1138,31 @@ export const IOActionsContextProvider = ({file.path,AppConfig.dirSeparator,);- if (metaFilePath !== undefined) {- for (let i = 0; i < arrMeta.length; i += 1) {- const metaFile = arrMeta[i];- if (- metaFile.path.replace(/[/\\]/g, '') ===- metaFilePath.replace(/[/\\]/g, '')- ) {- // eslint-disable-next-line no-param-reassign- file.meta = metaFile.meta;- }- }- }+const thumbFilePath = getThumbFileLocationForFile(file.path,AppConfig.dirSeparator,);- if (thumbFilePath !== undefined) {- for (let i = 0; i < arrThumb.length; i += 1) {- const thumbFile = arrThumb[i];- if (- thumbFile.path.replace(/[/\\]/g, '') ===- thumbFilePath.replace(/[/\\]/g, '')- ) {+ if (metaFilePath !== undefined) {+ for (let i = 0; i < arrMeta.length; i += 1) {+ const metaFile = arrMeta[i];+ const metaFilePath = metaFile.path.replace(/[/\\]/g, '');+ if (metaFilePath === metaFilePath.replace(/[/\\]/g, '')) {// eslint-disable-next-line no-param-reassign- file.meta.thumbPath = PlatformIO.getURLforPath(- thumbFile.meta.thumbPath,- );+ file.meta = {+ ...(file.meta && file.meta),+ ...metaFile.meta,+ };+ } else if (+ thumbFilePath &&+ metaFilePath === thumbFilePath.replace(/[/\\]/g, '')+ ) {+ file.meta = {+ ...(file.meta && file.meta),+ thumbPath: currentLocation.getURLforPath(+ file.meta.thumbPath,+ ),+ };}}}@@ -1085,7 +1170,7 @@ export const IOActionsContextProvider = ({return enhanceEntry(file,AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);}return file;@@ -1115,8 +1200,12 @@ export const IOActionsContextProvider = ({function renameDirectory(directoryPath: string,newDirectoryName: string,+ locationID: string,): Promise<string> {- return renameDirectoryPromise(directoryPath, newDirectoryName)+ return renameDirectoryPromise(+ { path: directoryPath, locationID },+ newDirectoryName,+ ).then((newDirPath) => {if (currentDirectoryPath === directoryPath) {openDirectory(newDirPath);@@ -1125,7 +1214,7 @@ export const IOActionsContextProvider = ({showNotification(`Renaming directory ${extractDirectoryName(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),)} successful.`,'default',true,@@ -1133,11 +1222,11 @@ export const IOActionsContextProvider = ({return newDirPath;}).catch((error) => {- console.warn('Error while renaming directory: ' + error);+ console.log('Error while renaming directory: ' + error);showNotification(`Error renaming directory '${extractDirectoryName(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),)}'`,'error',true,@@ -1149,9 +1238,16 @@ export const IOActionsContextProvider = ({function renameFile(filePath: string,newFilePath: string,+ locationID: string,reflect = true,): Promise<boolean> {- return renameFilePromise(filePath, newFilePath, undefined, reflect)+ return renameFilePromise(+ filePath,+ newFilePath,+ locationID,+ undefined,+ reflect,+ ).then(() => {// const newFilePathFromPromise = result[1];console.info('File renamed ' + filePath + ' to ' + newFilePath);@@ -1162,26 +1258,27 @@ export const IOActionsContextProvider = ({[getMetaFileLocationForFile(filePath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),),getMetaFileLocationForFile(newFilePath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),),],[getThumbFileLocationForFile(filePath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),false,),getThumbFileLocationForFile(newFilePath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),false,),],],+ locationID,undefined,false,)@@ -1195,7 +1292,7 @@ export const IOActionsContextProvider = ({return true;}).catch((err) => {- console.warn(+ console.log('Renaming meta file and thumb failed from ' +filePath +' to:' +@@ -1222,13 +1319,13 @@ export const IOActionsContextProvider = ({if (selectedEntries && selectedEntries.length > 0) {const fsEntry = selectedEntries[selectedEntries.length - 1];if (fsEntry.isFile) {- PlatformIO.openFile(fsEntry.path, warningOpeningFilesExternally);+ openFileMessage(fsEntry.path, warningOpeningFilesExternally);} else {- PlatformIO.openDirectory(fsEntry.path);+ openDirectoryMessage(fsEntry.path);}}} else {- PlatformIO.openFile(selectedFile, warningOpeningFilesExternally);+ openFileMessage(selectedFile, warningOpeningFilesExternally);}}@@ -1236,30 +1333,33 @@ export const IOActionsContextProvider = ({if (selectedFilePath) {const dirPath = extractContainingDirectoryPath(selectedFilePath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const fileName = extractFileName(selectedFilePath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const extractedTags = extractTags(selectedFilePath,AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);extractedTags.push('copy');extractedTags.push(formatDateTime4Tag(new Date(), true));- const newFilePath =- (dirPath ? dirPath + PlatformIO.getDirSeparator() : '') ++ const newFilePath = joinPaths(+ currentLocation?.getDirSeparator(),+ dirPath,generateFileName(fileName,extractedTags,AppConfig.tagDelimiter,+ currentLocation?.getDirSeparator(),prefixTagContainer,- );+ ),+ );copyFilePromise(selectedFilePath, newFilePath)/*.then(() => {@@ -1268,108 +1368,127 @@ export const IOActionsContextProvider = ({.catch((error) => {showNotification('Error creating duplicate: ', error);});+ } else {+ showNotification('Unable to duplicate, no file selected');}- showNotification('Unable to duplicate, no file selected');}+ function saveCurrentLocationMetaData(+ path: string,+ metaData: any,+ ): Promise<TS.FileSystemEntryMeta> {+ return currentLocation+ .getPropertiesPromise(path)+ .then((entryProperties) =>+ saveMetaDataPromise(entryProperties, metaData),+ );+ }/**- * @param path+ * @param entry* @param metaData - this will override existing meta data*/async function saveMetaDataPromise(- path: string,+ entry: TS.FileSystemEntry,metaData: any,): Promise<TS.FileSystemEntryMeta> {- const entryProperties = await PlatformIO.getPropertiesPromise(path);+ const location = findLocation(entry.locationID);//const cleanedMetaData = cleanMetaData(metaData);- if (entryProperties) {+ if (entry) {let metaFilePath;- if (entryProperties.isFile) {+ if (entry.isFile) {metaFilePath = getMetaFileLocationForFile(- path,- PlatformIO.getDirSeparator(),+ entry.path,+ location.getDirSeparator(),);// check and create meta folder if not existconst metaFolder = getMetaDirectoryPath(- extractContainingDirectoryPath(path, PlatformIO.getDirSeparator()),- PlatformIO.getDirSeparator(),+ extractContainingDirectoryPath(+ entry.path,+ location.getDirSeparator(),+ ),+ location.getDirSeparator(),);- const metaExist = await PlatformIO.getPropertiesPromise(metaFolder);+ const metaExist = await location.getPropertiesPromise(metaFolder);if (!metaExist) {- await PlatformIO.createDirectoryPromise(metaFolder);+ await createDirectoryPromise(metaFolder, location.uuid);}} else {// check and create meta folder if not exist// todo not need to check if folder exist first createDirectoryPromise() recursively will skip creation of existing folders https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callbackconst metaDirectoryPath = getMetaDirectoryPath(- path,- PlatformIO.getDirSeparator(),+ entry.path,+ location.getDirSeparator(),);const metaDirectoryProperties =- await PlatformIO.getPropertiesPromise(metaDirectoryPath);+ await location.getPropertiesPromise(metaDirectoryPath);if (!metaDirectoryProperties) {- await PlatformIO.createDirectoryPromise(metaDirectoryPath);+ await createDirectoryPromise(metaDirectoryPath, location.uuid);}metaFilePath = getMetaFileLocationForDir(- path,- PlatformIO.getDirSeparator(),+ entry.path,+ location.getDirSeparator(),);}const meta = cleanMetaData(mergeFsEntryMeta(metaData));const content = JSON.stringify(meta);- return saveTextFilePromise({ path: metaFilePath }, content, true).then(- () => meta,- );+ return saveTextFilePromise(+ { path: metaFilePath, locationID: entry.locationID },+ content,+ true,+ ).then(() => meta);}- return Promise.reject(new Error('file not found' + path));+ return Promise.reject(new Error('file not found' + entry.path));}/*** @param path* @param id FileSystemEntry.uuid+ * @param location*/- function getMetadataID(path: string, id: string): Promise<string> {- return loadMetaDataPromise(path)+ function getMetadataID(+ path: string,+ id: string,+ location: CommonLocation,+ ): Promise<string> {+ return location+ .loadMetaDataPromise(path).then((fsEntryMeta: TS.FileSystemEntryMeta) => {if (fsEntryMeta.id) {return fsEntryMeta.id;} else {- return createFsEntryMeta(path, { ...fsEntryMeta, id: id });+ return createFsEntryMeta(+ location.toFsEntry(path, fsEntryMeta.isFile),+ { ...fsEntryMeta, id: id },+ );}}).catch(() => {- return createFsEntryMeta(path, { id: id });+ // create new meta id to not be changed -> next time listDirectory will get the same id for the file from meta+ const content = JSON.stringify({ id: id });+ const metaFilePath = path.endsWith(location.getDirSeparator())+ ? getMetaFileLocationForDir(path, location.getDirSeparator())+ : getMetaFileLocationForFile(path, location.getDirSeparator());+ return saveTextFilePromise(+ { path: metaFilePath, locationID: location.uuid },+ content,+ true,+ ).then(() => id);+ //return createFsEntryMeta(path, { id: id });});}- function switchLocationAndSaveMetaData(- path: string,- meta: any,- locationId = undefined,- ): Promise<TS.FileSystemEntryMeta> {- return switchLocationTypeByID(locationId).then((currentLocationId) =>- saveFsEntryMeta(path, meta)- .then((entryMeta) => entryMeta)- .catch((error) => {- if (currentLocationId) {- switchCurrentLocationType();- }- console.warn('Error saving color for folder ' + error);- // showNotification(t('Error saving color for folder'));- return undefined;- }),- );- }-- function createFsEntryMeta(path: string, props: any = {}): Promise<string> {+ function createFsEntryMeta(+ entry: TS.FileSystemEntry,+ props: any = {},+ ): Promise<string> {const newFsEntryMeta: TS.FileSystemEntryMeta = mergeFsEntryMeta(props);- return saveMetaDataPromise(path, newFsEntryMeta)+ return saveMetaDataPromise(entry, newFsEntryMeta).then(() => newFsEntryMeta.id).catch((error) => {console.log('Error saveMetaDataPromise for ' +- path ++ entry.path +' orphan id: ' +newFsEntryMeta.id,error,@@ -1379,28 +1498,30 @@ export const IOActionsContextProvider = ({}function saveFsEntryMeta(- path: string,+ entry: TS.FileSystemEntry,meta: any,): Promise<TS.FileSystemEntryMeta> {- return loadMetaDataPromise(path)+ return findLocation(entry.locationID)+ .loadMetaDataPromise(entry.path).then((fsEntryMeta) => {- return saveMetaDataPromise(path, {+ return saveMetaDataPromise(entry, {...fsEntryMeta,...meta,lastUpdated: new Date().getTime(),});}).catch(() => {- return saveMetaDataPromise(path, mergeFsEntryMeta(meta));+ return saveMetaDataPromise(entry, mergeFsEntryMeta(meta));});}function savePerspective(- path: string,+ entry: TS.FileSystemEntry,perspective: TS.PerspectiveType,): Promise<TS.FileSystemEntryMeta> {return new Promise((resolve, reject) => {- loadMetaDataPromise(path)+ findLocation(entry.locationID)+ .loadMetaDataPromise(entry.path).then((fsEntryMeta: TS.FileSystemEntryMeta) => {let updatedFsEntryMeta: TS.FileSystemEntryMeta;if (perspective && perspective !== 'unspecified') {@@ -1412,14 +1533,14 @@ export const IOActionsContextProvider = ({const { perspective: remove, ...rest } = fsEntryMeta;updatedFsEntryMeta = rest;}- saveMetaDataPromise(path, updatedFsEntryMeta)+ saveMetaDataPromise(entry, updatedFsEntryMeta).then(() => {resolve(updatedFsEntryMeta);return true;}).catch((err) => {- console.warn(- 'Error adding perspective for ' + path + ' with ' + err,+ console.log(+ 'Error adding perspective for ' + entry.path + ' with ' + err,);reject();});@@ -1429,14 +1550,14 @@ export const IOActionsContextProvider = ({const newFsEntryMeta: TS.FileSystemEntryMeta = mergeFsEntryMeta({perspective,});- saveMetaDataPromise(path, newFsEntryMeta)+ saveMetaDataPromise(entry, newFsEntryMeta).then(() => {resolve(newFsEntryMeta);return true;}).catch((error) => {- console.warn(- 'Error adding perspective for ' + path + ' with ' + error,+ console.log(+ 'Error adding perspective for ' + entry.path + ' with ' + error,);reject();});@@ -1449,7 +1570,8 @@ export const IOActionsContextProvider = ({perspective: string,): Promise<TS.FileSystemEntryMeta> {return new Promise((resolve, reject) => {- loadMetaDataPromise(path, true)+ currentLocation+ .loadMetaDataPromise(path, true).then((fsEntryMeta: TS.FileSystemEntryMeta) => {let updatedFsEntryMeta: TS.FileSystemEntryMeta = {...(fsEntryMeta && fsEntryMeta),@@ -1461,13 +1583,13 @@ export const IOActionsContextProvider = ({},};- saveMetaDataPromise(path, updatedFsEntryMeta)+ saveCurrentLocationMetaData(path, updatedFsEntryMeta).then(() => {resolve(updatedFsEntryMeta);return true;}).catch((err) => {- console.warn(+ console.log('Error adding perspective for ' + path + ' with ' + err,);reject();@@ -1480,13 +1602,13 @@ export const IOActionsContextProvider = ({[perspective]: undefined,},});- saveMetaDataPromise(path, newFsEntryMeta)+ saveCurrentLocationMetaData(path, newFsEntryMeta).then(() => {resolve(newFsEntryMeta);return true;}).catch((error) => {- console.warn(+ console.log('Error adding perspective for ' + path + ' with ' + error,);reject();@@ -1495,16 +1617,8 @@ export const IOActionsContextProvider = ({});}- function setAutoSave(- entry: TS.FileSystemEntry,- autoSave: boolean,- locationId = undefined,- ) {- return switchLocationAndSaveMetaData(- entry.path,- { autoSave },- locationId,- ).then((meta) => {+ function setAutoSave(entry: TS.FileSystemEntry, autoSave: boolean) {+ return saveFsEntryMeta(entry, { autoSave }).then((meta) => {if (meta) {const action: TS.EditMetaAction = {action: 'autoSaveChange',@@ -1523,13 +1637,8 @@ export const IOActionsContextProvider = ({function saveDirectoryPerspective(entry: TS.FileSystemEntry,perspective: TS.PerspectiveType,- locationId = undefined,): Promise<boolean> {- return switchLocationAndSaveMetaData(- entry.path,- { perspective },- locationId,- ).then((meta) => {+ return saveFsEntryMeta(entry, { perspective }).then((meta) => {if (meta) {const action: TS.EditMetaAction = {action: 'perspectiveChange',@@ -1548,13 +1657,8 @@ export const IOActionsContextProvider = ({function setDescriptionChange(entry: TS.FileSystemEntry,description: string,- locationId = undefined,): Promise<boolean> {- return switchLocationAndSaveMetaData(- entry.path,- { description },- locationId,- ).then((meta) => {+ return saveFsEntryMeta(entry, { description }).then((meta) => {if (meta) {const action: TS.EditMetaAction = {action: 'descriptionChange',@@ -1571,13 +1675,16 @@ export const IOActionsContextProvider = ({}function setBackgroundImageChange(entry: TS.FileSystemEntry) {- if (PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()) {+ if (+ currentLocation?.haveObjectStoreSupport() ||+ currentLocation?.haveWebDavSupport()+ ) {// reload cacheconst folderBgndPath = getBgndFileLocationForDirectory(entry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);- PlatformIO.generateURLforPath(folderBgndPath, 604800);+ currentLocation.generateURLforPath(folderBgndPath, 604800);}const action: TS.EditMetaAction = {action: 'bgdImgChange',@@ -1595,13 +1702,8 @@ export const IOActionsContextProvider = ({function setBackgroundColorChange(entry: TS.FileSystemEntry,color: string,- locationId = undefined,): Promise<boolean> {- return switchLocationAndSaveMetaData(- entry.path,- { color },- locationId,- ).then((meta) => {+ return saveFsEntryMeta(entry, { color }).then((meta) => {if (meta) {const action: TS.EditMetaAction = {action: 'bgdColorChange',@@ -1618,13 +1720,16 @@ export const IOActionsContextProvider = ({}function setThumbnailImageChange(entry: TS.FileSystemEntry) {- if (PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()) {+ if (+ currentLocation?.haveObjectStoreSupport() ||+ currentLocation?.haveWebDavSupport()+ ) {// reload cacheconst folderThumbPath = getThumbFileLocationForDirectory(entry.path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);- PlatformIO.generateURLforPath(folderThumbPath, 604800);+ currentLocation.generateURLforPath(folderThumbPath, 604800);}const action: TS.EditMetaAction = {action: 'thumbChange',@@ -1647,10 +1752,15 @@ export const IOActionsContextProvider = ({): Promise<string> {const folderBgndPath = getBgndFileLocationForDirectory(directoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);- return generateImageThumbnail(filePath, AppConfig.maxBgndSize) // 4K -> 3840, 2K -> 2560+ return generateImageThumbnail(+ filePath,+ currentLocation.getFileContentPromise,+ currentLocation?.getDirSeparator(),+ AppConfig.maxBgndSize,+ ) // 4K -> 3840, 2K -> 2560.then((base64Image) => {if (base64Image) {const data = base64ToBlob(base64Image.split(',').pop());@@ -1675,14 +1785,14 @@ export const IOActionsContextProvider = ({dir: TS.OrderVisibilitySettings,parentDirPath: string = undefined,) {- if (Pro && Pro.MetaOperations) {+ if (Pro) {const currentDirPath = parentDirPath? parentDirPath: currentDirectoryPath;- Pro.MetaOperations.toggleDirectoryVisibility(currentDirPath, dir).then(+ toggleDirectoryVisibility(currentDirPath, dir).then((updatedFsEntryMeta) => {if (updatedFsEntryMeta) {- saveMetaDataPromise(currentDirPath, updatedFsEntryMeta)+ saveCurrentLocationMetaData(currentDirPath, updatedFsEntryMeta).then(() => {const action: TS.KanBanMetaActions = {action: 'directoryVisibilityChange',@@ -1691,7 +1801,7 @@ export const IOActionsContextProvider = ({setReflectKanBanActions(action);}).catch((err) => {- console.warn(+ console.log('Error adding dirs for ' + currentDirPath + ' with ' + err,);});@@ -1701,6 +1811,149 @@ export const IOActionsContextProvider = ({}}+ /**+ * @param currentDirPath+ * @param dir+ * return updatedFsEntryMeta+ */+ function toggleDirectoryVisibility(+ currentDirPath: string,+ dir: TS.OrderVisibilitySettings,+ ): Promise<TS.FileSystemEntryMeta> {+ return currentLocation+ .loadMetaDataPromise(currentDirPath)+ .then((fsEntryMeta) => {+ const customOrder: TS.CustomOrder = fsEntryMeta.customOrder+ ? fsEntryMeta.customOrder+ : {};++ let dirs: TS.OrderVisibilitySettings[] = [dir];+ if (customOrder.folders && customOrder.folders.length > 0) {+ const index = customOrder.folders.findIndex(+ (col) => col.name === dir.name,+ );+ if (index !== -1) {+ customOrder.folders.splice(index, 1);+ dirs = customOrder.folders;+ } else {+ dirs = [...customOrder.folders, dir];+ }+ }++ return {+ ...fsEntryMeta,+ customOrder: { ...customOrder, folders: dirs },+ };+ })+ .catch((ex) => {+ console.log(ex);+ return mergeFsEntryMeta({+ customOrder: { folders: [dir] },+ });+ });+ }++ function getDirectoryOrder(+ path: string,+ dirs: Array<TS.FileSystemEntry>,+ ): Promise<TS.FileSystemEntryMeta> {+ const dirsArray: Array<TS.OrderVisibilitySettings> = dirs+ .filter((dir) => dir !== undefined)+ .map((dir) => ({ uuid: dir.uuid, name: dir.name }));+ return currentLocation+ .loadMetaDataPromise(path)+ .then((fsEntryMeta) => {+ const customOrder: TS.CustomOrder = fsEntryMeta.customOrder+ ? fsEntryMeta.customOrder+ : {};++ return {+ ...fsEntryMeta,+ customOrder: { ...customOrder, folders: dirsArray },+ };+ })+ .catch(() => {+ return {+ id: getUuid(),+ customOrder: { folders: dirsArray },+ };+ });+ }++ function getFilesOrder(+ entry: TS.FileSystemEntry,+ filesArray: Array<TS.FileSystemEntry>,+ ): Promise<TS.FileSystemEntryMeta> {+ const files: Array<TS.OrderVisibilitySettings> = filesArray.map((file) => ({+ uuid: file.uuid,+ name: file.name,+ }));+ return currentLocation+ .loadMetaDataPromise(entry.path)+ .then((fsEntryMeta) => {+ const customOrder: TS.CustomOrder = fsEntryMeta.customOrder+ ? fsEntryMeta.customOrder+ : {};+ return {+ ...fsEntryMeta,+ customOrder: { ...customOrder, files: files },+ };+ })+ .catch(() => {+ return {+ id: entry.uuid || getUuid(),+ customOrder: { files: files },+ };+ });+ }++ /**+ * @param path+ * @param file+ * @param files === undefined toTop else toBottom+ */+ function pushFileOrder(+ path: string,+ file: TS.OrderVisibilitySettings,+ files: Array<TS.OrderVisibilitySettings> = undefined,+ ): Promise<TS.FileSystemEntryMeta> {+ return currentLocation+ .loadMetaDataPromise(path)+ .then((fsEntryMeta) => {+ const customOrder: TS.CustomOrder = fsEntryMeta.customOrder+ ? fsEntryMeta.customOrder+ : {};+ const customOrderFiles = customOrder.files+ ? customOrder.files.filter((f) => f.name !== file.name)+ : [];+ const orderFiles = files+ ? [+ ...customOrderFiles,+ ...files.filter(+ (f) =>+ f.name !== file.name &&+ !customOrderFiles.some((ff) => ff.name === f.name),+ ),+ file,+ ]+ : [file, ...customOrderFiles];++ return {+ ...fsEntryMeta,+ customOrder: { ...customOrder, files: orderFiles },+ };+ })+ .catch(() => {+ const orderFiles = files+ ? [...files.filter((f) => f.name !== file.name), file]+ : [file];+ return {+ id: getUuid(),+ customOrder: { files: orderFiles },+ };+ });+ }+const context = useMemo(() => {return {createDirectory,@@ -1718,6 +1971,7 @@ export const IOActionsContextProvider = ({renameFile,openFileNatively,duplicateFile,+ saveCurrentLocationMetaData,saveMetaDataPromise,getMetadataID,createFsEntryMeta,@@ -1732,6 +1986,9 @@ export const IOActionsContextProvider = ({setThumbnailImageChange,setFolderBackgroundPromise,toggleDirVisibility,+ getDirectoryOrder,+ getFilesOrder,+ pushFileOrder,};}, [warningOpeningFilesExternally, currentDirectoryPath]);diff --git a/src/renderer/hooks/LocationIndexContextProvider.tsx b/src/renderer/hooks/LocationIndexContextProvider.tsxindex 6ee364730..751ac6e31 100644--- a/src/renderer/hooks/LocationIndexContextProvider.tsx+++ b/src/renderer/hooks/LocationIndexContextProvider.tsx@@ -25,30 +25,31 @@ import React, {} from 'react';import { useSelector } from 'react-redux';import { useTranslation } from 'react-i18next';-import * as cordovaIO from '@tagspaces/tagspaces-common-cordova';-import * as objectStoreAPI from '@tagspaces/tagspaces-common-aws';import { TS } from '-/tagspaces.namespace';-import {- createDirectoryIndex,- executePromisesInBatches,- loadIndexFromDisk,-} from '-/services/utils-io';+import { executePromisesInBatches } from '-/services/utils-io';import { getEnableWS } from '-/reducers/settings';+import { loadJSONString } from '@tagspaces/tagspaces-common/utils-io';import { locationType } from '@tagspaces/tagspaces-common/misc';-import { getMetaIndexFilePath } from '@tagspaces/tagspaces-indexer';-import PlatformIO from '-/services/platform-facade';+import {+ getMetaIndexFilePath,+ createIndex,+} from '@tagspaces/tagspaces-indexer';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';-import { getLocations } from '-/reducers/locations';import AppConfig from '-/AppConfig';import Search from '-/services/search';import {getThumbFileLocationForDirectory,getThumbFileLocationForFile,+ getMetaDirectoryPath,+ joinPaths,+ cleanTrailingDirSeparator,} from '@tagspaces/tagspaces-common/paths';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useEditedEntryContext } from '-/hooks/useEditedEntryContext';import { useFSWatcherContext } from '-/hooks/useFSWatcherContext';+import { CommonLocation } from '-/utils/CommonLocation';+import { Pro } from '-/pro';type LocationIndexContextData = {index: TS.FileSystemEntry[];@@ -56,7 +57,7 @@ type LocationIndexContextData = {isIndexing: string;getIndex: () => TS.FileSystemEntry[];cancelDirectoryIndexing: () => void;- createLocationIndex: (location: TS.Location) => Promise<boolean>;+ createLocationIndex: (location: CommonLocation) => Promise<boolean>;createLocationsIndexes: (extractText?: boolean) => Promise<boolean>;clearDirectoryIndex: () => void;searchLocationIndex: (searchQuery: TS.SearchQuery) => void;@@ -91,17 +92,16 @@ export const LocationIndexContextProvider = ({}: LocationIndexContextProviderProps) => {const { t } = useTranslation();- const { currentLocation, getLocationPath } = useCurrentLocationContext();+ const { locations, findLocation, currentLocation, getLocationPath } =+ useCurrentLocationContext();const { ignoreByWatcher, deignoreByWatcher } = useFSWatcherContext();const { setSearchResults, appendSearchResults, updateCurrentDirEntries } =useDirectoryContentContext();const { actions } = useEditedEntryContext();const { showNotification, hideNotifications } = useNotificationContext();- const { switchLocationTypeByID, switchCurrentLocationType } =- useCurrentLocationContext();const enableWS = useSelector(getEnableWS);- const allLocations = useSelector(getLocations);+ //const allLocations = useSelector(getLocations);const isIndexing = useRef<string>(undefined);let walking = true;@@ -209,6 +209,85 @@ export const LocationIndexContextProvider = ({forceUpdate();}+ function createDirectoryIndex(+ param: string | any,+ extractText = false,+ ignorePatterns: Array<string> = [],+ enableWS = true,+ isWalking = () => true,+ // disableIndexing = true,+ ): Promise<TS.FileSystemEntry[]> {+ if (isWalking()) {+ if (Pro && Pro.Watcher) {+ Pro.Watcher.stopWatching();+ }+ let directoryPath;+ let locationID;+ if (typeof param === 'object' && param !== null) {+ directoryPath = param.path;+ ({ locationID } = param);+ } else {+ directoryPath = param;+ }+ const loc = findLocation(locationID);+ const dirPath = cleanTrailingDirSeparator(directoryPath);+ if (+ enableWS &&+ !loc.haveObjectStoreSupport() &&+ !loc.haveWebDavSupport() &&+ !AppConfig.isCordova+ ) {+ // Start indexing in worker if not in the object store mode+ return loc+ .createDirectoryIndexInWorker(dirPath, extractText, ignorePatterns)+ .then((result) => {+ if (result && result.success) {+ return loadIndexFromDisk(dirPath, locationID);+ } else if (result && result.error) {+ console.error(+ 'createDirectoryIndexInWorker failed:' + result.error,+ );+ } else {+ console.error(+ 'createDirectoryIndexInWorker failed: unknown error',+ );+ }+ return undefined; // todo create index not in worker+ });+ }++ const mode = ['extractThumbPath'];+ if (extractText) {+ mode.push('extractTextContent');+ }+ return createIndex(+ param,+ loc.listDirectoryPromise,+ loc.loadTextFilePromise,+ mode,+ ignorePatterns,+ isWalking,+ )+ .then((directoryIndex) =>+ persistIndex(param, directoryIndex).then((success) => {+ if (success) {+ console.log('Index generated in folder: ' + directoryPath);+ return enhanceDirectoryIndex(+ directoryIndex,+ locationID,+ directoryPath,+ );+ //return enhanceDirectoryIndex(param, directoryIndex, locationID);+ }+ return undefined;+ }),+ )+ .catch((err) => {+ console.log('Error creating index: ', err);+ });+ }+ }+function createDirectoryIndexWrapper(param: string | any,extractText = false,@@ -217,31 +296,27 @@ export const LocationIndexContextProvider = ({// disableIndexing = true,): Promise<any> {const indexFilePath = getMetaIndexFilePath(param.path);- return switchLocationTypeByID(param.locationID)- .then(() => {- ignoreByWatcher(indexFilePath);- return createDirectoryIndex(- param,- extractText,- ignorePatterns,- enableWS,- isWalking,- );++ ignoreByWatcher(indexFilePath);+ return createDirectoryIndex(+ param,+ extractText,+ ignorePatterns,+ enableWS,+ isWalking,+ )+ .then((index) => {+ deignoreByWatcher(indexFilePath);+ return index;})- .then((index) =>- switchCurrentLocationType().then(() => {- deignoreByWatcher(indexFilePath);- return index;- }),- ).catch((err) => {//lastError.current = err;- console.warn('Error loading text content ' + err);+ console.log('Error loading text content ' + err);return false; //switchCurrentLocationType();});}- function createLocationIndex(location: TS.Location): Promise<boolean> {+ function createLocationIndex(location: CommonLocation): Promise<boolean> {if (location) {return getLocationPath(location).then((locationPath) => {const isCurrentLocation =@@ -275,7 +350,7 @@ export const LocationIndexContextProvider = ({}async function createLocationsIndexes(extractText = true): Promise<boolean> {- for (let location of allLocations) {+ for (let location of locations) {try {const locationPath = await getLocationPath(location);isIndexing.current = locationPath;@@ -314,24 +389,17 @@ export const LocationIndexContextProvider = ({function enhanceSearchEntry(entry: TS.FileSystemEntry,): Promise<TS.FileSystemEntry> {- const loc = allLocations.find((l) => l.uuid === entry.locationID);+ const loc = findLocation(entry.locationID);if (loc) {const thumbFilePath = entry.isFile- ? getThumbFileLocationForFile(- entry.path,- PlatformIO.getDirSeparator(),- false,- )- : getThumbFileLocationForDirectory(- entry.path,- PlatformIO.getDirSeparator(),- );+ ? getThumbFileLocationForFile(entry.path, loc.getDirSeparator(), false)+ : getThumbFileLocationForDirectory(entry.path, loc.getDirSeparator());if (thumbFilePath) {- return checkFileExist(thumbFilePath, loc).then((exist) => {+ return loc.checkFileExist(thumbFilePath).then((exist) => {if (exist) {const thumbPath =loc.type === locationType.TYPE_CLOUD- ? getURLforPath(thumbFilePath, loc)+ ? loc.getURLforPath(thumbFilePath): thumbFilePath;return { ...entry, meta: { ...entry.meta, thumbPath } };}@@ -342,18 +410,18 @@ export const LocationIndexContextProvider = ({return undefined;}- function getURLforPath(path: string, location: TS.Location) {+ /*function getURLforPath(path: string, location: CommonLocation) {const api = objectStoreAPI.getS3Api(location);return api.getSignedUrl('getObject', {Bucket: location.bucketName,Key: normalizePath(path),Expires: 900,});- }+ }*/- function checkFileExist(+ /*function checkFileExist(path: string,- location: TS.Location,+ location: CommonLocation,): Promise<boolean> {if (location.type === locationType.TYPE_LOCAL) {return window.electronIO.ipcRenderer.invoke('checkFileExist', path);@@ -374,7 +442,7 @@ export const LocationIndexContextProvider = ({} else if (AppConfig.isCordova) {return cordovaIO.checkFileExist(path);}- }+ }*/function enhanceSearchEntries(entries: TS.FileSystemEntry[]) {const promises: Promise<TS.FileSystemEntry>[] = entries.map(@@ -475,18 +543,12 @@ export const LocationIndexContextProvider = ({setSearchResults([]);showNotification(t('core:searching'), 'default', false, 'TIDSearching');- // Preparing for global search- // setSearchResults([]);- /*if (currentLocation && currentLocation.type === locationType.TYPE_CLOUD) {- PlatformIO.disableObjectStoreSupport();- }*/-walking = true;//let searchResultCount = 0;let searchResults = [];let maxSearchResultReached = false;- const result = allLocations.reduce(+ const result = locations.reduce((accumulatorPromise, location) =>accumulatorPromise.then(async () => {// cancel search if max search result count reached@@ -496,7 +558,6 @@ export const LocationIndexContextProvider = ({}const nextPath = await getLocationPath(location);const isCloudLocation = location.type === locationType.TYPE_CLOUD;- await switchLocationTypeByID(location.uuid);let directoryIndex = await loadIndexFromDisk(nextPath, location.uuid);//console.log('Searching in: ' + nextPath);showNotification(@@ -506,12 +567,6 @@ export const LocationIndexContextProvider = ({'TIDSearching',);- /*const folderIndexPath =- getMetaDirectoryPath(nextPath) +- PlatformIO.getDirSeparator() +- AppConfig.folderIndexFile;- const indexExist = await PlatformIO.checkFileExist(folderIndexPath);*/-if (!location.disableIndexing &&(!directoryIndex ||@@ -542,54 +597,6 @@ export const LocationIndexContextProvider = ({return true;},);- /*return Search.searchLocationIndex(directoryIndex, searchQuery)- .then((searchResults: Array<TS.FileSystemEntry>) => {- let enhancedSearchResult = searchResults;- if (isCloudLocation) {- enhancedSearchResult = searchResults- // Excluding s3 folders from global search- .filter((entry) => entry && entry.isFile)- .map((entry: TS.FileSystemEntry) => {- const cleanedPath = entry.path.startsWith('/')- ? entry.path.substr(1)- : entry.path;- const url = PlatformIO.getURLforPath(cleanedPath);- let thumbPath;- if (- entry.meta &&- entry.meta.thumbPath &&- entry.meta.thumbPath.length > 1 &&- !entry.meta.thumbPath.startsWith('http')- ) {- thumbPath = PlatformIO.getURLforPath(- entry.meta.thumbPath,- );- }- return { ...entry, url, thumbPath };- });- }-- searchResultCount += enhancedSearchResult.length;- appendSearchResults(enhancedSearchResult);- hideNotifications();- /!*if (isCloudLocation) {- PlatformIO.disableObjectStoreSupport();- }*!/- return true;- })- .catch((e) => {- /!*if (isCloudLocation) {- PlatformIO.disableObjectStoreSupport();- }*!/- console.log('Searching Index failed: ', e);- setSearchResults([]);- // dispatch(AppActions.hideNotifications());- showNotification(- t('core:searchingFailed') + ' ' + e.message,- 'warning',- true,- );- });*/}),Promise.resolve(),);@@ -610,17 +617,91 @@ export const LocationIndexContextProvider = ({showNotification(t('Global search completed'), 'default', true);}console.log('Global search completed!');- return switchCurrentLocationType();}).catch((e) => {- /*if (- currentLocation &&- currentLocation.type === locationType.TYPE_CLOUD- ) {- PlatformIO.enableObjectStoreSupport(currentLocation);- }*/console.timeEnd('globalSearch');- console.warn('Global search failed!', e);+ console.log('Global search failed!', e);+ });+ }++ /**+ * persistIndex based on location - used for S3 and cordova only+ * for native used common-platform/indexer.js -> persistIndex instead+ * @param param+ * @param directoryIndex+ */+ async function persistIndex(param: string | any, directoryIndex: any) {+ let directoryPath;+ if (typeof param === 'object' && param !== null) {+ directoryPath = param.path;+ } else {+ directoryPath = param;+ }+ const metaDirectory = getMetaDirectoryPath(directoryPath);+ const exist = await currentLocation.checkDirExist(metaDirectory);+ if (!exist) {+ await currentLocation.createDirectoryPromise(metaDirectory); // todo platformFacade?+ }+ const folderIndexPath =+ metaDirectory ++ currentLocation?.getDirSeparator() ++ AppConfig.folderIndexFile; // getMetaIndexFilePath(directoryPath);+ return currentLocation+ .saveTextFilePromise(+ { ...param, path: folderIndexPath },+ JSON.stringify(directoryIndex), // relativeIndex),+ true,+ )+ .then(() => {+ console.log(+ 'Index persisted for: ' + directoryPath + ' to ' + folderIndexPath,+ );+ return true;+ })+ .catch((err) => {+ console.log('Error saving the index for ' + folderIndexPath, err);+ });+ }++ function enhanceDirectoryIndex(+ directoryIndex: TS.FileSystemEntry[],+ locationID,+ folderPath,+ ): TS.FileSystemEntry[] {+ const loc = findLocation(locationID);+ return directoryIndex.map((i: TS.FileSystemEntry) => ({+ ...i,+ locationID,+ path: joinPaths(+ loc.getDirSeparator(),+ folderPath,+ AppConfig.isWin+ ? i.path.replaceAll('/', loc.getDirSeparator())+ : i.path, //toPlatformPath()+ ),+ }));+ }++ function loadIndexFromDisk(+ folderPath: string,+ locationID: string,+ ): Promise<TS.FileSystemEntry[]> {+ const loc = findLocation(locationID);+ const folderIndexPath =+ getMetaDirectoryPath(folderPath) ++ loc.getDirSeparator() ++ AppConfig.folderIndexFile;+ return loc+ .loadTextFilePromise(folderIndexPath)+ .then((jsonContent) => {+ const directoryIndex = loadJSONString(+ jsonContent,+ ) as TS.FileSystemEntry[];+ return enhanceDirectoryIndex(directoryIndex, locationID, folderPath);+ })+ .catch((e) => {+ console.log('cannot load json:' + folderPath, e);+ return undefined;});}diff --git a/src/renderer/hooks/OpenedEntryContextProvider.tsx b/src/renderer/hooks/OpenedEntryContextProvider.tsxindex d65c8e2a4..4c3b2f56b 100644--- a/src/renderer/hooks/OpenedEntryContextProvider.tsx+++ b/src/renderer/hooks/OpenedEntryContextProvider.tsx@@ -27,10 +27,9 @@ import { useDispatch, useSelector } from 'react-redux';import { AppDispatch } from '-/reducers/app';import { Pro } from '-/pro';import { TS } from '-/tagspaces.namespace';-import PlatformIO from '-/services/platform-facade';import {- findExtensionsForEntry,- getAllPropertiesPromise,+ findExtensionPathForId,+ getDirProperties,getRelativeEntryPath,openURLExternally,} from '-/services/utils-io';@@ -39,7 +38,6 @@ import {getNewHTMLFileContent,getSupportedFileTypes,} from '-/reducers/settings';-import { getLocations } from '-/reducers/locations';import { clearURLParam, getURLParameter, updateHistory } from '-/utils/dom';import {cleanRootPath,@@ -48,6 +46,7 @@ import {generateSharingLink,joinPaths,normalizePath,+ extractFileExtension,} from '@tagspaces/tagspaces-common/paths';import {formatDateTime4Tag,@@ -64,6 +63,7 @@ import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';import { useEditedEntryContext } from '-/hooks/useEditedEntryContext';import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';+import { CommonLocation } from '-/utils/CommonLocation';type OpenedEntryContextData = {openedEntry: TS.OpenedEntry;@@ -132,14 +132,14 @@ export const OpenedEntryContextProvider = ({const dispatch: AppDispatch = useDispatch();const { t } = useTranslation();+ const { currentLocation, findLocation, openLocation, getLocationPath } =+ useCurrentLocationContext();const {- openLocation,- currentLocation,- getLocationPath,- switchLocationTypeByID,- } = useCurrentLocationContext();- const { currentDirectoryPath, currentLocationPath, openDirectory } =- useDirectoryContentContext();+ currentDirectoryPath,+ currentLocationPath,+ openDirectory,+ getAllPropertiesPromise,+ } = useDirectoryContentContext();const { selectedEntries } = useSelectedEntriesContext();const { showNotification } = useNotificationContext();@@ -148,7 +148,7 @@ export const OpenedEntryContextProvider = ({const { saveFilePromise } = usePlatformFacadeContext();const supportedFileTypes = useSelector(getSupportedFileTypes);- const locations: TS.Location[] = useSelector(getLocations);+ //const locations: CommonLocation[] = useSelector(getLocations);const historyKeys = Pro && Pro.history ? Pro.history.historyKeys : {};const fileOpenHistory = useSelector((state: any) => state.settings[historyKeys.fileOpenKey],@@ -264,20 +264,64 @@ export const OpenedEntryContextProvider = ({if (currentEntry.current &&!currentEntry.current.isFile &&- !PlatformIO.haveObjectStoreSupport() &&- !PlatformIO.haveWebDavSupport()+ !currentLocation.haveObjectStoreSupport() &&+ !currentLocation.haveWebDavSupport()) {- return PlatformIO.getDirProperties(currentEntry.current.path).catch(- (ex) => {- console.debug('getDirProperties:', ex.message);- return Promise.resolve(undefined);- },- );+ return getDirProperties(currentEntry.current.path).catch((ex) => {+ console.debug('getDirProperties:', ex.message);+ return Promise.resolve(undefined);+ });}return Promise.resolve(undefined);}- function setSharedLinks(openedFile?) {+ async function setSharedLinks(openedFile?) {+ if (openedFile) {+ const folderLocation = findLocation(openedFile.locationID);+ const locationPath = await getLocationPath(folderLocation);+ const folderPath = extractContainingDirectoryPath(openedFile.path);+ if (folderPath.indexOf(cleanTrailingDirSeparator(locationPath)) === 0) {+ sharingParentFolderLink.current = generateSharingLink(+ openedFile.locationID,+ undefined,+ cleanRootPath(+ folderPath,+ locationPath,+ folderLocation?.getDirSeparator(),+ ),+ );+ }++ if (openedFile.isFile) {+ const relativePath = getRelativeEntryPath(+ locationPath,+ openedFile.path,+ );+ const relativeDirPath = getRelativeEntryPath(locationPath, folderPath);+ sharingLink.current = generateSharingLink(+ openedFile.locationID,+ relativePath,+ relativeDirPath,+ );+ } else {+ const relativePath = getRelativeEntryPath(+ locationPath,+ openedFile.path,+ );++ sharingLink.current = generateSharingLink(+ openedFile.locationID,+ undefined,+ relativePath,+ );+ }+ } else {+ sharingLink.current = undefined;+ sharingParentFolderLink.current = undefined;+ }+ }++ /*function setSharedLinks(openedFile?) {if (openedFile) {if (window.location.href.indexOf('?') > 0) {const sharingURL = new URL(window.location.href);@@ -286,9 +330,7 @@ export const OpenedEntryContextProvider = ({const locationId = params.get('tslid');//if (params.has('tsdpath')) {// const folderPath2 = params.get('tsdpath');- const folderLocation = locations.find(- (location) => location.uuid === locationId,- );+ const folderLocation = findLocation(locationId);const folderPath = extractContainingDirectoryPath(openedFile.path);if (folderPath.indexOf(@@ -301,7 +343,7 @@ export const OpenedEntryContextProvider = ({cleanRootPath(folderPath,folderLocation.path,- PlatformIO.getDirSeparator(),+ folderLocation?.getDirSeparator(),),);}@@ -340,20 +382,21 @@ export const OpenedEntryContextProvider = ({sharingLink.current = undefined;sharingParentFolderLink.current = undefined;}- }+ }*/function addToEntryContainer(fsEntry: TS.OpenedEntry) {- setSharedLinks(fsEntry);- currentEntry.current = { ...fsEntry };- forceUpdate();+ setSharedLinks(fsEntry).then(() => {+ currentEntry.current = { ...fsEntry };+ forceUpdate();+ });// setOpenedEntries([fsEntry]); // [...openedEntries, fsEntry] // TODO uncomment for multiple file support}function closeOpenedEntries() {- setSharedLinks();- currentEntry.current = undefined;- forceUpdate();- // setOpenedEntries([]);+ setSharedLinks().then(() => {+ currentEntry.current = undefined;+ forceUpdate();+ });}function closeAllFiles() {@@ -387,12 +430,15 @@ export const OpenedEntryContextProvider = ({if (currentEntry.current) {currentEntry.current.editMode = false;//return openEntry(currentEntry.current.path); //true);- return getAllPropertiesPromise(currentEntry.current.path)+ return getAllPropertiesPromise(+ currentEntry.current.path,+ currentEntry.current.locationID,+ ).then((fsEntry: TS.FileSystemEntry) =>openFsEntry({ ...currentEntry.current, ...fsEntry }, undefined),).catch((error) => {- console.warn(+ console.log('Error getting properties for entry: ' +currentEntry.current.path +' - ' +@@ -411,7 +457,7 @@ export const OpenedEntryContextProvider = ({return getAllPropertiesPromise(path).then((fsEntry: TS.FileSystemEntry) => openFsEntry(fsEntry, showDetails)).catch((error) => {- console.warn(+ console.log('Error getting properties for entry: ' + path + ' - ' + error,);return false;@@ -422,30 +468,25 @@ export const OpenedEntryContextProvider = ({fsEntry: TS.FileSystemEntry,showDetails = undefined,): Promise<boolean> {- return switchLocationTypeByID(fsEntry.locationID).then(() => {- return getAllPropertiesPromise(fsEntry.path)- .then((entry: TS.FileSystemEntry) => {- if (entry) {- return openFsEntry(entry, showDetails);- } else {- showNotification(- 'File ' + fsEntry.path + ' not exist on filesystem!',- 'warning',- true,- );- return openFsEntry(fsEntry, showDetails);- }- })- .catch((error) => {- console.warn(- 'Error getting properties for entry: ' +- fsEntry.path +- ' - ' +- error,+ return getAllPropertiesPromise(fsEntry.path, fsEntry.locationID)+ .then((entry: TS.FileSystemEntry) => {+ if (entry) {+ return openFsEntry(entry, showDetails);+ } else {+ showNotification(+ 'File ' + fsEntry.path + ' not exist on filesystem!',+ 'warning',+ true,);- return false;- });- });+ return openFsEntry(fsEntry, showDetails);+ }+ })+ .catch((error) => {+ console.log(+ 'Error getting properties for entry: ' + fsEntry.path + ' - ' + error,+ );+ return false;+ });}function openFsEntry(@@ -456,7 +497,7 @@ export const OpenedEntryContextProvider = ({if (selectedEntries && selectedEntries.length > 0) {const lastSelectedEntry = selectedEntries[selectedEntries.length - 1];if (!lastSelectedEntry.isFile) {- return openDirectory(lastSelectedEntry.path, currentLocation.uuid); //, false);+ return openDirectory(lastSelectedEntry.path); //, false);}} else {return Promise.resolve(false);@@ -487,11 +528,12 @@ export const OpenedEntryContextProvider = ({dispatch(SettingsActions.setShowDetails(showDetails));}entryForOpening = findExtensionsForEntry(fsEntry, supportedFileTypes);- if (PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()) {+ const loc = findLocation(fsEntry.locationID);+ if (loc.haveObjectStoreSupport() || loc.haveWebDavSupport()) {const cleanedPath = fsEntry.path.startsWith('/')? fsEntry.path.substr(1): fsEntry.path;- entryForOpening.url = PlatformIO.getURLforPath(cleanedPath);+ entryForOpening.url = loc.getURLforPath(cleanedPath);} else if (fsEntry.url) {entryForOpening.url = fsEntry.url;}@@ -502,18 +544,16 @@ export const OpenedEntryContextProvider = ({entryForOpening.editMode = true;}- const locationName = currentLocation ? currentLocation.name : 'TagSpaces'; // TODO get it later from app config+ const locationName = loc ? loc.name : 'TagSpaces'; // TODO get it later from app configdocument.title = fsEntry.name + ' | ' + locationName;- if (!entryForOpening.locationId && currentLocation) {- entryForOpening.locationId = currentLocation.uuid;- updateHistory(- { ...currentLocation, path: currentLocationPath },- currentDirectoryPath,- fsEntry.path,- );- }+ // update history window.location.href - used for shared link generation+ updateHistory(+ { ...currentLocation, path: currentLocationPath },+ currentDirectoryPath,+ fsEntry.path,+ );addToEntryContainer(entryForOpening);@@ -602,13 +642,13 @@ export const OpenedEntryContextProvider = ({const cmdOpen = getURLParameter('cmdopen', url);if (cmdOpen && cmdOpen.length > 0) {const entryPath = decodeURIComponent(cmdOpen);- getAllPropertiesPromise(entryPath)+ getAllPropertiesPromise(entryPath, lid).then((fsEntry: TS.FileSystemEntry) => {if (fsEntry.isFile) {openFsEntry(fsEntry);setEntryInFullWidth(options.fullWidth);} else {- openDirectory(fsEntry.path, currentLocation.uuid);+ openDirectory(fsEntry.path);}return true;})@@ -625,11 +665,9 @@ export const OpenedEntryContextProvider = ({directoryPath = extractContainingDirectoryPath(entryPath);}// Check for relative paths- const targetLocation: TS.Location = locations.find(- (location) => location.uuid === locationId,- );+ const targetLocation: CommonLocation = findLocation(locationId);if (targetLocation) {- let openLocationTimer = 1000;+ //let openLocationTimer = 1000;const isCloudLocation =targetLocation.type === locationType.TYPE_CLOUD;if (@@ -637,90 +675,89 @@ export const OpenedEntryContextProvider = ({targetLocation.uuid !== currentLocation.uuid) {openLocation(targetLocation, true);- } else {+ } /*else {openLocationTimer = 0;- }+ }*/getLocationPath(targetLocation).then((path) => {const locationPath: string = cleanTrailingDirSeparator(path);// setTimeout is needed for case of a location switch, if no location swith the timer is 0- setTimeout(() => {- if (isCloudLocation) {- // PlatformIO.enableObjectStoreSupport(targetLocation).then(() => {- if (directoryPath && directoryPath.length > 0) {- const newRelDir = getRelativeEntryPath(path, directoryPath);- const dirFullPath =- locationPath.length > 0- ? locationPath + '/' + newRelDir- : directoryPath;- openDirectory(dirFullPath, targetLocation.uuid);- } else {- openDirectory(locationPath, targetLocation.uuid);- }+ //setTimeout(() => {+ if (isCloudLocation) {+ if (directoryPath && directoryPath.length > 0) {+ const newRelDir = getRelativeEntryPath(path, directoryPath);+ const dirFullPath =+ locationPath.length > 0+ ? locationPath + '/' + newRelDir+ : directoryPath;+ openDirectory(dirFullPath, undefined, targetLocation);+ } else {+ openDirectory(locationPath, undefined, targetLocation);+ }- if (entryPath) {- getAllPropertiesPromise(- (locationPath.length > 0 ? locationPath + '/' : '') +- entryPath,- )- .then((fsEntry: TS.FileSystemEntry) => {- if (fsEntry) {- openFsEntry(fsEntry);- if (options.fullWidth) {- setEntryInFullWidth(true);- }+ if (entryPath) {+ getAllPropertiesPromise(+ (locationPath.length > 0 ? locationPath + '/' : '') ++ entryPath,+ lid,+ )+ .then((fsEntry: TS.FileSystemEntry) => {+ if (fsEntry) {+ openFsEntry(fsEntry);+ if (options.fullWidth) {+ setEntryInFullWidth(true);}- return true;- })- .catch(() =>- showNotification(t('core:invalidLink'), 'warning', true),- );- }- // });- } else {- // local files case- if (directoryPath && directoryPath.length > 0) {- if (- directoryPath.includes('../') ||- directoryPath.includes('..\\')- ) {- showNotification(t('core:invalidLink'), 'warning', true);+ }return true;- }- const dirFullPath = joinPaths(- PlatformIO.getDirSeparator(),- locationPath,- directoryPath,+ })+ .catch(() =>+ showNotification(t('core:invalidLink'), 'warning', true),);- //locationPath + PlatformIO.getDirSeparator() + directoryPath;- openDirectory(dirFullPath, targetLocation.uuid);- } else {- openDirectory(locationPath, targetLocation.uuid);+ }+ // });+ } else {+ // local files case+ if (directoryPath && directoryPath.length > 0) {+ if (+ directoryPath.includes('../') ||+ directoryPath.includes('..\\')+ ) {+ showNotification(t('core:invalidLink'), 'warning', true);+ return true;}+ const dirFullPath = joinPaths(+ targetLocation.getDirSeparator(),+ locationPath,+ directoryPath,+ );+ openDirectory(dirFullPath, undefined, targetLocation);+ } else {+ openDirectory(locationPath, undefined, targetLocation);+ }- if (entryPath && entryPath.length > 0) {- if (entryPath.includes('../') || entryPath.includes('..\\')) {- showNotification(t('core:invalidLink'), 'warning', true);- return true;- }- const entryFullPath =- locationPath + PlatformIO.getDirSeparator() + entryPath;- getAllPropertiesPromise(entryFullPath)- .then((fsEntry: TS.FileSystemEntry) => {- if (fsEntry) {- openFsEntry(fsEntry);- if (options.fullWidth) {- setEntryInFullWidth(true);- }- }- return true;- })- .catch(() =>- showNotification(t('core:invalidLink'), 'warning', true),- );+ if (entryPath && entryPath.length > 0) {+ if (entryPath.includes('../') || entryPath.includes('..\\')) {+ showNotification(t('core:invalidLink'), 'warning', true);+ return true;}+ const entryFullPath =+ locationPath + targetLocation.getDirSeparator() + entryPath;+ getAllPropertiesPromise(entryFullPath, lid)+ .then((fsEntry: TS.FileSystemEntry) => {+ if (fsEntry) {+ openFsEntry(fsEntry);+ if (options.fullWidth) {+ setEntryInFullWidth(true);+ }+ }+ return true;+ })+ .catch(() =>+ showNotification(t('core:invalidLink'), 'warning', true),+ );}- }, openLocationTimer);+ }+ //}, openLocationTimer);});} else {showNotification(t('core:invalidLink'), 'warning', true);@@ -751,7 +788,9 @@ export const OpenedEntryContextProvider = ({if (currentDirectoryPath !== undefined) {const filePath =currentDirectoryPath +- PlatformIO.getDirSeparator() ++ (currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator) +'textfile' +AppConfig.beginTagContainer +formatDateTime4Tag(new Date(), true) +@@ -763,7 +802,7 @@ export const OpenedEntryContextProvider = ({return true;}).catch((err) => {- console.warn('File creation failed with ' + err);+ console.log('File creation failed with ' + err);showNotification(t('core:errorCreatingFile'), 'warning', true);});} else {@@ -786,7 +825,11 @@ export const OpenedEntryContextProvider = ({creationDate.substring(0, 10) +'.';const filePath =- normalizePath(targetPath) + PlatformIO.getDirSeparator() + fileNameAndExt;+ normalizePath(targetPath) ++ (currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator) ++ fileNameAndExt;let fileContent = content;if (fileType === 'html') {fileContent =@@ -810,7 +853,7 @@ export const OpenedEntryContextProvider = ({return true;}).catch((error) => {- console.warn('Error creating file: ' + error);+ console.log('Error creating file: ' + error);showNotification(`Error creating file '${fileNameAndExt}'`,'error',@@ -819,6 +862,66 @@ export const OpenedEntryContextProvider = ({});}+ function addExtensionsForEntry(+ openedEntry: TS.OpenedEntry,+ supportedFileTypes: Array<TS.FileTypes>,+ ): TS.OpenedEntry {+ const fileExtension = extractFileExtension(+ openedEntry.path,+ currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator,+ ).toLowerCase();++ const fileForOpening = { ...openedEntry };+ const fileType: TS.FileTypes = supportedFileTypes.find(+ (fileType) =>+ fileType.viewer && fileType.type.toLowerCase() === fileExtension,+ );+ if (fileType) {+ fileForOpening.viewingExtensionId = fileType.viewer;+ if (fileType.color) {+ fileForOpening.meta = fileForOpening.meta+ ? { ...fileForOpening.meta, color: fileType.color }+ : { id: openedEntry.uuid, color: fileType.color };+ }+ fileForOpening.viewingExtensionPath = findExtensionPathForId(+ fileType.viewer,+ //fileType.extensionExternalPath,+ );+ if (fileType.editor && fileType.editor.length > 0) {+ fileForOpening.editingExtensionId = fileType.editor;+ fileForOpening.editingExtensionPath = findExtensionPathForId(+ fileType.editor,+ //fileType.extensionExternalPath,+ );+ }+ } else {+ fileForOpening.viewingExtensionPath = openedEntry.isFile+ ? findExtensionPathForId('@tagspaces/extensions/text-viewer')+ : 'about:blank';+ }+ return fileForOpening;+ }++ function findExtensionsForEntry(+ entry: TS.FileSystemEntry,+ supportedFileTypes: Array<any>,+ ): TS.OpenedEntry {+ return addExtensionsForEntry(+ {+ ...entry,+ viewingExtensionPath: 'about:blank',+ viewingExtensionId: '',+ /*lmdt: 0,+ size: 0,+ name: '',+ tags: [],*/+ },+ supportedFileTypes,+ );+ }+const context = useMemo(() => {return {openedEntry: currentEntry.current,diff --git a/src/renderer/hooks/PerspectiveSettingsContextProvider.tsx b/src/renderer/hooks/PerspectiveSettingsContextProvider.tsxindex 7f4318385..45bde4848 100644--- a/src/renderer/hooks/PerspectiveSettingsContextProvider.tsx+++ b/src/renderer/hooks/PerspectiveSettingsContextProvider.tsx@@ -27,6 +27,8 @@ import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { TS } from '-/tagspaces.namespace';import { Pro } from '-/pro';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { mergeFsEntryMeta } from '-/services/utils-io';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';type PerspectiveSettingsContextData = {orderBy: boolean;@@ -80,6 +82,7 @@ export type PerspectiveSettingsContextProviderProps = {export const PerspectiveSettingsContextProvider = ({children,}: PerspectiveSettingsContextProviderProps) => {+ const { currentLocation } = useCurrentLocationContext();const {currentDirectoryPath,perspective,@@ -88,7 +91,7 @@ export const PerspectiveSettingsContextProvider = ({getDefaultPerspectiveSettings,getPerspective,} = useDirectoryContentContext();- const { removeFolderCustomSettings, saveMetaDataPromise } =+ const { removeFolderCustomSettings, saveCurrentLocationMetaData } =useIOActionsContext();const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);const settings = useRef<TS.FolderSettings>(@@ -162,12 +165,12 @@ export const PerspectiveSettingsContextProvider = ({isDefaultSetting = !haveLocalSetting();}if (Pro && !isDefaultSetting) {- Pro.MetaOperations.setPerspectiveSettings(+ setPerspectiveSettings(currentDirectoryPath,getPerspective(),settings.current,).then((updatedFsEntryMeta: TS.FileSystemEntryMeta) => {- saveMetaDataPromise(currentDirectoryPath, updatedFsEntryMeta);+ saveCurrentLocationMetaData(currentDirectoryPath, updatedFsEntryMeta);setDirectoryMeta(updatedFsEntryMeta);});} else {@@ -179,6 +182,35 @@ export const PerspectiveSettingsContextProvider = ({}}+ function setPerspectiveSettings(+ path: string,+ perspective: string,+ folderSettings?: TS.FolderSettings,+ ): Promise<TS.FileSystemEntryMeta> {+ return new Promise((resolve, reject) => {+ currentLocation+ .loadMetaDataPromise(path, true)+ .then((fsEntryMeta: TS.FileSystemEntryMeta) => {+ return {+ ...(fsEntryMeta && fsEntryMeta),+ perspectiveSettings: {+ ...(fsEntryMeta &&+ fsEntryMeta.perspectiveSettings &&+ fsEntryMeta.perspectiveSettings),+ [perspective]: folderSettings,+ },+ };+ })+ .catch(() => {+ return mergeFsEntryMeta({+ perspectiveSettings: {+ [perspective]: folderSettings,+ },+ });+ });+ });+ }+const context = useMemo(() => {return {showDirectories: settings.current.showDirectories,diff --git a/src/renderer/hooks/PlatformFacadeContextProvider.tsx b/src/renderer/hooks/PlatformFacadeContextProvider.tsxindex 4138284ef..6e00ac7ba 100644--- a/src/renderer/hooks/PlatformFacadeContextProvider.tsx+++ b/src/renderer/hooks/PlatformFacadeContextProvider.tsx@@ -17,7 +17,6 @@*/import React, { createContext, useMemo } from 'react';-import PlatformFacade from '-/services/platform-facade';import { TS } from '-/tagspaces.namespace';import { useFSWatcherContext } from '-/hooks/useFSWatcherContext';import {@@ -28,83 +27,102 @@ import {getThumbFileLocationForFile,normalizePath,} from '@tagspaces/tagspaces-common/paths';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { useTranslation } from 'react-i18next';import { useSelector } from 'react-redux';import { useEditedEntryContext } from '-/hooks/useEditedEntryContext';-import {- executePromisesInBatches,- getAllPropertiesPromise,- toFsEntry,-} from '-/services/utils-io';+import { executePromisesInBatches } from '-/services/utils-io';import { getUseTrashCan } from '-/reducers/settings';-+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import AppConfig from '-/AppConfig';+import { CommonLocation } from '-/utils/CommonLocation';++interface PlatformParms {+ path: string;+ lmdt?: number;+ locationID?: string;+ total?: number;+}+interface getLocationProps extends Omit<PlatformParms, 'path'> {+ // All the properties from PlatformParms, except 'path'+}type PlatformFacadeContextData = {- createDirectoryPromise: (path: string) => Promise<any>;+ createDirectoryPromise: (path: string, locationID?: string) => Promise<any>;copyFilePromise: (sourceFilePath: string,targetFilePath: string,+ locationID?: string,confirmMessage?: string,) => Promise<any>;copyFilesWithProgress: (paths: Array<string>,targetPath: string,+ locationID: string,onProgress?,reflect?: boolean,) => Promise<boolean>;copyFilePromiseOverwrite: (sourceFilePath: string,targetFilePath: string,+ locationID?: string,reflect?,) => Promise<any>;renameFilePromise: (filePath: string,newFilePath: string,+ locationID: string,onProgress?,reflect?,) => Promise<any>;renameFilesPromise: (renameJobs: Array<Array<string>>,+ locationID: string,onProgress?,reflect?,) => Promise<any>;moveFilePromise: (- filePath: string,+ param: PlatformParms,newFilePath: string,onProgress?,reflect?,) => Promise<any>;moveFilesPromise: (renameJobs: Array<Array<string>>,+ locationID: string,onProgress?,reflect?,) => Promise<any>;reflectMoveFiles: (moveJobs: Array<Array<string>>) => Promise<boolean>;- renameDirectoryPromise: (dirPath: string, newDirName: string) => Promise<any>;+ renameDirectoryPromise: (+ param: PlatformParms,+ newDirName: string,+ ) => Promise<any>;copyDirectoryPromise: (- param: any,+ param: PlatformParms,newDirPath: string,onProgress?,reflect?,) => Promise<any>;moveDirectoryPromise: (- param: any,+ param: PlatformParms,newDirPath: string,onProgress?,reflect?,) => Promise<any>;saveFilePromise: (- param: any,+ param: PlatformParms,content: any,overwrite: boolean,open?: boolean,) => Promise<any>;saveTextFilePromise: (- param: any,+ param: PlatformParms,content: string,overwrite: boolean,) => Promise<any>;saveBinaryFilePromise: (- param: any,+ param: PlatformParms,content: any,overwrite: boolean,onUploadProgress?: (@@ -150,19 +168,34 @@ export const PlatformFacadeContextProvider = ({reflectDeleteEntries,setReflectActions,} = useEditedEntryContext();+ const { currentLocation, findLocation } = useCurrentLocationContext();+ const { getAllPropertiesPromise } = useDirectoryContentContext();const { ignoreByWatcher, deignoreByWatcher, ignored } = useFSWatcherContext(); //watcherconst { t } = useTranslation();const useTrashCan = useSelector(getUseTrashCan);- function createDirectoryPromise(path: string): Promise<any> {+ function getLocation(param: getLocationProps): CommonLocation {+ const { locationID } = param;+ if (locationID) {+ return findLocation(locationID);+ }+ return currentLocation;+ }++ function createDirectoryPromise(+ path: string,+ locationID?: string,+ ): Promise<any> {ignoreByWatcher(path);- return PlatformFacade.createDirectoryPromise(path).then((result) => {- reflectAddEntry(toFsEntry(path, false));- deignoreByWatcher(path);- return result;- });+ return getLocation({ locationID })+ .createDirectoryPromise(path)+ .then((result) => {+ reflectAddEntry(currentLocation.toFsEntry(path, false));+ deignoreByWatcher(path);+ return result;+ });}/**@@ -172,26 +205,27 @@ export const PlatformFacadeContextProvider = ({function setFolderThumbnailPromise(filePath: string): Promise<string> {const directoryPath = extractContainingDirectoryPath(filePath,- PlatformFacade.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const directoryName = extractDirectoryName(directoryPath,- PlatformFacade.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const sourceThumbPath = getThumbFileLocationForFile(filePath,- PlatformFacade.getDirSeparator(),+ currentLocation?.getDirSeparator(),false,);const destThumbPath = getThumbFileLocationForDirectory(directoryPath,- PlatformFacade.getDirSeparator(),+ currentLocation?.getDirSeparator(),);return copyFilePromise(sourceThumbPath,destThumbPath,+ undefined,t('core:thumbAlreadyExists', { directoryName }),).then(() => {// dispatch(AppActions.setLastThumbnailImageChange(destThumbPath));@@ -202,31 +236,41 @@ export const PlatformFacadeContextProvider = ({function copyFilePromise(sourceFilePath: string,targetFilePath: string,+ locationID: string,confirmMessage: string = 'File ' +targetFilePath +' exist do you want to override it?',): Promise<any> {- return PlatformFacade.getPropertiesPromise(targetFilePath).then(- (isTargetExist) => {+ return getLocation({ locationID })+ .getPropertiesPromise(targetFilePath)+ .then((isTargetExist) => {if (isTargetExist) {// eslint-disable-next-line no-alertconst confirmOverwrite = window && window.confirm(confirmMessage);if (confirmOverwrite === true) {- return copyFilePromiseOverwrite(sourceFilePath, targetFilePath);+ return copyFilePromiseOverwrite(+ sourceFilePath,+ targetFilePath,+ locationID,+ );}// eslint-disable-next-line prefer-promise-reject-errorsreturn Promise.reject('File "' + targetFilePath + '" exists. Copying failed.',);}- return copyFilePromiseOverwrite(sourceFilePath, targetFilePath);- },- );+ return copyFilePromiseOverwrite(+ sourceFilePath,+ targetFilePath,+ locationID,+ );+ });}function copyFilesWithProgress(paths: string[],targetPath: string,+ locationID: string,onProgress = undefined,reflect = true,): Promise<boolean> {@@ -236,10 +280,12 @@ export const PlatformFacadeContextProvider = ({const ioJobPromises = paths.map((path) => {const targetFile =normalizePath(targetPath) +- PlatformFacade.getDirSeparator() +- extractFileName(path, PlatformFacade.getDirSeparator());+ (currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator) ++ extractFileName(path, currentLocation?.getDirSeparator());return {- promise: copyFilePromiseOverwrite(path, targetFile, false),+ promise: copyFilePromiseOverwrite(path, targetFile, locationID, false),path: path,};});@@ -261,11 +307,14 @@ export const PlatformFacadeContextProvider = ({};return trackProgress(ioJobPromises, signal, progress).then(() => {if (reflect) {- const targetPaths = paths.map(- (path) =>+ const targetPaths = paths.map((path) =>+ getAllPropertiesPromise(normalizePath(targetPath) +- PlatformFacade.getDirSeparator() +- extractFileName(path, PlatformFacade.getDirSeparator()),+ (currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator) ++ extractFileName(path, currentLocation?.getDirSeparator()),+ ),);return reflectAddEntryPath(...targetPaths);}@@ -295,7 +344,7 @@ export const PlatformFacadeContextProvider = ({if (progress) {progress(completed, path);}- console.warn('Promise ' + path + ' error:', err);+ console.log('Promise ' + path + ' error:', err);}),);@@ -305,7 +354,7 @@ export const PlatformFacadeContextProvider = ({.catch((err) => {if (abortSignal.aborted) {aborted = true;- console.warn('Promise execution aborted');+ console.log('Promise execution aborted');} else {throw err;}@@ -315,26 +364,28 @@ export const PlatformFacadeContextProvider = ({function copyFilePromiseOverwrite(sourceFilePath: string,targetFilePath: string,+ locationID: string,reflect: boolean = true,): Promise<any> {ignoreByWatcher(targetFilePath);- return PlatformFacade.copyFilePromiseOverwrite(- sourceFilePath,- targetFilePath,- ).then((result) => {- if (reflect) {- getAllPropertiesPromise(targetFilePath).then(- (fsEntry: TS.FileSystemEntry) => reflectAddEntry(fsEntry, false),- );- }- deignoreByWatcher(targetFilePath);- return result;- });+ const location = getLocation({ locationID });+ return location+ .copyFilePromiseOverwrite(sourceFilePath, targetFilePath)+ .then((result) => {+ if (reflect) {+ getAllPropertiesPromise(targetFilePath, location.uuid).then(+ (fsEntry: TS.FileSystemEntry) => reflectAddEntry(fsEntry, false),+ );+ }+ deignoreByWatcher(targetFilePath);+ return result;+ });}/*** @param filePath* @param newFilePath+ * @param locationID* @param onProgress* @param reflect* return Promise<TS.FileSystemEntry> new file entry renamed@@ -342,48 +393,49 @@ export const PlatformFacadeContextProvider = ({function renameFilePromise(filePath: string,newFilePath: string,+ locationID: string = undefined,onProgress = undefined,reflect = true,): Promise<TS.FileSystemEntry> {ignoreByWatcher(filePath, newFilePath);- return PlatformFacade.renameFilePromise(- filePath,- newFilePath,- onProgress,- ).then((result) => {- deignoreByWatcher(filePath, newFilePath);- return getAllPropertiesPromise(newFilePath).then(- (fsEntry: TS.FileSystemEntry) => {- if (reflect) {- setReflectActions({- action: 'update',- entry: fsEntry,- oldEntryPath: filePath,- });- }- return fsEntry;- },- );- });+ return getLocation({ locationID })+ .renameFilePromise(filePath, newFilePath, onProgress)+ .then((result) => {+ deignoreByWatcher(filePath, newFilePath);+ return getAllPropertiesPromise(newFilePath).then(+ (fsEntry: TS.FileSystemEntry) => {+ if (reflect) {+ setReflectActions({+ action: 'update',+ entry: fsEntry,+ oldEntryPath: filePath,+ });+ }+ return fsEntry;+ },+ );+ });}function renameFilesPromise(renameJobs: Array<Array<string>>,+ locationID: string = undefined,onProgress = undefined,reflect = true,): Promise<any> {const flatArray = renameJobs.flat();ignoreByWatcher(...flatArray);+ const location = getLocation({ locationID });return executePromisesInBatches(renameJobs.map(async (renameJob) => {try {- return await PlatformFacade.renameFilePromise(+ return await location.renameFilePromise(renameJob[0],renameJob[1],onProgress,);} catch (err) {- console.warn('Error rename file:', err);+ console.log('Error rename file:', err);return false;}}),@@ -391,7 +443,7 @@ export const PlatformFacadeContextProvider = ({if (reflect) {const actions: TS.EditAction[] = renameJobs.map((job) => ({action: 'update',- entry: toFsEntry(job[1], true),+ entry: location.toFsEntry(job[1], true),oldEntryPath: job[0],}));setReflectActions(...actions);@@ -402,27 +454,26 @@ export const PlatformFacadeContextProvider = ({}function moveFilePromise(- filePath: string,+ param: PlatformParms,newFilePath: string,onProgress = undefined,reflect = true,): Promise<any> {- ignoreByWatcher(filePath, newFilePath);- return PlatformFacade.renameFilePromise(- filePath,- newFilePath,- onProgress,- ).then((result) => {- if (reflect) {- reflectMoveFiles([[filePath, newFilePath]]);- }- deignoreByWatcher(filePath, newFilePath);- return result;- });+ ignoreByWatcher(param.path, newFilePath);+ return getLocation(param)+ .renameFilePromise(param.path, newFilePath, onProgress)+ .then((result) => {+ if (reflect) {+ reflectMoveFiles([[param.path, newFilePath]]);+ }+ deignoreByWatcher(param.path, newFilePath);+ return result;+ });}function moveFilesPromise(renameJobs: Array<Array<string>>,+ locationID: string,onProgress = undefined,reflect = true,): Promise<any> {@@ -431,13 +482,13 @@ export const PlatformFacadeContextProvider = ({return executePromisesInBatches(renameJobs.map(async (renameJob) => {try {- return await PlatformFacade.renameFilePromise(+ return await getLocation({ locationID }).renameFilePromise(renameJob[0],renameJob[1],onProgress,);} catch (err) {- console.warn('Error rename file:', err);+ console.log('Error rename file:', err);return undefined;}}),@@ -479,100 +530,104 @@ export const PlatformFacadeContextProvider = ({}function renameDirectoryPromise(- dirPath: string,+ param: PlatformParms,newDirName: string,): Promise<any> {- ignoreByWatcher(dirPath, newDirName);- return PlatformFacade.renameDirectoryPromise(dirPath, newDirName).then(- (newDirPath) => {+ ignoreByWatcher(param.path, newDirName);+ return getLocation(param)+ .renameDirectoryPromise(param.path, newDirName)+ .then((newDirPath) => {getAllPropertiesPromise(newDirPath).then((fsEntry: TS.FileSystemEntry) =>setReflectActions({action: 'update',entry: fsEntry,- oldEntryPath: dirPath,+ oldEntryPath: param.path,}),);- deignoreByWatcher(dirPath, newDirName);+ deignoreByWatcher(param.path, newDirName);return newDirPath;- },- );+ });}function copyDirectoryPromise(- param: any,+ param: PlatformParms,newDirPath: string,onProgress = undefined,reflect = true,): Promise<any> {ignoreByWatcher(param.path, newDirPath);- return PlatformFacade.copyDirectoryPromise(- param,- newDirPath,- onProgress,- ).then((result) => {- if (reflect) {- getAllPropertiesPromise(param.path).then(- (fsEntry: TS.FileSystemEntry) => reflectAddEntry(fsEntry),- );- }- deignoreByWatcher(param.path, newDirPath);- return result;- });+ return getLocation(param)+ .copyDirectoryPromise(param, newDirPath, onProgress)+ .then((result) => {+ if (reflect) {+ getAllPropertiesPromise(param.path).then(+ (fsEntry: TS.FileSystemEntry) => reflectAddEntry(fsEntry),+ );+ }+ deignoreByWatcher(param.path, newDirPath);+ return result;+ });}function moveDirectoryPromise(- param: any,+ param: PlatformParms,newDirPath: string,onProgress = undefined,reflect = true,): Promise<any> {ignoreByWatcher(param.path, newDirPath);- return PlatformFacade.moveDirectoryPromise(- param,- newDirPath,- onProgress,- ).then((result) => {- if (reflect) {- getAllPropertiesPromise(newDirPath).then(- (fsEntry: TS.FileSystemEntry) =>- setReflectActions({- action: 'move',- entry: fsEntry,- oldEntryPath: param.path,- }),- );- }+ const location = getLocation(param);+ return location+ .moveDirectoryPromise(param, newDirPath, onProgress)+ .then((result) => {+ if (reflect) {+ getAllPropertiesPromise(newDirPath, location.uuid).then(+ (fsEntry: TS.FileSystemEntry) =>+ setReflectActions({+ action: 'move',+ entry: fsEntry,+ oldEntryPath: param.path,+ }),+ );+ }- deignoreByWatcher(param.path, newDirPath);- return result;- });+ deignoreByWatcher(param.path, newDirPath);+ return result;+ });}function saveFilePromise(- param: any,+ param: PlatformParms,content: any,overwrite: boolean,open: boolean = false,): Promise<TS.FileSystemEntry> {ignoreByWatcher(param.path);- return PlatformFacade.saveFilePromise(param, content, overwrite).then(- (fsEntry) => {- reflectAddEntry(fsEntry, open);+ const location = getLocation(param);+ return location+ .saveFilePromise(param, content, overwrite)+ .then((fsEntry) => {+ const entry = {+ ...fsEntry,+ uuid: getUuid(),+ locationID: location.uuid,+ };+ reflectAddEntry(entry, open);deignoreByWatcher(param.path);- return fsEntry;- },- );+ return entry;+ });}function saveTextFilePromise(- param: any,+ param: PlatformParms,content: string,isUpdated: boolean,): Promise<TS.FileSystemEntry> {ignoreByWatcher(param.path);- return PlatformFacade.saveTextFilePromise(param, content, isUpdated).then(- (fsEntry) => {+ return getLocation(param)+ .saveTextFilePromise(param, content, isUpdated)+ .then((fsEntry) => {if (isUpdated) {setReflectActions({action: 'update',@@ -583,12 +638,11 @@ export const PlatformFacadeContextProvider = ({}deignoreByWatcher(param.path);return fsEntry;- },- );+ });}function saveBinaryFilePromise(- param: any,+ param: PlatformParms,content: any,overwrite: boolean,onUploadProgress?: (@@ -598,18 +652,15 @@ export const PlatformFacadeContextProvider = ({reflect: boolean = true,): Promise<TS.FileSystemEntry> {ignoreByWatcher(param.path);- return PlatformFacade.saveBinaryFilePromise(- param,- content,- overwrite,- onUploadProgress,- ).then((fsEntry) => {- if (reflect) {- reflectAddEntry(fsEntry, false);- }- deignoreByWatcher(param.path);- return fsEntry;- });+ return getLocation(param)+ .saveBinaryFilePromise(param, content, overwrite, onUploadProgress)+ .then((fsEntry) => {+ if (reflect) {+ reflectAddEntry(fsEntry, false);+ }+ deignoreByWatcher(param.path);+ return fsEntry;+ });}function deleteEntriesPromise(@@ -620,9 +671,9 @@ export const PlatformFacadeContextProvider = ({ignoreByWatcher(...entriesPaths);const promises = entries.map((e) => {if (e.isFile) {- return PlatformFacade.deleteFilePromise(e.path, useTrashCan);+ return getLocation(e).deleteFilePromise(e.path, useTrashCan);}- return PlatformFacade.deleteDirectoryPromise(e.path, useTrashCan);+ return getLocation(e).deleteDirectoryPromise(e.path, useTrashCan);});return executePromisesInBatches(promises).then(() => {reflectDeleteEntries(...entries);@@ -633,6 +684,30 @@ export const PlatformFacadeContextProvider = ({return Promise.resolve(false);}+ /*function loadTextFilePromise(+ locationID: string,+ path: string,+ isPreview?: boolean,+ ): Promise<string> {+ const location = findLocation(locationID);+ if(location){+ return location.loadTextFilePromise(path, isPreview);+ }+ return Promise.reject(new Error('loadTextFilePromise: no location locationID:'+locationID));+ }++ function getFileContentPromise(+ locationID: string,+ filePath: string,+ type?: string,+ ): Promise<string> {+ const location = findLocation(locationID);+ if(location){+ return location.getFileContentPromise(filePath, type);+ }+ return Promise.reject(new Error('getFileContentPromise: no location locationID:'+locationID));+ }*/+const context = useMemo(() => {return {createDirectoryPromise,@@ -653,7 +728,7 @@ export const PlatformFacadeContextProvider = ({deleteEntriesPromise,setFolderThumbnailPromise,};- }, [ignored]); //watcher+ }, [ignored, currentLocation]); //watcherreturn (<PlatformFacadeContext.Provider value={context}>diff --git a/src/renderer/hooks/TagGroupsLocationContextProvider.tsx b/src/renderer/hooks/TagGroupsLocationContextProvider.tsxindex 3a6970a36..15616e930 100644--- a/src/renderer/hooks/TagGroupsLocationContextProvider.tsx+++ b/src/renderer/hooks/TagGroupsLocationContextProvider.tsx@@ -18,43 +18,39 @@import React, { createContext, useMemo } from 'react';import { TS } from '-/tagspaces.namespace';-import {- getDescriptionPreview,- loadJSONFile,- mergeFsEntryMeta,-} from '-/services/utils-io';+import { getDescriptionPreview, mergeFsEntryMeta } from '-/services/utils-io';import {getMetaDirectoryPath,getMetaFileLocationForDir,} from '@tagspaces/tagspaces-common/paths';-import PlatformIO from '-/services/platform-facade';import AppConfig from '-/AppConfig';import versionMeta from '-/version.json';import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';import { useSelector } from 'react-redux';import { getSaveTagInLocation } from '-/reducers/settings';+import { CommonLocation } from '-/utils/CommonLocation';type TagGroupsLocationContextData = {- getTagGroups: (path: string) => Promise<TS.TagGroup[]>;+ getTagGroups: (location: CommonLocation) => Promise<TS.TagGroup[]>;createLocationTagGroup: (- path: string,+ location: CommonLocation,tagGroup: TS.TagGroup,) => Promise<TS.FileSystemEntryMeta>;editLocationTagGroup: (- path: string,+ location: CommonLocation,tagGroup: TS.TagGroup,replaceTags?,) => Promise<TS.FileSystemEntryMeta>;removeLocationTagGroup: (- path: string,+ location: CommonLocation,tagGroupUuid: string,) => Promise<TS.FileSystemEntryMeta>;mergeLocationTagGroup: (- path: string,+ location: CommonLocation,tagGroup: TS.TagGroup,) => Promise<TS.FileSystemEntryMeta>;loadLocationDataPromise: (- path: string,+ location: CommonLocation,metaFile?,) => Promise<TS.FileSystemEntryMeta>;};@@ -94,8 +90,8 @@ export const TagGroupsLocationContextProvider = ({}}, [currentLocation]);*/- function getTagGroups(path: string): Promise<TS.TagGroup[]> {- return loadLocationDataPromise(path).then(+ function getTagGroups(location: CommonLocation): Promise<TS.TagGroup[]> {+ return loadLocationDataPromise(location).then((fsEntryMeta: TS.FileSystemEntryMeta) => {if (fsEntryMeta) {return fsEntryMeta.tagGroups;@@ -106,37 +102,36 @@ export const TagGroupsLocationContextProvider = ({}async function loadLocationDataPromise(- path: string,+ location: CommonLocation,metaFile = AppConfig.folderLocationsFile,): Promise<TS.FileSystemEntryMeta> {if (saveTagInLocation) {- const entryProperties = await PlatformIO.getPropertiesPromise(path);- if (!entryProperties.isFile) {- const metaFilePath = getMetaFileLocationForDir(- path,- PlatformIO.getDirSeparator(),- metaFile,- );- const metaData = await loadJSONFile(metaFilePath);- if (metaData) {- return {- ...metaData,- description: getDescriptionPreview(metaData.description, 200),- };- }+ //const entryProperties = await location.getPropertiesPromise(location.path);+ //if (!entryProperties.isFile) {+ const metaFilePath = getMetaFileLocationForDir(+ location.path,+ location.getDirSeparator(),+ metaFile,+ );+ const metaData = await location.loadJSONFile(metaFilePath);+ if (metaData) {+ return {+ ...metaData,+ description: getDescriptionPreview(metaData.description, 200),+ };}}return Promise.resolve(undefined);}function createLocationTagGroup(- path: string,+ location: CommonLocation,tagGroup: TS.TagGroup,): Promise<TS.FileSystemEntryMeta> {if (!saveTagInLocation) {return Promise.resolve(undefined);}- return loadLocationDataPromise(path)+ return loadLocationDataPromise(location).then((fsEntryMeta: TS.FileSystemEntryMeta) => {let tagGroups;if (@@ -156,7 +151,7 @@ export const TagGroupsLocationContextProvider = ({...(fsEntryMeta && fsEntryMeta),tagGroups,};- return saveLocationDataPromise(path, updatedEntryMeta)+ return saveLocationDataPromise(location, updatedEntryMeta).then(() => {return updatedEntryMeta;})@@ -168,7 +163,7 @@ export const TagGroupsLocationContextProvider = ({const newFsEntryMeta: TS.FileSystemEntryMeta = mergeFsEntryMeta({tagGroups: [tagGroup],});- return saveLocationDataPromise(path, newFsEntryMeta)+ return saveLocationDataPromise(location, newFsEntryMeta).then(() => {return newFsEntryMeta;})@@ -179,7 +174,7 @@ export const TagGroupsLocationContextProvider = ({}function editLocationTagGroup(- path: string,+ location: CommonLocation,tagGroup: TS.TagGroup,replaceTags = false,): Promise<TS.FileSystemEntryMeta> {@@ -187,7 +182,7 @@ export const TagGroupsLocationContextProvider = ({return Promise.resolve(undefined);}return new Promise((resolve, reject) => {- loadLocationDataPromise(path)+ loadLocationDataPromise(location).then((fsEntryMeta: TS.FileSystemEntryMeta) => {const oldTagGroup = fsEntryMeta.tagGroups.find((group) => group.uuid === tagGroup.uuid,@@ -226,14 +221,17 @@ export const TagGroupsLocationContextProvider = ({...fsEntryMeta,tagGroups,};- saveLocationDataPromise(path, updatedEntryMeta)+ saveLocationDataPromise(location, updatedEntryMeta).then(() => {resolve(updatedEntryMeta);return true;}).catch((err) => {- console.warn(- 'Error adding perspective for ' + path + ' with ' + err,+ console.log(+ 'Error adding perspective for ' ++ location.path ++ ' with ' ++ err,);reject();});@@ -243,14 +241,17 @@ export const TagGroupsLocationContextProvider = ({const newFsEntryMeta: TS.FileSystemEntryMeta = mergeFsEntryMeta({tagGroups: [tagGroup],});- saveLocationDataPromise(path, newFsEntryMeta)+ saveLocationDataPromise(location, newFsEntryMeta).then(() => {resolve(newFsEntryMeta);return true;}).catch((error) => {- console.warn(- 'Error adding perspective for ' + path + ' with ' + error,+ console.log(+ 'Error adding perspective for ' ++ location.path ++ ' with ' ++ error,);reject();});@@ -259,14 +260,14 @@ export const TagGroupsLocationContextProvider = ({}function removeLocationTagGroup(- path: string,+ location: CommonLocation,tagGroupUuid: string,): Promise<TS.FileSystemEntryMeta> {if (!saveTagInLocation) {return Promise.resolve(undefined);}return new Promise((resolve, reject) => {- loadLocationDataPromise(path)+ loadLocationDataPromise(location).then((fsEntryMeta: TS.FileSystemEntryMeta) => {const tagGroups = fsEntryMeta.tagGroups.filter((group) => group.uuid !== tagGroupUuid,@@ -275,14 +276,17 @@ export const TagGroupsLocationContextProvider = ({...fsEntryMeta,tagGroups,};- saveLocationDataPromise(path, updatedEntryMeta)+ saveLocationDataPromise(location, updatedEntryMeta).then(() => {resolve(updatedEntryMeta);return true;}).catch((err) => {- console.warn(- 'Error adding perspective for ' + path + ' with ' + err,+ console.log(+ 'Error adding perspective for ' ++ location.path ++ ' with ' ++ err,);reject();});@@ -295,14 +299,14 @@ export const TagGroupsLocationContextProvider = ({}function mergeLocationTagGroup(- path: string,+ location: CommonLocation,tagGroup: TS.TagGroup,): Promise<TS.FileSystemEntryMeta> {if (!saveTagInLocation) {return Promise.resolve(undefined);}return new Promise((resolve, reject) => {- loadLocationDataPromise(path)+ loadLocationDataPromise(location).then((fsEntryMeta: TS.FileSystemEntryMeta) => {const oldTagGroup = fsEntryMeta.tagGroups.find((group) => group.uuid === tagGroup.uuid,@@ -318,14 +322,17 @@ export const TagGroupsLocationContextProvider = ({...fsEntryMeta,tagGroups,};- saveLocationDataPromise(path, updatedEntryMeta)+ saveLocationDataPromise(location, updatedEntryMeta).then(() => {resolve(updatedEntryMeta);return true;}).catch((err) => {- console.warn(- 'Error adding perspective for ' + path + ' with ' + err,+ console.log(+ 'Error adding perspective for ' ++ location.path ++ ' with ' ++ err,);reject();});@@ -335,14 +342,17 @@ export const TagGroupsLocationContextProvider = ({const newFsEntryMeta: TS.FileSystemEntryMeta = mergeFsEntryMeta({tagGroups: [tagGroup],});- saveLocationDataPromise(path, newFsEntryMeta)+ saveLocationDataPromise(location, newFsEntryMeta).then(() => {resolve(newFsEntryMeta);return true;}).catch((error) => {- console.warn(- 'Error adding perspective for ' + path + ' with ' + error,+ console.log(+ 'Error adding perspective for ' ++ location.path ++ ' with ' ++ error,);reject();});@@ -351,43 +361,47 @@ export const TagGroupsLocationContextProvider = ({}async function saveLocationDataPromise(- path: string,+ location: CommonLocation,metaData: any,): Promise<any> {if (!saveTagInLocation) {return Promise.resolve(undefined);}- const entryProperties = await PlatformIO.getPropertiesPromise(path);- if (entryProperties) {- let metaFilePath;- if (!entryProperties.isFile) {- // check and create meta folder if not exist- // todo not need to check if folder exist first createDirectoryPromise() recursively will skip creation of existing folders https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback- const metaDirectoryPath = getMetaDirectoryPath(- path,- PlatformIO.getDirSeparator(),- );- const metaDirectoryProperties =- await PlatformIO.getPropertiesPromise(metaDirectoryPath);- if (!metaDirectoryProperties) {- await createDirectoryPromise(metaDirectoryPath);- }-- metaFilePath = getMetaFileLocationForDir(- path,- PlatformIO.getDirSeparator(),- AppConfig.folderLocationsFile,- );- }- const content = JSON.stringify({- ...metaData,- appName: versionMeta.name,- appVersion: versionMeta.version,- lastUpdated: new Date().toJSON(),- });- return saveTextFilePromise({ path: metaFilePath }, content, true);+ // const entryProperties = await location.getPropertiesPromise(location.path);+ // if (entryProperties) {+ let metaFilePath;+ // if (!entryProperties.isFile) {+ // check and create meta folder if not exist+ // todo not need to check if folder exist first createDirectoryPromise() recursively will skip creation of existing folders https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback+ const metaDirectoryPath = getMetaDirectoryPath(+ location.path,+ location.getDirSeparator(),+ );+ const metaDirectoryProperties =+ await location.getPropertiesPromise(metaDirectoryPath);+ if (!metaDirectoryProperties) {+ await createDirectoryPromise(metaDirectoryPath, location.uuid);}- return Promise.reject(new Error('file not found' + path));++ metaFilePath = getMetaFileLocationForDir(+ location.path,+ location.getDirSeparator(),+ AppConfig.folderLocationsFile,+ );+ //}+ const content = JSON.stringify({+ ...metaData,+ appName: versionMeta.name,+ appVersion: versionMeta.version,+ lastUpdated: new Date().toJSON(),+ });+ return saveTextFilePromise(+ { path: metaFilePath, locationID: location.uuid },+ content,+ true,+ );+ // }+ // return Promise.reject(new Error('file not found' + path));}const context = useMemo(() => {diff --git a/src/renderer/hooks/TaggingActionsContextProvider.tsx b/src/renderer/hooks/TaggingActionsContextProvider.tsxindex e9584f43e..3cd00b108 100644--- a/src/renderer/hooks/TaggingActionsContextProvider.tsx+++ b/src/renderer/hooks/TaggingActionsContextProvider.tsx@@ -39,22 +39,13 @@ import {getTagDelimiter,getTagTextColor,} from '-/reducers/settings';-import PlatformIO from '-/services/platform-facade';-import {- generateFileName,- getAllPropertiesPromise,- loadDirMetaDataPromise,- loadFileMetaDataPromise,- loadMetaDataPromise,- parseNewTags,-} from '-/services/utils-io';+import { generateFileName, parseNewTags } from '-/services/utils-io';import {extractContainingDirectoryPath,extractFileName,extractTags,} from '@tagspaces/tagspaces-common/paths';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';-import { getLocations } from '-/reducers/locations';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';@@ -64,6 +55,7 @@ import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useTagGroupsLocationContext } from '-/hooks/useTagGroupsLocationContext';import AppConfig from '-/AppConfig';import { useEditedTagLibraryContext } from '-/hooks/useEditedTagLibraryContext';+import { CommonLocation } from '-/utils/CommonLocation';type extractOptions = {EXIFGeo?: boolean;@@ -88,7 +80,7 @@ type TaggingActionsContextData = {collectTagsFromLocation: (tagGroup: TS.TagGroup) => void;createTagGroup: (entry: TS.TagGroup,- location?: TS.Location,+ location?: CommonLocation,) => Promise<boolean>;mergeTagGroup: (entry: TS.TagGroup) => void;removeTagGroup: (parentTagGroupUuid: TS.Uuid) => void;@@ -153,7 +145,7 @@ export const TaggingActionsContextProvider = ({children,}: TaggingActionsContextProviderProps) => {const { t } = useTranslation();- const { currentLocation, persistTagsInSidecarFile } =+ const { findLocation, currentLocation, persistTagsInSidecarFile } =useCurrentLocationContext();const { tagGroups, reflectTagLibraryChanged } = useEditedTagLibraryContext();const {@@ -163,9 +155,11 @@ export const TaggingActionsContextProvider = ({removeLocationTagGroup,mergeLocationTagGroup,} = useTagGroupsLocationContext();- const { currentDirectoryEntries } = useDirectoryContentContext();+ const { currentDirectoryEntries, getAllPropertiesPromise } =+ useDirectoryContentContext();const { getIndex } = useLocationIndexContext();- const { renameFile, saveMetaDataPromise } = useIOActionsContext();+ const { renameFile, saveMetaDataPromise, saveCurrentLocationMetaData } =+ useIOActionsContext();const { reflectUpdateMeta, setReflectActions } = useEditedEntryContext();const { showNotification, hideNotifications } = useNotificationContext();const dispatch: AppDispatch = useDispatch();@@ -175,7 +169,7 @@ export const TaggingActionsContextProvider = ({const tagTextColor: string = useSelector(getTagTextColor);const tagDelimiter: string = useSelector(getTagDelimiter);const prefixTagContainer: boolean = useSelector(getPrefixTagContainer);- const locations: TS.Location[] = useSelector(getLocations);+ //const locations: CommonLocation[] = useSelector(getLocations);const saveTagInLocation: boolean = useSelector(getSaveTagInLocation);useEffect(() => {@@ -186,7 +180,7 @@ export const TaggingActionsContextProvider = ({function refreshTagsFromLocation() {if (currentLocation) {- getTagGroups(currentLocation.path).then((locationTagGroups) => {+ getTagGroups(currentLocation).then((locationTagGroups) => {if (locationTagGroups && locationTagGroups.length > 0) {const oldGroups = getTagLibrary();if (checkTagGroupModified(locationTagGroups, oldGroups)) {@@ -223,6 +217,7 @@ export const TaggingActionsContextProvider = ({showNotification('Extracting content...', 'info', false);return Pro.ContentExtractor.extractContent(currentDirectoryEntries,+ currentLocation.getFileContentPromise,options,).then((extracted: { [filePath: string]: TS.Tag[] }) => {hideNotifications();@@ -235,25 +230,32 @@ export const TaggingActionsContextProvider = ({const extractedTags: string[] = extractTags(path,tagDelimiter,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const uniqueTags = tags.filter((tag) => !extractedTags.some((tagName) => tagName === tag),);- const fileName = extractFileName(path, PlatformIO.getDirSeparator());+ const fileName = extractFileName(+ path,+ currentLocation?.getDirSeparator(),+ );const containingDirectoryPath = extractContainingDirectoryPath(path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);return ((containingDirectoryPath- ? containingDirectoryPath + PlatformIO.getDirSeparator()+ ? containingDirectoryPath ++ (currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator): '') +generateFileName(fileName,[...extractedTags, ...uniqueTags],tagDelimiter,+ currentLocation?.getDirSeparator(),prefixTagContainer,));@@ -396,14 +398,6 @@ export const TaggingActionsContextProvider = ({files[path] = processedTags;});return addFilesTags(files);-- /*return Promise.all(promises).then((editedPaths) => {- let sideCarChanges = editedPaths.filter((item) => paths.includes(item));- if (sideCarChanges.length > 0) {- reflectUpdateMeta(...sideCarChanges);- }- return true;- });*/}return Promise.resolve(false);}@@ -465,8 +459,8 @@ export const TaggingActionsContextProvider = ({let fsEntryMeta;try {fsEntryMeta = entry.isFile- ? await loadFileMetaDataPromise(entry.path)- : await loadDirMetaDataPromise(entry.path);+ ? await currentLocation.loadFileMetaDataPromise(entry.path)+ : await currentLocation.loadDirMetaDataPromise(entry.path);} catch (error) {console.log('No sidecar found ' + error);}@@ -476,7 +470,11 @@ export const TaggingActionsContextProvider = ({if (fsEntryMeta) {const uniqueTags = getNonExistingTags(tags,- extractTags(entry.path, tagDelimiter, PlatformIO.getDirSeparator()),+ extractTags(+ entry.path,+ tagDelimiter,+ currentLocation?.getDirSeparator(),+ ),fsEntryMeta.tags,);if (uniqueTags.length > 0) {@@ -485,15 +483,15 @@ export const TaggingActionsContextProvider = ({...fsEntryMeta,tags: newTags,};- return saveMetaDataPromise(entry.path, updatedFsEntryMeta)+ return saveMetaDataPromise(entry, updatedFsEntryMeta).then(() => {if (reflect) {- reflectUpdateMeta(entry.path);+ reflectUpdateMeta(entry);}return entry.path;}).catch((err) => {- console.warn(+ console.log('Error adding tags for ' + entry.path + ' with ' + err,);showNotification(@@ -506,15 +504,15 @@ export const TaggingActionsContextProvider = ({}} else {const newFsEntryMeta = { tags };- return saveMetaDataPromise(entry.path, newFsEntryMeta)+ return saveMetaDataPromise(entry, newFsEntryMeta).then(() => {if (reflect) {- reflectUpdateMeta(entry.path);+ reflectUpdateMeta(entry);}return entry.path;}).catch((error) => {- console.warn(+ console.log('Error adding tags for ' + entry.path + ' with ' + error,);showNotification(@@ -530,7 +528,7 @@ export const TaggingActionsContextProvider = ({const extractedTags = extractTags(entry.path,tagDelimiter,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const uniqueTags = getNonExistingTags(tags,@@ -543,7 +541,12 @@ export const TaggingActionsContextProvider = ({uniqueTags.map((tag) => tag.title),);if (entry.path !== newFilePath) {- return renameFile(entry.path, newFilePath, reflect).then(() => {+ return renameFile(+ entry.path,+ newFilePath,+ entry.locationID,+ reflect,+ ).then(() => {return newFilePath;});}@@ -555,7 +558,12 @@ export const TaggingActionsContextProvider = ({tags.map((tag) => tag.title),);if (entry.path !== newFilePath) {- return renameFile(entry.path, newFilePath, reflect).then(() => {+ return renameFile(+ entry.path,+ newFilePath,+ entry.locationID,+ reflect,+ ).then(() => {return newFilePath;});}@@ -597,9 +605,9 @@ export const TaggingActionsContextProvider = ({tags: Array<TS.Tag>,reflect: boolean = true,): Promise<string> {- return PlatformIO.getPropertiesPromise(path).then((entry) =>- addTagsToFsEntry(entry, tags, reflect),- );+ return currentLocation+ .getPropertiesPromise(path)+ .then((entry) => addTagsToFsEntry(entry, tags, reflect));}/**@@ -624,7 +632,7 @@ export const TaggingActionsContextProvider = ({) {// Work around solutiondelete tag.functionality;- const entryProperties = await PlatformIO.getPropertiesPromise(path);+ const entryProperties = await currentLocation.getPropertiesPromise(path);if (entryProperties.isFile && !persistTagsInSidecarFile) {tag.type = 'plain';}@@ -637,15 +645,18 @@ export const TaggingActionsContextProvider = ({const extractedTags: string[] = extractTags(path,tagDelimiter,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);// TODO: Handle adding already added tagsif (extractedTags.includes(tag.title)) {// tag.type === 'plain') {- const fileName = extractFileName(path, PlatformIO.getDirSeparator());+ const fileName = extractFileName(+ path,+ currentLocation?.getDirSeparator(),+ );const containingDirectoryPath = extractContainingDirectoryPath(path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);let tagFoundPosition = -1;@@ -669,17 +680,24 @@ export const TaggingActionsContextProvider = ({fileName,extractedTags,tagDelimiter,+ currentLocation?.getDirSeparator(),prefixTagContainer,);if (newFileName !== fileName) {await renameFile(path,- containingDirectoryPath + PlatformIO.getDirSeparator() + newFileName,+ containingDirectoryPath ++ (currentLocation+ ? currentLocation.getDirSeparator()+ : AppConfig.dirSeparator) ++ newFileName,+ currentLocation.uuid,);}} else {//if (tag.type === 'sidecar') {- loadMetaDataPromise(path)+ currentLocation+ .loadMetaDataPromise(path).then((fsEntryMeta) => {let tagFoundPosition = -1;let newTagsArray = fsEntryMeta.tags.map((sidecarTag, index) => {@@ -707,16 +725,18 @@ export const TaggingActionsContextProvider = ({(item, pos, array) =>array.findIndex((el) => el.title === item.title) === pos,);- saveMetaDataPromise(path, {+ saveCurrentLocationMetaData(path, {...fsEntryMeta,tags: newTagsArray,}).then(() => {- reflectUpdateMeta(path);+ getAllPropertiesPromise(path).then((entry) =>+ reflectUpdateMeta(entry),+ );return true;}).catch((err) => {- console.warn('Error adding tags for ' + path + ' with ' + err);+ console.log('Error adding tags for ' + path + ' with ' + err);showNotification(t('core:addingTagsFailed' as any) as string,'error',@@ -727,20 +747,22 @@ export const TaggingActionsContextProvider = ({}).catch((error) => {// json metadata not exist -create the new one- console.warn(+ console.log('json metadata not exist create new ' + path + ' with ' + error,);// dispatch(AppActions.showNotification(t('core:addingTagsFailed'), 'error', true));// eslint-disable-next-line no-param-reassigntag.title = newTagTitle;const fsEntryMeta = { tags: [tag] };- saveMetaDataPromise(path, fsEntryMeta)+ saveCurrentLocationMetaData(path, fsEntryMeta).then(() => {- reflectUpdateMeta(path);+ getAllPropertiesPromise(path).then((entry) =>+ reflectUpdateMeta(entry),+ );return true;}).catch((err) => {- console.warn('Error adding tags for ' + path + ' with ' + err);+ console.log('Error adding tags for ' + path + ' with ' + err);showNotification(t('core:addingTagsFailed' as any) as string,'error',@@ -830,7 +852,8 @@ export const TaggingActionsContextProvider = ({const tagTitlesForRemoving = tags? tags.map((tag) => tag.title): undefined;- return loadMetaDataPromise(path)+ return currentLocation+ .loadMetaDataPromise(path).then((fsEntryMeta: TS.FileSystemEntryMeta) => {const newTags = tagTitlesForRemoving? fsEntryMeta.tags.filter(@@ -846,7 +869,9 @@ export const TaggingActionsContextProvider = ({newFilePath,).then(() => {if (reflect) {- reflectUpdateMeta(newFilePath);+ getAllPropertiesPromise(newFilePath).then((entry) =>+ reflectUpdateMeta(entry),+ );}return newFilePath;});@@ -854,7 +879,7 @@ export const TaggingActionsContextProvider = ({);}).catch((error) => {- console.warn('Error removing tags for ' + path + ' with ' + error);+ console.log('Error removing tags for ' + path + ' with ' + error);// dispatch(AppActions.showNotification(t('core:removingSidecarTagsFailed'), 'error', true));return removeTagsFromFilename(true, reflect);});@@ -870,13 +895,15 @@ export const TaggingActionsContextProvider = ({...fsEntryMeta,tags: newTags,};- return saveMetaDataPromise(path, updatedFsEntryMeta)+ return saveCurrentLocationMetaData(path, updatedFsEntryMeta).then(() => {- reflectUpdateMeta(newFilePath);+ getAllPropertiesPromise(newFilePath).then((entry) =>+ reflectUpdateMeta(entry),+ );return true;}).catch((err) => {- console.warn(+ console.log('Removing sidecar tags failed ' + path + ' with ' + err,);showNotification(@@ -905,13 +932,16 @@ export const TaggingActionsContextProvider = ({let extractedTags = extractTags(path,tagDelimiter,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);if (extractedTags.length > 0) {- const fileName = extractFileName(path, PlatformIO.getDirSeparator());+ const fileName = extractFileName(+ path,+ currentLocation?.getDirSeparator(),+ );const containingDirectoryPath = extractContainingDirectoryPath(path,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);if (tagTitlesForRemoving) {for (let i = 0; i < tagTitlesForRemoving.length; i += 1) {@@ -929,16 +959,22 @@ export const TaggingActionsContextProvider = ({}const newFilePath =(containingDirectoryPath- ? containingDirectoryPath + PlatformIO.getDirSeparator()+ ? containingDirectoryPath + currentLocation.getDirSeparator(): '') +generateFileName(fileName,extractedTags,tagDelimiter,+ currentLocation?.getDirSeparator(),prefixTagContainer,);if (path !== newFilePath) {- const success = await renameFile(path, newFilePath, reflect);+ const success = await renameFile(+ path,+ newFilePath,+ currentLocation.uuid,+ reflect,+ );if (!success) {reject(new Error('Error renaming file'));return;@@ -1035,11 +1071,9 @@ export const TaggingActionsContextProvider = ({};if (Pro && entry.locationId) {- const location: TS.Location = locations.find(- (l) => l.uuid === entry.locationId,- );+ const location: CommonLocation = findLocation(entry.locationId);if (location) {- editLocationTagGroup(location.path, modifiedEntry);+ editLocationTagGroup(location, modifiedEntry);}}@@ -1077,7 +1111,7 @@ export const TaggingActionsContextProvider = ({function createTagGroup(entry: TS.TagGroup,- location?: TS.Location,+ location?: CommonLocation,): Promise<boolean> {const newEntry = {...entry,@@ -1086,18 +1120,16 @@ export const TaggingActionsContextProvider = ({};saveTagLibrary([...tagGroups, newEntry]);if (Pro && location) {- return createLocationTagGroup(location.path, newEntry).then(() => true);+ return createLocationTagGroup(location, newEntry).then(() => true);}return Promise.resolve(true);}function mergeTagGroup(entry: TS.TagGroup) {- if (Pro && entry.locationId && locations) {- const location: TS.Location = locations.find(- (l) => l.uuid === entry.locationId,- );+ if (Pro && entry.locationId) {+ const location: CommonLocation = findLocation(entry.locationId);if (location) {- mergeLocationTagGroup(location.path, entry);+ mergeLocationTagGroup(location, entry);}}const indexForEditing = tagGroups.findIndex(@@ -1140,11 +1172,9 @@ export const TaggingActionsContextProvider = ({if (indexForRemoving >= 0) {const tagGroup: TS.TagGroup = tagGroups[indexForRemoving];if (Pro && tagGroup && tagGroup.locationId) {- const location: TS.Location = locations.find(- (l) => l.uuid === tagGroup.locationId,- );+ const location: CommonLocation = findLocation(tagGroup.locationId);if (location) {- removeLocationTagGroup(location.path, parentTagGroupUuid);+ removeLocationTagGroup(location, parentTagGroupUuid);}}@@ -1185,12 +1215,10 @@ export const TaggingActionsContextProvider = ({saveTags(newTags, tgIndex);if (Pro && tagGroup && tagGroup.locationId) {- const location: TS.Location = locations.find(- (l) => l.uuid === tagGroup.locationId,- );+ const location: CommonLocation = findLocation(tagGroup.locationId);if (location) {tagGroup.children = newTags;- editLocationTagGroup(location.path, tagGroup);+ editLocationTagGroup(location, tagGroup);}}}@@ -1219,11 +1247,9 @@ export const TaggingActionsContextProvider = ({};if (Pro && tagGroup && tagGroup.locationId) {- const location: TS.Location = locations.find(- (l) => l.uuid === tagGroup.locationId,- );+ const location: CommonLocation = findLocation(tagGroup.locationId);if (location) {- editLocationTagGroup(location.path, newTagGroup, true);+ editLocationTagGroup(location, newTagGroup, true);}}updateTagGroup(newTagGroup);@@ -1249,11 +1275,9 @@ export const TaggingActionsContextProvider = ({};if (Pro && tagGroup.locationId) {- const location: TS.Location = locations.find(- (l) => l.uuid === tagGroup.locationId,- );+ const location: CommonLocation = findLocation(tagGroup.locationId);if (location) {- editLocationTagGroup(location.path, editedTagGroup, true);+ editLocationTagGroup(location, editedTagGroup, true);}}updateTagGroup(editedTagGroup);@@ -1302,9 +1326,7 @@ export const TaggingActionsContextProvider = ({];return saveTagLibrary(newTagLibrary);}- console.warn(- 'Tag with this title already exists in the target tag group',- );+ console.log('Tag with this title already exists in the target tag group');}}diff --git a/src/renderer/hooks/ThumbGenerationContextProvider.tsx b/src/renderer/hooks/ThumbGenerationContextProvider.tsxindex 8185eb99b..bcc98ba33 100644--- a/src/renderer/hooks/ThumbGenerationContextProvider.tsx+++ b/src/renderer/hooks/ThumbGenerationContextProvider.tsx@@ -29,7 +29,6 @@ import {getShowUnixHiddenEntries,getUseGenerateThumbnails,} from '-/reducers/settings';-import PlatformIO from '-/services/platform-facade';import { TS } from '-/tagspaces.namespace';import AppConfig from '-/AppConfig';import {@@ -43,10 +42,15 @@ import {import { usePaginationContext } from '-/hooks/usePaginationContext';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useNotificationContext } from '-/hooks/useNotificationContext';-import { loadCurrentDirMeta } from '-/services/meta-loader';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { base64ToBlob } from '-/utils/dom';import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';+import {+ createThumbnailsInWorker,+ isWorkerAvailable,+} from '-/services/utils-io';+import { CommonLocation } from '-/utils/CommonLocation';+import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';type ThumbGenerationContextData = {generateThumbnails: (dirEntries: TS.FileSystemEntry[]) => Promise<boolean>;@@ -69,9 +73,12 @@ export const ThumbGenerationContextProvider = ({currentDirectoryPath,currentDirectoryEntries,updateCurrentDirEntries,+ loadCurrentDirMeta,} = useDirectoryContentContext();- const { currentLocation } = useCurrentLocationContext();- const { saveBinaryFilePromise } = usePlatformFacadeContext();+ const { findLocation } = useCurrentLocationContext();+ const { saveBinaryFilePromise, createDirectoryPromise } =+ usePlatformFacadeContext();+ const { metaActions } = useEditedEntryMetaContext();const { pageFiles, page } = usePaginationContext();const { setGeneratingThumbs } = useNotificationContext();const useGenerateThumbnails = useSelector(getUseGenerateThumbnails);@@ -126,19 +133,40 @@ export const ThumbGenerationContextProvider = ({}}, [currentDirectoryPath, page]); //, isMetaFolderExist]);- function genThumbnailsEnabled(): boolean {+ useEffect(() => {+ if (metaActions && metaActions.length > 0) {+ const entries = [];+ for (const action of metaActions) {+ if (action.action === 'thumbGenerate') {+ entries.push(action.entry);+ }+ }+ if (entries.length > 0) {+ generateThumbnails(entries).then(() => {+ return loadCurrentDirMeta(currentDirectoryPath, entries).then(+ (ent) => {+ updateCurrentDirEntries(ent);+ return true;+ },+ );+ });+ }+ }+ }, [metaActions]);++ function genThumbnailsEnabled(location: CommonLocation): boolean {if (currentDirectoryPath === undefined ||currentDirectoryPath.endsWith(AppConfig.dirSeparator + AppConfig.metaFolder,) ||- currentDirectoryPath.endsWith(+ currentDirectoryPath.indexOf(AppConfig.dirSeparator + AppConfig.metaFolder + AppConfig.dirSeparator,- )+ ) !== -1) {return false; // dont generate thumbnails in meta folder}- if (currentLocation?.disableThumbnailGeneration === true) {+ if (!location || location.disableThumbnailGeneration === true) {return false; // dont generate thumbnails if it's not enabled in location settings}if (AppConfig.useGenerateThumbnails !== undefined) {@@ -150,28 +178,30 @@ export const ThumbGenerationContextProvider = ({function generateThumbnails(dirEntries: TS.FileSystemEntry[],): Promise<boolean> {- if (- //AppConfig.isWeb || // not in web mode- //PlatformIO.haveObjectStoreSupport() || // not in object store mode- //PlatformIO.haveWebDavSupport() || // not in webdav mode- !genThumbnailsEnabled() // enabled in the settings- ) {+ if (dirEntries.length === 0) {+ return Promise.resolve(false);+ }+ const location: CommonLocation = findLocation(dirEntries[0].locationID);+ if (!location || location.disableThumbnailGeneration === true) {+ return Promise.resolve(false); // dont generate thumbnails if it's not enabled in location settings+ }+ if (!genThumbnailsEnabled(location)) {return Promise.resolve(false);}if (AppConfig.isElectron) {- return PlatformIO.isWorkerAvailable().then((isWorkerAvailable) =>- generateThumbnails2(dirEntries, isWorkerAvailable),+ return isWorkerAvailable().then((isWorkerAvailable) =>+ generateThumbnails2(dirEntries, isWorkerAvailable, location),);}- return generateThumbnails2(dirEntries, false);+ return generateThumbnails2(dirEntries, false, location);}function generateThumbnails2(dirEntries: TS.FileSystemEntry[],isWorkerAvailable,+ location: CommonLocation,): Promise<boolean> {- // const isWorkerAvailable = enableWS && PlatformIO.isWorkerAvailable();const workerEntries: string[] = [];const mainEntries: string[] = [];dirEntries.map((entry) => {@@ -184,7 +214,9 @@ export const ThumbGenerationContextProvider = ({if (isWorkerAvailable &&enableWS &&- supportedImgsWS.includes(entry.extension)+ supportedImgsWS.includes(entry.extension) &&+ !location.haveObjectStoreSupport() &&+ !location.haveWebDavSupport()) {workerEntries.push(entry.path);} else if (@@ -203,9 +235,9 @@ export const ThumbGenerationContextProvider = ({if (workerEntries.length > 0) {setGenThumbs(true);- return PlatformIO.createThumbnailsInWorker(workerEntries)+ return createThumbnailsInWorker(workerEntries).then(() =>- thumbnailMainGeneration(mainEntries).then(() => {+ thumbnailMainGeneration(mainEntries, location).then(() => {setGenThumbs(false);return true;}),@@ -213,17 +245,17 @@ export const ThumbGenerationContextProvider = ({.catch((e) => {// WS error handle let process thumbgeneration in Main process Generatorconsole.log('createThumbnailsInWorker', e);- return thumbnailMainGeneration([- ...workerEntries,- ...mainEntries,- ]).then(() => {+ return thumbnailMainGeneration(+ [...workerEntries, ...mainEntries],+ location,+ ).then(() => {setGenThumbs(false);return true;});});} else if (mainEntries.length > 0) {setGenThumbs(true);- return thumbnailMainGeneration(mainEntries).then(() => {+ return thumbnailMainGeneration(mainEntries, location).then(() => {setGenThumbs(false);return true;});@@ -233,10 +265,13 @@ export const ThumbGenerationContextProvider = ({return Promise.resolve(false);}- function thumbnailMainGeneration(mainEntries: string[]): Promise<boolean> {+ function thumbnailMainGeneration(+ mainEntries: string[],+ location: CommonLocation,+ ): Promise<boolean> {const maxExecutionTime = 9000;const promises = mainEntries.map((tmbPath) =>- getThumbnailURLPromise(tmbPath),+ getThumbnailURLPromise(tmbPath, location),);const promisesWithTimeout = promises.map((promise) => {const timeoutPromise = new Promise((resolve, reject) => {@@ -262,11 +297,14 @@ export const ThumbGenerationContextProvider = ({function getThumbnailURLPromise(filePath: string,+ location: CommonLocation,): Promise<{ filePath: string; tmbPath?: string }> {- return PlatformIO.getPropertiesPromise(filePath)+ return location+ .getPropertiesPromise(filePath).then((origStats) => {- const thumbFilePath = getThumbFileLocation(filePath);- return PlatformIO.getPropertiesPromise(thumbFilePath)+ const thumbFilePath = getThumbFileLocation(filePath, location);+ return location+ .getPropertiesPromise(thumbFilePath).then((stats) => {if (stats) {// Thumbnail exists@@ -277,10 +315,11 @@ export const ThumbGenerationContextProvider = ({origStats.size,thumbFilePath,origStats.isFile,+ location,).then((tmbPath) => ({ filePath, tmbPath })).catch((err) => {- console.warn('Thumb generation failed ' + err);+ console.log('Thumb generation failed ' + err);return Promise.resolve({filePath,tmbPath: thumbFilePath,@@ -297,6 +336,7 @@ export const ThumbGenerationContextProvider = ({origStats.size,thumbFilePath,origStats.isFile,+ location,).then((tmbPath) => {if (tmbPath !== undefined) {@@ -306,35 +346,35 @@ export const ThumbGenerationContextProvider = ({}}).catch((err) => {- console.warn('Thumb generation failed ' + err);+ console.log('Thumb generation failed ' + err);return Promise.resolve({ filePath });});}}).catch((err) => {- console.warn('Error getting tmb properties ' + err);+ console.log('Error getting tmb properties ' + err);return Promise.resolve({ filePath });});}).catch((err) => {- console.warn('Error getting file properties ' + err);+ console.log('Error getting file properties ' + err);return Promise.resolve({ filePath });});}- function getThumbFileLocation(filePath: string) {+ function getThumbFileLocation(filePath: string, location: CommonLocation) {const containingFolder = extractContainingDirectoryPath(filePath,- PlatformIO.getDirSeparator(),+ location.getDirSeparator(),);const metaFolder = getMetaDirectoryPath(containingFolder,- PlatformIO.getDirSeparator(),+ location.getDirSeparator(),);return (metaFolder +- PlatformIO.getDirSeparator() +- extractFileName(filePath, PlatformIO.getDirSeparator()) ++ location.getDirSeparator() ++ extractFileName(filePath, location.getDirSeparator()) +AppConfig.thumbFileExt);}@@ -344,25 +384,36 @@ export const ThumbGenerationContextProvider = ({fileSize: number,thumbFilePath: string,isFile: boolean,+ location: CommonLocation,): Promise<string | undefined> {const metaDirectory = extractContainingDirectoryPath(thumbFilePath,- PlatformIO.getDirSeparator(),+ location.getDirSeparator(),);const fileDirectory = isFile- ? extractContainingDirectoryPath(filePath, PlatformIO.getDirSeparator())+ ? extractContainingDirectoryPath(filePath, location.getDirSeparator()): filePath;const normalizedFileDirectory = normalizePath(fileDirectory);if (normalizedFileDirectory.endsWith(AppConfig.metaFolder)) {return Promise.resolve(undefined); // prevent creating thumbs in meta/.ts folder}- return PlatformIO.checkDirExist(metaDirectory).then((exist) => {+ return location.checkDirExist(metaDirectory).then((exist) => {if (!exist) {- return PlatformIO.createDirectoryPromise(metaDirectory).then(() => {- return createThumbnailSavePromise(filePath, fileSize, thumbFilePath);+ return createDirectoryPromise(metaDirectory, location.uuid).then(() => {+ return createThumbnailSavePromise(+ filePath,+ fileSize,+ thumbFilePath,+ location,+ );});} else {- return createThumbnailSavePromise(filePath, fileSize, thumbFilePath);+ return createThumbnailSavePromise(+ filePath,+ fileSize,+ thumbFilePath,+ location,+ );}});}@@ -371,26 +422,33 @@ export const ThumbGenerationContextProvider = ({filePath: string,fileSize: number,thumbFilePath: string,+ location: CommonLocation,): Promise<string | undefined> {- return generateThumbnailPromise(filePath, fileSize)+ return generateThumbnailPromise(+ filePath,+ fileSize,+ location.loadTextFilePromise,+ location.getFileContentPromise,+ location.getDirSeparator(),+ ).then((dataURL) => {if (dataURL && dataURL.length) {- return saveThumbnailPromise(thumbFilePath, dataURL)+ return saveThumbnailPromise(thumbFilePath, dataURL, location.uuid).then(() => thumbFilePath).catch((err) => {- console.warn('Thumb saving failed ' + err + ' for ' + filePath);+ console.log('Thumb saving failed ' + err + ' for ' + filePath);return Promise.resolve(undefined);});}return undefined; // thumbFilePath;}).catch((err) => {- console.warn('Thumb generation failed ' + err + ' for ' + filePath);+ console.log('Thumb generation failed ' + err + ' for ' + filePath);return Promise.resolve(undefined);});}- function saveThumbnailPromise(filePath, dataURL) {+ function saveThumbnailPromise(filePath, dataURL, locationID) {if (!dataURL || dataURL.length < 7) {// data:,return Promise.reject(new Error('Invalid dataURL'));@@ -398,13 +456,13 @@ export const ThumbGenerationContextProvider = ({const baseString = dataURL.split(',').pop();const content = base64ToBlob(baseString);return saveBinaryFilePromise(- { path: filePath },+ { path: filePath, locationID },content, //PlatformIO.isMinio() ? content : content.buffer,true,).then(() => filePath).catch((error) => {- console.warn(+ console.log('Saving thumbnail for ' +filePath +' failed with ' +@@ -418,7 +476,7 @@ export const ThumbGenerationContextProvider = ({return {generateThumbnails,};- }, [currentLocation]);+ }, []);return (<ThumbGenerationContext.Provider value={context}>diff --git a/src/renderer/perspectives/common/DirectoryMenuItems.tsx b/src/renderer/perspectives/common/DirectoryMenuItems.tsxindex b64eae877..45b997890 100644--- a/src/renderer/perspectives/common/DirectoryMenuItems.tsx+++ b/src/renderer/perspectives/common/DirectoryMenuItems.tsx@@ -6,7 +6,6 @@ import OpenFolderIcon from '@mui/icons-material/SubdirectoryArrowLeft';import MoveCopy from '@mui/icons-material/FileCopy';import ListItemText from '@mui/material/ListItemText';import RenameFolderIcon from '@mui/icons-material/FormatTextdirectionLToR';-import PlatformIO from '-/services/platform-facade';import AppConfig from '-/AppConfig';import OpenFolderNativelyIcon from '@mui/icons-material/Launch';import AddRemoveTags from '@mui/icons-material/Loyalty';@@ -29,10 +28,10 @@ import {} from '-/components/CommonIcons';import { getKeyBindingObject } from '-/reducers/settings';import MenuKeyBinding from '-/components/menus/MenuKeyBinding';-import { TS } from '-/tagspaces.namespace';+import { CommonLocation } from '-/utils/CommonLocation';export function getDirectoryMenuItems(- currentLocation: TS.Location,+ currentLocation: CommonLocation,selectedEntriesLength: number,perspectiveMode: boolean,isReadOnlyMode: boolean,@@ -178,10 +177,11 @@ export function getDirectoryMenuItems(}if (+ currentLocation &&selectedEntriesLength < 2 &&!(- PlatformIO.haveObjectStoreSupport() ||- PlatformIO.haveWebDavSupport() ||+ currentLocation.haveObjectStoreSupport() ||+ currentLocation.haveWebDavSupport() ||AppConfig.isWeb) &&showInFileManagerdiff --git a/src/renderer/perspectives/common/main-container.tsx b/src/renderer/perspectives/common/main-container.tsxindex fb2c04d2f..1bb530c48 100644--- a/src/renderer/perspectives/common/main-container.tsx+++ b/src/renderer/perspectives/common/main-container.tsx@@ -3,11 +3,8 @@ import FileSourceDnd from '-/components/FileSourceDnd';import TargetMoveFileBox from '-/components/TargetMoveFileBox';import DragItemTypes from '-/components/DragItemTypes';import React from 'react';-import { locationType } from '@tagspaces/tagspaces-common/misc';-import PlatformIO from '-/services/platform-facade';import AppConfig from '-/AppConfig';import TagDropContainer from '-/components/TagDropContainer';-import { getAllPropertiesPromise } from '-/services/utils-io';export const fileOperationsEnabled = (selectedEntries) => {let selectionContainsDirectories = false;@@ -59,13 +56,18 @@ export const renderCell = (openDirectory,setFileContextMenuAnchorEl,setDirContextMenuAnchorEl,- switchLocationTypeByID,showNotification: (text: string,notificationType: string,autohide: boolean,) => void,- moveFiles: (files: Array<string>, destination: string) => Promise<boolean>,+ moveFiles: (+ files: Array<string>,+ destination: string,+ locationID: string,+ onProgress?,+ reflect?: boolean,+ ) => Promise<boolean>,clearSelection: () => void,isLast?: boolean,) => {@@ -143,23 +145,7 @@ export const renderCell = (const handleGridCellDblClick = (event, fsEntry: TS.FileSystemEntry) => {setSelectedEntries([]);- if (currentLocation.type === locationType.TYPE_CLOUD) {- PlatformIO.enableObjectStoreSupport(currentLocation)- .then(() => {- openLocation(fsEntry);- return true;- })- .catch((error) => {- console.log('enableObjectStoreSupport', error);- });- } else if (currentLocation.type === locationType.TYPE_WEBDAV) {- PlatformIO.enableWebdavSupport(currentLocation);- openLocation(fsEntry);- } else if (currentLocation.type === locationType.TYPE_LOCAL) {- PlatformIO.disableObjectStoreSupport();- PlatformIO.disableWebdavSupport();- openLocation(fsEntry);- }+ openLocation(fsEntry);};const handleGridCellClick = (event, fsEntry: TS.FileSystemEntry) => {@@ -263,7 +249,7 @@ export const renderCell = (arrPath = [item.path];}console.log('Dropped files: ' + item.path);- moveFiles(arrPath, item.targetPath);+ moveFiles(arrPath, item.targetPath, currentLocation.uuid);//clearSelection();}};diff --git a/src/renderer/perspectives/grid/components/GridCell.tsx b/src/renderer/perspectives/grid/components/GridCell.tsxindex b54ac7663..9fc37df57 100644--- a/src/renderer/perspectives/grid/components/GridCell.tsx+++ b/src/renderer/perspectives/grid/components/GridCell.tsx@@ -48,15 +48,12 @@ import {findBackgroundColorForFolder,findColorForEntry,getDescriptionPreview,- getThumbPath,} from '-/services/utils-io';import TagContainerDnd from '-/components/TagContainerDnd';import TagContainer from '-/components/TagContainer';import TagsPreview from '-/components/TagsPreview';-import PlatformIO from '-/services/platform-facade';import EntryIcon from '-/components/EntryIcon';import { TS } from '-/tagspaces.namespace';-import { actions as AppActions, AppDispatch } from '-/reducers/app';import { dataTidFormat } from '-/services/test';import { getSupportedFileTypes, isReorderTags } from '-/reducers/settings';import { defaultSettings } from '../index';@@ -66,7 +63,6 @@ import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';import { usePerspectiveSettingsContext } from '-/hooks/usePerspectiveSettingsContext';import i18n from '-/services/i18n';import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';-import { getLocations } from '-/reducers/locations';export function urlGetDelim(url) {return url.indexOf('?') > 0 ? '&' : '?';@@ -135,18 +131,18 @@ function GridCell(props: Props) {const { metaActions } = useEditedEntryMetaContext();const { selectedEntries, selectEntry } = useSelectedEntriesContext();const { addTags, addTag, editTagForEntry } = useTaggingActionsContext();- const { readOnlyMode } = useCurrentLocationContext();+ const { findLocation, readOnlyMode } = useCurrentLocationContext();const supportedFileTypes = useSelector(getSupportedFileTypes);const reorderTags: boolean = useSelector(isReorderTags);- const locations: Array<TS.Location> = useSelector(getLocations);+ //const locations: Array<CommonLocation> = useSelector(getLocations);//const lastThumbnailImageChange = useSelector(getLastThumbnailImageChange);// const desktopMode = useSelector(isDesktopMode);const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);- /*const fileSystemEntryBgColor = useRef<string>(- findBackgroundColorForFolder(fsEntry),- );*/- //const thumbUrl = useRef<string>(undefined);+ const fileSystemEntryColor = findColorForEntry(fsEntry, supportedFileTypes);+ const maxHeight = calculateEntryHeight(entrySize);+ const entryPath = fsEntry.path;+ const isSmall = entrySize === 'tiny' || entrySize === 'small';useEffect(() => {if (metaActions && metaActions.length > 0) {@@ -187,6 +183,12 @@ function GridCell(props: Props) {}}, [metaActions]);+ const gridCellLocation = findLocation(fsEntry.locationID);+ if (!gridCellLocation && fsEntry.locationID) {+ // location not exist in locationManager (maybe removed)+ return null;+ }+const handleEditTag = (path: string, tag: TS.Tag, newTagTitle?: string) => {editTagForEntry(path, tag, newTagTitle);};@@ -206,7 +208,7 @@ function GridCell(props: Props) {const entryTitle = extractTitle(fsEntry.name,!fsEntry.isFile,- PlatformIO.getDirSeparator(),+ gridCellLocation?.getDirSeparator(),);let description;@@ -223,17 +225,35 @@ function GridCell(props: Props) {}}- const fileSystemEntryColor = findColorForEntry(fsEntry, supportedFileTypes);+ function generateCardHeader() {+ return (+ !isSmall &&+ fsEntry.isFile &&+ fsEntry.lmdt && (+ <>+ <Tooltip+ title={+ t('core:modifiedDate') + ': ' + formatDateTime(fsEntry.lmdt, true)+ }+ >+ {formatDateTime(fsEntry.lmdt, false)}+ </Tooltip>+ <Tooltip title={fsEntry.size + ' ' + t('core:sizeInBytes')}>+ <span>{' | ' + formatFileSize(fsEntry.size)}</span>+ </Tooltip>+ </>+ )+ );+ }let fileNameTags = [];if (fsEntry.isFile) {fileNameTags = extractTagsAsObjects(fsEntry.name,AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),+ gridCellLocation?.getDirSeparator(),);}-const fileSystemEntryTags =fsEntry.meta && fsEntry.meta.tags ? fsEntry.meta.tags : [];const sideCarTagsTitles = fileSystemEntryTags.map((tag) => tag.title);@@ -241,23 +261,7 @@ function GridCell(props: Props) {...fileSystemEntryTags,...fileNameTags.filter((tag) => !sideCarTagsTitles.includes(tag.title)),];-- const entryPath = fsEntry.path;- const isSmall = entrySize === 'tiny' || entrySize === 'small';-- function isLocalFile(locationID): boolean {- if (locationID) {- const loc = locations.find((l) => l.uuid === locationID);- if (loc) {- return loc.type === locationType.TYPE_LOCAL;- }- }- return false;- }-- const isLocal = fsEntry.locationID ? isLocalFile(fsEntry.locationID) : false;-- const renderTags = useMemo(() => {+ const renderTags = () => {let sideCarLength = 0;return entryTags.map((tag: TS.Tag, index) => {const tagContainer = readOnlyMode ? (@@ -288,30 +292,7 @@ function GridCell(props: Props) {}return tagContainer;});- }, [entryTags, readOnlyMode, reorderTags, entryPath]);-- const maxHeight = calculateEntryHeight(entrySize);-- function generateCardHeader() {- return (- !isSmall &&- fsEntry.isFile &&- fsEntry.lmdt && (- <>- <Tooltip- title={- t('core:modifiedDate') + ': ' + formatDateTime(fsEntry.lmdt, true)- }- >- {formatDateTime(fsEntry.lmdt, false)}- </Tooltip>- <Tooltip title={fsEntry.size + ' ' + t('core:sizeInBytes')}>- <span>{' | ' + formatFileSize(fsEntry.size)}</span>- </Tooltip>- </>- )- );- }+ }; //, [entryTags, readOnlyMode, reorderTags, entryPath]);function generateExtension() {return selectionMode ? (@@ -428,7 +409,7 @@ function GridCell(props: Props) {><Box style={{ position: 'absolute' }}>{showTags && entryTags ? (- renderTags+ renderTags()) : (<TagsPreview tags={entryTags} />)}@@ -441,10 +422,9 @@ function GridCell(props: Props) {onError={(i) => (i.target.style.display = 'none')}alt="thumbnail image"height="auto"- src={getThumbPath(+ src={gridCellLocation.getThumbPath(fsEntry.meta.thumbPath,fsEntry.meta?.lastUpdated,- isLocal,)}style={{height: maxHeight - 70,diff --git a/src/renderer/perspectives/grid/components/GridPagination.tsx b/src/renderer/perspectives/grid/components/GridPagination.tsxindex bbfbbad76..bb29d3e66 100644--- a/src/renderer/perspectives/grid/components/GridPagination.tsx+++ b/src/renderer/perspectives/grid/components/GridPagination.tsx@@ -30,12 +30,7 @@ import EntryIcon from '-/components/EntryIcon';import TagsPreview from '-/components/TagsPreview';import TagContainer from '-/components/TagContainer';import { TS } from '-/tagspaces.namespace';-import {- getDescriptionPreview,- getFolderThumbPath,- getFolderBgndPath,-} from '-/services/utils-io';-import PlatformIO from '-/services/platform-facade';+import { getDescriptionPreview } from '-/services/utils-io';import { MilkdownEditor } from '@tagspaces/tagspaces-md';import { renderCell } from '-/perspectives/common/main-container';import { useTranslation } from 'react-i18next';@@ -102,8 +97,7 @@ function GridPagination(props: Props) {const { openEntryInternal } = useOpenedEntryContext();const { moveFiles, openFileNatively } = useIOActionsContext();const { showNotification } = useNotificationContext();- const { readOnlyMode, currentLocation, switchLocationTypeByID } =- useCurrentLocationContext();+ const { readOnlyMode, currentLocation } = useCurrentLocationContext();const { openDirectory, directoryMeta } = useDirectoryContentContext();const { sortedDirContent } = useSortedDirContext();const { page, pageFiles, setCurrentPage } = usePaginationContext();@@ -128,7 +122,7 @@ function GridPagination(props: Props) {const folderName = extractDirectoryName(props.currentDirectoryPath,- PlatformIO.getDirSeparator(),+ currentLocation?.getDirSeparator(),);const dirColor =@@ -163,7 +157,7 @@ function GridPagination(props: Props) {overflowY: 'auto',backgroundImage:'url("' +- getFolderBgndPath(+ currentLocation?.getFolderBgndPath(currentDirectoryPath,directoryMeta?.lastUpdated,) +@@ -276,7 +270,7 @@ function GridPagination(props: Props) {width: 140,backgroundImage:'url("' +- getFolderThumbPath(+ currentLocation?.getFolderThumbPath(currentDirectoryPath,directoryMeta?.lastUpdated,) +@@ -336,7 +330,6 @@ function GridPagination(props: Props) {openDirectory,setFileContextMenuAnchorEl,setDirContextMenuAnchorEl,- switchLocationTypeByID,showNotification,moveFiles,clearSelection,@@ -361,7 +354,6 @@ function GridPagination(props: Props) {openDirectory,setFileContextMenuAnchorEl,setDirContextMenuAnchorEl,- switchLocationTypeByID,showNotification,moveFiles,clearSelection,diff --git a/src/renderer/perspectives/grid/components/MainContainer.tsx b/src/renderer/perspectives/grid/components/MainContainer.tsxindex 2249ca5ed..5c9822b4c 100644--- a/src/renderer/perspectives/grid/components/MainContainer.tsx+++ b/src/renderer/perspectives/grid/components/MainContainer.tsx@@ -31,7 +31,6 @@ import GridCell from './GridCell';import MainToolbar from '-/perspectives/grid/components/MainToolbar';import SortingMenu from '-/perspectives/grid/components/SortingMenu';import GridOptionsMenu from '-/perspectives/grid/components/GridOptionsMenu';-import PlatformIO from '-/services/platform-facade';import GridPagination from '-/perspectives/grid/components/GridPagination';import GridSettingsDialog from '-/perspectives/grid/components/GridSettingsDialog';import AddTagToTagGroupDialog from '-/components/dialogs/AddTagToTagGroupDialog';@@ -49,6 +48,7 @@ import { usePerspectiveSettingsContext } from '-/hooks/usePerspectiveSettingsConimport { GridCellsStyleContextProvider } from '-/perspectives/grid/hooks/GridCellsStyleProvider';import { useRendererListenerContext } from '-/hooks/useRendererListenerContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {openRenameEntryDialog: () => void;@@ -60,6 +60,7 @@ function GridPerspective(props: Props) {const { openEntry } = useOpenedEntryContext();const { openPrevFile, openNextFile } = useRendererListenerContext();const { showDirectories } = usePerspectiveSettingsContext();+ const { currentLocation } = useCurrentLocationContext();const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();const { openFileNatively, duplicateFile } = useIOActionsContext();const dispatch: AppDispatch = useDispatch();@@ -177,7 +178,9 @@ function GridPerspective(props: Props) {};const openShareFilesDialog = () => {- setIsShareFilesDialogOpened(true);+ if (currentLocation && currentLocation.haveObjectStoreSupport()) {+ setIsShareFilesDialogOpened(true);+ }};const openDeleteFileDialog = () => {@@ -346,9 +349,7 @@ function GridPerspective(props: Props) {handleSortingMenu={handleSortingMenu}handleExportCsvMenu={handleExportCsvMenu}openSettings={openSettings}- openShareFilesDialog={- PlatformIO.haveObjectStoreSupport() ? openShareFilesDialog : undefined- }+ openShareFilesDialog={openShareFilesDialog}/><GlobalHotKeyskeyMap={keyMap}@@ -418,11 +419,7 @@ function GridPerspective(props: Props) {openDeleteFileDialog={openDeleteFileDialog}openRenameFileDialog={openRenameEntryDialog}openMoveCopyFilesDialog={openMoveCopyFilesDialog}- openShareFilesDialog={- PlatformIO.haveObjectStoreSupport()- ? openShareFilesDialog- : undefined- }+ openShareFilesDialog={openShareFilesDialog}openAddRemoveTagsDialog={openAddRemoveTagsDialog}selectedFilePath={lastSelectedEntryPath ? lastSelectedEntryPath : currentDirectoryPathdiff --git a/src/renderer/perspectives/grid/components/MainToolbar.tsx b/src/renderer/perspectives/grid/components/MainToolbar.tsxindex 39f8d15a8..6eba8b06c 100644--- a/src/renderer/perspectives/grid/components/MainToolbar.tsx+++ b/src/renderer/perspectives/grid/components/MainToolbar.tsx@@ -51,7 +51,6 @@ import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';import { usePerspectiveSettingsContext } from '-/hooks/usePerspectiveSettingsContext';-import PlatformIO from '-/services/platform-facade';interface Props {prefixDataTID?: string;@@ -86,7 +85,7 @@ function MainToolbar(props: Props) {const { selectedEntries } = useSelectedEntriesContext();const keyBindings = useSelector(getKeyBindingObject);const dispatch: AppDispatch = useDispatch();- const { readOnlyMode } = useCurrentLocationContext();+ const { currentLocation, readOnlyMode } = useCurrentLocationContext();function showProperties() {return openEntry(currentDirectoryPath, true);@@ -98,7 +97,7 @@ function MainToolbar(props: Props) {const cleanedPath = entry.path.startsWith('/')? entry.path.substr(1): entry.path;- const url = PlatformIO.generateURLforPath(cleanedPath, 900);+ const url = currentLocation.generateURLforPath(cleanedPath, 900);fetch(url).then((res) => res.blob()) // Gets the response and returns it as a blob.then((blob) => {diff --git a/src/renderer/perspectives/list/components/MainContainer.tsx b/src/renderer/perspectives/list/components/MainContainer.tsxindex 7e484fb15..953293318 100644--- a/src/renderer/perspectives/list/components/MainContainer.tsx+++ b/src/renderer/perspectives/list/components/MainContainer.tsx@@ -31,7 +31,6 @@ import RowCell from '-/perspectives/list/components/RowCell';import MainToolbar from '-/perspectives/grid/components/MainToolbar';import SortingMenu from '-/perspectives/grid/components/SortingMenu';import GridOptionsMenu from '-/perspectives/grid/components/GridOptionsMenu';-import PlatformIO from '-/services/platform-facade';import GridPagination from '-/perspectives/grid/components/GridPagination';import GridSettingsDialog from '-/perspectives/grid/components/GridSettingsDialog';import AddTagToTagGroupDialog from '-/components/dialogs/AddTagToTagGroupDialog';@@ -49,6 +48,7 @@ import { usePerspectiveSettingsContext } from '-/hooks/usePerspectiveSettingsConimport { ListCellsStyleContextProvider } from '../hooks/ListCellsStyleProvider';import { useRendererListenerContext } from '-/hooks/useRendererListenerContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {openRenameEntryDialog: () => void;@@ -60,6 +60,7 @@ function ListPerspective(props: Props) {const { openEntry } = useOpenedEntryContext();const { openPrevFile, openNextFile } = useRendererListenerContext();const { showDirectories } = usePerspectiveSettingsContext();+ const { currentLocation } = useCurrentLocationContext();const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();const { openFileNatively, duplicateFile } = useIOActionsContext();const dispatch: AppDispatch = useDispatch();@@ -177,7 +178,9 @@ function ListPerspective(props: Props) {};const openShareFilesDialog = () => {- setIsShareFilesDialogOpened(true);+ if (currentLocation && currentLocation.haveObjectStoreSupport()) {+ setIsShareFilesDialogOpened(true);+ }};const openDeleteFileDialog = () => {@@ -346,9 +349,7 @@ function ListPerspective(props: Props) {handleSortingMenu={handleSortingMenu}handleExportCsvMenu={handleExportCsvMenu}openSettings={openSettings}- openShareFilesDialog={- PlatformIO.haveObjectStoreSupport() ? openShareFilesDialog : undefined- }+ openShareFilesDialog={openShareFilesDialog}/><GlobalHotKeyskeyMap={keyMap}@@ -418,11 +419,7 @@ function ListPerspective(props: Props) {openDeleteFileDialog={openDeleteFileDialog}openRenameFileDialog={openRenameEntryDialog}openMoveCopyFilesDialog={openMoveCopyFilesDialog}- openShareFilesDialog={- PlatformIO.haveObjectStoreSupport()- ? openShareFilesDialog- : undefined- }+ openShareFilesDialog={openShareFilesDialog}openAddRemoveTagsDialog={openAddRemoveTagsDialog}selectedFilePath={lastSelectedEntryPath ? lastSelectedEntryPath : currentDirectoryPathdiff --git a/src/renderer/perspectives/list/components/RowCell.tsx b/src/renderer/perspectives/list/components/RowCell.tsxindex a43d902ea..f328ebabd 100644--- a/src/renderer/perspectives/list/components/RowCell.tsx+++ b/src/renderer/perspectives/list/components/RowCell.tsx@@ -47,9 +47,7 @@ import {import TagContainerDnd from '-/components/TagContainerDnd';import TagContainer from '-/components/TagContainer';import TagsPreview from '-/components/TagsPreview';-import PlatformIO from '-/services/platform-facade';import { TS } from '-/tagspaces.namespace';-import { actions as AppActions, AppDispatch } from '-/reducers/app';import { getSupportedFileTypes, isReorderTags } from '-/reducers/settings';import { defaultSettings } from '../index';import { useTranslation } from 'react-i18next';@@ -135,9 +133,10 @@ function RowCell(props: Props) {const { entrySize, showTags, thumbnailMode } =usePerspectiveSettingsContext();const { addTags, addTag, editTagForEntry } = useTaggingActionsContext();- const { readOnlyMode } = useCurrentLocationContext();+ const { findLocation, readOnlyMode } = useCurrentLocationContext();const supportedFileTypes = useSelector(getSupportedFileTypes);const reorderTags: boolean = useSelector(isReorderTags);+ const rowCellLocation = findLocation(fsEntry.locationID);// You can use the dispatch function to dispatch actionsconst handleEditTag = (path: string, tag: TS.Tag, newTagTitle?: string) => {@@ -159,7 +158,7 @@ function RowCell(props: Props) {const entryTitle = extractTitle(fsEntry.name,!fsEntry.isFile,- PlatformIO.getDirSeparator(),+ rowCellLocation?.getDirSeparator(),);let description;@@ -188,7 +187,7 @@ function RowCell(props: Props) {fileNameTags = extractTagsAsObjects(fsEntry.name,AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),+ rowCellLocation?.getDirSeparator(),);}@@ -465,8 +464,8 @@ function RowCell(props: Props) {fsEntry.meta?.thumbPath +(fsEntry.meta &&fsEntry.meta.thumbPath &&- !PlatformIO.haveObjectStoreSupport() &&- !PlatformIO.haveWebDavSupport()+ !rowCellLocation.haveObjectStoreSupport() &&+ !rowCellLocation.haveWebDavSupport()? urlGetDelim(fsEntry.meta?.thumbPath) +fsEntry.meta.lastUpdated: '')diff --git a/src/renderer/reducers/app.ts b/src/renderer/reducers/app.tsindex f689daa3c..4781c3b43 100644--- a/src/renderer/reducers/app.ts+++ b/src/renderer/reducers/app.ts@@ -18,8 +18,13 @@import AppConfig from '-/AppConfig';import { getURLParameter } from '-/utils/dom';-import PlatformIO from '../services/platform-facade';-import { mergeByProp } from '-/services/utils-io';+import {+ isWorkerAvailable,+ loadExtensions,+ mergeByProp,+ setGlobalShortcuts,+ setLanguage,+} from '-/services/utils-io';import i18n from '../services/i18n';import {actions as SettingsActions,@@ -669,8 +674,8 @@ export const actions = {dispatch(actions.toggleLicenseDialog());}setTimeout(() => {- PlatformIO.setGlobalShortcuts(isGlobalKeyBindingEnabled(state));- PlatformIO.loadExtensions();+ setGlobalShortcuts(isGlobalKeyBindingEnabled(state));+ loadExtensions();}, 1000);const langURLParam = getURLParameter('locale');if (@@ -680,11 +685,11 @@ export const actions = {) {i18n.changeLanguage(langURLParam).then(() => {dispatch(SettingsActions.setLanguage(langURLParam));- PlatformIO.setLanguage(langURLParam);+ setLanguage(langURLParam);return true;});}- PlatformIO.isWorkerAvailable().then((workerAvailable) =>+ isWorkerAvailable().then((workerAvailable) =>workerAvailable? console.log('Worker is available in renderer thread'): console.log('Worker is not available in renderer thread'),diff --git a/src/renderer/reducers/locations.ts b/src/renderer/reducers/locations.tsindex 486984f3f..74cd1b206 100644--- a/src/renderer/reducers/locations.ts+++ b/src/renderer/reducers/locations.ts@@ -16,21 +16,10 @@**/-import {- immutablySwapItems,- locationType,-} from '@tagspaces/tagspaces-common/misc';-import { actions as AppActions } from '-/reducers/app';-import PlatformIO from '-/services/platform-facade';-import { TS } from '-/tagspaces.namespace';+import { immutablySwapItems } from '@tagspaces/tagspaces-common/misc';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';+import { CommonLocation } from '-/utils/CommonLocation';-/* import { ThunkDispatch } from 'redux-thunk';-import { AnyAction } from 'redux';--type State = Array<TS.Location>;-export type LocationsDispatch = ThunkDispatch<State, any, AnyAction>;- */export const types = {ADD_LOCATION: 'APP/ADD_LOCATION',MOVE_LOCATION: 'APP/MOVE_LOCATION',@@ -42,17 +31,18 @@ export const types = {export const initialState = [];-export default (state: Array<TS.Location> = initialState, action: any) => {+export default (state: Array<CommonLocation> = initialState, action: any) => {switch (action.type) {case types.ADD_LOCATION: {const locations = action.location.isDefault? state.map((location) => ({ ...location, isDefault: false })): [...state];- const newLocation = {+ const newLocation: CommonLocation = {...action.location,uuid: action.location.uuid || getUuid(),- creationDate: new Date().toJSON(),+ creationDate: new Date().getTime(),+ lastEditedDate: new Date().getTime(),};if (action.locationPosition) {locations.splice(action.locationPosition, 0, newLocation);@@ -84,6 +74,7 @@ export default (state: Array<TS.Location> = initialState, action: any) => {? action.location.newuuid: action.location.uuid,persistTagsInSidecarFile: action.location.persistTagsInSidecarFile,+ lastEditedDate: new Date().getTime(),},...state.slice(indexForEditing + 1),];@@ -143,7 +134,6 @@ export default (state: Array<TS.Location> = initialState, action: any) => {...state.slice(0, indexForRemoving),...state.slice(indexForRemoving + 1),];- // return state.filter( (item, index) => index !== indexForRemoving);}return state;}@@ -155,7 +145,7 @@ export default (state: Array<TS.Location> = initialState, action: any) => {export const actions = {createLocation: (- location: TS.Location,+ location: CommonLocation,locationPosition: number = undefined,) => ({type: types.ADD_LOCATION,@@ -172,89 +162,34 @@ export const actions = {type: types.MOVE_DOWN_LOCATION,uuid,}),- /*editLocation: (location: TS.Location, openAfterEdit = true) => (- dispatch: (actions: Object) => void- ) => {- dispatch(actions.changeLocation(location));- if (PlatformIO.haveObjectStoreSupport()) {- // disableObjectStoreSupport to revoke objectStoreAPI cached object- PlatformIO.disableObjectStoreSupport();- }- if (PlatformIO.haveWebDavSupport()) {- // disableWebdavSupport to revoke cached object- PlatformIO.disableWebdavSupport();- }- if (openAfterEdit) {- /!**- * check if location uuid is changed- *!/- if (- location.newuuid !== undefined &&- location.newuuid !== location.uuid- ) {- dispatch(- AppActions.openLocation({ ...location, uuid: location.newuuid })- );- } else {- dispatch(AppActions.openLocation(location));- }- dispatch(AppActions.setReadOnlyMode(location.isReadOnly || false));- }- },*/- /*switchLocationType: (locationId: string) => (- dispatch: (actions) => Promise<string | null>,- getState: () => any- ): Promise<string | null> => {- const { locations } = getState();- const location: TS.Location = locations.find(- location => location.uuid === locationId- );- if (location) {- return dispatch(AppActions.switchLocationType(location));- }- return Promise.resolve(null);- },*/- changeLocation: (location: TS.Location) => ({+ changeLocation: (location: CommonLocation) => ({type: types.EDIT_LOCATION,location,}),- /*removeLocation: (location: TS.Location) => (- dispatch: (actions: Object) => void- ) => {- //dispatch(AppActions.closeLocation(location.uuid));- dispatch(actions.deleteLocation(location));- },*/- deleteLocation: (location: TS.Location) => ({+ deleteLocation: (location: CommonLocation) => ({type: types.REMOVE_LOCATION,location,}),};// Selectors-export const getLocations = (state: any): Array<TS.Location> => state.locations;+export const getLocations = (state: any): Array<CommonLocation> =>+ state.locations.map((l) => new CommonLocation(l));export const getLocation = (state: any,locationId: string,-): TS.Location | null =>+): CommonLocation | null =>state.locations.find((location) => location.uuid === locationId);-/*export const getLocationPosition = (state: any, locationId: string): number =>- state.locations.findIndex(location => location.uuid === locationId);*/export const getLocationByPath = (state: any,path: string,-): TS.Location | null =>+): CommonLocation | null =>state.locations.find((location) => location.path === path);export const getDefaultLocationId = (state: any): string | undefined => {let foundLocation = state.locations.find((location) => location.isDefault);return foundLocation ? foundLocation.uuid : undefined;};-/*export const getCurrentLocation = (state: any): TS.Location | undefined => {- let foundLocation = state.locations.find(- location => location.uuid === state.app.currentLocationId- );- return foundLocation ? foundLocation : undefined;-};*/-export const getFirstRWLocation = (state: any): TS.Location | undefined => {+export const getFirstRWLocation = (state: any): CommonLocation | undefined => {let foundLocation = state.locations.find((location) => location.isDefault && !location.isReadOnly,);diff --git a/src/renderer/reducers/settings.ts b/src/renderer/reducers/settings.tsindex f2678ec7e..d8ccec6a0 100644--- a/src/renderer/reducers/settings.ts+++ b/src/renderer/reducers/settings.ts@@ -19,7 +19,6 @@import semver from 'semver';import AppConfig from '-/AppConfig';import defaultSettings from './settings-default';-import PlatformIO from '-/services/platform-facade';import Links from 'assets/links';import versionMeta from '-/version.json';import { actions as AppActions } from './app';@@ -30,6 +29,7 @@ import {getDefaultEditor,getDefaultViewer,mergeByProp,+ setZoomFactorElectron,updateByProp,} from '-/services/utils-io';@@ -315,11 +315,11 @@ export default (state: any = defaultSettings, action: any) => {};}case types.SET_ZOOM_RESET: {- PlatformIO.setZoomFactorElectron(1);+ setZoomFactorElectron(1);return { ...state, zoomFactor: 1 };}case types.SET_ZOOM_RESTORE: {- PlatformIO.setZoomFactorElectron(state.zoomFactor);+ setZoomFactorElectron(state.zoomFactor);return state;}case types.SET_ZOOM_IN: {@@ -329,7 +329,7 @@ export default (state: any = defaultSettings, action: any) => {const threshold = zoomLevel + correctedOffset;if (zoomLevel.toPrecision(2) <= threshold) {zoomLevel += offSet;- PlatformIO.setZoomFactorElectron(zoomLevel);+ setZoomFactorElectron(zoomLevel);}return { ...state, zoomFactor: zoomLevel };}@@ -338,7 +338,7 @@ export default (state: any = defaultSettings, action: any) => {const offSet = 0.1;if (zoomLevel.toPrecision(2) > offSet * 4) {zoomLevel -= offSet;- PlatformIO.setZoomFactorElectron(zoomLevel);+ setZoomFactorElectron(zoomLevel);}return { ...state, zoomFactor: zoomLevel };}@@ -804,7 +804,7 @@ export const actions = {return true;}).catch((error) => {- console.warn('Error while checking for update: ' + error);+ console.log('Error while checking for update: ' + error);});},};diff --git a/src/renderer/reducers/taglibrary.ts b/src/renderer/reducers/taglibrary.tsdeleted file mode 100644index 0464b389b..000000000--- a/src/renderer/reducers/taglibrary.ts+++ /dev/null@@ -1,653 +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 {- immutablySwapItems,- formatDateTime4Tag,- extend,- prepareTagGroupForExport,-} from '@tagspaces/tagspaces-common/misc';-import AppConfig from '-/AppConfig';-import { getUuid } from '@tagspaces/tagspaces-common/utils-io';-import { parseNewTags, saveAsTextFile } from '-/services/utils-io';-import versionMeta from '../version.json';-import defaultTagLibrary from './taglibrary-default';-import { TS } from '-/tagspaces.namespace';-import { Pro } from '-/pro';--export const types = {- DELETE_ALL: 'DELETE_ALL',- CREATE_TAGGROUP: 'CREATE_TAGGROUP',- IMPORT_TAGGROUP: 'IMPORT_TAGGROUP',- IMPORT_OLD_TAGGROUP: 'IMPORT_OLD_TAGGROUP',- ADD_TAGGROUP: 'ADD_TAGGROUP',- MERGE_TAGGROUP: 'MERGE_TAGGROUP',- REMOVE_TAGGROUP: 'REMOVE_TAGGROUP',- UPDATE_TAGGROUP: 'UPDATE_TAGGROUP',- // TOGGLE_TAGGROUP: 'TOGGLE_TAGGROUP',- ADD_TAGS: 'ADD_TAGS',- ADD_TAG: 'ADD_TAG',- // REMOVE_TAG: 'REMOVE_TAG',- // UPDATE_TAG: 'UPDATE_TAG',- SORT_TAG_GROUP_UP: 'SORT_TAG_GROUP_UP',- MOVE_TAG_GROUP: 'MOVE_TAG_GROUP',- MOVE_TAG_GROUP_UP: 'MOVE_TAG_GROUP_UP',- MOVE_TAG_GROUP_DOWN: 'MOVE_TAG_GROUP_DOWN',- EDIT_TAG_COLOR: 'EDIT_TAG_COLOR',- MOVE_TAG: 'MOVE_TAG',- CHANGE_TAG_ORDER: 'CHANGE_TAG_ORDER',-};--export default (state: Array<TS.TagGroup> = defaultTagLibrary, action: any) => {- switch (action.type) {- case types.DELETE_ALL: {- return [];- }- case types.CREATE_TAGGROUP: {- return [- ...state,- {- ...action.entry,- created_date: new Date(),- modified_date: new Date(),- },- ];- }- case types.ADD_TAGGROUP: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.entry.uuid) {- indexForEditing = index;- }- });- if (indexForEditing >= 0) {- return [- ...state.slice(0, indexForEditing),- {- uuid: action.entry.uuid,- title: action.entry.title,- children: [- ...state[indexForEditing].children,- action.entry.children[0],- ],- created_date: new Date(),- modified_date: new Date(),- },- ...state.slice(indexForEditing + 1),- ];- }- return state;- }- case types.MERGE_TAGGROUP: {- const indexForEditing = state.findIndex(- (obj) => obj.uuid === action.entry.uuid,- );- if (indexForEditing >= 0) {- const tags = [- ...state[indexForEditing].children,- ...action.entry.children,- ];- tags.splice(0, tags.length - AppConfig.maxCollectedTag);- return [- ...state.slice(0, indexForEditing),- {- uuid: action.entry.uuid,- title: action.entry.title,- children: tags,- created_date: action.entry.created_date,- modified_date: new Date(),- },- ...state.slice(indexForEditing + 1),- ];- }- return [- ...state,- {- uuid: action.entry.uuid || getUuid(),- title: action.entry.title,- color: action.entry.color,- textcolor: action.entry.textcolor,- children: action.entry.children,- created_date: new Date(),- modified_date: new Date(),- },- ];- }- case types.UPDATE_TAGGROUP: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.entry.uuid) {- indexForEditing = index;- }- });-- if (indexForEditing >= 0) {- const modifiedEntry = extend(- { created_date: new Date() },- action.entry,- { modified_date: new Date() },- );- return [- ...state.slice(0, indexForEditing),- modifiedEntry,- ...state.slice(indexForEditing + 1),- ];- }- return state;- }- case types.REMOVE_TAGGROUP: {- let indexForRemoving = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForRemoving = index;- }- });- if (indexForRemoving >= 0) {- return [- ...state.slice(0, indexForRemoving),- ...state.slice(indexForRemoving + 1),- ];- }- return state;- }- case types.ADD_TAGS: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.tagGroup.uuid) {- indexForEditing = index;- }- });- if (indexForEditing >= 0) {- return [- ...state.slice(0, indexForEditing),- {- ...state[indexForEditing],- children: action.tags,- },- ...state.slice(indexForEditing + 1),- ];- }- return state;- }- case types.ADD_TAG: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForEditing = index;- }- });-- if (indexForEditing >= 0) {- const taggroupTags = state[indexForEditing].children;- const newTag = action.tag;- if (!taggroupTags.some((tag) => tag.title === newTag.title)) {- return [- ...state.slice(0, indexForEditing),- {- ...state[indexForEditing],- children: [...taggroupTags, newTag],- },- ...state.slice(indexForEditing + 1),- ];- }- }- return state;- }- case types.MOVE_TAG_GROUP_DOWN: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating >= 0 && indexForUpdating < state.length - 1) {- const secondIndex = indexForUpdating + 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);- }- return state;- }- case types.MOVE_TAG_GROUP: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating > -1 && indexForUpdating !== action.position) {- const tagGroups = Array.from(state);- const [removed] = tagGroups.splice(indexForUpdating, 1);- tagGroups.splice(action.position, 0, removed);- return tagGroups;- }- return state;- }- case types.MOVE_TAG_GROUP_UP: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating > 0) {- const secondIndex = indexForUpdating - 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);- }- return state;- }- case types.SORT_TAG_GROUP_UP: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating >= 0) {- return [- ...state.slice(0, indexForUpdating),- {- ...state[indexForUpdating],- children: state[indexForUpdating].children.sort((a, b) =>- a.title > b.title ? 1 : a.title < b.title ? -1 : 0,- ),- },- ...state.slice(indexForUpdating + 1),- ];- }- return state;- }- case types.MOVE_TAG: {- let tagIndexForRemoving = -1;- let indexFromGroup = -1;- let indexToGroup = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.fromTagGroupId) {- indexFromGroup = index;- }- if (tagGroup.uuid === action.toTagGroupId) {- indexToGroup = index;- }- });- if (indexFromGroup >= 0 && state[indexFromGroup].children) {- state[indexFromGroup].children.forEach((tag, tagIndex) => {- if (tag.title === action.tagTitle) {- tagIndexForRemoving = tagIndex;- }- return true;- });- }- if (indexToGroup >= 0 && indexToGroup >= 0 && tagIndexForRemoving >= 0) {- const newTagLibrary = [...state];- const tag = { ...state[indexFromGroup].children[tagIndexForRemoving] };- const found = newTagLibrary[indexToGroup].children.find(- (t) => t.title === tag.title,- );- if (!found) {- newTagLibrary[indexToGroup].children.push(tag);- newTagLibrary[indexFromGroup].children = [- ...newTagLibrary[indexFromGroup].children.slice(- 0,- tagIndexForRemoving,- ),- ...newTagLibrary[indexFromGroup].children.slice(- tagIndexForRemoving + 1,- ),- ];- return newTagLibrary;- }- console.warn(- 'Tag with this title already exists in the target tag group',- );- }- return state;- }- case types.CHANGE_TAG_ORDER: {- let indexFromGroup = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.tagGroupUuid) {- indexFromGroup = index;- }- });-- if (indexFromGroup >= 0) {- const newTagLibrary = [...state];- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#swapping_variables- [- newTagLibrary[indexFromGroup].children[action.fromIndex],- newTagLibrary[indexFromGroup].children[action.toIndex],- ] = [- newTagLibrary[indexFromGroup].children[action.toIndex],- newTagLibrary[indexFromGroup].children[action.fromIndex],- ];-- return newTagLibrary;- }- return state;- }- case types.IMPORT_TAGGROUP: {- const arr = action.replace ? [] : [...state];- console.log(arr);- if (action.entries[0] && action.entries[0].key) {- action.entries.forEach((tagGroup, index) => {- // migration of old tag groups 2.9 or less in the new version 3.0-present- // @ts-ignore- if (tagGroup.key === state.uuid || tagGroup.key !== state.uuid) {- tagGroup = {- title: tagGroup.title,- uuid: tagGroup.key,- children: tagGroup.children,- };- const tagsArr = [];- tagGroup.children.forEach((tag) => {- tagsArr.push(tag);- tagGroup.children = tagsArr;- arr.push(tagGroup);- });- }- });- } else {- action.entries.forEach((tagGroup) => {- const index = arr.findIndex((obj) => obj.uuid === tagGroup.uuid);- if (index > -1) {- tagGroup.children.forEach((tag) => {- const stateTag = arr[index].children.find(- (obj) => obj.title === tag.title,- );- if (stateTag === undefined) {- arr[index].children.push(tag);- }- });- if (tagGroup.locationId) {- arr[index].locationId = tagGroup.locationId;- }- } else {- arr.push(tagGroup);- }- });- }-- return arr;- }- default: {- return state;- }- }-};--export const actions = {- deleteAll: () => ({- type: types.DELETE_ALL,- }),- createTagGroup:- (entry: TS.TagGroup) =>- (dispatch: (actions: Object) => void, getState: () => any) => {- if (Pro && entry.locationId) {- const { locations } = getState();- const location: TS.Location = locations.find(- (l) => l.uuid === entry.locationId,- );- if (location) {- Pro.MetaOperations.createTagGroup(location.path, entry);- }- }- dispatch(actions.createTagGroupInt(entry));- },- createTagGroupInt: (entry: TS.TagGroup) => ({- type: types.CREATE_TAGGROUP,- entry,- }),- editTagGroup:- (entry: TS.TagGroup) =>- (dispatch: (actions: Object) => void, getState: () => any) => {- if (Pro && entry.locationId) {- const { locations } = getState();- const location: TS.Location = locations.find(- (l) => l.uuid === entry.locationId,- );- if (location) {- Pro.MetaOperations.editTagGroup(location.path, entry);- }- }- dispatch(actions.editTagGroupInt(entry));- },- editTagGroupInt: (entry: TS.TagGroup) => ({- type: types.UPDATE_TAGGROUP,- entry,- }),- removeTagGroup:- (parentTagGroupUuid: TS.Uuid) =>- (dispatch: (actions: Object) => void, getState: () => any) => {- const { taglibrary } = getState();- const tagGroup: TS.TagGroup = taglibrary.find(- (t) => t.uuid === parentTagGroupUuid,- );- if (Pro && tagGroup && tagGroup.locationId) {- const { locations } = getState();- const location: TS.Location = locations.find(- (l) => l.uuid === tagGroup.locationId,- );- if (location) {- Pro.MetaOperations.removeTagGroup(location.path, parentTagGroupUuid);- }- }- dispatch(actions.removeTagGroupInt(parentTagGroupUuid));- },- removeTagGroupInt: (parentTagGroupUuid: TS.Uuid) => ({- type: types.REMOVE_TAGGROUP,- uuid: parentTagGroupUuid,- }),- /!**- * @deprecated use /services/taglibrary-utils/mergeTagGroup instead- *!/- mergeTagGroup:- (entry: TS.TagGroup) =>- (dispatch: (actions: Object) => void, getState: () => any) => {- if (Pro && entry.locationId) {- const { locations } = getState();- const location: TS.Location = locations.find(- (l) => l.uuid === entry.locationId,- );- if (location) {- Pro.MetaOperations.mergeTagGroup(location.path, entry);- }- }- dispatch(actions.mergeTagGroupInt(entry));- },- mergeTagGroupInt: (entry: TS.TagGroup) => ({- type: types.MERGE_TAGGROUP,- entry,- }),- addTag:- (tag: any, parentTagGroupUuid: TS.Uuid) =>- (dispatch: (actions: Object) => void, getState: () => any) => {- const { settings, taglibrary } = getState();- const { tagTextColor, tagBackgroundColor } = settings;-- const tagGroup: TS.TagGroup = taglibrary.find(- (t) => t.uuid === parentTagGroupUuid,- );-- let newTags: Array<TS.Tag>;- if (typeof tag === 'object' && tag !== null) {- if (tagGroup.children.some((t) => t.title === tag.title)) {- // tag exist- return;- }- const tagObject: TS.Tag = {- ...tag,- textcolor: tag.textcolor || tagTextColor,- color: tag.color || tagBackgroundColor,- };- newTags = [tagObject];- dispatch(actions.addTagInt(tagObject, parentTagGroupUuid));- } else {- const newTagGroup = {- ...tagGroup,- color: tagGroup.color ? tagGroup.color : tagBackgroundColor,- textcolor: tagGroup.textcolor ? tagGroup.textcolor : tagTextColor,- };- newTags = parseNewTags(tag, newTagGroup);- dispatch(actions.addTags(newTags, newTagGroup));- }-- if (Pro && tagGroup && tagGroup.locationId) {- const { locations } = getState();- const location: TS.Location = locations.find(- (l) => l.uuid === tagGroup.locationId,- );- if (location) {- tagGroup.children = newTags;- Pro.MetaOperations.editTagGroup(location.path, tagGroup);- }- }- },- addTags: (tags: Array<TS.Tag>, tagGroup: TS.TagGroup) => ({- type: types.ADD_TAGS,- tags,- tagGroup,- }),- addTagInt: (tag: TS.Tag, parentTagGroupUuid: TS.Uuid) => ({- type: types.ADD_TAG,- tag,- uuid: parentTagGroupUuid,- }),- editTag:- (tag: TS.Tag, parentTagGroupUuid: TS.Uuid, origTitle: string) =>- (dispatch: (actions: Object) => void, getState: () => any) => {- const { taglibrary } = getState();- const tagGroup: TS.TagGroup = taglibrary.find(- (t) => t.uuid === parentTagGroupUuid,- );- const newTagGroup = {- ...tagGroup,- children: tagGroup.children.map((t) => {- if (t.title === origTitle) {- return tag;- }- return t;- }),- };-- if (Pro && tagGroup && tagGroup.locationId) {- const { locations } = getState();- const location: TS.Location = locations.find(- (l) => l.uuid === tagGroup.locationId,- );- if (location) {- Pro.MetaOperations.editTagGroup(location.path, newTagGroup, true);- }- }- dispatch(actions.editTagGroupInt(newTagGroup));- },- deleteTag:- (tagTitle: string, parentTagGroupUuid: TS.Uuid) =>- (dispatch: (actions: Object) => void, getState: () => any) => {- const { taglibrary } = getState();-- const tagGroup: TS.TagGroup = taglibrary.find(- (t) => t.uuid === parentTagGroupUuid,- );-- const tagIndexForRemoving = tagGroup.children.findIndex(- (tag) => tag.title === tagTitle,- );- if (tagIndexForRemoving >= 0) {- const editedTagGroup = {- ...tagGroup,- children: [- ...tagGroup.children.slice(0, tagIndexForRemoving),- ...tagGroup.children.slice(tagIndexForRemoving + 1),- ],- };-- if (Pro && tagGroup.locationId) {- const { locations } = getState();- const location: TS.Location = locations.find(- (l) => l.uuid === tagGroup.locationId,- );- if (location) {- Pro.MetaOperations.editTagGroup(- location.path,- editedTagGroup,- true,- );- }- }- dispatch(actions.editTagGroupInt(editedTagGroup));- }- },- moveTagGroup: (tagGroupUuid: TS.Uuid, position: number) => ({- type: types.MOVE_TAG_GROUP,- uuid: tagGroupUuid,- position,- }),- moveTagGroupUp: (parentTagGroupUuid: TS.Uuid) => ({- type: types.MOVE_TAG_GROUP_UP,- uuid: parentTagGroupUuid,- }),- moveTagGroupDown: (parentTagGroupUuid: TS.Uuid) => ({- type: types.MOVE_TAG_GROUP_DOWN,- uuid: parentTagGroupUuid,- }),- sortTagGroup: (parentTagGroupUuid: TS.Uuid) => ({- type: types.SORT_TAG_GROUP_UP,- uuid: parentTagGroupUuid,- }),- moveTag: (- tagTitle: string,- fromTagGroupUuid: TS.Uuid,- toTagGroupUuid: TS.Uuid,- ) => ({- type: types.MOVE_TAG,- tagTitle,- fromTagGroupId: fromTagGroupUuid,- toTagGroupId: toTagGroupUuid,- }),- changeTagOrder: (- tagGroupUuid: TS.Uuid,- fromIndex: number,- toIndex: number,- ) => ({- type: types.CHANGE_TAG_ORDER,- tagGroupUuid,- fromIndex,- toIndex,- }),- importTagGroups: (entries: Array<TS.TagGroup>, replace = false) => ({- type: types.IMPORT_TAGGROUP,- entries,- replace,- }),-};--// Selectors-export const getTagGroups = (state: any) => state.taglibrary;-export const getAllTags = (state: any) => {- const uniqueTags: TS.Tag[] = [];- state.taglibrary.forEach((tagGroup) => {- tagGroup.children.forEach((tag) => {- const found = uniqueTags.find((uTag) => uTag.title === tag.title);- if (!found) {- uniqueTags.push(tag);- }- });- });- return uniqueTags.sort((a, b) =>- a.title > b.title ? 1 : a.title < b.title ? -1 : 0,- );-};-*/diff --git a/src/renderer/services/meta-loader.ts b/src/renderer/services/meta-loader.tsdeleted file mode 100644index 5402e26aa..000000000--- a/src/renderer/services/meta-loader.ts+++ /dev/null@@ -1,248 +0,0 @@-import { TS } from '-/tagspaces.namespace';-import PlatformIO from '-/services/platform-facade';-import {- executePromisesInBatches,- getMetaForEntry,- loadJSONFile,- loadMetaForDir,-} from '-/services/utils-io';-import {- getMetaFileLocationForDir,- getMetaFileLocationForFile,- getThumbFileLocationForDirectory,- getThumbFileLocationForFile,-} from '@tagspaces/tagspaces-common/paths';-import { getUuid } from '@tagspaces/tagspaces-common/utils-io';-import AppConfig from '-/AppConfig';-import { enhanceEntry } from '@tagspaces/tagspaces-common/utils-io';--export function loadCurrentDirMeta(- directoryPath: string,- dirEntries: TS.FileSystemEntry[],- pageFiles?: TS.FileSystemEntry[],-): Promise<TS.FileSystemEntry[]> {- return PlatformIO.listMetaDirectoryPromise(directoryPath)- .then((meta) => {- const dirEntriesPromises = dirEntries- .filter((entry) => !entry.isFile)- .map((entry) => getEnhancedDir(entry));- const files = pageFiles- ? pageFiles- : dirEntries.filter((entry) => entry.isFile);- const fileEntriesPromises = getFileEntriesPromises(files, meta);- const thumbs = getThumbs(files, meta);- return getEntries([- ...dirEntriesPromises,- ...fileEntriesPromises,- ...thumbs,- ]);- })- .catch((ex) => {- console.log(ex);- return undefined;- });-}--function getEntries(metaPromises): Promise<TS.FileSystemEntry[]> {- // const catchHandler = (error) => undefined;- //return Promise.all(metaPromises.map((promise) => promise.catch(catchHandler)))- return executePromisesInBatches(metaPromises, 100)- .then((entries: TS.FileSystemEntry[]) => {- return entries;- })- .catch((err) => {- console.log('err updateEntries:', err);- return undefined;- });-}--function getFileEntriesPromises(- pageFiles: TS.FileSystemEntry[],- meta: Array<any>,-): Promise<TS.FileSystemEntry>[] {- return pageFiles.map((entry) => {- const metaFilePath = getMetaFileLocationForFile(- entry.path,- PlatformIO.getDirSeparator(),- );- if (- // check if metaFilePath exist in listMetaDirectory content- meta.some((metaFile) => metaFilePath.endsWith(metaFile.path)) &&- // !checkEntryExist(entry.path) &&- entry.path.indexOf(- AppConfig.metaFolder + PlatformIO.getDirSeparator(),- ) === -1- ) {- return getMetaForEntry(entry, metaFilePath); /*Promise.resolve({- [entry.path]: getMetaForEntry(entry, metaFilePath)- });*/- }- return Promise.resolve(entry); //Promise.resolve({ [entry.path]: undefined });- });-}--function getThumbs(- pageFiles: TS.FileSystemEntry[],- meta: Array<any>,-): Promise<TS.FileSystemEntry>[] {- return pageFiles.map((entry) =>- Promise.resolve(setThumbForEntry(entry, meta)),- );-}--function setThumbForEntry(- entry: TS.FileSystemEntry,- meta: Array<any>, //TS.FileSystemEntryMeta[], -> todo extra path in meta-): TS.FileSystemEntry {- const thumbEntry = { ...entry, tags: [] };- let thumbPath = getThumbFileLocationForFile(- entry.path,- PlatformIO.getDirSeparator(),- false,- );- const metaFile = meta.find((m) => thumbPath && thumbPath.endsWith(m.path));- if (thumbPath && metaFile) {- thumbEntry.meta = { id: getUuid(), thumbPath }; //{ ...metaFile, thumbPath };- if (PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()) {- if (thumbPath && thumbPath.startsWith('/')) {- thumbPath = thumbPath.substring(1);- }-- thumbPath = PlatformIO.generateURLforPath(thumbPath, 604800);- if (thumbPath) {- thumbEntry.meta = { id: getUuid(), thumbPath };- }- }- }- return thumbEntry;-}--export function getEnhancedDir(- entry: TS.FileSystemEntry,-): Promise<TS.FileSystemEntry> {- if (!entry) {- return Promise.resolve(undefined);- }- if (entry.isFile) {- return Promise.reject(- new Error('getEnhancedDir accept dir only:' + entry.path),- );- }- if (entry.name === AppConfig.metaFolder) {- return Promise.resolve(undefined);- }- return getDirMeta(entry.path).then((meta) => ({- ...entry,- meta,- }));-- /*return PlatformIO.listMetaDirectoryPromise(entry.path).then((meta) => {- const metaFilePath = getMetaFileLocationForDir(- entry.path,- PlatformIO.getDirSeparator(),- );- const thumbDirPath = getThumbFileLocationForDirectory(- entry.path,- PlatformIO.getDirSeparator(),- );- let enhancedEntry;- if (meta.some((metaFile) => thumbDirPath.endsWith(metaFile.path))) {- const thumbPath =- PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()- ? PlatformIO.getURLforPath(thumbDirPath)- : thumbDirPath;- enhancedEntry = { ...entry, meta: { thumbPath } };- }- if (- meta.some((metaFile) => metaFilePath.endsWith(metaFile.path)) &&- entry.path.indexOf(- AppConfig.metaFolder + PlatformIO.getDirSeparator(),- ) === -1- ) {- return getMetaForEntry(enhancedEntry || entry, metaFilePath);- }- return enhancedEntry;- });*/-}--export function getEnhancedFile(- entry: TS.FileSystemEntry,-): Promise<TS.FileSystemEntry> {- if (!entry) {- return Promise.resolve(undefined);- }- if (!entry.isFile) {- return Promise.reject(- new Error('getEnhancedFile accept file only:' + entry.path),- );- }-- const thumbFilePath = getThumbFileLocationForFile(- entry.path,- PlatformIO.getDirSeparator(),- false,- );-- return PlatformIO.checkFileExist(thumbFilePath).then((exist) => {- const metaProps = exist ? { thumbPath: thumbFilePath } : {};-- const metaFilePath = getMetaFileLocationForFile(- entry.path,- PlatformIO.getDirSeparator(),- );-- try {- return loadJSONFile(metaFilePath).then((meta: TS.FileSystemEntryMeta) => {- if (meta) {- return enhanceEntry(- { ...entry, meta: { ...meta, ...metaProps } },- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),- );- }- return enhanceEntry(- { ...entry, meta: { ...metaProps } },- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),- );- });- } catch (e) {- return enhanceEntry(- { ...entry, meta: { ...metaProps } },- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),- );- }- });-}--export function getDirMeta(dirPath: string): Promise<TS.FileSystemEntryMeta> {- return PlatformIO.listMetaDirectoryPromise(dirPath).then((meta) => {- const metaFilePath = getMetaFileLocationForDir(- dirPath,- PlatformIO.getDirSeparator(),- );- const thumbDirPath = getThumbFileLocationForDirectory(- dirPath,- PlatformIO.getDirSeparator(),- );- let thumbPath;- if (meta.some((metaFile) => thumbDirPath.endsWith(metaFile.path))) {- thumbPath =- PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()- ? PlatformIO.getURLforPath(thumbDirPath)- : thumbDirPath;- }- if (- meta.some((metaFile) => metaFilePath.endsWith(metaFile.path)) &&- dirPath.indexOf(AppConfig.metaFolder + PlatformIO.getDirSeparator()) ===- -1- ) {- return loadMetaForDir(dirPath, { thumbPath });- }- if (thumbPath) {- return { id: '', thumbPath, lastUpdated: new Date().getTime() };- }- return undefined;- });-}diff --git a/src/renderer/services/platform-facade.ts b/src/renderer/services/platform-facade.tsindex 638143a90..a23d18aeb 100644--- a/src/renderer/services/platform-facade.ts+++ b/src/renderer/services/platform-facade.ts@@ -15,6 +15,7 @@* along with this program. If not, see <https://www.gnu.org/licenses/>.**/+/*import * as cordovaIO from '@tagspaces/tagspaces-common-cordova';import AppConfig from '-/AppConfig';@@ -130,13 +131,13 @@ export default class PlatformFacade {static quitApp = (): void => {if (AppConfig.isElectron) {window.electronIO.ipcRenderer.sendMessage('quitApp');- } /*else {+ } /!*else {platformQuitApp();- }*/+ }*!/};- /*static watchDirectory = (dirPath: string, listener): void =>- platformWatchDirectory(dirPath, listener);*/+ /!*static watchDirectory = (dirPath: string, listener): void =>+ platformWatchDirectory(dirPath, listener);*!/static focusWindow = (): void => {if (AppConfig.isElectron) {@@ -155,12 +156,12 @@ export default class PlatformFacade {}};- /**+ /!*** ObjectStore and webDav only* Function to generate or retrieve cached URL with expiration date* @param path* @param expirationInSeconds- */+ *!/static getURLforPath = (path: string,expirationInSeconds: number = 900,@@ -196,9 +197,9 @@ export default class PlatformFacade {return url;};- /**+ /!*** needs to run in init this function always return false first time- */+ *!/static isWorkerAvailable = (): Promise<boolean> => {if (AppConfig.isElectron &&@@ -236,9 +237,9 @@ export default class PlatformFacade {}};- /*static tiffJs = () => {+ /!*static tiffJs = () => {return platformTiffJs();- };*/+ };*!/static createDirectoryIndexInWorker = (directoryPath: string,@@ -284,13 +285,13 @@ export default class PlatformFacade {return Promise.reject(new Error('createThumbnailsInWorker not Electron!'));};- /**+ /!*** Promise === undefined on error* @param path* @param mode = ['extractTextContent', 'extractThumbPath']* @param ignorePatterns* @param resultsLimit- */+ *!/static listDirectoryPromise = (path: string,mode = ['extractThumbPath'],@@ -447,10 +448,10 @@ export default class PlatformFacade {return Promise.reject(new Error('createDirectoryPromise: not implemented'));};- /**+ /!*** @param sourceFilePath* @param targetFilePath - if exist overwrite it- */+ *!/static copyFilePromiseOverwrite = (sourceFilePath: string,targetFilePath: string,@@ -860,10 +861,10 @@ export default class PlatformFacade {return Promise.reject(new Error('selectDirectoryDialog: not implemented'));};- /**+ /!*** cordova only* @param files- */+ *!/static shareFiles = (files: Array<string>): void => {if (AppConfig.isCordova) {cordovaIO.shareFiles(files);@@ -872,9 +873,9 @@ export default class PlatformFacade {}};- /**+ /!*** Load extensions is supported only on Electron- */+ *!/static loadExtensions() {if (AppConfig.isElectron) {window.electronIO.ipcRenderer.sendMessage('load-extensions');@@ -921,3 +922,4 @@ export default class PlatformFacade {}}}+*/diff --git a/src/renderer/services/search.ts b/src/renderer/services/search.tsindex c70a3f48d..65eea9a5c 100644--- a/src/renderer/services/search.ts+++ b/src/renderer/services/search.ts@@ -305,7 +305,7 @@ function prepareIndex(enhancedTag.title = tag.title.toLowerCase();}} catch (e) {- console.warn(+ console.log('Error parsing tag ' + JSON.stringify(tag) + ' from ' + entry.path,);}diff --git a/src/renderer/services/thumbsgenerator.ts b/src/renderer/services/thumbsgenerator.tsindex e0d505f5a..e75320d09 100644--- a/src/renderer/services/thumbsgenerator.ts+++ b/src/renderer/services/thumbsgenerator.ts@@ -21,7 +21,6 @@ import {encodeFileName,} from '@tagspaces/tagspaces-common/paths';import AppConfig from '-/AppConfig';-import PlatformIO from '../services/platform-facade';import { Pro } from '../pro';import { FileTypeGroups } from '-/services/search';@@ -97,16 +96,19 @@ const maxFileSize = 30 * 1024 * 1024; // 30 MB/*** return thumbFilePath: Promise<string> or empty sting on error or not supported*/-export function generateThumbnailPromise(fileURL: string, fileSize: number) {- const ext = extractFileExtension(- fileURL,- PlatformIO.getDirSeparator(),- ).toLowerCase();+export function generateThumbnailPromise(+ fileURL: string,+ fileSize: number,+ loadTextFilePromise,+ getFileContentPromise,+ dirSeparator: string,+) {+ const ext = extractFileExtension(fileURL, dirSeparator).toLowerCase();const fileURLEscaped =/^https?:\/\//.test(fileURL) || AppConfig.isElectron? fileURL- : encodeFileName(fileURL, PlatformIO.getDirSeparator());+ : encodeFileName(fileURL, dirSeparator);if (supportedImgs.indexOf(ext) >= 0) {if (Pro && ext === 'tga') {@@ -122,26 +124,44 @@ export function generateThumbnailPromise(fileURL: string, fileSize: number) {} else if (Pro && ext === 'psd') {return Pro.ThumbsGenerator.generatePSDThumbnail(fileURLEscaped, maxSize);} else if (fileSize && fileSize < maxFileSize) {- return generateImageThumbnail(fileURL); //fileURLEscaped);+ return generateImageThumbnail(+ fileURL,+ getFileContentPromise,+ dirSeparator,+ ); //fileURLEscaped);}} else if (Pro && ext === 'pdf') {return Pro.ThumbsGenerator.generatePDFThumbnail(fileURLEscaped, maxSize);} else if (Pro && ext === 'html') {- return Pro.ThumbsGenerator.generateHtmlThumbnail(fileURLEscaped, maxSize);+ return Pro.ThumbsGenerator.generateHtmlThumbnail(+ fileURLEscaped,+ maxSize,+ loadTextFilePromise,+ );} else if (Pro && ext === 'url') {- return Pro.ThumbsGenerator.generateUrlThumbnail(fileURLEscaped, maxSize);+ return Pro.ThumbsGenerator.generateUrlThumbnail(+ fileURLEscaped,+ maxSize,+ loadTextFilePromise,+ );} else if (Pro && ext === 'mp3') {if (fileSize && fileSize < maxFileSize) {// return Pro.ThumbsGenerator.generateMp3Thumbnail(fileURL, maxSize);}} else if (Pro && supportedText.indexOf(ext) >= 0) {- return Pro.ThumbsGenerator.generateTextThumbnail(fileURLEscaped, maxSize);+ return Pro.ThumbsGenerator.generateTextThumbnail(+ fileURLEscaped,+ maxSize,+ loadTextFilePromise,+ );} else if (Pro && supportedContainers.indexOf(ext) >= 0) {if (fileSize && fileSize < maxFileSize) {return Pro.ThumbsGenerator.generateZipContainerImageThumbnail(fileURLEscaped,maxSize,supportedImgs,+ getFileContentPromise,+ dirSeparator,);}} else if (supportedVideos.indexOf(ext) >= 0) {@@ -156,6 +176,54 @@ export function generateThumbnailPromise(fileURL: string, fileSize: number) {return generateDefaultThumbnail();}+export function generateImageThumbnail(+ fileURL: string,+ getFileContentPromise,+ dirSeparator,+ maxTmbSize?: number,+): Promise<string> {+ try {+ if (fileURL.startsWith('http://') || fileURL.startsWith('https://')) {+ return getResizedImageThumbnail(fileURL, maxTmbSize);+ }+ return getFileContentPromise(fileURL, 'arraybuffer')+ .then((content) => {+ const ext = extractFileExtension(fileURL, dirSeparator).toLowerCase();+ const blob = new Blob([content], { type: getMimeType(ext) });+ if (AppConfig.isCordova) {+ return cordovaCreateObjectURL(blob).then((url) =>+ getResizedImageThumbnail(url, maxTmbSize),+ );+ } else {+ return getResizedImageThumbnail(+ URL.createObjectURL(blob),+ maxTmbSize,+ );+ }+ })+ .catch((e) => {+ console.log(`Error get: ${fileURL}`, e);+ return Promise.resolve('');+ });+ } catch (e) {+ console.log(`Error creating image thumb for : ${fileURL}`, e);+ return Promise.resolve('');+ }+}++function cordovaCreateObjectURL(blob): Promise<string> {+ return new Promise((resolve) => {+ const reader = new FileReader();++ reader.onload = function (event) {+ const dataUrl = event.target?.result as string;+ resolve(dataUrl);+ };++ reader.readAsDataURL(blob);+ });+}+function generateDefaultThumbnail() {return Promise.resolve('');}@@ -258,61 +326,12 @@ export function getResizedImageThumbnail(};img.src = src;img.onerror = (err) => {- console.warn(`Error getResizedImageThumbnail`, err);+ console.log(`Error getResizedImageThumbnail`, err);resolve('');};});}-export function generateImageThumbnail(- fileURL: string,- maxTmbSize?: number,-): Promise<string> {- try {- if (fileURL.startsWith('http://') || fileURL.startsWith('https://')) {- return getResizedImageThumbnail(fileURL, maxTmbSize);- }- return PlatformIO.getFileContentPromise(fileURL, 'arraybuffer')- .then((content) => {- const ext = extractFileExtension(- fileURL,- PlatformIO.getDirSeparator(),- ).toLowerCase();- const blob = new Blob([content], { type: getMimeType(ext) });- if (AppConfig.isCordova) {- return cordovaCreateObjectURL(blob).then((url) =>- getResizedImageThumbnail(url, maxTmbSize),- );- } else {- return getResizedImageThumbnail(- URL.createObjectURL(blob),- maxTmbSize,- );- }- })- .catch((e) => {- console.log(`Error get: ${fileURL}`, e);- return Promise.resolve('');- });- } catch (e) {- console.warn(`Error creating image thumb for : ${fileURL}`, e);- return Promise.resolve('');- }-}--function cordovaCreateObjectURL(blob): Promise<string> {- return new Promise((resolve) => {- const reader = new FileReader();-- reader.onload = function (event) {- const dataUrl = event.target?.result as string;- resolve(dataUrl);- };-- reader.readAsDataURL(blob);- });-}-function generateVideoThumbnail(fileURL): Promise<string> {return new Promise((resolve) => {try {@@ -337,7 +356,7 @@ function generateVideoThumbnail(fileURL): Promise<string> {ctx.drawImage(video, 0, 0, canvas.width, canvas.height);const dataurl = canvas.toDataURL(AppConfig.thumbType);img.onerror = (err) => {- console.warn(`Error loading: ${fileURL} for tmb gen with: ${err} `);+ console.log(`Error loading: ${fileURL} for tmb gen with: ${err} `);resolve('');};resolve(dataurl);@@ -346,12 +365,12 @@ function generateVideoThumbnail(fileURL): Promise<string> {video = null;};video.onerror = (err) => {- console.warn(`Error opening: ${fileURL} for tmb gen with: ${err} `);+ console.log(`Error opening: ${fileURL} for tmb gen with: ${err} `);resolve('');};video.src = fileURL;} catch (e) {- console.warn(`Error creating video thumb for : ${fileURL} with: ${e}`);+ console.log(`Error creating video thumb for : ${fileURL} with: ${e}`);resolve('');}});diff --git a/src/renderer/services/utils-io.ts b/src/renderer/services/utils-io.tsindex f28b79c56..05d3f102f 100644--- a/src/renderer/services/utils-io.ts+++ b/src/renderer/services/utils-io.ts@@ -16,39 +16,17 @@*/import { getUuid } from '@tagspaces/tagspaces-common/utils-io';-import { createIndex } from '@tagspaces/tagspaces-indexer';-import {- enhanceEntry,- loadJSONString,-} from '@tagspaces/tagspaces-common/utils-io';import { saveAs } from 'file-saver';+import { prepareTagForExport } from '@tagspaces/tagspaces-common/misc';import {- locationType,- prepareTagForExport,-} from '@tagspaces/tagspaces-common/misc';-import {- extractTagsAsObjects,extractFileExtension,cleanTrailingDirSeparator,- getMetaDirectoryPath,- getMetaFileLocationForFile,- getMetaFileLocationForDir,- extractDirectoryName,- extractFileName,- normalizePath,- getThumbFileLocationForDirectory,- getThumbFileLocationForFile,- getBgndFileLocationForDirectory,cleanFrontDirSeparator,- joinPaths,} from '@tagspaces/tagspaces-common/paths';import AppConfig from '-/AppConfig';-import PlatformIO from './platform-facade';import versionMeta from '../version.json';import { TS } from '-/tagspaces.namespace';-import { Pro } from '-/pro';import { supportedFileTypes } from '-/extension-config';-import { getEnhancedDir, getEnhancedFile } from '-/services/meta-loader';import removeMd from 'remove-markdown';export function getAllTags(entry: TS.FileSystemEntry): Array<TS.Tag> {@@ -69,71 +47,7 @@ export function getAllTags(entry: TS.FileSystemEntry): Array<TS.Tag> {return tags;}-/**- * @deprecated use loadMetaForDir- * @param entry- * @param metaFilePath- */-export function getMetaForEntry(- entry: TS.FileSystemEntry,- metaFilePath?: string,-): Promise<TS.FileSystemEntry> {- //if (entry.meta) {- // && Object.keys(entry.meta).length > 0) {- // entry is Enhanced- // return Promise.resolve(entry);- //}- if (!metaFilePath) {- if (entry.isFile) {- metaFilePath = getMetaFileLocationForFile(- entry.path,- PlatformIO.getDirSeparator(),- );- } else {- metaFilePath = getMetaFileLocationForDir(- entry.path,- PlatformIO.getDirSeparator(),- );- }- }- return loadJSONFile(metaFilePath).then((meta: TS.FileSystemEntryMeta) => {- if (meta) {- return enhanceEntry(- {- ...entry,- meta: {- ...(entry.meta && entry.meta),- ...meta,- // description: getDescriptionPreview(meta.description, 200),- },- },- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),- );- }- return entry;- });-}--export function loadMetaForDir(- dirPath: string,- metaAdd?,-): Promise<TS.FileSystemEntryMeta> {- return loadJSONFile(- getMetaFileLocationForDir(dirPath, PlatformIO.getDirSeparator()),- ).then((meta: TS.FileSystemEntryMeta) => {- if (meta) {- return {- ...(metaAdd && metaAdd),- ...meta,- // description: getDescriptionPreview(meta.description, 200),- };- }- return undefined;- });-}--export function enhanceOpenedEntry(+/*export function enhanceOpenedEntry(entry: TS.OpenedEntry,tagDelimiter,): TS.OpenedEntry {@@ -167,115 +81,6 @@ export function enhanceOpenedEntry(};}return entry;-}--/*export function prepareDirectoryContent(- dirEntries,- directoryPath,- settings,- dispatch,- getState,- dirEntryMeta,- generateThumbnails-) {- const currentLocation: TS.Location = getLocation(- getState(),- getState().app.currentLocationId- );- const isCloudLocation = currentLocation.type === locationType.TYPE_CLOUD;-- function genThumbnails() {- if (- !directoryPath ||- directoryPath.endsWith(AppConfig.dirSeparator + AppConfig.metaFolder) ||- directoryPath.endsWith(- AppConfig.dirSeparator + AppConfig.metaFolder + AppConfig.dirSeparator- )- ) {- return false; // dont generate thumbnails in meta folder- }- if (AppConfig.useGenerateThumbnails !== undefined) {- return AppConfig.useGenerateThumbnails;- }- return settings.useGenerateThumbnails;- }-- const {- directoryContent,- tmbGenerationPromises,- tmbGenerationList- } = enhanceDirectoryContent(- dirEntries,- isCloudLocation,- settings.showUnixHiddenEntries,- generateThumbnails && genThumbnails(),- true,- undefined,- settings.enableWS- );-- function handleTmbGenerationResults(results) {- // console.log('tmb results' + JSON.stringify(results));- const tmbURLs = [];- results.map(tmbResult => {- if (tmbResult.tmbPath && tmbResult.tmbPath.length > 0) {- // dispatch(actions.updateThumbnailUrl(tmbResult.filePath, tmbResult.tmbPath));- tmbURLs.push(tmbResult);- }- return true;- });- dispatch(AppActions.setGeneratingThumbnails(false));- // dispatch(actions.hideNotifications());- if (tmbURLs.length > 0) {- dispatch(AppActions.updateThumbnailUrls(tmbURLs));- }- return true;- }-- function handleTmbGenerationFailed(error) {- console.warn('Thumb generation failed: ' + error);- dispatch(AppActions.setGeneratingThumbnails(false));- dispatch(- AppActions.showNotification(- 'Generating thumbnails failed', //t('core:generatingThumbnailsFailed'),- 'warning',- true- )- );- }-- if (- generateThumbnails &&- (tmbGenerationList.length > 0 || tmbGenerationPromises.length > 0)- ) {- dispatch(AppActions.setGeneratingThumbnails(true));- if (tmbGenerationList.length > 0) {- PlatformIO.createThumbnailsInWorker(tmbGenerationList)- .then(handleTmbGenerationResults)- .catch(() => {- // WS error handle- Promise.all(- tmbGenerationList.map(tmbPath => getThumbnailURLPromise(tmbPath))- )- .then(handleTmbGenerationResults)- .catch(handleTmbGenerationFailed);- });- }- if (tmbGenerationPromises.length > 0) {- Promise.all(tmbGenerationPromises)- .then(handleTmbGenerationResults)- .catch(handleTmbGenerationFailed);- }- }-- console.log('Dir ' + directoryPath + ' contains ' + directoryContent.length);- dispatch(- AppActions.loadDirectorySuccess(- directoryPath,- directoryContent,- dirEntryMeta- )- );}*//**@@ -352,64 +157,6 @@ export function findExtensionPathForId(: '../../node_modules/' + extensionId;}-export function addExtensionsForEntry(- openedEntry: TS.OpenedEntry,- supportedFileTypes: Array<TS.FileTypes>,-): TS.OpenedEntry {- const fileExtension = extractFileExtension(- openedEntry.path,- PlatformIO.getDirSeparator(),- ).toLowerCase();-- const fileForOpening = { ...openedEntry };- const fileType: TS.FileTypes = supportedFileTypes.find(- (fileType) =>- fileType.viewer && fileType.type.toLowerCase() === fileExtension,- );- if (fileType) {- fileForOpening.viewingExtensionId = fileType.viewer;- if (fileType.color) {- fileForOpening.meta = fileForOpening.meta- ? { ...fileForOpening.meta, color: fileType.color }- : { id: openedEntry.uuid, color: fileType.color };- }- fileForOpening.viewingExtensionPath = findExtensionPathForId(- fileType.viewer,- //fileType.extensionExternalPath,- );- if (fileType.editor && fileType.editor.length > 0) {- fileForOpening.editingExtensionId = fileType.editor;- fileForOpening.editingExtensionPath = findExtensionPathForId(- fileType.editor,- //fileType.extensionExternalPath,- );- }- } else {- fileForOpening.viewingExtensionPath = openedEntry.isFile- ? findExtensionPathForId('@tagspaces/extensions/text-viewer')- : 'about:blank';- }- return fileForOpening;-}--export function findExtensionsForEntry(- entry: TS.FileSystemEntry,- supportedFileTypes: Array<any>,-): TS.OpenedEntry {- return addExtensionsForEntry(- {- ...entry,- viewingExtensionPath: 'about:blank',- viewingExtensionId: '',- /*lmdt: 0,- size: 0,- name: '',- tags: [],*/- },- supportedFileTypes,- );-}-export function getNextFile(pivotFilePath?: string,lastSelectedEntry?: string,@@ -483,215 +230,6 @@ export function getPrevFile(return prevFile;}-/**- * persistIndex based on location - used for S3 and cordova only- * for native used common-platform/indexer.js -> persistIndex instead- * @param param- * @param directoryIndex- */-async function persistIndex(param: string | any, directoryIndex: any) {- let directoryPath;- if (typeof param === 'object' && param !== null) {- directoryPath = param.path;- } else {- directoryPath = param;- }- const metaDirectory = getMetaDirectoryPath(directoryPath);- const exist = await PlatformIO.checkDirExist(metaDirectory);- if (!exist) {- await PlatformIO.createDirectoryPromise(metaDirectory);- }- const folderIndexPath =- metaDirectory + PlatformIO.getDirSeparator() + AppConfig.folderIndexFile; // getMetaIndexFilePath(directoryPath);- return PlatformIO.saveTextFilePromise(- { ...param, path: folderIndexPath },- JSON.stringify(directoryIndex), // relativeIndex),- true,- )- .then(() => {- console.log(- 'Index persisted for: ' + directoryPath + ' to ' + folderIndexPath,- );- return true;- })- .catch((err) => {- console.log('Error saving the index for ' + folderIndexPath, err);- });-}--export function enhanceDirectoryIndex(- directoryIndex: TS.FileSystemEntry[],- locationID,- folderPath,-): TS.FileSystemEntry[] {- return directoryIndex.map((i: TS.FileSystemEntry) => ({- ...i,- locationID,- path: joinPaths(- AppConfig.dirSeparator,- folderPath,- AppConfig.isWin ? i.path.replaceAll('/', AppConfig.dirSeparator) : i.path, //toPlatformPath()- ),- }));-}--export function loadIndexFromDisk(- folderPath: string,- locationID: string,-): Promise<TS.FileSystemEntry[]> {- const folderIndexPath =- getMetaDirectoryPath(folderPath) +- PlatformIO.getDirSeparator() +- AppConfig.folderIndexFile;- return PlatformIO.loadTextFilePromise(folderIndexPath)- .then((jsonContent) => {- const directoryIndex = loadJSONString(- jsonContent,- ) as TS.FileSystemEntry[];- return enhanceDirectoryIndex(directoryIndex, locationID, folderPath);- /*return enhanceDirectoryIndex(- {- path: folderPath,- locationID: location.uuid,- ...(location.type === locationType.TYPE_CLOUD && {- bucketName: location.bucketName,- }),- },- directoryIndex,- location.uuid,- ) as TS.FileSystemEntry[];*/- })- .catch((e) => {- console.log('cannot load json:' + folderPath, e);- return undefined;- });- // const indexExist = PlatformIO.checkFileExist(folderIndexPath);-}--export function createDirectoryIndex(- param: string | any,- extractText = false,- ignorePatterns: Array<string> = [],- enableWS = true,- isWalking = () => true,- // disableIndexing = true,-): Promise<TS.FileSystemEntry[]> {- if (isWalking()) {- if (Pro && Pro.Watcher) {- Pro.Watcher.stopWatching();- }- let directoryPath;- let locationID;- if (typeof param === 'object' && param !== null) {- directoryPath = param.path;- ({ locationID } = param);- } else {- directoryPath = param;- }- const dirPath = cleanTrailingDirSeparator(directoryPath);- if (- enableWS &&- !PlatformIO.haveObjectStoreSupport() &&- !PlatformIO.haveWebDavSupport() &&- !AppConfig.isCordova- // PlatformIO.isWorkerAvailable()- ) {- // Start indexing in worker if not in the object store mode- return PlatformIO.createDirectoryIndexInWorker(- dirPath,- extractText,- ignorePatterns,- ).then((result) => {- if (result && result.success) {- return loadIndexFromDisk(dirPath, locationID);- /*return loadIndex(- { path: dirPath, locationID },- PlatformIO.getDirSeparator(),- PlatformIO.loadTextFilePromise,- );*/- } else if (result && result.error) {- console.error('createDirectoryIndexInWorker failed:' + result.error);- } else {- console.error('createDirectoryIndexInWorker failed: unknown error');- }- return undefined; // todo create index not in worker- });- }-- let listDirectoryPromise;- //let loadTextFilePromise;- if (PlatformIO.haveObjectStoreSupport()) {- listDirectoryPromise = PlatformIO.listObjectStoreDir;- //loadTextFilePromise = PlatformIO.loadTextFilePromise;- } else {- listDirectoryPromise = PlatformIO.listDirectoryPromise;- }- const mode = ['extractThumbPath'];- if (extractText) {- mode.push('extractTextContent');- }- return createIndex(- param,- listDirectoryPromise,- PlatformIO.loadTextFilePromise,- mode,- ignorePatterns,- isWalking,- )- .then((directoryIndex) =>- persistIndex(param, directoryIndex).then((success) => {- if (success) {- console.log('Index generated in folder: ' + directoryPath);- return enhanceDirectoryIndex(- directoryIndex,- locationID,- directoryPath,- );- //return enhanceDirectoryIndex(param, directoryIndex, locationID);- }- return undefined;- }),- )- .catch((err) => {- console.log('Error creating index: ', err);- });- }-}--/**- * get full entry properties - with full description- */-export function getAllPropertiesPromise(- entryPath: string,-): Promise<TS.FileSystemEntry> {- return PlatformIO.getPropertiesPromise(entryPath).then(- (entryProps: TS.FileSystemEntry) => {- if (entryProps) {- if (!entryProps.isFile) {- return getEnhancedDir(entryProps);- }- return getEnhancedFile(entryProps);- }- console.log('Error getting props for ' + entryPath);- return entryProps;- },- );-}--export function loadJSONFile(- filePath: string,-): Promise<TS.FileSystemEntryMeta> {- // console.debug('loadJSONFile:' + filePath);- return PlatformIO.loadTextFilePromise(filePath)- .then(- (jsonContent) => loadJSONString(jsonContent) as TS.FileSystemEntryMeta,- )- .catch((e) => {- console.log('cannot load json:' + filePath, e);- return undefined;- });-}-export function saveAsTextFile(blob: any, filename: string) {saveAs(blob, filename);}@@ -725,64 +263,7 @@ export function getFulfilledResults<T>(return results.filter(isFulfilled).map((result) => result.value);}-interface FileExistenceCheck {- promise: Promise<boolean>;- path: string;-}--export function checkFilesExistPromise(- paths: string[],- targetPath: string,-): Promise<Array<string>> {- const promises: FileExistenceCheck[] = paths.map((path) => {- const targetFile =- normalizePath(targetPath) +- PlatformIO.getDirSeparator() +- extractFileName(path, PlatformIO.getDirSeparator());- return { promise: PlatformIO.checkFileExist(targetFile), path };- });- const progressPromises: Array<Promise<string>> = promises.map(- ({ promise, path }) =>- promise- .then((exists) => (exists ? path : ''))- .catch((err) => {- console.warn(`Promise ${path} error:`, err);- return '';- }),- );-- return Promise.allSettled(progressPromises).then((results) => {- return getFulfilledResults(results).filter((r) => r);- });-}--export function checkDirsExistPromise(- paths: string[],- targetPath: string,-): Promise<Array<string>> {- const promises: FileExistenceCheck[] = paths.map((path) => {- const targetDir =- normalizePath(targetPath) +- PlatformIO.getDirSeparator() +- extractDirectoryName(path, PlatformIO.getDirSeparator());- return { promise: PlatformIO.checkDirExist(targetDir), path };- });- const progressPromises: Array<Promise<string>> = promises.map(- ({ promise, path }) =>- promise- .then((exists) => (exists ? path : ''))- .catch((err) => {- console.warn(`Promise ${path} error:`, err);- return '';- }),- );-- return Promise.allSettled(progressPromises).then((results) => {- return getFulfilledResults(results).filter((r) => r);- });-}--export async function loadSubFolders(path: string, loadHidden = false) {+/*export async function loadSubFolders(path: string, loadHidden = false) {const folderContent = await PlatformIO.listDirectoryPromise(path, []); // 'extractThumbPath']);const subfolders = [];let i = 0;@@ -823,12 +304,13 @@ export async function loadSubFolders(path: string, loadHidden = false) {});}return subfolders;-}+}*/export function generateFileName(fileName: string,tags: string[],tagDelimiter: string,+ dirSeparator: string = AppConfig.dirSeparator,prefixTagContainer = AppConfig.prefixTagContainer,) {let tagsString = '';@@ -844,9 +326,8 @@ export function generateFileName(}tagsString = tagsString.trim() + AppConfig.endTagContainer;}- // console.log('The tags string: ' + tagsString);- const fileExt = extractFileExtension(fileName, PlatformIO.getDirSeparator());- // console.log('Filename: ' + fileName + ' file extension: ' + fileExt);++ const fileExt = extractFileExtension(fileName, dirSeparator);// Assembling the new filename with the tagslet newFileName = '';const beginTagContainer = fileName.indexOf(AppConfig.beginTagContainer);@@ -929,83 +410,6 @@ export function parseNewTags(tagsInput: string, tagGroup: TS.TagGroup) {}}-/**- * if you have entryProperties.isFile prefer to use loadFileMetaDataPromise/loadDirMetaDataPromise- * @param path- * @param fullDescription- */-export function loadMetaDataPromise(- path: string,- fullDescription = false,-): Promise<TS.FileSystemEntryMeta> {- return PlatformIO.getPropertiesPromise(path).then((entryProperties) => {- if (entryProperties) {- if (entryProperties.isFile) {- return loadFileMetaDataPromise(path, fullDescription);- }- return loadDirMetaDataPromise(path, fullDescription);- }- throw new Error('loadMetaDataPromise not exist' + path);- });-}--export function loadFileMetaDataPromise(- path: string,- fullDescription = false,-): Promise<TS.FileSystemEntryMeta> {- const metaFilePath = getMetaFileLocationForFile(- path,- PlatformIO.getDirSeparator(),- );- return loadJSONFile(metaFilePath).then((metaData) => {- if (!metaData) {- throw new Error('loadFileMetaDataPromise ' + metaFilePath + ' not exist');- }- return {- id: getUuid(),- isFile: true,- color: '',- tags: [],- appName: '',- appVersion: '',- // lastUpdated: 0,- ...metaData,- description: fullDescription- ? metaData.description- : getDescriptionPreview(metaData.description, 200),- };- });-}--export function loadDirMetaDataPromise(- path: string,- fullDescription = false,-): Promise<TS.FileSystemEntryMeta> {- const metaDirPath = getMetaFileLocationForDir(- path,- PlatformIO.getDirSeparator(),- );- return loadJSONFile(metaDirPath).then((metaData) => {- if (!metaData) {- throw new Error('loadDirMetaDataPromise ' + metaDirPath + ' not exist');- }- return {- id: getUuid(),- isFile: false,- color: '',- perspective: 'grid',- tags: [],- appName: '',- appVersion: '',- // lastUpdated: 0,- ...metaData,- description: fullDescription- ? metaData.description- : getDescriptionPreview(metaData.description, 200),- };- });-}-export function cleanMetaData(metaData: TS.FileSystemEntryMeta,): TS.FileSystemEntryMeta {@@ -1253,22 +657,6 @@ export function fileNameValidation(fileName): boolean {return true;}-/**- * normalize path for URL is always '/'- */-export function normalizeUrl(url: string) {- let normalizedUrl = url;- if (PlatformIO.getDirSeparator() !== '/') {- if (url) {- normalizedUrl = url.replaceAll(PlatformIO.getDirSeparator(), '/');- }- }- if (!normalizedUrl.startsWith('http') && !normalizedUrl.startsWith('/')) {- normalizedUrl = '/' + normalizedUrl;- }- return normalizedUrl;-}-/*** @param a - source array* @param b - updates array@@ -1333,97 +721,7 @@ function mergeTags(oldTagsArray: Array<TS.Tag>, newTagsArray: Array<TS.Tag>) {return [...oldTagsArray, ...uniqueTags];}-export function getThumbEntryPath(entry: TS.FileSystemEntry, encoded = false) {- if (!entry) {- return undefined;- }- return entry.isFile- ? getThumbFileLocationForFile(- entry.path,- PlatformIO.getDirSeparator(),- encoded,- )- : getThumbFileLocationForDirectory(- entry.path,- PlatformIO.getDirSeparator(),- );-}--export function getEntryThumbPath(entry: TS.FileSystemEntry, dt = undefined) {- if (entry) {- return getThumbPath(getThumbEntryPath(entry), dt);- }- return undefined;-}--/**- * @param path- * @param dt- */-export function getFolderThumbPath(path: string, dt = undefined) {- if (path) {- return getThumbPath(- getThumbFileLocationForDirectory(path, PlatformIO.getDirSeparator()),- dt,- );- }- return undefined;-}--/**- * @param thumbPath- * @param dt- * @param isLocalFile - force to generate local URL- */-export function getThumbPath(- thumbPath: string,- dt = undefined,- isLocalFile = false,-) {- if (!thumbPath) {- return undefined;- }- if (- !isLocalFile &&- (PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport())- ) {- if (isSignedURL(thumbPath)) {- return thumbPath;- }- return PlatformIO.getURLforPath(thumbPath);- }- return normalizeUrl(thumbPath) + (dt ? '?' + dt : '');-}--function isSignedURL(signedUrl) {- try {- // const query = url.parse(signedUrl, true).query;- return signedUrl.indexOf('Signature=') !== -1;- } catch (ex) {}- return false;-}--export function getFolderBgndPath(path: string, dt = undefined) {- if (path !== undefined) {- return getBgndPath(- getBgndFileLocationForDirectory(path, PlatformIO.getDirSeparator()),- dt,- );- }- return undefined;-}--export function getBgndPath(bgndPath: string, dt = undefined) {- if (!bgndPath) {- return undefined;- }- if (PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()) {- return PlatformIO.getURLforPath(bgndPath);- }- return normalizeUrl(bgndPath) + (dt ? '?' + dt : '');-}--export function setLocationType(location: TS.Location): Promise<boolean> {+/*export function setLocationType(location: CommonLocation): Promise<boolean> {if (location) {if (location.type === locationType.TYPE_CLOUD) {return PlatformIO.enableObjectStoreSupport(location);@@ -1436,12 +734,6 @@ export function setLocationType(location: TS.Location): Promise<boolean> {return Promise.resolve(true);}return Promise.resolve(false);-}--/*export function getCleanLocationPath(location: TS.Location): string {- let locationPath = PlatformIO.getLocationPath(location);- locationPath = cleanTrailingDirSeparator(locationPath);- return locationPath;}*/export function getRelativeEntryPath(@@ -1494,27 +786,6 @@ export function mergeFsEntryMeta(props: any = {}): TS.FileSystemEntryMeta {};}-export function toFsEntry(path: string, isFile: boolean): TS.FileSystemEntry {- const name = isFile- ? extractFileName(path, PlatformIO.getDirSeparator())- : extractDirectoryName(path, PlatformIO.getDirSeparator());- const tags = extractTagsAsObjects(- name,- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator(),- );- return {- uuid: getUuid(),- name,- isFile,- extension: extractFileExtension(path, PlatformIO.getDirSeparator()),- tags,- size: 0,- lmdt: new Date().getTime(),- path,- };-}-/*export function openedToFsEntry(openedEntry: TS.OpenedEntry): TS.FileSystemEntry {return {uuid: getUuid(),@@ -1548,13 +819,23 @@ export function getDefaultEditor(fileType) {}return undefined;}++export function openUrl(url: string): void {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('openUrl', url);+ } else {+ // web or cordova+ openUrlForWeb(url);+ }+}+export function openURLExternally(url: string, skipConfirmation = false) {if (skipConfirmation) {- PlatformIO.openUrl(url);+ openUrl(url);} else if (window.confirm('Do you really want to open this url: ' + url + ' ?')) {- PlatformIO.openUrl(url);+ openUrl(url);}}@@ -1597,3 +878,180 @@ export async function executePromisesInBatches<T>(return results;}++export function setZoomFactorElectron(zoomLevel) {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('setZoomFactor', zoomLevel);+ }+}++export function setGlobalShortcuts(globalShortcutsEnabled) {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage(+ 'global-shortcuts-enabled',+ globalShortcutsEnabled,+ );+ }+}++export function loadExtensions() {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('load-extensions');+ }+}+export function setLanguage(language: string) {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('set-language', language);+ }+}++/**+ * needs to run in init this function always return false first time+ */+export function isWorkerAvailable(): Promise<boolean> {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('isWorkerAvailable');+ }+ return Promise.resolve(false);+}++export function createThumbnailsInWorker(+ tmbGenerationList: Array<string>,+): Promise<any> {+ if (AppConfig.isElectron) {+ const payload = JSON.stringify(tmbGenerationList);+ return window.electronIO.ipcRenderer.invoke(+ 'postRequest',+ payload,+ '/thumb-gen',+ );+ }+ return Promise.reject(new Error('createThumbnailsInWorker not Electron!'));+}++export function 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.',+ ),+ );+ }+}++export function watchFolderMessage(locationPath, depth) {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage(+ 'watchFolder',+ locationPath,+ depth,+ );+ }+}++export function openDirectoryMessage(dirPath: string): void {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('openDirectory', dirPath);+ } else {+ console.error('Is supported only in Electron');+ }+}++export function openFileMessage(+ filePath: string,+ warningOpeningFilesExternally: boolean,+): void {+ if (+ !warningOpeningFilesExternally ||+ // eslint-disable-next-line no-restricted-globals+ confirm(+ 'Do you really want to open "' ++ filePath ++ '"? Execution of some files can be potentially dangerous!',+ )+ ) {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('openFile', filePath);+ } else {+ console.error('Is supported only in Electron');+ }+ }+}++export function createNewInstance(url?: string): void {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('create-new-window', url);+ } else {+ if (url) {+ window.open(url, '_blank');+ } else {+ window.open('index.html', '_blank');+ }+ }+}++export function readMacOSTags(filename: string): Promise<TS.Tag[]> {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('readMacOSTags', filename);+ }+ return Promise.resolve(undefined);+}++export function getUserDataDir(): Promise<string> {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('getUserDataDir');+ } else {+ return Promise.reject('getUserDataDir is supported only on Electron.');+ }+}++export function unZip(filePath, targetPath): Promise<string> {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('unZip', filePath, targetPath);+ } else {+ console.log('UnZip is supported only on Electron.');+ }+}++export function removeExtension(extensionId: string) {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('removeExtension', extensionId);+ } else {+ console.error('remove extensions is supported only on Electron.');+ }+}++export function quitApp(): void {+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage('quitApp');+ }+}+export function uploadAbort(path?: string): Promise<any> {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('uploadAbort', path);+ }+ return Promise.resolve(false);+}+export function getDevicePaths(): Promise<any> {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('getDevicePaths');+ } else if (AppConfig.isCordova) {+ const ioAPI = require('@tagspaces/tagspaces-common-cordova');+ return ioAPI.getDevicePaths();+ } else {+ console.log('getDevicePaths not supported');+ return Promise.resolve(undefined);+ }+}++export function selectDirectoryDialog(): Promise<any> {+ if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('selectDirectoryDialog');+ } else if (AppConfig.isCordova) {+ const ioAPI = require('@tagspaces/tagspaces-common-cordova');+ return ioAPI.selectDirectoryDialog();+ }+ return Promise.reject(new Error('selectDirectoryDialog: not implemented'));+}diff --git a/src/renderer/store/configureStore.dev.ts b/src/renderer/store/configureStore.dev.tsindex bf9c03ecf..5b134bc5a 100644--- a/src/renderer/store/configureStore.dev.ts+++ b/src/renderer/store/configureStore.dev.ts@@ -21,9 +21,9 @@ import { createStore, applyMiddleware, compose } from 'redux';import { persistStore } from 'redux-persist';import thunk from 'redux-thunk';import { createLogger } from 'redux-logger';+import AppConfig from '-/AppConfig';import rootReducer from '../reducers';import onlineListener from '../services/onlineListener';-import PlatformIO from '-/services/platform-facade';const configureStore = (initialState) => {// Redux Configuration@@ -67,8 +67,13 @@ const configureStore = (initialState) => {const persistor = persistStore(store, null, () => {// languageChanged event is not handled in main process on store loaded (App is not ready)setTimeout(() => {- // @ts-ignore- PlatformIO.setLanguage(store.getState().settings.interfaceLanguage);+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage(+ 'set-language',+ // @ts-ignore+ store.getState().settings.interfaceLanguage,+ );+ }}, 500);// document.dispatchEvent(new Event('storeLoaded'));// store.dispatch(push('/main'));diff --git a/src/renderer/store/configureStore.prod.ts b/src/renderer/store/configureStore.prod.tsindex 59802bad6..1274a7d58 100644--- a/src/renderer/store/configureStore.prod.ts+++ b/src/renderer/store/configureStore.prod.ts@@ -19,9 +19,9 @@import { compose, createStore, applyMiddleware } from 'redux';import { persistStore } from 'redux-persist';import thunk from 'redux-thunk';+import AppConfig from '-/AppConfig';import rootReducer from '../reducers';import onlineListener from '../services/onlineListener';-import PlatformIO from '-/services/platform-facade';const enhancer = compose(applyMiddleware(thunk), // , router)@@ -35,8 +35,13 @@ function configureStore(initialState) {// document.dispatchEvent(new Event('storeLoaded'));// console.log('Store rehydrated.');setTimeout(() => {- // @ts-ignore- PlatformIO.setLanguage(store.getState().settings.interfaceLanguage);+ if (AppConfig.isElectron) {+ window.electronIO.ipcRenderer.sendMessage(+ 'set-language',+ // @ts-ignore+ store.getState().settings.interfaceLanguage,+ );+ }}, 500);});return { store, persistor };diff --git a/src/renderer/tagspaces.namespace.d.ts b/src/renderer/tagspaces.namespace.d.tsindex 6944d3a4b..1675044a1 100644--- a/src/renderer/tagspaces.namespace.d.ts+++ b/src/renderer/tagspaces.namespace.d.ts@@ -1,5 +1,3 @@-import { ScopeType } from '-/components/SearchOptions';-/*** TagSpaces - universal file and folder organizer* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)@@ -18,6 +16,9 @@ import { ScopeType } from '-/components/SearchOptions';**/+import { ScopeType } from '-/components/SearchOptions';+import AWS from 'aws-sdk';+export namespace TS {interface Location {uuid: string;@@ -27,17 +28,12 @@ export namespace TS {authType?: string; // none,password,digest,tokenusername?: string;password?: string;- accessKeyId?: string;- secretAccessKey?: string;- sessionToken?: string;- bucketName?: string;- region?: string;paths?: Array<string>; // deprecatedpath?: string;- endpointURL?: string;- children?: Array<any>;+ //children?: Array<any>;perspective?: string; // id of the perspective- creationDate?: string;+ creationDate?: number;+ lastEditedDate?: number;isDefault: boolean;isReadOnly?: boolean;isNotEditable?: boolean;@@ -51,6 +47,21 @@ export namespace TS {ignorePatternPaths?: Array<string>;}+ interface S3Location extends Location {+ accessKeyId?: string;+ secretAccessKey?: string;+ sessionToken?: string;+ bucketName?: string;+ region?: string;+ endpointURL?: string;+ s3API?: AWS.S3;+ }++ interface FileExistenceCheck {+ promise: Promise<boolean>;+ path: string;+ }+interface Extension {extensionId: string;extensionName: string;@@ -115,6 +126,7 @@ export namespace TS {| 'autoSaveChange'| 'descriptionChange'| 'thumbChange'+ | 'thumbGenerate'| 'bgdImgChange'| 'bgdColorChange';entry: TS.FileSystemEntry;@@ -166,7 +178,7 @@ export namespace TS {name: string;isFile: boolean;isNewFile?: boolean;- locationID?: string;+ locationID: string;//isAutoSaveEnabled?: boolean; // common with OpenedEntryextension?: string;textContent?: string;@@ -197,7 +209,6 @@ export namespace TS {}interface OpenedEntry extends FileSystemEntry {- locationId?: string;viewingExtensionPath: string;viewingExtensionId: string;editingExtensionPath?: string;diff --git a/src/renderer/third-party.txt b/src/renderer/third-party.txtindex 614f82d25..4a50f375a 100644--- a/src/renderer/third-party.txt+++ b/src/renderer/third-party.txt@@ -3579,7 +3579,7 @@ MIT LicenseThe following npm package may be included in this product:- - @tagspacespro/[email protected]+ - @tagspacespro/[email protected]This package contains the following license and notice below:@@ -7361,12 +7361,11 @@ Creative Commons may be contacted at creativecommons.org.------------The following npm packages may be included in this product:+The following npm package may be included in this product:-These packages each contain the following license and notice below:+This package contains the following license and notice below:AWS SDK for JavaScriptCopyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.@@ -9152,12 +9151,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.------------The following npm packages may be included in this product:+The following npm package may be included in this product:-These packages each contain the following license and notice below:+This package contains the following license and notice below:Copyright 2010, 2011, 2012, 2013. All rights reserved.@@ -14532,36 +14530,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI------------The following npm package may be included in this product:---This package contains the following license and notice below:--The MIT License (MIT)--Copyright (c) 2013 Ozgur Ozcitak--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in-all copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN-THE SOFTWARE.--------------The following npm package may be included in this product:@@ -17036,10 +17004,10 @@ SOFTWARE.The following npm packages may be included in this product:- - @tagspaces/[email protected]- - @tagspaces/[email protected]- - @tagspaces/[email protected]- - @tagspaces/[email protected]+ - @tagspaces/[email protected]+ - @tagspaces/[email protected]+ - @tagspaces/[email protected]+ - @tagspaces/[email protected]- @tagspaces/[email protected]These packages each contain the following license and notice below:diff --git a/src/renderer/utils/CommonLocation.ts b/src/renderer/utils/CommonLocation.tsnew file mode 100644index 000000000..59685628f--- /dev/null+++ b/src/renderer/utils/CommonLocation.ts@@ -0,0 +1,933 @@+// import AWS from "aws-sdk";+import { locationType } from '@tagspaces/tagspaces-common/misc';+import {+ extractDirectoryName,+ extractFileExtension,+ extractFileName,+ extractTagsAsObjects,+ getBgndFileLocationForDirectory,+ getMetaFileLocationForDir,+ getMetaFileLocationForFile,+ getThumbFileLocationForDirectory,+ getThumbFileLocationForFile,+ normalizePath,+} from '@tagspaces/tagspaces-common/paths';+import { getUuid, loadJSONString } from '@tagspaces/tagspaces-common/utils-io';+import AppConfig from '-/AppConfig';+//import * as objectStoreAPI from '@tagspaces/tagspaces-common-aws';+import * as cordovaIO from '@tagspaces/tagspaces-common-cordova';+import { TS } from '-/tagspaces.namespace';+import {+ getDescriptionPreview,+ getFulfilledResults,+} from '-/services/utils-io';++export class CommonLocation implements TS.Location {+ uuid: string;+ newuuid?: string;+ name: string;+ type: string; // 0 - local; 1 - S3; 2 - amplify; 3 - webdav+ authType?: string; // none,password,digest,token+ username?: string;+ password?: string;+ paths?: Array<string>; // deprecated+ path?: string;+ children?: Array<any>; // this is for tree -> getDirectoriesTree+ perspective?: string; // id of the perspective+ creationDate?: number;+ lastEditedDate?: number;+ isDefault: boolean;+ isReadOnly?: boolean;+ isNotEditable?: boolean;+ watchForChanges?: boolean;+ disableIndexing?: boolean;+ disableThumbnailGeneration?: boolean;+ fullTextIndex?: boolean;+ maxIndexAge?: number;+ maxLoops?: number;+ persistTagsInSidecarFile?: boolean;+ ignorePatternPaths?: Array<string>;+ accessKeyId?: string;+ secretAccessKey?: string;+ sessionToken?: string;+ bucketName?: string;+ region?: string;+ endpointURL?: string;+ ioAPI?: any; //AWS.S3; //common API for IO operations interface+ urlCache = {};++ constructor(location: TS.Location) {+ this.uuid = location.uuid;+ this.newuuid = location.newuuid;+ this.name = location.name;+ this.type = location.type; // 0 - local; 1 - S3; 2 - amplify; 3 - webdav+ this.authType = location.authType; // none,password,digest,token+ this.username = location.username;+ this.password = location.password;+ //this.paths = location.paths; // deprecated+ this.path = location.path;+ //children?: Array<any>;+ this.perspective = location.perspective; // id of the perspective+ this.creationDate = location.creationDate+ ? location.creationDate+ : new Date().getTime();+ this.lastEditedDate = new Date().getTime();+ this.isDefault = location.isDefault;+ this.isReadOnly = location.isReadOnly;+ this.isNotEditable = location.isNotEditable;+ this.watchForChanges = location.watchForChanges;+ this.disableIndexing = location.disableIndexing;+ this.disableThumbnailGeneration = location.disableThumbnailGeneration;+ this.fullTextIndex = location.fullTextIndex;+ this.maxIndexAge = location.maxIndexAge;+ this.maxLoops = location.maxLoops;+ this.persistTagsInSidecarFile = location.persistTagsInSidecarFile;+ this.ignorePatternPaths = location.ignorePatternPaths;+ if (location.type === locationType.TYPE_CLOUD) {+ this.accessKeyId = (location as TS.S3Location).accessKeyId;+ this.secretAccessKey = (location as TS.S3Location).secretAccessKey;+ this.sessionToken = (location as TS.S3Location).sessionToken;+ this.bucketName = (location as TS.S3Location).bucketName;+ this.region = (location as TS.S3Location).region;+ this.endpointURL = (location as TS.S3Location).endpointURL;+ this.ioAPI = require('@tagspaces/tagspaces-common-aws3'); //objectStoreAPI.getS3Api(location);+ } else if (location.type === locationType.TYPE_WEBDAV) {+ // TODO impl+ } else if (AppConfig.isCordova) {+ this.ioAPI = cordovaIO;+ }+ }++ getPath = (param) => {+ if (typeof param === 'object' && param !== null) {+ return param.path;+ } else if (param) {+ return param;+ }+ return '';+ };+ /**+ * normalize path for URL is always '/'+ */+ normalizeUrl = (url: string) => {+ let normalizedUrl = url;+ if (this.getDirSeparator() !== '/') {+ if (url) {+ normalizedUrl = url.replaceAll(this.getDirSeparator(), '/');+ }+ }+ if (!normalizedUrl.startsWith('http') && !normalizedUrl.startsWith('/')) {+ normalizedUrl = '/' + normalizedUrl;+ }+ return normalizedUrl;+ };++ haveObjectStoreSupport = (): boolean => this.type === locationType.TYPE_CLOUD;++ haveWebDavSupport = (): boolean => this.type === locationType.TYPE_WEBDAV;++ getDirSeparator = (): string => {+ return this.ioAPI ? '/' : AppConfig.dirSeparator;+ };++ getEntryThumbPath = (entry: TS.FileSystemEntry, dt = undefined) => {+ if (entry) {+ return this.getThumbPath(this.getThumbEntryPath(entry), dt);+ }+ return undefined;+ };++ getThumbEntryPath = (entry: TS.FileSystemEntry, encoded = false) => {+ if (!entry) {+ return undefined;+ }+ return entry.isFile+ ? getThumbFileLocationForFile(entry.path, this.getDirSeparator(), encoded)+ : getThumbFileLocationForDirectory(entry.path, this.getDirSeparator());+ };+ /**+ * @param path+ * @param dt+ */+ getFolderThumbPath = (path: string, dt = undefined) => {+ if (path) {+ return this.getThumbPath(+ getThumbFileLocationForDirectory(path, this.getDirSeparator()),+ dt,+ );+ }+ return undefined;+ };++ /**+ * @param thumbPath+ * @param dt+ * // isLocalFile - force to generate local URL+ */+ getThumbPath = (+ thumbPath: string,+ dt = undefined,+ // isLocalFile = false, // todo rethink this+ ) => {+ if (!thumbPath) {+ return undefined;+ }+ if (this.haveObjectStoreSupport() || this.haveWebDavSupport()) {+ if (this.isSignedURL(thumbPath)) {+ return thumbPath;+ }+ return this.getURLforPath(thumbPath);+ }+ return this.normalizeUrl(thumbPath) + (dt ? '?' + dt : '');+ };++ isSignedURL = (signedUrl) => {+ try {+ // const query = url.parse(signedUrl, true).query;+ return signedUrl.indexOf('Signature=') !== -1;+ } catch (ex) {}+ return false;+ };++ getFolderBgndPath = (path: string, dt = undefined) => {+ if (path !== undefined) {+ return this.getBgndPath(+ getBgndFileLocationForDirectory(path, this.getDirSeparator()),+ dt,+ );+ }+ return undefined;+ };++ getBgndPath = (bgndPath: string, dt = undefined) => {+ if (!bgndPath) {+ return undefined;+ }+ if (this.haveObjectStoreSupport() || this.haveWebDavSupport()) {+ return this.getURLforPath(bgndPath);+ }+ return this.normalizeUrl(bgndPath) + (dt ? '?' + dt : '');+ };++ listDirectoryPromise = (+ param: any,+ mode = ['extractThumbPath'],+ ignorePatterns: Array<string> = [],+ resultsLimit: any = {},+ ): Promise<Array<any>> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.listDirectoryPromise(+ {+ path: this.getPath(param),+ bucketName: this.bucketName,+ location: this,+ },+ mode,+ ignorePatterns,+ resultsLimit,+ );+ }+ return this.ioAPI.listDirectoryPromise(+ param,+ mode,+ ignorePatterns,+ resultsLimit,+ );+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'listDirectoryPromise',+ param,+ mode,+ ignorePatterns,+ resultsLimit,+ );+ }+ return Promise.reject(new Error('listDirectoryPromise not implemented!'));+ };++ listMetaDirectoryPromise = (param: any): Promise<Array<any>> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.listMetaDirectoryPromise({+ path: this.getPath(param),+ bucketName: this.bucketName,+ location: this,+ });+ }+ return this.ioAPI.listMetaDirectoryPromise(param);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'listMetaDirectoryPromise',+ param,+ );+ }+ return Promise.reject(+ new Error('listMetaDirectoryPromise not implemented!'),+ );+ };++ getPropertiesPromise = (path: string): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.getPropertiesPromise({+ path,+ bucketName: this.bucketName,+ location: this,+ });+ }+ return this.ioAPI.getPropertiesPromise(path);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('getPropertiesPromise', path);+ }+ return Promise.reject(new Error('getPropertiesPromise: not implemented'));+ };++ checkFileExist = (file: string): Promise<boolean> => {+ if (file === undefined) {+ return Promise.resolve(false);+ }+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.isFileExist({+ path: file,+ bucketName: this.bucketName,+ location: this,+ });+ } else if (AppConfig.isCordova) {+ return this.ioAPI.checkFileExist(file);+ }+ return this.ioAPI+ .getPropertiesPromise(file)+ .then((stats) => stats && stats.isFile);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('checkFileExist', file);+ }+ return Promise.reject(new Error('checkFileExist: not implemented'));+ };++ checkDirExist = (dir: string): Promise<boolean> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI+ .getPropertiesPromise({+ path: dir,+ bucketName: this.bucketName,+ location: this,+ })+ .then((stats) => stats && !stats.isFile);+ } else if (AppConfig.isCordova) {+ return this.ioAPI.checkDirExist(dir);+ }+ return this.ioAPI+ .getPropertiesPromise(dir)+ .then((stats) => stats && !stats.isFile);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke('checkDirExist', dir);+ }+ return Promise.reject(new Error('checkDirExist: not implemented'));+ };++ getURLforPath = (path: string, expirationInSeconds: number = 900): string => {+ const currentTime = new Date().getTime();++ // Check if URL is cached and not expired+ if (+ this.urlCache[path] &&+ this.urlCache[path].expirationTime > currentTime+ ) {+ return this.urlCache[path].url;+ } else {+ // Generate new URL and cache it with expiration time+ return this.generateURLforPath(path, expirationInSeconds);+ }+ };++ generateURLforPath = (path, expirationInSeconds) => {+ let url;+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ const param = {+ path,+ bucketName: this.bucketName,+ location: this,+ };+ url = this.ioAPI.getURLforPath(param, expirationInSeconds);+ } else if (this.haveWebDavSupport()) {+ url = this.ioAPI.getURLforPath(path);+ }+ }+ if (url) {+ this.urlCache[path] = {+ url: url,+ expirationTime: new Date().getTime() + expirationInSeconds * 1000,+ };+ }+ return url;+ };++ toFsEntry = (path: string, isFile: boolean): TS.FileSystemEntry => {+ const name = isFile+ ? extractFileName(path, this.getDirSeparator())+ : extractDirectoryName(path, this.getDirSeparator());+ const tags = extractTagsAsObjects(+ name,+ AppConfig.tagDelimiter,+ this.getDirSeparator(),+ );+ return {+ uuid: getUuid(),+ name,+ isFile,+ locationID: this.uuid,+ extension: extractFileExtension(path, this.getDirSeparator()),+ tags,+ size: 0,+ lmdt: new Date().getTime(),+ path,+ };+ };++ createDirectoryPromise = (dirPath: string): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.createDirectoryPromise({+ path: dirPath,+ bucketName: this.bucketName,+ location: this,+ });+ }+ return this.ioAPI.createDirectoryPromise(dirPath);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'createDirectoryPromise',+ dirPath,+ );+ }+ return Promise.reject(new Error('createDirectoryPromise: not implemented'));+ };++ copyFilePromiseOverwrite = (+ sourceFilePath: string,+ targetFilePath: string,+ ): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.copyFilePromise(+ {+ path: sourceFilePath,+ bucketName: this.bucketName,+ location: this,+ },+ targetFilePath,+ );+ }+ return this.ioAPI.copyFilePromise(sourceFilePath, targetFilePath);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'copyFilePromiseOverwrite',+ sourceFilePath,+ targetFilePath,+ );+ }+ return Promise.reject(+ new Error('copyFilePromiseOverwrite: not implemented'),+ );+ };++ renameFilePromise = (+ filePath: string,+ newFilePath: string,+ onProgress = undefined,+ ): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.renameFilePromise(+ {+ path: filePath,+ bucketName: this.bucketName,+ location: this,+ },+ newFilePath,+ onProgress,+ );+ }+ return this.ioAPI.renameFilePromise(filePath, newFilePath, onProgress);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'renameFilePromise',+ filePath,+ newFilePath,+ onProgress !== undefined,+ );+ }+ return Promise.reject(new Error('renameFilePromise: not implemented'));+ };++ renameDirectoryPromise = (+ dirPath: string,+ newDirName: string,+ ): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.renameDirectoryPromise(+ {+ path: dirPath,+ bucketName: this.bucketName,+ location: this,+ },+ newDirName,+ );+ }+ return this.ioAPI.renameDirectoryPromise(dirPath, newDirName);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'renameDirectoryPromise',+ dirPath,+ newDirName,+ );+ }+ return Promise.reject(new Error('renameDirectoryPromise: not implemented'));+ };++ copyDirectoryPromise = (+ param: any,+ newDirPath: string,+ onProgress = undefined,+ ): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.copyDirectoryPromise(+ {+ ...param,+ bucketName: this.bucketName,+ location: this,+ },+ newDirPath,+ onProgress,+ );+ }+ return this.ioAPI.copyDirectoryPromise(param, newDirPath, onProgress);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'copyDirectoryPromise',+ param,+ newDirPath,+ onProgress !== undefined,+ );+ }+ return Promise.reject(new Error('copyDirectoryPromise: not implemented'));+ };++ moveDirectoryPromise = (+ param: any,+ newDirPath: string,+ onProgress = undefined,+ ): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.moveDirectoryPromise(+ {+ ...param,+ bucketName: this.bucketName,+ location: this,+ },+ newDirPath,+ onProgress,+ );+ }+ return this.ioAPI.moveDirectoryPromise(param, newDirPath, onProgress);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'moveDirectoryPromise',+ param,+ newDirPath,+ onProgress !== undefined,+ );+ }+ return Promise.reject(new Error('moveDirectoryPromise: not implemented'));+ };++ saveFilePromise = (+ param: any,+ content: any,+ overwrite: boolean,+ ): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.saveFilePromise(+ {+ ...param,+ bucketName: this.bucketName,+ location: this,+ },+ content,+ overwrite,+ );+ }+ return this.ioAPI.saveFilePromise(param, content, overwrite);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'saveFilePromise',+ param,+ content,+ overwrite,+ );+ }+ return Promise.reject(new Error('saveFilePromise: not implemented'));+ };++ saveTextFilePromise = (+ param: any,+ content: string,+ overwrite: boolean,+ ): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.saveTextFilePromise(+ {+ ...param,+ bucketName: this.bucketName,+ location: this,+ },+ content,+ overwrite,+ );+ }+ return this.ioAPI.saveTextFilePromise(param, content, overwrite);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'saveTextFilePromise',+ param,+ content,+ overwrite,+ );+ }+ return Promise.reject(new Error('saveTextFilePromise: not implemented'));+ };++ 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> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.saveBinaryFilePromise(+ {+ ...param,+ bucketName: this.bucketName,+ location: this,+ },+ content,+ overwrite,+ onUploadProgress,+ );+ } else if (AppConfig.isCordova) {+ return this.ioAPI+ .saveBinaryFilePromise(param, content, overwrite)+ .then((succeeded) => {+ if (succeeded && onUploadProgress) {+ onUploadProgress(+ { key: param.path, loaded: 1, total: 1 },+ undefined,+ );+ }+ return succeeded;+ });+ }+ return this.ioAPI.saveBinaryFilePromise(+ param,+ content,+ overwrite,+ onUploadProgress,+ );+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'saveBinaryFilePromise',+ param,+ content,+ overwrite,+ !!onUploadProgress,+ );+ }+ return Promise.reject(new Error('saveBinaryFilePromise: not implemented'));+ };++ deleteFilePromise = (path: string, useTrash?: boolean): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.deleteFilePromise({+ path,+ bucketName: this.bucketName,+ location: this,+ });+ }+ return this.ioAPI.deleteFilePromise(path);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'deleteFilePromise',+ path,+ useTrash,+ );+ }+ return Promise.reject(new Error('deleteFilePromise: not implemented'));+ };++ deleteDirectoryPromise = (path: string, useTrash?: boolean): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.deleteDirectoryPromise({+ path,+ bucketName: this.bucketName,+ location: this,+ });+ }+ return this.ioAPI.deleteDirectoryPromise(path);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'deleteDirectoryPromise',+ path,+ useTrash,+ );+ }+ return Promise.reject(new Error('deleteDirectoryPromise: not implemented'));+ };++ shareFiles = (files: Array<string>): void => {+ if (AppConfig.isCordova) {+ cordovaIO.shareFiles(files);+ } else {+ console.log('shareFiles is implemented in Cordova only.');+ }+ };++ getLocalFileContentPromise = (+ filePath: string,+ type?: string,+ ): Promise<any> => {+ return window.electronIO.ipcRenderer.invoke(+ 'getFileContentPromise',+ filePath,+ type,+ );+ };++ loadTextFilePromise = (param: any, isPreview?: boolean): Promise<string> => {+ let filePath = this.getPath(param);+ try {+ filePath = decodeURIComponent(filePath);+ } catch (ex) {}+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.loadTextFilePromise(+ {+ path: filePath,+ bucketName: this.bucketName,+ location: this,+ },+ isPreview,+ );+ }+ return this.ioAPI.loadTextFilePromise(filePath, isPreview);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'loadTextFilePromise',+ filePath,+ isPreview,+ );+ }+ return Promise.reject(new Error('loadTextFilePromise: not implemented'));+ };++ getFileContentPromise = (filePath: string, type?: string): Promise<any> => {+ if (this.ioAPI) {+ if (this.haveObjectStoreSupport()) {+ return this.ioAPI.getFileContentPromise(+ {+ path: filePath,+ bucketName: this.bucketName,+ location: this,+ },+ type,+ );+ }+ return this.ioAPI.getFileContentPromise(filePath, type);+ } else if (AppConfig.isElectron) {+ return window.electronIO.ipcRenderer.invoke(+ 'getFileContentPromise',+ filePath,+ type,+ );+ }+ return Promise.reject(new Error('getFileContentPromise: not implemented'));+ };++ createDirectoryIndexInWorker = (+ directoryPath: string,+ extractText: boolean,+ ignorePatterns: Array<string>,+ ): Promise<any> => {+ if (+ AppConfig.isElectron &&+ !this.haveObjectStoreSupport() &&+ !this.haveWebDavSupport()+ ) {+ const payload = JSON.stringify({+ directoryPath,+ extractText,+ ignorePatterns,+ });+ return window.electronIO.ipcRenderer.invoke(+ 'postRequest',+ payload,+ '/indexer',+ );+ }+ return Promise.reject(+ new Error('createDirectoryIndexInWorker not Electron!'),+ );+ };++ loadJSONFile = (filePath: string): Promise<TS.FileSystemEntryMeta> => {+ return this.loadTextFilePromise(filePath)+ .then(+ (jsonContent) => loadJSONString(jsonContent) as TS.FileSystemEntryMeta,+ )+ .catch((e) => {+ console.log('cannot load json:' + filePath, e);+ return undefined;+ });+ };++ checkFilesExistPromise = (+ paths: string[],+ targetPath: string,+ ): Promise<Array<string>> => {+ const promises: TS.FileExistenceCheck[] = paths.map((path) => {+ const targetFile =+ normalizePath(targetPath) ++ this.getDirSeparator() ++ extractFileName(path, this.getDirSeparator());+ return { promise: this.checkFileExist(targetFile), path };+ });+ const progressPromises: Array<Promise<string>> = promises.map(+ ({ promise, path }) =>+ promise+ .then((exists) => (exists ? path : ''))+ .catch((err) => {+ console.log(`Promise ${path} error:`, err);+ return '';+ }),+ );++ return Promise.allSettled(progressPromises).then((results) => {+ return getFulfilledResults(results).filter((r) => r);+ });+ };++ checkDirsExistPromise = (+ paths: string[],+ targetPath: string,+ ): Promise<Array<string>> => {+ const promises: TS.FileExistenceCheck[] = paths.map((path) => {+ const targetDir =+ normalizePath(targetPath) ++ this.getDirSeparator() ++ extractDirectoryName(path, this.getDirSeparator());+ return { promise: this.checkDirExist(targetDir), path };+ });+ const progressPromises: Array<Promise<string>> = promises.map(+ ({ promise, path }) =>+ promise+ .then((exists) => (exists ? path : ''))+ .catch((err) => {+ console.log(`Promise ${path} error:`, err);+ return '';+ }),+ );++ return Promise.allSettled(progressPromises).then((results) => {+ return getFulfilledResults(results).filter((r) => r);+ });+ };+ /**+ * if you have entryProperties.isFile prefer to use loadFileMetaDataPromise/loadDirMetaDataPromise+ * @param path+ * @param fullDescription+ */+ loadMetaDataPromise = (+ path: string,+ fullDescription = false,+ ): Promise<TS.FileSystemEntryMeta> => {+ return this.getPropertiesPromise(path).then((entryProperties) => {+ if (entryProperties) {+ if (entryProperties.isFile) {+ return this.loadFileMetaDataPromise(path, fullDescription);+ }+ return this.loadDirMetaDataPromise(path, fullDescription);+ }+ throw new Error('loadMetaDataPromise not exist' + path);+ });+ };++ loadFileMetaDataPromise = (+ path: string,+ fullDescription = false,+ ): Promise<TS.FileSystemEntryMeta> => {+ const metaFilePath = getMetaFileLocationForFile(+ path,+ this.getDirSeparator(),+ );+ return this.loadJSONFile(metaFilePath).then((metaData) => {+ if (!metaData) {+ throw new Error(+ 'loadFileMetaDataPromise ' + metaFilePath + ' not exist',+ );+ }+ return {+ id: getUuid(),+ isFile: true,+ color: '',+ tags: [],+ appName: '',+ appVersion: '',+ // lastUpdated: 0,+ ...metaData,+ description: fullDescription+ ? metaData.description+ : getDescriptionPreview(metaData.description, 200),+ };+ });+ };++ loadDirMetaDataPromise = (+ path: string,+ fullDescription = false,+ ): Promise<TS.FileSystemEntryMeta> => {+ const metaDirPath = getMetaFileLocationForDir(path, this.getDirSeparator());+ return this.loadJSONFile(metaDirPath).then((metaData) => {+ if (!metaData) {+ throw new Error('loadDirMetaDataPromise ' + metaDirPath + ' not exist');+ }+ return {+ id: getUuid(),+ isFile: false,+ color: '',+ perspective: 'grid',+ tags: [],+ appName: '',+ appVersion: '',+ // lastUpdated: 0,+ ...metaData,+ description: fullDescription+ ? metaData.description+ : getDescriptionPreview(metaData.description, 200),+ };+ });+ };+}diff --git a/src/renderer/utils/dom.ts b/src/renderer/utils/dom.tsindex 68acc3bfc..b5c827f95 100644--- a/src/renderer/utils/dom.ts+++ b/src/renderer/utils/dom.ts@@ -1,5 +1,6 @@import { TS } from '-/tagspaces.namespace';import { getRelativeEntryPath } from '-/services/utils-io';+import { CommonLocation } from '-/utils/CommonLocation';export function isVisibleOnScreen(element: any) {const rectangle = element.getBoundingClientRect();@@ -35,7 +36,7 @@ export function clearURLParam(paramName) {}export function updateHistory(- newLocation: TS.Location,+ newLocation: CommonLocation,newDirectoryPath: string,newEntryPath?: string,) {diff --git a/tests/e2e/fileopener.pw.e2e.js b/tests/e2e/fileopener.pw.e2e.jsindex d74b12595..d00ce6679 100644--- a/tests/e2e/fileopener.pw.e2e.js+++ b/tests/e2e/fileopener.pw.e2e.js@@ -244,8 +244,15 @@ test.describe('TST08 - File folder properties', () => {//await clickOn(getGridFileSelector('sample[' + tagName + '].txt'));//await clickOn('[data-tid=detailsTabTID]');- const propsTags = await getPropertiesTags();- expect(propsTags).toContain(tagName);+ //const propsTags = await getPropertiesTags();+ // expect(propsTags).toContain(tagName);+ await expectElementExist(+ '[data-tid=PropertiesTagsSelectTID] [data-tid=tagContainer_' ++ tagName ++ ']',+ true,+ 4000,+ );});test('TST0811 - Duplicate file [web,minio,electron]', async () => {