From 087113d8a1214ba4c7df03bfe66747d8d944280c Mon Sep 17 00:00:00 2001 From: Markus Hatvan Date: Tue, 14 Sep 2021 11:03:28 +0200 Subject: chore: convert JS to TS (#1934) --- src/electron/ipc-api/download.ts | 59 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/electron/ipc-api/download.ts (limited to 'src/electron/ipc-api/download.ts') diff --git a/src/electron/ipc-api/download.ts b/src/electron/ipc-api/download.ts new file mode 100644 index 000000000..822658f26 --- /dev/null +++ b/src/electron/ipc-api/download.ts @@ -0,0 +1,59 @@ +import { ipcMain, dialog, BrowserWindow } from 'electron'; +import { download } from 'electron-dl'; +import mime from 'mime-types'; +import { writeFileSync } from 'fs-extra'; +import { PathLike } from 'fs'; + +const debug = require('debug')('Ferdi:ipcApi:download'); + +function decodeBase64Image(dataString: string) { + const matches = dataString.match(/^data:([A-Za-z-+/]+);base64,(.+)$/); + + if (matches?.length !== 3) { + return new Error('Invalid input string'); + } + + return Buffer.from(matches[2], 'base64'); +} + +export default (params: { mainWindow: BrowserWindow }) => { + ipcMain.on( + 'download-file', + async (_event, { url, content, fileOptions = {} }) => { + const win = BrowserWindow.getFocusedWindow(); + + try { + if (!content) { + const dl = await download(win!, url, { + saveAs: true, + }); + debug('File saved to', dl.savePath); + } else { + const extension = mime.extension(fileOptions.mime); + const filename = `${fileOptions.name}.${extension}`; + + try { + const saveDialog = await dialog.showSaveDialog(params.mainWindow, { + defaultPath: filename, + }); + + if (saveDialog.canceled) return; + + const binaryImage = decodeBase64Image(content); + writeFileSync( + saveDialog.filePath as PathLike, + binaryImage as unknown as string, + 'binary', + ); + + debug('File blob saved to', saveDialog.filePath); + } catch (err) { + console.log(err); + } + } + } catch (e) { + console.error(e); + } + }, + ); +}; -- cgit v1.2.3-54-g00ecf