import { Context, Element, MessageEncoder } from '@satorijs/core' import { MailBot } from './bot' import { Attachment } from './mail' const letters = 'abcdefghijklmnopqrstuvwxyz' export function randomId() { return Array(8).fill(0).map(() => letters[Math.floor(Math.random() * letters.length)]).join('') } export class MailMessageEncoder extends MessageEncoder> { buffer = '' reply: string attachments: Attachment[] = [] figure = false async flush() { if (!this.buffer && this.attachments.length === 0) return const messageId = await this.bot.internal.send({ to: this.session.channelId.substring(8), html: `
${this.buffer}
`, attachments: this.attachments, inReplyTo: this.reply, subject: this.bot.config.subject, }) const session = this.bot.session() session.messageId = messageId session.timestamp = +new Date() session.userId = this.bot.selfId this.results.push(session.event.message) session.app.emit(session, 'send', session) this.buffer = '' this.reply = undefined this.attachments = [] } async visit(element: Element) { const { type, attrs, children } = element if (type === 'text') { this.buffer += attrs.content } else if (type === 'br') { this.buffer += '
' } else if (['b', 'strong', 'i', 'em', 'u', 'ins', 's', 'del', 'p', 'code', 'li', 'ul', 'ol', 'blockquote'].includes(type)) { this.buffer += `<${type}>` await this.render(children) this.buffer += `` } else if (type === 'a') { this.buffer += `` await this.render(children) this.buffer += `` } else if (type === 'at') { if (attrs.id) { this.buffer += `@${attrs.id}` } } else if (type === 'sharp' && attrs.id) { this.buffer += ` #${attrs.id} ` } else if (['image', 'audio', 'video', 'file'].includes(type) && (attrs.src || attrs.url)) { let url: string = attrs.src || attrs.url if (!url.match(/^https?:/)) { const cid = randomId() const { filename, type, data } = await this.bot.ctx.http.file(url) this.attachments.push({ cid, filename, content: Buffer.from(data), contentType: type, }) url = `cid:${cid}` } if (type === 'image') { this.buffer += `` } else if (type === 'audio') { this.buffer += `