diff options
Diffstat (limited to 'src/electron/ipc-api/download.ts')
-rw-r--r-- | src/electron/ipc-api/download.ts | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/src/electron/ipc-api/download.ts b/src/electron/ipc-api/download.ts new file mode 100644 index 000000000..af15b157e --- /dev/null +++ b/src/electron/ipc-api/download.ts | |||
@@ -0,0 +1,59 @@ | |||
1 | import { ipcMain, dialog, BrowserWindow } from 'electron'; | ||
2 | import { download } from 'electron-dl'; | ||
3 | import mime from 'mime-types'; | ||
4 | import { writeFileSync } from 'fs-extra'; | ||
5 | import { PathLike } from 'fs'; | ||
6 | |||
7 | const debug = require('debug')('Ferdi:ipcApi:download'); | ||
8 | |||
9 | function decodeBase64Image(dataString: string) { | ||
10 | const matches = dataString.match(/^data:([+/A-Za-z-]+);base64,(.+)$/); | ||
11 | |||
12 | if (matches?.length !== 3) { | ||
13 | return new Error('Invalid input string'); | ||
14 | } | ||
15 | |||
16 | return Buffer.from(matches[2], 'base64'); | ||
17 | } | ||
18 | |||
19 | export default (params: { mainWindow: BrowserWindow }) => { | ||
20 | ipcMain.on( | ||
21 | 'download-file', | ||
22 | async (_event, { url, content, fileOptions = {} }) => { | ||
23 | const win = BrowserWindow.getFocusedWindow(); | ||
24 | |||
25 | try { | ||
26 | if (!content) { | ||
27 | const dl = await download(win!, url, { | ||
28 | saveAs: true, | ||
29 | }); | ||
30 | debug('File saved to', dl.savePath); | ||
31 | } else { | ||
32 | const extension = mime.extension(fileOptions.mime); | ||
33 | const filename = `${fileOptions.name}.${extension}`; | ||
34 | |||
35 | try { | ||
36 | const saveDialog = await dialog.showSaveDialog(params.mainWindow, { | ||
37 | defaultPath: filename, | ||
38 | }); | ||
39 | |||
40 | if (saveDialog.canceled) return; | ||
41 | |||
42 | const binaryImage = decodeBase64Image(content); | ||
43 | writeFileSync( | ||
44 | saveDialog.filePath as PathLike, | ||
45 | binaryImage as unknown as string, | ||
46 | 'binary', | ||
47 | ); | ||
48 | |||
49 | debug('File blob saved to', saveDialog.filePath); | ||
50 | } catch (error) { | ||
51 | console.log(error); | ||
52 | } | ||
53 | } | ||
54 | } catch (error) { | ||
55 | console.error(error); | ||
56 | } | ||
57 | }, | ||
58 | ); | ||
59 | }; | ||