@dotlabo/agent-chat-relay 0.0.0-stage → 0.2.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/CHANGELOG.md +109 -0
- package/LICENSE +21 -0
- package/README.md +154 -2
- package/bin/agent-chat-relay +22 -0
- package/package.json +69 -4
- package/src/connectors/chatwork.ts +289 -0
- package/src/connectors/common.ts +106 -0
- package/src/connectors/discord.ts +335 -0
- package/src/connectors/http.ts +137 -0
- package/src/connectors/line-media.ts +63 -0
- package/src/connectors/line.ts +444 -0
- package/src/connectors/terminal.ts +367 -0
- package/src/core/access.ts +250 -0
- package/src/core/instructions.ts +21 -0
- package/src/core/mcp.ts +160 -0
- package/src/core/relay.ts +1063 -0
- package/src/core/retention.ts +44 -0
- package/src/harness/config.ts +137 -0
- package/src/harness/harness.ts +327 -0
- package/src/harness/log-file.ts +34 -0
- package/src/harness/pi/config.ts +51 -0
- package/src/harness/pi/state.ts +97 -0
- package/src/harness/pi/tool-approval.ts +128 -0
- package/src/harness/protect.ts +37 -0
- package/src/home.ts +67 -0
- package/src/jev.ts +201 -0
- package/src/main.ts +275 -0
- package/src/prompt.ts +12 -0
- package/src/serve-args.ts +56 -0
- package/src/shutdown.ts +52 -0
- package/src/terminal.ts +172 -0
- package/src/vendor/pi/adapter.js +3238 -0
- package/src/vendor/pi/managed-extension.ts +94 -0
- package/src/vendor/pi/managed-pi-rpc.ts +102 -0
- package/src/vendor/pi/managed-read.ts +99 -0
- package/src/vendor/pi/package.json +7 -0
- package/src/vendor/pi/pi-LICENSE +21 -0
- package/src/vendor/pi/pi-acp-LICENSE +21 -0
- package/src/version.ts +4 -0
- package/src/workspace.ts +117 -0
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
// LINE のコネクター。Webhook の受信と、Messaging API での送信を担当する。
|
|
2
|
+
|
|
3
|
+
import { extname, join } from "node:path"
|
|
4
|
+
import { localId } from "../core/access.ts"
|
|
5
|
+
import { schedulePrune } from "../core/retention.ts"
|
|
6
|
+
import { MAX_IMAGE_BYTES, MediaStore } from "./line-media.ts"
|
|
7
|
+
import { acknowledger, assertNumericId, parsePermissionData, permissionData, remember, saveDownload, splitText, truncate, verdictText } from "./common.ts"
|
|
8
|
+
import { ApiClient, ApiError, jsonError, verifySignature } from "./http.ts"
|
|
9
|
+
import type { Attachment, Capabilities, Connector, ConnectorDeps, Log, Relay, Routes } from "../core/relay.ts"
|
|
10
|
+
|
|
11
|
+
const SERVICE = "line"
|
|
12
|
+
const REPLY_TOKEN_TTL_MS = 50 * 1000 // Reply トークンの有効期限は 1 分。余裕を見て 50 秒
|
|
13
|
+
const MAX_BUBBLES = 5 // 1 回の送信に入れられるメッセージの数(本文の吹き出しと画像を合わせて)
|
|
14
|
+
const MAX_BUBBLE_UNITS = 5000 // 吹き出し 1 つの最大文字数(UTF-16 の単位)
|
|
15
|
+
const MEDIA_TEXT = { image: "(画像)", video: "(動画)", audio: "(音声)" }
|
|
16
|
+
// 公開 URL に使うホスト名(Webhook の Host ヘッダー)の形。ヘッダーの値をそのまま URL に入れるので絞る
|
|
17
|
+
const HOST_RE = /^[A-Za-z0-9.-]{1,253}(:[0-9]{1,5})?$/
|
|
18
|
+
|
|
19
|
+
type Source = { type: "user" | "group" | "room"; userId?: string; groupId?: string; roomId?: string }
|
|
20
|
+
/** type は user(人)か all(全員)。userId は、その人がプロフィールの取得に同意しているときだけある */
|
|
21
|
+
type Mentionee = { index: number; length: number; type?: string; userId?: string; isSelf?: boolean }
|
|
22
|
+
type LineEvent = {
|
|
23
|
+
type: string
|
|
24
|
+
webhookEventId?: string
|
|
25
|
+
timestamp: number
|
|
26
|
+
replyToken?: string
|
|
27
|
+
source: Source
|
|
28
|
+
deliveryContext?: { isRedelivery?: boolean }
|
|
29
|
+
message?: {
|
|
30
|
+
id: string
|
|
31
|
+
type: string
|
|
32
|
+
text?: string
|
|
33
|
+
quoteToken?: string
|
|
34
|
+
/** 既読を付けるためのトークン(期限なし) */
|
|
35
|
+
markAsReadToken?: string
|
|
36
|
+
quotedMessageId?: string
|
|
37
|
+
mention?: { mentionees: Mentionee[] }
|
|
38
|
+
fileName?: string
|
|
39
|
+
fileSize?: number
|
|
40
|
+
contentProvider?: { type: string }
|
|
41
|
+
title?: string
|
|
42
|
+
address?: string
|
|
43
|
+
latitude?: number
|
|
44
|
+
longitude?: number
|
|
45
|
+
keywords?: string[]
|
|
46
|
+
}
|
|
47
|
+
postback?: { data: string }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type LineMessage = NonNullable<LineEvent["message"]>
|
|
51
|
+
|
|
52
|
+
type LineConfig = {
|
|
53
|
+
channelSecret: string
|
|
54
|
+
channelToken: string
|
|
55
|
+
apiBase?: string
|
|
56
|
+
dataApiBase?: string
|
|
57
|
+
/** 返す画像を公開する場所(ADR 0005)。ないと画像を送れない */
|
|
58
|
+
media?: MediaStore
|
|
59
|
+
/** 画像を公開する URL の先頭(例:https://example.com)。なければ、署名を確認した Webhook が届いたホスト名を使う */
|
|
60
|
+
publicUrl?: string
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** チャネルシークレットとアクセストークンがあれば、コネクターを作る */
|
|
64
|
+
export function lineFromEnv(env: Record<string, string | undefined>, deps: ConnectorDeps): LineConnector | undefined {
|
|
65
|
+
const channelSecret = env.RELAY_LINE_CHANNEL_SECRET
|
|
66
|
+
const channelToken = env.RELAY_LINE_CHANNEL_TOKEN
|
|
67
|
+
if (!channelSecret || !channelToken) return undefined
|
|
68
|
+
return new LineConnector(
|
|
69
|
+
{
|
|
70
|
+
channelSecret,
|
|
71
|
+
channelToken,
|
|
72
|
+
apiBase: env.RELAY_LINE_API_BASE,
|
|
73
|
+
dataApiBase: env.RELAY_LINE_DATA_API_BASE,
|
|
74
|
+
// 返す画像の公開場所。作業ディレクトリの外に置き、reply の files で送れる範囲(ADR 0009)や作業物と混ざらないようにする
|
|
75
|
+
media: new MediaStore(join(deps.home, "media")),
|
|
76
|
+
publicUrl: env.RELAY_PUBLIC_URL,
|
|
77
|
+
},
|
|
78
|
+
deps.relay,
|
|
79
|
+
deps.log,
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export class LineConnector implements Connector {
|
|
84
|
+
readonly service = SERVICE
|
|
85
|
+
readonly label = "LINE"
|
|
86
|
+
readonly capabilities: Capabilities = {
|
|
87
|
+
// 1 回の送信に入る吹き出しは 5 つ。本文に 1 つ残す
|
|
88
|
+
files: { kinds: "JPEG と PNG の画像", maxBytes: MAX_IMAGE_BYTES, maxCount: MAX_BUBBLES - 1 },
|
|
89
|
+
// 分けた本文も 1 回の送信に入れるので、通数は増えない。画像を添えると、分けられる数はその分減る
|
|
90
|
+
text: { max: MAX_BUBBLE_UNITS, parts: MAX_BUBBLES },
|
|
91
|
+
}
|
|
92
|
+
readonly routes: Routes
|
|
93
|
+
private readonly api: ApiClient
|
|
94
|
+
private readonly dataApi: ApiClient
|
|
95
|
+
private readonly tokens = new Map<string, { token: string; at: number }[]>()
|
|
96
|
+
private readonly quoteTokens = new Map<string, string>()
|
|
97
|
+
private readonly sentIds = new Set<string>()
|
|
98
|
+
/** 受けた発言の送信者。引用元が送信者以外の発言かを確かめる(ADR 0028) */
|
|
99
|
+
private readonly senders = new Map<string, string>()
|
|
100
|
+
private readonly seenEvents = new Set<string>()
|
|
101
|
+
private readonly names = new Map<string, string>()
|
|
102
|
+
/** ファイルの元の名前。取得したファイルの拡張子に使う */
|
|
103
|
+
private readonly fileNames = new Map<string, string>()
|
|
104
|
+
/** 動画と音声の発言。取得の前に、LINE 側の変換が済んだかを確かめる */
|
|
105
|
+
private readonly transcoding = new Map<string, true>()
|
|
106
|
+
private publicBase?: string
|
|
107
|
+
private stopPrune?: () => void
|
|
108
|
+
private readonly acknowledge: ReturnType<typeof acknowledger>
|
|
109
|
+
|
|
110
|
+
constructor(
|
|
111
|
+
private readonly cfg: LineConfig,
|
|
112
|
+
private readonly relay: Relay,
|
|
113
|
+
private readonly log: Log,
|
|
114
|
+
private readonly now: () => number = Date.now,
|
|
115
|
+
) {
|
|
116
|
+
const client = (base: string) =>
|
|
117
|
+
new ApiClient({
|
|
118
|
+
label: this.label,
|
|
119
|
+
base,
|
|
120
|
+
auth: () => ({ Authorization: `Bearer ${cfg.channelToken}` }),
|
|
121
|
+
errorMessage: (raw) => jsonError(raw, (b) => b.message),
|
|
122
|
+
})
|
|
123
|
+
this.api = client(cfg.apiBase ?? "https://api.line.me")
|
|
124
|
+
this.dataApi = client(cfg.dataApiBase ?? cfg.apiBase ?? "https://api-data.line.me")
|
|
125
|
+
this.publicBase = cfg.publicUrl?.replace(/\/$/, "")
|
|
126
|
+
this.acknowledge = acknowledger(log, this.label)
|
|
127
|
+
const media = cfg.media
|
|
128
|
+
this.routes = {
|
|
129
|
+
"/line/webhook": { POST: (req) => this.handleWebhook(req) },
|
|
130
|
+
// 返した画像(ADR 0005)。トンネルで外へ公開される
|
|
131
|
+
...(media ? { "/media/:name": { GET: (req) => media.serve(req.params.name ?? "") } } : {}),
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Webhook はエンドポイントで受けるので、ここでは返した画像の定期削除だけを始める(ADR 0005) */
|
|
136
|
+
async start(): Promise<void> {
|
|
137
|
+
if (this.cfg.media) this.stopPrune = schedulePrune(this.cfg.media.dir, "公開した画像", this.log)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
stop(): void {
|
|
141
|
+
this.stopPrune?.()
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 署名を確認し、すぐ 200 を返す。イベントはその後で処理する */
|
|
145
|
+
async handleWebhook(req: Request): Promise<Response> {
|
|
146
|
+
const body = await req.text()
|
|
147
|
+
if (!verifySignature(this.cfg.channelSecret, body, req.headers.get("x-line-signature") ?? "")) {
|
|
148
|
+
return new Response("bad signature", { status: 401 })
|
|
149
|
+
}
|
|
150
|
+
// 署名が合えば、LINE が登録された URL へ送ってきたもの。そのホスト名で画像を公開する(Quick Tunnel は起動ごとに変わる)。
|
|
151
|
+
// LINE は HTTPS の URL しか受け付けないので、トンネル経由(X-Forwarded-Proto: https)のときだけ使う
|
|
152
|
+
const host = req.headers.get("host") ?? ""
|
|
153
|
+
if (!this.cfg.publicUrl && req.headers.get("x-forwarded-proto") === "https" && HOST_RE.test(host)) this.publicBase = `https://${host}`
|
|
154
|
+
let events: LineEvent[]
|
|
155
|
+
try {
|
|
156
|
+
events = (JSON.parse(body) as { events?: LineEvent[] }).events ?? []
|
|
157
|
+
} catch {
|
|
158
|
+
return new Response("bad request", { status: 400 })
|
|
159
|
+
}
|
|
160
|
+
queueMicrotask(() => {
|
|
161
|
+
for (const ev of events) {
|
|
162
|
+
this.handleEvent(ev).catch((err) => this.log.error("LINE のイベントの処理に失敗しました", { error: String(err) }))
|
|
163
|
+
}
|
|
164
|
+
})
|
|
165
|
+
return new Response("ok")
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async handleEvent(ev: LineEvent): Promise<void> {
|
|
169
|
+
if (ev.webhookEventId) {
|
|
170
|
+
if (this.seenEvents.has(ev.webhookEventId)) return
|
|
171
|
+
remember(this.seenEvents, ev.webhookEventId)
|
|
172
|
+
}
|
|
173
|
+
const room = roomOf(ev.source)
|
|
174
|
+
if (!room) return
|
|
175
|
+
if (ev.replyToken && !ev.deliveryContext?.isRedelivery) this.addToken(room, ev.replyToken)
|
|
176
|
+
const sender = ev.source.userId ? `${SERVICE}:${ev.source.userId}` : undefined
|
|
177
|
+
|
|
178
|
+
if (ev.type === "join") {
|
|
179
|
+
this.relay.joined(room)
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
if (ev.type === "postback") {
|
|
183
|
+
const p = parsePermissionData(ev.postback?.data ?? "")
|
|
184
|
+
if (!p || !sender) return
|
|
185
|
+
const ok = this.relay.answer(sender, p.id, p.verdict)
|
|
186
|
+
try {
|
|
187
|
+
await this.notice(room, verdictText(ok, p.verdict))
|
|
188
|
+
} finally {
|
|
189
|
+
if (ok) this.relay.remindPending(sender)
|
|
190
|
+
}
|
|
191
|
+
return
|
|
192
|
+
}
|
|
193
|
+
const msg = ev.message
|
|
194
|
+
if (ev.type !== "message" || !msg || !sender) return
|
|
195
|
+
const isDM = ev.source.type === "user"
|
|
196
|
+
if (msg.quoteToken) remember(this.quoteTokens, msg.id, msg.quoteToken)
|
|
197
|
+
remember(this.senders, msg.id, sender)
|
|
198
|
+
|
|
199
|
+
const content = this.content(msg, sender)
|
|
200
|
+
if (!content) return
|
|
201
|
+
const result = this.relay.receive({
|
|
202
|
+
id: msg.id,
|
|
203
|
+
room,
|
|
204
|
+
sender,
|
|
205
|
+
senderName: await this.memberName(ev.source).catch(() => undefined),
|
|
206
|
+
text: content.text,
|
|
207
|
+
ts: ev.timestamp,
|
|
208
|
+
attachments: content.attachments,
|
|
209
|
+
isDM,
|
|
210
|
+
mentioned: isDM || content.mentioned,
|
|
211
|
+
toOthers: content.toOthers,
|
|
212
|
+
})
|
|
213
|
+
if (result.acknowledge) this.acknowledge(() => this.acknowledgeMessage(msg.markAsReadToken, isDM ? localId(sender) : undefined))
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** 発言の本文・添付と、Bot へのメンションか、他人宛ての印があるか。扱わない種類なら undefined */
|
|
217
|
+
private content(msg: LineMessage, sender: string): { text: string; attachments: Attachment[]; mentioned: boolean; toOthers?: boolean } | undefined {
|
|
218
|
+
switch (msg.type) {
|
|
219
|
+
case "text": {
|
|
220
|
+
const mentionees = msg.mention?.mentionees ?? []
|
|
221
|
+
return {
|
|
222
|
+
text: stripSelfMentions(msg.text ?? "", mentionees),
|
|
223
|
+
attachments: [],
|
|
224
|
+
mentioned: mentionees.some((m) => m.isSelf) || this.quotesMe(msg),
|
|
225
|
+
toOthers: mentionsOthers(mentionees, sender) || this.quotesOthers(msg, sender),
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
case "image":
|
|
229
|
+
case "video":
|
|
230
|
+
case "audio":
|
|
231
|
+
// 外部の URL にあるもの(contentProvider が line 以外)は、LINE から取得できない
|
|
232
|
+
if (msg.contentProvider?.type !== "line") return undefined
|
|
233
|
+
if (msg.type !== "image") remember(this.transcoding, msg.id, true)
|
|
234
|
+
return { text: MEDIA_TEXT[msg.type], attachments: [{ name: `${msg.type}-${msg.id}`, type: msg.type }], mentioned: false }
|
|
235
|
+
case "file":
|
|
236
|
+
if (msg.fileName) remember(this.fileNames, msg.id, msg.fileName)
|
|
237
|
+
return { text: "(ファイル)", attachments: [{ name: msg.fileName ?? `file-${msg.id}`, type: "file", size: msg.fileSize }], mentioned: false }
|
|
238
|
+
case "location":
|
|
239
|
+
return { text: `(位置情報)${[msg.title, msg.address].filter(Boolean).join(" ")} (${msg.latitude}, ${msg.longitude})`, attachments: [], mentioned: false }
|
|
240
|
+
case "sticker": {
|
|
241
|
+
// text はメッセージスタンプに入力した文字。キーワードは最大 15 個あるので、先頭だけを書く
|
|
242
|
+
const label = msg.text || (msg.keywords ?? []).slice(0, 5).join("、")
|
|
243
|
+
return { text: label ? `(スタンプ:${label})` : "(スタンプ)", attachments: [], mentioned: this.quotesMe(msg), toOthers: this.quotesOthers(msg, sender) }
|
|
244
|
+
}
|
|
245
|
+
default:
|
|
246
|
+
return undefined
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Bot の発言への返信か(メンションとして扱う) */
|
|
251
|
+
private quotesMe(msg: LineMessage): boolean {
|
|
252
|
+
return msg.quotedMessageId !== undefined && this.sentIds.has(msg.quotedMessageId)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** 送信者以外の人の発言への返信か。引用元を受けていなければ、分からないので false(再起動の前の発言など) */
|
|
256
|
+
private quotesOthers(msg: LineMessage, sender: string): boolean {
|
|
257
|
+
const quoted = this.senders.get(msg.quotedMessageId ?? "")
|
|
258
|
+
return quoted !== undefined && quoted !== sender
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** 受け取りの合図(ADR 0012)。既読は、OAM の[チャット]がオンでないと API で付けられない */
|
|
262
|
+
private async acknowledgeMessage(markAsReadToken: string | undefined, dmUser: string | undefined): Promise<void> {
|
|
263
|
+
await Promise.all([
|
|
264
|
+
markAsReadToken ? this.post("/v2/bot/chat/markAsRead", { markAsReadToken }) : undefined,
|
|
265
|
+
dmUser ? this.post("/v2/bot/chat/loading/start", { chatId: dmUser, loadingSeconds: 60 }) : undefined,
|
|
266
|
+
])
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async send(room: string, text: string, opts?: { replyTo?: string; files?: string[] }): Promise<string[]> {
|
|
270
|
+
const files = opts?.files ?? []
|
|
271
|
+
// 画像を先に公開する。送れないものがあれば、何も送らずにエラーを返す
|
|
272
|
+
const images = await Promise.all(files.map((f) => this.publish(f)))
|
|
273
|
+
const bubbles = splitText(text, this.capabilities.text.max, this.capabilities.text.parts - images.length)
|
|
274
|
+
if (bubbles.length === 0 && images.length === 0) throw new Error("本文が空です")
|
|
275
|
+
const quoteToken = opts?.replyTo ? this.quoteTokens.get(opts.replyTo) : undefined
|
|
276
|
+
const messages: object[] = bubbles.map((t, i) => ({ type: "text", text: t, ...(i === 0 && quoteToken ? { quoteToken } : {}) }))
|
|
277
|
+
for (const img of images) messages.push({ type: "image", originalContentUrl: img.original, previewImageUrl: img.preview })
|
|
278
|
+
return this.deliver(room, messages)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
private async publish(path: string): Promise<{ original: string; preview: string }> {
|
|
282
|
+
if (!this.cfg.media) throw new Error("画像を送る設定がありません")
|
|
283
|
+
if (!this.publicBase) throw new Error("画像を公開する URL が分からないため、送れません。Webhook が一度届くか、RELAY_PUBLIC_URL を設定すると送れます")
|
|
284
|
+
const { original, preview } = await this.cfg.media.publish(path)
|
|
285
|
+
return { original: `${this.publicBase}/media/${original}`, preview: `${this.publicBase}/media/${preview}` }
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async sendApproval(user: string, text: string, requestId: string, opts?: { always?: boolean }): Promise<void> {
|
|
289
|
+
// 承認者の DM へ Push で送る。ボタンでも、yes/no の文字でも答えられる
|
|
290
|
+
const items = [
|
|
291
|
+
{ label: "許可", data: permissionData("allow", requestId) },
|
|
292
|
+
...(opts?.always ? [{ label: "常に許可", data: permissionData("always", requestId) }] : []),
|
|
293
|
+
{ label: "拒否", data: permissionData("deny", requestId) },
|
|
294
|
+
].map((b) => ({ type: "action", action: { type: "postback", label: b.label, data: b.data, displayText: b.label } }))
|
|
295
|
+
await this.post("/v2/bot/message/push", {
|
|
296
|
+
to: localId(user),
|
|
297
|
+
messages: [{ type: "text", text: truncate(text, this.capabilities.text.max), quickReply: { items } }],
|
|
298
|
+
})
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async notice(room: string, text: string, opts: { push?: boolean } = {}): Promise<boolean> {
|
|
302
|
+
const messages = [{ type: "text", text }]
|
|
303
|
+
// Push が許されても、使うのは 1 対 1 のトークだけ。グループと複数人トークでは、人数分の通数になる(ADR 0024)
|
|
304
|
+
if (opts.push && localId(room).startsWith("U")) {
|
|
305
|
+
await this.deliver(room, messages)
|
|
306
|
+
return true
|
|
307
|
+
}
|
|
308
|
+
// それ以外の案内は Reply でだけ送り、Push の通数を使わない
|
|
309
|
+
const token = this.takeToken(room)
|
|
310
|
+
if (!token) return false
|
|
311
|
+
await this.post("/v2/bot/message/reply", { replyToken: token, messages })
|
|
312
|
+
return true
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async download(_room: string, messageId: string, dir: string): Promise<string[]> {
|
|
316
|
+
assertNumericId(messageId)
|
|
317
|
+
if (this.transcoding.has(messageId)) {
|
|
318
|
+
const { status } = (await this.dataApi.call("GET", `/v2/bot/message/${messageId}/content/transcoding`)) as { status: string }
|
|
319
|
+
if (status === "processing") throw new Error("LINE で動画・音声を準備しているところです。しばらくしてから取得してください")
|
|
320
|
+
if (status !== "succeeded") throw new Error("LINE で動画・音声の準備に失敗したため、取得できません")
|
|
321
|
+
}
|
|
322
|
+
const res = await this.dataApi.download(`/v2/bot/message/${messageId}/content`, "first")
|
|
323
|
+
// 元の名前の拡張子が使えなければ(記号だけなど)、Content-Type から決める
|
|
324
|
+
const named = extname(this.fileNames.get(messageId) ?? "").replace(/[^.a-zA-Z0-9]/g, "")
|
|
325
|
+
const ext = named.length > 1 ? named : extension(res.headers.get("content-type") ?? "")
|
|
326
|
+
return [await saveDownload(res, dir, `${this.now()}-${messageId}`, ext)]
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async roomName(room: string): Promise<string | undefined> {
|
|
330
|
+
const id = localId(room)
|
|
331
|
+
if (!id.startsWith("C")) return undefined
|
|
332
|
+
const cached = this.names.get(room)
|
|
333
|
+
if (cached) return cached
|
|
334
|
+
const name = ((await this.api.call("GET", `/v2/bot/group/${id}/summary`)) as { groupName?: string } | null)?.groupName
|
|
335
|
+
if (name) remember(this.names, room, name)
|
|
336
|
+
return name
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private async memberName(source: Source): Promise<string | undefined> {
|
|
340
|
+
const user = source.userId
|
|
341
|
+
if (!user) return undefined
|
|
342
|
+
const key = `${source.groupId ?? source.roomId ?? ""}/${user}`
|
|
343
|
+
const cached = this.names.get(key)
|
|
344
|
+
if (cached) return cached
|
|
345
|
+
const path = source.groupId
|
|
346
|
+
? `/v2/bot/group/${source.groupId}/member/${user}`
|
|
347
|
+
: source.roomId
|
|
348
|
+
? `/v2/bot/room/${source.roomId}/member/${user}`
|
|
349
|
+
: `/v2/bot/profile/${user}`
|
|
350
|
+
const name = ((await this.api.call("GET", path)) as { displayName?: string } | null)?.displayName
|
|
351
|
+
if (name) remember(this.names, key, name)
|
|
352
|
+
return name
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Reply は通数に数えないので優先する。トークンがないか無効なら Push で送る */
|
|
356
|
+
private async deliver(room: string, messages: object[]): Promise<string[]> {
|
|
357
|
+
const token = this.takeToken(room)
|
|
358
|
+
let res: unknown
|
|
359
|
+
// 応答の本文がなくても(null)、Reply で届いていれば Push しない(二重に届き、通数も使う)
|
|
360
|
+
let delivered = false
|
|
361
|
+
if (token) {
|
|
362
|
+
try {
|
|
363
|
+
res = await this.post("/v2/bot/message/reply", { replyToken: token, messages })
|
|
364
|
+
delivered = true
|
|
365
|
+
} catch (err) {
|
|
366
|
+
// 期限切れなどで使えない Reply トークンなら、Push に回す
|
|
367
|
+
if (!(err instanceof ApiError && err.status === 400 && /reply token/i.test(err.apiMessage))) throw err
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (!delivered) {
|
|
371
|
+
res = await this.post("/v2/bot/message/push", { to: localId(room), messages }).catch((err) => {
|
|
372
|
+
if (err instanceof ApiError && err.status === 429 && /monthly limit/i.test(err.apiMessage)) {
|
|
373
|
+
throw new Error("LINE の今月の送信数の上限に達したため、送れませんでした。次に発言があれば、その返事として送れます")
|
|
374
|
+
}
|
|
375
|
+
throw err
|
|
376
|
+
})
|
|
377
|
+
}
|
|
378
|
+
return ((res as { sentMessages?: { id: string; quoteToken?: string }[] } | null)?.sentMessages ?? []).map((s) => {
|
|
379
|
+
remember(this.sentIds, s.id)
|
|
380
|
+
if (s.quoteToken) remember(this.quoteTokens, s.id, s.quoteToken)
|
|
381
|
+
return s.id
|
|
382
|
+
})
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
private liveTokens(room: string): { token: string; at: number }[] {
|
|
386
|
+
return (this.tokens.get(room) ?? []).filter((t) => this.now() - t.at < REPLY_TOKEN_TTL_MS)
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
private addToken(room: string, token: string): void {
|
|
390
|
+
this.tokens.set(room, [...this.liveTokens(room), { token, at: this.now() }])
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private takeToken(room: string): string | undefined {
|
|
394
|
+
const list = this.liveTokens(room)
|
|
395
|
+
const t = list.pop()
|
|
396
|
+
this.tokens.set(room, list)
|
|
397
|
+
return t?.token
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
private post(path: string, payload: object): Promise<unknown> {
|
|
401
|
+
return this.api.call("POST", path, payload)
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function roomOf(s: Source): string | undefined {
|
|
406
|
+
const id = s.type === "group" ? s.groupId : s.type === "room" ? s.roomId : s.userId
|
|
407
|
+
return id ? `${SERVICE}:${id}` : undefined
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** 送信者以外の人へのメンションがあるか(Bot を含む。Inbound.toOthers)。全員へのメンション(type が all)は含まない */
|
|
411
|
+
function mentionsOthers(mentionees: Mentionee[], sender: string): boolean {
|
|
412
|
+
return mentionees.some((m) => m.type === "user" && m.userId !== localId(sender))
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** 本文から Bot へのメンションを取り除く。LINE の index と length は UTF-16 の単位 */
|
|
416
|
+
export function stripSelfMentions(text: string, mentionees: Mentionee[]): string {
|
|
417
|
+
const remove = Array.from({ length: text.length }, () => false)
|
|
418
|
+
for (const m of mentionees) {
|
|
419
|
+
if (!m.isSelf || m.index < 0 || m.length <= 0 || m.index + m.length > text.length) continue
|
|
420
|
+
remove.fill(true, m.index, m.index + m.length)
|
|
421
|
+
}
|
|
422
|
+
// split("") は UTF-16 の単位で分ける
|
|
423
|
+
return text
|
|
424
|
+
.split("")
|
|
425
|
+
.filter((_, i) => !remove[i])
|
|
426
|
+
.join("")
|
|
427
|
+
.trim()
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
const EXTENSIONS: Record<string, string> = {
|
|
432
|
+
"image/jpeg": ".jpg",
|
|
433
|
+
"image/png": ".png",
|
|
434
|
+
"image/gif": ".gif",
|
|
435
|
+
"video/mp4": ".mp4",
|
|
436
|
+
"audio/x-m4a": ".m4a",
|
|
437
|
+
"audio/mp4": ".m4a",
|
|
438
|
+
"application/pdf": ".pdf",
|
|
439
|
+
"text/plain": ".txt",
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function extension(contentType: string): string {
|
|
443
|
+
return EXTENSIONS[contentType.split(";")[0]!.trim()] ?? ".bin"
|
|
444
|
+
}
|