aero-mail/src/main/services/retention-service.ts
r.rasputin 69a3c74187 Ограничение количества сообщений в папке
Позволяет задать для папки (рекурсивно — с наследованием вложенными)
лимит хранимых сообщений: старые письма сверх лимита удаляются.
Проверка тикает в отдельном worker-потоке main-процесса с частотой
автопроверки почты, само удаление выполняет main через IMAP.
2026-07-30 12:53:57 +07:00

79 lines
2.6 KiB
TypeScript

import { Worker } from 'node:worker_threads'
import { join } from 'node:path'
import type { BrowserWindow } from 'electron'
import type { FolderRetentionRule } from '@shared/types/retention'
import type { AccountManager } from './account-manager'
import { RetentionStore } from './retention-store'
export class RetentionService {
private worker: Worker
private store = new RetentionStore()
private mainWindow: BrowserWindow | null = null
private checking = false
constructor(private accountManager: AccountManager) {
this.worker = new Worker(join(__dirname, 'workers/retention-worker.js'))
this.worker.on('message', (msg: { type: string }) => {
if (msg.type === 'tick') {
this.runCheck().catch((err) => {
console.error('[RetentionService] check failed:', err)
})
}
})
this.worker.on('error', (err) => {
console.error('[RetentionService] worker error:', err)
})
}
setMainWindow(win: BrowserWindow): void {
this.mainWindow = win
}
setCheckInterval(minutes: number): void {
this.worker.postMessage({ type: 'setInterval', intervalMinutes: minutes })
}
listRules(accountId: string): FolderRetentionRule[] {
return this.store.getForAccount(accountId)
}
setRule(rule: FolderRetentionRule): void {
this.store.set(rule)
}
removeRule(accountId: string, folderId: string): void {
this.store.remove(accountId, folderId)
}
removeRulesForAccount(accountId: string): void {
this.store.removeForAccount(accountId)
}
dispose(): void {
this.worker.terminate().catch(() => {})
}
private async runCheck(): Promise<void> {
// Тики могут прийти чаще, чем успевает отработать предыдущая проверка (медленная сеть) — пропускаем внахлёст
if (this.checking) return
this.checking = true
try {
for (const accountId of this.accountManager.getConnectedAccountIds()) {
const rules = this.store.getForAccount(accountId)
if (rules.length === 0) continue
try {
const results = await this.accountManager.enforceRetention(accountId, rules)
const cleaned = results.filter((r) => r.deletedCount > 0)
if (cleaned.length > 0 && this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.webContents.send('retention:cleaned', { accountId, results: cleaned })
}
} catch (err) {
console.warn(`[RetentionService] enforceRetention failed for ${accountId}:`, (err as Error).message)
}
}
} finally {
this.checking = false
}
}
}