diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 2732bfe..7c0e4c9 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -20,6 +20,16 @@ export default defineConfig({ '@shared': resolve('src/shared'), '@main': resolve('src/main') } + }, + build: { + rollupOptions: { + // retention-worker — отдельная точка входа: запускается через worker_threads + // как самостоятельный .js-файл, а не импортируется из index.ts + input: { + index: resolve('src/main/index.ts'), + 'workers/retention-worker': resolve('src/main/workers/retention-worker.ts') + } + } } }, preload: { diff --git a/src/main/index.ts b/src/main/index.ts index 93bc3fa..24b7c00 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -3,15 +3,18 @@ import { join, basename } from 'node:path' import { statSync, mkdirSync, copyFileSync, writeFileSync, readdirSync, unlinkSync, existsSync } from 'node:fs' import { homedir } from 'node:os' import { AccountManager } from './services/account-manager' +import { RetentionService } from './services/retention-service' 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 { updater } from './services/updater' import type { ComposeSession } from '@shared/types/message' const accountManager = new AccountManager() +const retentionService = new RetentionService(accountManager) // ── Compose windows ─────────────────────────────────────── // webContentsId → session, заполняется до loadURL, читается окном при монтировании @@ -95,6 +98,7 @@ function createWindow(): BrowserWindow { }) accountManager.setMainWindow(mainWindow) + retentionService.setMainWindow(mainWindow) // Разрешаем Web Notifications API из renderer mainWindow.webContents.session.setPermissionRequestHandler((_wc, permission, callback) => { @@ -195,11 +199,12 @@ app.whenReady().then(async () => { await accountManager.initialize() // Register all IPC handlers - registerAccountHandlers(accountManager) + registerAccountHandlers(accountManager, retentionService) registerFolderHandlers(accountManager) registerMessageHandlers(accountManager) registerCalendarHandlers(accountManager) registerUpdaterHandlers() + registerRetentionHandlers(retentionService) createWindow() @@ -219,3 +224,7 @@ app.on('window-all-closed', () => { app.quit() } }) + +app.on('before-quit', () => { + retentionService.dispose() +}) diff --git a/src/main/ipc/accounts.handler.ts b/src/main/ipc/accounts.handler.ts index 169f757..623df88 100644 --- a/src/main/ipc/accounts.handler.ts +++ b/src/main/ipc/accounts.handler.ts @@ -1,8 +1,9 @@ import { registerHandler } from './registry' import type { AccountManager } from '../services/account-manager' +import type { RetentionService } from '../services/retention-service' import { safeStorage } from 'electron' -export function registerAccountHandlers(manager: AccountManager): void { +export function registerAccountHandlers(manager: AccountManager, retentionService: RetentionService): void { registerHandler('app:isEncryptionAvailable', async () => { return safeStorage.isEncryptionAvailable() }) @@ -16,6 +17,7 @@ export function registerAccountHandlers(manager: AccountManager): void { registerHandler('accounts:remove', async ({ accountId }) => { await manager.removeAccount(accountId) + retentionService.removeRulesForAccount(accountId) }) registerHandler('accounts:test', async (config) => { diff --git a/src/main/ipc/retention.handler.ts b/src/main/ipc/retention.handler.ts new file mode 100644 index 0000000..12dd559 --- /dev/null +++ b/src/main/ipc/retention.handler.ts @@ -0,0 +1,37 @@ +import { registerHandler } from './registry' +import type { RetentionService } from '../services/retention-service' + +function assertId(value: unknown, name: string): asserts value is string { + if (typeof value !== 'string' || value.length === 0) { + throw new Error(`Invalid IPC argument: ${name} must be a non-empty string`) + } +} + +export function registerRetentionHandlers(retentionService: RetentionService): void { + registerHandler('retention:list', async ({ accountId }) => { + assertId(accountId, 'accountId') + return retentionService.listRules(accountId) + }) + + registerHandler('retention:set', async (rule) => { + assertId(rule.accountId, 'accountId') + assertId(rule.folderId, 'folderId') + if (!Number.isInteger(rule.maxMessages) || rule.maxMessages < 1) { + throw new Error('Invalid IPC argument: maxMessages must be a positive integer') + } + retentionService.setRule(rule) + }) + + registerHandler('retention:remove', async ({ accountId, folderId }) => { + assertId(accountId, 'accountId') + assertId(folderId, 'folderId') + retentionService.removeRule(accountId, folderId) + }) + + registerHandler('retention:setCheckInterval', async ({ minutes }) => { + if (typeof minutes !== 'number' || minutes < 0) { + throw new Error('Invalid IPC argument: minutes must be a non-negative number') + } + retentionService.setCheckInterval(minutes) + }) +} diff --git a/src/main/providers/imap.provider.ts b/src/main/providers/imap.provider.ts index c21e9e4..796e11d 100644 --- a/src/main/providers/imap.provider.ts +++ b/src/main/providers/imap.provider.ts @@ -6,6 +6,7 @@ import type { MessageBody, MessageFlags, MessageEnvelope, Address, ComposeData, 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' // imapflow MailboxObject type @@ -305,6 +306,64 @@ export class ImapProvider implements IEmailProvider { } } + async enforceRetention(rules: FolderRetentionRule[]): Promise { + if (rules.length === 0) return [] + const tree = await this.client.listTree() as { folders?: ImapMailbox[] } + const folders = this.convertMailboxArray(tree.folders ?? []) + const results: RetentionCleanupResult[] = [] + await this.enforceRetentionTree(folders, rules, null, results) + return results + } + + // inheritedLimit — лимит, унаследованный от ближайшего предка с recursive: true (null — нет ограничения) + private async enforceRetentionTree( + folders: Folder[], + rules: FolderRetentionRule[], + inheritedLimit: number | null, + results: RetentionCleanupResult[] + ): Promise { + for (const folder of folders) { + const ownRule = rules.find((r) => r.folderId === folder.id) + const effectiveLimit = ownRule ? ownRule.maxMessages : inheritedLimit + + if (effectiveLimit !== null) { + try { + const deletedCount = await this.trimFolder(folder.id, effectiveLimit) + if (deletedCount > 0) results.push({ folderId: folder.id, deletedCount }) + } catch (err) { + console.warn(`[IMAP:retention] folder error ${folder.id}:`, (err as Error).message) + } + } + + const childInheritedLimit = ownRule ? (ownRule.recursive ? ownRule.maxMessages : null) : inheritedLimit + if (folder.children.length > 0) { + await this.enforceRetentionTree(folder.children, rules, childInheritedLimit, results) + } + } + } + + // Удаляет самые старые письма сверх maxMessages. Сортировка по sequence number — + // тот же порядок "старое → новое", что используется в listMessages. + 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 + + 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 + + await this.client.messageDelete(uidsToDelete.join(','), { uid: true }) + return uidsToDelete.length + } finally { + lock.release() + } + } + async sendMessage(compose: ComposeData): Promise { const creds = this.config.credentials as ImapCredentials diff --git a/src/main/services/account-manager.ts b/src/main/services/account-manager.ts index cddebb9..21b9b73 100644 --- a/src/main/services/account-manager.ts +++ b/src/main/services/account-manager.ts @@ -4,6 +4,7 @@ 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' @@ -216,6 +217,16 @@ export class AccountManager { ) } + getConnectedAccountIds(): string[] { + return [...this.providers.keys()] + } + + async enforceRetention(accountId: string, rules: FolderRetentionRule[]): Promise { + return this.withAutoReconnect(accountId, () => + this.getProvider(accountId).enforceRetention(rules) + ) + } + // ── Calendar ──────────────────────────────────────────── async listCalendars(accountId: string): Promise { diff --git a/src/main/services/retention-service.ts b/src/main/services/retention-service.ts new file mode 100644 index 0000000..d709858 --- /dev/null +++ b/src/main/services/retention-service.ts @@ -0,0 +1,79 @@ +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 { + // Тики могут прийти чаще, чем успевает отработать предыдущая проверка (медленная сеть) — пропускаем внахлёст + 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 + } + } +} diff --git a/src/main/services/retention-store.ts b/src/main/services/retention-store.ts new file mode 100644 index 0000000..70bf5c2 --- /dev/null +++ b/src/main/services/retention-store.ts @@ -0,0 +1,46 @@ +import Store from 'electron-store' +import type { FolderRetentionRule } from '@shared/types/retention' + +interface RetentionStoreSchema { + rules: FolderRetentionRule[] +} + +export class RetentionStore { + private store: Store + + constructor() { + this.store = new Store({ + name: 'retention-rules', + defaults: { rules: [] } + }) + } + + getAll(): FolderRetentionRule[] { + return this.store.get('rules', []) + } + + getForAccount(accountId: string): FolderRetentionRule[] { + return this.getAll().filter((r) => r.accountId === accountId) + } + + set(rule: FolderRetentionRule): void { + const rules = this.getAll() + const idx = rules.findIndex((r) => r.accountId === rule.accountId && r.folderId === rule.folderId) + if (idx === -1) { + rules.push(rule) + } else { + rules[idx] = rule + } + this.store.set('rules', rules) + } + + remove(accountId: string, folderId: string): void { + const rules = this.getAll().filter((r) => !(r.accountId === accountId && r.folderId === folderId)) + this.store.set('rules', rules) + } + + removeForAccount(accountId: string): void { + const rules = this.getAll().filter((r) => r.accountId !== accountId) + this.store.set('rules', rules) + } +} diff --git a/src/main/workers/retention-worker.ts b/src/main/workers/retention-worker.ts new file mode 100644 index 0000000..36b6e53 --- /dev/null +++ b/src/main/workers/retention-worker.ts @@ -0,0 +1,28 @@ +import { parentPort } from 'node:worker_threads' + +// Отдельный поток: только тикающий таймер, никакой работы с IMAP здесь не делаем — +// imapflow-соединения и расшифрованные credentials живут в main-потоке (AccountManager), +// worker_threads не имеют доступа к Electron API (safeStorage и т.п.), поэтому реальная +// очистка выполняется в RetentionService по сигналу тика. +type WorkerMessage = + | { type: 'setInterval'; intervalMinutes: number } + +let timer: ReturnType | null = null + +function applyInterval(intervalMinutes: number): void { + if (timer) { + clearInterval(timer) + timer = null + } + if (intervalMinutes > 0) { + timer = setInterval(() => { + parentPort?.postMessage({ type: 'tick' }) + }, intervalMinutes * 60_000) + } +} + +parentPort?.on('message', (msg: WorkerMessage) => { + if (msg.type === 'setInterval') { + applyInterval(msg.intervalMinutes) + } +}) diff --git a/src/renderer/src/App.vue b/src/renderer/src/App.vue index c77d11a..e723914 100644 --- a/src/renderer/src/App.vue +++ b/src/renderer/src/App.vue @@ -2,12 +2,16 @@ import { onMounted, onUnmounted, watch } from 'vue' import { useAccountsStore } from './stores/accounts.store' import { useSettingsStore } from './stores/settings.store' +import { useFoldersStore } from './stores/folders.store' +import { useMessagesStore } from './stores/messages.store' import { useIpc } from './composables/useIpc' import UpdateBanner from './components/UpdateBanner.vue' const accountsStore = useAccountsStore() const settingsStore = useSettingsStore() -const { invoke } = useIpc() +const foldersStore = useFoldersStore() +const messagesStore = useMessagesStore() +const { invoke, on } = useIpc() onMounted(() => { accountsStore.loadAccounts() @@ -35,6 +39,30 @@ function restartPollTimer(): void { watch(() => settingsStore.autoCheckInterval, restartPollTimer) onMounted(restartPollTimer) onUnmounted(() => { if (pollTimer) clearInterval(pollTimer) }) + +// ── Лимит хранения писем: интервал проверки — тот же, что для проверки почты ── +// Тикает в отдельном worker-потоке main-процесса (RetentionService) +function pushRetentionInterval(): void { + invoke('retention:setCheckInterval', { minutes: settingsStore.autoCheckInterval }).catch(() => {}) +} + +watch(() => settingsStore.autoCheckInterval, pushRetentionInterval) +onMounted(pushRetentionInterval) + +let unsubRetentionCleaned: (() => void) | null = null + +onMounted(() => { + unsubRetentionCleaned = on('retention:cleaned', ({ accountId, results }) => { + foldersStore.refreshUnreadCounts(accountId) + if (accountsStore.activeAccountId === accountId + && foldersStore.activeFolderId + && results.some((r) => r.folderId === foldersStore.activeFolderId)) { + messagesStore.loadMessages(accountId, foldersStore.activeFolderId, 0) + } + }) +}) + +onUnmounted(() => { unsubRetentionCleaned?.() }) diff --git a/src/renderer/src/components/sidebar/FolderTreeItem.vue b/src/renderer/src/components/sidebar/FolderTreeItem.vue index 6a14ef0..4beba2e 100644 --- a/src/renderer/src/components/sidebar/FolderTreeItem.vue +++ b/src/renderer/src/components/sidebar/FolderTreeItem.vue @@ -6,9 +6,11 @@ import { useFoldersStore } from '../../stores/folders.store' import { useAccountsStore } from '../../stores/accounts.store' import { useNotificationsStore } from '../../stores/notifications.store' import { useMessagesStore } from '../../stores/messages.store' +import { useRetentionStore } from '../../stores/retention.store' import AppIcon from '../AppIcon.vue' import type { IconName } from '../AppIcon.vue' import FolderContextMenu from './FolderContextMenu.vue' +import RetentionLimitDialog from './RetentionLimitDialog.vue' const props = defineProps<{ folder: Folder @@ -19,8 +21,10 @@ const foldersStore = useFoldersStore() const accountsStore = useAccountsStore() const notificationsStore = useNotificationsStore() const messagesStore = useMessagesStore() +const retentionStore = useRetentionStore() const expanded = ref(true) const contextMenu = ref<{ x: number; y: number } | null>(null) +const showRetentionDialog = ref(false) const isActive = computed(() => foldersStore.activeFolderId === props.folder.id) const hasChildren = computed(() => props.folder.children.length > 0) @@ -32,6 +36,10 @@ const isMuted = computed(() => { if (!accountsStore.activeAccountId) return false return notificationsStore.isMuted(accountsStore.activeAccountId, props.folder.id) }) +const ownRetentionRule = computed(() => { + if (!accountsStore.activeAccountId) return null + return retentionStore.getOwnRule(accountsStore.activeAccountId, props.folder.id) +}) const folderIcon = computed((): IconName => { switch (props.folder.role) { @@ -83,6 +91,25 @@ function handleMarkAllRead(): void { } contextMenu.value = null } + +function handleEditRetention(): void { + contextMenu.value = null + showRetentionDialog.value = true +} + +function handleRemoveRetention(): void { + if (accountsStore.activeAccountId) { + retentionStore.removeRule(accountsStore.activeAccountId, props.folder.id) + } + contextMenu.value = null +} + +function handleSaveRetention(maxMessages: number, recursive: boolean): void { + if (accountsStore.activeAccountId) { + retentionStore.setRule(accountsStore.activeAccountId, props.folder.id, maxMessages, recursive) + } + showRetentionDialog.value = false +}