import { ImapFlow } from 'imapflow' import type { BrowserWindow } from 'electron' import type { AccountConfig, ImapCredentials } from '@shared/types/account' import type { MessageEnvelope } from '@shared/types/message' import type { IndexSyncStatus } from '@shared/types/search-index' import { convertImapMessage } from '../lib/imap-message-mapper' import { SearchIndexStore } from './search-index-store' interface ImapMailboxNode { name: string path: string folders?: ImapMailboxNode[] } const FETCH_BATCH_SIZE = 500 const PERIODIC_SYNC_INTERVAL_MS = 15 * 60_000 // Держит локальный индекс заголовков писем в актуальном состоянии: // - при подключении аккаунта — полная синхронизация (если индекса ещё нет) либо дифф-синхронизация // - на новое письмо (onNewMail в AccountManager) — точечная индексация без похода по всей папке // - на удаление (messages:delete, retention) — точечное удаление из индекса // - раз в PERIODIC_SYNC_INTERVAL_MS — фоновая дифф-синхронизация всех подключённых аккаунтов // (подстраховка: внешние действия в другом почтовом клиенте, пропущенные события и т.п.) export class MailIndexer { private store = new SearchIndexStore() private accounts = new Map() private syncing = new Set() private progress = new Map() private periodicTimer: ReturnType | null = null private mainWindow: BrowserWindow | null = null setMainWindow(win: BrowserWindow): void { this.mainWindow = win } startPeriodicSync(): void { if (this.periodicTimer) return this.periodicTimer = setInterval(() => { for (const [accountId, config] of this.accounts) { if (this.syncing.has(accountId)) continue this.differentialSync(accountId, config).catch((err) => { console.warn(`[MailIndexer] periodic sync failed for ${accountId}:`, (err as Error).message) }) } }, PERIODIC_SYNC_INTERVAL_MS) } dispose(): void { if (this.periodicTimer) { clearInterval(this.periodicTimer) this.periodicTimer = null } } async onAccountConnected(accountId: string, config: AccountConfig): Promise { this.accounts.set(accountId, config) if (this.syncing.has(accountId)) return await this.store.load(accountId) if (this.store.hasData(accountId)) { await this.differentialSync(accountId, config) } else { await this.fullSync(accountId, config) } } removeAccount(accountId: string): void { this.accounts.delete(accountId) this.progress.delete(accountId) this.store.removeAccount(accountId) } async search(accountId: string, query: string, limit: number): Promise { await this.store.load(accountId) return this.store.search(accountId, query, limit) } async getStatus(accountId: string): Promise { await this.store.load(accountId) const cached = this.progress.get(accountId) if (cached) return cached const stats = this.store.getStats(accountId) return { accountId, state: stats.indexed > 0 ? 'ready' : 'idle', indexed: stats.indexed, total: stats.indexed } } // Индексирует одно только что пришедшее письмо — без похода по всей папке indexEnvelope(accountId: string, envelope: MessageEnvelope): void { this.store.upsertMany(accountId, [envelope]) } removeMessages(accountId: string, folderId: string, uids: string[]): void { this.store.remove(accountId, folderId, uids) } private async fullSync(accountId: string, config: AccountConfig): Promise { this.syncing.add(accountId) this.updateProgress(accountId, { state: 'syncing', indexed: 0, total: 0 }) const client = this.createClient(config) try { await client.connect() const folders = await this.listFolderPaths(client) const totals = new Map() let total = 0 for (const path of folders) { const status = await client.status(path, { messages: true }) as { messages?: number } | null const count = status?.messages ?? 0 totals.set(path, count) total += count } this.updateProgress(accountId, { state: 'syncing', indexed: 0, total }) let indexed = 0 for (const path of folders) { const count = totals.get(path) ?? 0 if (count === 0) continue const lock = await client.getMailboxLock(path) try { for (let start = 1; start <= count; start += FETCH_BATCH_SIZE) { const end = Math.min(start + FETCH_BATCH_SIZE - 1, count) const batch: MessageEnvelope[] = [] for await (const msg of client.fetch(`${start}:${end}`, { uid: true, envelope: true, flags: true, bodyStructure: true })) { batch.push(convertImapMessage(msg, path)) } this.store.upsertMany(accountId, batch) indexed += batch.length this.updateProgress(accountId, { state: 'syncing', indexed, total }) } } finally { lock.release() } } await this.store.flush(accountId) this.updateProgress(accountId, { state: 'ready', indexed, total }) } catch (err) { this.updateProgress(accountId, { state: 'error', indexed: 0, total: 0, error: (err as Error).message }) } finally { this.syncing.delete(accountId) await client.logout().catch(() => {}) } } // Лёгкая синхронизация: SEARCH ALL по каждой папке (без фильтра по содержимому — этому критерию // серверы не отказывают в поддержке), сравниваем с уже проиндексированными UID и подтягиваем/ // удаляем только разницу. Ловит и новые письма, и удалённые/перемещённые внешними клиентами. private async differentialSync(accountId: string, config: AccountConfig): Promise { this.syncing.add(accountId) const client = this.createClient(config) try { await client.connect() const folders = await this.listFolderPaths(client) for (const path of folders) { const lock = await client.getMailboxLock(path) try { const raw = await client.search({ all: true }, { uid: true }) const serverUids = new Set((Array.isArray(raw) ? raw : []).map(String)) const indexedUids = this.store.getFolderUidSet(accountId, path) const missing = [...serverUids].filter((uid) => !indexedUids.has(uid)) const stale = [...indexedUids].filter((uid) => !serverUids.has(uid)) if (stale.length) this.store.remove(accountId, path, stale) if (missing.length) { const batch: MessageEnvelope[] = [] for await (const msg of client.fetch(missing.join(','), { uid: true, envelope: true, flags: true, bodyStructure: true }, { uid: true })) { batch.push(convertImapMessage(msg, path)) } this.store.upsertMany(accountId, batch) } } finally { lock.release() } } await this.store.flush(accountId) const stats = this.store.getStats(accountId) this.updateProgress(accountId, { state: 'ready', indexed: stats.indexed, total: stats.indexed }) } catch (err) { console.warn(`[MailIndexer] differential sync failed for ${accountId}:`, (err as Error).message) } finally { this.syncing.delete(accountId) await client.logout().catch(() => {}) } } private async listFolderPaths(client: ImapFlow): Promise { const tree = await client.listTree() as { folders?: ImapMailboxNode[] } const flatten = (nodes: ImapMailboxNode[]): string[] => nodes.flatMap((n) => [n.path, ...flatten(n.folders ?? [])]) return flatten(tree.folders ?? []) } private createClient(config: AccountConfig): ImapFlow { const creds = config.credentials as ImapCredentials return new ImapFlow({ host: creds.host, port: creds.port, secure: creds.secure, auth: { user: creds.username, pass: creds.password }, logger: false }) } private updateProgress(accountId: string, partial: Omit): void { const status: IndexSyncStatus = { accountId, ...partial } this.progress.set(accountId, status) if (this.mainWindow && !this.mainWindow.isDestroyed()) { this.mainWindow.webContents.send('search:indexProgress', status) } } }