import { app, BrowserWindow, shell, ipcMain, dialog, Menu, globalShortcut, clipboard } from 'electron' import { join, basename } from 'node:path' import { statSync, mkdirSync, copyFileSync, writeFileSync, readdirSync, unlinkSync, existsSync } from 'node:fs' import { homedir } from 'node:os' import { AccountManager } from './services/account-manager' import { RetentionService } from './services/retention-service' import { registerAccountHandlers } from './ipc/accounts.handler' import { registerFolderHandlers } from './ipc/folders.handler' import { registerMessageHandlers } from './ipc/messages.handler' import { registerCalendarHandlers } from './ipc/calendar.handler' import { registerUpdaterHandlers } from './ipc/updater.handler' import { registerRetentionHandlers } from './ipc/retention.handler' import { updater } from './services/updater' import type { ComposeSession } from '@shared/types/message' const accountManager = new AccountManager() const retentionService = new RetentionService(accountManager) // ── Compose windows ─────────────────────────────────────── // webContentsId → session, заполняется до loadURL, читается окном при монтировании const composeSessions = new Map() function createComposeWindow(session: ComposeSession): void { const iconPath = app.isPackaged ? join(process.resourcesPath, 'icon.png') : join(app.getAppPath(), 'resources/icon.png') const win = new BrowserWindow({ width: 700, height: 580, minWidth: 520, minHeight: 440, icon: iconPath, backgroundColor: '#09090e', title: session.mode === 'new' ? 'Новое письмо' : session.mode === 'forward' ? 'Переслать' : 'Ответить', webPreferences: { preload: join(__dirname, '../preload/index.js'), sandbox: false, contextIsolation: true, nodeIntegration: false } }) const webContentsId = win.webContents.id composeSessions.set(webContentsId, session) win.on('closed', () => composeSessions.delete(webContentsId)) if (process.env.ELECTRON_RENDERER_URL) { win.loadURL(`${process.env.ELECTRON_RENDERER_URL}#/compose`) } else { win.loadFile(join(__dirname, '../renderer/index.html'), { hash: '/compose' }) } } ipcMain.handle('compose:open', (_event, session: ComposeSession) => { createComposeWindow(session) }) ipcMain.handle('compose:getData', (event) => { const session = composeSessions.get(event.sender.id) ?? null return session }) ipcMain.handle('compose:pickFiles', async (event) => { const win = BrowserWindow.fromWebContents(event.sender) const result = await dialog.showOpenDialog(win ?? BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], { properties: ['openFile', 'multiSelections'], title: 'Прикрепить файлы' }) if (result.canceled) return [] return result.filePaths.map((p) => ({ path: p, filename: basename(p), size: statSync(p).size })) }) function createWindow(): BrowserWindow { const iconPath = app.isPackaged ? join(process.resourcesPath, 'icon.png') : join(app.getAppPath(), 'resources/icon.png') const mainWindow = new BrowserWindow({ width: 1280, height: 800, minWidth: 900, minHeight: 600, icon: iconPath, backgroundColor: '#1e1e1e', webPreferences: { preload: join(__dirname, '../preload/index.js'), sandbox: false, contextIsolation: true, nodeIntegration: false } }) accountManager.setMainWindow(mainWindow) retentionService.setMainWindow(mainWindow) // Разрешаем Web Notifications API из renderer mainWindow.webContents.session.setPermissionRequestHandler((_wc, permission, callback) => { callback(permission === 'notifications') }) globalShortcut.register('F12', () => { mainWindow.webContents.toggleDevTools() }) // Open external links in browser mainWindow.webContents.setWindowOpenHandler(({ url }) => { shell.openExternal(url) return { action: 'deny' } }) // Load the renderer if (process.env.ELECTRON_RENDERER_URL) { mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL) } else { mainWindow.loadFile(join(__dirname, '../renderer/index.html')) } return mainWindow } Menu.setApplicationMenu(null) ipcMain.handle('app:setZoom', (event, { factor }: { factor: number }) => { event.sender.setZoomFactor(Math.max(0.5, Math.min(3, factor))) }) ipcMain.handle('app:getDownloadsFolder', () => app.getPath('downloads')) ipcMain.handle('app:chooseFolder', async () => { const result = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'] }) return result.canceled ? null : (result.filePaths[0] ?? null) }) ipcMain.handle('app:openFile', async (_event, { path }: { path: string }) => { const err = await shell.openPath(path) return err ? { success: false, error: err } : { success: true } }) ipcMain.handle('app:copyToClipboard', (_event, { text }: { text: string }) => { clipboard.writeText(text) }) function setupLinuxIntegration(): void { if (process.platform !== 'linux' || !app.isPackaged) return const home = homedir() const appImagePath = process.env['APPIMAGE'] ?? '' // Копируем иконку из ресурсов AppImage в hicolor-тему const srcIcon = join(process.resourcesPath, 'icon.png') if (existsSync(srcIcon)) { for (const size of ['512x512', '256x256', '128x128']) { const dir = join(home, `.local/share/icons/hicolor/${size}/apps`) mkdirSync(dir, { recursive: true }) copyFileSync(srcIcon, join(dir, 'aero-mail.png')) } } // Удаляем старые записи AppImageLauncher const appsDir = join(home, '.local/share/applications') mkdirSync(appsDir, { recursive: true }) try { for (const f of readdirSync(appsDir)) { if (/^appimagekit_.*Aero_Mail\.desktop$/.test(f)) { unlinkSync(join(appsDir, f)) } } } catch (_) {} // Пишем чистый desktop-файл if (appImagePath) { writeFileSync( join(appsDir, 'aero-mail.desktop'), [ '[Desktop Entry]', 'Name=Aero Mail', `Exec=${appImagePath} --no-sandbox %U`, 'Terminal=false', 'Type=Application', 'Icon=aero-mail', 'StartupWMClass=Aero Mail', 'Comment=Desktop email client built with Vue 3 + Electron', 'Categories=Network;', '', ].join('\n'), ) } } app.whenReady().then(async () => { setupLinuxIntegration() await accountManager.initialize() // Register all IPC handlers registerAccountHandlers(accountManager, retentionService) registerFolderHandlers(accountManager) registerMessageHandlers(accountManager) registerCalendarHandlers(accountManager) registerUpdaterHandlers() registerRetentionHandlers(retentionService) createWindow() if (app.isPackaged) { setTimeout(() => updater.checkForUpdates(), 10_000) } app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('before-quit', () => { retentionService.dispose() })