diff --git a/main/index.ts b/main/index.ts index 0cefc48ef..1c1f3812e 100644 --- a/main/index.ts +++ b/main/index.ts @@ -9,6 +9,7 @@ import electronReload from 'electron-reload'; import { PROD_HOST_URL, RENDERER_OUTPUT_DIR } from './config'; import { isDev } from './utils/common'; import serveNextAt from 'next-electron-server'; +import { existsSync } from 'fs'; if (isDev) { electronReload(__dirname, {}); @@ -71,17 +72,53 @@ if (!gotTheLock) { if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); - const trayImgPath = isDev - ? 'build/taskbar-icon.png' - : path.join(process.resourcesPath, 'taskbar-icon.png'); - const trayIcon = nativeImage.createFromPath(trayImgPath); - tray = new Tray(trayIcon); - tray.setToolTip('ente'); - tray.setContextMenu(buildContextMenu(mainWindow)); - + setupTrayItem(); setupIpcComs(tray, mainWindow); - if (!isDev) { - AppUpdater.checkForUpdate(tray, mainWindow); - } + handleUpdates(); + handleDownloads(); }); } + +function handleUpdates() { + if (!isDev) { + AppUpdater.checkForUpdate(tray, mainWindow); + } +} + +function setupTrayItem() { + const trayImgPath = isDev + ? 'build/taskbar-icon.png' + : path.join(process.resourcesPath, 'taskbar-icon.png'); + const trayIcon = nativeImage.createFromPath(trayImgPath); + tray = new Tray(trayIcon); + tray.setToolTip('ente'); + tray.setContextMenu(buildContextMenu(mainWindow)); +} + +function handleDownloads() { + mainWindow.webContents.session.on('will-download', (event, item) => { + item.setSavePath( + getUniqueSavePath(item.getFilename(), app.getPath('downloads')) + ); + }); +} + +function getUniqueSavePath(filename: string, directory: string): string { + let uniqueFileSavePath = path.join(directory, filename); + const { name: filenameWithoutExtension, ext: extension } = + path.parse(filename); + let n = 0; + while (existsSync(uniqueFileSavePath)) { + n++; + // filter need to remove undefined extension from the array + // else [`${fileName}`, undefined].join(".") will lead to `${fileName}.` as joined string + const fileNameWithNumberedSuffix = [ + `${filenameWithoutExtension}(${n})`, + extension, + ] + .filter((x) => x) // filters out undefined/null values + .join('.'); + uniqueFileSavePath = path.join(directory, fileNameWithNumberedSuffix); + } + return uniqueFileSavePath; +}