311 lines
11 KiB
TypeScript
311 lines
11 KiB
TypeScript
import { NewMailDeduplicator } from './services/new-mail-deduplicator'
|
|
import { ImapInboxWatcher } from './services/inbox-watcher'
|
|
import { ImapInboxClientAdapter } from './providers/imap-inbox-client'
|
|
import { createImapClient } from './providers/imap-client'
|
|
import { watcherScheduler } from './services/watcher-scheduler'
|
|
import type { ComposeSettings } from '@shared/types/compose'
|
|
import { ComposeSettingsService } from './services/compose-settings-service'
|
|
import { registerComposeSettingsHandlers } from './ipc/compose-settings.handler'
|
|
import { JsonAgentHistoryRepository } from './services/mail-agent-history'
|
|
import { StatisticsService } from './services/statistics-service'
|
|
import { registerStatisticsHandlers } from './ipc/statistics.handler'
|
|
import { DEFAULT_AGENT_PROMPT } from '@shared/constants/agent'
|
|
import { createUsageStatistics } from './services/mail-agent-usage'
|
|
import Store from 'electron-store'
|
|
import { CredentialStore } from './services/credential-store'
|
|
import type { AgentStoreSchema } from './services/mail-agent-service'
|
|
import { MailAgentService } from './services/mail-agent-service'
|
|
import { registerAgentHandlers } from './ipc/agent.handler'
|
|
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 { registerReminderHandlers } from './ipc/reminder.handler'
|
|
import { MeetingReminderService } from './services/meeting-reminder-service'
|
|
import { MeetingReminderStore } from './services/meeting-reminder-store'
|
|
import { ReminderWindow } from './windows/reminder-window'
|
|
import { updater } from './services/updater'
|
|
import type { ComposeSession } from '@shared/types/message'
|
|
import type { CalendarEvent } from '@shared/types/calendar'
|
|
|
|
const accountManager = new AccountManager((config, publish) => new ImapInboxWatcher(
|
|
() => new ImapInboxClientAdapter(createImapClient(config)), publish,
|
|
(error: Error): void => console.warn('[InboxWatcher] %s:', config.email, error.message), watcherScheduler
|
|
), new NewMailDeduplicator((): number => Date.now()))
|
|
const retentionService = new RetentionService(accountManager)
|
|
|
|
let mainWindowRef: BrowserWindow | null = null
|
|
|
|
const mailAgentStore: Store<AgentStoreSchema> = new Store<AgentStoreSchema>({
|
|
name: 'mail-agent',
|
|
defaults: { settings: { enabled: false, notifyMutedFolders: false, prompt: DEFAULT_AGENT_PROMPT, pageSize: 100, batchSize: 1, concurrency: 2, url: 'http://localhost:11434/v1', model: '' }, processed: {}, baselines: {}, usage: createUsageStatistics() }
|
|
})
|
|
const mailAgent = new MailAgentService(accountManager,
|
|
mailAgentStore,
|
|
new CredentialStore('agent-credentials.json'),
|
|
(event): void => {
|
|
if (mainWindowRef && !mainWindowRef.isDestroyed()) mainWindowRef.webContents.send('agent:notification', event)
|
|
},
|
|
(message): void => {
|
|
if (mainWindowRef && !mainWindowRef.isDestroyed()) mainWindowRef.webContents.send('agent:error', { message })
|
|
},
|
|
(event): void => {
|
|
if (mainWindowRef && !mainWindowRef.isDestroyed()) mainWindowRef.webContents.send('agent:analyzed', event)
|
|
},
|
|
new JsonAgentHistoryRepository(mailAgentStore)
|
|
)
|
|
accountManager.setMailNotificationFilter((event): boolean => mailAgent.filterNotification(event))
|
|
accountManager.setNewMailObserver((event): void => mailAgent.enqueueNewMail(event))
|
|
app.on('before-quit', (): void => { mailAgent.stop(); accountManager.disposeWatchers() })
|
|
|
|
/** «Открыть» в напоминании: выводим главное окно и показываем событие в календаре. */
|
|
function openEventInMainWindow(event: CalendarEvent): void {
|
|
const win = mainWindowRef
|
|
if (!win || win.isDestroyed()) return
|
|
if (win.isMinimized()) win.restore()
|
|
win.show()
|
|
win.focus()
|
|
win.webContents.send('calendar:openEvent', { event })
|
|
}
|
|
|
|
const reminderWindow = new ReminderWindow(() => reminderService.dismissAll())
|
|
const reminderService = new MeetingReminderService(
|
|
accountManager,
|
|
new MeetingReminderStore(),
|
|
reminderWindow,
|
|
openEventInMainWindow
|
|
)
|
|
|
|
// ── Compose windows ───────────────────────────────────────
|
|
// webContentsId → session, заполняется до loadURL, читается окном при монтировании
|
|
const composeSessions = new Map<number, ComposeSession>()
|
|
|
|
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)
|
|
mainWindowRef = mainWindow
|
|
// Скрытое окно напоминаний иначе не даст сработать window-all-closed
|
|
mainWindow.on('closed', () => {
|
|
mainWindowRef = null
|
|
reminderWindow.destroy()
|
|
})
|
|
|
|
// Разрешаем 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, mailAgent)
|
|
registerCalendarHandlers(accountManager)
|
|
registerUpdaterHandlers()
|
|
registerRetentionHandlers(retentionService)
|
|
registerReminderHandlers(reminderService)
|
|
registerComposeSettingsHandlers(new ComposeSettingsService(new Store<ComposeSettings>({ name: 'compose-settings', defaults: { signature: '' } })))
|
|
registerAgentHandlers(mailAgent)
|
|
registerStatisticsHandlers(new StatisticsService(accountManager, mailAgent))
|
|
await mailAgent.initialize()
|
|
|
|
createWindow()
|
|
reminderService.start()
|
|
|
|
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()
|
|
reminderService.dispose()
|
|
})
|