@im-more/dsh-mail 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/cordis.patch.yml +14 -0
- package/lib/index.js +1334 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +49 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +189 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +51 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +55 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +60 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +195 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +33 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +156 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/html.d.ts +30 -0
- package/lib/types/html.d.ts.map +1 -0
- package/lib/types/html.js +121 -0
- package/lib/types/html.js.map +1 -0
- package/lib/types/index.d.ts +11 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +10 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/mail.d.ts +24 -0
- package/lib/types/mail.d.ts.map +1 -0
- package/lib/types/mail.js +26 -0
- package/lib/types/mail.js.map +1 -0
- package/lib/types/media.d.ts +52 -0
- package/lib/types/media.d.ts.map +1 -0
- package/lib/types/media.js +81 -0
- package/lib/types/media.js.map +1 -0
- package/lib/types/modes/html.d.ts +13 -0
- package/lib/types/modes/html.d.ts.map +1 -0
- package/lib/types/modes/html.js +70 -0
- package/lib/types/modes/html.js.map +1 -0
- package/lib/types/modes/shared.d.ts +114 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +185 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/send.d.ts +26 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +58 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/transport/imap.d.ts +95 -0
- package/lib/types/transport/imap.d.ts.map +1 -0
- package/lib/types/transport/imap.js +354 -0
- package/lib/types/transport/imap.js.map +1 -0
- package/package.json +70 -3
- package/src/bot.ts +264 -0
- package/src/config.ts +98 -0
- package/src/decode.ts +275 -0
- package/src/errors.ts +199 -0
- package/src/html.ts +137 -0
- package/src/index.ts +32 -0
- package/src/mail.ts +46 -0
- package/src/media.ts +102 -0
- package/src/modes/html.ts +105 -0
- package/src/modes/shared.ts +285 -0
- package/src/send.ts +87 -0
- package/src/transport/imap.ts +418 -0
- package/README.md +0 -3
package/src/bot.ts
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
+
import {
|
|
3
|
+
Adapter,
|
|
4
|
+
PlatformError,
|
|
5
|
+
Status,
|
|
6
|
+
} from '@deepseek-ai/cordis-plugin-im-core'
|
|
7
|
+
import type {
|
|
8
|
+
Mode,
|
|
9
|
+
PrepareContext,
|
|
10
|
+
ResolvedResource,
|
|
11
|
+
ResourceKind,
|
|
12
|
+
ResourceRef,
|
|
13
|
+
SendContext,
|
|
14
|
+
SentPart,
|
|
15
|
+
Target,
|
|
16
|
+
} from '@deepseek-ai/cordis-plugin-im-core'
|
|
17
|
+
import type { Attachment, ParsedMail } from 'mailparser'
|
|
18
|
+
import { addressOf, Config } from './config.ts'
|
|
19
|
+
import type { Config as MailConfig } from './config.ts'
|
|
20
|
+
import { decodeMessage } from './decode.ts'
|
|
21
|
+
import type { MailDecoder, MailSource } from './decode.ts'
|
|
22
|
+
import { classifyMailError } from './errors.ts'
|
|
23
|
+
import { MediaStaging } from './media.ts'
|
|
24
|
+
import { createHtmlMode } from './modes/html.ts'
|
|
25
|
+
import type { MailModeTypes, MailPayload } from './modes/shared.ts'
|
|
26
|
+
import { sendPayload } from './send.ts'
|
|
27
|
+
import { ImapTransport } from './transport/imap.ts'
|
|
28
|
+
import { SMTP } from './mail.ts'
|
|
29
|
+
|
|
30
|
+
/** The one mode this adapter implements. */
|
|
31
|
+
export interface MailModes {
|
|
32
|
+
[mode: string]: Mode<MailModeTypes>
|
|
33
|
+
html: Mode<MailModeTypes>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The error message of a caught value. */
|
|
37
|
+
function messageOf(error: unknown): string {
|
|
38
|
+
return error instanceof Error ? error.message : String(error)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Response headers of one attachment served through the `satori:` route. */
|
|
42
|
+
function attachmentHeaders(attachment: Attachment): Headers {
|
|
43
|
+
const headers = new Headers({ 'content-type': attachment.contentType })
|
|
44
|
+
const disposition = attachment.contentDisposition ?? 'attachment'
|
|
45
|
+
headers.set(
|
|
46
|
+
'content-disposition',
|
|
47
|
+
attachment.filename === undefined
|
|
48
|
+
? disposition
|
|
49
|
+
: `${disposition}; filename="${attachment.filename.replaceAll('"', '')}"`,
|
|
50
|
+
)
|
|
51
|
+
return headers
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Mail adapter: IMAP inbound, SMTP outbound, one `html` mode.
|
|
56
|
+
*
|
|
57
|
+
* Identity is fixed at construction because a mail account has no platform user id to look up: `bot.id` is
|
|
58
|
+
* `mail:<address>` and `bot.selfId` is the address itself. Inbound messages are acknowledged by `\\Seen` only after
|
|
59
|
+
* `bot.receive` accepted them; outbound attachments are staged in memory between `prepare` and `sendPayload`.
|
|
60
|
+
*/
|
|
61
|
+
export class MailBot extends Adapter<MailConfig, MailModes> {
|
|
62
|
+
/** The Loader applies this schema to a profile row's `config` before the constructor runs. */
|
|
63
|
+
static readonly Config = Config
|
|
64
|
+
|
|
65
|
+
readonly modes: MailModes = { html: createHtmlMode() }
|
|
66
|
+
readonly modeOrder = ['html'] as const
|
|
67
|
+
|
|
68
|
+
/** Outbound SMTP transport (the adapter's platform API). */
|
|
69
|
+
override readonly internal: SMTP
|
|
70
|
+
/** Outbound attachment bytes between `prepare` and `sendPayload`. */
|
|
71
|
+
readonly staging: MediaStaging
|
|
72
|
+
|
|
73
|
+
private transport: ImapTransport | undefined
|
|
74
|
+
/** Single-entry memo of the last message fetched for an attachment, so a message with several attachments costs one fetch. */
|
|
75
|
+
private memo: { uid: number; mail: ParsedMail } | undefined
|
|
76
|
+
|
|
77
|
+
constructor(ctx: Context, config: MailConfig) {
|
|
78
|
+
const address = addressOf(config)
|
|
79
|
+
super(ctx, config, {
|
|
80
|
+
id: `mail:${address}`,
|
|
81
|
+
platform: 'mail',
|
|
82
|
+
adapter: 'mail',
|
|
83
|
+
})
|
|
84
|
+
this.selfId = address
|
|
85
|
+
this.user = {
|
|
86
|
+
id: address,
|
|
87
|
+
...(config.name ? { name: config.name } : {}),
|
|
88
|
+
isBot: true,
|
|
89
|
+
}
|
|
90
|
+
this.internal = new SMTP(config)
|
|
91
|
+
this.staging = new MediaStaging(
|
|
92
|
+
config.media.stagingTtlMs,
|
|
93
|
+
config.media.maxStagedBytes,
|
|
94
|
+
)
|
|
95
|
+
this.defineInternalRoute('/messages/:uid/attachments/:index', (request) =>
|
|
96
|
+
this.serveAttachment(request),
|
|
97
|
+
)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
override async connect(): Promise<void> {
|
|
101
|
+
// A wrong SMTP configuration becomes visible at startup, but inbound must not be blocked by it.
|
|
102
|
+
try {
|
|
103
|
+
await this.internal.transporter.verify()
|
|
104
|
+
this.ctx.logger.debug('mail: SMTP credentials verified')
|
|
105
|
+
} catch (error) {
|
|
106
|
+
this.ctx.logger.warn(
|
|
107
|
+
'mail: SMTP verification failed, sending may fail: %s',
|
|
108
|
+
messageOf(error),
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
const transport = new ImapTransport({
|
|
112
|
+
config: this.config,
|
|
113
|
+
logger: this.ctx.logger,
|
|
114
|
+
deliver: (mail, source) => this.deliver(mail, source),
|
|
115
|
+
onOnline: () => {
|
|
116
|
+
this.online()
|
|
117
|
+
},
|
|
118
|
+
onReconnect: () => {
|
|
119
|
+
this.status = Status.RECONNECT
|
|
120
|
+
},
|
|
121
|
+
onOffline: (error) => {
|
|
122
|
+
this.offline(error)
|
|
123
|
+
},
|
|
124
|
+
})
|
|
125
|
+
this.transport = transport
|
|
126
|
+
try {
|
|
127
|
+
await transport.start()
|
|
128
|
+
} catch (error) {
|
|
129
|
+
// `Bot.start` only stores a connect failure on `bot.error`; a permanent failure belongs in the log as well.
|
|
130
|
+
this.ctx.logger.error('mail: connect failed: %s', messageOf(error))
|
|
131
|
+
await transport.stop()
|
|
132
|
+
this.transport = undefined
|
|
133
|
+
throw error
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
override async disconnect(): Promise<void> {
|
|
138
|
+
const transport = this.transport
|
|
139
|
+
this.transport = undefined
|
|
140
|
+
await transport?.stop()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
override async upload(
|
|
144
|
+
ref: ResourceRef,
|
|
145
|
+
_scope: string,
|
|
146
|
+
ctx: PrepareContext,
|
|
147
|
+
): Promise<ResolvedResource> {
|
|
148
|
+
let fetched
|
|
149
|
+
try {
|
|
150
|
+
fetched = await ctx.fetch(ref.src, ctx.signal)
|
|
151
|
+
} catch (error) {
|
|
152
|
+
// No byte left this host, so the publication certainly did not happen.
|
|
153
|
+
throw new PlatformError(
|
|
154
|
+
'invalid',
|
|
155
|
+
`mail: the resource "${ref.src}" could not be read: ${messageOf(error)}`,
|
|
156
|
+
{
|
|
157
|
+
published: 'no',
|
|
158
|
+
cause: error,
|
|
159
|
+
},
|
|
160
|
+
)
|
|
161
|
+
}
|
|
162
|
+
const mime = ref.meta.mime ?? fetched.mime
|
|
163
|
+
return this.staging.stage({
|
|
164
|
+
data: fetched.data,
|
|
165
|
+
name: ref.meta.name ?? fetched.name ?? '',
|
|
166
|
+
...(mime === undefined ? {} : { mime }),
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
override resourceScope(_target: Target, _kind: ResourceKind): string {
|
|
171
|
+
return this.id
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
override async sendPayload(
|
|
175
|
+
payload: unknown,
|
|
176
|
+
target: Target,
|
|
177
|
+
ctx: SendContext,
|
|
178
|
+
): Promise<SentPart> {
|
|
179
|
+
return sendPayload(
|
|
180
|
+
{ config: this.config, staging: this.staging, smtp: this.internal },
|
|
181
|
+
payload as MailPayload,
|
|
182
|
+
target,
|
|
183
|
+
ctx,
|
|
184
|
+
)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
override classify(error: unknown) {
|
|
188
|
+
return classifyMailError(error)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Decode and hand one message to the host; `\\Seen` is written by the transport once this resolved. */
|
|
192
|
+
private async deliver(mail: ParsedMail, source: MailSource): Promise<void> {
|
|
193
|
+
const decoder: MailDecoder = {
|
|
194
|
+
selfId: this.selfId,
|
|
195
|
+
config: this.config,
|
|
196
|
+
getInternalUrl: (path, init) => this.getInternalUrl(path, init),
|
|
197
|
+
log: (text) => {
|
|
198
|
+
this.ctx.logger.debug(text)
|
|
199
|
+
},
|
|
200
|
+
}
|
|
201
|
+
const message = decodeMessage(decoder, mail, source)
|
|
202
|
+
if (message === undefined) return
|
|
203
|
+
await this.receive(
|
|
204
|
+
this.session({
|
|
205
|
+
type: 'message',
|
|
206
|
+
id: message.id,
|
|
207
|
+
timestamp: message.time,
|
|
208
|
+
message,
|
|
209
|
+
}),
|
|
210
|
+
)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Serve one attachment of a stored message, re-fetching the message by UID. */
|
|
214
|
+
private async serveAttachment(
|
|
215
|
+
request: Request & {
|
|
216
|
+
params: { uid: string; index: string }
|
|
217
|
+
query: URLSearchParams
|
|
218
|
+
},
|
|
219
|
+
): Promise<Response> {
|
|
220
|
+
const uid = Number(request.params.uid)
|
|
221
|
+
const index = Number(request.params.index)
|
|
222
|
+
if (
|
|
223
|
+
!Number.isSafeInteger(uid) ||
|
|
224
|
+
uid <= 0 ||
|
|
225
|
+
!Number.isSafeInteger(index) ||
|
|
226
|
+
index < 0
|
|
227
|
+
) {
|
|
228
|
+
return new Response(null, { status: 400 })
|
|
229
|
+
}
|
|
230
|
+
if (request.query.get('box') !== this.config.mailbox)
|
|
231
|
+
return new Response(null, { status: 404 })
|
|
232
|
+
let mail: ParsedMail | undefined
|
|
233
|
+
try {
|
|
234
|
+
mail = await this.fetchMail(uid)
|
|
235
|
+
} catch (error) {
|
|
236
|
+
this.ctx.logger.warn(
|
|
237
|
+
'mail: the message %d could not be fetched: %s',
|
|
238
|
+
uid,
|
|
239
|
+
messageOf(error),
|
|
240
|
+
)
|
|
241
|
+
return new Response(null, { status: 502 })
|
|
242
|
+
}
|
|
243
|
+
const attachment = mail?.attachments[index]
|
|
244
|
+
if (attachment === undefined) return new Response(null, { status: 404 })
|
|
245
|
+
return new Response(new Uint8Array(attachment.content), {
|
|
246
|
+
headers: attachmentHeaders(attachment),
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Fetch one message for the attachment route, memoizing the last one. */
|
|
251
|
+
private async fetchMail(uid: number): Promise<ParsedMail | undefined> {
|
|
252
|
+
if (this.memo?.uid === uid) return this.memo.mail
|
|
253
|
+
const transport = this.transport
|
|
254
|
+
if (transport === undefined)
|
|
255
|
+
throw new Error('mail: the IMAP connection is not open')
|
|
256
|
+
const mail = await transport.fetch(uid)
|
|
257
|
+
if (mail !== undefined) this.memo = { uid, mail }
|
|
258
|
+
return mail
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export { Config }
|
|
263
|
+
|
|
264
|
+
export default MailBot
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import z from '@deepseek-ai/schemastery'
|
|
2
|
+
|
|
3
|
+
/** One mail account: IMAP credentials and the two transport endpoints. */
|
|
4
|
+
export interface Config {
|
|
5
|
+
/** Login name of the account (usually the address); used by both IMAP `LOGIN` and SMTP `AUTH`. */
|
|
6
|
+
username: string
|
|
7
|
+
/** Password or application password. */
|
|
8
|
+
password: string
|
|
9
|
+
/** The address this bot answers as; defaults to {@link Config.username}. */
|
|
10
|
+
selfId?: string | null
|
|
11
|
+
/** Display name of the `From:` header. */
|
|
12
|
+
name?: string | null
|
|
13
|
+
/** Subject of a message that does not answer another one. */
|
|
14
|
+
subject: string
|
|
15
|
+
/** Mailbox the inbound scan watches. */
|
|
16
|
+
mailbox: string
|
|
17
|
+
imap: {
|
|
18
|
+
host: string
|
|
19
|
+
/** Implicit TLS. With `port: 143` this asks `node-imap` to upgrade via STARTTLS. */
|
|
20
|
+
tls: boolean
|
|
21
|
+
port: number
|
|
22
|
+
}
|
|
23
|
+
smtp: {
|
|
24
|
+
host: string
|
|
25
|
+
/** Implicit TLS (`secure`). */
|
|
26
|
+
tls: boolean
|
|
27
|
+
port: number
|
|
28
|
+
}
|
|
29
|
+
retry: {
|
|
30
|
+
/** Fast-retry budget of the reconnect timer; it never gives up. */
|
|
31
|
+
times: number
|
|
32
|
+
/** Delay between dials while the fast-retry budget lasts. */
|
|
33
|
+
interval: number
|
|
34
|
+
/** Delay between dials once the fast-retry budget is spent. */
|
|
35
|
+
lazy: number
|
|
36
|
+
}
|
|
37
|
+
media: {
|
|
38
|
+
/** How long outbound attachment bytes stay staged for a retry. */
|
|
39
|
+
stagingTtlMs: number
|
|
40
|
+
/** Upper bound of all staged bytes; the oldest entries are evicted first. */
|
|
41
|
+
maxStagedBytes: number
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Validated Mail adapter configuration. */
|
|
46
|
+
export const Config: z<Config> = z.object({
|
|
47
|
+
username: z.string().required(),
|
|
48
|
+
password: z.string().role('secret').required(),
|
|
49
|
+
selfId: z.string(),
|
|
50
|
+
name: z.string(),
|
|
51
|
+
subject: z.string().default('Koishi'),
|
|
52
|
+
mailbox: z.string().default('INBOX'),
|
|
53
|
+
imap: z.intersect([
|
|
54
|
+
z.object({
|
|
55
|
+
host: z.string().required(),
|
|
56
|
+
tls: z.boolean().default(true),
|
|
57
|
+
}),
|
|
58
|
+
z.union([
|
|
59
|
+
z.object({ tls: z.const(true), port: z.natural().default(993) }),
|
|
60
|
+
z.object({ tls: z.const(false), port: z.natural().default(143) }),
|
|
61
|
+
]),
|
|
62
|
+
]),
|
|
63
|
+
smtp: z.intersect([
|
|
64
|
+
z.object({
|
|
65
|
+
host: z.string().required(),
|
|
66
|
+
tls: z.boolean().default(true),
|
|
67
|
+
}),
|
|
68
|
+
z.union([
|
|
69
|
+
z.object({ tls: z.const(true), port: z.natural().default(465) }),
|
|
70
|
+
z.object({ tls: z.const(false), port: z.natural().default(25) }),
|
|
71
|
+
]),
|
|
72
|
+
]),
|
|
73
|
+
retry: z
|
|
74
|
+
.object({
|
|
75
|
+
times: z.natural().default(6),
|
|
76
|
+
interval: z.natural().role('ms').default(5_000),
|
|
77
|
+
lazy: z.natural().role('ms').default(60_000),
|
|
78
|
+
})
|
|
79
|
+
.default({}),
|
|
80
|
+
media: z
|
|
81
|
+
.object({
|
|
82
|
+
stagingTtlMs: z
|
|
83
|
+
.natural()
|
|
84
|
+
.role('ms')
|
|
85
|
+
.default(10 * 60_000),
|
|
86
|
+
maxStagedBytes: z.natural().default(64 * 1024 * 1024),
|
|
87
|
+
})
|
|
88
|
+
.default({}),
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The address this bot answers as: `selfId` when given, else the login name.
|
|
93
|
+
* @param config - the validated adapter configuration.
|
|
94
|
+
* @returns the bot's own address.
|
|
95
|
+
*/
|
|
96
|
+
export function addressOf(config: Config): string {
|
|
97
|
+
return config.selfId || config.username
|
|
98
|
+
}
|
package/src/decode.ts
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inbound decoding: one parsed message becomes one {@link InboundMessage}.
|
|
3
|
+
*
|
|
4
|
+
* The message is addressed to the sender's own mailbox (`chat.id = private:<address>`), the `Message-ID` is the
|
|
5
|
+
* message identity (and the intake dedupe key), `In-Reply-To`/`References` become `quote`/`referrer`, and attachments
|
|
6
|
+
* become media elements whose `src` is the bot's `satori:` attachment route. Messages sent by the bot itself are
|
|
7
|
+
* skipped, because a copy arriving back in the mailbox would otherwise answer itself.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type {
|
|
11
|
+
ChatRef,
|
|
12
|
+
InboundMessage,
|
|
13
|
+
UserRef,
|
|
14
|
+
} from '@deepseek-ai/cordis-plugin-im-core'
|
|
15
|
+
import { h } from '@deepseek-ai/satori-element'
|
|
16
|
+
import type { Element } from '@deepseek-ai/satori-element'
|
|
17
|
+
import type { AddressObject, EmailAddress, ParsedMail } from 'mailparser'
|
|
18
|
+
import type { Config } from './config.ts'
|
|
19
|
+
import { htmlToElements } from './html.ts'
|
|
20
|
+
|
|
21
|
+
/** Where one message was read from; the attachment route re-fetches by the same coordinates. */
|
|
22
|
+
export interface MailSource {
|
|
23
|
+
uid: number
|
|
24
|
+
mailbox: string
|
|
25
|
+
size: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Adapter-private context carried through `Target.referrer`. */
|
|
29
|
+
export interface MailReferrer {
|
|
30
|
+
/** The sender's address (the `From:` mailbox), the chat this message belongs to. */
|
|
31
|
+
address: string
|
|
32
|
+
/** The message this one is, as delivered. */
|
|
33
|
+
messageId: string
|
|
34
|
+
subject?: string
|
|
35
|
+
/** `Reply-To:`, when the message names another answer address. */
|
|
36
|
+
replyTo?: string
|
|
37
|
+
/** `References:`, oldest first, as `<…>` values. */
|
|
38
|
+
references?: string[]
|
|
39
|
+
/** IMAP UID this message was read at (attachment route). */
|
|
40
|
+
uid: number
|
|
41
|
+
/** Mailbox this message was read from. */
|
|
42
|
+
mailbox: string
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The part of the bot inbound decoding uses. */
|
|
46
|
+
export interface MailDecoder {
|
|
47
|
+
readonly selfId: string
|
|
48
|
+
readonly config: Config
|
|
49
|
+
getInternalUrl(path: string, init?: Record<string, string>): string
|
|
50
|
+
/** Reports a dropped `<sub>`/`<sup>`; optional so decoding needs no logger. */
|
|
51
|
+
readonly log?: (message: string) => void
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Which media element an attachment's MIME type maps to. */
|
|
55
|
+
export type AttachmentKind = 'img' | 'audio' | 'video' | 'file'
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The element kind of one attachment.
|
|
59
|
+
* @param mime - the attachment's MIME type.
|
|
60
|
+
* @returns the vocabulary tag the attachment is shown as.
|
|
61
|
+
*/
|
|
62
|
+
export function attachmentKind(mime: string): AttachmentKind {
|
|
63
|
+
const type = mime.split(';')[0]?.trim().toLowerCase() ?? ''
|
|
64
|
+
if (type.startsWith('image/')) return 'img'
|
|
65
|
+
if (type.startsWith('audio/')) return 'audio'
|
|
66
|
+
if (type.startsWith('video/')) return 'video'
|
|
67
|
+
return 'file'
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Every address of the given headers, groups expanded; entries without an address are dropped. */
|
|
71
|
+
function addressesOf(
|
|
72
|
+
...headers: (AddressObject | AddressObject[] | undefined)[]
|
|
73
|
+
): EmailAddress[] {
|
|
74
|
+
const out: EmailAddress[] = []
|
|
75
|
+
for (const header of headers) {
|
|
76
|
+
if (header === undefined) continue
|
|
77
|
+
for (const object of Array.isArray(header) ? header : [header]) {
|
|
78
|
+
for (const item of object.value) {
|
|
79
|
+
const list = item.group ?? [item]
|
|
80
|
+
for (const address of list) {
|
|
81
|
+
if (address.address) out.push(address)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return out
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** `References:` as a list of `<…>` values (mailparser gives a string for a single reference). */
|
|
90
|
+
function referencesOf(mail: ParsedMail): string[] {
|
|
91
|
+
if (mail.references === undefined) return []
|
|
92
|
+
return Array.isArray(mail.references)
|
|
93
|
+
? [...mail.references]
|
|
94
|
+
: [mail.references]
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A stable id for a message that carries no `Message-ID`. */
|
|
98
|
+
function synthesizedId(uid: number, selfId: string): string {
|
|
99
|
+
const at = selfId.lastIndexOf('@')
|
|
100
|
+
return `<${uid}@${at < 0 ? selfId : selfId.slice(at + 1)}>`
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The display name of an address, when it has one. */
|
|
104
|
+
function nameOf(address: EmailAddress): string | undefined {
|
|
105
|
+
const name = address.name.trim()
|
|
106
|
+
return name === '' ? undefined : name
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Media elements of the message's attachments, in MIME order, served by the attachment route. */
|
|
110
|
+
function attachmentElements(
|
|
111
|
+
bot: MailDecoder,
|
|
112
|
+
mail: ParsedMail,
|
|
113
|
+
source: MailSource,
|
|
114
|
+
): Element[] {
|
|
115
|
+
return mail.attachments.map((attachment, index) => {
|
|
116
|
+
const kind = attachmentKind(attachment.contentType)
|
|
117
|
+
const filename = attachment.filename ?? `attachment-${index + 1}`
|
|
118
|
+
const src = bot.getInternalUrl(
|
|
119
|
+
`/messages/${source.uid}/attachments/${index}`,
|
|
120
|
+
{ box: source.mailbox },
|
|
121
|
+
)
|
|
122
|
+
switch (kind) {
|
|
123
|
+
case 'img':
|
|
124
|
+
return h('img', {
|
|
125
|
+
src,
|
|
126
|
+
...(attachment.filename === undefined
|
|
127
|
+
? {}
|
|
128
|
+
: { alt: attachment.filename }),
|
|
129
|
+
})
|
|
130
|
+
case 'audio':
|
|
131
|
+
return h('audio', { src, name: filename })
|
|
132
|
+
case 'video':
|
|
133
|
+
return h('video', { src, name: filename })
|
|
134
|
+
case 'file':
|
|
135
|
+
return h('file', { src, name: filename })
|
|
136
|
+
}
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The body elements of one message: the HTML traversal, or the plain text part, plus the attachments. */
|
|
141
|
+
function bodyElements(
|
|
142
|
+
bot: MailDecoder,
|
|
143
|
+
mail: ParsedMail,
|
|
144
|
+
source: MailSource,
|
|
145
|
+
): Element[] {
|
|
146
|
+
const body: Element[] = []
|
|
147
|
+
if (!mail.html) {
|
|
148
|
+
const text = mail.text ?? ''
|
|
149
|
+
if (text !== '') body.push(h.text(text))
|
|
150
|
+
} else {
|
|
151
|
+
const log = bot.log
|
|
152
|
+
body.push(
|
|
153
|
+
...htmlToElements(
|
|
154
|
+
mail.html,
|
|
155
|
+
log === undefined
|
|
156
|
+
? {}
|
|
157
|
+
: {
|
|
158
|
+
onSubscript: () => {
|
|
159
|
+
log(
|
|
160
|
+
'mail: dropped <sub>/<sup>, the vocabulary has no subscript',
|
|
161
|
+
)
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
),
|
|
165
|
+
)
|
|
166
|
+
}
|
|
167
|
+
body.push(...attachmentElements(bot, mail, source))
|
|
168
|
+
return body
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Decode one parsed message.
|
|
173
|
+
*
|
|
174
|
+
* @param bot - the adapter the message arrived for (identity, mailbox, `satori:` route base).
|
|
175
|
+
* @param mail - the parsed MIME message.
|
|
176
|
+
* @param source - the IMAP coordinates the message was read at.
|
|
177
|
+
* @returns the inbound message, or `undefined` when the message cannot be routed (no sender address, or the bot's
|
|
178
|
+
* own message).
|
|
179
|
+
*/
|
|
180
|
+
export function decodeMessage(
|
|
181
|
+
bot: MailDecoder,
|
|
182
|
+
mail: ParsedMail,
|
|
183
|
+
source: MailSource,
|
|
184
|
+
): InboundMessage | undefined {
|
|
185
|
+
const from = mail.from?.value[0]
|
|
186
|
+
if (from?.address === undefined || from.address === '') {
|
|
187
|
+
bot.log?.('mail: dropped a message without a sender address')
|
|
188
|
+
return undefined
|
|
189
|
+
}
|
|
190
|
+
if (from.address.toLowerCase() === bot.selfId.toLowerCase()) {
|
|
191
|
+
bot.log?.(
|
|
192
|
+
`mail: dropped a message from the bot's own address (${from.address})`,
|
|
193
|
+
)
|
|
194
|
+
return undefined
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const address = from.address
|
|
198
|
+
const name = nameOf(from)
|
|
199
|
+
const messageId = mail.messageId ?? synthesizedId(source.uid, bot.selfId)
|
|
200
|
+
const replyTo = mail.replyTo?.value[0]?.address
|
|
201
|
+
const references = referencesOf(mail)
|
|
202
|
+
const body = bodyElements(bot, mail, source)
|
|
203
|
+
// Content must never be empty; a structural-only message becomes one `<raw>` child.
|
|
204
|
+
const content = h(
|
|
205
|
+
'message',
|
|
206
|
+
{},
|
|
207
|
+
...(body.length === 0
|
|
208
|
+
? [
|
|
209
|
+
h(
|
|
210
|
+
'raw',
|
|
211
|
+
{
|
|
212
|
+
platform: 'mail',
|
|
213
|
+
type: 'message',
|
|
214
|
+
data: {
|
|
215
|
+
messageId,
|
|
216
|
+
contentType: mail.headers.get('content-type'),
|
|
217
|
+
},
|
|
218
|
+
},
|
|
219
|
+
h.text(''),
|
|
220
|
+
),
|
|
221
|
+
]
|
|
222
|
+
: body),
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
const recipients = addressesOf(mail.to, mail.cc)
|
|
226
|
+
const seen = new Set<string>()
|
|
227
|
+
const users: UserRef[] = []
|
|
228
|
+
let mentionsSelf = false
|
|
229
|
+
for (const recipient of recipients) {
|
|
230
|
+
if (recipient.address === undefined) continue
|
|
231
|
+
const lower = recipient.address.toLowerCase()
|
|
232
|
+
if (lower === bot.selfId.toLowerCase()) {
|
|
233
|
+
mentionsSelf = true
|
|
234
|
+
continue
|
|
235
|
+
}
|
|
236
|
+
if (seen.has(lower)) continue
|
|
237
|
+
seen.add(lower)
|
|
238
|
+
const recipientName = nameOf(recipient)
|
|
239
|
+
users.push({
|
|
240
|
+
id: recipient.address,
|
|
241
|
+
...(recipientName === undefined ? {} : { name: recipientName }),
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const chat: ChatRef = {
|
|
246
|
+
id: `private:${address}`,
|
|
247
|
+
type: 'direct',
|
|
248
|
+
...(name === undefined ? {} : { name }),
|
|
249
|
+
}
|
|
250
|
+
const sender: UserRef = {
|
|
251
|
+
id: address,
|
|
252
|
+
...(name === undefined ? {} : { name }),
|
|
253
|
+
}
|
|
254
|
+
const referrer: MailReferrer = {
|
|
255
|
+
address,
|
|
256
|
+
messageId,
|
|
257
|
+
...(mail.subject === undefined ? {} : { subject: mail.subject }),
|
|
258
|
+
...(replyTo === undefined ? {} : { replyTo }),
|
|
259
|
+
...(references.length === 0 ? {} : { references }),
|
|
260
|
+
uid: source.uid,
|
|
261
|
+
mailbox: source.mailbox,
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
id: messageId,
|
|
266
|
+
chat,
|
|
267
|
+
sender,
|
|
268
|
+
content,
|
|
269
|
+
...(mail.inReplyTo === undefined ? {} : { quote: { id: mail.inReplyTo } }),
|
|
270
|
+
mentions: { self: mentionsSelf, all: false, users },
|
|
271
|
+
time: mail.date === undefined ? Date.now() : +mail.date,
|
|
272
|
+
referrer,
|
|
273
|
+
raw: { uid: source.uid, mailbox: source.mailbox, size: source.size },
|
|
274
|
+
}
|
|
275
|
+
}
|