502 lines
19 KiB
TypeScript
502 lines
19 KiB
TypeScript
import type { IncomingMail } from './mail-agent-notifications'
|
||
import { BrowserWindow, powerMonitor } 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'])
|
||
// Паузы между фоновыми попытками реконнекта; на последнем значении остаёмся
|
||
const RECONNECT_BACKOFF_MS = [5_000, 30_000, 120_000, 300_000]
|
||
|
||
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
|
||
private filterMailNotification: (event: IncomingMail) => boolean = (): boolean => false
|
||
// Одна попытка реконнекта на аккаунт: параллельные вызовы ждут общий промис
|
||
private reconnecting = new Map<string, Promise<void>>()
|
||
private reconnectTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||
|
||
constructor() {
|
||
this.store = new Store<AccountStoreSchema>({
|
||
name: 'accounts',
|
||
defaults: { accounts: [] }
|
||
})
|
||
this.credentialStore = new CredentialStore('credentials.json')
|
||
// После сна соединения обычно мертвы: проверяем сразу, не дожидаясь таймера опроса
|
||
powerMonitor.on('resume', () => {
|
||
for (const accountId of this.providers.keys()) void this.pollNewMessages(accountId)
|
||
})
|
||
}
|
||
|
||
setMailNotificationFilter(provider: (event: IncomingMail) => boolean): void {
|
||
this.filterMailNotification = provider
|
||
}
|
||
|
||
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((account): AccountConfig => {
|
||
const raw: string | undefined = this.credentialStore.get(account.id)
|
||
if (!raw) throw new Error(`Настройки подключения аккаунта ${account.id} не найдены`)
|
||
const credentials: ImapCredentials = JSON.parse(raw) as ImapCredentials
|
||
return {
|
||
...account,
|
||
credentials: { ...credentials, password: '' }
|
||
}
|
||
})
|
||
}
|
||
|
||
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> {
|
||
this.cancelScheduledReconnect(accountId)
|
||
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> {
|
||
if (!this.providers.has(accountId)) return
|
||
try {
|
||
await this.withAutoReconnect(accountId, () => this.getProvider(accountId).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 listMessagesAfterUid(accountId: string, folderId: string, afterUid: number, limit: number): Promise<MessageListResult> {
|
||
return this.withAutoReconnect(accountId, () => this.getProvider(accountId).listMessagesAfterUid(folderId, afterUid, limit))
|
||
}
|
||
|
||
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 ?? ''
|
||
const isDead = this.providers.get(accountId)?.isConnected() === false
|
||
if (!RECONNECT_CODES.has(code) && !isDead) throw err
|
||
}
|
||
|
||
try {
|
||
await this.reconnectAccount(accountId)
|
||
} catch (reconnectErr) {
|
||
console.error(`[AccountManager] reconnect failed for ${accountId}:`, reconnectErr)
|
||
// Провайдер удалён — без фонового повтора аккаунт остался бы отключённым
|
||
this.scheduleReconnect(accountId, 1)
|
||
throw new Error(`Reconnect failed: ${(reconnectErr as Error).message}`, { cause: originalError })
|
||
}
|
||
|
||
return await fn()
|
||
}
|
||
|
||
private reconnectAccount(accountId: string): Promise<void> {
|
||
const inFlight = this.reconnecting.get(accountId)
|
||
if (inFlight) return inFlight
|
||
|
||
const attempt = this.doReconnect(accountId).finally(() => this.reconnecting.delete(accountId))
|
||
this.reconnecting.set(accountId, attempt)
|
||
return attempt
|
||
}
|
||
|
||
private async doReconnect(accountId: string): Promise<void> {
|
||
this.cancelScheduledReconnect(accountId)
|
||
|
||
// Убиваем старый провайдер, забирая его счётчики непрочитанных
|
||
const old = this.providers.get(accountId)
|
||
const unseenCounts = old?.getUnseenCounts()
|
||
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()
|
||
// Без этого первое письмо после реконнекта не даст уведомления
|
||
if (unseenCounts) provider.seedUnseenCounts(unseenCounts)
|
||
this.providers.set(accountId, provider)
|
||
this.setupNewMailListener(accountId, provider)
|
||
}
|
||
|
||
// Фоновый реконнект после обрыва, с нарастающей паузой
|
||
private scheduleReconnect(accountId: string, attempt = 0): void {
|
||
if (this.reconnectTimers.has(accountId) || !this.isKnownAccount(accountId)) return
|
||
const delay = RECONNECT_BACKOFF_MS[Math.min(attempt, RECONNECT_BACKOFF_MS.length - 1)]
|
||
const timer = setTimeout(() => {
|
||
this.reconnectTimers.delete(accountId)
|
||
this.reconnectAccount(accountId).catch((err) => {
|
||
console.warn(`[AccountManager] background reconnect failed for ${accountId}:`, (err as Error).message)
|
||
// Провайдер уже удалён в doReconnect — планируем следующую попытку
|
||
this.scheduleReconnect(accountId, attempt + 1)
|
||
})
|
||
}, delay)
|
||
this.reconnectTimers.set(accountId, timer)
|
||
}
|
||
|
||
private cancelScheduledReconnect(accountId: string): void {
|
||
const timer = this.reconnectTimers.get(accountId)
|
||
if (timer) clearTimeout(timer)
|
||
this.reconnectTimers.delete(accountId)
|
||
}
|
||
|
||
private isKnownAccount(accountId: string): boolean {
|
||
return this.store.get('accounts', []).some((a) => a.id === accountId)
|
||
}
|
||
|
||
// ── 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
|
||
this.cancelScheduledReconnect(config.id)
|
||
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, agentEnabled: this.filterMailNotification({ accountId, folderId, envelope }) })
|
||
}
|
||
})
|
||
provider.onClose(() => {
|
||
// Игнорируем close устаревшего провайдера (его уже заменили)
|
||
if (this.providers.get(accountId) !== provider) return
|
||
console.warn(`[AccountManager] connection closed for ${accountId}, scheduling reconnect`)
|
||
this.scheduleReconnect(accountId)
|
||
})
|
||
}
|
||
}
|