aboutsummaryrefslogtreecommitdiffstats
path: root/src/electron/ipc-api/download.js
blob: 16de66229703d6563837a3c3f886f858651bada0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { ipcMain, dialog } from 'electron';
import { download } from 'electron-dl';
import mime from 'mime-types';
import fs from 'fs-extra';

const debug = require('debug')('Ferdi:ipcApi:download');

function decodeBase64Image(dataString) {
  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) => {
  ipcMain.on('download-file', async (event, { url, content, fileOptions = {} }) => {
    // We're passing a fake browserWindow to `electron-dl` in order to access the
    // webContents of the webview that has initiated the download
    const fakeWindow = {
      webContents: event.sender.webContents,
    };

    try {
      if (!content) {
        const dl = await download(fakeWindow, 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);
          fs.writeFileSync(saveDialog.filePath, binaryImage, 'binary');

          debug('File blob saved to', saveDialog.filePath);
        } catch (err) {
          console.log(err);
        }
      }
    } catch (e) {
      console.error(e);
    }
  });
};