diff options
Diffstat (limited to 'src/electron/ipc-api/download.js')
-rw-r--r-- | src/electron/ipc-api/download.js | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/electron/ipc-api/download.js b/src/electron/ipc-api/download.js new file mode 100644 index 000000000..399ca6117 --- /dev/null +++ b/src/electron/ipc-api/download.js | |||
@@ -0,0 +1,43 @@ | |||
1 | import { ipcMain, dialog } from 'electron'; | ||
2 | import { download } from 'electron-dl'; | ||
3 | import mime from 'mime-types'; | ||
4 | import fs from 'fs-extra'; | ||
5 | |||
6 | const debug = require('debug')('Franz:ipcApi:download'); | ||
7 | |||
8 | function decodeBase64Image(dataString) { | ||
9 | const matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/); | ||
10 | |||
11 | if (matches.length !== 3) { | ||
12 | return new Error('Invalid input string'); | ||
13 | } | ||
14 | |||
15 | return new Buffer(matches[2], 'base64'); | ||
16 | } | ||
17 | |||
18 | export default (params) => { | ||
19 | ipcMain.on('download-file', async (event, { url, content, fileOptions = {} }) => { | ||
20 | try { | ||
21 | if (!content) { | ||
22 | const dl = await download(params.mainWindow, url, { | ||
23 | saveAs: true, | ||
24 | }); | ||
25 | debug('File saved to', dl.getSavePath()); | ||
26 | } else { | ||
27 | const extension = mime.extension(fileOptions.mime); | ||
28 | const filename = `${fileOptions.name}.${extension}`; | ||
29 | |||
30 | dialog.showSaveDialog(params.mainWindow, { | ||
31 | defaultPath: filename, | ||
32 | }, (name) => { | ||
33 | const binaryImage = decodeBase64Image(content); | ||
34 | fs.writeFileSync(name, binaryImage, 'binary'); | ||
35 | |||
36 | debug('File blob saved to', name); | ||
37 | }); | ||
38 | } | ||
39 | } catch (e) { | ||
40 | console.error(e); | ||
41 | } | ||
42 | }); | ||
43 | }; | ||