import { BrowserWindow, Notification, nativeImage } from 'electron' import { join } from 'node:path' import type { AccountConfig } from '@shared/types/account' import { AccountType } from '@shared/types/account' import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider' import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData } from '@shared/types/message' import { ImapProvider } from '../providers/imap.provider' import { ExchangeProvider } from '../providers/exchange.provider' import { GmailProvider } from '../providers/gmail.provider' import { CredentialStore } from './credential-store' import Store from 'electron-store' interface AccountStoreSchema { accounts: Omit[] } // Коды ошибок imapflow при потере соединения const RECONNECT_CODES = new Set(['NoConnection', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND']) export class AccountManager { private providers = new Map() private store: Store private credentialStore: CredentialStore private mainWindow: BrowserWindow | null = null constructor() { this.store = new Store({ name: 'accounts', defaults: { accounts: [] } }) this.credentialStore = new CredentialStore() } setMainWindow(win: BrowserWindow): void { this.mainWindow = win } async initialize(): Promise { await this.credentialStore.load() } getAccounts(): AccountConfig[] { const accounts = this.store.get('accounts', []) return accounts.map((acc) => ({ ...acc, credentials: {} as AccountConfig['credentials'] })) } async addAccount(config: AccountConfig): Promise<{ success: boolean; error?: string }> { try { const provider = this.createProvider(config) await provider.connect() await this.credentialStore.save(config.id, JSON.stringify(config.credentials)) const { credentials: _, ...safeConfig } = config const accounts = this.store.get('accounts', []) accounts.push(safeConfig) this.store.set('accounts', accounts) this.providers.set(config.id, provider) this.setupNewMailListener(config.id, provider) return { success: true } } catch (error) { return { success: false, error: (error as Error).message } } } async removeAccount(accountId: string): Promise { const provider = this.providers.get(accountId) if (provider) { provider.offNewMail() await provider.disconnect() this.providers.delete(accountId) } await this.credentialStore.remove(accountId) const accounts = this.store.get('accounts', []) this.store.set('accounts', accounts.filter((a) => a.id !== accountId)) } async testConnection(config: AccountConfig): Promise<{ success: boolean; error?: string }> { try { const provider = this.createProvider(config) await provider.connect() await provider.disconnect() return { success: true } } catch (error) { return { success: false, error: (error as Error).message } } } async connectAccount(accountId: string): Promise<{ success: boolean; error?: string }> { if (this.providers.has(accountId)) { return { success: true } } try { const accounts = this.store.get('accounts', []) const accMeta = accounts.find((a) => a.id === accountId) if (!accMeta) return { success: false, error: 'Account not found' } const credRaw = this.credentialStore.get(accountId) if (!credRaw) return { success: false, error: 'Credentials not found' } const config: AccountConfig = { ...accMeta, credentials: JSON.parse(credRaw) } const provider = this.createProvider(config) await provider.connect() this.providers.set(accountId, provider) this.setupNewMailListener(accountId, provider) return { success: true } } catch (error) { return { success: false, error: (error as Error).message } } } async listFolders(accountId: string): Promise { return this.withAutoReconnect(accountId, () => this.getProvider(accountId).listFolders() ) } async pollNewMessages(accountId: string): Promise { const provider = this.providers.get(accountId) if (provider) await provider.pollNewMessages().catch(() => {}) } async sendMessage(accountId: string, compose: ComposeData): Promise { return this.withAutoReconnect(accountId, () => this.getProvider(accountId).sendMessage(compose) ) } async searchMessages(accountId: string, query: string, limit: number): Promise { return this.withAutoReconnect(accountId, () => { const provider = this.providers.get(accountId) if (!provider) return Promise.resolve([]) return provider.searchMessages(query, limit) }) } async listMessages( accountId: string, folderId: string, offset: number, limit: number, unseenOnly = false ): Promise { return this.withAutoReconnect(accountId, () => this.getProvider(accountId).listMessages({ folderId, offset, limit, unseenOnly }) ) } async fetchMessageBody( accountId: string, folderId: string, messageId: string ): Promise { return this.withAutoReconnect(accountId, () => this.getProvider(accountId).fetchMessageBody(folderId, messageId) ) } async downloadAttachment( accountId: string, folderId: string, messageId: string, attachmentId: string ): Promise { return this.withAutoReconnect(accountId, () => this.getProvider(accountId).downloadAttachment(folderId, messageId, attachmentId) ) } async updateFlags( accountId: string, folderId: string, messageIds: string[], flags: Partial ): Promise { return this.withAutoReconnect(accountId, () => this.getProvider(accountId).updateFlags(folderId, messageIds, flags) ) } async deleteMessages( accountId: string, folderId: string, messageIds: string[] ): Promise { return this.withAutoReconnect(accountId, () => this.getProvider(accountId).deleteMessages(folderId, messageIds) ) } // ── Auto-reconnect ────────────────────────────────────── private async withAutoReconnect(accountId: string, fn: () => Promise): Promise { try { return await fn() } catch (err) { const code = (err as { code?: string }).code ?? '' if (RECONNECT_CODES.has(code)) { await this.reconnectAccount(accountId) return await fn() } throw err } } private async reconnectAccount(accountId: string): Promise { // Убиваем старый провайдер const old = this.providers.get(accountId) if (old) { old.offNewMail() try { await old.disconnect() } catch { /* уже отвалился */ } this.providers.delete(accountId) } const accounts = this.store.get('accounts', []) const accMeta = accounts.find((a) => a.id === accountId) if (!accMeta) throw new Error('Account not found') const credRaw = this.credentialStore.get(accountId) if (!credRaw) throw new Error('Credentials not found') const config: AccountConfig = { ...accMeta, credentials: JSON.parse(credRaw) } const provider = this.createProvider(config) await provider.connect() this.providers.set(accountId, provider) this.setupNewMailListener(accountId, provider) } // ── Private helpers ───────────────────────────────────── private getProvider(accountId: string): IEmailProvider { const provider = this.providers.get(accountId) if (!provider) throw new Error(`Account ${accountId} is not connected`) return provider } private createProvider(config: AccountConfig): IEmailProvider { switch (config.type) { case AccountType.IMAP: return new ImapProvider(config) case AccountType.Exchange: return new ExchangeProvider(config) case AccountType.Gmail: return new GmailProvider(config) default: throw new Error(`Unknown account type: ${config.type}`) } } private setupNewMailListener(accountId: string, provider: IEmailProvider): void { provider.onNewMail((folderId, envelope) => { if (this.mainWindow && !this.mainWindow.isDestroyed()) { this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope }) } if (Notification.isSupported()) { const from = envelope.from.name || envelope.from.email || 'Новое письмо' const subject = envelope.subject || '(без темы)' const iconPath = join(__dirname, '../../resources/icon.png') const icon = nativeImage.createFromPath(iconPath) const n = new Notification({ title: from, body: subject, icon: icon.isEmpty() ? undefined : icon, silent: false, }) n.on('click', () => { if (this.mainWindow && !this.mainWindow.isDestroyed()) { this.mainWindow.show() this.mainWindow.focus() this.mainWindow.webContents.send('notification:click', { accountId, folderId, messageId: envelope.id }) } }) n.show() } }) } }