Skip to content

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

fix S3 upload on Win, saveFile returns fsentry (#1220)

Stanimirf1b7b8d1c245
diff --git a/app/components/LocationManager.tsx b/app/components/LocationManager.tsx
index 8a91a8fb1..8150328b2 100644
--- a/app/components/LocationManager.tsx
+++ b/app/components/LocationManager.tsx
@@ -107,6 +107,7 @@ interface Props {
isReadOnlyMode: boolean;
hideDrawer: () => void;
openFsEntry: (fsEntry: FileSystemEntry) => void;
+ reflectCreateEntries: (fsEntries: Array<FileSystemEntry>) => void;
openURLExternally: (path: string) => void;
loadDirectoryContent: (path: string) => void;
openLocation: (location: Location) => void;
@@ -137,7 +138,7 @@ interface Props {
files: Array<string>,
destination: string,
onUploadProgress?: (progress: Progress, response: any) => void
- ) => void;
+ ) => Promise<Array<FileSystemEntry>>;
toggleUploadDialog: () => void;
resetProgress: () => void;
}
@@ -472,11 +473,15 @@ class LocationManager extends React.Component<Props, State> {
PlatformIO.enableObjectStoreSupport(targetLocation)
.then(() => {
this.props.resetProgress();
- this.props.uploadFiles(
- arrPath,
- targetPath,
- this.props.onUploadProgress
- );
+ this.props
+ .uploadFiles(arrPath, targetPath, this.props.onUploadProgress)
+ .then((fsEntries: Array<FileSystemEntry>) => {
+ this.props.reflectCreateEntries(fsEntries);
+ return true;
+ })
+ .catch(error => {
+ console.log('uploadFiles', error);
+ });
this.props.toggleUploadDialog();
return true;
})
@@ -832,6 +837,7 @@ function mapDispatchToProps(dispatch) {
openFileNatively: AppActions.openFileNatively,
openFsEntry: AppActions.openFsEntry,
showNotification: AppActions.showNotification,
+ reflectCreateEntries: AppActions.reflectCreateEntries,
moveFiles: IOActions.moveFiles,
uploadFiles: IOActions.uploadFiles,
openURLExternally: AppActions.openURLExternally,
diff --git a/app/components/dialogs/CreateDialog.tsx b/app/components/dialogs/CreateDialog.tsx
index 5a6d09825..645f46cab 100644
--- a/app/components/dialogs/CreateDialog.tsx
+++ b/app/components/dialogs/CreateDialog.tsx
@@ -39,6 +39,7 @@ import { actions as AppActions } from '-/reducers/app';
import AppConfig from '-/config';
import { formatDateTime4Tag } from '-/utils/misc';
import IOActions from '-/reducers/io-actions';
+import { FileSystemEntry } from '-/services/utils-io';
const styles: any = () => ({
root: {
@@ -67,7 +68,7 @@ interface Props {
// fullScreen: boolean;
chooseDirectoryPath: (path: string) => void;
showNotification: (message: string, type: string, autohide: boolean) => void;
- reflectCreateEntry: (path: string, isFile: boolean) => void;
+ reflectCreateEntries: (fsEntries: Array<FileSystemEntry>) => void;
createFileAdvanced: (
targetPath: string,
fileName: string,
@@ -79,7 +80,7 @@ interface Props {
files: Array<File>,
destination: string,
onUploadProgress?: (progress: Progress, response: any) => void
- ) => void;
+ ) => any;
onUploadProgress: (progress: Progress, response: any) => void;
toggleUploadDialog: () => void;
resetProgress: () => void;
@@ -173,11 +174,19 @@ const CreateDialog = (props: Props) => {
// console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0]));
// const file = selection.currentTarget.files[0];
props.resetProgress();
- props.uploadFilesAPI(
- Array.from(selection.currentTarget.files),
- selectedDirectoryPath,
- props.onUploadProgress
- );
+ props
+ .uploadFilesAPI(
+ Array.from(selection.currentTarget.files),
+ selectedDirectoryPath,
+ props.onUploadProgress
+ )
+ .then(fsEntries => {
+ props.reflectCreateEntries(fsEntries);
+ return true;
+ })
+ .catch(error => {
+ console.log('uploadFiles', error);
+ });
props.toggleUploadDialog();
props.onClose();
@@ -355,7 +364,7 @@ function mapActionCreatorsToProps(dispatch) {
{
createFileAdvanced: AppActions.createFileAdvanced,
showNotification: AppActions.showNotification,
- reflectCreateEntry: AppActions.reflectCreateEntry,
+ reflectCreateEntries: AppActions.reflectCreateEntries,
uploadFilesAPI: IOActions.uploadFilesAPI,
onUploadProgress: AppActions.onUploadProgress,
toggleUploadDialog: AppActions.toggleUploadDialog,
diff --git a/app/components/menus/DirectoryMenu.tsx b/app/components/menus/DirectoryMenu.tsx
index e77b38e0c..357303250 100644
--- a/app/components/menus/DirectoryMenu.tsx
+++ b/app/components/menus/DirectoryMenu.tsx
@@ -78,7 +78,8 @@ interface Props {
files: Array<File>,
destination: string,
onUploadProgress?: (progress: Progress, response: any) => void
- ) => void;
+ ) => any;
+ reflectCreateEntries: (fsEntries: Array<FileSystemEntry>) => void;
onUploadProgress: (progress: Progress, response: any) => void;
switchPerspective?: (perspectiveId: string) => void;
perspectiveMode?: boolean;
@@ -309,11 +310,20 @@ const DirectoryMenu = (props: Props) => {
// console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0]));
// const file = selection.currentTarget.files[0];
props.resetProgress();
- props.uploadFilesAPI(
- Array.from(selection.currentTarget.files),
- props.directoryPath,
- props.onUploadProgress
- );
+
+ props
+ .uploadFilesAPI(
+ Array.from(selection.currentTarget.files),
+ props.directoryPath,
+ props.onUploadProgress
+ )
+ .then(fsEntries => {
+ props.reflectCreateEntries(fsEntries);
+ return true;
+ })
+ .catch(error => {
+ console.log('uploadFiles', error);
+ });
props.toggleUploadDialog();
/*
const filePath =
@@ -603,6 +613,7 @@ function mapDispatchToProps(dispatch) {
toggleUploadDialog: AppActions.toggleUploadDialog,
toggleProgressDialog: AppActions.toggleProgressDialog,
resetProgress: AppActions.resetProgress,
+ reflectCreateEntries: AppActions.reflectCreateEntries,
extractContent: IOActions.extractContent,
uploadFilesAPI: IOActions.uploadFilesAPI,
addTags: TaggingActions.addTags
diff --git a/app/containers/MainPage.tsx b/app/containers/MainPage.tsx
index b0c89a05c..14a60958b 100644
--- a/app/containers/MainPage.tsx
+++ b/app/containers/MainPage.tsx
@@ -212,12 +212,12 @@ interface Props {
notificationType?: string,
autohide?: boolean
) => void;
- reflectCreateEntry: (path: string, isFile: boolean) => void;
+ reflectCreateEntries: (fsEntries: Array<FileSystemEntry>) => void;
uploadFilesAPI: (
files: Array<File>,
destination: string,
onUploadProgress?: (progress: Progress, response: any) => void
- ) => void;
+ ) => any;
onUploadProgress: (progress: Progress, response: any) => void;
}
@@ -513,12 +513,21 @@ class MainPage extends Component<Props, State> {
);
} else {
this.props.resetProgress();
- this.props.uploadFilesAPI(
- files,
- this.props.directoryPath,
- this.props.onUploadProgress
- );
+ this.props
+ .uploadFilesAPI(
+ files,
+ this.props.directoryPath,
+ this.props.onUploadProgress
+ )
+ .then(fsEntries => {
+ this.props.reflectCreateEntries(fsEntries);
+ return true;
+ })
+ .catch(error => {
+ console.log('uploadFiles', error);
+ });
this.props.toggleUploadDialog();
+
/* files.map(file => {
let filePath = '';
let fileName = '';
@@ -1015,7 +1024,7 @@ function mapDispatchToProps(dispatch) {
setLeftVerticalSplitSize: SettingsActions.setLeftVerticalSplitSize,
setMainVerticalSplitSize: SettingsActions.setMainVerticalSplitSize,
showNotification: AppActions.showNotification,
- reflectCreateEntry: AppActions.reflectCreateEntry,
+ reflectCreateEntries: AppActions.reflectCreateEntries,
openLocationManagerPanel: AppActions.openLocationManagerPanel,
openTagLibraryPanel: AppActions.openTagLibraryPanel,
openSearchPanel: AppActions.openSearchPanel,
diff --git a/app/perspectives/grid-perspective/components/CellContent.tsx b/app/perspectives/grid-perspective/components/CellContent.tsx
index 81f7ee242..0a5d9bc20 100644
--- a/app/perspectives/grid-perspective/components/CellContent.tsx
+++ b/app/perspectives/grid-perspective/components/CellContent.tsx
@@ -99,10 +99,12 @@ const CellContent = (props: Props) => {
);
let tagTitles = '';
- fsEntry.tags.map(tag => {
- tagTitles += tag.title + ', ';
- return true;
- });
+ if (fsEntry.tags) {
+ fsEntry.tags.map(tag => {
+ tagTitles += tag.title + ', ';
+ return true;
+ });
+ }
tagTitles = tagTitles.substring(0, tagTitles.length - 2);
const tagPlaceholder =
tagTitles.length > 0 ? (
@@ -144,7 +146,7 @@ const CellContent = (props: Props) => {
/>
)}
<div id="gridCellTags" className={classes.gridCellTags}>
- {showTags
+ {showTags && fsEntry.tags
? fsEntry.tags.map(tag => renderTag(tag))
: tagPlaceholder}
</div>
@@ -271,7 +273,7 @@ const CellContent = (props: Props) => {
<Typography style={{ wordBreak: 'break-all', alignSelf: 'center' }}>
{entryTitle}
&nbsp;
- {showTags
+ {showTags && fsEntry.tags
? fsEntry.tags.map(tag => renderTag(tag))
: tagPlaceholder}
</Typography>
@@ -281,7 +283,7 @@ const CellContent = (props: Props) => {
<Typography style={{ wordBreak: 'break-all' }}>
{entryTitle}
</Typography>
- {showTags
+ {showTags && fsEntry.tags
? fsEntry.tags.map(tag => renderTag(tag))
: tagPlaceholder}
<Typography
diff --git a/app/reducers/app.ts b/app/reducers/app.ts
index 705082ffb..7f01d96b9 100644
--- a/app/reducers/app.ts
+++ b/app/reducers/app.ts
@@ -1525,6 +1525,11 @@ export const actions = {
type: types.REFLECT_CREATE_ENTRY,
newEntry
}),
+ reflectCreateEntries: (fsEntries: Array<FileSystemEntry>) => (
+ dispatch: (actions: Object) => void
+ ) => {
+ fsEntries.map(entry => dispatch(actions.reflectCreateEntryInt(entry))); // TODO remove map and set state once
+ },
reflectCreateEntry: (path: string, isFile: boolean) => (
dispatch: (actions: Object) => void
) => {
diff --git a/app/reducers/io-actions.ts b/app/reducers/io-actions.ts
index 782e9c7f4..150ae5d87 100644
--- a/app/reducers/io-actions.ts
+++ b/app/reducers/io-actions.ts
@@ -20,6 +20,7 @@ import { Progress } from 'aws-sdk/clients/s3';
import { actions as AppActions } from './app';
import {
extractFileName,
+ getMetaFileLocationForDir,
getMetaFileLocationForFile,
getThumbFileLocationForFile,
normalizePath
@@ -27,6 +28,9 @@ import {
import {
copyFilesPromise,
enhanceEntry,
+ FileSystemEntry,
+ loadJSONFile,
+ loadJSONString,
renameFilesPromise
} from '-/services/utils-io';
import i18n from '../services/i18n';
@@ -186,82 +190,92 @@ const actions = {
actions.uploadFiles(arrFiles, targetPath, onUploadProgress)
);
}
- // -> cannot upload meta data (for every upload in web browser its need to have <input> element)
- setupReader(0);
- function setupReader(i) {
- const file = files[i];
- const reader = new FileReader();
- const filePath =
- normalizePath(targetPath) +
- PlatformIO.getDirSeparator() +
- decodeURIComponent(file.name);
- reader.onload = (event: any) => {
- readerLoaded(event, i, filePath);
- };
- if (AppConfig.isCordova) {
- reader.readAsDataURL(file);
- } else {
- reader.readAsArrayBuffer(file);
+ return new Promise(resolve => {
+ const fsEntries = [];
+ // -> cannot upload meta data (for every upload in web browser its need to have <input> element)
+ setupReader(0);
+
+ function setupReader(i) {
+ const file = files[i];
+ const reader = new FileReader();
+ let filePath =
+ normalizePath(targetPath) +
+ PlatformIO.getDirSeparator() +
+ decodeURIComponent(file.name);
+ if (PlatformIO.haveObjectStoreSupport() && filePath.startsWith('/')) {
+ filePath = filePath.substr(1);
+ }
+ reader.onload = (event: any) => {
+ readerLoaded(event, i, filePath);
+ };
+ if (AppConfig.isCordova) {
+ reader.readAsDataURL(file);
+ } else {
+ reader.readAsArrayBuffer(file);
+ }
}
- }
- function readerLoaded(event, i, fileTargetPath) {
- PlatformIO.getPropertiesPromise(fileTargetPath)
- .then(entryProps => {
- if (entryProps) {
- dispatch(
- AppActions.showNotification(
- 'File with the same name already exist, importing skipped!',
- 'warning',
- true
+ function readerLoaded(event, i, fileTargetPath) {
+ PlatformIO.getPropertiesPromise(fileTargetPath)
+ .then(entryProps => {
+ if (entryProps) {
+ dispatch(
+ AppActions.showNotification(
+ 'File with the same name already exist, importing skipped!',
+ 'warning',
+ true
+ )
+ );
+ } else {
+ PlatformIO.saveBinaryFilePromise(
+ fileTargetPath,
+ event.currentTarget.result,
+ true,
+ onUploadProgress
)
- );
- } else {
- PlatformIO.saveBinaryFilePromise(
- fileTargetPath,
- event.currentTarget.result,
- true,
- onUploadProgress
- )
- .then(() => {
- dispatch(
- AppActions.showNotification(
- 'File ' + fileTargetPath + ' successfully imported.',
- 'default',
- true
- )
- );
- dispatch(AppActions.reflectCreateEntry(fileTargetPath, true));
- return true;
- })
- .catch(error => {
- // TODO showAlertDialog("Saving " + filePath + " failed.");
- console.error(
- 'Save to file ' + fileTargetPath + ' failed ' + error
- );
- dispatch(
- AppActions.showNotification(
- 'Importing file ' + fileTargetPath + ' failed.',
- 'error',
- true
- )
- );
- return true;
- });
- }
- return true;
- })
- .catch(err => {
- console.log('Error getting properties ' + err);
- });
+ .then((fsEntry: FileSystemEntry) => {
+ dispatch(
+ AppActions.showNotification(
+ 'File ' + fileTargetPath + ' successfully imported.',
+ 'default',
+ true
+ )
+ );
+ fsEntries.push(fsEntry);
+ // dispatch(AppActions.reflectCreateEntry(fileTargetPath, true));
+ return true;
+ })
+ .catch(error => {
+ // TODO showAlertDialog("Saving " + filePath + " failed.");
+ console.error(
+ 'Save to file ' + fileTargetPath + ' failed ' + error
+ );
+ dispatch(
+ AppActions.showNotification(
+ 'Importing file ' + fileTargetPath + ' failed.',
+ 'error',
+ true
+ )
+ );
+ return true;
+ });
+ }
+ return true;
+ })
+ .catch(err => {
+ console.log('Error getting properties ' + err);
+ });
- // If there's a file left to load
- if (i < files.length - 1) {
- // Load the next file
- setupReader(i + 1);
+ // If there's a file left to load
+ if (i < files.length - 1) {
+ // Load the next file
+ setupReader(i + 1);
+ } else {
+ resolve(fsEntries);
+ }
}
- }
+ });
},
/**
@@ -278,111 +292,168 @@ const actions = {
new Promise(resolve => {
const uploadJobs = [];
paths.map(path => {
- const target =
+ let target =
normalizePath(targetPath) +
- PlatformIO.getDirSeparator() +
- extractFileName(path, PlatformIO.getDirSeparator());
+ AppConfig.dirSeparator +
+ extractFileName(path, AppConfig.dirSeparator); // PlatformIO.getDirSeparator()); // with "/" dir separator cannot extractFileName on Win
+ // fix for Win
+ if (
+ PlatformIO.haveObjectStoreSupport() &&
+ (target.startsWith('\\') || target.startsWith('/'))
+ ) {
+ target = target.substr(1);
+ }
uploadJobs.push([path, target]);
// copy meta
uploadJobs.push([
- getMetaFileLocationForFile(path, PlatformIO.getDirSeparator()),
- getMetaFileLocationForFile(target, PlatformIO.getDirSeparator())
+ getMetaFileLocationForFile(path, AppConfig.dirSeparator),
+ getMetaFileLocationForFile(target, AppConfig.dirSeparator)
]);
uploadJobs.push([
- getThumbFileLocationForFile(path, PlatformIO.getDirSeparator()),
- getThumbFileLocationForFile(target, PlatformIO.getDirSeparator())
+ getThumbFileLocationForFile(path, AppConfig.dirSeparator),
+ getThumbFileLocationForFile(target, AppConfig.dirSeparator)
]);
return true;
});
- resolve(
- uploadJobs.map(job => {
- // console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0]));
- // const file = selection.currentTarget.files[0];
- const filePath = job[1];
- /* normalizePath(props.directoryPath) +
+ const jobsPromises = uploadJobs.map(job => {
+ // console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0]));
+ // const file = selection.currentTarget.files[0];
+ const filePath = job[1];
+ /* normalizePath(props.directoryPath) +
PlatformIO.getDirSeparator() +
decodeURIComponent(file.name); */
- // TODO try to replace this with <input type="file"
- if (AppConfig.isElectron) {
- return import('fs-extra')
- .then(fs => {
- const fileContent = fs.readFileSync(job[0]);
- // TODO event.currentTarget.result is ArrayBuffer
- // Sample call from PRO version using content = Utils.base64ToArrayBuffer(baseString);
- return PlatformIO.getPropertiesPromise(filePath)
- .then(entryProps => {
- if (entryProps) {
- dispatch(
- AppActions.showNotification(
- 'File with the same name already exist, importing skipped!',
- 'warning',
- true
- )
- );
- dispatch(AppActions.setProgress(filePath, -1, undefined));
- } else {
- // dispatch(AppActions.setProgress(filePath, progress));
- return PlatformIO.saveBinaryFilePromise(
- filePath,
- fileContent,
- true,
- onUploadProgress
+ // TODO try to replace this with <input type="file"
+ if (AppConfig.isElectron) {
+ return import('fs-extra')
+ .then(fs => {
+ const fileContent = fs.readFileSync(job[0]);
+ // TODO event.currentTarget.result is ArrayBuffer
+ // Sample call from PRO version using content = Utils.base64ToArrayBuffer(baseString);
+ return PlatformIO.getPropertiesPromise(filePath)
+ .then(entryProps => {
+ if (entryProps) {
+ dispatch(
+ AppActions.showNotification(
+ 'File with the same name already exist, importing skipped!',
+ 'warning',
+ true
)
- .then(() => {
- dispatch(
- AppActions.showNotification(
- 'File ' + filePath + ' successfully imported.',
- 'default',
- true
- )
- );
- dispatch(
- AppActions.reflectCreateEntry(filePath, true)
- );
- // TODO handle Thumbnail
- if (filePath.indexOf('/.ts/') === -1) {
- return enhanceEntry({
- name: filePath.substring(
- filePath.lastIndexOf(AppConfig.dirSeparator) +
- 1,
- filePath.length
- ),
- isFile: true,
- size: fileContent.length,
- lmdt: Date.now(),
- path: filePath
- });
+ );
+ dispatch(AppActions.setProgress(filePath, -1, undefined));
+ } else {
+ // dispatch(AppActions.setProgress(filePath, progress));
+ return PlatformIO.saveBinaryFilePromise(
+ filePath,
+ fileContent,
+ true,
+ onUploadProgress
+ )
+ .then((fsEntry: FileSystemEntry) => {
+ if (filePath.indexOf('.ts/') !== -1) {
+ // handle meta file TODO catch thumb
+ if (fsEntry.path.endsWith('.json')) {
+ try {
+ // eslint-disable-next-line no-param-reassign
+ fsEntry.meta = loadJSONString(
+ fileContent.toString()
+ );
+ } catch (e) {
+ console.debug('cannot parse entry meta');
+ }
}
- return undefined;
- })
- .catch(err => {
- console.error(
- 'Importing file ' + filePath + ' failed ' + err
- );
- dispatch(
- AppActions.showNotification(
- 'Importing file ' + filePath + ' failed.',
- 'error',
- true
- )
- );
- return undefined;
- });
- }
- return undefined;
- })
- .catch(err => {
- console.log('Error getting properties ' + err);
- });
- })
- .catch(err => {
- console.log('Error import fs: ' + err);
- });
- }
- return undefined;
+ }
+
+ return fsEntry;
+ })
+ .catch(err => {
+ console.error(
+ 'Importing file ' + filePath + ' failed ' + err
+ );
+ dispatch(
+ AppActions.showNotification(
+ 'Importing file ' + filePath + ' failed.',
+ 'error',
+ true
+ )
+ );
+ return undefined;
+ });
+ }
+ return undefined;
+ })
+ .catch(err => {
+ console.log('Error getting properties ' + err);
+ });
+ })
+ .catch(err => {
+ console.log('Error import fs: ' + err);
+ });
+ }
+ return undefined;
+ });
+ Promise.all(jobsPromises)
+ .then(filesProm => {
+ const arrFiles: Array<FileSystemEntry> = [];
+ const arrMeta: Array<FileSystemEntry> = [];
+ const arrThumb: Array<FileSystemEntry> = [];
+
+ filesProm.map(file => {
+ if (file) {
+ if (file.path.indexOf('.ts/') === -1) {
+ arrFiles.push(file); // enhanceEntry(file));
+ } else if (file.meta) {
+ arrMeta.push(file);
+ } else {
+ arrThumb.push(file);
+ }
+ }
+ /* if (file !== undefined) {
+ // dispatch(AppActions.reflectCreateEntryInt(entryEnhanced));
+ const metaFileProps = await PlatformIO.getPropertiesPromise(metaFilePath);
+ if (metaFileProps.isFile) {
+ entryProps.meta = await loadJSONFile(metaFilePath);
+ }
+ arrFiles.push(enhanceEntry(file)); // TODO optimize and Enhance Entry with uploaded .ts metafiles
+ } */
+ return true;
+ });
+ dispatch(
+ AppActions.showNotification(
+ 'File ' +
+ arrFiles.map(file => file.name).toString() +
+ ' successfully imported.',
+ 'default',
+ true
+ )
+ );
+
+ // Enhance entries
+ resolve(
+ arrFiles.map((file: FileSystemEntry) => {
+ const metaFilePath = getMetaFileLocationForFile(
+ file.path,
+ AppConfig.dirSeparator
+ );
+ for (let i = 0; i < arrMeta.length; i += 1) {
+ const metaFile = arrMeta[i];
+ if (metaFile.path === metaFilePath) {
+ // eslint-disable-next-line no-param-reassign
+ file.meta = metaFile.meta;
+ }
+ }
+ if (file.meta) {
+ return enhanceEntry(file);
+ }
+ return file;
+ })
+ );
+
+ return true;
})
- );
+ .catch(err => {
+ console.log('Error import fs: ' + err);
+ });
})
};
diff --git a/app/services/cordova-io.ts b/app/services/cordova-io.ts
index e6091d637..cc76a4b81 100644
--- a/app/services/cordova-io.ts
+++ b/app/services/cordova-io.ts
@@ -21,7 +21,9 @@ import AppConfig from '../config';
import { b64toBlob } from '../utils/misc';
import {
extractParentDirectoryPath,
- cleanTrailingDirSeparator
+ cleanTrailingDirSeparator,
+ extractFileName,
+ extractFileExtension
} from '../utils/paths';
import { FileSystemEntry } from './utils-io';
@@ -792,12 +794,12 @@ export default class CordovaIO {
content,
overWrite: boolean,
isRaw?: boolean
- ): Promise<any> => {
+ ): Promise<FileSystemEntry> => {
// eslint-disable-next-line no-param-reassign
filePath = this.normalizePath(filePath);
console.log('Saving file: ' + filePath);
return new Promise((resolve, reject) => {
- let isFileNew = true;
+ let isNewFile = true;
// Checks if the file already exists
this.fsRoot.getFile(
filePath,
@@ -807,12 +809,12 @@ export default class CordovaIO {
},
entry => {
if (entry.isFile) {
- isFileNew = false;
+ isNewFile = false;
}
},
() => {}
);
- if (isFileNew || overWrite) {
+ if (isNewFile || overWrite) {
this.fsRoot.getFile(
filePath,
{
@@ -824,7 +826,18 @@ export default class CordovaIO {
writer => {
writer.onwriteend = function(evt) {
// resolve(this.fsRoot.fullPath + "/" + filePath);
- resolve(isFileNew);
+ resolve({
+ name: extractFileName(filePath, AppConfig.dirSeparator),
+ isFile: true,
+ path: filePath,
+ extension: extractFileExtension(
+ filePath,
+ AppConfig.dirSeparator
+ ),
+ size: 0, // TODO debug evt and set size
+ lmdt: new Date().getTime(),
+ isNewFile
+ });
};
if (isRaw) {
writer.write(content);
@@ -888,7 +901,7 @@ export default class CordovaIO {
filePath: string,
content: any,
overWrite: boolean
- ) => {
+ ): Promise<FileSystemEntry> => {
console.log('Saving binary file: ' + filePath);
// var dataView = new Int8Array(content);
const dataView = content;
diff --git a/app/services/electron-io.ts b/app/services/electron-io.ts
index e7ace55c2..d9969857b 100644
--- a/app/services/electron-io.ts
+++ b/app/services/electron-io.ts
@@ -20,6 +20,8 @@ import fsextra from 'fs-extra';
import pathLib from 'path';
import winattr from 'winattr';
import {
+ extractFileExtension,
+ extractFileName,
extractParentDirectoryPath,
getMetaDirectoryPath
} from '../utils/paths';
@@ -31,6 +33,7 @@ import TrayIcon from '../assets/icons/trayIcon.png';
import TrayIcon2x from '../assets/icons/[email protected]';
import TrayIcon3x from '../assets/icons/[email protected]';
import { Pro } from '../pro';
+import { FileSystemEntry } from '-/services/utils-io';
export default class ElectronIO {
electron: any;
@@ -696,25 +699,25 @@ export default class ElectronIO {
filePath: string,
content: any,
overwrite: boolean = true
- ): Promise<any> =>
+ ): Promise<FileSystemEntry> =>
new Promise((resolve, reject) => {
const fileSystem = this.fs;
- function saveFile(fPath, tContent, isNewFile) {
- fileSystem.writeFile(fPath, tContent, 'utf8', error => {
+ function saveFile(entry: FileSystemEntry, tContent) {
+ fileSystem.writeFile(entry.path, tContent, 'utf8', error => {
if (error) {
reject(error);
return;
}
- resolve(isNewFile);
+ resolve(entry);
});
}
this.getPropertiesPromise(filePath)
- .then(entry => {
+ .then((entry: FileSystemEntry) => {
if (entry && entry.isFile && overwrite) {
- saveFile(filePath, content, false);
+ saveFile({ ...entry, isNewFile: false }, content);
} else {
- saveFile(filePath, content, true);
+ saveFile({ ...entry, isNewFile: true }, content);
}
return true;
})
@@ -723,7 +726,16 @@ export default class ElectronIO {
console.log(
'Getting properties for ' + filePath + ' failed with: ' + error
);
- saveFile(filePath, content, true);
+ const fsEntry = {
+ name: extractFileName(filePath, AppConfig.dirSeparator),
+ isFile: true,
+ path: filePath,
+ extension: extractFileExtension(filePath, AppConfig.dirSeparator),
+ size: 0,
+ lmdt: new Date().getTime(),
+ isNewFile: true
+ };
+ saveFile(fsEntry, content);
});
});
@@ -731,7 +743,7 @@ export default class ElectronIO {
filePath: string,
content: string,
overwrite: boolean
- ): Promise<any> => {
+ ): Promise<FileSystemEntry> => {
console.log('Saving file: ' + filePath);
// Handling the UTF8 support for text files
@@ -751,7 +763,7 @@ export default class ElectronIO {
filePath: string,
content: any,
overwrite: boolean
- ): Promise<any> => {
+ ): Promise<FileSystemEntry> => {
console.log('Saving binary file: ' + filePath);
const buff = arrayBufferToBuffer(content);
return this.saveFilePromise(filePath, buff, overwrite);
diff --git a/app/services/platform-io.ts b/app/services/platform-io.ts
index 2b98c9f38..17ea6be0f 100644
--- a/app/services/platform-io.ts
+++ b/app/services/platform-io.ts
@@ -21,6 +21,7 @@ import { Pro } from '../pro';
// @ts-ignore
import NativePlatformIO from './_PLATFORMIO_';
import AppConfig from '-/config';
+import { FileSystemEntry } from '-/services/utils-io';
const nativeAPI: any = new NativePlatformIO();
let objectStoreAPI;
@@ -63,7 +64,7 @@ export default class PlatformIO {
static haveObjectStoreSupport = (): boolean => objectStoreAPI !== undefined;
- static getDirSeparator = (): string =>
+ static getDirSeparator = (): string => // TODO rethink usage for S3 on Win
PlatformIO.haveObjectStoreSupport() ? '/' : AppConfig.dirSeparator;
static initMainMenu = (menuConfig: Array<Object>): void => {
@@ -243,7 +244,7 @@ export default class PlatformIO {
progress: any, // ManagedUpload.Progress,
response: any // AWS.Response<AWS.S3.PutObjectOutput, AWS.AWSError>
) => void
- ): Promise<any> => {
+ ): Promise<FileSystemEntry> => {
if (objectStoreAPI) {
return objectStoreAPI.saveBinaryFilePromise(
filePath,
diff --git a/app/services/utils-io.ts b/app/services/utils-io.ts
index 8bf6192ef..07ea5a141 100644
--- a/app/services/utils-io.ts
+++ b/app/services/utils-io.ts
@@ -39,6 +39,7 @@ export interface FileSystemEntry {
uuid?: string;
name: string;
isFile: boolean;
+ isNewFile?: boolean;
extension: string;
thumbPath?: string;
color?: string;
@@ -366,9 +367,9 @@ export async function getAllPropertiesPromise(
}
export async function loadJSONFile(filePath: string) {
- let jsonObject;
- let jsonContent = await PlatformIO.loadTextFilePromise(filePath);
- const UTF8_BOM = '\ufeff';
+ const jsonContent = await PlatformIO.loadTextFilePromise(filePath);
+ return loadJSONString(jsonContent);
+ /* const UTF8_BOM = '\ufeff';
if (jsonContent.indexOf(UTF8_BOM) === 0) {
jsonContent = jsonContent.substring(1, jsonContent.length);
}
@@ -377,6 +378,21 @@ export async function loadJSONFile(filePath: string) {
} catch (err) {
console.warn('Error parsing meta json file for ' + filePath + ' - ' + err);
}
+ return jsonObject; */
+}
+
+export function loadJSONString(jsonContent: string) {
+ let jsonObject;
+ let json;
+ const UTF8_BOM = '\ufeff';
+ if (jsonContent.indexOf(UTF8_BOM) === 0) {
+ json = jsonContent.substring(1, jsonContent.length);
+ }
+ try {
+ jsonObject = JSON.parse(json);
+ } catch (err) {
+ console.error('Error parsing meta json file: ' + json, err);
+ }
return jsonObject;
}
diff --git a/app/services/webdav-io.ts b/app/services/webdav-io.ts
index d35b32623..d80dbf9f3 100644
--- a/app/services/webdav-io.ts
+++ b/app/services/webdav-io.ts
@@ -20,7 +20,9 @@ import nl from '../utils/js-webdav-client';
import {
extractParentDirectoryPath,
normalizePath,
- getMetaFileLocationForDir
+ getMetaFileLocationForDir,
+ extractFileName,
+ extractFileExtension
} from '../utils/paths';
import AppConfig from '../config';
import { FileSystemEntry } from './utils-io';
@@ -452,7 +454,7 @@ export default class WebDAVIO {
content: string,
overWrite: boolean,
mode?: string
- ): Promise<Object> =>
+ ): Promise<FileSystemEntry> =>
new Promise((resolve, reject) => {
let isNewFile = false;
this.davClient.propfind(
@@ -461,25 +463,36 @@ export default class WebDAVIO {
console.log(
'Check file exists: Status / Content: ' + status + ' / ' + data
);
- if (parseInt(status) === 404) {
+ if (parseInt(status, 10) === 404) {
isNewFile = true;
}
if (isNewFile || overWrite === true || mode === 'text') {
this.davClient.put(
encodeURI(filePath),
- (status, data, headers) => {
+ (status1, data1, headers) => {
console.log(
'Creating File Status/Content/Headers: ' +
status +
' / ' +
- data +
+ data1 +
' / ' +
headers
);
- if (this.checkStatusCode(status)) {
- resolve(isNewFile);
+ if (this.checkStatusCode(status1)) {
+ resolve({
+ name: extractFileName(filePath, AppConfig.dirSeparator),
+ isFile: true,
+ path: filePath,
+ extension: extractFileExtension(
+ filePath,
+ AppConfig.dirSeparator
+ ),
+ size: 0,
+ lmdt: new Date().getTime(),
+ isNewFile
+ });
} else {
- reject('saveFilePromise: ' + filePath + ' failed ' + status);
+ reject('saveFilePromise: ' + filePath + ' failed ' + status1);
}
},
content,
@@ -512,7 +525,7 @@ export default class WebDAVIO {
filePath: string,
content: string,
overWrite: boolean
- ): Promise<Object> {
+ ): Promise<FileSystemEntry> {
console.log('Saving binary file: ' + filePath);
return this.saveFilePromise(filePath, content, overWrite);
}