mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-03 23:32:22 -08:00
fix(mobile): save downloaded media (#1445)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description fix download on ios and android <!-- Please include a summary of the change. Please also include relevant motivation and context. List any dependencies that are required for this change. --> Fixes #1439 #### Type of change - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [x] My code follows the style guidelines of this project - [x] I have performed a self-review of my own code - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. -->
This commit is contained in:
12 files changed
+222
-20
No files matched your search
@@ -42,6 +42,7 @@ src-tauri/target/
|
||||
src-tauri/gen/android/app/build/
|
||||
# Tauri Apple outputs
|
||||
src-tauri/gen/apple/*
|
||||
!src-tauri/gen/apple/PrivacyInfo.xcprivacy
|
||||
# Tauri Android release keystore
|
||||
*.jks
|
||||
|
||||
|
||||
@@ -57,6 +57,8 @@
|
||||
"@tauri-apps/api": "2.11.1",
|
||||
"@tauri-apps/plugin-clipboard-manager": "2.3.2",
|
||||
"@tauri-apps/plugin-deep-link": "2.4.9",
|
||||
"@tauri-apps/plugin-dialog": "2.7.1",
|
||||
"@tauri-apps/plugin-fs": "2.5.1",
|
||||
"@tauri-apps/plugin-http": "2.5.9",
|
||||
"@tauri-apps/plugin-opener": "2.5.4",
|
||||
"@tauri-apps/plugin-os": "2.3.2",
|
||||
|
||||
Generated
+20
@@ -76,6 +76,12 @@ importers:
|
||||
'@tauri-apps/plugin-deep-link':
|
||||
specifier: 2.4.9
|
||||
version: 2.4.9
|
||||
'@tauri-apps/plugin-dialog':
|
||||
specifier: 2.7.1
|
||||
version: 2.7.1
|
||||
'@tauri-apps/plugin-fs':
|
||||
specifier: 2.5.1
|
||||
version: 2.5.1
|
||||
'@tauri-apps/plugin-http':
|
||||
specifier: 2.5.9
|
||||
version: 2.5.9
|
||||
@@ -3009,6 +3015,12 @@ packages:
|
||||
'@tauri-apps/[email protected]':
|
||||
resolution: {integrity: sha512-u0SKOUHnJ1wqeqXsDFq2+kASCBj9xxbG0g9XZWPy9SOmU4wXtp6b/wiYpm6oH6/5fBTQsLqnLhIvqLBRpgHJlA==}
|
||||
|
||||
'@tauri-apps/[email protected]':
|
||||
resolution: {integrity: sha512-OK1UBXYt+ojcmxMktzzuyonYIFta8CmAASpX+CA+DTGK24KlHjhYI6x2iOJ/TjZF4N7/ACK1oFmEOjIY9IhzOQ==}
|
||||
|
||||
'@tauri-apps/[email protected]':
|
||||
resolution: {integrity: sha512-9Lz+Jopp6QyeEWhlpkMx4R/+P9HgR+AVAI4vOZhlT8Xaymtz8iVI/Ov984/XTqgJz/5gz5NretqPB/XEMS3NhQ==}
|
||||
|
||||
'@tauri-apps/[email protected]':
|
||||
resolution: {integrity: sha512-lCiY0+vs4HvIUSvZrBs8TC3TiCB0MOPRmiUjTq4prW7SlcJE2jdLeT6KBsJrT9Tlplufl7W1pY6SFAO3gCWxDA==}
|
||||
|
||||
@@ -8039,6 +8051,14 @@ snapshots:
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.11.1
|
||||
|
||||
'@tauri-apps/[email protected]':
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.11.1
|
||||
|
||||
'@tauri-apps/[email protected]':
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.11.1
|
||||
|
||||
'@tauri-apps/[email protected]':
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.11.1
|
||||
|
||||
Generated
+1
@@ -5381,6 +5381,7 @@ dependencies = [
|
||||
"tauri-plugin-devtools",
|
||||
"tauri-plugin-dialog",
|
||||
"tauri-plugin-edge-to-edge",
|
||||
"tauri-plugin-fs",
|
||||
"tauri-plugin-global-shortcut",
|
||||
"tauri-plugin-http",
|
||||
"tauri-plugin-log",
|
||||
|
||||
@@ -64,6 +64,7 @@ tauri-plugin-deep-link = "2.4.9"
|
||||
tauri-plugin-http = "2.5.9"
|
||||
tauri-plugin-store = "2.4.4"
|
||||
tauri-plugin-clipboard-manager = "2.3.2"
|
||||
tauri-plugin-dialog = "2"
|
||||
|
||||
# Debug-only in practice: only initialized under #[cfg(debug_assertions)] in
|
||||
# lib.rs, so the release build never calls into it.
|
||||
@@ -98,7 +99,6 @@ tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugi
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
tauri-plugin-updater = { version = "2", optional = true }
|
||||
tauri-plugin-process = "2"
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-window-state = "2.4.1"
|
||||
tauri-plugin-global-shortcut = "2"
|
||||
regex = "1"
|
||||
@@ -128,6 +128,7 @@ tauri-plugin-sharekit = { git = "https://github.com/Choochmeque/tauri-plugin-sha
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
objc2 = "0.6"
|
||||
objc2-foundation = { version = "0.3", features = ["NSFileManager", "NSString", "NSURL"] }
|
||||
tauri-plugin-fs = "2"
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
tauri-plugin-android-fs = { version = "=28.4.0", features = ["legacy-storage-permission"] }
|
||||
|
||||
@@ -4,8 +4,12 @@
|
||||
"platforms": ["android"],
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"android-fs:allow-check-public-files-permission",
|
||||
"android-fs:allow-create-new-public-file",
|
||||
"android-fs:allow-request-public-files-permission",
|
||||
"android-fs:allow-write-file",
|
||||
"android-fs:allow-set-public-file-pending"
|
||||
"android-fs:allow-set-public-file-pending",
|
||||
"android-fs:allow-scan-public-file",
|
||||
"android-fs:allow-remove-file"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/mobile-schema.json",
|
||||
"identifier": "ios-capability",
|
||||
"platforms": ["iOS"],
|
||||
"windows": ["main"],
|
||||
"permissions": ["dialog:allow-save", "fs:allow-write-file"]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<string>C617.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -80,6 +80,8 @@ targets:
|
||||
{{~#each ios-additional-targets}}
|
||||
- path: {{prefix-path this}}{{/each}}
|
||||
- path: LaunchScreen.storyboard
|
||||
- path: PrivacyInfo.xcprivacy
|
||||
buildPhase: resources
|
||||
# UNNotificationSound resolves names from the bundle root, not tauri's assets/ dir.
|
||||
- path: ../../resources/notification.caf
|
||||
buildPhase: resources
|
||||
|
||||
@@ -343,6 +343,11 @@ pub fn run() {
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.plugin(tauri_plugin_dialog::init());
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
let builder = builder
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_fs::init());
|
||||
|
||||
#[cfg(mobile)]
|
||||
let builder = builder
|
||||
.plugin(tauri_plugin_edge_to_edge::init())
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import FileSaver from 'file-saver';
|
||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
import { showToast } from '$state/toast';
|
||||
import { saveFileToDevice } from './download';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
androidFs: {
|
||||
checkPublicFilesPermission: vi.fn<() => Promise<boolean>>(),
|
||||
requestPublicFilesPermission: vi.fn<() => Promise<boolean>>(),
|
||||
createNewPublicFile: vi.fn<() => Promise<string>>(),
|
||||
writeFile: vi.fn<() => Promise<void>>(),
|
||||
setPublicFilePending: vi.fn<() => Promise<void>>(),
|
||||
scanPublicFile: vi.fn<() => Promise<void>>(),
|
||||
removeFile: vi.fn<() => Promise<void>>(),
|
||||
},
|
||||
save: vi.fn<(options?: { defaultPath?: string }) => Promise<string | null>>(),
|
||||
writeFile: vi.fn<(path: string | URL, data: Uint8Array) => Promise<void>>(),
|
||||
saveAs: vi.fn<(data: Blob | string, filename?: string) => void>(),
|
||||
invoke: vi.fn<(cmd: string, args?: Record<string, unknown>) => Promise<unknown>>(),
|
||||
isTauri: vi.fn<() => boolean>(),
|
||||
osType: vi.fn<() => string>(),
|
||||
showToast: vi.fn<(text: string, durationMs?: number) => void>(),
|
||||
}));
|
||||
const { androidFs, save, writeFile } = mocks;
|
||||
|
||||
vi.mock('file-saver', () => ({ default: { saveAs: mocks.saveAs } }));
|
||||
vi.mock('@tauri-apps/api/core', () => ({
|
||||
invoke: mocks.invoke,
|
||||
isTauri: mocks.isTauri,
|
||||
}));
|
||||
vi.mock('@tauri-apps/plugin-os', () => ({ type: mocks.osType }));
|
||||
vi.mock('$state/toast', () => ({ showToast: mocks.showToast }));
|
||||
vi.mock('tauri-plugin-android-fs-api', () => ({
|
||||
AndroidFs: mocks.androidFs,
|
||||
AndroidPublicGeneralPurposeDir: { Download: 'Download' },
|
||||
}));
|
||||
vi.mock('@tauri-apps/plugin-dialog', () => ({ save: mocks.save }));
|
||||
vi.mock('@tauri-apps/plugin-fs', () => ({ writeFile: mocks.writeFile }));
|
||||
|
||||
describe('saveFileToDevice', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(isTauri).mockReturnValue(true);
|
||||
vi.mocked(osType).mockReturnValue('android');
|
||||
vi.mocked(invoke).mockResolvedValue(true);
|
||||
androidFs.checkPublicFilesPermission.mockResolvedValue(true);
|
||||
androidFs.requestPublicFilesPermission.mockResolvedValue(true);
|
||||
androidFs.createNewPublicFile.mockResolvedValue('content://download/file');
|
||||
androidFs.writeFile.mockResolvedValue(undefined);
|
||||
androidFs.setPublicFilePending.mockResolvedValue(undefined);
|
||||
androidFs.scanPublicFile.mockResolvedValue(undefined);
|
||||
androidFs.removeFile.mockResolvedValue(undefined);
|
||||
save.mockResolvedValue(null);
|
||||
writeFile.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('scans an Android Downloads file after making it public', async () => {
|
||||
await saveFileToDevice(new Blob(['data'], { type: 'text/plain' }), 'file.txt');
|
||||
|
||||
expect(androidFs.createNewPublicFile).toHaveBeenCalledWith(
|
||||
'Download',
|
||||
'file.txt',
|
||||
'text/plain',
|
||||
{ isPending: true, requestPermission: true }
|
||||
);
|
||||
expect(androidFs.setPublicFilePending).toHaveBeenCalledWith('content://download/file', false);
|
||||
expect(androidFs.scanPublicFile).toHaveBeenCalledWith('content://download/file');
|
||||
expect(showToast).toHaveBeenCalledWith('Saved to Downloads');
|
||||
});
|
||||
|
||||
it('cleans up an Android file and shows an error toast when writing fails', async () => {
|
||||
const error = new Error('write failed');
|
||||
androidFs.writeFile.mockRejectedValue(error);
|
||||
|
||||
await saveFileToDevice(new Blob(['data']), 'file.txt');
|
||||
|
||||
expect(androidFs.removeFile).toHaveBeenCalledWith('content://download/file');
|
||||
expect(showToast).toHaveBeenCalledWith('Failed to save file: write failed');
|
||||
});
|
||||
|
||||
it('does not write or toast when the iOS save picker is cancelled', async () => {
|
||||
vi.mocked(osType).mockReturnValue('ios');
|
||||
|
||||
await saveFileToDevice(new Blob(['data']), 'file.txt');
|
||||
|
||||
expect(save).toHaveBeenCalledWith({ defaultPath: 'file.txt' });
|
||||
expect(writeFile).not.toHaveBeenCalled();
|
||||
expect(showToast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('writes the selected iOS path and shows the success toast', async () => {
|
||||
vi.mocked(osType).mockReturnValue('ios');
|
||||
save.mockResolvedValue('file:///exports/file.txt');
|
||||
|
||||
await saveFileToDevice(new Blob(['data']), 'file.txt');
|
||||
|
||||
expect(writeFile).toHaveBeenCalledWith('file:///exports/file.txt', expect.any(Uint8Array));
|
||||
expect(showToast).toHaveBeenCalledWith('File saved');
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps browser downloads on FileSaver', async () => {
|
||||
vi.mocked(isTauri).mockReturnValue(false);
|
||||
|
||||
await saveFileToDevice(new Blob(['data']), 'file.txt');
|
||||
|
||||
expect(FileSaver.saveAs).toHaveBeenCalledWith(expect.any(Blob), 'file.txt');
|
||||
});
|
||||
});
|
||||
+46
-18
@@ -63,26 +63,54 @@ export async function saveFileToDevice(
|
||||
mimeType?: string
|
||||
): Promise<void> {
|
||||
if (isTauri()) {
|
||||
const blob = await resolveBlob(input);
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
try {
|
||||
const blob = await resolveBlob(input);
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
|
||||
if (osType() === 'android') {
|
||||
const { AndroidFs, AndroidPublicGeneralPurposeDir } =
|
||||
await import('tauri-plugin-android-fs-api');
|
||||
const uri = await AndroidFs.createNewPublicFile(
|
||||
AndroidPublicGeneralPurposeDir.Download,
|
||||
filename,
|
||||
mimeType || blob.type || null,
|
||||
{ isPending: true }
|
||||
);
|
||||
await AndroidFs.writeFile(uri, bytes);
|
||||
await AndroidFs.setPublicFilePending(uri, false);
|
||||
showToast('Saved to Downloads');
|
||||
return;
|
||||
if (osType() === 'android') {
|
||||
const { AndroidFs, AndroidPublicGeneralPurposeDir } =
|
||||
await import('tauri-plugin-android-fs-api');
|
||||
let uri: Awaited<ReturnType<typeof AndroidFs.createNewPublicFile>> | undefined;
|
||||
try {
|
||||
if (!(await AndroidFs.checkPublicFilesPermission())) {
|
||||
const granted = await AndroidFs.requestPublicFilesPermission();
|
||||
if (!granted) throw new Error('Storage permission was denied');
|
||||
}
|
||||
|
||||
uri = await AndroidFs.createNewPublicFile(
|
||||
AndroidPublicGeneralPurposeDir.Download,
|
||||
filename,
|
||||
mimeType || blob.type || null,
|
||||
{ isPending: true, requestPermission: true }
|
||||
);
|
||||
await AndroidFs.writeFile(uri, bytes);
|
||||
await AndroidFs.setPublicFilePending(uri, false);
|
||||
await AndroidFs.scanPublicFile(uri);
|
||||
showToast('Saved to Downloads');
|
||||
return;
|
||||
} catch (error) {
|
||||
if (uri) await AndroidFs.removeFile(uri).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (osType() === 'ios') {
|
||||
const { save } = await import('@tauri-apps/plugin-dialog');
|
||||
const path = await save({ defaultPath: filename });
|
||||
if (!path) return;
|
||||
|
||||
const { writeFile } = await import('@tauri-apps/plugin-fs');
|
||||
await writeFile(path, bytes);
|
||||
showToast('File saved');
|
||||
return;
|
||||
}
|
||||
|
||||
const saved = await invoke<boolean>('save_download', { filename, bytes: Array.from(bytes) });
|
||||
if (saved) showToast('File saved');
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'unknown error';
|
||||
showToast(`Failed to save file: ${message}`);
|
||||
}
|
||||
|
||||
const saved = await invoke<boolean>('save_download', { filename, bytes: Array.from(bytes) });
|
||||
if (saved) showToast('File saved');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user