@cmach_socket/opencode-qq-bot 0.3.4 → 0.5.1
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/NOTICE +63 -0
- package/README.md +170 -20
- package/package.json +20 -2
- package/src/bot-lock.ts +17 -26
- package/src/config.ts +218 -3
- package/src/emoji/command.ts +189 -0
- package/src/emoji/faces.ts +136 -0
- package/src/emoji/favorite-index.ts +150 -0
- package/src/emoji/favorites.ts +161 -0
- package/src/emoji/label.ts +318 -0
- package/src/home.ts +45 -0
- package/src/index.ts +156 -32
- package/src/instance.ts +30 -17
- package/src/keepalive.ts +222 -0
- package/src/logger.ts +273 -17
- package/src/media-path.ts +186 -0
- package/src/model-view.ts +130 -0
- package/src/naplink/client.ts +10 -19
- package/src/naplink/history.ts +258 -0
- package/src/naplink/media.ts +34 -103
- package/src/naplink/render.ts +96 -32
- package/src/outbound.ts +146 -0
- package/src/rate-limit.ts +161 -0
- package/src/safe-fetch.ts +143 -0
- package/src/sensitive.ts +309 -0
- package/src/session/manager.ts +232 -18
- package/src/session/prompt.ts +4 -1
- package/src/tools/ask-guard.ts +3 -2
- package/src/tools/qq.ts +218 -36
- package/src/tools/send-guard.ts +72 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import type { MessageEvent, MessageSegment, OneBotApi } from "@naplink/naplink"
|
|
2
|
+
import type { ChatTarget } from "../chat"
|
|
3
|
+
import type { Logger } from "../logger"
|
|
4
|
+
import { formatModelMessage, sanitizeSenderName } from "../model-view"
|
|
5
|
+
import type { MediaStore } from "./media"
|
|
6
|
+
import { createImageBudget, renderMessage, type PromptFile, type RenderContext } from "./render"
|
|
7
|
+
|
|
8
|
+
/** 已经投递到的位置:消息 ID 与发送时间。 */
|
|
9
|
+
export interface HistoryPosition {
|
|
10
|
+
/** 消息 ID。 */
|
|
11
|
+
id: string
|
|
12
|
+
/** 发送时间(秒)。 */
|
|
13
|
+
time: number
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** 历史回填的请求参数。 */
|
|
17
|
+
export interface HistoryOptions {
|
|
18
|
+
/** 最多补多少条历史消息。 */
|
|
19
|
+
count: number
|
|
20
|
+
/** 上次已经投递到的位置;只补它之后的消息。 */
|
|
21
|
+
since?: HistoryPosition
|
|
22
|
+
/** 本次运行已经实时处理过的消息 ID,不重复补。 */
|
|
23
|
+
exclude?: ReadonlySet<string>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 历史回填的结果。 */
|
|
27
|
+
export interface HistoryResult {
|
|
28
|
+
/** 拼在首轮消息前面的历史文本块。 */
|
|
29
|
+
text: string
|
|
30
|
+
/** 历史消息里的图片附件。 */
|
|
31
|
+
files: PromptFile[]
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 历史回填的来源,会话管理只依赖这个接口。 */
|
|
35
|
+
export interface HistoryProvider {
|
|
36
|
+
/** 拉取目标的历史消息并渲染成文本块与附件。 */
|
|
37
|
+
fetch(target: ChatTarget, options: HistoryOptions): Promise<HistoryResult>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** NapCat 历史接口返回的消息结构,只取插件用得到的字段。 */
|
|
41
|
+
interface RawMessage {
|
|
42
|
+
message_id?: number
|
|
43
|
+
message_seq?: number
|
|
44
|
+
time?: number
|
|
45
|
+
user_id?: number
|
|
46
|
+
sender?: { user_id?: number; nickname?: string; card?: string }
|
|
47
|
+
message?: MessageSegment[] | string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 补齐历史时最多翻多少页,避免长时间离线时无限翻页。 */
|
|
51
|
+
const MAX_HISTORY_PAGES = 10
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 创建历史回填的来源。
|
|
55
|
+
*
|
|
56
|
+
* 群聊与私聊都要补,NapCat 的两个历史接口参数不同,这里按目标类型分派。
|
|
57
|
+
*/
|
|
58
|
+
export function createHistoryProvider(deps: {
|
|
59
|
+
api: OneBotApi
|
|
60
|
+
logger: Logger
|
|
61
|
+
media: MediaStore
|
|
62
|
+
names?: Map<string, { name: string; expires: number }>
|
|
63
|
+
}): HistoryProvider {
|
|
64
|
+
return {
|
|
65
|
+
async fetch(target, options) {
|
|
66
|
+
const count = Math.max(0, Math.floor(options.count))
|
|
67
|
+
if (count === 0) return { text: "", files: [] }
|
|
68
|
+
|
|
69
|
+
const ctx: RenderContext = { ...deps, target }
|
|
70
|
+
const entries = options.since
|
|
71
|
+
? await fetchGap(ctx, options.since, count, options.exclude)
|
|
72
|
+
: await fetchLatest(ctx, count, options.exclude)
|
|
73
|
+
if (entries.length === 0) return { text: "", files: [] }
|
|
74
|
+
|
|
75
|
+
// 整批历史共用一份图片预算,避免单次回填塞爆上下文。
|
|
76
|
+
const budget = createImageBudget()
|
|
77
|
+
const lines: string[] = []
|
|
78
|
+
const files: PromptFile[] = []
|
|
79
|
+
for (const entry of entries) {
|
|
80
|
+
const rendered = await renderMessage(ctx, toEvent(entry), budget)
|
|
81
|
+
const text = rendered.text.trim()
|
|
82
|
+
if (!text && rendered.files.length === 0) continue
|
|
83
|
+
lines.push(
|
|
84
|
+
formatModelMessage({
|
|
85
|
+
sender: senderName(entry),
|
|
86
|
+
userId: String(entry.sender?.user_id ?? entry.user_id ?? ""),
|
|
87
|
+
text: rendered.text,
|
|
88
|
+
time: entry.time ?? 0,
|
|
89
|
+
}),
|
|
90
|
+
)
|
|
91
|
+
for (const file of rendered.files) {
|
|
92
|
+
files.push({ ...file, name: `qq-history-${files.length + 1}-${file.name}` })
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (lines.length === 0) return { text: "", files: [] }
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
text: `<history>\n之前的聊天记录(按时间顺序):\n${lines.join("\n")}\n</history>`,
|
|
99
|
+
files,
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 补最近的历史消息:新建会话时用。
|
|
107
|
+
*
|
|
108
|
+
* 已经在本次运行里实时处理过的消息要排除掉,否则会在首轮里重复出现。
|
|
109
|
+
*/
|
|
110
|
+
async function fetchLatest(
|
|
111
|
+
ctx: RenderContext,
|
|
112
|
+
count: number,
|
|
113
|
+
exclude: ReadonlySet<string> | undefined,
|
|
114
|
+
): Promise<RawMessage[]> {
|
|
115
|
+
// 多要一些,用来抵消被排除的消息。
|
|
116
|
+
const wanted = count + Math.min(exclude?.size ?? 0, count)
|
|
117
|
+
// 不传 reverse_order 或传 false:取目标 seq 往当前时间的 count 条。
|
|
118
|
+
const entries = await requestHistory(ctx, "0", wanted, false)
|
|
119
|
+
const fresh = exclude
|
|
120
|
+
? entries.filter((entry) => !exclude.has(String(entry.message_id)))
|
|
121
|
+
: entries
|
|
122
|
+
return sortByTime(fresh).slice(-count)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 补上次位置之后的历史消息:从重启中恢复时用。
|
|
127
|
+
*
|
|
128
|
+
* NapCat 的历史接口方向由 `reverse_order` 决定:传 true 才是往更早的时间翻。
|
|
129
|
+
* 所以从最新一条开始往回翻(游标取页内最旧一条的 message_id),翻到上次位置为止;
|
|
130
|
+
* 翻到的消息按时间排序后就是增量。
|
|
131
|
+
*/
|
|
132
|
+
async function fetchGap(
|
|
133
|
+
ctx: RenderContext,
|
|
134
|
+
since: HistoryPosition,
|
|
135
|
+
count: number,
|
|
136
|
+
exclude: ReadonlySet<string> | undefined,
|
|
137
|
+
): Promise<RawMessage[]> {
|
|
138
|
+
const collected: RawMessage[] = []
|
|
139
|
+
const seen = new Set<string>()
|
|
140
|
+
let cursor = "0"
|
|
141
|
+
let reached = false
|
|
142
|
+
let pages = 0
|
|
143
|
+
|
|
144
|
+
for (let page = 0; page < MAX_HISTORY_PAGES; page += 1) {
|
|
145
|
+
pages += 1
|
|
146
|
+
const entries = await requestHistory(ctx, cursor, count, true)
|
|
147
|
+
if (entries.length === 0) break
|
|
148
|
+
|
|
149
|
+
let added = 0
|
|
150
|
+
for (const entry of entries) {
|
|
151
|
+
const id = String(entry.message_id)
|
|
152
|
+
if (seen.has(id)) continue
|
|
153
|
+
seen.add(id)
|
|
154
|
+
collected.push(entry)
|
|
155
|
+
added += 1
|
|
156
|
+
if (id === since.id) reached = true
|
|
157
|
+
}
|
|
158
|
+
// 这一页没有新消息,说明往前翻不动了。
|
|
159
|
+
if (added === 0) break
|
|
160
|
+
if (reached) break
|
|
161
|
+
|
|
162
|
+
const oldest = entries.reduce((min, entry) =>
|
|
163
|
+
(entry.time ?? 0) <= (min.time ?? 0) ? entry : min,
|
|
164
|
+
)
|
|
165
|
+
const next = String(oldest.message_id)
|
|
166
|
+
if (next === cursor) break
|
|
167
|
+
cursor = next
|
|
168
|
+
}
|
|
169
|
+
if (!reached && pages >= MAX_HISTORY_PAGES) {
|
|
170
|
+
ctx.logger.warn(`历史增量超过 ${MAX_HISTORY_PAGES} 页,只补最近 ${count} 条`)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const sorted = sortByTime(collected)
|
|
174
|
+
// 命中上次位置就按位置切;没命中(位置已被清理)就按时间切。
|
|
175
|
+
const start = reached
|
|
176
|
+
? sorted.findIndex((entry) => String(entry.message_id) === since.id) + 1
|
|
177
|
+
: sorted.findIndex((entry) => (entry.time ?? 0) > since.time)
|
|
178
|
+
const fresh = sorted.slice(start < 0 ? sorted.length : start)
|
|
179
|
+
const withoutExclude = exclude
|
|
180
|
+
? fresh.filter((entry) => !exclude.has(String(entry.message_id)))
|
|
181
|
+
: fresh
|
|
182
|
+
return withoutExclude.slice(-count)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** 请求 NapCat 的历史接口;失败或没有历史时返回空列表。 */
|
|
186
|
+
async function requestHistory(
|
|
187
|
+
ctx: RenderContext,
|
|
188
|
+
cursor: string,
|
|
189
|
+
count: number,
|
|
190
|
+
reverseOrder: boolean,
|
|
191
|
+
): Promise<RawMessage[]> {
|
|
192
|
+
// 失败必须让调用方知道:把空数组当成“没有历史”会让 historyDone 被错误置位。
|
|
193
|
+
const response =
|
|
194
|
+
ctx.target.kind === "group"
|
|
195
|
+
? await ctx.api.getGroupMsgHistory({
|
|
196
|
+
group_id: ctx.target.id,
|
|
197
|
+
message_seq: cursor,
|
|
198
|
+
count,
|
|
199
|
+
reverse_order: reverseOrder,
|
|
200
|
+
})
|
|
201
|
+
: await ctx.api.getFriendMsgHistory({
|
|
202
|
+
user_id: ctx.target.id,
|
|
203
|
+
message_seq: cursor,
|
|
204
|
+
count,
|
|
205
|
+
reverse_order: reverseOrder,
|
|
206
|
+
})
|
|
207
|
+
return normalize(response)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** NapCat 返回 `{ messages: [...] }`,兼容裸数组。 */
|
|
211
|
+
function normalize(response: unknown): RawMessage[] {
|
|
212
|
+
if (Array.isArray(response)) return response as RawMessage[]
|
|
213
|
+
if (response && typeof response === "object") {
|
|
214
|
+
const messages = (response as { messages?: unknown }).messages
|
|
215
|
+
if (Array.isArray(messages)) return messages as RawMessage[]
|
|
216
|
+
}
|
|
217
|
+
return []
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 按发送时间从旧到新排序,时间相同时用消息序号稳定排序。 */
|
|
221
|
+
function sortByTime(entries: readonly RawMessage[]): RawMessage[] {
|
|
222
|
+
return [...entries].sort(
|
|
223
|
+
(a, b) => (a.time ?? 0) - (b.time ?? 0) || (a.message_seq ?? 0) - (b.message_seq ?? 0),
|
|
224
|
+
)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** 把历史消息拼成渲染器能吃的消息事件。 */
|
|
228
|
+
function toEvent(entry: RawMessage): MessageEvent {
|
|
229
|
+
const message: MessageSegment[] = Array.isArray(entry.message)
|
|
230
|
+
? entry.message
|
|
231
|
+
: [{ type: "text", data: { text: String(entry.message ?? "") } }]
|
|
232
|
+
return {
|
|
233
|
+
time: entry.time ?? 0,
|
|
234
|
+
self_id: 0,
|
|
235
|
+
post_type: "message",
|
|
236
|
+
message_type: "private",
|
|
237
|
+
sub_type: "normal",
|
|
238
|
+
message_id: entry.message_id ?? 0,
|
|
239
|
+
user_id: entry.user_id ?? 0,
|
|
240
|
+
message,
|
|
241
|
+
raw_message: "",
|
|
242
|
+
font: 0,
|
|
243
|
+
sender: {
|
|
244
|
+
user_id: entry.sender?.user_id ?? entry.user_id,
|
|
245
|
+
nickname: entry.sender?.nickname,
|
|
246
|
+
card: entry.sender?.card,
|
|
247
|
+
},
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** 历史消息里的显示名,优先用群名片。 */
|
|
252
|
+
function senderName(entry: RawMessage): string {
|
|
253
|
+
const card = entry.sender?.card?.trim()
|
|
254
|
+
if (card) return sanitizeSenderName(card)
|
|
255
|
+
const nickname = entry.sender?.nickname?.trim()
|
|
256
|
+
if (nickname) return sanitizeSenderName(nickname)
|
|
257
|
+
return sanitizeSenderName(String(entry.user_id ?? "未知用户"))
|
|
258
|
+
}
|
package/src/naplink/media.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { createHash } from "node:crypto"
|
|
2
2
|
import { access, mkdir, readdir, stat, unlink, writeFile } from "node:fs/promises"
|
|
3
|
-
import { tmpdir } from "node:os"
|
|
4
3
|
import { join } from "node:path"
|
|
5
4
|
import { pathToFileURL } from "node:url"
|
|
6
5
|
import type { Logger } from "../logger"
|
|
6
|
+
import { defaultMediaDir } from "../media-path"
|
|
7
|
+
import { type SafeFetcher, safeFetchBytes } from "../safe-fetch"
|
|
7
8
|
|
|
8
9
|
/** 单张图片下载与落盘的字节上限。 */
|
|
9
10
|
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
|
@@ -88,77 +89,27 @@ function truncateForLog(value: string, max = 120): string {
|
|
|
88
89
|
return value.length > max ? `${value.slice(0, max)}…` : value
|
|
89
90
|
}
|
|
90
91
|
|
|
91
|
-
/** 判断主机名是否指向本机或内网,避免下载请求打内网服务。 */
|
|
92
|
-
export function isPrivateHost(hostname: string): boolean {
|
|
93
|
-
let host = hostname.trim().toLowerCase()
|
|
94
|
-
if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1)
|
|
95
|
-
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) return true
|
|
96
|
-
if (host === "::1" || host === "::") return true
|
|
97
|
-
if (host.startsWith("fc") || host.startsWith("fd") || host.startsWith("fe80")) return true
|
|
98
|
-
|
|
99
|
-
const parts = host.split(".")
|
|
100
|
-
if (parts.length !== 4) return false
|
|
101
|
-
const octets = parts.map(Number)
|
|
102
|
-
if (octets.some((value) => !Number.isInteger(value) || value < 0 || value > 255)) return false
|
|
103
|
-
const [first, second] = octets
|
|
104
|
-
return (
|
|
105
|
-
first === 0 ||
|
|
106
|
-
first === 10 ||
|
|
107
|
-
first === 127 ||
|
|
108
|
-
(first === 169 && second === 254) ||
|
|
109
|
-
(first === 172 && second !== undefined && second >= 16 && second <= 31) ||
|
|
110
|
-
(first === 192 && second === 168)
|
|
111
|
-
)
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
async function readCapped(response: Response, limit: number): Promise<Uint8Array | undefined> {
|
|
115
|
-
const body = response.body
|
|
116
|
-
if (!body) {
|
|
117
|
-
const buffer = new Uint8Array(await response.arrayBuffer())
|
|
118
|
-
return buffer.byteLength > limit ? undefined : buffer
|
|
119
|
-
}
|
|
120
|
-
const reader = body.getReader()
|
|
121
|
-
const chunks: Uint8Array[] = []
|
|
122
|
-
let total = 0
|
|
123
|
-
try {
|
|
124
|
-
for (;;) {
|
|
125
|
-
const { done, value } = await reader.read()
|
|
126
|
-
if (done) break
|
|
127
|
-
if (!value) continue
|
|
128
|
-
total += value.byteLength
|
|
129
|
-
if (total > limit) {
|
|
130
|
-
await reader.cancel().catch(() => {})
|
|
131
|
-
return undefined
|
|
132
|
-
}
|
|
133
|
-
chunks.push(value)
|
|
134
|
-
}
|
|
135
|
-
} finally {
|
|
136
|
-
reader.releaseLock()
|
|
137
|
-
}
|
|
138
|
-
const buffer = new Uint8Array(total)
|
|
139
|
-
let offset = 0
|
|
140
|
-
for (const chunk of chunks) {
|
|
141
|
-
buffer.set(chunk, offset)
|
|
142
|
-
offset += chunk.byteLength
|
|
143
|
-
}
|
|
144
|
-
return buffer
|
|
145
|
-
}
|
|
146
|
-
|
|
147
92
|
function decodeBase64(value: string): Uint8Array | undefined {
|
|
148
93
|
if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(value)) return undefined
|
|
149
94
|
const bytes = Buffer.from(value, "base64")
|
|
150
95
|
return bytes.byteLength > MAX_IMAGE_BYTES ? undefined : new Uint8Array(bytes)
|
|
151
96
|
}
|
|
152
97
|
|
|
153
|
-
function parseDataUrl(uri: string): ImageBytes | undefined {
|
|
98
|
+
function parseDataUrl(uri: string, logger: Logger): ImageBytes | undefined {
|
|
154
99
|
const match = /^data:([^;,]+)?(?:;[^,]*)*;base64,(.*)$/s.exec(uri)
|
|
155
100
|
if (!match) return undefined
|
|
156
101
|
const bytes = decodeBase64(match[2] ?? "")
|
|
157
102
|
if (!bytes) return undefined
|
|
103
|
+
// 以魔数嗅探为准:URI 里声明的类型由消息发送方控制,不能直接信任。
|
|
104
|
+
const mime = mimeFromBytes(bytes)
|
|
105
|
+
if (!mime) {
|
|
106
|
+
logger.warn("data URL 图片类型无法识别")
|
|
107
|
+
return undefined
|
|
108
|
+
}
|
|
158
109
|
const declared = match[1]?.trim()
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
110
|
+
if (declared && declared !== mime) {
|
|
111
|
+
logger.warn(`data URL 声明类型与实际内容不符 declared=${declared} actual=${mime}`)
|
|
112
|
+
}
|
|
162
113
|
return { bytes, mime }
|
|
163
114
|
}
|
|
164
115
|
|
|
@@ -175,6 +126,7 @@ export class MediaStore {
|
|
|
175
126
|
private readonly root: string,
|
|
176
127
|
private readonly logger: Logger,
|
|
177
128
|
private readonly ttlMs = MEDIA_TTL_MS,
|
|
129
|
+
private readonly fetcher: SafeFetcher = safeFetchBytes,
|
|
178
130
|
) {}
|
|
179
131
|
|
|
180
132
|
private async ensureRoot(): Promise<void> {
|
|
@@ -203,7 +155,7 @@ export class MediaStore {
|
|
|
203
155
|
}
|
|
204
156
|
return { bytes, mime }
|
|
205
157
|
}
|
|
206
|
-
if (url.startsWith("data:")) return parseDataUrl(url)
|
|
158
|
+
if (url.startsWith("data:")) return parseDataUrl(url, this.logger)
|
|
207
159
|
if (!url.startsWith("http://") && !url.startsWith("https://")) {
|
|
208
160
|
this.logger.warn(`不支持的图片地址,跳过下载 url=${truncateForLog(url)}`)
|
|
209
161
|
return undefined
|
|
@@ -215,49 +167,28 @@ export class MediaStore {
|
|
|
215
167
|
} catch {
|
|
216
168
|
return undefined
|
|
217
169
|
}
|
|
218
|
-
|
|
219
|
-
|
|
170
|
+
const response = await this.fetcher(parsed, {
|
|
171
|
+
maxBytes: MAX_IMAGE_BYTES,
|
|
172
|
+
timeoutMs: IMAGE_FETCH_TIMEOUT_MS,
|
|
173
|
+
logger: this.logger,
|
|
174
|
+
})
|
|
175
|
+
if (!response) return undefined
|
|
176
|
+
if (response.bytes.byteLength > MAX_IMAGE_BYTES) {
|
|
177
|
+
this.logger.warn(`图片过大,跳过下载 bytes=${response.bytes.byteLength} url=${url}`)
|
|
220
178
|
return undefined
|
|
221
179
|
}
|
|
222
180
|
|
|
223
|
-
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
redirect: "error",
|
|
229
|
-
})
|
|
230
|
-
if (!response.ok) {
|
|
231
|
-
this.logger.warn(`下载图片失败 status=${response.status} url=${url}`)
|
|
232
|
-
return undefined
|
|
233
|
-
}
|
|
234
|
-
const lengthHeader = response.headers.get("content-length")
|
|
235
|
-
const declaredLength = lengthHeader === null ? undefined : Number(lengthHeader)
|
|
236
|
-
if (declaredLength !== undefined && Number.isFinite(declaredLength)) {
|
|
237
|
-
if (declaredLength > MAX_IMAGE_BYTES) {
|
|
238
|
-
this.logger.warn(`图片过大,跳过下载 bytes=${declaredLength} url=${url}`)
|
|
239
|
-
return undefined
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
const bytes = await readCapped(response, MAX_IMAGE_BYTES)
|
|
243
|
-
if (!bytes) {
|
|
244
|
-
this.logger.warn(`图片过大,跳过下载 url=${url}`)
|
|
245
|
-
return undefined
|
|
246
|
-
}
|
|
247
|
-
const declared = response.headers.get("content-type")?.split(";")[0]?.trim()
|
|
248
|
-
const mime =
|
|
249
|
-
declared?.startsWith("image/") === true ? declared : (mimeFromBytes(bytes) ?? undefined)
|
|
250
|
-
if (!mime) {
|
|
251
|
-
this.logger.warn(`图片类型无法识别 url=${url}`)
|
|
252
|
-
return undefined
|
|
253
|
-
}
|
|
254
|
-
return { bytes, mime }
|
|
255
|
-
} catch (error) {
|
|
256
|
-
this.logger.warn(`下载图片异常 url=${url}`, error)
|
|
181
|
+
// 声明类型只能当参考:服务器可能把 HTML 标成 image/png,或返回不支持的 svg。
|
|
182
|
+
const declared = response.contentType?.split(";")[0]?.trim()
|
|
183
|
+
const mime = mimeFromBytes(response.bytes)
|
|
184
|
+
if (!mime) {
|
|
185
|
+
this.logger.warn(`图片类型无法识别 url=${url} declared=${declared ?? "无"}`)
|
|
257
186
|
return undefined
|
|
258
|
-
} finally {
|
|
259
|
-
clearTimeout(timer)
|
|
260
187
|
}
|
|
188
|
+
if (declared?.startsWith("image/") === true && declared !== mime) {
|
|
189
|
+
this.logger.warn(`图片类型与声明不一致 declared=${declared} actual=${mime} url=${url}`)
|
|
190
|
+
}
|
|
191
|
+
return { bytes: response.bytes, mime }
|
|
261
192
|
}
|
|
262
193
|
|
|
263
194
|
private async storeBytes(bytes: Uint8Array, mime: string): Promise<StoredImage> {
|
|
@@ -307,10 +238,10 @@ export class MediaStore {
|
|
|
307
238
|
/** 创建默认的临时图片存储,并立即清理一次过期文件。 */
|
|
308
239
|
export async function createMediaStore(
|
|
309
240
|
logger: Logger,
|
|
310
|
-
options: { root?: string; ttlMs?: number } = {},
|
|
241
|
+
options: { root?: string; ttlMs?: number; fetcher?: SafeFetcher } = {},
|
|
311
242
|
): Promise<MediaStore> {
|
|
312
|
-
const root = options.root ??
|
|
313
|
-
const store = new MediaStore(root, logger, options.ttlMs)
|
|
243
|
+
const root = options.root ?? defaultMediaDir()
|
|
244
|
+
const store = new MediaStore(root, logger, options.ttlMs, options.fetcher)
|
|
314
245
|
await store.cleanup()
|
|
315
246
|
return store
|
|
316
247
|
}
|