Skip to content

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

Implementing download from URL in separate dialog for Electron only (#2175)

Stanimir911039ec1389
diff --git a/src/main/mainEvents.ts b/src/main/mainEvents.ts
index c32f24c73..6856b48bd 100644
--- a/src/main/mainEvents.ts
+++ b/src/main/mainEvents.ts
@@ -29,6 +29,8 @@ import {
isDirectory,
} from '@tagspaces/tagspaces-common-node/io-node';
import fs from 'fs-extra';
+import http from 'http';
+import https from 'https';
import path from 'path';
import WebSocket from 'ws';
import {
@@ -81,6 +83,61 @@ export default function loadMainEvents() {
//watchFolder(mainWindow, e, path, depth);
});
+ ipcMain.handle('fetchUrl', async (event, url, targetPath, withProgress) => {
+ function fetchHttp(url) {
+ return new Promise((resolve, reject) => {
+ const client = url.startsWith('https') ? https : http;
+
+ client
+ .get(url, (res) => {
+ let downloadedSize = 0;
+ const totalSize = parseInt(res.headers['content-length'], 10);
+
+ let onUploadProgress = undefined;
+ if (withProgress) {
+ progress['fetchUrl'] = newProgress('fetchUrl', totalSize);
+ onUploadProgress = getOnProgress('fetchUrl', progress);
+ }
+
+ const fileStream = fs.createWriteStream(targetPath); // Write file to disk
+ // Pipe the response data into the file
+ res.pipe(fileStream);
+
+ // Collect data chunks and calculate size
+ res.on('data', (chunk) => {
+ downloadedSize += chunk.length; // Add the size of the current chunk
+ if (onUploadProgress) {
+ onUploadProgress(
+ { key: targetPath, loaded: downloadedSize, total: totalSize },
+ undefined,
+ );
+ }
+ });
+
+ // Resolve the response on end
+ res.on('end', () => {
+ if (onUploadProgress) {
+ onUploadProgress(
+ { key: targetPath, loaded: 1, total: 1 },
+ undefined,
+ );
+ }
+ resolve({ success: true, filePath: targetPath });
+ });
+ })
+ .on('error', (err) => {
+ reject(err);
+ });
+ });
+ }
+
+ try {
+ const response = await fetchHttp(url);
+ return response;
+ } catch (error) {
+ return { error: error.message };
+ }
+ });
ipcMain.handle('isWorkerAvailable', async () => {
const results = await isWorkerAvailable();
return results;
@@ -308,7 +365,6 @@ export default function loadMainEvents() {
param,
content,
overwrite,
- onUploadProgress,
).then((succeeded) => {
if (succeeded && onUploadProgress) {
onUploadProgress({ key: param.path, loaded: 1, total: 1 }, undefined);
diff --git a/src/main/preload.ts b/src/main/preload.ts
index 5c02bfa53..54b264e31 100644
--- a/src/main/preload.ts
+++ b/src/main/preload.ts
@@ -9,6 +9,7 @@ import {
export type Channels =
| 'isWorkerAvailable'
+ | 'fetchUrl'
| 'isDirectory'
| 'resolveRelativePaths'
| 'set-language'
diff --git a/src/renderer/components/EntryContainerTabs.tsx b/src/renderer/components/EntryContainerTabs.tsx
index e5b422a1d..4855054cd 100644
--- a/src/renderer/components/EntryContainerTabs.tsx
+++ b/src/renderer/components/EntryContainerTabs.tsx
@@ -147,9 +147,9 @@ function EntryContainerTabs(props: EntryContainerTabsProps) {
const backupFilePath = getBackupFileDir(
openedEntry.path,
openedEntry.uuid,
- location.getDirSeparator(),
+ location?.getDirSeparator(),
);
- location.checkDirExist(backupFilePath).then((exist) => {
+ location?.checkDirExist(backupFilePath).then((exist) => {
if (exist) {
haveRevisions.current = exist;
forceUpdate();
diff --git a/src/renderer/components/EntryProperties.tsx b/src/renderer/components/EntryProperties.tsx
index 8c1fb433f..46d6564db 100644
--- a/src/renderer/components/EntryProperties.tsx
+++ b/src/renderer/components/EntryProperties.tsx
@@ -340,7 +340,7 @@ function EntryProperties(props: Props) {
openedEntry.path,
location?.getDirSeparator(),
);
- const nextPath = path + location.getDirSeparator() + editName;
+ const nextPath = path + location?.getDirSeparator() + editName;
if (openedEntry.isFile) {
renameFile(openedEntry.path, nextPath, openedEntry.locationID).catch(
@@ -411,7 +411,7 @@ function EntryProperties(props: Props) {
} else if (dirProps.current) {
return formatBytes(dirProps.current.totalSize);
}
- return t(location.haveObjectStoreSupport() ? 'core:notAvailable' : '?');
+ return t(location?.haveObjectStoreSupport() ? 'core:notAvailable' : '?');
};
const toggleBackgroundColorPicker = () => {
@@ -775,7 +775,7 @@ function EntryProperties(props: Props) {
<Grid item xs={12}>
<Tooltip
title={
- !location.haveObjectStoreSupport() &&
+ !location?.haveObjectStoreSupport() &&
dirProps.current &&
!openedEntry.isFile &&
dirProps.current.dirsCount +
diff --git a/src/renderer/components/MobileNavigation.tsx b/src/renderer/components/MobileNavigation.tsx
index 8295b4c69..91dc066f5 100644
--- a/src/renderer/components/MobileNavigation.tsx
+++ b/src/renderer/components/MobileNavigation.tsx
@@ -23,6 +23,7 @@ import classNames from 'classnames';
import Box from '@mui/material/Box';
import Tooltip from '-/components/Tooltip';
import ToggleButton from '@mui/material/ToggleButton';
+import FileDownloadIcon from '@mui/icons-material/FileDownload';
import Button from '@mui/material/Button';
import ButtonGroup from '@mui/material/ButtonGroup';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
@@ -55,7 +56,6 @@ import ProTeaser from '-/components/ProTeaser';
import TagLibrary from '-/components/TagLibrary';
import LocationManager from '-/components/LocationManager';
import HelpFeedbackPanel from '-/components/HelpFeedbackPanel';
-import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import ClickAwayListener from '@mui/material/ClickAwayListener';
import Grow from '@mui/material/Grow';
import Paper from '@mui/material/Paper';
@@ -84,6 +84,7 @@ import { useUserContext } from '-/hooks/useUserContext';
import { useFileUploadContext } from '-/hooks/useFileUploadContext';
import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';
import { useLinkDialogContext } from '-/components/dialogs/hooks/useLinkDialogContext';
+import { useDownloadUrlDialogContext } from '-/components/dialogs/hooks/useDownloadUrlDialogContext';
const PREFIX = 'MobileNavigation';
@@ -122,6 +123,7 @@ function MobileNavigation(props: Props) {
const { openSettingsDialog } = useSettingsDialogContext();
const { openLinkDialog } = useLinkDialogContext();
const { currentOpenedPanel, showPanel } = usePanelsContext();
+ const { openDownloadUrl } = useDownloadUrlDialogContext();
const keyBindings = useSelector(getKeyBindingObject);
/* const isLocationManagerPanelOpenedSelector = useSelector(
isLocationManagerPanelOpened,
@@ -316,7 +318,7 @@ function MobileNavigation(props: Props) {
<InfoIcon tooltip={t('core:createNoteTitle')} />
</MenuItem>
<MenuItem
- key="createNewLinkFileTID"
+ key="createNewLinkFile"
data-tid="createNewLinkFileTID"
onClick={() => {
openNewFileDialog('url');
@@ -372,6 +374,24 @@ function MobileNavigation(props: Props) {
</ListItemIcon>
<ListItemText primary={t('core:addFiles')} />
</MenuItem>
+ {AppConfig.isElectron && (
+ <MenuItem
+ key="newFromDownloadURL"
+ data-tid="newFromDownloadURLTID"
+ onClick={() => {
+ openDownloadUrl();
+ setOpenCreateMenu(false);
+ if (hideDrawer) {
+ hideDrawer();
+ }
+ }}
+ >
+ <ListItemIcon>
+ <FileDownloadIcon />
+ </ListItemIcon>
+ <ListItemText primary={t('core:newFromDownloadURL')} />
+ </MenuItem>
+ )}
<Divider />
<MenuItem
key="createNewFolderTID"
@@ -409,7 +429,6 @@ function MobileNavigation(props: Props) {
</MenuItem>
{!AppConfig.isCordova && (
<>
- {/* <Divider /> */}
<MenuItem
key="createWindowTID"
ata-tid="createWindowTID"
diff --git a/src/renderer/components/dialogs/components/CreateDirectory.tsx b/src/renderer/components/dialogs/DownloadUrlDialog.tsx
similarity index 51%
rename from src/renderer/components/dialogs/components/CreateDirectory.tsx
rename to src/renderer/components/dialogs/DownloadUrlDialog.tsx
index acc2632ec..08d359e4a 100644
--- a/src/renderer/components/dialogs/components/CreateDirectory.tsx
+++ b/src/renderer/components/dialogs/DownloadUrlDialog.tsx
@@ -17,29 +17,31 @@
*/
import React, { useRef, useState } from 'react';
-import { styled } from '@mui/material/styles';
-import { useDispatch } from 'react-redux';
import { saveAs } from 'file-saver';
+import DialogContent from '@mui/material/DialogContent';
+import DialogTitle from '@mui/material/DialogTitle';
+import Dialog from '@mui/material/Dialog';
+import Paper from '@mui/material/Paper';
+import DraggablePaper from '-/components/DraggablePaper';
+import DialogCloseButton from '-/components/dialogs/DialogCloseButton';
+import { styled, useTheme } from '@mui/material/styles';
+import useMediaQuery from '@mui/material/useMediaQuery';
+import TargetPath from '-/components/dialogs/components/TargetPath';
+import { TargetPathContextProvider } from '-/components/dialogs/hooks/TargetPathContextProvider';
+import { useTranslation } from 'react-i18next';
+import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
-import ButtonGroup from '@mui/material/ButtonGroup';
-import Grid from '@mui/material/Grid';
+import DialogActions from '@mui/material/DialogActions';
import AppConfig from '-/AppConfig';
import { actions as AppActions, AppDispatch } from '-/reducers/app';
-import Tooltip from '-/components/Tooltip';
-import TextField from '@mui/material/TextField';
-import { useTargetPathContext } from '-/components/dialogs/hooks/useTargetPathContext';
-import Typography from '@mui/material/Typography';
-import { useTranslation } from 'react-i18next';
+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { useIOActionsContext } from '-/hooks/useIOActionsContext';
import { useNotificationContext } from '-/hooks/useNotificationContext';
-import { Pro } from '-/pro';
-import { ProLabel } from '-/components/HelperComponents';
-import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { useFileUploadDialogContext } from '-/components/dialogs/hooks/useFileUploadDialogContext';
-import { useCreateEditLocationDialogContext } from '-/components/dialogs/hooks/useCreateEditLocationDialogContext';
-import { useCreateDirectoryDialogContext } from '-/components/dialogs/hooks/useCreateDirectoryDialogContext';
-import { useNewAudioDialogContext } from '-/components/dialogs/hooks/useNewAudioDialogContext';
-import { useFileUploadContext } from '-/hooks/useFileUploadContext';
+import { useDispatch } from 'react-redux';
+import { useTargetPathContext } from '-/components/dialogs/hooks/useTargetPathContext';
+import { TS } from '-/tagspaces.namespace';
+import { useEditedEntryContext } from '-/hooks/useEditedEntryContext';
const PREFIX = 'CreateDirectory';
@@ -55,40 +57,26 @@ const Root = styled('div')(() => ({
}));
interface Props {
- onClose: () => void;
- tidPrefix?: string;
+ open: boolean;
+ onClose: (event?: Object, reason?: string) => void;
}
-function CreateDirectory(props: Props) {
- const { onClose, tidPrefix } = props;
+function DownloadUrlDialog(props: Props) {
+ const { open, onClose } = props;
const { t } = useTranslation();
- const { currentLocation } = useCurrentLocationContext();
+ const theme = useTheme();
+ const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
+ const { currentLocation, getFirstRWLocation } = useCurrentLocationContext();
+ const { setReflectActions } = useEditedEntryContext();
const { downloadFile } = useIOActionsContext();
const { showNotification } = useNotificationContext();
const { openFileUploadDialog } = useFileUploadDialogContext();
- const { openCreateEditLocationDialog } = useCreateEditLocationDialogContext();
- const { openCreateDirectoryDialog } = useCreateDirectoryDialogContext();
- const { openNewAudioDialog } = useNewAudioDialogContext();
- const { openFileUpload } = useFileUploadContext();
const dispatch: AppDispatch = useDispatch();
const { targetDirectoryPath } = useTargetPathContext();
const fileUrl = useRef<string>();
const [invalidURL, setInvalidURL] = useState<boolean>(false);
- const noSuitableLocation = !targetDirectoryPath;
-
- /*function loadLocation() {
- if (!currentDirectoryPath && firstRWLocation) {
- openLocation(firstRWLocation);
- }
- }*/
-
- function addFile() {
- openFileUpload(targetDirectoryPath);
- onClose();
- }
-
const onUploadProgress = (progress, abort, fileName) => {
dispatch(AppActions.onUploadProgress(progress, abort, fileName));
};
@@ -99,6 +87,7 @@ function CreateDirectory(props: Props) {
function downloadURL() {
if (fileUrl.current) {
+ const location = currentLocation ? currentLocation : getFirstRWLocation();
try {
const url = new URL(fileUrl.current);
if (invalidURL) {
@@ -125,7 +114,7 @@ function CreateDirectory(props: Props) {
} else if (fileName.indexOf('.') === -1) {
fileName = url.hostname + '-' + fileName + '.html';
}
- if (currentLocation?.haveObjectStoreSupport() || AppConfig.isElectron) {
+ if (!location.haveObjectStoreSupport() && AppConfig.isElectron) {
dispatch(AppActions.resetProgress());
openFileUploadDialog();
downloadFile(
@@ -133,11 +122,18 @@ function CreateDirectory(props: Props) {
targetDirectoryPath + '/' + decodeURIComponent(fileName),
onUploadProgress,
)
- .then(() => {
- if (currentLocation.haveObjectStoreSupport()) {
+ .then((entry) => {
+ /*if (location?.haveObjectStoreSupport()) {
// currently objectStore location in downloadFile use saveFilePromise and this function not have progress handling
dispatch(AppActions.setProgress(fileUrl.current, 100));
- }
+ }*/
+ const reflectAction: TS.EditAction = {
+ action: 'add',
+ entry: entry,
+ open: true,
+ source: 'upload',
+ };
+ setReflectActions(reflectAction);
})
.catch((e) => {
console.log('downloadFile error:', e);
@@ -161,108 +157,66 @@ function CreateDirectory(props: Props) {
}
}
- function tid(tid) {
- if (tidPrefix) {
- return tidPrefix + tid;
- }
- return tid;
- }
-
return (
<Root>
- <Grid item xs={12}>
- <Button
- variant="outlined"
- onClick={() => {
- onClose();
- openCreateEditLocationDialog();
- }}
- className={classes.createButton}
- data-tid={tid('createLocationButton')}
- >
- <Tooltip title={t('createLocationTitle')}>
- <Typography variant="button" display="block" gutterBottom>
- {t('core:createLocation')}
- </Typography>
- </Tooltip>
- </Button>
- </Grid>
- <Grid style={{ marginTop: 20 }} item xs={12}>
- <Button
- variant="outlined"
- onClick={() => {
- onClose();
- openCreateDirectoryDialog();
- }}
- className={classes.createButton}
- data-tid={tid('newSubDirTID')}
- disabled={noSuitableLocation}
+ <TargetPathContextProvider>
+ <Dialog
+ open={open}
+ onClose={onClose}
+ fullScreen={fullScreen}
+ keepMounted
+ aria-labelledby="draggable-dialog-title"
+ PaperComponent={fullScreen ? Paper : DraggablePaper}
+ scroll="paper"
>
- {t('core:newSubdirectory')}
- </Button>
- </Grid>
- <Grid style={{ marginTop: 20 }} item xs={12}>
- <Button
- variant="outlined"
- disabled={!Pro || noSuitableLocation}
- onClick={() => {
- onClose();
- openNewAudioDialog();
- }}
- className={classes.createButton}
- data-tid={tid('newSubDirTID')}
- >
- {t('core:newAudioRecording')}
- {!Pro && <ProLabel />}
- </Button>
- </Grid>
- <Grid style={{ marginTop: 20 }} item xs={12}>
- <Tooltip title={t('core:addFilesTitle')}>
- <Button
- variant="outlined"
- onClick={addFile}
- className={classes.createButton}
- data-tid={tid('addFilesButton')}
- disabled={noSuitableLocation}
- >
- {t('addFiles')}
- </Button>
- </Tooltip>
- </Grid>
- <Grid item xs={12}>
- <TextField
- error={invalidURL}
- label={t('core:url')}
- margin="dense"
- name="name"
- fullWidth={true}
- data-tid={tid('newUrlTID')}
- onKeyDown={(event) => {
- if (event.key === 'Enter') {
- downloadURL();
- }
- }}
- onChange={handleUrlChange}
- />
- </Grid>
- <Grid item xs={12}>
- <ButtonGroup
- style={{
- textAlign: 'center',
- width: '100%',
- }}
- >
- <Button
- data-tid={tid('downloadFileUrlTID')}
- className={classes.createButton}
- onClick={() => downloadURL()}
- >
+ <DialogTitle style={{ cursor: 'move' }} id="draggable-dialog-title">
{t('core:downloadFile')}
- </Button>
- </ButtonGroup>
- </Grid>
+ <DialogCloseButton
+ testId="closeCreateDialogTID"
+ onClose={() => onClose()}
+ />
+ </DialogTitle>
+ <DialogContent
+ style={{
+ minWidth: 200,
+ //minHeight: 300,
+ marginBottom: 20,
+ overflow: 'overlay',
+ }}
+ data-tid="downloadUrlDialogTID"
+ >
+ <TextField
+ error={invalidURL}
+ label={t('core:url')}
+ autoFocus
+ margin="dense"
+ name="name"
+ fullWidth={true}
+ data-tid="newUrlTID"
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ downloadURL();
+ }
+ }}
+ onChange={handleUrlChange}
+ />
+ <TargetPath />
+ </DialogContent>
+ <DialogActions>
+ <Button onClick={onClose}>{t('core:cancel')}</Button>
+ <Button
+ variant="contained"
+ data-tid={'downloadFileUrlTID'}
+ className={classes.createButton}
+ onClick={() => downloadURL()}
+ >
+ {t('core:ok')}
+ </Button>
+ </DialogActions>
+ </Dialog>
+ </TargetPathContextProvider>
</Root>
);
}
-export default CreateDirectory;
+export default DownloadUrlDialog;
diff --git a/src/renderer/components/dialogs/KeyboardDialog.tsx b/src/renderer/components/dialogs/KeyboardDialog.tsx
index 4585c5700..c52f03f97 100644
--- a/src/renderer/components/dialogs/KeyboardDialog.tsx
+++ b/src/renderer/components/dialogs/KeyboardDialog.tsx
@@ -35,8 +35,13 @@ import { useTranslation } from 'react-i18next';
import AppConfig from '-/AppConfig';
export function adjustKeyBinding(keyBinding: string) {
- if (!keyBinding || !keyBinding.length || keyBinding.length < 1) return '';
- let adjKB = keyBinding.toLowerCase();
+ if (!keyBinding || !keyBinding.length) return '';
+ let adjKB = '';
+ if (Array.isArray(keyBinding)) {
+ adjKB = keyBinding.join(', ');
+ } else {
+ adjKB = keyBinding?.toLowerCase();
+ }
if (AppConfig.isMacLike) {
adjKB = adjKB
.replaceAll('+', ' ')
diff --git a/src/renderer/components/dialogs/NewEntryDialog.tsx b/src/renderer/components/dialogs/NewEntryDialog.tsx
deleted file mode 100644
index a8e6dc265..000000000
--- a/src/renderer/components/dialogs/NewEntryDialog.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
-/!**
- * TagSpaces - universal file and folder organizer
- * Copyright (C) 2017-present TagSpaces GmbH
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License (version 3) as
- * published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- *
- *!/
-
-import React from 'react';
-import Typography from '@mui/material/Typography';
-import DialogContent from '@mui/material/DialogContent';
-import DialogTitle from '@mui/material/DialogTitle';
-import Dialog from '@mui/material/Dialog';
-import Paper from '@mui/material/Paper';
-import { Accordion, AccordionDetails, AccordionSummary } from '@mui/material';
-import DraggablePaper from '-/components/DraggablePaper';
-import DialogCloseButton from '-/components/dialogs/DialogCloseButton';
-import { useTheme } from '@mui/material/styles';
-import useMediaQuery from '@mui/material/useMediaQuery';
-import { ExpandIcon } from '-/components/CommonIcons';
-import CreateDirectory from '-/components/dialogs/components/CreateDirectory';
-import CreateFile from '-/components/dialogs/components/CreateFile';
-import TargetPath from '-/components/dialogs/components/TargetPath';
-import { TargetPathContextProvider } from '-/components/dialogs/hooks/TargetPathContextProvider';
-import { useTranslation } from 'react-i18next';
-
-interface Props {
- open: boolean;
- onClose: (event?: Object, reason?: string) => void;
-}
-
-function NewEntryDialog(props: Props) {
- const { open, onClose } = props;
- const { t } = useTranslation();
-
- const theme = useTheme();
- const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
- return (
- <TargetPathContextProvider>
- <Dialog
- open={open}
- onClose={onClose}
- fullScreen={fullScreen}
- keepMounted
- aria-labelledby="draggable-dialog-title"
- PaperComponent={fullScreen ? Paper : DraggablePaper}
- scroll="paper"
- >
- <DialogTitle style={{ cursor: 'move' }} id="draggable-dialog-title">
- {t('core:create') + '...'}
- <DialogCloseButton
- testId="closeCreateDialogTID"
- onClose={() => onClose()}
- />
- </DialogTitle>
- <DialogContent
- style={{
- minWidth: 200,
- minHeight: 300,
- marginBottom: 20,
- overflow: 'overlay',
- }}
- data-tid="newEntryDialog"
- >
- <Accordion style={{ marginTop: 5 }} defaultExpanded>
- <AccordionDetails style={{ paddingTop: 16 }}>
- <CreateFile onClose={onClose} tidPrefix="entry" />
- </AccordionDetails>
- </Accordion>
- <Accordion>
- <AccordionSummary
- expandIcon={<ExpandIcon />}
- aria-controls="panelGeneral-content"
- id="panelGeneral-header"
- >
- <Typography>{t('core:moreOperations')}</Typography>
- </AccordionSummary>
- <AccordionDetails>
- <CreateDirectory onClose={onClose} tidPrefix="entry" />
- </AccordionDetails>
- </Accordion>
- <TargetPath />
- </DialogContent>
- </Dialog>
- </TargetPathContextProvider>
- );
-}
-
-export default NewEntryDialog;
-*/
diff --git a/src/renderer/components/dialogs/NewFileDialog.tsx b/src/renderer/components/dialogs/NewFileDialog.tsx
index 10346d4cc..62d175ebb 100644
--- a/src/renderer/components/dialogs/NewFileDialog.tsx
+++ b/src/renderer/components/dialogs/NewFileDialog.tsx
@@ -94,7 +94,7 @@ function NewFileDialog(props: Props) {
if (fileType === 'url') {
return t('createLinkFile');
}
- return '...';
+ return t('newFileNote');
}
function loadLocation() {
diff --git a/src/renderer/components/dialogs/hooks/NewEntryDialogContextProvider.tsx b/src/renderer/components/dialogs/hooks/DownloadUrlDialogContextProvider.tsx
similarity index 58%
rename from src/renderer/components/dialogs/hooks/NewEntryDialogContextProvider.tsx
rename to src/renderer/components/dialogs/hooks/DownloadUrlDialogContextProvider.tsx
index 87846671c..c24b154e0 100644
--- a/src/renderer/components/dialogs/hooks/NewEntryDialogContextProvider.tsx
+++ b/src/renderer/components/dialogs/hooks/DownloadUrlDialogContextProvider.tsx
@@ -1,5 +1,4 @@
-/*
-/!**
+/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces GmbH
*
@@ -15,32 +14,33 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
- *!/
+ */
import React, { createContext, useMemo, useReducer, useRef } from 'react';
import LoadingLazy from '-/components/LoadingLazy';
-type NewEntryDialogContextData = {
- openNewEntryDialog: () => void;
- closeNewEntryDialog: () => void;
+type DownloadUrlContextData = {
+ openDownloadUrl: () => void;
+ closeDownloadUrl: () => void;
};
-export const NewEntryDialogContext = createContext<NewEntryDialogContextData>({
- openNewEntryDialog: undefined,
- closeNewEntryDialog: undefined,
+export const DownloadUrlDialogContext = createContext<DownloadUrlContextData>({
+ openDownloadUrl: undefined,
+ closeDownloadUrl: undefined,
});
-export type NewEntryDialogContextProviderProps = {
+export type DownloadUrlContextProviderProps = {
children: React.ReactNode;
};
-const NewEntryDialog = React.lazy(
- () => import(/!* webpackChunkName: "NewEntryDialog" *!/ '../NewEntryDialog'),
+const DownloadUrlDialog = React.lazy(
+ () =>
+ import(/* webpackChunkName: "DownloadUrlDialog" */ '../DownloadUrlDialog'),
);
-export const NewEntryDialogContextProvider = ({
+export const DownloadUrlContextProvider = ({
children,
-}: NewEntryDialogContextProviderProps) => {
+}: DownloadUrlContextProviderProps) => {
const open = useRef<boolean>(false);
const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);
@@ -55,33 +55,25 @@ export const NewEntryDialogContextProvider = ({
forceUpdate();
}
- function NewEntryDialogAsync(props) {
+ function DownloadUrlAsync(props) {
return (
<React.Suspense fallback={<LoadingLazy />}>
- <NewEntryDialog {...props} />
+ <DownloadUrlDialog {...props} />
</React.Suspense>
);
}
const context = useMemo(() => {
return {
- openNewEntryDialog: openDialog,
- closeNewEntryDialog: closeDialog,
+ openDownloadUrl: openDialog,
+ closeDownloadUrl: closeDialog,
};
}, []);
return (
- <NewEntryDialogContext.Provider value={context}>
- <NewEntryDialogAsync
- open={open.current}
- onClose={(event, reason) => {
- if (reason !== 'backdropClick') {
- closeDialog();
- }
- }}
- />
+ <DownloadUrlDialogContext.Provider value={context}>
+ <DownloadUrlAsync open={open.current} onClose={closeDialog} />
{children}
- </NewEntryDialogContext.Provider>
+ </DownloadUrlDialogContext.Provider>
);
};
-*/
diff --git a/src/renderer/components/dialogs/hooks/useDownloadUrlDialogContext.tsx b/src/renderer/components/dialogs/hooks/useDownloadUrlDialogContext.tsx
new file mode 100644
index 000000000..7741c8386
--- /dev/null
+++ b/src/renderer/components/dialogs/hooks/useDownloadUrlDialogContext.tsx
@@ -0,0 +1,6 @@
+import { useContext } from 'react';
+
+import { DownloadUrlDialogContext } from '-/components/dialogs/hooks/DownloadUrlDialogContextProvider';
+
+export const useDownloadUrlDialogContext = () =>
+ useContext(DownloadUrlDialogContext);
diff --git a/src/renderer/containers/DialogsRoot.tsx b/src/renderer/containers/DialogsRoot.tsx
index 4e4ef4ee2..9b4c5e2fa 100644
--- a/src/renderer/containers/DialogsRoot.tsx
+++ b/src/renderer/containers/DialogsRoot.tsx
@@ -36,6 +36,10 @@ import { SettingsDialogContextProvider } from '-/components/dialogs/hooks/Settin
import { DeleteMultipleEntriesDialogContextProvider } from '-/components/dialogs/hooks/DeleteMultipleEntriesDialogContextProvider';
import { ResolveConflictContextProvider } from '-/components/dialogs/hooks/ResolveConflictContextProvider';
import { FileUploadContextProvider } from '-/hooks/FileUploadContextProvider';
+import {
+ DownloadUrlContextProvider,
+ DownloadUrlDialogContext,
+} from '-/components/dialogs/hooks/DownloadUrlDialogContextProvider';
export type DialogsRootProps = {
children: React.ReactNode;
@@ -62,7 +66,9 @@ function DialogsRoot({ children }: DialogsRootProps) {
<ProTeaserDialogContextProvider>
<SettingsDialogContextProvider>
<ResolveConflictContextProvider>
- {children}
+ <DownloadUrlContextProvider>
+ {children}
+ </DownloadUrlContextProvider>
</ResolveConflictContextProvider>
</SettingsDialogContextProvider>
</ProTeaserDialogContextProvider>
diff --git a/src/renderer/hooks/IOActionsContextProvider.tsx b/src/renderer/hooks/IOActionsContextProvider.tsx
index ad9e3f400..bf2d99e56 100644
--- a/src/renderer/hooks/IOActionsContextProvider.tsx
+++ b/src/renderer/hooks/IOActionsContextProvider.tsx
@@ -281,7 +281,8 @@ export const IOActionsContextProvider = ({
const { setReflectKanBanActions } = useEditedKanBanMetaContext();
const { currentDirectoryPath, openDirectory, getAllPropertiesPromise } =
useDirectoryContentContext();
- const { currentLocation, findLocation } = useCurrentLocationContext();
+ const { currentLocation, findLocation, getFirstRWLocation } =
+ useCurrentLocationContext();
const { reflectUpdateSidecarMeta } = useLocationIndexContext();
const warningOpeningFilesExternally = useSelector(
getWarningOpeningFilesExternally,
@@ -770,8 +771,18 @@ export const IOActionsContextProvider = ({
});
}
+ function fetchUrl(url: string, targetPath: string, haveProgress: boolean) {
+ if (AppConfig.isElectron) {
+ return window.electronIO.ipcRenderer.invoke(
+ 'fetchUrl',
+ url,
+ targetPath,
+ haveProgress,
+ );
+ }
+ return fetch(url);
+ }
/**
- * S3 TODO deprecated fetch must be moved in main thread
* @param url
* @param targetPath
* @param onDownloadProgress
@@ -781,8 +792,13 @@ export const IOActionsContextProvider = ({
targetPath: string,
onDownloadProgress?: (progress, abort, fileName?) => void,
): Promise<TS.FileSystemEntry> {
- function saveFile(response: Response): Promise<TS.FileSystemEntry> {
- if (AppConfig.isElectron && !currentLocation.haveObjectStoreSupport()) {
+ const location = currentLocation || getFirstRWLocation();
+ function saveFile(response): Promise<TS.FileSystemEntry> {
+ if (response.filePath) {
+ //file is already saved
+ return location.getPropertiesPromise(response.filePath);
+ }
+ if (AppConfig.isElectron && !location.haveObjectStoreSupport()) {
return saveBinaryFilePromise(
{ path: targetPath },
response.body,
@@ -794,15 +810,15 @@ export const IOActionsContextProvider = ({
return saveFilePromise({ path: targetPath }, arrayBuffer, true);
});
}
- return fetch(url)
+ return fetchUrl(url, targetPath, onDownloadProgress !== undefined)
.then((response) => saveFile(response))
.then((fsEntry: TS.FileSystemEntry) => {
return generateThumbnailPromise(
- currentLocation.haveObjectStoreSupport() ? url : fsEntry.path,
+ location.haveObjectStoreSupport() ? url : fsEntry.path,
fsEntry.size,
- currentLocation.loadTextFilePromise,
- currentLocation.getFileContentPromise,
- currentLocation?.getDirSeparator(),
+ location.loadTextFilePromise,
+ location.getFileContentPromise,
+ location?.getDirSeparator(),
).then((dataURL) => {
if (dataURL && dataURL.length > 6) {
const baseString = dataURL.split(',').pop();
@@ -811,14 +827,14 @@ export const IOActionsContextProvider = ({
{
path: getThumbFileLocationForFile(
targetPath,
- currentLocation?.getDirSeparator(),
+ location?.getDirSeparator(),
false,
),
},
fileContent,
true,
).then((thumb: TS.FileSystemEntry) =>
- currentLocation.getThumbPath(thumb.path).then((thumbPath) => ({
+ location.getThumbPath(thumb.path).then((thumbPath) => ({
...fsEntry,
thumbPath: thumbPath,
})),
diff --git a/src/renderer/hooks/OpenedEntryContextProvider.tsx b/src/renderer/hooks/OpenedEntryContextProvider.tsx
index 96896ec01..1be137a1f 100644
--- a/src/renderer/hooks/OpenedEntryContextProvider.tsx
+++ b/src/renderer/hooks/OpenedEntryContextProvider.tsx
@@ -582,11 +582,11 @@ export const OpenedEntryContextProvider = ({
}
entryForOpening = findExtensionsForEntry(fsEntry, supportedFileTypes);
const loc = findLocation(fsEntry.locationID);
- if (loc.haveObjectStoreSupport() || loc.haveWebDavSupport()) {
+ if (loc?.haveObjectStoreSupport() || loc?.haveWebDavSupport()) {
const cleanedPath = fsEntry.path.startsWith('/')
? fsEntry.path.substr(1)
: fsEntry.path;
- entryForOpening.url = await loc.getURLforPathInt(cleanedPath);
+ entryForOpening.url = await loc?.getURLforPathInt(cleanedPath);
} else if (fsEntry.url) {
entryForOpening.url = fsEntry.url;
}
diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.json
index 4778ddbb8..25ee02ac0 100644
--- a/src/renderer/locales/en/core.json
+++ b/src/renderer/locales/en/core.json
@@ -274,7 +274,7 @@
"createRichTextFile": "New HTML File",
"createLinkFile": "New Link File",
"createDirectory": "New Folder",
- "addFiles": "Add Files",
+ "addFiles": "New From Device",
"addFilesTitle": "Add or upload files from your computer.",
"exitApp": "Exit",
"closeWin": "Close Window",
@@ -862,7 +862,8 @@
"createNew": "Create New",
"fileContent": "File Content",
"linkURL": "URL",
- "urlValidationHelp": "not valid URL",
+ "urlValidationHelp": "Invalid URL",
"openSharingLink": "Open sharing links created with the TagSpaces (ts:// links)",
+ "newFromDownloadURL": "New From URL",
"-": "-"
}
diff --git a/src/renderer/services/search-index.ts b/src/renderer/services/search-index.ts
deleted file mode 100644
index 1fa9a5ce0..000000000
--- a/src/renderer/services/search-index.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
-/!**
- * TagSpaces - universal file and folder organizer
- * Copyright (C) 2020-present TagSpaces GmbH
- *
- * 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 {
- extractFileName,
- extractFileExtension,
- extractTagsAsObjects
-} from '@tagspaces/tagspaces-common/paths';
-import { TS } from '-/tagspaces.namespace';
-import PlatformIO from '-/services/platform-facade';
-import AppConfig from '-/AppConfig';
-
-const GlobalSearch = (function() {
- let instance;
-
- function init() {
- // DateCreated for index
- let indexLoadedOn: number = undefined;
- let index = [];
- //let results = [];
-
- return {
- setIndexLoadedOn: function(loaded) {
- indexLoadedOn = loaded;
- },
- getIndexLoadedOn: () => indexLoadedOn,
- setIndex: function(i) {
- index = i;
- },
- getIndex: () => index,
- /!*setResults: function(r) {
- results = r;
- },
- getResults: () => results,*!/
- reflectDeleteEntry: (path: string) => {
- if (!index || index.length < 1) {
- return;
- }
- for (let i = 0; i < index.length; i += 1) {
- if (index[i].path === path) {
- index = index.splice(i, 1);
- i -= 1;
- }
- }
- },
- reflectDeleteEntries: (paths: string[]) => {
- if (!index || index.length < 1) {
- return;
- }
- for (let i = 0; i < index.length; i += 1) {
- if (paths.some(path => index[i].path === path)) {
- index = index.splice(i, 1);
- i -= 1;
- }
- }
- },
- reflectCreateEntry: (newEntry: TS.FileSystemEntry) => {
- if (!index || index.length < 1) {
- return;
- }
- let entryFound = index.some(entry => entry.path === newEntry.path);
- if (!entryFound) {
- index = [...index, newEntry];
- }
- // else todo update index entry ?
- },
- reflectRenameEntry: (path: string, newPath: string) => {
- if (!index || index.length < 1) {
- return;
- }
- for (let i = 0; i < index.length; i += 1) {
- if (index[i].path === path) {
- index[i].path = newPath;
- index[i].name = extractFileName(
- newPath,
- PlatformIO.getDirSeparator()
- );
- index[i].extension = extractFileExtension(
- newPath,
- PlatformIO.getDirSeparator()
- );
- index[i].tags = [
- ...index[i].tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags
- ...extractTagsAsObjects(
- newPath,
- AppConfig.tagDelimiter,
- PlatformIO.getDirSeparator()
- )
- ];
- }
- }
- },
- reflectUpdateSidecarTags: (path: string, tags: Array<TS.Tag>) => {
- if (!index || index.length < 1) {
- return;
- }
- for (let i = 0; i < index.length; i += 1) {
- if (index[i].path === path) {
- index[i].tags = [
- ...index[i].tags.filter(tag => tag.type === 'plain'),
- ...tags
- ];
- }
- }
- },
- reflectUpdateSidecarMeta: (path: string, entryMeta: Object) => {
- if (!index || index.length < 1) {
- return;
- }
- for (let i = 0; i < index.length; i += 1) {
- if (index[i].path === path) {
- index[i] = {
- ...index[i],
- ...entryMeta
- };
- }
- }
- }
- };
- }
-
- return {
- // get the singleton instance if it exists, or create one if it doesn't
- getInstance: function() {
- if (!instance) {
- instance = init();
- }
- return instance;
- }
- };
-})();
-export default GlobalSearch;
-*/