mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 17:11:17 -08:00
Revert "fix(android): retry a media save when MediaStore runs out of unique names"
This commit is contained in:
1 parent
8b11ac623e
commit
44d2270bad
2 files changed
+28
-132
No files matched your search
@@ -24,7 +24,6 @@ const mocks = vi.hoisted(() => ({
|
||||
osType: vi.fn<() => string>(),
|
||||
showToast: vi.fn<(text: string, durationMs?: number) => void>(),
|
||||
fetchMediaBlob: vi.fn<(input: string) => Promise<Blob>>(),
|
||||
captureException: vi.fn<(error: unknown, context?: unknown) => void>(),
|
||||
}));
|
||||
const { androidFs, save, writeFile } = mocks;
|
||||
|
||||
@@ -34,7 +33,6 @@ vi.mock('@tauri-apps/api/core', () => ({
|
||||
isTauri: mocks.isTauri,
|
||||
}));
|
||||
vi.mock('@tauri-apps/plugin-os', () => ({ type: mocks.osType }));
|
||||
vi.mock('@sentry/react', () => ({ captureException: mocks.captureException }));
|
||||
vi.mock('$state/toast', () => ({ showToast: mocks.showToast }));
|
||||
vi.mock('$utils/mediaTransport', () => ({ fetchMediaBlob: mocks.fetchMediaBlob }));
|
||||
vi.mock('tauri-plugin-android-fs-api', () => ({
|
||||
@@ -81,57 +79,6 @@ describe('saveFileToDevice', () => {
|
||||
expect(showToast).toHaveBeenCalledWith('Saved to Downloads');
|
||||
});
|
||||
|
||||
// MediaStore resolves the final name when the pending flag is cleared, so the
|
||||
// 32-name wall is hit after the bytes are written, not on create.
|
||||
const uniqueFileError = new Error(
|
||||
'Failed to build unique file: /storage/emulated/0/Download/Screenshot 2026-08-13 at 20.07.50.png' +
|
||||
' _display_name=Screenshot 2026-08-13 at 20.07.50.png mime_type=image/png' +
|
||||
' _data=/storage/emulated/0/Download/Screenshot 2026-08-13 at 20.07.50.png relative_path=Download/'
|
||||
);
|
||||
|
||||
it('retries the whole save under a unique name when clearing the pending flag fails', async () => {
|
||||
androidFs.setPublicFilePending.mockRejectedValueOnce(uniqueFileError);
|
||||
|
||||
const result = await saveFileToDevice(
|
||||
new Blob(['data'], { type: 'image/png' }),
|
||||
'Screenshot 2026-08-13 at 20.07.50.png'
|
||||
);
|
||||
|
||||
expect(result).toBe('saved');
|
||||
expect(androidFs.createNewPublicFile).toHaveBeenCalledTimes(2);
|
||||
expect(androidFs.createNewPublicFile).toHaveBeenLastCalledWith(
|
||||
'Download',
|
||||
expect.stringMatching(/^Screenshot 2026-08-13 at 20\.07\.50-\d+\.png$/),
|
||||
'image/png',
|
||||
{ isPending: true, requestPermission: true }
|
||||
);
|
||||
expect(androidFs.removeFile).toHaveBeenCalledWith('content://download/file');
|
||||
expect(showToast).toHaveBeenCalledWith('Saved to Downloads');
|
||||
});
|
||||
|
||||
it('reports a scrubbed error to Sentry when the unique-name retry also fails', async () => {
|
||||
androidFs.setPublicFilePending.mockRejectedValue(uniqueFileError);
|
||||
|
||||
const result = await saveFileToDevice(
|
||||
new Blob(['data'], { type: 'image/png' }),
|
||||
'Screenshot 2026-08-13 at 20.07.50.png'
|
||||
);
|
||||
|
||||
expect(result).toBe('failed');
|
||||
expect(androidFs.createNewPublicFile).toHaveBeenCalledTimes(2);
|
||||
|
||||
const [reported, context] = mocks.captureException.mock.calls[0] as [
|
||||
Error,
|
||||
{ tags: Record<string, string>; extra: Record<string, unknown> },
|
||||
];
|
||||
expect(reported.message).toContain('Failed to build unique file');
|
||||
expect(reported.message).not.toContain('Screenshot');
|
||||
expect(reported.message).not.toContain('20.07.50');
|
||||
expect(reported.message).not.toContain('/storage/emulated');
|
||||
expect(context.tags).toMatchObject({ feature: 'media-save', target: 'downloads' });
|
||||
expect(context.extra).toMatchObject({ mimeType: 'image/png' });
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
+28
-79
@@ -1,5 +1,4 @@
|
||||
import FileSaver from 'file-saver';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
import { showToast } from '$state/toast';
|
||||
@@ -56,47 +55,6 @@ export const getDownloadFilename = (
|
||||
fallback = 'download'
|
||||
): string => sanitizeDownloadFilename(getAttachmentFilename(filename, body, fallback), fallback);
|
||||
|
||||
const splitExtension = (filename: string): [stem: string, extension: string] => {
|
||||
const at = filename.lastIndexOf('.');
|
||||
return at > 0 ? [filename.slice(0, at), filename.slice(at)] : [filename, ''];
|
||||
};
|
||||
|
||||
// MediaStore only probes 32 numbered variants of a name before failing with
|
||||
// "Failed to build unique file". A pending file sits under a `.pending-` name,
|
||||
// so creation succeeds and the wall is only hit when the flag is cleared and
|
||||
// the file takes its final name — so the whole save is retried, not the create.
|
||||
const saveWithUniqueName = async (
|
||||
filename: string,
|
||||
save: (filename: string) => Promise<void>
|
||||
): Promise<void> => {
|
||||
try {
|
||||
await save(filename);
|
||||
} catch {
|
||||
const [stem, extension] = splitExtension(filename);
|
||||
await save(sanitizeDownloadFilename(`${stem}-${Date.now()}${extension}`));
|
||||
}
|
||||
};
|
||||
|
||||
const reportSaveFailure = (
|
||||
error: unknown,
|
||||
target: 'downloads' | 'gallery' | 'photos',
|
||||
filename: string,
|
||||
mimeType?: string
|
||||
): void => {
|
||||
// Names contain spaces, so the name goes first: `\S*` would otherwise stop at
|
||||
// the first space and leave the rest of it in the message.
|
||||
const scrubbed = getErrorMessage(error)
|
||||
.split(splitExtension(filename)[0])
|
||||
.join('[FILENAME]')
|
||||
.replace(/\/(?:storage|data|var|Users|home)\/\S*/g, '[PATH]')
|
||||
.replace(/\b(_display_name|_data|title|relative_path)=\S*/g, '$1=[REDACTED]');
|
||||
|
||||
Sentry.captureException(new Error(scrubbed), {
|
||||
tags: { feature: 'media-save', target, platform: osType() },
|
||||
extra: { mimeType },
|
||||
});
|
||||
};
|
||||
|
||||
async function resolveBlob(input: Blob | string): Promise<Blob> {
|
||||
if (typeof input !== 'string') return input;
|
||||
return fetchMediaBlob(getTauriMediaSourceUrl(input) ?? input);
|
||||
@@ -122,6 +80,7 @@ export async function saveMediaToGallery(
|
||||
|
||||
if (platform === 'android') {
|
||||
const { AndroidFs, AndroidPublicImageDir } = await import('tauri-plugin-android-fs-api');
|
||||
let uri: Awaited<ReturnType<typeof AndroidFs.createNewPublicImageFile>> | undefined;
|
||||
try {
|
||||
const blob = await resolveBlob(input);
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
@@ -131,25 +90,18 @@ export async function saveMediaToGallery(
|
||||
if (!granted) throw new Error('Storage permission was denied');
|
||||
}
|
||||
|
||||
await saveWithUniqueName(filename, async (name) => {
|
||||
const uri = await AndroidFs.createNewPublicImageFile(
|
||||
AndroidPublicImageDir.Pictures,
|
||||
name,
|
||||
mediaMimeType,
|
||||
{ isPending: true, requestPermission: true }
|
||||
);
|
||||
try {
|
||||
await AndroidFs.writeFile(uri, bytes);
|
||||
await AndroidFs.setPublicFilePending(uri, false);
|
||||
await AndroidFs.scanPublicFile(uri);
|
||||
} catch (error) {
|
||||
await AndroidFs.removeFile(uri).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
uri = await AndroidFs.createNewPublicImageFile(
|
||||
AndroidPublicImageDir.Pictures,
|
||||
filename,
|
||||
mediaMimeType,
|
||||
{ isPending: true, requestPermission: true }
|
||||
);
|
||||
await AndroidFs.writeFile(uri, bytes);
|
||||
await AndroidFs.setPublicFilePending(uri, false);
|
||||
await AndroidFs.scanPublicFile(uri);
|
||||
showToast('Saved to Gallery');
|
||||
} catch (error) {
|
||||
reportSaveFailure(error, 'gallery', filename, mediaMimeType);
|
||||
if (uri) await AndroidFs.removeFile(uri).catch(() => undefined);
|
||||
showToast(`Failed to save to gallery: ${getErrorMessage(error)}`);
|
||||
}
|
||||
return;
|
||||
@@ -166,7 +118,6 @@ export async function saveMediaToGallery(
|
||||
});
|
||||
showToast('Saved to Photos');
|
||||
} catch (error) {
|
||||
reportSaveFailure(error, 'photos', filename, mediaMimeType);
|
||||
showToast(`Failed to save to photos: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -191,29 +142,28 @@ export async function saveFileToDevice(
|
||||
if (osType() === 'android') {
|
||||
const { AndroidFs, AndroidPublicGeneralPurposeDir } =
|
||||
await import('tauri-plugin-android-fs-api');
|
||||
if (!(await AndroidFs.checkPublicFilesPermission())) {
|
||||
const granted = await AndroidFs.requestPublicFilesPermission();
|
||||
if (!granted) throw new Error('Storage permission was denied');
|
||||
}
|
||||
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');
|
||||
}
|
||||
|
||||
await saveWithUniqueName(filename, async (name) => {
|
||||
const uri = await AndroidFs.createNewPublicFile(
|
||||
uri = await AndroidFs.createNewPublicFile(
|
||||
AndroidPublicGeneralPurposeDir.Download,
|
||||
name,
|
||||
filename,
|
||||
mimeType || blob.type || null,
|
||||
{ isPending: true, requestPermission: true }
|
||||
);
|
||||
try {
|
||||
await AndroidFs.writeFile(uri, bytes);
|
||||
await AndroidFs.setPublicFilePending(uri, false);
|
||||
await AndroidFs.scanPublicFile(uri);
|
||||
} catch (error) {
|
||||
await AndroidFs.removeFile(uri).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
showToast('Saved to Downloads');
|
||||
return 'saved';
|
||||
await AndroidFs.writeFile(uri, bytes);
|
||||
await AndroidFs.setPublicFilePending(uri, false);
|
||||
await AndroidFs.scanPublicFile(uri);
|
||||
showToast('Saved to Downloads');
|
||||
return 'saved';
|
||||
} catch (error) {
|
||||
if (uri) await AndroidFs.removeFile(uri).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (osType() === 'ios') {
|
||||
@@ -231,7 +181,6 @@ export async function saveFileToDevice(
|
||||
if (saved) showToast('File saved');
|
||||
return saved ? 'saved' : 'cancelled';
|
||||
} catch (error) {
|
||||
reportSaveFailure(error, 'downloads', filename, mimeType || blob.type || undefined);
|
||||
showToast(`Failed to save file: ${getErrorMessage(error)}`);
|
||||
return 'failed';
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user