import type { ImapFlow } from 'imapflow' import type { InboxClient } from '../services/inbox-watcher' import type { MessageEnvelope } from '@shared/types/message' import type { MailCursor } from '@shared/types/mail-cursor' import { convertImapMessage } from '../lib/imap-message' export class ImapInboxClientAdapter implements InboxClient { private folderId: string = 'INBOX' constructor(private readonly client: ImapFlow) {} async connect(): Promise { await this.client.connect() } async selectInbox(): Promise { const mailbox = await this.client.mailboxOpen('INBOX', { readOnly: true }) this.folderId = mailbox.path if (!this.client.capabilities.has('IDLE')) console.info('[InboxWatcher] Сервер не поддерживает IDLE, используется резервная проверка') return { uidValidity: mailbox.uidValidity.toString(), nextUid: mailbox.uidNext } } async fetchAfter(uid: number, limit: number): Promise { const lock = await this.client.getMailboxLock(this.folderId, { readOnly: true }) try { const found = await this.client.search({ uid: `${uid + 1}:*` }, { uid: true }) const page: number[] = (found || []).filter((value: number): boolean => value > uid) .sort((first, second) => first - second).slice(0, limit) if (!page.length) return [] const messages: MessageEnvelope[] = [] for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, internalDate: true, flags: true, bodyStructure: true }, { uid: true })) { messages.push(convertImapMessage(message, this.folderId)) } return messages } finally { lock.release() } } onChange(callback: () => void): void { this.client.on('exists', callback) } onDisconnect(callback: (error: Error) => void): void { this.client.on('error', callback) this.client.on('close', (): void => callback(new Error('Соединение наблюдения за входящими закрыто'))) } close(): void { this.client.close() } }