aero-mail/src/main/providers/imap.provider.ts

861 lines
34 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { getAccountEmail } from '@shared/utils/account-email'
import { SmtpSendError } from '../lib/smtp-error'
import { buildComposeAttachments } from '../lib/compose-attachments'
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 { 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
interface ImapMailbox {
name: string
path: string
specialUse?: string
flags?: Set<string>
folders?: ImapMailbox[]
}
// imapflow BodyStructure type
interface BodyPart {
part?: string
type?: string
subtype?: string
disposition?: string
parameters?: Record<string, string>
id?: string
encoding?: string
childNodes?: BodyPart[]
}
export class ImapProvider implements IEmailProvider {
private client: ImapFlow
private connected = false
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
private closeCallback: (() => void) | null = null
// folderId → last known unseen count for polling
private lastUnseenCount = new Map<string, number>()
// uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message
private notifiedUids = new Map<string, number>()
private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes
// Промис с именем отправителя из Sent-папки; await-ится в sendMessage()
private senderNamePromise: Promise<string | null> = Promise.resolve(null)
constructor(private config: AccountConfig) {
const creds = config.credentials as ImapCredentials
this.client = new ImapFlow({
host: creds.host,
port: creds.port,
secure: creds.secure,
auth: {
user: creds.username,
pass: creds.password
},
logger: false
})
// Без слушателя 'error' обрыв сокета превращается в uncaught exception в main
this.client.on('error', (err: Error) => {
console.warn('[IMAP] connection error:', err.message)
this.connected = false
})
this.client.on('close', () => {
this.connected = false
this.closeCallback?.()
})
}
onClose(callback: () => void): void {
this.closeCallback = callback
}
getUnseenCounts(): Map<string, number> {
return new Map(this.lastUnseenCount)
}
seedUnseenCounts(counts: Map<string, number>): void {
for (const [path, count] of counts) {
if (!this.lastUnseenCount.has(path)) this.lastUnseenCount.set(path, count)
}
}
async connect(): Promise<void> {
let timeoutId: ReturnType<typeof setTimeout> | undefined
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
})
try {
await Promise.race([this.client.connect(), timeoutPromise])
} catch (err) {
// Close any socket imapflow opened or is opening (timeout race case)
this.client.logout().catch(() => {})
throw err
} finally {
clearTimeout(timeoutId)
}
this.connected = true
// Запускаем в фоне; промис await-ится в sendMessage() — гарантия что имя готово к отправке
this.senderNamePromise = this.fetchSenderName().catch(() => null)
}
async disconnect(): Promise<void> {
this.closeCallback = null // штатное закрытие не должно запускать реконнект
this.offNewMail()
if (this.connected) {
try {
await this.client.logout()
} catch { /* ignore */ }
this.connected = false
}
}
isConnected(): boolean {
return this.connected
}
async listFolders(): Promise<FolderListResult> {
// listTree() returns { root: true, folders: ImapMailbox[] }
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
const folders = this.convertMailboxArray(tree.folders ?? [])
await this.populateUnreadCounts(folders)
return { folders }
}
private async populateUnreadCounts(folders: Folder[]): Promise<void> {
// Собираем все папки в плоский список (включая вложенные)
const flatten = (list: Folder[]): Folder[] =>
list.flatMap((f) => [f, ...flatten(f.children)])
const all = flatten(folders)
// Параллельные STATUS запросы с concurrency limit 5
const CONCURRENCY = 5
for (let i = 0; i < all.length; i += CONCURRENCY) {
const batch = all.slice(i, i + CONCURRENCY)
await Promise.all(
batch.map(async (folder) => {
if (folder.selectable === false) return
try {
const status = await this.client.status(folder.id, { unseen: true, messages: true, uidNext: true, uidValidity: true }) as
{ unseen?: number; messages?: number; uidNext?: number; uidValidity?: bigint } | null
if (status) {
folder.unreadCount = status.unseen ?? 0
folder.totalCount = status.messages ?? 0
folder.uidNext = status.uidNext
folder.uidValidity = status.uidValidity?.toString()
} else {
folder.statusError = 'Сервер не вернул статус папки'
}
} catch (error: unknown) {
folder.statusError = error instanceof Error ? error.message : String(error)
}
})
)
}
}
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
const lock = await this.client.getMailboxLock(options.folderId)
try {
if (options.unseenOnly) {
return await this.listUnseenMessages(options)
}
const total = (this.client.mailbox as { exists?: number })?.exists ?? 0
if (total === 0) return { messages: [], total: 0, unseen: 0 }
// IMAP sequence numbers are 1-based, newest = highest number
const end = Math.max(1, total - options.offset)
const start = Math.max(1, end - options.limit + 1)
if (start > total) return { messages: [], total, unseen: 0 }
const messages: MessageEnvelope[] = []
for await (const msg of this.client.fetch(`${start}:${end}`, {
uid: true,
envelope: true,
flags: true,
bodyStructure: true
})) {
messages.push(this.convertMessage(msg, options.folderId))
}
// Newest first
messages.reverse()
return { messages, total, unseen: 0 }
} finally {
lock.release()
}
}
private async listUnseenMessages(options: MessageListOptions): Promise<MessageListResult> {
// Mailbox lock is already held by listMessages caller
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
if (!uids || uids.length === 0) return { messages: [], total: 0, unseen: 0 }
const total = uids.length
// Sort descending — higher UID = newer message
const sorted = [...uids].sort((a, b) => b - a)
const page = sorted.slice(options.offset, options.offset + options.limit)
if (page.length === 0) return { messages: [], total, unseen: total }
const uidSet = page.join(',')
const messages: MessageEnvelope[] = []
for await (const msg of this.client.fetch(uidSet, {
uid: true,
envelope: true,
flags: true,
bodyStructure: true
}, { uid: true })) {
messages.push(this.convertMessage(msg, options.folderId))
}
// Fetch returns ascending order → reverse to newest first
messages.sort((a, b) => Number(b.id) - Number(a.id))
return { messages, total, unseen: total }
}
async listMessagesAfterUid(folderId: string, afterUid: number, limit: number): Promise<MessageListResult> {
const lock = await this.client.getMailboxLock(folderId)
try {
const found = await this.client.search({ uid: `${afterUid + 1}:*` }, { uid: true })
const uids: number[] = (found || []).filter((uid: number): boolean => uid > afterUid).sort((first: number, second: number): number => first - second)
const page: number[] = uids.slice(0, limit)
if (!page.length) return { messages: [], total: 0, unseen: 0 }
const messages: MessageEnvelope[] = []
for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, flags: true, bodyStructure: true }, { uid: true })) {
messages.push(this.convertMessage(message, folderId))
}
messages.sort((first: MessageEnvelope, second: MessageEnvelope): number => Number(first.id) - Number(second.id))
return { messages, total: uids.length, unseen: messages.filter((message: MessageEnvelope): boolean => !message.flags.seen).length }
} finally { lock.release() }
}
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
const lock = await this.client.getMailboxLock(folderId)
try {
// imapflow использует BODY.PEEK[] (не BODY[]) для source-запросов — \Seen не ставится
const download = await this.client.download(messageId, undefined, { uid: true })
if (!download?.content) {
return { id: messageId, html: null, text: null, references: null, inlineImages: [], attachments: [] }
}
const parsed = await simpleParser(download.content)
const inlineImages: InlineImage[] = []
const attachments: Attachment[] = []
for (const att of parsed.attachments) {
if (att.contentDisposition === 'inline' && att.contentId && att.contentType.startsWith('image/')) {
inlineImages.push({
cid: att.contentId.replace(/[<>]/g, ''),
contentType: att.contentType,
data: att.content.toString('base64')
})
} else if (att.contentDisposition === 'attachment' || att.filename) {
attachments.push({
id: att.checksum ?? att.filename ?? '',
filename: att.filename ?? 'attachment',
contentType: att.contentType,
size: att.size ?? 0
})
}
}
// References header: mailparser returns string[] — join to space-separated string
const refsArray = (parsed as unknown as { references?: string | string[] }).references
const references = Array.isArray(refsArray)
? refsArray.join(' ')
: (typeof refsArray === 'string' ? refsArray : null)
const sanitizedHtml = parsed.html ? sanitizeHtml(parsed.html) : null
// Если text/plain части нет — деривируем из HTML (правильно: style/script уже отфильтрованы)
const text = parsed.text ?? (parsed.html ? this.htmlToPlainText(parsed.html) : null)
return {
id: messageId,
html: sanitizedHtml,
text,
references,
inlineImages,
attachments
}
} finally {
lock.release()
}
}
async downloadAttachment(folderId: string, messageId: string, attachmentId: string): Promise<Buffer> {
// TODO: имапфлоу поддерживает частичный download по part-номеру из BODYSTRUCTURE
// (client.download(uid, '2', {uid:true})). Оптимизация требует хранить part в Attachment.id
// и пробрасывать через IPC. Сейчас скачивается всё письмо целиком.
const lock = await this.client.getMailboxLock(folderId)
try {
const download = await this.client.download(messageId, undefined, { uid: true })
if (!download) throw new Error('Message not found')
const parsed = await simpleParser(download.content)
const att = parsed.attachments.find(
(a) => (a.checksum ?? a.filename ?? '') === attachmentId || a.filename === attachmentId
)
if (!att) throw new Error('Attachment not found')
return att.content
} finally {
lock.release()
}
}
async updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void> {
const lock = await this.client.getMailboxLock(folderId)
try {
const uidSet = messageIds.join(',')
const addFlags: string[] = []
const removeFlags: string[] = []
if (flags.seen === true) addFlags.push('\\Seen')
if (flags.seen === false) removeFlags.push('\\Seen')
if (flags.flagged === true) addFlags.push('\\Flagged')
if (flags.flagged === false) removeFlags.push('\\Flagged')
if (flags.answered === true) addFlags.push('\\Answered')
if (flags.deleted === true) addFlags.push('\\Deleted')
if (addFlags.length > 0) {
await this.client.messageFlagsAdd(uidSet, addFlags, { uid: true })
}
if (removeFlags.length > 0) {
await this.client.messageFlagsRemove(uidSet, removeFlags, { uid: true })
}
} finally {
lock.release()
}
}
async markAllRead(folderId: string): Promise<void> {
const lock = await this.client.getMailboxLock(folderId)
try {
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
if (!uids || uids.length === 0) return
await this.client.messageFlagsAdd(uids.join(','), ['\\Seen'], { uid: true })
} finally {
lock.release()
}
}
async deleteMessages(folderId: string, messageIds: string[]): Promise<void> {
const lock = await this.client.getMailboxLock(folderId)
try {
const uidSet = messageIds.join(',')
await this.client.messageDelete(uidSet, { uid: true })
} finally {
lock.release()
}
}
async enforceRetention(rules: FolderRetentionRule[]): Promise<RetentionCleanupResult[]> {
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<void> {
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<number> {
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<void> {
const creds = this.config.credentials as ImapCredentials
// SMTP-настройки: явные или авто-вывод из IMAP-хоста
const smtpHost = creds.smtpHost ?? creds.host.replace(/^imap\./i, 'smtp.')
const smtpPort = creds.smtpPort ?? 587
const smtpSecure = creds.smtpSecure ?? smtpPort === 465
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpSecure,
auth: { user: creds.username, pass: creds.password },
tls: creds.smtpAllowSelfSigned ? { rejectUnauthorized: false } : undefined
})
// Если email хранится без домена (только логин) — достраиваем из IMAP-хоста
const emailAddress = getAccountEmail(this.config)
// Имя отправителя: await-им промис из connect() — гарантирует что имя готово
const senderName = await this.senderNamePromise
const displayName = senderName ?? this.config.label
const from = displayName
? { name: displayName, address: emailAddress }
: emailAddress
// Собираем text + html из отдельных частей
const fullText = compose.quotedText
? compose.body + '\n\n' + compose.quotedText
: compose.body
const fullHtml = ImapProvider.buildComposeHtml(compose)
if (process.env.NODE_ENV !== 'production') {
console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j',
smtpHost, smtpPort, smtpSecure, from, compose.to)
}
const info = await transporter.sendMail({
from,
to: compose.to.join(', '),
cc: compose.cc.length ? compose.cc.join(', ') : undefined,
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
subject: compose.subject,
text: fullText,
html: fullHtml,
inReplyTo: compose.inReplyTo,
references: compose.references,
attachments: buildComposeAttachments(compose)
}).catch((error: unknown): never => {
throw new SmtpSendError(error, creds)
})
// Сохраняем в папку Sent (best-effort)
try {
const raw = await this.buildRawMessage(info.messageId ?? '', compose, from)
const sentFolder = await this.findSentFolder()
if (sentFolder && raw) {
await this.client.append(sentFolder, raw, ['\\Seen'])
}
} catch { /* не критично — письмо уже отправлено */ }
}
private async findSentFolder(): Promise<string | null> {
try {
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
return this.findFolderByRole(tree.folders ?? [], SpecialFolderRole.Sent)
} catch { return null }
}
private findFolderByRole(folders: ImapMailbox[], role: SpecialFolderRole): string | null {
for (const f of folders) {
const detected = this.detectFolderRole(f.specialUse, f.name)
if (detected === role) return f.path
if (f.folders?.length) {
const found = this.findFolderByRole(f.folders, role)
if (found) return found
}
}
return null
}
private async buildRawMessage(
messageId: string,
compose: ComposeData,
from: string | { name: string; address: string }
): Promise<Buffer | null> {
try {
const transporter = nodemailer.createTransport({ streamTransport: true, newline: 'unix' })
const fullText = compose.quotedText
? compose.body + '\n\n' + compose.quotedText
: compose.body
const fullHtml = ImapProvider.buildComposeHtml(compose)
const mail = await transporter.sendMail({
from,
to: compose.to.join(', '),
cc: compose.cc.length ? compose.cc.join(', ') : undefined,
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
subject: compose.subject,
text: fullText,
html: fullHtml,
messageId,
inReplyTo: compose.inReplyTo,
references: compose.references,
date: new Date(),
attachments: buildComposeAttachments(compose)
})
const chunks: Buffer[] = []
await new Promise<void>((res, rej) => {
;(mail.message as NodeJS.ReadableStream).on('data', (c: Buffer) => chunks.push(c))
;(mail.message as NodeJS.ReadableStream).on('end', res)
;(mail.message as NodeJS.ReadableStream).on('error', rej)
})
return Buffer.concat(chunks)
} catch { return null }
}
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
this.newMailCallback = callback
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
// Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо)
if (data.prevCount > 0 && data.count > data.prevCount) {
// Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения
this.pollSingleFolder(data.path).catch(() => {})
}
})
}
offNewMail(): void {
this.newMailCallback = null
this.client.removeAllListeners('exists')
}
async searchMessages(query: string, limit: number): Promise<MessageEnvelope[]> {
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<void> {
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<ReturnType<typeof this.client.getMailboxLock>> | 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<void> {
if (!this.newMailCallback) return
// Ошибки не глотаем: AccountManager по ним переподключается (withAutoReconnect)
if (!this.connected) throw Object.assign(new Error('IMAP connection lost'), { code: 'NoConnection' })
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
await this.pollFolderTree(tree.folders ?? [])
}
// Немедленная проверка одной папки — вызывается из exists-события
private async pollSingleFolder(folderPath: string): Promise<void> {
if (!this.newMailCallback) return
try {
await this.pollFolderTree([{ name: folderPath, path: folderPath }])
} catch { /* ignore */ }
}
private async pollFolderTree(folders: ImapMailbox[]): Promise<void> {
for (const folder of folders) {
try {
const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null
// Если STATUS вернул null или упал — не трогаем сохранённый счётчик
if (status) {
const unseen = status.unseen ?? 0
const prev = this.lastUnseenCount.get(folder.path)
this.lastUnseenCount.set(folder.path, unseen)
if (prev !== undefined && unseen > prev && this.newMailCallback) {
// Получаем последнее непрочитанное письмо для уведомления
const lock = await this.client.getMailboxLock(folder.path)
try {
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
if (uids?.length) {
const latestUid = Math.max(...uids).toString()
const dedupKey = `${folder.path}:${latestUid}`
if (!this.isRecentlyNotified(dedupKey)) {
for await (const msg of this.client.fetch(latestUid, {
uid: true, envelope: true, flags: true
}, { uid: true })) {
this.markNotified(dedupKey)
this.newMailCallback(folder.path, this.convertMessage(msg, folder.path))
break
}
}
}
} finally {
lock.release()
}
}
}
} catch (err) {
// Соединение умерло — не перебираем остальные папки с той же ошибкой
if (!this.connected) throw err
console.warn(`[IMAP] pollFolderTree error for ${folder.path}:`, (err as Error).message)
}
if (folder.folders?.length) {
await this.pollFolderTree(folder.folders)
}
}
}
private isRecentlyNotified(key: string): boolean {
const expiry = this.notifiedUids.get(key)
if (expiry === undefined) return false
if (Date.now() < expiry) return true
this.notifiedUids.delete(key)
return false
}
private markNotified(key: string): void {
// Чистим старые записи при росте кэша
if (this.notifiedUids.size > 200) {
const now = Date.now()
for (const [k, exp] of this.notifiedUids) {
if (now >= exp) this.notifiedUids.delete(k)
}
}
this.notifiedUids.set(key, Date.now() + ImapProvider.NOTIF_TTL_MS)
}
// ---- Private helpers ----
private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] {
return mailboxes.map((mb) => ({
id: mb.path,
name: mb.name,
role: this.detectFolderRole(mb.specialUse, mb.name),
selectable: !mb.flags?.has('\\Noselect'),
parentId,
unreadCount: 0,
totalCount: 0,
children: mb.folders ? this.convertMailboxArray(mb.folders, mb.path) : []
}))
}
private detectFolderRole(specialUse?: string, name?: string): SpecialFolderRole {
if (specialUse) {
const u = specialUse.toLowerCase()
if (u.includes('inbox')) return SpecialFolderRole.Inbox
if (u.includes('sent')) return SpecialFolderRole.Sent
if (u.includes('draft')) return SpecialFolderRole.Drafts
if (u.includes('trash') || u.includes('deleted')) return SpecialFolderRole.Trash
if (u.includes('junk') || u.includes('spam')) return SpecialFolderRole.Spam
if (u.includes('archive') || u.includes('all')) return SpecialFolderRole.Archive
}
if (name) {
const n = name.toLowerCase()
if (n === 'inbox') return SpecialFolderRole.Inbox
if (n === 'sent' || n === 'sent mail' || n === 'sent items') return SpecialFolderRole.Sent
if (n === 'drafts' || n === 'draft') return SpecialFolderRole.Drafts
if (n === 'trash' || n === 'deleted items' || n === 'deleted messages') return SpecialFolderRole.Trash
if (n === 'spam' || n === 'junk' || n === 'junk e-mail') return SpecialFolderRole.Spam
if (n === 'archive' || n === 'all mail') return SpecialFolderRole.Archive
}
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<string>
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<string>()
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,
}
}
private static buildComposeHtml(compose: ComposeData): string | undefined {
if (!compose.contentHtml && !compose.htmlBody) return undefined
const quote: string = compose.htmlBody ?? ImapProvider.textToHtml(compose.quotedText ?? '')
return (compose.contentHtml ?? ImapProvider.textToHtml(compose.body)) + quote
}
private static textToHtml(text: string): string {
if (!text) return ''
const escaped = text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
const paragraphs = escaped.split(/\n\n+/).filter((p) => p.trim())
if (paragraphs.length === 0) return '<p></p>'
return paragraphs
.map((p) => `<p>${p.replace(/\n/g, '<br>')}</p>`)
.join('\n')
}
/**
* Ищет имя отправителя в последнем письме папки Sent.
* Возвращает display name из заголовка From или null если Sent пуста / не найдена.
*/
private async fetchSenderName(): Promise<string | null> {
try {
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
const sentPath = this.findFolderByRole(tree.folders ?? [], SpecialFolderRole.Sent)
if (!sentPath) return null
const status = await this.client.status(sentPath, { messages: true }) as { messages?: number } | null
const total = status?.messages ?? 0
if (total === 0) return null
const lock = await this.client.getMailboxLock(sentPath)
try {
let name: string | null = null
// Берём только самое последнее письмо
for await (const msg of this.client.fetch(`${total}:${total}`, { envelope: true })) {
const fromList = (msg as { envelope?: { from?: Array<{ name?: string }> } }).envelope?.from
const candidate = fromList?.[0]?.name?.trim()
if (candidate) { name = candidate; break }
}
return name
} finally {
lock.release()
}
} catch {
return null
}
}
private htmlToPlainText(html: string): string {
return html
// Убираем целиком блоки <style> и <script> вместе с содержимым
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
// Блочные элементы → переносы строк
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
.replace(/<\/div>/gi, '\n')
.replace(/<\/li>/gi, '\n')
.replace(/<\/tr>/gi, '\n')
.replace(/<\/h[1-6]>/gi, '\n\n')
// Удаляем все оставшиеся теги
.replace(/<[^>]+>/g, '')
// HTML-сущности
.replace(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
// &amp; — последним, чтобы не двойной-декодинг
.replace(/&amp;/g, '&')
// Убираем лишние пустые строки
.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
}
}