Skip to content

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

fix: downloading files on capacitor

Ilian Sapundshiev36c5c5324b99
diff --git a/src/renderer/hooks/IOActionsContextProvider.tsx b/src/renderer/hooks/IOActionsContextProvider.tsx
index 32f043ee6..0a88c3c2f 100644
--- a/src/renderer/hooks/IOActionsContextProvider.tsx
+++ b/src/renderer/hooks/IOActionsContextProvider.tsx
@@ -1022,44 +1022,53 @@ export const IOActionsContextProvider = ({
function downloadFsEntry(fsEntry: TS.FileSystemEntry) {
const loc = findLocation(fsEntry.locationID);
- if (loc) {
- if (fsEntry.isEncrypted) {
- loc
- .getFileContentPromise(fsEntry.path, 'arraybuffer')
- .then((arrayBuffer) => {
- const url = window.URL || window.webkitURL;
- const openedEntryUrl = url.createObjectURL(new Blob([arrayBuffer]));
- const downloadResult = downloadFile(
- fsEntry.path,
- openedEntryUrl,
- currentLocation?.getDirSeparator(),
+ if (!loc) {
+ return;
+ }
+
+ // Resolve the URL to download from, depending on the entry/location type.
+ let urlPromise: Promise<string>;
+ if (fsEntry.isEncrypted) {
+ urlPromise = loc
+ .getFileContentPromise(fsEntry.path, 'arraybuffer')
+ .then((arrayBuffer) => {
+ const url = window.URL || window.webkitURL;
+ return url.createObjectURL(new Blob([arrayBuffer]));
+ });
+ } else if (loc.haveObjectStoreSupport()) {
+ urlPromise = loc.generateURLforPath(fsEntry.path, 86400);
+ } else {
+ urlPromise = Promise.resolve(fsEntry.url);
+ }
+
+ const fileName = extractFileName(
+ fsEntry.path,
+ currentLocation?.getDirSeparator(),
+ );
+
+ urlPromise.then((url) => {
+ const downloadResult = downloadFile(
+ fsEntry.path,
+ url,
+ currentLocation?.getDirSeparator(),
+ );
+ if (downloadResult === -1) {
+ showNotification(t('core:cantDownloadLocalFile'));
+ } else if (downloadResult instanceof Promise) {
+ // Native mobile (Capacitor): confirm start, then success/failure.
+ showNotification(t('core:downloadStarted', { fileName }));
+ downloadResult
+ .then(() => {
+ showNotification(t('core:downloadSuccessful', { fileName }));
+ return true;
+ })
+ .catch((e) => {
+ showNotification(
+ t('core:downloadFileError', { message: e.message }),
);
- if (downloadResult === -1) {
- showNotification(t('core:cantDownloadLocalFile'));
- }
});
- } else if (loc.haveObjectStoreSupport()) {
- loc.generateURLforPath(fsEntry.path, 86400).then((url) => {
- const downloadResult = downloadFile(
- fsEntry.path,
- url,
- currentLocation?.getDirSeparator(),
- );
- if (downloadResult === -1) {
- showNotification(t('core:cantDownloadLocalFile'));
- }
- });
- } else {
- const downloadResult = downloadFile(
- fsEntry.path,
- fsEntry.url,
- currentLocation?.getDirSeparator(),
- );
- if (downloadResult === -1) {
- showNotification(t('core:cantDownloadLocalFile'));
- }
}
- }
+ });
}
/**
* with HTML5 Files API
diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.json
index 62b7482bb..4951063e6 100644
--- a/src/renderer/locales/en/core.json
+++ b/src/renderer/locales/en/core.json
@@ -208,6 +208,8 @@
"openFileWith": "Open with…",
"downloadFile": "Download File",
"downloadFiles": "Download Files",
+ "downloadStarted": "Downloading {{fileName}}…",
+ "downloadSuccessful": "{{fileName}} downloaded",
"openFileNatively": "Open File Natively",
"openParentFolder": "Open Parent Folder",
"showInFileManager": "Show in File Manager",
diff --git a/src/renderer/services/io-capacitor.ts b/src/renderer/services/io-capacitor.ts
index 3b08c0644..9ad1eefa8 100644
--- a/src/renderer/services/io-capacitor.ts
+++ b/src/renderer/services/io-capacitor.ts
@@ -1183,6 +1183,78 @@ function shareFiles(files) {
});
}
+/**
+ * Download a file under Capacitor. Replaces the Cordova-only
+ * `window.plugins.Downloader`, which is undefined under Capacitor.
+ *
+ * Fetches the URL inside the WebView (handles blob:/data: object URLs used for
+ * encrypted files, signed S3 URLs, and plain http(s)), then writes the bytes
+ * via @capacitor/filesystem.
+ *
+ * - Android: saves directly to the public `Download/` folder.
+ * - iOS: there is no public Downloads folder. We write the file to the app's
+ * Cache directory and present the native share sheet so the user can pick a
+ * destination ("Save to Files", AirDrop, etc.) instead of it disappearing
+ * into the sandboxed app folder.
+ *
+ * Resolves with the result path (and, on iOS, whether the share sheet was
+ * shown), or rejects on a fetch/write failure so the caller can notify.
+ */
+function downloadFile(fileName, fileUrl) {
+ const platform = Capacitor.getPlatform();
+
+ return fetch(fileUrl)
+ .then((response) => {
+ if (!response.ok) {
+ throw new Error('HTTP ' + response.status);
+ }
+ return response.blob();
+ })
+ .then((blob) => blobToBase64(blob))
+ .then((base64Data) => {
+ if (platform === 'ios') {
+ // Stage in the cache dir, then let the user choose where to save it.
+ return Filesystem.writeFile({
+ path: fileName,
+ data: base64Data,
+ directory: Directory.Cache,
+ recursive: true,
+ }).then((result) =>
+ Share.share({
+ title: fileName,
+ url: result.uri,
+ dialogTitle: 'Save or share file',
+ })
+ .then(() => ({ path: result.uri, shared: true }))
+ .catch((err) => {
+ // User cancelling the share sheet rejects — treat as a no-op,
+ // the file is still in the cache dir at result.uri.
+ console.log('Share sheet dismissed: ' + err);
+ return { path: result.uri, shared: false };
+ }),
+ );
+ }
+ // Android: write straight into the public Downloads folder.
+ return Filesystem.writeFile({
+ path: 'Download/' + fileName,
+ data: base64Data,
+ directory: Directory.ExternalStorage,
+ recursive: true,
+ }).then((result) => ({
+ path: result.uri || 'Download/' + fileName,
+ shared: false,
+ }));
+ })
+ .then((result) => {
+ console.log('File downloaded to: ' + result.path);
+ return result;
+ })
+ .catch((err) => {
+ console.error('Capacitor downloadFile failed: ' + err);
+ throw err;
+ });
+}
+
// --- Auto-initialization ---
// In Capacitor, the native bridge is ready immediately when JS executes
// (unlike Cordova which requires waiting for the 'deviceready' event).
@@ -1245,4 +1317,5 @@ export {
openUrl,
focusWindow,
shareFiles,
+ downloadFile,
};
diff --git a/src/renderer/services/utils-io.ts b/src/renderer/services/utils-io.ts
index c9de55a74..47b6fb58d 100644
--- a/src/renderer/services/utils-io.ts
+++ b/src/renderer/services/utils-io.ts
@@ -1210,10 +1210,20 @@ export function downloadFile(
filePath: string,
fileUrl: string,
dirSeparator: string,
-): number {
+): number | Promise<{ path: string; shared: boolean }> {
const entryName = `${baseName(filePath, dirSeparator)}`;
const fileName = extractFileName(entryName, dirSeparator);
+ if (AppConfig.isCapacitor) {
+ if (!fileUrl) {
+ console.log('Can only download HTTP/HTTPS URIs');
+ return -1;
+ }
+ const ioAPI = require('-/services/io-capacitor');
+ // Returns a promise so the caller can confirm start/completion to the user.
+ return ioAPI.downloadFile(fileName, fileUrl);
+ }
+
if (AppConfig.isNativeMobile) {
if (fileUrl) {
const downloadCordova = (uri, filename) => {