diff --git a/src/main/index.ts b/src/main/index.ts index 24b7c00..ff74e7a 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -4,17 +4,22 @@ import { statSync, mkdirSync, copyFileSync, writeFileSync, readdirSync, unlinkSy import { homedir } from 'node:os' import { AccountManager } from './services/account-manager' import { RetentionService } from './services/retention-service' +import { MailIndexer } from './services/mail-indexer' 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 { registerSearchIndexHandlers } from './ipc/search-index.handler' import { updater } from './services/updater' import type { ComposeSession } from '@shared/types/message' const accountManager = new AccountManager() const retentionService = new RetentionService(accountManager) +const mailIndexer = new MailIndexer() +accountManager.setMailIndexer(mailIndexer) +retentionService.setMailIndexer(mailIndexer) // ── Compose windows ─────────────────────────────────────── // webContentsId → session, заполняется до loadURL, читается окном при монтировании @@ -99,6 +104,7 @@ function createWindow(): BrowserWindow { accountManager.setMainWindow(mainWindow) retentionService.setMainWindow(mainWindow) + mailIndexer.setMainWindow(mainWindow) // Разрешаем Web Notifications API из renderer mainWindow.webContents.session.setPermissionRequestHandler((_wc, permission, callback) => { @@ -201,12 +207,14 @@ app.whenReady().then(async () => { // Register all IPC handlers registerAccountHandlers(accountManager, retentionService) registerFolderHandlers(accountManager) - registerMessageHandlers(accountManager) + registerMessageHandlers(accountManager, mailIndexer) registerCalendarHandlers(accountManager) registerUpdaterHandlers() registerRetentionHandlers(retentionService) + registerSearchIndexHandlers(mailIndexer) createWindow() + mailIndexer.startPeriodicSync() if (app.isPackaged) { setTimeout(() => updater.checkForUpdates(), 10_000) @@ -227,4 +235,5 @@ app.on('window-all-closed', () => { app.on('before-quit', () => { retentionService.dispose() + mailIndexer.dispose() }) diff --git a/src/main/ipc/messages.handler.ts b/src/main/ipc/messages.handler.ts index a41aa27..eba4df4 100644 --- a/src/main/ipc/messages.handler.ts +++ b/src/main/ipc/messages.handler.ts @@ -3,6 +3,7 @@ import { writeFile, access } from 'fs/promises' import { join, extname, basename } from 'path' import { registerHandler } from './registry' import type { AccountManager } from '../services/account-manager' +import type { MailIndexer } from '../services/mail-indexer' function assertId(value: unknown, name: string): asserts value is string { if (typeof value !== 'string' || value.length === 0) { @@ -40,7 +41,7 @@ function sendProgress(attachmentId: string, stage: 'downloading' | 'saving' | 'd win?.webContents.send('attachment:progress', { attachmentId, stage, progress, error }) } -export function registerMessageHandlers(manager: AccountManager): void { +export function registerMessageHandlers(manager: AccountManager, mailIndexer: MailIndexer): void { registerHandler('messages:list', async ({ accountId, folderId, offset, limit, unseenOnly }) => { assertId(accountId, 'accountId') assertId(folderId, 'folderId') @@ -64,7 +65,7 @@ export function registerMessageHandlers(manager: AccountManager): void { registerHandler('messages:search', async ({ accountId, query, limit }) => { assertId(accountId, 'accountId') - return manager.searchMessages(accountId, query, limit) + return mailIndexer.search(accountId, query, limit) }) registerHandler('messages:body', async ({ accountId, folderId, messageId }) => { diff --git a/src/main/ipc/search-index.handler.ts b/src/main/ipc/search-index.handler.ts new file mode 100644 index 0000000..ca3bed6 --- /dev/null +++ b/src/main/ipc/search-index.handler.ts @@ -0,0 +1,8 @@ +import { registerHandler } from './registry' +import type { MailIndexer } from '../services/mail-indexer' + +export function registerSearchIndexHandlers(mailIndexer: MailIndexer): void { + registerHandler('search:status', async ({ accountId }) => { + return mailIndexer.getStatus(accountId) + }) +} diff --git a/src/main/lib/imap-message-mapper.ts b/src/main/lib/imap-message-mapper.ts new file mode 100644 index 0000000..eba34de --- /dev/null +++ b/src/main/lib/imap-message-mapper.ts @@ -0,0 +1,64 @@ +import type { MessageEnvelope, Address } from '@shared/types/message' + +// imapflow BodyStructure type +export interface ImapBodyPart { + part?: string + type?: string + subtype?: string + disposition?: string + parameters?: Record + id?: string + encoding?: string + childNodes?: ImapBodyPart[] +} + +interface ImapFetchedMessage { + uid: number + envelope?: { + subject?: string + from?: Array<{ name?: string; address?: string }> + to?: Array<{ name?: string; address?: string }> + cc?: Array<{ name?: string; address?: string }> + date?: Date + messageId?: string + inReplyTo?: string + } + flags?: Set + bodyStructure?: ImapBodyPart +} + +function addressesFrom(list?: Array<{ name?: string; address?: string }>): Address[] { + return (list ?? []).map((a) => ({ name: a.name ?? '', email: a.address ?? '' })) +} + +function messageHasAttachments(node?: ImapBodyPart): boolean { + if (!node) return false + if (node.disposition === 'attachment') return true + if (node.childNodes) return node.childNodes.some((c) => messageHasAttachments(c)) + return false +} + +export function convertImapMessage(msg: unknown, folderId: string): MessageEnvelope { + const m = msg as ImapFetchedMessage + const flags = m.flags ?? new Set() + + return { + id: String(m.uid), + folderId, + subject: m.envelope?.subject ?? '(no subject)', + from: addressesFrom(m.envelope?.from)[0] ?? { name: '', email: '' }, + to: addressesFrom(m.envelope?.to), + cc: addressesFrom(m.envelope?.cc), + date: m.envelope?.date?.toISOString() ?? new Date().toISOString(), + flags: { + seen: flags.has('\\Seen'), + flagged: flags.has('\\Flagged'), + answered: flags.has('\\Answered'), + deleted: flags.has('\\Deleted') + }, + hasAttachments: messageHasAttachments(m.bodyStructure), + snippet: '', + messageId: m.envelope?.messageId ?? undefined, + inReplyTo: m.envelope?.inReplyTo ?? undefined, + } +} diff --git a/src/main/providers/imap.provider.ts b/src/main/providers/imap.provider.ts index 796e11d..bd0d99d 100644 --- a/src/main/providers/imap.provider.ts +++ b/src/main/providers/imap.provider.ts @@ -2,12 +2,13 @@ import { ImapFlow } from 'imapflow' import { simpleParser } from 'mailparser' import nodemailer from 'nodemailer' import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider' -import type { MessageBody, MessageFlags, MessageEnvelope, Address, ComposeData, InlineImage, Attachment } from '@shared/types/message' +import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, InlineImage, Attachment } from '@shared/types/message' import { SpecialFolderRole } from '@shared/types/folder' import type { Folder } from '@shared/types/folder' import type { AccountConfig, ImapCredentials } from '@shared/types/account' import type { FolderRetentionRule, RetentionCleanupResult } from '@shared/types/retention' import { sanitizeHtml } from '../lib/html-sanitizer' +import { convertImapMessage } from '../lib/imap-message-mapper' // imapflow MailboxObject type interface ImapMailbox { @@ -17,18 +18,6 @@ interface ImapMailbox { folders?: ImapMailbox[] } -// imapflow BodyStructure type -interface BodyPart { - part?: string - type?: string - subtype?: string - disposition?: string - parameters?: Record - id?: string - encoding?: string - childNodes?: BodyPart[] -} - export class ImapProvider implements IEmailProvider { private client: ImapFlow private connected = false @@ -148,7 +137,7 @@ export class ImapProvider implements IEmailProvider { flags: true, bodyStructure: true })) { - messages.push(this.convertMessage(msg, options.folderId)) + messages.push(convertImapMessage(msg, options.folderId)) } // Newest first @@ -179,7 +168,7 @@ export class ImapProvider implements IEmailProvider { flags: true, bodyStructure: true }, { uid: true })) { - messages.push(this.convertMessage(msg, options.folderId)) + messages.push(convertImapMessage(msg, options.folderId)) } // Fetch returns ascending order → reverse to newest first messages.sort((a, b) => Number(b.id) - Number(a.id)) @@ -328,8 +317,8 @@ export class ImapProvider implements IEmailProvider { if (effectiveLimit !== null) { try { - const deletedCount = await this.trimFolder(folder.id, effectiveLimit) - if (deletedCount > 0) results.push({ folderId: folder.id, deletedCount }) + const deletedUids = await this.trimFolder(folder.id, effectiveLimit) + if (deletedUids.length > 0) results.push({ folderId: folder.id, deletedCount: deletedUids.length, deletedUids }) } catch (err) { console.warn(`[IMAP:retention] folder error ${folder.id}:`, (err as Error).message) } @@ -344,21 +333,22 @@ export class ImapProvider implements IEmailProvider { // Удаляет самые старые письма сверх maxMessages. Сортировка по sequence number — // тот же порядок "старое → новое", что используется в listMessages. - private async trimFolder(folderId: string, maxMessages: number): Promise { + // Возвращает UID удалённых писем — вызывающий код убирает их из локального поискового индекса. + private async trimFolder(folderId: string, maxMessages: number): Promise { const lock = await this.client.getMailboxLock(folderId) try { const total = (this.client.mailbox as { exists?: number })?.exists ?? 0 const excess = total - maxMessages - if (excess <= 0) return 0 + if (excess <= 0) return [] const uidsToDelete: number[] = [] for await (const msg of this.client.fetch(`1:${excess}`, { uid: true })) { uidsToDelete.push((msg as { uid: number }).uid) } - if (uidsToDelete.length === 0) return 0 + if (uidsToDelete.length === 0) return [] await this.client.messageDelete(uidsToDelete.join(','), { uid: true }) - return uidsToDelete.length + return uidsToDelete.map(String) } finally { lock.release() } @@ -501,74 +491,6 @@ export class ImapProvider implements IEmailProvider { this.client.removeAllListeners('exists') } - async searchMessages(query: string, limit: number): Promise { - const results: MessageEnvelope[] = [] - // Не ловим ошибки здесь — они должны попасть в withAutoReconnect (AccountManager) - // для переподключения при NoConnection и прочих сетевых сбоях - const tree = await this.client.listTree() as { folders?: ImapMailbox[] } - await this.searchFolderTree(tree.folders ?? [], query, limit, results) - return results - } - - private shouldSkipFolder(folder: ImapMailbox): boolean { - const n = folder.name.toLowerCase() - const p = (folder.path ?? '').toLowerCase() - return ( - n === 'trash' || n === 'deleted items' || n === 'deleted messages' || - n === 'spam' || n === 'junk' || n === 'junk e-mail' || - p.includes('[gmail]/trash') || p.includes('[gmail]/spam') - ) - } - - private async searchFolderTree( - folders: ImapMailbox[], - query: string, - limit: number, - results: MessageEnvelope[] - ): Promise { - for (const folder of folders) { - if (results.length >= limit) break - if (this.shouldSkipFolder(folder)) { - if (folder.folders?.length && results.length < limit) { - await this.searchFolderTree(folder.folders, query, limit, results) - } - continue - } - let lock: Awaited> | null = null - try { - lock = await this.client.getMailboxLock(folder.path) - - // SUBJECT + FROM — серверный поиск (быстрее, чем TEXT по телу) - const rawSubject = await this.client.search({ subject: query }, { uid: true }) - const rawFrom = await this.client.search({ from: query }, { uid: true }) - const subjectUids = Array.isArray(rawSubject) ? rawSubject : [] - const fromUids = Array.isArray(rawFrom) ? rawFrom : [] - - // Объединяем UIDs без дублей - const merged = [...new Set([...subjectUids, ...fromUids])] - - if (merged.length) { - const remaining = limit - results.length - const sorted = [...merged].sort((a, b) => b - a).slice(0, remaining) - for await (const msg of this.client.fetch(sorted.join(','), { - uid: true, envelope: true, flags: true, bodyStructure: true - }, { uid: true })) { - results.push(this.convertMessage(msg, folder.path)) - } - } - } catch (e) { - console.error('[IMAP:search] folder error:', folder?.path, e) - } - finally { - lock?.release() - } - - if (folder.folders?.length && results.length < limit) { - await this.searchFolderTree(folder.folders, query, limit, results) - } - } - } - async pollNewMessages(): Promise { if (!this.newMailCallback) return try { @@ -610,7 +532,7 @@ export class ImapProvider implements IEmailProvider { uid: true, envelope: true, flags: true }, { uid: true })) { this.markNotified(dedupKey) - this.newMailCallback(folder.path, this.convertMessage(msg, folder.path)) + this.newMailCallback(folder.path, convertImapMessage(msg, folder.path)) break } } @@ -685,48 +607,6 @@ export class ImapProvider implements IEmailProvider { return SpecialFolderRole.None } - private convertMessage(msg: unknown, folderId: string): MessageEnvelope { - const m = msg as { - uid: number - envelope: { - subject?: string - from?: Array<{ name?: string; address?: string }> - to?: Array<{ name?: string; address?: string }> - cc?: Array<{ name?: string; address?: string }> - date?: Date - messageId?: string - inReplyTo?: string - } - flags: Set - bodyStructure?: BodyPart - } - - const addr = (list?: Array<{ name?: string; address?: string }>): Address[] => - (list ?? []).map((a) => ({ name: a.name ?? '', email: a.address ?? '' })) - - const flags = m.flags ?? new Set() - - return { - id: String(m.uid), - folderId, - subject: m.envelope?.subject ?? '(no subject)', - from: addr(m.envelope?.from)[0] ?? { name: '', email: '' }, - to: addr(m.envelope?.to), - cc: addr(m.envelope?.cc), - date: m.envelope?.date?.toISOString() ?? new Date().toISOString(), - flags: { - seen: flags.has('\\Seen'), - flagged: flags.has('\\Flagged'), - answered: flags.has('\\Answered'), - deleted: flags.has('\\Deleted') - }, - hasAttachments: this.hasAttachments(m.bodyStructure), - snippet: '', - messageId: m.envelope?.messageId ?? undefined, - inReplyTo: m.envelope?.inReplyTo ?? undefined, - } - } - /** * Конвертирует plain text в минимальный HTML (параграфы + переносы строк). */ @@ -801,11 +681,4 @@ export class ImapProvider implements IEmailProvider { .replace(/\n{3,}/g, '\n\n') .trim() } - - private hasAttachments(node?: BodyPart): boolean { - if (!node) return false - if (node.disposition === 'attachment') return true - if (node.childNodes) return node.childNodes.some((c) => this.hasAttachments(c)) - return false - } } diff --git a/src/main/services/account-manager.ts b/src/main/services/account-manager.ts index 21b9b73..945e505 100644 --- a/src/main/services/account-manager.ts +++ b/src/main/services/account-manager.ts @@ -2,12 +2,13 @@ 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 { MessageBody, MessageFlags, 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 type { MailIndexer } from './mail-indexer' import Store from 'electron-store' interface AccountStoreSchema { @@ -23,6 +24,7 @@ export class AccountManager { private store: Store private credentialStore: CredentialStore private mainWindow: BrowserWindow | null = null + private mailIndexer: MailIndexer | null = null constructor() { this.store = new Store({ @@ -36,6 +38,10 @@ export class AccountManager { this.mainWindow = win } + setMailIndexer(indexer: MailIndexer): void { + this.mailIndexer = indexer + } + async initialize(): Promise { await this.credentialStore.load() } @@ -62,6 +68,9 @@ export class AccountManager { this.providers.set(config.id, provider) this.setupNewMailListener(config.id, provider) + this.mailIndexer?.onAccountConnected(config.id, config).catch((err) => { + console.warn(`[AccountManager] index sync failed for ${config.id}:`, (err as Error).message) + }) return { success: true } } catch (error) { @@ -78,6 +87,7 @@ export class AccountManager { } this.calendarProviders.delete(accountId) await this.credentialStore.remove(accountId) + this.mailIndexer?.removeAccount(accountId) const accounts = this.store.get('accounts', []) this.store.set('accounts', accounts.filter((a) => a.id !== accountId)) @@ -120,6 +130,9 @@ export class AccountManager { await provider.connect() this.providers.set(accountId, provider) this.setupNewMailListener(accountId, provider) + this.mailIndexer?.onAccountConnected(accountId, config).catch((err) => { + console.warn(`[AccountManager] index sync failed for ${accountId}:`, (err as Error).message) + }) return { success: true } } catch (error) { @@ -149,14 +162,6 @@ export class AccountManager { ) } - 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, @@ -206,9 +211,10 @@ export class AccountManager { folderId: string, messageIds: string[] ): Promise { - return this.withAutoReconnect(accountId, () => + await this.withAutoReconnect(accountId, () => this.getProvider(accountId).deleteMessages(folderId, messageIds) ) + this.mailIndexer?.removeMessages(accountId, folderId, messageIds) } async markAllRead(accountId: string, folderId: string): Promise { @@ -398,6 +404,9 @@ export class AccountManager { await newProvider.connect() this.providers.set(config.id, newProvider) this.setupNewMailListener(config.id, newProvider) + this.mailIndexer?.onAccountConnected(config.id, configWithCreds).catch((err) => { + console.warn(`[AccountManager] index sync failed for ${config.id}:`, (err as Error).message) + }) } return { success: true } @@ -408,6 +417,7 @@ export class AccountManager { private setupNewMailListener(accountId: string, provider: IEmailProvider): void { provider.onNewMail((folderId, envelope) => { + this.mailIndexer?.indexEnvelope(accountId, envelope) if (this.mainWindow && !this.mainWindow.isDestroyed()) { this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope }) } diff --git a/src/main/services/mail-indexer.ts b/src/main/services/mail-indexer.ts new file mode 100644 index 0000000..5c5aae1 --- /dev/null +++ b/src/main/services/mail-indexer.ts @@ -0,0 +1,220 @@ +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) + } + } +} diff --git a/src/main/services/retention-service.ts b/src/main/services/retention-service.ts index d709858..39f5d45 100644 --- a/src/main/services/retention-service.ts +++ b/src/main/services/retention-service.ts @@ -3,12 +3,14 @@ import { join } from 'node:path' import type { BrowserWindow } from 'electron' import type { FolderRetentionRule } from '@shared/types/retention' import type { AccountManager } from './account-manager' +import type { MailIndexer } from './mail-indexer' import { RetentionStore } from './retention-store' export class RetentionService { private worker: Worker private store = new RetentionStore() private mainWindow: BrowserWindow | null = null + private mailIndexer: MailIndexer | null = null private checking = false constructor(private accountManager: AccountManager) { @@ -29,6 +31,10 @@ export class RetentionService { this.mainWindow = win } + setMailIndexer(indexer: MailIndexer): void { + this.mailIndexer = indexer + } + setCheckInterval(minutes: number): void { this.worker.postMessage({ type: 'setInterval', intervalMinutes: minutes }) } @@ -65,6 +71,9 @@ export class RetentionService { try { const results = await this.accountManager.enforceRetention(accountId, rules) const cleaned = results.filter((r) => r.deletedCount > 0) + for (const result of cleaned) { + this.mailIndexer?.removeMessages(accountId, result.folderId, result.deletedUids) + } if (cleaned.length > 0 && this.mainWindow && !this.mainWindow.isDestroyed()) { this.mainWindow.webContents.send('retention:cleaned', { accountId, results: cleaned }) } diff --git a/src/main/services/search-index-store.ts b/src/main/services/search-index-store.ts new file mode 100644 index 0000000..e4bf118 --- /dev/null +++ b/src/main/services/search-index-store.ts @@ -0,0 +1,161 @@ +import { app } from 'electron' +import { existsSync, mkdirSync } from 'node:fs' +import { readFile, writeFile, unlink } from 'node:fs/promises' +import { join } from 'node:path' +import type { MessageEnvelope, Address } from '@shared/types/message' + +// Поле, к которому сужен поиск через префикс "from:"/"to:"/"cc:"/"subject:" (null — по всем сразу) +export type SearchField = 'from' | 'to' | 'cc' | 'subject' +export interface SearchQuery { + field: SearchField | null + term: string +} + +export function parseSearchQuery(raw: string): SearchQuery { + const match = raw.match(/^\s*(from|to|cc|subject)\s*:\s*(.+)$/i) + if (!match) return { field: null, term: raw.trim() } + return { field: match[1].toLowerCase() as SearchField, term: match[2].trim() } +} + +const SAVE_DEBOUNCE_MS = 2000 + +// Локальный индекс заголовков писем (без тела) — one file per account в userData, +// в памяти держим Map для мгновенного поиска. Так поиск работает по всей истории +// письма и не зависит от корректности серверного IMAP SEARCH. +export class SearchIndexStore { + // accountId → (folderId + ':' + uid) → письмо + private indices = new Map>() + private saveTimers = new Map>() + private dir: string + + constructor() { + this.dir = join(app.getPath('userData'), 'search-index') + } + + async load(accountId: string): Promise { + if (this.indices.has(accountId)) return + const map = new Map() + this.indices.set(accountId, map) + try { + const raw = await readFile(this.filePath(accountId), 'utf-8') + const messages = JSON.parse(raw) as MessageEnvelope[] + for (const msg of messages) { + map.set(this.key(msg.folderId, msg.id), msg) + } + } catch { + // индекса ещё нет — начинаем с пустого + } + } + + hasData(accountId: string): boolean { + return (this.indices.get(accountId)?.size ?? 0) > 0 + } + + getStats(accountId: string): { indexed: number } { + return { indexed: this.indices.get(accountId)?.size ?? 0 } + } + + getFolderUidSet(accountId: string, folderId: string): Set { + const result = new Set() + const map = this.indices.get(accountId) + if (!map) return result + for (const msg of map.values()) { + if (msg.folderId === folderId) result.add(msg.id) + } + return result + } + + upsertMany(accountId: string, messages: MessageEnvelope[]): void { + if (messages.length === 0) return + const map = this.indices.get(accountId) ?? new Map() + this.indices.set(accountId, map) + for (const msg of messages) { + map.set(this.key(msg.folderId, msg.id), msg) + } + this.scheduleSave(accountId) + } + + remove(accountId: string, folderId: string, uids: string[]): void { + const map = this.indices.get(accountId) + if (!map || uids.length === 0) return + for (const uid of uids) { + map.delete(this.key(folderId, uid)) + } + this.scheduleSave(accountId) + } + + removeAccount(accountId: string): void { + this.indices.delete(accountId) + const timer = this.saveTimers.get(accountId) + if (timer) { + clearTimeout(timer) + this.saveTimers.delete(accountId) + } + unlink(this.filePath(accountId)).catch(() => {}) + } + + search(accountId: string, rawQuery: string, limit: number): MessageEnvelope[] { + const map = this.indices.get(accountId) + if (!map) return [] + const query = parseSearchQuery(rawQuery) + if (!query.term) return [] + const lowerTerm = query.term.toLowerCase() + + const matches: MessageEnvelope[] = [] + for (const msg of map.values()) { + if (this.matches(msg, query.field, lowerTerm)) matches.push(msg) + } + matches.sort((a, b) => (a.date < b.date ? 1 : -1)) + return matches.slice(0, limit) + } + + async flush(accountId: string): Promise { + const timer = this.saveTimers.get(accountId) + if (timer) { + clearTimeout(timer) + this.saveTimers.delete(accountId) + } + await this.persist(accountId) + } + + private matches(msg: MessageEnvelope, field: SearchField | null, lowerTerm: string): boolean { + const matchesAddress = (addr: Address): boolean => + addr.name.toLowerCase().includes(lowerTerm) || addr.email.toLowerCase().includes(lowerTerm) + const matchesAddressList = (list: Address[]): boolean => list.some(matchesAddress) + const matchesSubject = (): boolean => msg.subject.toLowerCase().includes(lowerTerm) + + switch (field) { + case 'from': return matchesAddress(msg.from) + case 'to': return matchesAddressList(msg.to) + case 'cc': return matchesAddressList(msg.cc) + case 'subject': return matchesSubject() + default: + return matchesSubject() || matchesAddress(msg.from) || matchesAddressList(msg.to) || matchesAddressList(msg.cc) + } + } + + private scheduleSave(accountId: string): void { + const existing = this.saveTimers.get(accountId) + if (existing) clearTimeout(existing) + const timer = setTimeout(() => { + this.saveTimers.delete(accountId) + this.persist(accountId).catch((err) => console.warn('[SearchIndexStore] save failed:', err)) + }, SAVE_DEBOUNCE_MS) + this.saveTimers.set(accountId, timer) + } + + private async persist(accountId: string): Promise { + const map = this.indices.get(accountId) + if (!map) return + if (!existsSync(this.dir)) mkdirSync(this.dir, { recursive: true }) + await writeFile(this.filePath(accountId), JSON.stringify([...map.values()]), 'utf-8') + } + + private filePath(accountId: string): string { + return join(this.dir, `${accountId}.json`) + } + + private key(folderId: string, uid: string): string { + return `${folderId}:${uid}` + } +} diff --git a/src/renderer/src/components/messages/MessageList.vue b/src/renderer/src/components/messages/MessageList.vue index 310d010..2d4d943 100644 --- a/src/renderer/src/components/messages/MessageList.vue +++ b/src/renderer/src/components/messages/MessageList.vue @@ -62,6 +62,10 @@ function onSearchKeydown(e: KeyboardEvent): void { async function selectSearchResult(envelope: MessageEnvelope): Promise { foldersStore.setActiveFolder(envelope.folderId) + // Смена activeFolderId запускает watcher в messages.store, который сбрасывает + // selectedMessageId/messageBody (обычная навигация по папкам). Ждём его отработки — + // иначе он затирает выбор письма, который мы выставляем ниже, и превью не открывается. + await nextTick() await messagesStore.selectMessage(envelope.id) } @@ -94,6 +98,15 @@ onUnmounted(() => { if (searchDebounce) clearTimeout(searchDebounce) }) +const isIndexBuilding = computed(() => messagesStore.indexStatus?.state === 'syncing') +const indexProgressText = computed(() => { + const status = messagesStore.indexStatus + if (!status || status.state !== 'syncing') return '' + return status.total > 0 + ? `Идёт индексация писем: ${status.indexed} из ${status.total}` + : 'Идёт индексация писем…' +}) + const folderName = computed(() => foldersStore.activeFolder?.name ?? '') const hasSelected = computed(() => messagesStore.selectedIds.size > 0) const activeUnread = computed(() => { @@ -401,13 +414,18 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis :class="{ 'search-pill--open': searchOpen }" @click="!searchOpen && openSearch()" > - +