@1outres/dsh-bot-connector-google 0.0.0-stage → 0.3.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/README.md +33 -2
- package/cordis.patch.yml +6 -0
- package/icon.svg +8 -0
- package/lib/index.js +2268 -0
- package/locale/en.json +6 -0
- package/locale/ja.json +6 -0
- package/package.json +61 -3
- package/src/host/calendar/events.ts +139 -0
- package/src/host/calendar/own.ts +28 -0
- package/src/host/calendar/times.ts +40 -0
- package/src/host/calendar/tools.ts +633 -0
- package/src/host/connectors.ts +41 -0
- package/src/host/endpoints.ts +48 -0
- package/src/host/gmail/addresses.ts +73 -0
- package/src/host/gmail/compose.ts +244 -0
- package/src/host/gmail/events.ts +117 -0
- package/src/host/gmail/io.ts +212 -0
- package/src/host/gmail/message.ts +128 -0
- package/src/host/gmail/mime.ts +139 -0
- package/src/host/gmail/tools.ts +916 -0
- package/src/host/google.ts +93 -0
- package/src/host/kit.ts +62 -0
- package/src/host/provider.ts +53 -0
- package/src/host/scopes.ts +18 -0
- package/src/index.ts +70 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** Where Google's services are reached. */
|
|
2
|
+
export interface GoogleEndpoints {
|
|
3
|
+
readonly authorization: string
|
|
4
|
+
readonly token: string
|
|
5
|
+
readonly revocation: string
|
|
6
|
+
readonly userinfo: string
|
|
7
|
+
/** Gmail API root (`<root>gmail/v1/...`). */
|
|
8
|
+
readonly gmailRoot: string
|
|
9
|
+
/** Calendar API root (`<root>calendar/v3/...`). */
|
|
10
|
+
readonly calendarRoot: string
|
|
11
|
+
/** A development configuration (a fake Google), never Google itself. */
|
|
12
|
+
readonly development: boolean
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const GOOGLE_ENDPOINTS: GoogleEndpoints = {
|
|
16
|
+
authorization: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
17
|
+
token: "https://oauth2.googleapis.com/token",
|
|
18
|
+
revocation: "https://oauth2.googleapis.com/revoke",
|
|
19
|
+
userinfo: "https://openidconnect.googleapis.com/v1/userinfo",
|
|
20
|
+
gmailRoot: "https://gmail.googleapis.com/",
|
|
21
|
+
calendarRoot: "https://www.googleapis.com/",
|
|
22
|
+
development: false,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Every endpoint on one origin with Google's own paths: a fake Google for
|
|
27
|
+
* development and tests. A connection signed in at one origin is never
|
|
28
|
+
* refreshed at another (bot-core pins its token endpoint).
|
|
29
|
+
*/
|
|
30
|
+
export function developmentEndpoints(origin: string): GoogleEndpoints {
|
|
31
|
+
const url = new URL(origin)
|
|
32
|
+
if (
|
|
33
|
+
(url.protocol !== "http:" && url.protocol !== "https:") ||
|
|
34
|
+
url.origin !== origin.replace(/\/$/, "")
|
|
35
|
+
) {
|
|
36
|
+
throw new Error("development.googleOrigin must be an http(s) origin without a path")
|
|
37
|
+
}
|
|
38
|
+
const base = url.origin
|
|
39
|
+
return {
|
|
40
|
+
authorization: `${base}/o/oauth2/v2/auth`,
|
|
41
|
+
token: `${base}/token`,
|
|
42
|
+
revocation: `${base}/revoke`,
|
|
43
|
+
userinfo: `${base}/v1/userinfo`,
|
|
44
|
+
gmailRoot: `${base}/`,
|
|
45
|
+
calendarRoot: `${base}/`,
|
|
46
|
+
development: true,
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/** One mailbox of a header: an optional display name and an address. */
|
|
2
|
+
export interface Mailbox {
|
|
3
|
+
readonly name?: string
|
|
4
|
+
readonly address: string
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
const ADDRESS = /^[^\s@<>()",;:\\[\]]+@[^\s@<>()",;:\\[\]]+\.[^\s@<>()",;:\\[\]]+$/
|
|
8
|
+
const CONTROL = /[\p{Cc}\p{Cf}\u2028\u2029]/u
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A mailbox written by the bot: `name <address>` or `address`. Line breaks
|
|
12
|
+
* and control characters are refused, so no argument can add a header.
|
|
13
|
+
* @throws naming what is wrong.
|
|
14
|
+
*/
|
|
15
|
+
export function parseMailbox(input: string): Mailbox {
|
|
16
|
+
if (CONTROL.test(input))
|
|
17
|
+
throw new Error(`"${input.replace(CONTROL, "?")}" has a line break or control character`)
|
|
18
|
+
const text = input.trim()
|
|
19
|
+
const angled = /^(.*)<([^<>]+)>$/.exec(text)
|
|
20
|
+
const address = (angled?.[2] ?? text).trim()
|
|
21
|
+
if (!ADDRESS.test(address)) throw new Error(`"${text}" is not an email address`)
|
|
22
|
+
const name = angled?.[1]
|
|
23
|
+
?.trim()
|
|
24
|
+
.replace(/^"(.*)"$/, "$1")
|
|
25
|
+
.trim()
|
|
26
|
+
return name === undefined || name === "" ? { address } : { name, address }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function parseMailboxes(inputs: readonly string[] | undefined, what: string): Mailbox[] {
|
|
30
|
+
const list = (inputs ?? []).map((input) => {
|
|
31
|
+
try {
|
|
32
|
+
return parseMailbox(input)
|
|
33
|
+
} catch (error) {
|
|
34
|
+
throw new Error(`${what}: ${error instanceof Error ? error.message : String(error)}`)
|
|
35
|
+
}
|
|
36
|
+
})
|
|
37
|
+
return list
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A mailbox as people read it. */
|
|
41
|
+
export function showMailbox(mailbox: Mailbox): string {
|
|
42
|
+
return mailbox.name === undefined ? mailbox.address : `${mailbox.name} <${mailbox.address}>`
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Split an address header (From, To, Cc) into mailboxes, as received (lenient: outside data). */
|
|
46
|
+
export function readMailboxes(header: string | undefined): Mailbox[] {
|
|
47
|
+
if (header === undefined || header.trim() === "") return []
|
|
48
|
+
const parts: string[] = []
|
|
49
|
+
let current = ""
|
|
50
|
+
let quoted = false
|
|
51
|
+
let angled = false
|
|
52
|
+
for (const char of header) {
|
|
53
|
+
if (char === '"') quoted = !quoted
|
|
54
|
+
if (!quoted && char === "<") angled = true
|
|
55
|
+
if (!quoted && char === ">") angled = false
|
|
56
|
+
if (char === "," && !quoted && !angled) {
|
|
57
|
+
parts.push(current)
|
|
58
|
+
current = ""
|
|
59
|
+
} else {
|
|
60
|
+
current += char
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
parts.push(current)
|
|
64
|
+
return parts.flatMap((part) => {
|
|
65
|
+
try {
|
|
66
|
+
return [parseMailbox(part.replace(/[\r\n]+/g, " "))]
|
|
67
|
+
} catch {
|
|
68
|
+
return []
|
|
69
|
+
}
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export const sameAddress = (a: string, b: string) => a.toLowerCase() === b.toLowerCase()
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a sent message is, as one model: the preview a person approves and
|
|
3
|
+
* the MIME the connector sends are both made from it, so they cannot differ.
|
|
4
|
+
*/
|
|
5
|
+
import type { ConnectorPreview, ConnectorPreviewField } from "@1outres/dsh-bot-core"
|
|
6
|
+
import {
|
|
7
|
+
type Mailbox,
|
|
8
|
+
parseMailbox,
|
|
9
|
+
parseMailboxes,
|
|
10
|
+
readMailboxes,
|
|
11
|
+
sameAddress,
|
|
12
|
+
showMailbox,
|
|
13
|
+
} from "./addresses"
|
|
14
|
+
|
|
15
|
+
/** A file attached to a message, as the snapshot read it. */
|
|
16
|
+
export interface AttachmentFact {
|
|
17
|
+
/** Where it came from: a path in the bot's environment, or its place among a forwarded message's attachments. */
|
|
18
|
+
readonly source:
|
|
19
|
+
| { readonly kind: "file"; readonly path: string }
|
|
20
|
+
| { readonly kind: "forwarded"; readonly index: number }
|
|
21
|
+
readonly filename: string
|
|
22
|
+
readonly mimeType: string
|
|
23
|
+
readonly size: number
|
|
24
|
+
readonly sha256: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The message a reply or forward is about, as the snapshot read it. */
|
|
28
|
+
export interface OriginalFacts {
|
|
29
|
+
readonly id: string
|
|
30
|
+
readonly threadId: string
|
|
31
|
+
readonly messageId?: string
|
|
32
|
+
readonly references?: string
|
|
33
|
+
readonly subject: string
|
|
34
|
+
readonly from: string
|
|
35
|
+
readonly replyTo?: string
|
|
36
|
+
readonly to: string
|
|
37
|
+
readonly cc: string
|
|
38
|
+
readonly date: string
|
|
39
|
+
/** Its text, when the reply quotes it or the message is forwarded. */
|
|
40
|
+
readonly text?: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface Outgoing {
|
|
44
|
+
readonly from: Mailbox
|
|
45
|
+
readonly to: readonly Mailbox[]
|
|
46
|
+
readonly cc: readonly Mailbox[]
|
|
47
|
+
readonly bcc: readonly Mailbox[]
|
|
48
|
+
readonly subject: string
|
|
49
|
+
readonly body: string
|
|
50
|
+
readonly inReplyTo?: string
|
|
51
|
+
readonly references?: readonly string[]
|
|
52
|
+
readonly threadId?: string
|
|
53
|
+
readonly attachments: readonly AttachmentFact[]
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const CONTROL = /[\p{Cc}\p{Cf}\u2028\u2029]/u
|
|
57
|
+
|
|
58
|
+
function subjectOf(subject: string): string {
|
|
59
|
+
if (CONTROL.test(subject)) throw new Error("the subject has a line break or control character")
|
|
60
|
+
return subject.trim()
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function requireRecipients(message: Outgoing): Outgoing {
|
|
64
|
+
if (message.to.length + message.cc.length + message.bcc.length === 0) {
|
|
65
|
+
throw new Error("the message has no recipient")
|
|
66
|
+
}
|
|
67
|
+
return message
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface SendArguments {
|
|
71
|
+
readonly to: readonly string[]
|
|
72
|
+
readonly cc?: readonly string[]
|
|
73
|
+
readonly bcc?: readonly string[]
|
|
74
|
+
readonly subject: string
|
|
75
|
+
readonly body: string
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface MessageArguments {
|
|
79
|
+
readonly to?: readonly string[]
|
|
80
|
+
readonly cc?: readonly string[]
|
|
81
|
+
readonly bcc?: readonly string[]
|
|
82
|
+
readonly subject: string
|
|
83
|
+
readonly body: string
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A message as written, recipients not required yet (a draft). */
|
|
87
|
+
export function composeMessage(
|
|
88
|
+
args: MessageArguments,
|
|
89
|
+
from: string,
|
|
90
|
+
attachments: readonly AttachmentFact[],
|
|
91
|
+
): Outgoing {
|
|
92
|
+
return {
|
|
93
|
+
from: parseMailbox(from),
|
|
94
|
+
to: parseMailboxes(args.to, "to"),
|
|
95
|
+
cc: parseMailboxes(args.cc, "cc"),
|
|
96
|
+
bcc: parseMailboxes(args.bcc, "bcc"),
|
|
97
|
+
subject: subjectOf(args.subject),
|
|
98
|
+
body: args.body,
|
|
99
|
+
attachments,
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function composeSend(
|
|
104
|
+
args: SendArguments,
|
|
105
|
+
from: string,
|
|
106
|
+
attachments: readonly AttachmentFact[],
|
|
107
|
+
): Outgoing {
|
|
108
|
+
return requireRecipients(composeMessage(args, from, attachments))
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const prefixed = (prefix: string, subject: string) =>
|
|
112
|
+
new RegExp(`^${prefix}:\\s`, "i").test(subject)
|
|
113
|
+
? subject
|
|
114
|
+
: `${prefix[0]?.toUpperCase()}${prefix.slice(1)}: ${subject}`
|
|
115
|
+
|
|
116
|
+
function unique(list: readonly Mailbox[], except: readonly Mailbox[]): Mailbox[] {
|
|
117
|
+
const seen: Mailbox[] = []
|
|
118
|
+
for (const mailbox of list) {
|
|
119
|
+
if ([...except, ...seen].some((other) => sameAddress(other.address, mailbox.address))) continue
|
|
120
|
+
seen.push(mailbox)
|
|
121
|
+
}
|
|
122
|
+
return seen
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function references(original: OriginalFacts): string[] {
|
|
126
|
+
const previous = (original.references ?? "").split(/\s+/).filter((id) => /^<[^<>\s]+>$/.test(id))
|
|
127
|
+
return original.messageId === undefined ? previous : [...previous, original.messageId]
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function quoteOf(original: OriginalFacts): string {
|
|
131
|
+
const quoted = (original.text ?? "")
|
|
132
|
+
.replace(/\r\n/g, "\n")
|
|
133
|
+
.split("\n")
|
|
134
|
+
.map((line) => (line === "" ? ">" : `> ${line}`))
|
|
135
|
+
.join("\n")
|
|
136
|
+
return `On ${original.date}, ${original.from} wrote:\n${quoted}`
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface ReplyArguments {
|
|
140
|
+
readonly body: string
|
|
141
|
+
readonly reply_all: boolean
|
|
142
|
+
readonly quote: boolean
|
|
143
|
+
readonly cc?: readonly string[]
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function composeReply(
|
|
147
|
+
args: ReplyArguments,
|
|
148
|
+
from: string,
|
|
149
|
+
original: OriginalFacts,
|
|
150
|
+
attachments: readonly AttachmentFact[],
|
|
151
|
+
): Outgoing {
|
|
152
|
+
const self = parseMailbox(from)
|
|
153
|
+
const author = readMailboxes(original.replyTo ?? original.from)
|
|
154
|
+
const theirTo = readMailboxes(original.to)
|
|
155
|
+
const fromSelf = author.every((mailbox) => sameAddress(mailbox.address, self.address))
|
|
156
|
+
const primary = fromSelf ? theirTo : author
|
|
157
|
+
const to = unique(args.reply_all ? [...primary, ...theirTo] : primary, [self])
|
|
158
|
+
const cc = unique(
|
|
159
|
+
[...(args.reply_all ? readMailboxes(original.cc) : []), ...parseMailboxes(args.cc, "cc")],
|
|
160
|
+
[self, ...to],
|
|
161
|
+
)
|
|
162
|
+
const ids = references(original)
|
|
163
|
+
return requireRecipients({
|
|
164
|
+
from: self,
|
|
165
|
+
to,
|
|
166
|
+
cc,
|
|
167
|
+
bcc: [],
|
|
168
|
+
subject: prefixed("re", original.subject),
|
|
169
|
+
body: args.quote ? `${args.body}\n\n${quoteOf(original)}` : args.body,
|
|
170
|
+
...(original.messageId === undefined ? {} : { inReplyTo: original.messageId }),
|
|
171
|
+
...(ids.length === 0 ? {} : { references: ids }),
|
|
172
|
+
threadId: original.threadId,
|
|
173
|
+
attachments,
|
|
174
|
+
})
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface ForwardArguments {
|
|
178
|
+
readonly to: readonly string[]
|
|
179
|
+
readonly cc?: readonly string[]
|
|
180
|
+
readonly bcc?: readonly string[]
|
|
181
|
+
readonly comment?: string
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function composeForward(
|
|
185
|
+
args: ForwardArguments,
|
|
186
|
+
from: string,
|
|
187
|
+
original: OriginalFacts,
|
|
188
|
+
attachments: readonly AttachmentFact[],
|
|
189
|
+
): Outgoing {
|
|
190
|
+
const forwarded = [
|
|
191
|
+
"---------- Forwarded message ---------",
|
|
192
|
+
`From: ${original.from}`,
|
|
193
|
+
`Date: ${original.date}`,
|
|
194
|
+
`Subject: ${original.subject}`,
|
|
195
|
+
`To: ${original.to}`,
|
|
196
|
+
...(original.cc === "" ? [] : [`Cc: ${original.cc}`]),
|
|
197
|
+
"",
|
|
198
|
+
original.text ?? "",
|
|
199
|
+
].join("\n")
|
|
200
|
+
return requireRecipients({
|
|
201
|
+
from: parseMailbox(from),
|
|
202
|
+
to: parseMailboxes(args.to, "to"),
|
|
203
|
+
cc: parseMailboxes(args.cc, "cc"),
|
|
204
|
+
bcc: parseMailboxes(args.bcc, "bcc"),
|
|
205
|
+
subject: prefixed("fwd", original.subject),
|
|
206
|
+
body:
|
|
207
|
+
args.comment === undefined || args.comment === ""
|
|
208
|
+
? forwarded
|
|
209
|
+
: `${args.comment}\n\n${forwarded}`,
|
|
210
|
+
attachments,
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const list = (mailboxes: readonly Mailbox[]) => mailboxes.map(showMailbox).join(", ")
|
|
215
|
+
|
|
216
|
+
export function sizeLabel(bytes: number): string {
|
|
217
|
+
if (bytes < 1024) return `${bytes} B`
|
|
218
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`
|
|
219
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MiB`
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Everything the message carries, in the order a mail client shows it; the body follows. */
|
|
223
|
+
export function previewOf(
|
|
224
|
+
title: string,
|
|
225
|
+
message: Outgoing,
|
|
226
|
+
extra: readonly ConnectorPreviewField[] = [],
|
|
227
|
+
): ConnectorPreview {
|
|
228
|
+
const fields: ConnectorPreviewField[] = [
|
|
229
|
+
{ label: "From", value: showMailbox(message.from) },
|
|
230
|
+
{ label: "To", value: list(message.to) || "(none)" },
|
|
231
|
+
...(message.cc.length === 0 ? [] : [{ label: "Cc", value: list(message.cc) }]),
|
|
232
|
+
...(message.bcc.length === 0 ? [] : [{ label: "Bcc", value: list(message.bcc) }]),
|
|
233
|
+
{ label: "Subject", value: message.subject === "" ? "(no subject)" : message.subject },
|
|
234
|
+
...(message.inReplyTo === undefined
|
|
235
|
+
? []
|
|
236
|
+
: [{ label: "In reply to", value: message.inReplyTo }]),
|
|
237
|
+
...message.attachments.map((attachment, index) => ({
|
|
238
|
+
label: `Attachment ${index + 1}`,
|
|
239
|
+
value: `${attachment.filename} (${attachment.mimeType}, ${sizeLabel(attachment.size)}, sha256 ${attachment.sha256})`,
|
|
240
|
+
})),
|
|
241
|
+
...extra,
|
|
242
|
+
]
|
|
243
|
+
return { title, fields, body: message.body }
|
|
244
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type { BotConnectorEvents, ConnectorEvent, ConnectorJson } from "@1outres/dsh-bot-core"
|
|
2
|
+
import type { gmail_v1 } from "@googleapis/gmail"
|
|
3
|
+
import { type Google, googleStatus } from "../google"
|
|
4
|
+
import { oneLine } from "../kit"
|
|
5
|
+
import { METADATA_HEADERS, readMessage } from "./message"
|
|
6
|
+
|
|
7
|
+
export const MESSAGE_RECEIVED = "gmail.message.received"
|
|
8
|
+
|
|
9
|
+
/** Pages of history one poll reads at most; the rest waits for the next poll, which resumes after the last record read. */
|
|
10
|
+
const MAX_PAGES = 10
|
|
11
|
+
const MAX_MESSAGES = 200
|
|
12
|
+
|
|
13
|
+
interface Cursor {
|
|
14
|
+
readonly historyId: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const cursorOf = (value: ConnectorJson | undefined): Cursor | undefined => {
|
|
18
|
+
const historyId = (value as { historyId?: unknown } | null | undefined)?.historyId
|
|
19
|
+
return typeof historyId === "string" ? { historyId } : undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function profileCursor(gmail: gmail_v1.Gmail): Promise<Cursor> {
|
|
23
|
+
const profile = await gmail.users.getProfile({ userId: "me" })
|
|
24
|
+
const historyId = profile.data.historyId
|
|
25
|
+
if (!historyId) throw new Error("Gmail returned no historyId")
|
|
26
|
+
return { historyId }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** New messages in the inbox, from Gmail's history (users.history.list) since the last poll. */
|
|
30
|
+
export function gmailEvents(google: Google): BotConnectorEvents {
|
|
31
|
+
return {
|
|
32
|
+
kinds: [
|
|
33
|
+
{
|
|
34
|
+
kind: MESSAGE_RECEIVED,
|
|
35
|
+
label: { en: "New email in the inbox", ja: "受信トレイへの新着メール" },
|
|
36
|
+
},
|
|
37
|
+
],
|
|
38
|
+
delivery: "notify",
|
|
39
|
+
intervalMs: 60_000,
|
|
40
|
+
poll: (source, value) =>
|
|
41
|
+
google.as(source.connection, async ({ gmail }) => {
|
|
42
|
+
const cursor = cursorOf(value)
|
|
43
|
+
if (cursor === undefined) return { events: [], cursor: { ...(await profileCursor(gmail)) } }
|
|
44
|
+
const added = new Map<string, string>()
|
|
45
|
+
let latest = cursor.historyId
|
|
46
|
+
let pageToken: string | undefined
|
|
47
|
+
try {
|
|
48
|
+
for (let page = 0; page < MAX_PAGES; page += 1) {
|
|
49
|
+
const response = await gmail.users.history.list({
|
|
50
|
+
userId: "me",
|
|
51
|
+
startHistoryId: cursor.historyId,
|
|
52
|
+
historyTypes: ["messageAdded"],
|
|
53
|
+
labelId: "INBOX",
|
|
54
|
+
...(pageToken === undefined ? {} : { pageToken }),
|
|
55
|
+
})
|
|
56
|
+
const entries = response.data.history ?? []
|
|
57
|
+
for (const entry of entries) {
|
|
58
|
+
for (const item of entry.messagesAdded ?? []) {
|
|
59
|
+
const labels = item.message?.labelIds ?? []
|
|
60
|
+
if (
|
|
61
|
+
item.message?.id &&
|
|
62
|
+
labels.includes("INBOX") &&
|
|
63
|
+
!labels.includes("SENT") &&
|
|
64
|
+
!labels.includes("DRAFT")
|
|
65
|
+
) {
|
|
66
|
+
added.set(item.message.id, item.message.threadId ?? "")
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
pageToken = response.data.nextPageToken ?? undefined
|
|
71
|
+
if (pageToken === undefined) {
|
|
72
|
+
if (response.data.historyId) latest = response.data.historyId
|
|
73
|
+
break
|
|
74
|
+
}
|
|
75
|
+
const last = entries.at(-1)?.id
|
|
76
|
+
if (last) latest = last
|
|
77
|
+
if (added.size >= MAX_MESSAGES || page === MAX_PAGES - 1) break
|
|
78
|
+
}
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (googleStatus(error) === 404) {
|
|
81
|
+
return {
|
|
82
|
+
events: [],
|
|
83
|
+
cursor: { ...(await profileCursor(gmail)) },
|
|
84
|
+
gap: "Gmail no longer has the history since the last poll",
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
throw error
|
|
88
|
+
}
|
|
89
|
+
const events: ConnectorEvent[] = []
|
|
90
|
+
for (const [id, threadId] of added) {
|
|
91
|
+
let message: ReturnType<typeof readMessage>
|
|
92
|
+
try {
|
|
93
|
+
const response = await gmail.users.messages.get({
|
|
94
|
+
userId: "me",
|
|
95
|
+
id,
|
|
96
|
+
format: "metadata",
|
|
97
|
+
metadataHeaders: METADATA_HEADERS,
|
|
98
|
+
})
|
|
99
|
+
message = readMessage(response.data)
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (googleStatus(error) === 404) continue
|
|
102
|
+
throw error
|
|
103
|
+
}
|
|
104
|
+
events.push({
|
|
105
|
+
key: `gmail:${id}`,
|
|
106
|
+
kind: MESSAGE_RECEIVED,
|
|
107
|
+
occurredAt: message.internalDate ?? 0,
|
|
108
|
+
summary: oneLine(
|
|
109
|
+
`From: ${message.from ?? "?"} · Subject: ${message.subject ?? "(no subject)"} · ${message.snippet}`,
|
|
110
|
+
),
|
|
111
|
+
ref: { message_id: id, thread_id: threadId },
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
return { events, cursor: { historyId: latest } }
|
|
115
|
+
}),
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import type { BotConnectorEnvironment } from "@1outres/dsh-bot-core"
|
|
3
|
+
import type { gmail_v1 } from "@googleapis/gmail"
|
|
4
|
+
import type { AttachmentFact, OriginalFacts, Outgoing } from "./compose"
|
|
5
|
+
import { readMessage } from "./message"
|
|
6
|
+
import { buildMime, type MimeAttachment } from "./mime"
|
|
7
|
+
|
|
8
|
+
/** Most bytes of every attachment of one message together. */
|
|
9
|
+
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
|
|
10
|
+
/** Most characters of a quoted or forwarded text. */
|
|
11
|
+
export const MAX_ORIGINAL_TEXT = 100_000
|
|
12
|
+
|
|
13
|
+
const TYPES: Readonly<Record<string, string>> = {
|
|
14
|
+
pdf: "application/pdf",
|
|
15
|
+
txt: "text/plain",
|
|
16
|
+
md: "text/markdown",
|
|
17
|
+
csv: "text/csv",
|
|
18
|
+
json: "application/json",
|
|
19
|
+
html: "text/html",
|
|
20
|
+
png: "image/png",
|
|
21
|
+
jpg: "image/jpeg",
|
|
22
|
+
jpeg: "image/jpeg",
|
|
23
|
+
gif: "image/gif",
|
|
24
|
+
webp: "image/webp",
|
|
25
|
+
svg: "image/svg+xml",
|
|
26
|
+
zip: "application/zip",
|
|
27
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
28
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
29
|
+
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function mimeTypeOf(filename: string): string {
|
|
33
|
+
const extension = /\.([A-Za-z0-9]+)$/.exec(filename)?.[1]?.toLowerCase()
|
|
34
|
+
return (extension === undefined ? undefined : TYPES[extension]) ?? "application/octet-stream"
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const sha256 = (data: Uint8Array) => createHash("sha256").update(data).digest("hex")
|
|
38
|
+
|
|
39
|
+
export interface LoadedAttachment {
|
|
40
|
+
readonly fact: AttachmentFact
|
|
41
|
+
readonly data: Uint8Array
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function within(attachments: readonly { readonly size: number }[]) {
|
|
45
|
+
const total = attachments.reduce((sum, item) => sum + item.size, 0)
|
|
46
|
+
if (total > MAX_ATTACHMENT_BYTES) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
`the attachments are larger than ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MiB together`,
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Read files of the bot's environment to attach. */
|
|
54
|
+
export async function readFiles(
|
|
55
|
+
environment: BotConnectorEnvironment,
|
|
56
|
+
paths: readonly string[],
|
|
57
|
+
): Promise<LoadedAttachment[]> {
|
|
58
|
+
const loaded: LoadedAttachment[] = []
|
|
59
|
+
for (const path of paths) {
|
|
60
|
+
const absolute = path.startsWith("/") ? path : `${environment.workspace}/${path}`
|
|
61
|
+
const data = await environment.readFile(absolute, { maxBytes: MAX_ATTACHMENT_BYTES })
|
|
62
|
+
const filename = absolute.split("/").pop() ?? "attachment"
|
|
63
|
+
loaded.push({
|
|
64
|
+
fact: {
|
|
65
|
+
source: { kind: "file", path: absolute },
|
|
66
|
+
filename,
|
|
67
|
+
mimeType: mimeTypeOf(filename),
|
|
68
|
+
size: data.byteLength,
|
|
69
|
+
sha256: sha256(data),
|
|
70
|
+
},
|
|
71
|
+
data,
|
|
72
|
+
})
|
|
73
|
+
within(loaded.map((item) => item.fact))
|
|
74
|
+
}
|
|
75
|
+
return loaded
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function downloadAttachment(
|
|
79
|
+
gmail: gmail_v1.Gmail,
|
|
80
|
+
messageId: string,
|
|
81
|
+
attachmentId: string,
|
|
82
|
+
): Promise<Uint8Array> {
|
|
83
|
+
const response = await gmail.users.messages.attachments.get({
|
|
84
|
+
userId: "me",
|
|
85
|
+
messageId,
|
|
86
|
+
id: attachmentId,
|
|
87
|
+
})
|
|
88
|
+
return Buffer.from(response.data.data ?? "", "base64url")
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Read the original of a reply or forward; its text only when it is needed. */
|
|
92
|
+
export async function readOriginal(
|
|
93
|
+
gmail: gmail_v1.Gmail,
|
|
94
|
+
messageId: string,
|
|
95
|
+
withText: boolean,
|
|
96
|
+
): Promise<OriginalFacts> {
|
|
97
|
+
const response = await gmail.users.messages.get({ userId: "me", id: messageId, format: "full" })
|
|
98
|
+
const message = readMessage(response.data)
|
|
99
|
+
if (withText && message.text.length > MAX_ORIGINAL_TEXT) {
|
|
100
|
+
throw new Error(`the message's text is longer than ${MAX_ORIGINAL_TEXT} characters`)
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
id: message.id,
|
|
104
|
+
threadId: message.threadId,
|
|
105
|
+
...(message.messageId === undefined ? {} : { messageId: message.messageId }),
|
|
106
|
+
...(message.references === undefined ? {} : { references: message.references }),
|
|
107
|
+
subject: message.subject ?? "",
|
|
108
|
+
from: message.from ?? "",
|
|
109
|
+
...(message.replyTo === undefined ? {} : { replyTo: message.replyTo }),
|
|
110
|
+
to: message.to ?? "",
|
|
111
|
+
cc: message.cc ?? "",
|
|
112
|
+
date: message.date ?? "",
|
|
113
|
+
...(withText ? { text: message.text } : {}),
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The original's attachments with their hashes, for a forward that carries them. */
|
|
118
|
+
export async function forwardedAttachments(
|
|
119
|
+
gmail: gmail_v1.Gmail,
|
|
120
|
+
messageId: string,
|
|
121
|
+
): Promise<LoadedAttachment[]> {
|
|
122
|
+
const response = await gmail.users.messages.get({ userId: "me", id: messageId, format: "full" })
|
|
123
|
+
const message = readMessage(response.data)
|
|
124
|
+
within(message.attachments)
|
|
125
|
+
const loaded: LoadedAttachment[] = []
|
|
126
|
+
for (const [index, attachment] of message.attachments.entries()) {
|
|
127
|
+
const data = await downloadAttachment(gmail, messageId, attachment.attachmentId)
|
|
128
|
+
loaded.push({
|
|
129
|
+
fact: {
|
|
130
|
+
source: { kind: "forwarded", index },
|
|
131
|
+
filename: attachment.filename,
|
|
132
|
+
mimeType: attachment.mimeType,
|
|
133
|
+
size: data.byteLength,
|
|
134
|
+
sha256: sha256(data),
|
|
135
|
+
},
|
|
136
|
+
data,
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
return loaded
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The attachments' bytes now, checked against what the preview showed: a
|
|
144
|
+
* file changed since then (or a forwarded attachment that differs) fails the send.
|
|
145
|
+
*/
|
|
146
|
+
export async function loadApproved(
|
|
147
|
+
facts: readonly AttachmentFact[],
|
|
148
|
+
read: (fact: AttachmentFact) => Promise<Uint8Array>,
|
|
149
|
+
): Promise<MimeAttachment[]> {
|
|
150
|
+
const loaded: MimeAttachment[] = []
|
|
151
|
+
for (const fact of facts) {
|
|
152
|
+
const data = await read(fact)
|
|
153
|
+
if (sha256(data) !== fact.sha256) {
|
|
154
|
+
throw new Error(
|
|
155
|
+
`${fact.filename} changed since it was shown for approval, so nothing was sent`,
|
|
156
|
+
)
|
|
157
|
+
}
|
|
158
|
+
loaded.push({ filename: fact.filename, mimeType: fact.mimeType, data })
|
|
159
|
+
}
|
|
160
|
+
return loaded
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function mimeOf(message: Outgoing, attachments: readonly MimeAttachment[]): string {
|
|
164
|
+
return buildMime({
|
|
165
|
+
from: message.from,
|
|
166
|
+
to: message.to,
|
|
167
|
+
cc: message.cc,
|
|
168
|
+
bcc: message.bcc,
|
|
169
|
+
subject: message.subject,
|
|
170
|
+
body: message.body,
|
|
171
|
+
...(message.inReplyTo === undefined ? {} : { inReplyTo: message.inReplyTo }),
|
|
172
|
+
...(message.references === undefined ? {} : { references: message.references }),
|
|
173
|
+
attachments,
|
|
174
|
+
})
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Send the MIME as is (an upload, so large attachments fit). */
|
|
178
|
+
export async function sendMime(
|
|
179
|
+
gmail: gmail_v1.Gmail,
|
|
180
|
+
upload: { readonly rootUrl: string },
|
|
181
|
+
mime: string,
|
|
182
|
+
threadId: string | undefined,
|
|
183
|
+
) {
|
|
184
|
+
const response = await gmail.users.messages.send(
|
|
185
|
+
{
|
|
186
|
+
userId: "me",
|
|
187
|
+
requestBody: threadId === undefined ? {} : { threadId },
|
|
188
|
+
media: { mimeType: "message/rfc822", body: mime },
|
|
189
|
+
},
|
|
190
|
+
{ rootUrl: upload.rootUrl },
|
|
191
|
+
)
|
|
192
|
+
return { id: response.data.id ?? "", threadId: response.data.threadId ?? "" }
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* A forwarded attachment's bytes now: Gmail's attachment ids change between
|
|
196
|
+
* reads, so it is found again by its place and name in the message.
|
|
197
|
+
*/
|
|
198
|
+
export async function forwardedAttachment(
|
|
199
|
+
gmail: gmail_v1.Gmail,
|
|
200
|
+
messageId: string,
|
|
201
|
+
index: number,
|
|
202
|
+
filename: string,
|
|
203
|
+
): Promise<Uint8Array> {
|
|
204
|
+
const response = await gmail.users.messages.get({ userId: "me", id: messageId, format: "full" })
|
|
205
|
+
const attachment = readMessage(response.data).attachments[index]
|
|
206
|
+
if (attachment?.filename !== filename) {
|
|
207
|
+
throw new Error(
|
|
208
|
+
`${filename} is no longer attachment ${index + 1} of the message, so nothing was sent`,
|
|
209
|
+
)
|
|
210
|
+
}
|
|
211
|
+
return downloadAttachment(gmail, messageId, attachment.attachmentId)
|
|
212
|
+
}
|