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/onebot.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OneBot v11 bridge over plain HTTP: no extra dependency, no WebSocket client.
|
|
3
|
+
*
|
|
4
|
+
* Inbound events arrive because the bridge (NapCat, LLOneBot, ...) is told to
|
|
5
|
+
* POST its reports to this plugin's own route. Outbound messages use the
|
|
6
|
+
* bridge's HTTP API. Both directions carry the access token the bridge was
|
|
7
|
+
* configured with; the inbound route additionally requires its own token so a
|
|
8
|
+
* random local process cannot feed the plugin fake messages.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { extractMedia } from './media.js'
|
|
12
|
+
|
|
13
|
+
/** Markers substituted for non-text message segments. */
|
|
14
|
+
const CQ_MARKERS = [
|
|
15
|
+
['image', '[图片]'],
|
|
16
|
+
['face', '[表情]'],
|
|
17
|
+
['mface', '[表情]'],
|
|
18
|
+
['record', '[语音]'],
|
|
19
|
+
['video', '[视频]'],
|
|
20
|
+
['file', '[文件]'],
|
|
21
|
+
['redbag', '[红包]'],
|
|
22
|
+
['transfer', '[转账]'],
|
|
23
|
+
['json', '[卡片]'],
|
|
24
|
+
['xml', '[卡片]'],
|
|
25
|
+
['poke', '[戳一戳]'],
|
|
26
|
+
['forward', '[合并转发]'],
|
|
27
|
+
['reply', ''],
|
|
28
|
+
['at', '[at]'],
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
/** Replace every CQ code with something readable and keep the plain text. */
|
|
32
|
+
export function plainText(raw) {
|
|
33
|
+
let text = String(raw ?? '')
|
|
34
|
+
for (const [type, marker] of CQ_MARKERS) {
|
|
35
|
+
text = text.replace(new RegExp(`\\[CQ:${type},[^\\]]*\\]`, 'g'), marker)
|
|
36
|
+
}
|
|
37
|
+
return text.replace(/\[CQ:[a-z]+,[^\]]*\]/g, '').trim()
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Flatten a OneBot message-segment array into readable text.
|
|
42
|
+
* History responses carry segments instead of a `raw_message` string.
|
|
43
|
+
* @param {any} segments
|
|
44
|
+
* @returns {string}
|
|
45
|
+
*/
|
|
46
|
+
export function segmentsToText(segments) {
|
|
47
|
+
if (!Array.isArray(segments)) return ''
|
|
48
|
+
const parts = []
|
|
49
|
+
for (const segment of segments) {
|
|
50
|
+
if (segment === null || typeof segment !== 'object') continue
|
|
51
|
+
if (segment.type === 'text') {
|
|
52
|
+
parts.push(String(segment.data?.text ?? ''))
|
|
53
|
+
continue
|
|
54
|
+
}
|
|
55
|
+
const marker = CQ_MARKERS.find(([type]) => type === segment.type)
|
|
56
|
+
if (marker !== undefined && marker[1] !== '') parts.push(marker[1])
|
|
57
|
+
}
|
|
58
|
+
return parts.join('').trim()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Whether a raw message mentions one QQ number. */
|
|
62
|
+
function mentions(raw, uin) {
|
|
63
|
+
if (uin === '') return false
|
|
64
|
+
return String(raw ?? '').includes(`[CQ:at,qq=${uin}]`) || String(raw ?? '').includes(`@${uin}`)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Turn one OneBot v11 event into the shape the engine consumes.
|
|
69
|
+
*
|
|
70
|
+
* A message the account itself sent is returned too, marked `fromSelf`: it is
|
|
71
|
+
* worth archiving (it is the only evidence of how *I* talk), but it must never
|
|
72
|
+
* be answered. A bridge configured with `reportSelfMessage` delivers those.
|
|
73
|
+
* @param {any} payload - the posted report.
|
|
74
|
+
* @param {string} selfUin - the bridge's own QQ number, when known.
|
|
75
|
+
* @returns {{ kind: 'c2c' | 'group', peerUin: string, groupUin: string, conversationId: string,
|
|
76
|
+
* text: string, raw: string, ts: number, messageId: string, atSelf: boolean, senderName: string,
|
|
77
|
+
* fromSelf: boolean, images: Array<{ url: string, kind: 'image' | 'sticker', summary: string }> } | undefined}
|
|
78
|
+
*/
|
|
79
|
+
export function normalizeEvent(payload, selfUin = '') {
|
|
80
|
+
if (payload === null || typeof payload !== 'object') return undefined
|
|
81
|
+
if (payload.post_type !== 'message') return undefined
|
|
82
|
+
const selfId = String(payload.self_id ?? selfUin ?? '')
|
|
83
|
+
const senderUin = String(payload.user_id ?? '')
|
|
84
|
+
if (senderUin === '') return undefined
|
|
85
|
+
const fromSelf = selfId !== '' && senderUin === selfId
|
|
86
|
+
const raw = typeof payload.raw_message === 'string' ? payload.raw_message : ''
|
|
87
|
+
// The bridge may report segments instead of (or as well as) CQ text.
|
|
88
|
+
const segments = Array.isArray(payload.message) ? payload.message : undefined
|
|
89
|
+
const media = extractMedia(raw, segments)
|
|
90
|
+
const text = media.text
|
|
91
|
+
if (text === '') return undefined
|
|
92
|
+
const seconds = Number(payload.time)
|
|
93
|
+
const ts = Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : Date.now()
|
|
94
|
+
const sender = payload.sender ?? {}
|
|
95
|
+
const senderName = String(sender.card ?? '').trim() || String(sender.nickname ?? '').trim() || senderUin
|
|
96
|
+
const atSelf = mentions(raw, selfId)
|
|
97
|
+
|
|
98
|
+
// For my own message in a private chat the other half is the conversation it
|
|
99
|
+
// belongs to, which the payload reports as the target — not the sender.
|
|
100
|
+
const privatePeer = fromSelf ? String(payload.target_id ?? '') : senderUin
|
|
101
|
+
|
|
102
|
+
if (payload.message_type === 'group') {
|
|
103
|
+
const groupUin = String(payload.group_id ?? '')
|
|
104
|
+
if (groupUin === '') return undefined
|
|
105
|
+
return {
|
|
106
|
+
kind: 'group',
|
|
107
|
+
peerUin: senderUin,
|
|
108
|
+
groupUin,
|
|
109
|
+
conversationId: `group:${groupUin}`,
|
|
110
|
+
text,
|
|
111
|
+
raw,
|
|
112
|
+
ts,
|
|
113
|
+
messageId: String(payload.message_id ?? ''),
|
|
114
|
+
atSelf,
|
|
115
|
+
senderName,
|
|
116
|
+
fromSelf,
|
|
117
|
+
images: media.images.slice(0, 4),
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (privatePeer === '') return undefined
|
|
121
|
+
return {
|
|
122
|
+
kind: 'c2c',
|
|
123
|
+
peerUin: fromSelf ? privatePeer : senderUin,
|
|
124
|
+
groupUin: '',
|
|
125
|
+
conversationId: `c2c:${fromSelf ? privatePeer : senderUin}`,
|
|
126
|
+
text,
|
|
127
|
+
raw,
|
|
128
|
+
ts,
|
|
129
|
+
messageId: String(payload.message_id ?? ''),
|
|
130
|
+
atSelf: true,
|
|
131
|
+
senderName,
|
|
132
|
+
fromSelf,
|
|
133
|
+
images: media.images.slice(0, 4),
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Trim a configured base URL and drop a trailing slash. */
|
|
138
|
+
function baseOf(apiBase) {
|
|
139
|
+
const value = String(apiBase ?? '').trim()
|
|
140
|
+
if (value === '') throw new Error('还没有填写实时通道的 API 地址。')
|
|
141
|
+
let url
|
|
142
|
+
try {
|
|
143
|
+
url = new URL(value)
|
|
144
|
+
} catch {
|
|
145
|
+
throw new Error(`API 地址不是合法 URL:${value}`)
|
|
146
|
+
}
|
|
147
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('API 地址必须是 http 或 https。')
|
|
148
|
+
return value.replace(/\/+$/, '')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** One request against the bridge's HTTP API, decoding the OneBot envelope. */
|
|
152
|
+
export async function callApi(settings, action, payload, signal) {
|
|
153
|
+
const base = baseOf(settings.apiBase)
|
|
154
|
+
const headers = { 'content-type': 'application/json' }
|
|
155
|
+
if (typeof settings.accessToken === 'string' && settings.accessToken !== '') {
|
|
156
|
+
headers.authorization = `Bearer ${settings.accessToken}`
|
|
157
|
+
}
|
|
158
|
+
const response = await fetch(`${base}/${action}`, {
|
|
159
|
+
method: 'POST',
|
|
160
|
+
headers,
|
|
161
|
+
body: JSON.stringify(payload),
|
|
162
|
+
signal: signal ?? AbortSignal.timeout(15000),
|
|
163
|
+
})
|
|
164
|
+
const text = await response.text()
|
|
165
|
+
if (!response.ok) throw new Error(`通道返回 HTTP ${response.status}:${text.slice(0, 200)}`)
|
|
166
|
+
let value
|
|
167
|
+
try {
|
|
168
|
+
value = JSON.parse(text)
|
|
169
|
+
} catch {
|
|
170
|
+
throw new Error(`通道返回了非 JSON 内容:${text.slice(0, 200)}`)
|
|
171
|
+
}
|
|
172
|
+
if (value !== null && typeof value === 'object' && (value.status === 'failed' || (typeof value.retcode === 'number' && value.retcode !== 0))) {
|
|
173
|
+
throw new Error(`通道拒绝了这次调用:${value.message ?? value.wording ?? `retcode ${value.retcode}`}`)
|
|
174
|
+
}
|
|
175
|
+
return value?.data ?? value
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Ask the bridge who it is logged in as, which also proves the token works.
|
|
180
|
+
* @returns {Promise<{ uin: string, nickname: string }>}
|
|
181
|
+
*/
|
|
182
|
+
export async function probe(settings) {
|
|
183
|
+
const data = await callApi(settings, 'get_login_info', {}, AbortSignal.timeout(8000))
|
|
184
|
+
return {
|
|
185
|
+
uin: String(data?.user_id ?? ''),
|
|
186
|
+
nickname: String(data?.nickname ?? ''),
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Send one reply through the bridge.
|
|
192
|
+
* @param {object} settings - `{ apiBase, accessToken }`.
|
|
193
|
+
* @param {{ kind: 'c2c' | 'group', peerUin: string, groupUin: string }} target
|
|
194
|
+
* @param {string} text
|
|
195
|
+
* @returns {Promise<{ messageId: string }>}
|
|
196
|
+
*/
|
|
197
|
+
export async function send(settings, target, text) {
|
|
198
|
+
const message = String(text ?? '').trim()
|
|
199
|
+
if (message === '') throw new Error('回复内容是空的。')
|
|
200
|
+
const action = target.kind === 'group' ? 'send_group_msg' : 'send_private_msg'
|
|
201
|
+
const payload = target.kind === 'group'
|
|
202
|
+
? { group_id: Number(target.groupUin), message, auto_escape: true }
|
|
203
|
+
: { user_id: Number(target.peerUin), message, auto_escape: true }
|
|
204
|
+
const data = await callApi(settings, action, payload)
|
|
205
|
+
return { messageId: String(data?.message_id ?? '') }
|
|
206
|
+
}
|
|
207
|
+
|
package/lib/parse.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tolerant reader for exported QQ chat transcripts.
|
|
3
|
+
*
|
|
4
|
+
* QQ's own exports differ between versions and platforms, so this parser keys
|
|
5
|
+
* on the one thing they share: a timestamp at the start of a message block, with
|
|
6
|
+
* the sender written as `名字(QQ号)`, `名字<QQ号@qq.com>`, `名字:` or a bare name.
|
|
7
|
+
* Content lines that follow, up to the next timestamp, belong to that message.
|
|
8
|
+
* A JSON array of `{ time, sender, uin, text }` rows is accepted too.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** `2023-01-02 13:45:01 名字(10001) 内容` and its bracket/斜线 variants. */
|
|
12
|
+
const HEADER_TIME_FIRST = new RegExp(String.raw`^[\[\(【]?\s*(\d{4})\s*[-/年.]\s*(\d{1,2})\s*[-/月.]\s*(\d{1,2})\s*[日号]?\s+(\d{1,2}):(\d{2})(?::(\d{2}))?\s*[\]\)】]?\s*(.*)$`)
|
|
13
|
+
|
|
14
|
+
/** `名字 (2023-01-02 13:45:01)` — the mobile-export order. */
|
|
15
|
+
const HEADER_NAME_FIRST = new RegExp(String.raw`^(.*?)\s*[((]\s*(\d{4})\s*[-/]\s*(\d{1,2})\s*[-/]\s*(\d{1,2})\s+(\d{1,2}):(\d{2})(?::(\d{2}))?\s*[))]\s*$`)
|
|
16
|
+
|
|
17
|
+
/** Lines that belong to the export's own preamble, not to a message. */
|
|
18
|
+
const NOISE = [
|
|
19
|
+
/^=+$/,
|
|
20
|
+
/^-{3,}$/,
|
|
21
|
+
/^\s*$/,
|
|
22
|
+
/^消息记录/,
|
|
23
|
+
/^消息分组\s*[::]/,
|
|
24
|
+
/^消息对象\s*[::]/,
|
|
25
|
+
/^导出时间\s*[::]/,
|
|
26
|
+
/^提示\s*[::]/,
|
|
27
|
+
/^此消息记录为文本格式/,
|
|
28
|
+
/^={2,}/,
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
/** Strip the sender with its QQ number from the rest of a header line. */
|
|
32
|
+
function splitIdentity(rest) {
|
|
33
|
+
const text = String(rest ?? '').trim()
|
|
34
|
+
if (text === '') return { senderName: '', senderUin: '', inline: '' }
|
|
35
|
+
const withUin = text.match(new RegExp(String.raw`^(?<name>.+?)\s*(?:[((【<\[]\s*(?<uin>\d{5,12})(?:@qq\.com)?\s*[))】>\]])\s*[::]?\s*(?<inline>.*)$`))
|
|
36
|
+
if (withUin !== null) {
|
|
37
|
+
return {
|
|
38
|
+
senderName: withUin.groups.name.trim(),
|
|
39
|
+
senderUin: withUin.groups.uin,
|
|
40
|
+
inline: withUin.groups.inline.trim(),
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const colon = text.match(/^(?<name>[^::]{1,64})\s*[::]\s*(?<inline>.*)$/)
|
|
44
|
+
if (colon !== null) {
|
|
45
|
+
return { senderName: colon.groups.name.trim(), senderUin: '', inline: colon.groups.inline.trim() }
|
|
46
|
+
}
|
|
47
|
+
return { senderName: text.slice(0, 64), senderUin: '', inline: '' }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Milliseconds for one calendar time in the machine's zone. */
|
|
51
|
+
function stamp(year, month, day, hour, minute, second = '0') {
|
|
52
|
+
const value = new Date(
|
|
53
|
+
Number(year),
|
|
54
|
+
Number(month) - 1,
|
|
55
|
+
Number(day),
|
|
56
|
+
Number(hour),
|
|
57
|
+
Number(minute),
|
|
58
|
+
Number(second || 0),
|
|
59
|
+
).getTime()
|
|
60
|
+
return Number.isFinite(value) ? value : 0
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Recognize one header line, returning the timestamp and sender it carries. */
|
|
64
|
+
function matchHeader(line) {
|
|
65
|
+
const timeFirst = line.match(HEADER_TIME_FIRST)
|
|
66
|
+
if (timeFirst !== null) {
|
|
67
|
+
const [, year, month, day, hour, minute, second, rest] = timeFirst
|
|
68
|
+
const identity = splitIdentity(rest)
|
|
69
|
+
const restText = String(rest ?? '').trim()
|
|
70
|
+
// A message body can start with a date too. Without a QQ number or an
|
|
71
|
+
// explicit `名字:` prefix, the line is far more likely to be content.
|
|
72
|
+
const headerLike = identity.senderUin !== '' || /[::]/.test(restText) || restText === ''
|
|
73
|
+
if (!headerLike) return undefined
|
|
74
|
+
return { ts: stamp(year, month, day, hour, minute, second), ...identity }
|
|
75
|
+
}
|
|
76
|
+
const nameFirst = line.match(HEADER_NAME_FIRST)
|
|
77
|
+
if (nameFirst !== null) {
|
|
78
|
+
const [, name, year, month, day, hour, minute, second] = nameFirst
|
|
79
|
+
return {
|
|
80
|
+
ts: stamp(year, month, day, hour, minute, second),
|
|
81
|
+
senderName: String(name ?? '').trim().slice(0, 64),
|
|
82
|
+
senderUin: '',
|
|
83
|
+
inline: '',
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return undefined
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Read a JSON transcript array, tolerating the field names different exporters use. */
|
|
90
|
+
function fromJson(raw) {
|
|
91
|
+
let value
|
|
92
|
+
try {
|
|
93
|
+
value = JSON.parse(raw)
|
|
94
|
+
} catch {
|
|
95
|
+
return undefined
|
|
96
|
+
}
|
|
97
|
+
const rows = Array.isArray(value)
|
|
98
|
+
? value
|
|
99
|
+
: (Array.isArray(value?.messages) ? value.messages : (Array.isArray(value?.data) ? value.data : undefined))
|
|
100
|
+
if (rows === undefined) return undefined
|
|
101
|
+
const messages = []
|
|
102
|
+
for (const row of rows) {
|
|
103
|
+
if (row === null || typeof row !== 'object') continue
|
|
104
|
+
const text = String(row.text ?? row.content ?? row.message ?? '').trim()
|
|
105
|
+
if (text === '') continue
|
|
106
|
+
const rawTime = row.time ?? row.ts ?? row.date ?? row.timestamp ?? row.sendTime
|
|
107
|
+
const ts = typeof rawTime === 'number' ? rawTime : Date.parse(String(rawTime ?? ''))
|
|
108
|
+
if (!Number.isFinite(ts) || ts <= 0) continue
|
|
109
|
+
const senderUin = String(row.uin ?? row.qq ?? row.senderUin ?? row.fromUin ?? '').replace(/\D/g, '').slice(0, 12)
|
|
110
|
+
const senderName = String(row.sender ?? row.name ?? row.nick ?? row.from ?? '').trim().slice(0, 64)
|
|
111
|
+
messages.push({ ts, senderName: senderName || senderUin, senderUin, text })
|
|
112
|
+
}
|
|
113
|
+
messages.sort((a, b) => a.ts - b.ts)
|
|
114
|
+
const title = typeof value?.title === 'string' ? value.title : ''
|
|
115
|
+
return { title, messages }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Parse one exported transcript.
|
|
120
|
+
* @param {string} rawText - the exported file's text, or a JSON transcript.
|
|
121
|
+
* @returns {{ title: string, messages: Array<{ ts: number, senderName: string, senderUin: string, text: string }>, stats: object }}
|
|
122
|
+
*/
|
|
123
|
+
export function parseTranscript(rawText) {
|
|
124
|
+
const raw = String(rawText ?? '').replace(/^\uFEFF/, '').replace(/\u200b/g, '')
|
|
125
|
+
const json = fromJson(raw.trim())
|
|
126
|
+
if (json !== undefined) {
|
|
127
|
+
return {
|
|
128
|
+
title: json.title,
|
|
129
|
+
messages: json.messages,
|
|
130
|
+
stats: { format: 'json', candidates: 0, parsed: json.messages.length, skipped: 0 },
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const lines = raw.replace(/\r\n?/g, '\n').split('\n')
|
|
135
|
+
/** @type {Array<{ ts: number, senderName: string, senderUin: string, text: string }>} */
|
|
136
|
+
const messages = []
|
|
137
|
+
let title = ''
|
|
138
|
+
let current = null
|
|
139
|
+
let candidates = 0
|
|
140
|
+
let skipped = 0
|
|
141
|
+
|
|
142
|
+
const flush = () => {
|
|
143
|
+
if (current === null) return
|
|
144
|
+
const text = current.body.join('\n').trim()
|
|
145
|
+
if (text !== '' && current.ts > 0) {
|
|
146
|
+
messages.push({ ts: current.ts, senderName: current.senderName, senderUin: current.senderUin, text })
|
|
147
|
+
} else if (text === '') {
|
|
148
|
+
skipped += 1
|
|
149
|
+
}
|
|
150
|
+
current = null
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
for (const line of lines) {
|
|
154
|
+
const objectLine = line.match(/^消息对象\s*[::]\s*(.+)$/)
|
|
155
|
+
if (objectLine !== null && title === '') {
|
|
156
|
+
title = objectLine[1].trim().slice(0, 120)
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
159
|
+
if (NOISE.some(pattern => pattern.test(line))) continue
|
|
160
|
+
|
|
161
|
+
const header = matchHeader(line)
|
|
162
|
+
if (header !== undefined) {
|
|
163
|
+
candidates += 1
|
|
164
|
+
flush()
|
|
165
|
+
current = { ...header, body: header.inline === '' ? [] : [header.inline] }
|
|
166
|
+
continue
|
|
167
|
+
}
|
|
168
|
+
if (current !== null) current.body.push(line)
|
|
169
|
+
}
|
|
170
|
+
flush()
|
|
171
|
+
|
|
172
|
+
messages.sort((a, b) => a.ts - b.ts)
|
|
173
|
+
return {
|
|
174
|
+
title,
|
|
175
|
+
messages,
|
|
176
|
+
stats: {
|
|
177
|
+
format: 'text',
|
|
178
|
+
candidates,
|
|
179
|
+
parsed: messages.length,
|
|
180
|
+
skipped,
|
|
181
|
+
lines: lines.length,
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
}
|
package/lib/recover.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Startup recovery: merge whatever the bridge already has loaded back into the
|
|
2
|
+
// archive. The bridge only serves messages it captured itself — it never asks
|
|
3
|
+
// the QQ server for history — so this pull is bounded and cannot touch anything
|
|
4
|
+
// the user has not chosen to track: only enabled conversations are read.
|
|
5
|
+
import { appendFileSync } from 'node:fs'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
|
|
8
|
+
/** How many already-loaded messages the startup sync pulls per conversation. */
|
|
9
|
+
export const RECOVER_COUNT = 500
|
|
10
|
+
|
|
11
|
+
/** Skip the sync when the last one happened this recently. */
|
|
12
|
+
export const RECOVER_MIN_GAP_MS = 5 * 60 * 1000
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {object} options
|
|
16
|
+
* @param {import('./store.js').Store} options.store
|
|
17
|
+
* @param {() => number} [options.now]
|
|
18
|
+
* @param {() => Promise<Array<object>>} [options.runBackfill] - injectable for tests.
|
|
19
|
+
* @param {(line: string) => void} [options.log] - injectable for tests.
|
|
20
|
+
* @returns {Promise<{ ran: boolean, reason?: string, added?: number, reports?: Array<object> }>}
|
|
21
|
+
*/
|
|
22
|
+
export async function recoverLoaded({ store, now = Date.now, runBackfill, log }) {
|
|
23
|
+
const onebot = store.state.settings.onebot
|
|
24
|
+
if (onebot.enabled !== true || onebot.autoBackfill !== true) return { ran: false, reason: 'channel-off' }
|
|
25
|
+
if (store.state.conversations.every(row => row.enabled !== true)) return { ran: false, reason: 'nothing-enabled' }
|
|
26
|
+
const last = Date.parse(onebot.lastBackfillAt ?? '')
|
|
27
|
+
if (Number.isFinite(last) && now() - last < RECOVER_MIN_GAP_MS) return { ran: false, reason: 'too-recent' }
|
|
28
|
+
|
|
29
|
+
const run = runBackfill ?? (async () => {
|
|
30
|
+
const { backfillAll } = await import('./backfill.js')
|
|
31
|
+
return backfillAll({ store, bridge: onebot, count: RECOVER_COUNT })
|
|
32
|
+
})
|
|
33
|
+
const reports = await run()
|
|
34
|
+
const added = reports.reduce((total, report) => total + (report.added ?? 0), 0)
|
|
35
|
+
if (added > 0) {
|
|
36
|
+
onebot.lastBackfillAt = new Date(now()).toISOString()
|
|
37
|
+
store.save()
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
const write = log ?? ((line) => { appendFileSync(path.join(store.directory, 'sync.log'), `${line}\n`, 'utf8') })
|
|
41
|
+
write(`${new Date(now()).toISOString()} startup added=${added} ${reports.map(report => `${report.conversationId}:+${report.added ?? 0}`).join(' ')}`)
|
|
42
|
+
} catch {
|
|
43
|
+
// The sync worked; a failed log line must not look like a failed sync.
|
|
44
|
+
}
|
|
45
|
+
return { ran: true, added, reports }
|
|
46
|
+
}
|