50 lines
1.2 KiB
TypeScript
50 lines
1.2 KiB
TypeScript
import { registerMediaSaver } from './saveMedia';
|
|
import { isElectron } from './tauri';
|
|
|
|
type ElectronSaveResult = {
|
|
success?: boolean;
|
|
canceled?: boolean;
|
|
path?: string;
|
|
error?: string;
|
|
};
|
|
|
|
type ElectronMediaApi = {
|
|
saveFile?: (payload: {
|
|
filename: string;
|
|
mimeType?: string;
|
|
data: Uint8Array;
|
|
}) => Promise<ElectronSaveResult>;
|
|
};
|
|
|
|
async function blobToUint8Array(blob: Blob): Promise<Uint8Array> {
|
|
const buffer = await blob.arrayBuffer();
|
|
return new Uint8Array(buffer);
|
|
}
|
|
|
|
async function saveWithElectron(blob: Blob, filename: string): Promise<void> {
|
|
const media = (window.electron as { media?: ElectronMediaApi } | undefined)?.media;
|
|
if (!media?.saveFile) {
|
|
throw new Error('Electron media.saveFile is unavailable');
|
|
}
|
|
|
|
const data = await blobToUint8Array(blob);
|
|
const result = await media.saveFile({
|
|
filename,
|
|
mimeType: blob.type || 'application/octet-stream',
|
|
data,
|
|
});
|
|
|
|
if (result?.canceled) return;
|
|
if (result?.success === false) {
|
|
throw new Error(result.error || 'Failed to save file');
|
|
}
|
|
}
|
|
export function registerDesktopMediaSaver(): void {
|
|
if (isElectron()) {
|
|
registerMediaSaver(async (blob, filename) => {
|
|
await saveWithElectron(blob, filename);
|
|
});
|
|
return;
|
|
}
|
|
}
|