dsh-qq-affinity 0.0.0-stage → 0.14.2
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/README.md +55 -2
- package/client.js +3550 -0
- package/cordis.patch.yml +6 -0
- package/docs/DETAIL.md +332 -0
- package/icon.svg +12 -0
- package/index.js +128 -0
- package/lib/analyze.js +777 -0
- package/lib/api.js +984 -0
- package/lib/backfill.js +146 -0
- package/lib/bridge-server.js +78 -0
- package/lib/care.js +240 -0
- package/lib/features.js +200 -0
- package/lib/home.js +168 -0
- package/lib/inbound.js +120 -0
- package/lib/llm.js +137 -0
- package/lib/media.js +161 -0
- package/lib/onebot.js +207 -0
- package/lib/parse.js +184 -0
- package/lib/recover.js +46 -0
- package/lib/store.js +705 -0
- package/lib/util.js +186 -0
- package/lib/vision.js +108 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +38 -4
- package/scripts/api-e2e.mjs +538 -0
- package/scripts/backfill-e2e.mjs +142 -0
- package/scripts/backfill-live.mjs +60 -0
- package/scripts/bridge-e2e.mjs +137 -0
- package/scripts/care-e2e.mjs +217 -0
- package/scripts/check-hook-order.mjs +83 -0
- package/scripts/make-napcat-config.mjs +87 -0
- package/scripts/media-e2e.mjs +103 -0
- package/scripts/recover-e2e.mjs +75 -0
- package/scripts/selftest.mjs +159 -0
- package/scripts/strip-bom.mjs +27 -0
package/lib/api.js
ADDED
|
@@ -0,0 +1,984 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin's Host HTTP API. Every route sits below `/api`, so the Harness
|
|
3
|
+
* Connection admits it with the same browser credential and trust checks the
|
|
4
|
+
* rest of the GUI uses; nothing here is reachable from another origin.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import { clamp, isAiAuthored, styleReply } from './util.js'
|
|
10
|
+
import { parseTranscript } from './parse.js'
|
|
11
|
+
import { scorePerson, suggestReplies, analyzePersona, analyzeSelf } from './analyze.js'
|
|
12
|
+
import { routeFor } from './llm.js'
|
|
13
|
+
import { modelSeesImages } from './vision.js'
|
|
14
|
+
import { measure } from './features.js'
|
|
15
|
+
import { defaultCare } from './store.js'
|
|
16
|
+
import { probe, send as sendThroughBridge } from './onebot.js'
|
|
17
|
+
import { describeLocation, expandPath, relocate, resetLocation } from './home.js'
|
|
18
|
+
import { backfillAll, backfillConversation, AUTO_BACKFILL_COUNT } from './backfill.js'
|
|
19
|
+
|
|
20
|
+
/** The path the bridge must post its reports to, served outside `/api`. */
|
|
21
|
+
export const INBOUND_PATH = '/qq-affinity/onebot'
|
|
22
|
+
|
|
23
|
+
/** One JSON answer with the given status. */
|
|
24
|
+
function json(body, status = 200) {
|
|
25
|
+
return new Response(JSON.stringify(body), {
|
|
26
|
+
status,
|
|
27
|
+
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One failure answer; `error` is always a sentence the panel can show. */
|
|
32
|
+
function fail(message, status = 400, extra = {}) {
|
|
33
|
+
return json({ ok: false, error: message, ...extra }, status)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Read a JSON object body, rejecting anything else. */
|
|
37
|
+
async function readBody(request) {
|
|
38
|
+
let value
|
|
39
|
+
try {
|
|
40
|
+
value = await request.json()
|
|
41
|
+
} catch {
|
|
42
|
+
throw new Error('请求体不是合法的 JSON。')
|
|
43
|
+
}
|
|
44
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('请求体必须是 JSON 对象。')
|
|
45
|
+
return value
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A string field with a length bound. */
|
|
49
|
+
function textField(value, limit, fallback = '') {
|
|
50
|
+
if (typeof value !== 'string') return fallback
|
|
51
|
+
return value.trim().slice(0, limit)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Append one line to a log file inside the archive.
|
|
56
|
+
*
|
|
57
|
+
* Used for the two flows with no visible server-side effect when they fail, so
|
|
58
|
+
* "did the request arrive at all" stays answerable without asking the user to
|
|
59
|
+
* read a toast.
|
|
60
|
+
*/
|
|
61
|
+
function appendArchiveLog(store, file, message) {
|
|
62
|
+
try {
|
|
63
|
+
fs.appendFileSync(path.join(store.directory, file), `${new Date().toISOString()} ${message}\n`, 'utf8')
|
|
64
|
+
} catch {
|
|
65
|
+
// Logging must never break the request it describes.
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Trace one reorder request. */
|
|
70
|
+
function logOrder(store, message) {
|
|
71
|
+
appendArchiveLog(store, 'reorder.log', message)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Which half of "can we read images" is a model round trip, and which half is
|
|
76
|
+
* just a setting read.
|
|
77
|
+
*
|
|
78
|
+
* Only the capability is cached: the user's switch must take effect on the next
|
|
79
|
+
* poll, and a stale `allowed` would make the toggle look broken.
|
|
80
|
+
* @returns {Promise<{ attachmentService: boolean, provider: string, model: string, modelSeesImages: boolean }>}
|
|
81
|
+
*/
|
|
82
|
+
async function visionCapability(ctx) {
|
|
83
|
+
const route = await routeFor(ctx).catch(() => ({ provider: '', model: '' }))
|
|
84
|
+
const hasAttachments = ctx.get('attachments') !== undefined
|
|
85
|
+
const sees = hasAttachments ? await modelSeesImages(ctx, route.provider, route.model) : false
|
|
86
|
+
return {
|
|
87
|
+
attachmentService: hasAttachments,
|
|
88
|
+
provider: route.provider,
|
|
89
|
+
model: route.model,
|
|
90
|
+
modelSeesImages: sees,
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Compose the full vision status from the cached capability and the live setting. */
|
|
95
|
+
function visionStatus(store, capability) {
|
|
96
|
+
const allowed = store.state.settings.visionImages !== false
|
|
97
|
+
return {
|
|
98
|
+
...capability,
|
|
99
|
+
allowed,
|
|
100
|
+
ready: allowed && capability.attachmentService === true && capability.modelSeesImages === true,
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The public view of one person, joined with its score when one exists. */
|
|
105
|
+
function personView(store, uin, transcripts) {
|
|
106
|
+
const person = store.person(uin)
|
|
107
|
+
if (person === undefined) return undefined
|
|
108
|
+
/** Every enabled conversation that mentions this person, with its rows already read. */
|
|
109
|
+
const relevant = transcripts.filter(entry => entry.conversation.peerUin === uin
|
|
110
|
+
|| (entry.conversation.participants ?? []).includes(uin))
|
|
111
|
+
const messageRows = relevant.reduce((total, entry) => total + entry.rows
|
|
112
|
+
.filter(row => row.senderUin === uin || row.direction === 'out').length, 0)
|
|
113
|
+
// The remark the user typed for this person, taken from their private chat.
|
|
114
|
+
const privateChat = store.state.conversations.find(entry => entry.kind === 'c2c'
|
|
115
|
+
&& entry.peerUin === uin && typeof entry.title === 'string' && entry.title.trim() !== '')
|
|
116
|
+
// Who is this? A person the user added as a private chat is "someone I chose";
|
|
117
|
+
// anyone else only appears because they spoke in a group the user turned on.
|
|
118
|
+
const anyPrivateChat = store.state.conversations.find(entry => entry.kind === 'c2c' && entry.peerUin === uin)
|
|
119
|
+
return {
|
|
120
|
+
uin,
|
|
121
|
+
names: person.names,
|
|
122
|
+
remark: privateChat === undefined ? '' : privateChat.title.trim(),
|
|
123
|
+
origin: anyPrivateChat === undefined ? 'group' : 'private',
|
|
124
|
+
messageCount: person.messageCount,
|
|
125
|
+
firstSeen: person.firstSeen,
|
|
126
|
+
lastSeen: person.lastSeen,
|
|
127
|
+
conversationIds: person.conversationIds,
|
|
128
|
+
contributingConversations: relevant.map(entry => entry.conversation.id),
|
|
129
|
+
score: store.score(uin) ?? null,
|
|
130
|
+
persona: store.persona(uin) ?? null,
|
|
131
|
+
messageRows,
|
|
132
|
+
care: store.careFor(uin) ?? { ...defaultCare(), uin, enabled: false },
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Build the whole panel snapshot, reading each enabled transcript once. */
|
|
137
|
+
function stateOf(store, engine, bridgeStatus = {}) {
|
|
138
|
+
// Reading every transcript once keeps this snapshot linear instead of
|
|
139
|
+
// re-scanning the store for each person it lists.
|
|
140
|
+
const transcripts = store.state.conversations
|
|
141
|
+
.filter(row => row.enabled === true)
|
|
142
|
+
.map(conversation => ({ conversation, rows: store.messages(conversation.id) }))
|
|
143
|
+
// A user-arranged order wins; ids it does not mention keep their natural order
|
|
144
|
+
// after the arranged ones (sort is stable).
|
|
145
|
+
const rankOf = (kind) => {
|
|
146
|
+
const map = new Map()
|
|
147
|
+
store.state.order[kind].forEach((id, index) => map.set(id, index))
|
|
148
|
+
return (id) => (map.has(id) ? map.get(id) : Number.MAX_SAFE_INTEGER)
|
|
149
|
+
}
|
|
150
|
+
const peopleRank = rankOf('people')
|
|
151
|
+
const conversationRank = rankOf('conversations')
|
|
152
|
+
const people = Object.keys(store.state.people)
|
|
153
|
+
.map(uin => personView(store, uin, transcripts))
|
|
154
|
+
.filter(row => row !== undefined)
|
|
155
|
+
.sort((a, b) => {
|
|
156
|
+
const left = peopleRank(a.uin)
|
|
157
|
+
const right = peopleRank(b.uin)
|
|
158
|
+
if (left !== right) return left - right
|
|
159
|
+
return (b.messageCount ?? 0) - (a.messageCount ?? 0)
|
|
160
|
+
})
|
|
161
|
+
const orderedConversations = [...store.state.conversations]
|
|
162
|
+
.sort((a, b) => conversationRank(a.id) - conversationRank(b.id))
|
|
163
|
+
const outbox = store.outbox()
|
|
164
|
+
return {
|
|
165
|
+
ok: true,
|
|
166
|
+
dataDir: store.directory,
|
|
167
|
+
location: describeLocation(store.directory),
|
|
168
|
+
settings: store.state.settings,
|
|
169
|
+
channel: {
|
|
170
|
+
available: engine !== undefined,
|
|
171
|
+
inboundPath: INBOUND_PATH,
|
|
172
|
+
enabled: store.state.settings.onebot.enabled === true,
|
|
173
|
+
lastInboundAt: store.state.settings.onebot.lastInboundAt,
|
|
174
|
+
hasInboundToken: store.state.settings.onebot.inboundToken !== '',
|
|
175
|
+
autoBackfill: store.state.settings.onebot.autoBackfill === true,
|
|
176
|
+
lastBackfillAt: store.state.settings.onebot.lastBackfillAt,
|
|
177
|
+
// The fixed-port listener the bridge should be pointed at.
|
|
178
|
+
bridgeListening: bridgeStatus.listening === true,
|
|
179
|
+
bridgePort: bridgeStatus.port,
|
|
180
|
+
bridgeUrl: bridgeStatus.url ?? '',
|
|
181
|
+
bridgeError: bridgeStatus.error ?? '',
|
|
182
|
+
},
|
|
183
|
+
careAutoActive: Object.values(store.state.care).filter(entry => entry.enabled === true && entry.mode === 'auto').length,
|
|
184
|
+
pinned: store.state.pinned.slice(),
|
|
185
|
+
selfProfile: store.selfProfile(),
|
|
186
|
+
// Comparing the two versions is how a stale client bundle exposes itself.
|
|
187
|
+
versions: {
|
|
188
|
+
host: bridgeStatus.version ?? '',
|
|
189
|
+
client: bridgeStatus.clientVersion ?? '',
|
|
190
|
+
},
|
|
191
|
+
careUsage: engine?.usage?.() ?? {},
|
|
192
|
+
careActive: store.activeCare().length,
|
|
193
|
+
draftCount: outbox.filter(row => row.status === 'draft').length,
|
|
194
|
+
conversations: orderedConversations.map(row => ({
|
|
195
|
+
...row,
|
|
196
|
+
// Only an enabled conversation is read; the panel mirrors that in the UI.
|
|
197
|
+
readable: row.enabled === true,
|
|
198
|
+
aiAuthored: outbox.filter(entry => entry.conversationId === row.id && entry.status === 'sent').length,
|
|
199
|
+
})),
|
|
200
|
+
people,
|
|
201
|
+
adoptions: store.state.adoptions.map(row => ({
|
|
202
|
+
id: row.id,
|
|
203
|
+
conversationId: row.conversationId,
|
|
204
|
+
targetUin: row.targetUin,
|
|
205
|
+
createdAt: row.createdAt,
|
|
206
|
+
matched: (row.matchedMessageIds ?? []).length,
|
|
207
|
+
})),
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Build every route this plugin serves.
|
|
213
|
+
* @param {object} ctx - Cordis context.
|
|
214
|
+
* @param {import('./store.js').Store} store
|
|
215
|
+
* @param {object} [engine] - the automatic reply engine, from `lib/care.js`.
|
|
216
|
+
* @param {object} [bridge] - live status of the fixed-port listener.
|
|
217
|
+
* @param {{ send?: Function }} [overrides] - injectable message sender, for tests.
|
|
218
|
+
* @returns {Array<{ path: string, method: 'GET' | 'POST', requestBody: 'buffered', fetch: (request: Request) => Promise<Response> }>}
|
|
219
|
+
*/
|
|
220
|
+
export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
|
|
221
|
+
const deps = {
|
|
222
|
+
send: overrides.send ?? sendThroughBridge,
|
|
223
|
+
backfill: overrides.backfill ?? backfillConversation,
|
|
224
|
+
}
|
|
225
|
+
const bridgeStatus = bridge ?? { listening: false, port: 0, url: '', error: 'not started' }
|
|
226
|
+
if (overrides.version !== undefined) bridgeStatus.version = overrides.version
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The batch refresh job. In-memory only: a plugin reload resets it, and the
|
|
230
|
+
* panel just stops showing progress.
|
|
231
|
+
*/
|
|
232
|
+
const refreshJob = {
|
|
233
|
+
running: false,
|
|
234
|
+
total: 0,
|
|
235
|
+
done: 0,
|
|
236
|
+
failed: 0,
|
|
237
|
+
current: '',
|
|
238
|
+
startedAt: '',
|
|
239
|
+
results: [],
|
|
240
|
+
abort: null,
|
|
241
|
+
}
|
|
242
|
+
const jobView = () => ({
|
|
243
|
+
running: refreshJob.running,
|
|
244
|
+
total: refreshJob.total,
|
|
245
|
+
done: refreshJob.done,
|
|
246
|
+
failed: refreshJob.failed,
|
|
247
|
+
current: refreshJob.current,
|
|
248
|
+
startedAt: refreshJob.startedAt,
|
|
249
|
+
results: refreshJob.results.slice(-10),
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
/** Refresh every profiled person: scores always, personas only when one exists. */
|
|
253
|
+
async function runRefreshAll() {
|
|
254
|
+
if (refreshJob.running) return
|
|
255
|
+
refreshJob.running = true
|
|
256
|
+
refreshJob.total = 0
|
|
257
|
+
refreshJob.done = 0
|
|
258
|
+
refreshJob.failed = 0
|
|
259
|
+
refreshJob.current = ''
|
|
260
|
+
refreshJob.results = []
|
|
261
|
+
refreshJob.startedAt = new Date().toISOString()
|
|
262
|
+
refreshJob.abort = new AbortController()
|
|
263
|
+
// Only people the user opened a private chat with. Someone who merely spoke
|
|
264
|
+
// in a group is not a profile the user maintains, so a batch refresh must not
|
|
265
|
+
// spend model calls on them.
|
|
266
|
+
const privateUins = new Set(store.state.conversations
|
|
267
|
+
.filter(row => row.kind === 'c2c' && typeof row.peerUin === 'string' && row.peerUin !== '')
|
|
268
|
+
.map(row => row.peerUin))
|
|
269
|
+
// Busiest people first, so the visible rows update earliest.
|
|
270
|
+
const targets = Object.keys(store.state.people)
|
|
271
|
+
.filter(uin => privateUins.has(uin))
|
|
272
|
+
.sort((left, right) => (store.state.people[right]?.messageCount ?? 0) - (store.state.people[left]?.messageCount ?? 0))
|
|
273
|
+
refreshJob.total = targets.length
|
|
274
|
+
let cursor = 0
|
|
275
|
+
const worker = async () => {
|
|
276
|
+
while (cursor < targets.length) {
|
|
277
|
+
if (!refreshJob.running) return
|
|
278
|
+
const uin = targets[cursor]
|
|
279
|
+
cursor += 1
|
|
280
|
+
refreshJob.current = uin
|
|
281
|
+
const outcome = { uin, score: false, persona: false, error: '' }
|
|
282
|
+
try {
|
|
283
|
+
await scorePerson(ctx, store, uin, { signal: refreshJob.abort.signal })
|
|
284
|
+
outcome.score = true
|
|
285
|
+
} catch (error) {
|
|
286
|
+
if (!refreshJob.running) return
|
|
287
|
+
outcome.error = error instanceof Error ? error.message : String(error)
|
|
288
|
+
}
|
|
289
|
+
if (outcome.error === '' && store.persona(uin) !== undefined) {
|
|
290
|
+
try {
|
|
291
|
+
await analyzePersona(ctx, store, uin, { signal: refreshJob.abort.signal })
|
|
292
|
+
outcome.persona = true
|
|
293
|
+
} catch {
|
|
294
|
+
// A persona refresh failure must not fail the batch.
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
refreshJob.done += 1
|
|
298
|
+
if (outcome.error !== '') refreshJob.failed += 1
|
|
299
|
+
refreshJob.results.push(outcome)
|
|
300
|
+
if (refreshJob.results.length > 200) refreshJob.results.splice(0, refreshJob.results.length - 200)
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
// Two at a time: faster than one, still polite to the model provider.
|
|
304
|
+
await Promise.all([worker(), worker()])
|
|
305
|
+
refreshJob.running = false
|
|
306
|
+
refreshJob.current = ''
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Turn one conversation on and pull its most recent messages.
|
|
311
|
+
*
|
|
312
|
+
* Adding or switching a conversation on is the user's act of consent, so this
|
|
313
|
+
* is the moment history is fetched — but only when the live channel is on:
|
|
314
|
+
* without a bridge there is nothing to fetch, and the report would just be an
|
|
315
|
+
* error the user cannot act on.
|
|
316
|
+
* @returns {Promise<object | undefined>} a backfill report, or undefined when skipped.
|
|
317
|
+
*/
|
|
318
|
+
const autoPull = async (conversation) => {
|
|
319
|
+
if (conversation === undefined) return undefined
|
|
320
|
+
const bridge = store.state.settings.onebot
|
|
321
|
+
if (bridge.enabled !== true) return { action: 'skipped', reason: 'channel-off', fetched: 0, added: 0, duplicates: 0 }
|
|
322
|
+
if (conversation.enabled !== true) store.setEnabled(conversation.id, true)
|
|
323
|
+
const report = await deps.backfill({
|
|
324
|
+
store,
|
|
325
|
+
bridge,
|
|
326
|
+
conversation: store.conversation(conversation.id),
|
|
327
|
+
count: AUTO_BACKFILL_COUNT,
|
|
328
|
+
})
|
|
329
|
+
if (report.added > 0) {
|
|
330
|
+
store.state.settings.onebot.lastBackfillAt = new Date().toISOString()
|
|
331
|
+
store.save()
|
|
332
|
+
}
|
|
333
|
+
return report
|
|
334
|
+
}
|
|
335
|
+
/** Wrap one handler so a thrown message becomes a readable failure. */
|
|
336
|
+
const guard = (handler) => async (request) => {
|
|
337
|
+
try {
|
|
338
|
+
return await handler(request)
|
|
339
|
+
} catch (error) {
|
|
340
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
341
|
+
ctx.logger?.warn?.(`qq-affinity: ${message}`)
|
|
342
|
+
return fail(message, 400)
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return [
|
|
347
|
+
{
|
|
348
|
+
path: '/api/qq-affinity/state',
|
|
349
|
+
method: 'GET',
|
|
350
|
+
requestBody: 'buffered',
|
|
351
|
+
fetch: guard(async (request) => {
|
|
352
|
+
// Remember which client build is asking, so a stale bundle is visible in
|
|
353
|
+
// the response instead of looking like a broken feature.
|
|
354
|
+
const version = new URL(request.url).searchParams.get('v') ?? ''
|
|
355
|
+
if (version !== '') bridgeStatus.clientVersion = version.slice(0, 24)
|
|
356
|
+
// One line per changed version: the panel polls state constantly, and the
|
|
357
|
+
// log only needs to answer "which build is actually running".
|
|
358
|
+
if (bridgeStatus.lastSeenClient !== version) {
|
|
359
|
+
bridgeStatus.lastSeenClient = version
|
|
360
|
+
appendArchiveLog(store, 'client.log', `state v=${version === '' ? '(none)' : version.slice(0, 24)}`)
|
|
361
|
+
}
|
|
362
|
+
const snapshot = stateOf(store, engine, bridgeStatus)
|
|
363
|
+
// Resolving model capability is a round trip; one answer per few seconds
|
|
364
|
+
// is plenty for a panel that polls.
|
|
365
|
+
const now = Date.now()
|
|
366
|
+
if (bridgeStatus.visionCache === undefined || now - bridgeStatus.visionCache.at > 15000) {
|
|
367
|
+
bridgeStatus.visionCache = { at: now, value: await visionCapability(ctx) }
|
|
368
|
+
}
|
|
369
|
+
snapshot.vision = visionStatus(store, bridgeStatus.visionCache.value)
|
|
370
|
+
return json(snapshot)
|
|
371
|
+
}),
|
|
372
|
+
},
|
|
373
|
+
{
|
|
374
|
+
path: '/api/qq-affinity/messages',
|
|
375
|
+
method: 'GET',
|
|
376
|
+
requestBody: 'buffered',
|
|
377
|
+
fetch: guard(async (request) => {
|
|
378
|
+
const url = new URL(request.url)
|
|
379
|
+
const conversationId = url.searchParams.get('conversationId') ?? ''
|
|
380
|
+
const limit = clamp(Number(url.searchParams.get('limit') ?? 80), 10, 500)
|
|
381
|
+
const conversation = store.conversation(conversationId)
|
|
382
|
+
if (conversation === undefined) return fail('找不到这个对话。', 404)
|
|
383
|
+
if (conversation.enabled !== true) {
|
|
384
|
+
return json({ ok: true, enabled: false, messages: [], note: '这个对话没有开启,插件不会读取它的内容。' })
|
|
385
|
+
}
|
|
386
|
+
const rows = store.messages(conversationId)
|
|
387
|
+
const features = measure(rows, conversation.peerUin)
|
|
388
|
+
return json({
|
|
389
|
+
ok: true,
|
|
390
|
+
enabled: true,
|
|
391
|
+
conversation,
|
|
392
|
+
features,
|
|
393
|
+
outbox: store.outboxFor(conversationId, 20),
|
|
394
|
+
care: store.careFor(conversation.peerUin) ?? null,
|
|
395
|
+
messages: rows.slice(-limit).map(row => ({
|
|
396
|
+
id: row.id,
|
|
397
|
+
ts: row.ts,
|
|
398
|
+
senderName: row.senderName,
|
|
399
|
+
senderUin: row.senderUin,
|
|
400
|
+
direction: row.direction,
|
|
401
|
+
text: row.text,
|
|
402
|
+
aiAdopted: row.aiAdopted === true,
|
|
403
|
+
aiAuto: row.aiAuto === true,
|
|
404
|
+
aiAuthored: isAiAuthored(row),
|
|
405
|
+
})),
|
|
406
|
+
})
|
|
407
|
+
}),
|
|
408
|
+
},
|
|
409
|
+
{
|
|
410
|
+
path: '/api/qq-affinity/suggestions',
|
|
411
|
+
method: 'GET',
|
|
412
|
+
requestBody: 'buffered',
|
|
413
|
+
fetch: guard(async (request) => {
|
|
414
|
+
const conversationId = new URL(request.url).searchParams.get('conversationId') ?? ''
|
|
415
|
+
if (store.conversation(conversationId) === undefined) return fail('找不到这个对话。', 404)
|
|
416
|
+
return json({ ok: true, batches: store.suggestions(conversationId) })
|
|
417
|
+
}),
|
|
418
|
+
},
|
|
419
|
+
{
|
|
420
|
+
path: '/api/qq-affinity/settings',
|
|
421
|
+
method: 'POST',
|
|
422
|
+
requestBody: 'buffered',
|
|
423
|
+
fetch: guard(async (request) => {
|
|
424
|
+
const body = await readBody(request)
|
|
425
|
+
if (typeof body.selfUin === 'string') {
|
|
426
|
+
const next = body.selfUin.replace(/\D/g, '').slice(0, 12)
|
|
427
|
+
if (next !== store.state.settings.selfUin) {
|
|
428
|
+
store.state.settings.selfUin = next
|
|
429
|
+
// Direction is derived from this value, so stored rows are re-derived.
|
|
430
|
+
rederiveDirections(store, next)
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (typeof body.selfName === 'string') store.state.settings.selfName = textField(body.selfName, 60)
|
|
434
|
+
if (body.maxTranscriptChars !== undefined) {
|
|
435
|
+
store.state.settings.maxTranscriptChars = Math.round(clamp(body.maxTranscriptChars, 2000, 60000))
|
|
436
|
+
}
|
|
437
|
+
if (typeof body.careEnabled === 'boolean') store.state.settings.careEnabled = body.careEnabled
|
|
438
|
+
if (typeof body.visionImages === 'boolean') store.state.settings.visionImages = body.visionImages
|
|
439
|
+
if (body.onebot !== null && typeof body.onebot === 'object') {
|
|
440
|
+
const bridge = store.state.settings.onebot
|
|
441
|
+
const before = { apiBase: bridge.apiBase, accessToken: bridge.accessToken }
|
|
442
|
+
if (typeof body.onebot.apiBase === 'string') bridge.apiBase = textField(body.onebot.apiBase, 200) || 'http://127.0.0.1:3001'
|
|
443
|
+
if (typeof body.onebot.accessToken === 'string') bridge.accessToken = body.onebot.accessToken.trim().slice(0, 200)
|
|
444
|
+
if (typeof body.onebot.inboundToken === 'string') bridge.inboundToken = body.onebot.inboundToken.trim().slice(0, 200)
|
|
445
|
+
if (typeof body.onebot.enabled === 'boolean') bridge.enabled = body.onebot.enabled
|
|
446
|
+
if (typeof body.onebot.autoBackfill === 'boolean') bridge.autoBackfill = body.onebot.autoBackfill
|
|
447
|
+
// A changed endpoint or token invalidates the last successful probe: the
|
|
448
|
+
// panel must not keep claiming the bridge is reachable.
|
|
449
|
+
if (bridge.apiBase !== before.apiBase || bridge.accessToken !== before.accessToken) bridge.enabled = false
|
|
450
|
+
}
|
|
451
|
+
store.save()
|
|
452
|
+
return json(stateOf(store, engine, bridgeStatus))
|
|
453
|
+
}),
|
|
454
|
+
},
|
|
455
|
+
{
|
|
456
|
+
path: '/api/qq-affinity/location',
|
|
457
|
+
method: 'POST',
|
|
458
|
+
requestBody: 'buffered',
|
|
459
|
+
fetch: guard(async (request) => {
|
|
460
|
+
const body = await readBody(request)
|
|
461
|
+
const action = textField(body.action, 20)
|
|
462
|
+
// Flush the current archive first so a migration copies what the panel shows.
|
|
463
|
+
store.save()
|
|
464
|
+
let outcome
|
|
465
|
+
if (action === 'default') {
|
|
466
|
+
outcome = resetLocation(store.directory)
|
|
467
|
+
} else if (action === 'move') {
|
|
468
|
+
outcome = relocate({
|
|
469
|
+
from: store.directory,
|
|
470
|
+
target: expandPath(body.target),
|
|
471
|
+
mode: body.mode === 'switch' ? 'switch' : 'migrate',
|
|
472
|
+
cleanup: body.cleanup === true,
|
|
473
|
+
})
|
|
474
|
+
} else {
|
|
475
|
+
return fail(`未知操作:${action}`)
|
|
476
|
+
}
|
|
477
|
+
store.retarget(outcome.directory)
|
|
478
|
+
// Materialize meta.json so an empty target becomes a real archive.
|
|
479
|
+
store.save()
|
|
480
|
+
return json({
|
|
481
|
+
ok: true,
|
|
482
|
+
outcome,
|
|
483
|
+
note: outcome.mode === 'migrate' && outcome.cleanup !== true
|
|
484
|
+
? `原来的数据仍留在 ${outcome.previous},确认新位置没问题后可以手动删除。`
|
|
485
|
+
: '',
|
|
486
|
+
state: stateOf(store, engine, bridgeStatus),
|
|
487
|
+
})
|
|
488
|
+
}),
|
|
489
|
+
},
|
|
490
|
+
{
|
|
491
|
+
path: '/api/qq-affinity/pinned',
|
|
492
|
+
method: 'POST',
|
|
493
|
+
requestBody: 'buffered',
|
|
494
|
+
fetch: guard(async (request) => {
|
|
495
|
+
const body = await readBody(request)
|
|
496
|
+
const id = textField(body.id, 80)
|
|
497
|
+
const action = textField(body.action, 20)
|
|
498
|
+
if (store.conversation(id) === undefined) return fail('找不到这个对话。', 404)
|
|
499
|
+
if (action === 'toggle') {
|
|
500
|
+
const isPinned = store.state.pinned.includes(id)
|
|
501
|
+
const pinned = isPinned ? store.unpin(id) : store.pin(id)
|
|
502
|
+
return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus) })
|
|
503
|
+
}
|
|
504
|
+
if (action === 'move') {
|
|
505
|
+
const delta = Math.round(Number(body.delta))
|
|
506
|
+
const pinned = store.movePinned(id, Number.isFinite(delta) ? delta : 0)
|
|
507
|
+
return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus) })
|
|
508
|
+
}
|
|
509
|
+
return fail(`未知操作:${action}`)
|
|
510
|
+
}),
|
|
511
|
+
},
|
|
512
|
+
{
|
|
513
|
+
// One route for start / status / cancel: the Connection refuses two
|
|
514
|
+
// registrations on the same path even with different methods.
|
|
515
|
+
path: '/api/qq-affinity/refresh-all',
|
|
516
|
+
method: 'POST',
|
|
517
|
+
requestBody: 'buffered',
|
|
518
|
+
fetch: guard(async (request) => {
|
|
519
|
+
const body = await readBody(request)
|
|
520
|
+
const action = textField(body.action, 20)
|
|
521
|
+
if (action === 'status') return json({ ok: true, job: jobView(), state: stateOf(store, engine, bridgeStatus) })
|
|
522
|
+
if (action === 'cancel') {
|
|
523
|
+
if (!refreshJob.running) return fail('当前没有正在进行的更新。', 409)
|
|
524
|
+
refreshJob.running = false
|
|
525
|
+
refreshJob.abort?.abort()
|
|
526
|
+
return json({ ok: true, job: jobView() })
|
|
527
|
+
}
|
|
528
|
+
if (refreshJob.running) return fail('已经有一个更新在跑了,先取消或等它跑完。', 409)
|
|
529
|
+
void runRefreshAll()
|
|
530
|
+
return json({ ok: true, job: jobView() })
|
|
531
|
+
}),
|
|
532
|
+
},
|
|
533
|
+
{
|
|
534
|
+
path: '/api/qq-affinity/order',
|
|
535
|
+
method: 'POST',
|
|
536
|
+
requestBody: 'buffered',
|
|
537
|
+
fetch: guard(async (request) => {
|
|
538
|
+
const body = await readBody(request)
|
|
539
|
+
const kind = textField(body.kind, 20)
|
|
540
|
+
const ok = kind === 'conversations' || kind === 'people'
|
|
541
|
+
if (!ok) {
|
|
542
|
+
logOrder(store, `rejected kind=${kind}`)
|
|
543
|
+
return fail(`未知的列表:${kind}`)
|
|
544
|
+
}
|
|
545
|
+
if (!Array.isArray(body.ids)) {
|
|
546
|
+
logOrder(store, `rejected ${kind}: ids not an array`)
|
|
547
|
+
return fail('ids 必须是数组。')
|
|
548
|
+
}
|
|
549
|
+
let ordered
|
|
550
|
+
try {
|
|
551
|
+
ordered = store.setOrder(kind, body.ids)
|
|
552
|
+
} catch (error) {
|
|
553
|
+
// A write failure must be visible in the request log, not only in a toast.
|
|
554
|
+
logOrder(store, `write failed ${kind}: ${error instanceof Error ? error.message : String(error)}`)
|
|
555
|
+
throw error
|
|
556
|
+
}
|
|
557
|
+
if (ordered === undefined) {
|
|
558
|
+
logOrder(store, `missing ${kind}`)
|
|
559
|
+
return fail('保存顺序失败。', 500)
|
|
560
|
+
}
|
|
561
|
+
logOrder(store, `saved ${kind} count=${ordered.length}`)
|
|
562
|
+
return json({ ok: true, kind, order: ordered, state: stateOf(store, engine, bridgeStatus) })
|
|
563
|
+
}),
|
|
564
|
+
},
|
|
565
|
+
{
|
|
566
|
+
path: '/api/qq-affinity/care',
|
|
567
|
+
method: 'POST',
|
|
568
|
+
requestBody: 'buffered',
|
|
569
|
+
fetch: guard(async (request) => {
|
|
570
|
+
const body = await readBody(request)
|
|
571
|
+
const uin = textField(body.uin, 24).replace(/\D/g, '')
|
|
572
|
+
if (uin === '') return fail('缺少 QQ 号。')
|
|
573
|
+
if (store.person(uin) === undefined) return fail(`还没有 QQ ${uin} 的档案,先导入并开启一个包含 TA 的对话。`, 404)
|
|
574
|
+
if (body.patch !== null && typeof body.patch === 'object' && body.patch.enabled === true) {
|
|
575
|
+
if (store.state.settings.selfUin === '') return fail('请先填写你的 QQ 号,托管需要用它在回复时区分身份。', 409, { needsSelfUin: true })
|
|
576
|
+
}
|
|
577
|
+
const care = store.setCare(uin, body.patch !== null && typeof body.patch === 'object' ? body.patch : {})
|
|
578
|
+
if (care === undefined) return fail('保存失败。', 500)
|
|
579
|
+
return json({ ok: true, care, state: stateOf(store, engine, bridgeStatus) })
|
|
580
|
+
}),
|
|
581
|
+
},
|
|
582
|
+
{
|
|
583
|
+
path: '/api/qq-affinity/onebot/test',
|
|
584
|
+
method: 'POST',
|
|
585
|
+
requestBody: 'buffered',
|
|
586
|
+
fetch: guard(async (request) => {
|
|
587
|
+
const body = await readBody(request).catch(() => ({}))
|
|
588
|
+
// Test the values the form currently shows, not the last saved ones.
|
|
589
|
+
const draft = body !== null && typeof body.onebot === 'object' && body.onebot !== null ? body.onebot : {}
|
|
590
|
+
const bridge = {
|
|
591
|
+
apiBase: typeof draft.apiBase === 'string' && draft.apiBase.trim() !== ''
|
|
592
|
+
? draft.apiBase.trim()
|
|
593
|
+
: store.state.settings.onebot.apiBase,
|
|
594
|
+
accessToken: typeof draft.accessToken === 'string'
|
|
595
|
+
? draft.accessToken.trim()
|
|
596
|
+
: store.state.settings.onebot.accessToken,
|
|
597
|
+
}
|
|
598
|
+
if (bridge.apiBase.trim() === '') return fail('还没有填写实时通道的 API 地址。')
|
|
599
|
+
try {
|
|
600
|
+
const info = await probe(bridge)
|
|
601
|
+
const settings = store.state.settings.onebot
|
|
602
|
+
settings.apiBase = bridge.apiBase
|
|
603
|
+
settings.accessToken = bridge.accessToken
|
|
604
|
+
settings.enabled = true
|
|
605
|
+
if (store.state.settings.selfUin === '' && info.uin !== '') {
|
|
606
|
+
store.state.settings.selfUin = info.uin
|
|
607
|
+
rederiveDirections(store, info.uin)
|
|
608
|
+
}
|
|
609
|
+
store.save()
|
|
610
|
+
// With the channel proven, quietly fill in the history of every enabled
|
|
611
|
+
// conversation so the archive starts complete instead of from "now".
|
|
612
|
+
if (store.state.settings.onebot.autoBackfill === true) {
|
|
613
|
+
const bridgeSettings = { ...store.state.settings.onebot }
|
|
614
|
+
void backfillAll({ store, bridge: bridgeSettings })
|
|
615
|
+
.then((reports) => {
|
|
616
|
+
const added = reports.reduce((total, report) => total + report.added, 0)
|
|
617
|
+
if (reports.length > 0) {
|
|
618
|
+
store.state.settings.onebot.lastBackfillAt = new Date().toISOString()
|
|
619
|
+
store.save()
|
|
620
|
+
}
|
|
621
|
+
ctx.logger?.info?.(`qq-affinity: auto backfill added ${added} message(s) across ${reports.length} conversation(s)`)
|
|
622
|
+
})
|
|
623
|
+
.catch((error) => {
|
|
624
|
+
ctx.logger?.warn?.(`qq-affinity: auto backfill failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
625
|
+
})
|
|
626
|
+
}
|
|
627
|
+
return json({
|
|
628
|
+
ok: true,
|
|
629
|
+
login: info,
|
|
630
|
+
state: stateOf(store, engine, bridgeStatus),
|
|
631
|
+
})
|
|
632
|
+
} catch (error) {
|
|
633
|
+
store.state.settings.onebot.enabled = false
|
|
634
|
+
store.save()
|
|
635
|
+
return fail(`连不上实时通道:${error instanceof Error ? error.message : String(error)}`, 502, {
|
|
636
|
+
hint: '确认 NapCat / LLOneBot 已启动,HTTP API 地址正确,并且 access token 与通道设置一致。',
|
|
637
|
+
})
|
|
638
|
+
}
|
|
639
|
+
}),
|
|
640
|
+
},
|
|
641
|
+
{
|
|
642
|
+
path: '/api/qq-affinity/backfill',
|
|
643
|
+
method: 'POST',
|
|
644
|
+
requestBody: 'buffered',
|
|
645
|
+
fetch: guard(async (request) => {
|
|
646
|
+
const body = await readBody(request)
|
|
647
|
+
const bridgeSettings = store.state.settings.onebot
|
|
648
|
+
if (bridgeSettings.enabled !== true) {
|
|
649
|
+
return fail('实时通道还没接通。先到「设置 → 实时通道」里测试连接。', 409)
|
|
650
|
+
}
|
|
651
|
+
const bridge = { ...bridgeSettings }
|
|
652
|
+
const conversationId = textField(body.conversationId, 80)
|
|
653
|
+
const count = body.count
|
|
654
|
+
|
|
655
|
+
let reports
|
|
656
|
+
if (conversationId !== '') {
|
|
657
|
+
const conversation = store.conversation(conversationId)
|
|
658
|
+
if (conversation === undefined) return fail('找不到这个对话。', 404)
|
|
659
|
+
reports = [await backfillConversation({ store, bridge, conversation, count })]
|
|
660
|
+
} else {
|
|
661
|
+
reports = await backfillAll({ store, bridge, count })
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
if (reports.length > 0 && reports.some(report => report.fetched > 0)) {
|
|
665
|
+
store.state.settings.onebot.lastBackfillAt = new Date().toISOString()
|
|
666
|
+
store.save()
|
|
667
|
+
}
|
|
668
|
+
const added = reports.reduce((total, report) => total + report.added, 0)
|
|
669
|
+
const failed = reports.filter(report => typeof report.error === 'string' && report.error !== '')
|
|
670
|
+
return json({
|
|
671
|
+
ok: true,
|
|
672
|
+
added,
|
|
673
|
+
reports,
|
|
674
|
+
// Per-conversation failures are reported, not thrown: one bridge that
|
|
675
|
+
// refuses group history should not hide the private chats that worked.
|
|
676
|
+
note: failed.length === 0
|
|
677
|
+
? `补齐完成,新增 ${added} 条。`
|
|
678
|
+
: `${reports.length - failed.length} 个对话补齐,另 ${failed.length} 个没成功:${failed[0].error}`,
|
|
679
|
+
state: stateOf(store, engine, bridgeStatus),
|
|
680
|
+
})
|
|
681
|
+
}),
|
|
682
|
+
},
|
|
683
|
+
{
|
|
684
|
+
path: '/api/qq-affinity/outbox',
|
|
685
|
+
method: 'GET',
|
|
686
|
+
requestBody: 'buffered',
|
|
687
|
+
fetch: guard(async (request) => {
|
|
688
|
+
const url = new URL(request.url)
|
|
689
|
+
const conversationId = url.searchParams.get('conversationId') ?? ''
|
|
690
|
+
const uin = (url.searchParams.get('uin') ?? '').replace(/\D/g, '')
|
|
691
|
+
let rows = store.outbox()
|
|
692
|
+
if (conversationId !== '') rows = rows.filter(row => row.conversationId === conversationId)
|
|
693
|
+
if (uin !== '') rows = rows.filter(row => row.uin === uin)
|
|
694
|
+
return json({ ok: true, rows: rows.slice(-60) })
|
|
695
|
+
}),
|
|
696
|
+
},
|
|
697
|
+
{
|
|
698
|
+
path: '/api/qq-affinity/outbox/action',
|
|
699
|
+
method: 'POST',
|
|
700
|
+
requestBody: 'buffered',
|
|
701
|
+
fetch: guard(async (request) => {
|
|
702
|
+
if (engine === undefined) return fail('托管引擎没有启动。', 503)
|
|
703
|
+
const body = await readBody(request)
|
|
704
|
+
const id = textField(body.id, 80)
|
|
705
|
+
const action = textField(body.action, 20)
|
|
706
|
+
if (action === 'approve') {
|
|
707
|
+
const row = await engine.approve(id)
|
|
708
|
+
return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus) })
|
|
709
|
+
}
|
|
710
|
+
if (action === 'cancel') {
|
|
711
|
+
const row = engine.cancel(id)
|
|
712
|
+
return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus) })
|
|
713
|
+
}
|
|
714
|
+
return fail(`未知操作:${action}`)
|
|
715
|
+
}),
|
|
716
|
+
},
|
|
717
|
+
{
|
|
718
|
+
path: '/api/qq-affinity/conversation',
|
|
719
|
+
method: 'POST',
|
|
720
|
+
requestBody: 'buffered',
|
|
721
|
+
fetch: guard(async (request) => {
|
|
722
|
+
const body = await readBody(request)
|
|
723
|
+
const action = textField(body.action, 20)
|
|
724
|
+
if (action === 'create') {
|
|
725
|
+
const kind = body.kind === 'group' ? 'group' : 'c2c'
|
|
726
|
+
const title = textField(body.title, 120)
|
|
727
|
+
const peerUin = textField(body.peerUin, 24).replace(/\D/g, '')
|
|
728
|
+
const groupUin = textField(body.groupUin, 24).replace(/\D/g, '')
|
|
729
|
+
if (title === '' && peerUin === '' && groupUin === '') return fail('至少填一个名字或 QQ 号。')
|
|
730
|
+
const { conversation, created } = store.ensureConversation({ kind, title, peerUin, groupUin })
|
|
731
|
+
// A freshly added conversation is turned on and filled right away: the
|
|
732
|
+
// user adding it is the consent. The master switch still governs, so an
|
|
733
|
+
// unscoped archive never reads anything.
|
|
734
|
+
const pull = created ? await autoPull(conversation) : undefined
|
|
735
|
+
return json({
|
|
736
|
+
ok: true,
|
|
737
|
+
created,
|
|
738
|
+
conversation: store.conversation(conversation.id),
|
|
739
|
+
autoPull: pull,
|
|
740
|
+
state: stateOf(store, engine, bridgeStatus),
|
|
741
|
+
})
|
|
742
|
+
}
|
|
743
|
+
const id = textField(body.id, 80)
|
|
744
|
+
const conversation = store.conversation(id)
|
|
745
|
+
if (conversation === undefined) return fail('找不到这个对话。', 404)
|
|
746
|
+
if (action === 'toggle') {
|
|
747
|
+
store.setEnabled(id, body.enabled === true)
|
|
748
|
+
// Switching one on is also the moment to fetch its recent history.
|
|
749
|
+
const pull = body.enabled === true ? await autoPull(store.conversation(id)) : undefined
|
|
750
|
+
return json({
|
|
751
|
+
ok: true,
|
|
752
|
+
conversation: store.conversation(id),
|
|
753
|
+
autoPull: pull,
|
|
754
|
+
state: stateOf(store, engine, bridgeStatus),
|
|
755
|
+
})
|
|
756
|
+
}
|
|
757
|
+
if (action === 'update') {
|
|
758
|
+
store.updateConversation(id, {
|
|
759
|
+
title: typeof body.title === 'string' ? body.title : undefined,
|
|
760
|
+
peerUin: typeof body.peerUin === 'string' ? body.peerUin : undefined,
|
|
761
|
+
groupUin: typeof body.groupUin === 'string' ? body.groupUin : undefined,
|
|
762
|
+
})
|
|
763
|
+
return json({ ok: true, conversation: store.conversation(id), state: stateOf(store, engine, bridgeStatus) })
|
|
764
|
+
}
|
|
765
|
+
if (action === 'remove') {
|
|
766
|
+
store.removeConversation(id)
|
|
767
|
+
return json({ ok: true, state: stateOf(store, engine, bridgeStatus) })
|
|
768
|
+
}
|
|
769
|
+
return fail(`未知操作:${action}`)
|
|
770
|
+
}),
|
|
771
|
+
},
|
|
772
|
+
{
|
|
773
|
+
path: '/api/qq-affinity/import',
|
|
774
|
+
method: 'POST',
|
|
775
|
+
requestBody: 'buffered',
|
|
776
|
+
fetch: guard(async (request) => {
|
|
777
|
+
const body = await readBody(request)
|
|
778
|
+
const id = textField(body.conversationId, 80)
|
|
779
|
+
const conversation = store.conversation(id)
|
|
780
|
+
if (conversation === undefined) return fail('找不到这个对话。', 404)
|
|
781
|
+
if (conversation.enabled !== true) {
|
|
782
|
+
return fail('这个对话还没有开启。开启之后插件才会读取记录。', 409)
|
|
783
|
+
}
|
|
784
|
+
if (store.state.settings.selfUin === '') {
|
|
785
|
+
return fail('请先在设置里填写你的 QQ 号:插件需要它区分「我」和「对方」。', 409, { needsSelfUin: true })
|
|
786
|
+
}
|
|
787
|
+
const text = typeof body.text === 'string' ? body.text : ''
|
|
788
|
+
if (text.trim() === '') return fail('没有收到聊天记录内容。')
|
|
789
|
+
if (text.length > 40 * 1024 * 1024) return fail('记录太大(超过 40MB),请分次导入。')
|
|
790
|
+
|
|
791
|
+
// QQ's own export is `.bak`, which is a ZIP holding an encrypted QQ NT
|
|
792
|
+
// database. Saying "no messages found" there would send the user hunting
|
|
793
|
+
// for a format problem that does not exist, so name the real cause — and
|
|
794
|
+
// distinguish the ZIP case, because it tells the user we looked.
|
|
795
|
+
const isZip = text.startsWith('PK\u0003\u0004')
|
|
796
|
+
if (isZip || /[\u0000-\u0008\u000E-\u001F]/.test(text) || text.includes('\uFFFD')) {
|
|
797
|
+
return fail(
|
|
798
|
+
isZip
|
|
799
|
+
? '这是一个 ZIP 包,里面是加密的 QQ 消息库(db/… 几个文件,数据接近满熵)。'
|
|
800
|
+
+ '密钥在 QQ 手里,插件不解析加密库。改用「消息管理器 → 导出 → 文本(.txt)」,'
|
|
801
|
+
+ '或者直接靠实时通道同步(设置 → 实时通道)。'
|
|
802
|
+
: '这是二进制文件(QQ 导出的 .bak 就是这种),插件解析不了。'
|
|
803
|
+
+ '要走这条路只能用实时通道自动拉取(设置 → 实时通道);'
|
|
804
|
+
+ '或者从别的客户端导出成 .txt 再导入。',
|
|
805
|
+
415,
|
|
806
|
+
{ binary: true, zip: isZip },
|
|
807
|
+
)
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
const parsed = parseTranscript(text)
|
|
811
|
+
if (parsed.messages.length === 0) {
|
|
812
|
+
return fail(
|
|
813
|
+
'没能识别出任何消息。导出格式可能是 HTML/MHT,请改用文本导出的 .txt,或先复制粘贴一段带「时间 昵称(QQ号)」格式的记录。',
|
|
814
|
+
422,
|
|
815
|
+
{ stats: parsed.stats },
|
|
816
|
+
)
|
|
817
|
+
}
|
|
818
|
+
if (conversation.title === '' && parsed.title !== '') {
|
|
819
|
+
conversation.title = parsed.title
|
|
820
|
+
}
|
|
821
|
+
// A private chat needs its other half's QQ number; the export already
|
|
822
|
+
// carries it, so a conversation created without one learns it here.
|
|
823
|
+
if (conversation.kind === 'c2c' && conversation.peerUin === '') {
|
|
824
|
+
const selfUin = store.state.settings.selfUin
|
|
825
|
+
const counts = new Map()
|
|
826
|
+
for (const message of parsed.messages) {
|
|
827
|
+
if (message.senderUin === '' || message.senderUin === selfUin) continue
|
|
828
|
+
counts.set(message.senderUin, (counts.get(message.senderUin) ?? 0) + 1)
|
|
829
|
+
}
|
|
830
|
+
const learned = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]
|
|
831
|
+
if (learned !== undefined) conversation.peerUin = learned[0]
|
|
832
|
+
}
|
|
833
|
+
const before = conversation.messageCount
|
|
834
|
+
const result = store.appendMessages(id, parsed.messages)
|
|
835
|
+
const matched = store.matchAdoptions(id)
|
|
836
|
+
const after = store.conversation(id)?.messageCount ?? before
|
|
837
|
+
return json({
|
|
838
|
+
ok: true,
|
|
839
|
+
parsed: parsed.messages.length,
|
|
840
|
+
added: result.added,
|
|
841
|
+
duplicates: result.duplicates,
|
|
842
|
+
stats: parsed.stats,
|
|
843
|
+
totalMessages: after,
|
|
844
|
+
adoptedMatched: matched,
|
|
845
|
+
state: stateOf(store, engine, bridgeStatus),
|
|
846
|
+
})
|
|
847
|
+
}),
|
|
848
|
+
},
|
|
849
|
+
{
|
|
850
|
+
path: '/api/qq-affinity/score',
|
|
851
|
+
method: 'POST',
|
|
852
|
+
requestBody: 'buffered',
|
|
853
|
+
fetch: guard(async (request) => {
|
|
854
|
+
const body = await readBody(request)
|
|
855
|
+
const uin = textField(body.uin, 24).replace(/\D/g, '')
|
|
856
|
+
if (uin === '') return fail('缺少 QQ 号。')
|
|
857
|
+
if (store.person(uin) === undefined) return fail(`没有关于 QQ ${uin} 的任何记录。`, 404)
|
|
858
|
+
const result = await scorePerson(ctx, store, uin)
|
|
859
|
+
return json({ ok: true, score: result, state: stateOf(store, engine, bridgeStatus) })
|
|
860
|
+
}),
|
|
861
|
+
},
|
|
862
|
+
{
|
|
863
|
+
path: '/api/qq-affinity/self',
|
|
864
|
+
method: 'POST',
|
|
865
|
+
requestBody: 'buffered',
|
|
866
|
+
fetch: guard(async () => {
|
|
867
|
+
const profile = await analyzeSelf(ctx, store)
|
|
868
|
+
return json({ ok: true, selfProfile: profile, state: stateOf(store, engine, bridgeStatus) })
|
|
869
|
+
}),
|
|
870
|
+
},
|
|
871
|
+
{
|
|
872
|
+
// Client-side breadcrumbs. A drag that never fires leaves no other trace,
|
|
873
|
+
// and the panel cannot be inspected from outside.
|
|
874
|
+
path: '/api/qq-affinity/trace',
|
|
875
|
+
method: 'POST',
|
|
876
|
+
requestBody: 'buffered',
|
|
877
|
+
fetch: guard(async (request) => {
|
|
878
|
+
const body = await readBody(request)
|
|
879
|
+
appendArchiveLog(store, 'client.log', `${textField(body.tag, 40)} ${textField(body.detail, 200)} v=${textField(body.version, 24)}`)
|
|
880
|
+
return json({ ok: true })
|
|
881
|
+
}),
|
|
882
|
+
},
|
|
883
|
+
{
|
|
884
|
+
path: '/api/qq-affinity/persona',
|
|
885
|
+
method: 'POST',
|
|
886
|
+
requestBody: 'buffered',
|
|
887
|
+
fetch: guard(async (request) => {
|
|
888
|
+
const body = await readBody(request)
|
|
889
|
+
const uin = textField(body.uin, 24).replace(/\D/g, '')
|
|
890
|
+
if (uin === '') return fail('缺少 QQ 号。')
|
|
891
|
+
if (store.person(uin) === undefined) return fail(`没有关于 QQ ${uin} 的任何记录。`, 404)
|
|
892
|
+
const result = await analyzePersona(ctx, store, uin)
|
|
893
|
+
return json({ ok: true, persona: result, state: stateOf(store, engine, bridgeStatus) })
|
|
894
|
+
}),
|
|
895
|
+
},
|
|
896
|
+
{
|
|
897
|
+
path: '/api/qq-affinity/suggest',
|
|
898
|
+
method: 'POST',
|
|
899
|
+
requestBody: 'buffered',
|
|
900
|
+
fetch: guard(async (request) => {
|
|
901
|
+
const body = await readBody(request)
|
|
902
|
+
const conversationId = textField(body.conversationId, 80)
|
|
903
|
+
const batch = await suggestReplies(ctx, store, conversationId)
|
|
904
|
+
return json({ ok: true, batch, batches: store.suggestions(conversationId) })
|
|
905
|
+
}),
|
|
906
|
+
},
|
|
907
|
+
{
|
|
908
|
+
path: '/api/qq-affinity/adopt',
|
|
909
|
+
method: 'POST',
|
|
910
|
+
requestBody: 'buffered',
|
|
911
|
+
fetch: guard(async (request) => {
|
|
912
|
+
const body = await readBody(request)
|
|
913
|
+
const conversationId = textField(body.conversationId, 80)
|
|
914
|
+
const suggestionId = textField(body.suggestionId, 80)
|
|
915
|
+
const conversation = store.conversation(conversationId)
|
|
916
|
+
if (conversation === undefined) return fail('找不到这个对话。', 404)
|
|
917
|
+
const adoption = store.adopt(conversationId, suggestionId)
|
|
918
|
+
if (adoption === undefined) return fail('找不到这条候选,或它已经被采用过了。', 404)
|
|
919
|
+
|
|
920
|
+
const text = styleReply(adoption.text)
|
|
921
|
+
const bridge = store.state.settings.onebot
|
|
922
|
+
const fallbackNote = '实时通道没接通,所以没有替你发出去。文本已复制到剪贴板,请手动粘贴发送。'
|
|
923
|
+
if (bridge.enabled !== true) {
|
|
924
|
+
return json({ ok: true, adoption, sent: false, note: fallbackNote })
|
|
925
|
+
}
|
|
926
|
+
if (store.state.settings.selfUin === '') {
|
|
927
|
+
return json({ ok: true, adoption, sent: false, note: '还没有填写我的 QQ 号,无法以你的身份发送。' })
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
try {
|
|
931
|
+
const result = await deps.send(bridge, {
|
|
932
|
+
kind: conversation.kind === 'group' ? 'group' : 'c2c',
|
|
933
|
+
peerUin: adoption.targetUin,
|
|
934
|
+
groupUin: conversation.groupUin,
|
|
935
|
+
}, text)
|
|
936
|
+
// Record it as mine but AI-authored, exactly like a re-imported adoption.
|
|
937
|
+
store.appendMessages(conversationId, [{
|
|
938
|
+
ts: Date.now(),
|
|
939
|
+
senderName: store.state.settings.selfName === '' ? '我' : store.state.settings.selfName,
|
|
940
|
+
senderUin: store.state.settings.selfUin,
|
|
941
|
+
text,
|
|
942
|
+
aiAdopted: true,
|
|
943
|
+
}])
|
|
944
|
+
store.markStale(conversation)
|
|
945
|
+
return json({
|
|
946
|
+
ok: true,
|
|
947
|
+
adoption,
|
|
948
|
+
sent: true,
|
|
949
|
+
messageId: result.messageId,
|
|
950
|
+
text,
|
|
951
|
+
note: '已直接发送给对方。这条记为 AI 代笔,不计入「你对 TA 的好感度」。',
|
|
952
|
+
})
|
|
953
|
+
} catch (error) {
|
|
954
|
+
return fail(
|
|
955
|
+
`采用已记录,但发送失败:${error instanceof Error ? error.message : String(error)}。可以手动复制发送。`,
|
|
956
|
+
502,
|
|
957
|
+
{ adoption, text },
|
|
958
|
+
)
|
|
959
|
+
}
|
|
960
|
+
}),
|
|
961
|
+
},
|
|
962
|
+
]
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/** Re-derive `direction` on every stored row after the self QQ number changes. */
|
|
966
|
+
function rederiveDirections(store, selfUin) {
|
|
967
|
+
for (const conversation of store.state.conversations) {
|
|
968
|
+
const rows = store.messages(conversation.id)
|
|
969
|
+
if (rows.length === 0) continue
|
|
970
|
+
let touched = false
|
|
971
|
+
for (const row of rows) {
|
|
972
|
+
const next = selfUin !== '' && row.senderUin === selfUin
|
|
973
|
+
? 'out'
|
|
974
|
+
: (row.senderUin === '' ? 'unknown' : 'in')
|
|
975
|
+
if (row.direction !== next) {
|
|
976
|
+
row.direction = next
|
|
977
|
+
touched = true
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
if (touched) store.rewrite(conversation.id, rows)
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
|