aboutsummaryrefslogtreecommitdiffstats
path: root/src/electron/ipc-api/download.ts
blob: a306ba68d29bbe68752cbfb210dea1bb58fe4347 (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
56
57
58
59
60
61
62
63
64
65
import type { PathLike } from 'node:fs';
import { BrowserWindow, dialog, ipcMain } from 'electron';
import { download } from 'electron-dl';
import { writeFileSync } from 'fs-extra';

const debug = require('../../preload-safe-debug')('Ferdium: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) {
          try {
            const saveDialog = await dialog.showSaveDialog(params.mainWindow, {
              defaultPath: fileOptions.name,
            });

            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 (error) {
            console.error(error);
          }
        } else {
          const dl = await download(win!, url, {
            saveAs: true,
          });
          debug('File saved to', dl.savePath);
        }
      } catch (error) {
        console.error(error);
      }
    },
  );

  ipcMain.handle('download-folder-select', async () => {
    const result = await dialog.showOpenDialog(params.mainWindow, {
      properties: ['openDirectory'],
    });

    if (result.canceled) return null;

    return result.filePaths[0];
  });
};