aero-mail/src/main/services/account-manager.ts
d.a.kolesov 137426ed1c
All checks were successful
Release / release (push) Successful in 3m18s
recursive mark as read
2026-11-11 13:14:58 +07:00

429 lines
15 KiB
TypeScript

import { BrowserWindow } from 'electron'
import type { AccountConfig, ImapCredentials } 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 type { CalendarInfo, CalendarEvent } from '@shared/types/calendar'
import type { FolderRetentionRule, RetentionCleanupResult } from '@shared/types/retention'
import { ImapProvider } from '../providers/imap.provider'
import { CalDavProvider } from '../providers/caldav.provider'
import { CredentialStore } from './credential-store'
import Store from 'electron-store'
interface AccountStoreSchema {
accounts: Omit<AccountConfig, 'credentials'>[]
}
// Коды ошибок imapflow при потере соединения
const RECONNECT_CODES = new Set(['NoConnection', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'])
export class AccountManager {
private providers = new Map<string, IEmailProvider>()
private calendarProviders = new Map<string, CalDavProvider>()
private store: Store<AccountStoreSchema>
private credentialStore: CredentialStore
private mainWindow: BrowserWindow | null = null
constructor() {
this.store = new Store<AccountStoreSchema>({
name: 'accounts',
defaults: { accounts: [] }
})
this.credentialStore = new CredentialStore()
}
setMainWindow(win: BrowserWindow): void {
this.mainWindow = win
}
async initialize(): Promise<void> {
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<void> {
const provider = this.providers.get(accountId)
if (provider) {
provider.offNewMail()
await provider.disconnect()
this.providers.delete(accountId)
}
this.calendarProviders.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 }> {
const provider = this.createProvider(config)
try {
await provider.connect()
return { success: true }
} catch (error) {
return { success: false, error: (error as Error).message }
} finally {
provider.disconnect().catch(() => {})
}
}
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' }
let credentials: AccountConfig['credentials']
try {
credentials = JSON.parse(credRaw)
} catch {
return { success: false, error: 'Corrupted credentials — please re-add the account' }
}
const config: AccountConfig = { ...accMeta, credentials }
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<FolderListResult> {
return this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).listFolders()
)
}
async pollNewMessages(accountId: string): Promise<void> {
const provider = this.providers.get(accountId)
if (!provider) return
try {
await provider.pollNewMessages()
} catch (err) {
console.warn(`[AccountManager] poll error for ${accountId}:`, (err as Error).message)
}
}
async sendMessage(accountId: string, compose: ComposeData): Promise<void> {
return this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).sendMessage(compose)
)
}
async searchMessages(accountId: string, query: string, limit: number): Promise<MessageEnvelope[]> {
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<MessageListResult> {
return this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).listMessages({ folderId, offset, limit, unseenOnly })
)
}
async fetchMessageBody(
accountId: string,
folderId: string,
messageId: string
): Promise<MessageBody> {
return this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).fetchMessageBody(folderId, messageId)
)
}
async downloadAttachment(
accountId: string,
folderId: string,
messageId: string,
attachmentId: string
): Promise<Buffer> {
return this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).downloadAttachment(folderId, messageId, attachmentId)
)
}
async updateFlags(
accountId: string,
folderId: string,
messageIds: string[],
flags: Partial<MessageFlags>
): Promise<void> {
return this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).updateFlags(folderId, messageIds, flags)
)
}
async deleteMessages(
accountId: string,
folderId: string,
messageIds: string[]
): Promise<void> {
return this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).deleteMessages(folderId, messageIds)
)
}
async markAllRead(accountId: string, folderIds: string[]): Promise<void> {
return this.withAutoReconnect(accountId, async () => {
const provider = this.getProvider(accountId)
let lastError: unknown = null
let failed = 0
// Последовательно: одно IMAP-соединение, блокировки мейлбоксов не пересекаются.
// Ошибка одной папки (например, \Noselect-контейнер) не прерывает остальные.
for (const folderId of folderIds) {
try {
await provider.markAllRead(folderId)
} catch (error) {
failed++
lastError = error
}
}
if (failed === folderIds.length) throw lastError
})
}
getConnectedAccountIds(): string[] {
return [...this.providers.keys()]
}
async enforceRetention(accountId: string, rules: FolderRetentionRule[]): Promise<RetentionCleanupResult[]> {
return this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).enforceRetention(rules)
)
}
// ── Calendar ────────────────────────────────────────────
async listCalendars(accountId: string): Promise<CalendarInfo[]> {
const provider = await this.getOrCreateCalendarProvider(accountId)
return provider.listCalendars(accountId)
}
async listCalendarEvents(
accountId: string,
calendarId: string,
start: Date,
end: Date
): Promise<CalendarEvent[]> {
const provider = await this.getOrCreateCalendarProvider(accountId)
return provider.listEvents(accountId, calendarId, start, end)
}
async probeCalendarPaths(accountId: string): Promise<{ path: string; status: number; note: string }[]> {
// Create a fresh provider (no cached state) and probe without connecting
const accounts = this.store.get('accounts', [])
const accMeta = accounts.find((a) => a.id === accountId)
if (!accMeta) throw new Error(`Account ${accountId} not found`)
const credRaw = this.credentialStore.get(accountId)
if (!credRaw) throw new Error(`Credentials for ${accountId} not found`)
let credentials: AccountConfig['credentials']
try {
credentials = JSON.parse(credRaw)
} catch {
throw new Error('Corrupted credentials')
}
const config: AccountConfig = { ...accMeta, credentials }
const provider = new CalDavProvider(config)
return provider.probePaths()
}
private async getOrCreateCalendarProvider(accountId: string): Promise<CalDavProvider> {
const existing = this.calendarProviders.get(accountId)
if (existing?.isConnected()) return existing
const accounts = this.store.get('accounts', [])
const accMeta = accounts.find((a) => a.id === accountId)
if (!accMeta) throw new Error(`Account ${accountId} not found`)
const credRaw = this.credentialStore.get(accountId)
if (!credRaw) throw new Error(`Credentials for ${accountId} not found`)
let credentials: AccountConfig['credentials']
try {
credentials = JSON.parse(credRaw)
} catch {
throw new Error('Corrupted credentials')
}
const config: AccountConfig = { ...accMeta, credentials }
const provider = new CalDavProvider(config)
await provider.connect()
this.calendarProviders.set(accountId, provider)
return provider
}
// ── Auto-reconnect ──────────────────────────────────────
private async withAutoReconnect<T>(accountId: string, fn: () => Promise<T>): Promise<T> {
let originalError: unknown
try {
return await fn()
} catch (err) {
originalError = err
const code = (err as { code?: string }).code ?? ''
if (!RECONNECT_CODES.has(code)) throw err
}
try {
await this.reconnectAccount(accountId)
} catch (reconnectErr) {
console.error(`[AccountManager] reconnect failed for ${accountId}:`, reconnectErr)
throw new Error(`Reconnect failed: ${(reconnectErr as Error).message}`, { cause: originalError })
}
return await fn()
}
private async reconnectAccount(accountId: string): Promise<void> {
// Убиваем старый провайдер
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')
let credentials: AccountConfig['credentials']
try {
credentials = JSON.parse(credRaw)
} catch {
throw new Error('Corrupted credentials — please re-add the account')
}
const config: AccountConfig = { ...accMeta, credentials }
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 {
if (config.type !== AccountType.IMAP) {
throw new Error(`Unsupported account type: ${config.type}`)
}
return new ImapProvider(config)
}
async updateAccount(config: AccountConfig): Promise<{ success: boolean; error?: string }> {
try {
// If password is empty string, preserve existing credentials password
const creds = config.credentials as ImapCredentials
let newCredentials = config.credentials
if ('password' in creds && creds.password === '') {
const existingCredRaw = this.credentialStore.get(config.id)
if (existingCredRaw) {
try {
const existing = JSON.parse(existingCredRaw) as ImapCredentials
newCredentials = { ...creds, password: existing.password }
} catch {
return { success: false, error: 'Corrupted existing credentials — please re-add the account' }
}
}
}
const configWithCreds: AccountConfig = { ...config, credentials: newCredentials }
// Update credentials
await this.credentialStore.save(config.id, JSON.stringify(configWithCreds.credentials))
// Update metadata in store
const { credentials: _, ...safeConfig } = configWithCreds
const accounts = this.store.get('accounts', [])
const idx = accounts.findIndex((a) => a.id === config.id)
if (idx === -1) return { success: false, error: 'Account not found' }
accounts[idx] = safeConfig
this.store.set('accounts', accounts)
// Reconnect if currently connected
const existingProvider = this.providers.get(config.id)
if (existingProvider) {
existingProvider.offNewMail()
try { await existingProvider.disconnect() } catch { /* already disconnected */ }
this.providers.delete(config.id)
const newProvider = this.createProvider(configWithCreds)
await newProvider.connect()
this.providers.set(config.id, newProvider)
this.setupNewMailListener(config.id, newProvider)
}
return { success: true }
} catch (error) {
return { success: false, error: (error as Error).message }
}
}
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 })
}
})
}
}