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 | 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 { // Test connection by fetching inbox const view = new FolderView(1) await this.service.FindFolders(WellKnownFolderName.MsgFolderRoot, view) this.connected = true } async disconnect(): Promise { this.offNewMail() this.connected = false } isConnected(): boolean { return this.connected } async listFolders(): Promise { 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 { 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 { 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): Promise { 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 { throw new Error('Attachment download not supported for Exchange accounts') } async deleteMessages(folderId: string, messageIds: string[]): Promise { 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 { /* Exchange использует свой polling через onNewMail */ } async searchMessages(_query: string, _limit: number): Promise { return [] } async sendMessage(_compose: import('@shared/types/message').ComposeData): Promise { throw new Error('Send not implemented for Exchange') } 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 } }