aero-mail/src/main/providers/exchange.provider.ts
d.a.kolesov ab1c084b91 feature/search: поиск писем по всем папкам аккаунта
- IPC-канал messages:search + тип в IpcChannelMap
- IMAP: server-side SEARCH OR SUBJECT FROM по всем папкам
- Gmail: search через API q-параметр
- Exchange: stub (пустой результат)
- messages.store: состояние searchQuery/searchResults/searchLoading + actions search/clearSearch
- Сброс поиска при смене папки
- MessageList: поисковая строка в хедере (Ctrl+F / кнопка)
- Результаты с бейджем папки, дебаунс 300ms, Escape закрывает
- Иконки search/close в AppIcon

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 13:20:16 +07:00

203 lines
6.7 KiB
TypeScript

import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
import type { MessageBody, MessageFlags, MessageEnvelope } from '@shared/types/message'
import type { Folder } from '@shared/types/folder'
import { SpecialFolderRole } from '@shared/types/folder'
import type { AccountConfig, ExchangeCredentials } from '@shared/types/account'
import { sanitizeHtml } from '../lib/html-sanitizer'
// EWS imports
import {
ExchangeService,
ExchangeVersion,
WebCredentials,
Uri,
WellKnownFolderName,
FolderView,
ItemView,
PropertySet,
BasePropertySet,
EmailMessageSchema,
FolderSchema,
Folder as EwsFolder,
EmailMessage,
ItemId,
FolderId as EwsFolderId,
SortDirection
} from 'ews-javascript-api'
export class ExchangeProvider implements IEmailProvider {
private service: ExchangeService
private connected = false
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
private pollInterval: ReturnType<typeof setInterval> | null = null
constructor(private config: AccountConfig) {
const creds = config.credentials as ExchangeCredentials
this.service = new ExchangeService(ExchangeVersion.Exchange2013)
this.service.Credentials = new WebCredentials(creds.username, creds.password, creds.domain)
this.service.Url = new Uri(creds.serverUrl)
}
async connect(): Promise<void> {
// Test connection by fetching inbox
const view = new FolderView(1)
await this.service.FindFolders(WellKnownFolderName.MsgFolderRoot, view)
this.connected = true
}
async disconnect(): Promise<void> {
this.offNewMail()
this.connected = false
}
isConnected(): boolean {
return this.connected
}
async listFolders(): Promise<FolderListResult> {
const view = new FolderView(100)
view.PropertySet = new PropertySet(
BasePropertySet.IdOnly,
FolderSchema.DisplayName,
FolderSchema.UnreadCount,
FolderSchema.TotalCount,
FolderSchema.ParentFolderId
)
const result = await this.service.FindFolders(WellKnownFolderName.MsgFolderRoot, view)
const folders: Folder[] = result.Folders.map((f: EwsFolder) => ({
id: f.Id.UniqueId,
name: f.DisplayName,
role: this.detectRole(f.DisplayName),
parentId: null,
unreadCount: f.UnreadCount ?? 0,
totalCount: f.TotalCount ?? 0,
children: []
}))
return { folders }
}
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
const view = new ItemView(options.limit, options.offset)
view.PropertySet = new PropertySet(
BasePropertySet.IdOnly,
EmailMessageSchema.Subject,
EmailMessageSchema.From,
EmailMessageSchema.ToRecipients,
EmailMessageSchema.CcRecipients,
EmailMessageSchema.DateTimeReceived,
EmailMessageSchema.IsRead,
EmailMessageSchema.HasAttachments,
EmailMessageSchema.Importance
)
view.OrderBy.Add(EmailMessageSchema.DateTimeReceived, SortDirection.Descending)
const folderId = new EwsFolderId(options.folderId)
const result = await this.service.FindItems(folderId, view)
const messages: MessageEnvelope[] = result.Items.map((item: EmailMessage) => ({
id: item.Id.UniqueId,
folderId: options.folderId,
subject: item.Subject ?? '(no subject)',
from: {
name: item.From?.Name ?? '',
email: item.From?.Address ?? ''
},
to: (item.ToRecipients?.GetEnumerator() ?? []).map((r: { Name: string; Address: string }) => ({
name: r.Name ?? '',
email: r.Address ?? ''
})),
cc: (item.CcRecipients?.GetEnumerator() ?? []).map((r: { Name: string; Address: string }) => ({
name: r.Name ?? '',
email: r.Address ?? ''
})),
date: item.DateTimeReceived?.toISOString() ?? new Date().toISOString(),
flags: {
seen: item.IsRead ?? false,
flagged: false,
answered: false,
deleted: false
},
hasAttachments: item.HasAttachments ?? false,
snippet: ''
}))
return { messages, total: result.TotalCount ?? messages.length }
}
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
const msg = await EmailMessage.Bind(this.service, new ItemId(messageId), new PropertySet(
BasePropertySet.FirstClassProperties
))
let html: string | null = null
let text: string | null = null
const body = msg.Body?.Text ?? ''
if (msg.Body?.BodyType === 0) { // HTML
html = sanitizeHtml(body)
} else {
text = body
}
return {
id: messageId,
html,
text,
inlineImages: [],
attachments: []
}
}
async updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void> {
for (const messageId of messageIds) {
const msg = await EmailMessage.Bind(this.service, new ItemId(messageId))
if (flags.seen !== undefined) {
msg.IsRead = flags.seen
}
await msg.Update(1) // ConflictResolutionMode.AutoResolve
}
}
async downloadAttachment(_folderId: string, _messageId: string, _attachmentId: string): Promise<Buffer> {
throw new Error('Attachment download not supported for Exchange accounts')
}
async deleteMessages(folderId: string, messageIds: string[]): Promise<void> {
for (const messageId of messageIds) {
const msg = await EmailMessage.Bind(this.service, new ItemId(messageId))
await msg.Delete(1) // DeleteMode.HardDelete
}
}
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
this.newMailCallback = callback
// EWS doesn't support push natively from JS — poll every 60s
this.pollInterval = setInterval(async () => {
// Simplified polling — in production would track last known count
}, 60_000)
}
offNewMail(): void {
this.newMailCallback = null
if (this.pollInterval) {
clearInterval(this.pollInterval)
this.pollInterval = null
}
}
async pollNewMessages(): Promise<void> { /* Exchange использует свой polling через onNewMail */ }
async searchMessages(_query: string, _limit: number): Promise<import('@shared/types/message').MessageEnvelope[]> { return [] }
private detectRole(name: string): SpecialFolderRole {
const n = name.toLowerCase()
if (n === 'inbox') return SpecialFolderRole.Inbox
if (n === 'sent items' || n === 'sent') return SpecialFolderRole.Sent
if (n === 'drafts') return SpecialFolderRole.Drafts
if (n === 'deleted items' || n === 'trash') return SpecialFolderRole.Trash
if (n === 'junk email' || n === 'spam') return SpecialFolderRole.Spam
if (n === 'archive') return SpecialFolderRole.Archive
return SpecialFolderRole.None
}
}