feat: add async SQLite on Node 24 and improve messaging diagnostics (#520)
Move database work off the main thread on Node.js 24 and improve message handling and runtime diagnostics. Preserve migration, restart, and concurrency coverage with the async SQLite driver.
This commit is contained in:
1 parent
20f48d11ec
commit
c7428363cb
170 files changed
+7748
-3913
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { FriendDressError } from '@snowluma/protocol/web/friend-dress';
|
||||
@@ -398,6 +399,13 @@ function primitiveText(value: unknown): string {
|
||||
return '';
|
||||
}
|
||||
|
||||
const forwardMessagesField = f
|
||||
.message()
|
||||
.optional()
|
||||
.describe(
|
||||
'转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。',
|
||||
);
|
||||
|
||||
const forwardPreviewParams = {
|
||||
source: f.string().optional(),
|
||||
summary: f.string().optional(),
|
||||
@@ -451,7 +459,7 @@ async function groupTodoRun(
|
||||
ctx: ApiActionContext,
|
||||
op: (groupId: number, msgSeq: bigint) => Promise<void>,
|
||||
) {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
@@ -624,7 +632,7 @@ export const actions = [
|
||||
.filter((message): message is GroupEssenceMessage => message !== null)
|
||||
.map((message) => projectEssenceMessage(message, p.group_id));
|
||||
|
||||
ctx.cacheMessageMetas(
|
||||
await ctx.cacheMessageMetas(
|
||||
projections.map(({ messageId, meta }) => ({
|
||||
messageId,
|
||||
meta,
|
||||
@@ -649,7 +657,7 @@ export const actions = [
|
||||
is_set: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta || !meta.isGroup) {
|
||||
return failedResponse(
|
||||
@@ -829,7 +837,7 @@ export const actions = [
|
||||
group_id: f.groupId().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta || !meta.isGroup) {
|
||||
return failedResponse(
|
||||
@@ -858,7 +866,7 @@ export const actions = [
|
||||
user_id: f.userId().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta || meta.isGroup) {
|
||||
return failedResponse(
|
||||
@@ -887,7 +895,7 @@ export const actions = [
|
||||
target_id: f.uint().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
@@ -989,8 +997,8 @@ export const actions = [
|
||||
name: 'upload_forward_msg',
|
||||
summary: '上传转发消息',
|
||||
params: {
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
group_id: f.groupId().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
@@ -1021,8 +1029,8 @@ export const actions = [
|
||||
name: 'upload_foward_msg',
|
||||
summary: '上传转发消息(别名拼写)',
|
||||
params: {
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
group_id: f.groupId().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
@@ -1072,6 +1080,8 @@ export const actions = [
|
||||
name: 'get_record',
|
||||
summary: '获取语音信息;传 out_format 则服务端转码并附带 base64',
|
||||
readOnly: true,
|
||||
returns:
|
||||
'语音信息(file/url 为向 QQ 获取的当前下载地址);资源元数据缺失或远端获取失败时返回错误。out_format 指定时附带转码后的 base64。',
|
||||
params: {
|
||||
file: f.string().default('').role('record'),
|
||||
file_id: f.string().default('').role('file_id'),
|
||||
@@ -1264,7 +1274,7 @@ export const actions = [
|
||||
summary: '标记全部已读',
|
||||
params: {},
|
||||
run: async (_p, ctx) => {
|
||||
const sessions = ctx.listReadSessions();
|
||||
const sessions = await ctx.listReadSessions();
|
||||
await ctx.bridge.apis.message.markAllRead(sessions.groupIds, sessions.privateUserIds);
|
||||
return okResponse();
|
||||
},
|
||||
@@ -2911,8 +2921,8 @@ export const actions = [
|
||||
// group_id/user_id are routing hints, not identity: 0 means "this branch
|
||||
// does not apply" and must not error. int({min:0}) optional, not groupId.
|
||||
params: {
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
message_type: f.string().optional(),
|
||||
group_id: f.int({ min: 0 }).optional(),
|
||||
user_id: f.int({ min: 0 }).optional(),
|
||||
@@ -2969,8 +2979,8 @@ export const actions = [
|
||||
summary: '发送群合并转发',
|
||||
returns: '{ message_id, res_id, forward_id }',
|
||||
params: {
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
...forwardPreviewParams,
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
@@ -2999,8 +3009,8 @@ export const actions = [
|
||||
returns: '{ message_id, res_id, forward_id }',
|
||||
params: {
|
||||
user_id: f.userId(),
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
...forwardPreviewParams,
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
@@ -3027,7 +3037,8 @@ export const actions = [
|
||||
name: 'get_forward_msg',
|
||||
summary: '获取合并转发消息(id 或 message_id)',
|
||||
readOnly: true,
|
||||
returns: '{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件,内部字段不固定)。',
|
||||
returns:
|
||||
'{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件);reply 保留 id,有内嵌引用内容时附带 message 和可用的 qq/time/seq,可作为转发节点 content 再次发送。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -3047,7 +3058,7 @@ export const actions = [
|
||||
const numericMessageId = integerFromDecimalString(p.message_id);
|
||||
|
||||
if (numericMessageId > 0) {
|
||||
const event = ctx.getMessage(numericMessageId);
|
||||
const event = await ctx.getMessage(numericMessageId);
|
||||
const segments = Array.isArray(event?.message) ? event.message : [];
|
||||
|
||||
for (const seg of segments) {
|
||||
@@ -3306,7 +3317,7 @@ export const actions = [
|
||||
return { todo, messageId, meta };
|
||||
});
|
||||
|
||||
ctx.cacheMessageMetas(
|
||||
await ctx.cacheMessageMetas(
|
||||
projections.map(({ messageId, meta }) => ({
|
||||
messageId,
|
||||
meta,
|
||||
@@ -3314,8 +3325,8 @@ export const actions = [
|
||||
);
|
||||
|
||||
return okResponse(
|
||||
projections.map(({ todo, messageId }) => {
|
||||
const cached = ctx.getMessage(messageId)?.message;
|
||||
await mapWithConcurrency(projections, 8, async ({ todo, messageId }) => {
|
||||
const cached = (await ctx.getMessage(messageId))?.message;
|
||||
return {
|
||||
message_id: messageId,
|
||||
message_seq: todo.sequence,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
import type { ApiActionContext } from '../api-handler';
|
||||
import { defineAction, groupAction, f, type Field } from '../action-kit';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
@@ -21,60 +20,6 @@ function sendMsgOptionalGroupId(): Field<number | undefined> {
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
/**
|
||||
* Re-sign image URLs in a stored message event at read time. `get_msg`
|
||||
* returns a copy persisted when the message first arrived, and image rkeys
|
||||
* expire — so walk the segment array and refresh each image URL through
|
||||
* `ctx.getImageInfo`, which mints a current rkey. Best-effort and in-place;
|
||||
* `findEvent` returns a fresh parse, so mutating the array is safe.
|
||||
*/
|
||||
async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): Promise<void> {
|
||||
const segments = event.message;
|
||||
|
||||
if (!Array.isArray(segments)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const seg of segments) {
|
||||
if (!seg || typeof seg !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const segment = seg as { type?: unknown; data?: Record<string, JsonValue> };
|
||||
|
||||
if (segment.type !== 'image') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = segment.data;
|
||||
|
||||
if (!data || typeof data !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const file =
|
||||
typeof data.file === 'string'
|
||||
? data.file
|
||||
: typeof data.file_id === 'string'
|
||||
? data.file_id
|
||||
: '';
|
||||
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const info = await ctx.getImageInfo(file);
|
||||
|
||||
if (info && typeof info.url === 'string' && info.url) {
|
||||
data.url = info.url;
|
||||
}
|
||||
} catch {
|
||||
// Keep the stored URL when the refresh fails.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'send_custom_face',
|
||||
@@ -204,10 +149,10 @@ export const actions = [
|
||||
summary: '获取消息',
|
||||
readOnly: true,
|
||||
returns:
|
||||
'消息事件对象(首次收到时存储的副本,已去除 post_type/self_id、附带 real_id 字段并刷新图片 URL)。',
|
||||
'消息事件对象(去除 post_type/self_id,附带 real_id);逐个尝试刷新图片、语音和视频 URL,成功使用新地址,失败保留该段原地址并继续返回消息;地址更新时同步 raw_message。',
|
||||
params: { message_id: f.messageId() },
|
||||
run: async (p, ctx) => {
|
||||
const data = ctx.getMessage(p.message_id);
|
||||
const data = await ctx.getMessage(p.message_id);
|
||||
|
||||
if (!data) {
|
||||
log.warn('[get_msg] miss message_id=%d', p.message_id);
|
||||
@@ -218,7 +163,7 @@ export const actions = [
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? p.message_id) as JsonValue;
|
||||
await refreshStoredImageUrls(result, ctx);
|
||||
await ctx.refreshMessageMedia(p.message_id, result);
|
||||
return okResponse(result);
|
||||
},
|
||||
}),
|
||||
@@ -228,7 +173,7 @@ export const actions = [
|
||||
summary: '撤回消息',
|
||||
params: { message_id: f.messageId() },
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta) {
|
||||
return failedResponse(
|
||||
|
||||
@@ -55,10 +55,13 @@ export interface ApiActionContext {
|
||||
getLoginInfo: () => { userId: number; nickname: string };
|
||||
isOnline: () => boolean;
|
||||
getUptimeMs: () => number;
|
||||
getMessage: (messageId: number) => JsonObject | null;
|
||||
getMessageMeta: (messageId: number) => MessageMeta | null;
|
||||
cacheMessageMetas: (entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>) => void;
|
||||
listReadSessions: () => ReadSessionTargets;
|
||||
getMessage: (messageId: number) => JsonObject | null | Promise<JsonObject | null>;
|
||||
refreshMessageMedia: (messageId: number, event: JsonObject) => Promise<void>;
|
||||
getMessageMeta: (messageId: number) => MessageMeta | null | Promise<MessageMeta | null>;
|
||||
cacheMessageMetas: (
|
||||
entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>,
|
||||
) => void | Promise<void>;
|
||||
listReadSessions: () => ReadSessionTargets | Promise<ReadSessionTargets>;
|
||||
sendPrivateMessage: (
|
||||
userId: number,
|
||||
message: JsonValue,
|
||||
|
||||
@@ -295,7 +295,7 @@ export const ELEMENT_CODECS = {
|
||||
const eventName = ctx.isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: privateMessageEventName(sentBySelf, false);
|
||||
const id = resolveReplyId(
|
||||
const id = await resolveReplyId(
|
||||
ctx.isGroup,
|
||||
ctx.sessionId,
|
||||
element.replySeq ?? 0,
|
||||
@@ -328,10 +328,10 @@ export const ELEMENT_CODECS = {
|
||||
return null;
|
||||
}
|
||||
|
||||
const meta = options?.resolveReplyMeta?.(id) ?? null;
|
||||
const meta = (await options?.resolveReplyMeta?.(id)) ?? null;
|
||||
|
||||
if (options?.resolveReplySequence) {
|
||||
const resolved = options.resolveReplySequence(id);
|
||||
const resolved = await options.resolveReplySequence(id);
|
||||
|
||||
if (typeof resolved === 'number' && resolved > 0) {
|
||||
const element: MessageElement = {
|
||||
@@ -400,7 +400,7 @@ export const ELEMENT_CODECS = {
|
||||
}
|
||||
|
||||
if (ctx.mediaSegmentSink) {
|
||||
ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
|
||||
await ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
|
||||
}
|
||||
|
||||
return { type: 'image', data };
|
||||
@@ -437,7 +437,7 @@ export const ELEMENT_CODECS = {
|
||||
};
|
||||
|
||||
if (ctx.mediaSegmentSink) {
|
||||
ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId);
|
||||
await ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId);
|
||||
}
|
||||
|
||||
return { type: 'record', data };
|
||||
@@ -468,7 +468,7 @@ export const ELEMENT_CODECS = {
|
||||
};
|
||||
|
||||
if (ctx.mediaSegmentSink) {
|
||||
ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId);
|
||||
await ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId);
|
||||
}
|
||||
|
||||
return { type: 'video', data };
|
||||
|
||||
@@ -40,7 +40,7 @@ export type MessageIdResolver = (
|
||||
eventName: string,
|
||||
timestamp?: number,
|
||||
replyElements?: readonly MessageElement[],
|
||||
) => number;
|
||||
) => number | Promise<number>;
|
||||
|
||||
export type MediaSegmentSink = (
|
||||
mediaType: 'image' | 'record' | 'video',
|
||||
@@ -48,7 +48,7 @@ export type MediaSegmentSink = (
|
||||
data: JsonObject,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
) => void;
|
||||
) => void | Promise<void>;
|
||||
|
||||
// ─────────────── context ───────────────
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ async function convertPrivateMessage(
|
||||
event.kind === 'friend_message'
|
||||
? privateMessageEventName(isSelf, hasCanonicalNtSequence)
|
||||
: PRIVATE_MESSAGE_EVENT;
|
||||
const messageId = applyMessageIdResolver(
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
false,
|
||||
sessionId,
|
||||
@@ -104,7 +104,7 @@ export async function convertGroupMessage(
|
||||
): Promise<JsonObject> {
|
||||
const isSelf = event.senderUin === ctx.selfId;
|
||||
const postType = isSelf ? 'message_sent' : 'message';
|
||||
const messageId = applyMessageIdResolver(
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
true,
|
||||
event.groupId,
|
||||
|
||||
@@ -84,8 +84,11 @@ export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): Jso
|
||||
});
|
||||
}
|
||||
|
||||
export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
export async function convertFriendRecall(
|
||||
ctx: ConverterContext,
|
||||
event: FriendRecall,
|
||||
): Promise<JsonObject> {
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
false,
|
||||
event.userUin,
|
||||
@@ -100,8 +103,11 @@ export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall):
|
||||
});
|
||||
}
|
||||
|
||||
export function convertGroupRecall(ctx: ConverterContext, event: GroupRecall): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
export async function convertGroupRecall(
|
||||
ctx: ConverterContext,
|
||||
event: GroupRecall,
|
||||
): Promise<JsonObject> {
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
true,
|
||||
event.groupId,
|
||||
@@ -143,8 +149,11 @@ export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonO
|
||||
});
|
||||
}
|
||||
|
||||
export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
export async function convertGroupEssence(
|
||||
ctx: ConverterContext,
|
||||
event: GroupEssence,
|
||||
): Promise<JsonObject> {
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
true,
|
||||
event.groupId,
|
||||
@@ -265,11 +274,11 @@ export function convertFriendInputStatus(
|
||||
});
|
||||
}
|
||||
|
||||
export function convertGroupMsgEmojiLike(
|
||||
export async function convertGroupMsgEmojiLike(
|
||||
ctx: ConverterContext,
|
||||
event: GroupMsgEmojiLike,
|
||||
): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
): Promise<JsonObject> {
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
true,
|
||||
event.groupId,
|
||||
|
||||
@@ -8,29 +8,14 @@ import { attachMessageMedia } from '../message-media';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
function toSegmentContext(
|
||||
ctx: ConverterContext,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): ToSegmentContext {
|
||||
return {
|
||||
isGroup,
|
||||
sessionId,
|
||||
selfId: ctx.selfId,
|
||||
imageUrlResolver: ctx.imageUrlResolver,
|
||||
mediaUrlResolver: ctx.mediaUrlResolver,
|
||||
messageIdResolver: ctx.messageIdResolver,
|
||||
mediaSegmentSink: ctx.mediaSegmentSink,
|
||||
};
|
||||
}
|
||||
|
||||
export async function elementsToOneBotSegments(
|
||||
ctx: ConverterContext,
|
||||
elements: MessageElement[],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
options: { includeReplyContent?: boolean } = {},
|
||||
): Promise<JsonArray> {
|
||||
const segmentCtx = toSegmentContext(ctx, isGroup, sessionId);
|
||||
const segmentCtx: ToSegmentContext = { ...ctx, isGroup, sessionId, mediaSegmentSink: null };
|
||||
const result: JsonArray = [];
|
||||
|
||||
for (const element of elements) {
|
||||
@@ -39,7 +24,7 @@ export async function elementsToOneBotSegments(
|
||||
// One malformed element shouldn't drop the whole message — skip it (with a
|
||||
// breadcrumb) and keep converting the rest.
|
||||
try {
|
||||
segment = await elementToSegment(element, { ...segmentCtx, mediaSegmentSink: null });
|
||||
segment = await elementToSegment(element, segmentCtx);
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'segment convert skipped type=%s (%s)',
|
||||
@@ -49,11 +34,43 @@ export async function elementsToOneBotSegments(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Forward quotes often refer to messages outside the local account's
|
||||
// history. Carry their inline content so consumers can resend the node.
|
||||
if (
|
||||
options.includeReplyContent &&
|
||||
element.type === 'reply' &&
|
||||
element.replyElements?.length
|
||||
) {
|
||||
const message = await elementsToOneBotSegments(
|
||||
ctx,
|
||||
element.replyElements.filter((quoted) => quoted.type !== 'reply'),
|
||||
isGroup,
|
||||
sessionId,
|
||||
);
|
||||
|
||||
if (message.length > 0) {
|
||||
const data = segment.data as JsonObject;
|
||||
data.message = message;
|
||||
|
||||
if (element.replySenderUin) {
|
||||
data.qq = String(element.replySenderUin);
|
||||
}
|
||||
|
||||
if (element.replyTime !== undefined) {
|
||||
data.time = String(element.replyTime);
|
||||
}
|
||||
|
||||
if (element.replySeq) {
|
||||
data.seq = String(element.replySeq);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Persistence failures must propagate, not masquerade as bad wire elements.
|
||||
attachMessageMedia(segment, element);
|
||||
|
||||
if (element.type === 'image' || element.type === 'record' || element.type === 'video') {
|
||||
ctx.mediaSegmentSink?.(
|
||||
await ctx.mediaSegmentSink?.(
|
||||
element.type,
|
||||
element,
|
||||
segment.data as JsonObject,
|
||||
|
||||
@@ -2,11 +2,6 @@ import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
||||
import type { MessageIdResolver } from './index';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
|
||||
export function parseSelfId(instanceUin: string): number {
|
||||
const parsed = Number.parseInt(instanceUin, 10);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
export function isSameActor(
|
||||
leftUin: number,
|
||||
leftUid: string | undefined,
|
||||
@@ -20,16 +15,16 @@ export function isSameActor(
|
||||
return Boolean(leftUid) && leftUid === rightUid;
|
||||
}
|
||||
|
||||
export function applyMessageIdResolver(
|
||||
export async function applyMessageIdResolver(
|
||||
resolver: MessageIdResolver | null,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
eventName: string,
|
||||
timestamp?: number,
|
||||
): number {
|
||||
): Promise<number> {
|
||||
if (resolver) {
|
||||
const resolved = resolver(isGroup, sessionId, sequence, eventName, timestamp);
|
||||
const resolved = await resolver(isGroup, sessionId, sequence, eventName, timestamp);
|
||||
|
||||
if (Number.isInteger(resolved) && resolved !== 0) {
|
||||
return resolved;
|
||||
@@ -40,7 +35,7 @@ export function applyMessageIdResolver(
|
||||
return seq === 0 ? 0 : seq;
|
||||
}
|
||||
|
||||
export function resolveReplyId(
|
||||
export async function resolveReplyId(
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
@@ -48,7 +43,7 @@ export function resolveReplyId(
|
||||
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
|
||||
timestamp?: number,
|
||||
replyElements?: readonly MessageElement[],
|
||||
): number {
|
||||
): Promise<number> {
|
||||
const seq = Math.trunc(sequence);
|
||||
|
||||
if (seq === 0) {
|
||||
@@ -56,7 +51,14 @@ export function resolveReplyId(
|
||||
}
|
||||
|
||||
if (resolver) {
|
||||
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp, replyElements);
|
||||
const resolved = await resolver(
|
||||
isGroup,
|
||||
sessionId,
|
||||
seq,
|
||||
eventName,
|
||||
timestamp,
|
||||
replyElements,
|
||||
);
|
||||
|
||||
if (Number.isInteger(resolved) && resolved !== 0) {
|
||||
return resolved;
|
||||
|
||||
@@ -199,7 +199,7 @@ async function convertAndDispatch(
|
||||
renderParamsVerbose(converted),
|
||||
]);
|
||||
|
||||
if (event.kind === 'friend_message' && isFriendMessageRecalled(ctx, log, event)) {
|
||||
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
|
||||
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_before_backfill');
|
||||
return;
|
||||
}
|
||||
@@ -227,12 +227,12 @@ async function convertAndDispatch(
|
||||
|
||||
// Backfill can await several network/media operations. Re-check immediately
|
||||
// before dispatch so a recall that arrived during that gap wins the race.
|
||||
if (event.kind === 'friend_message' && isFriendMessageRecalled(ctx, log, event)) {
|
||||
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
|
||||
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_after_backfill');
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.dispatchEvent(converted, 'bridge', state.startedAt);
|
||||
await ctx.dispatchEvent(converted, 'bridge', state.startedAt);
|
||||
state.handedOff = true;
|
||||
}
|
||||
|
||||
@@ -261,12 +261,12 @@ function traceEventTerminal(
|
||||
]);
|
||||
}
|
||||
|
||||
function cacheGroupMessageMeta(
|
||||
async function cacheGroupMessageMeta(
|
||||
ctx: OneBotInstanceContext,
|
||||
event: Extract<QQEventVariant, { kind: 'group_message' }>,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
|
||||
ctx.cacheMessageMeta(messageId, {
|
||||
await ctx.cacheMessageMeta(messageId, {
|
||||
isGroup: true,
|
||||
targetId: event.groupId,
|
||||
sequence: event.msgSeq,
|
||||
@@ -278,7 +278,7 @@ function cacheGroupMessageMeta(
|
||||
});
|
||||
}
|
||||
|
||||
function cachePrivateMessageMeta(
|
||||
async function cachePrivateMessageMeta(
|
||||
ctx: OneBotInstanceContext,
|
||||
sessionId: number,
|
||||
messageSequence: number,
|
||||
@@ -288,7 +288,7 @@ function cachePrivateMessageMeta(
|
||||
random: number,
|
||||
sequenceAuthoritative: boolean,
|
||||
privateDirection: MessageMeta['privateDirection'],
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const isFriendMessage = privateDirection !== undefined;
|
||||
const hasNtSequence = isFriendMessage && sequenceAuthoritative && serverSequence > 0;
|
||||
const eventName = isFriendMessage
|
||||
@@ -299,7 +299,7 @@ function cachePrivateMessageMeta(
|
||||
sessionId,
|
||||
eventName,
|
||||
);
|
||||
ctx.cacheMessageMeta(messageId, {
|
||||
await ctx.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: sessionId,
|
||||
sequence: serverSequence,
|
||||
@@ -312,15 +312,15 @@ function cachePrivateMessageMeta(
|
||||
});
|
||||
}
|
||||
|
||||
function isFriendMessageRecalled(
|
||||
async function isFriendMessageRecalled(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'friend_message' }>,
|
||||
): boolean {
|
||||
): Promise<boolean> {
|
||||
const peerUin = event.peerUin ?? event.senderUin;
|
||||
const clientSequence = event.clientSeq ?? event.msgSeq;
|
||||
const sentBySelf = event.senderUin === ctx.selfId;
|
||||
const recalled = ctx.messageStore.isPrivateMessageRecalled(
|
||||
const recalled = await ctx.messageStore.isPrivateMessageRecalled(
|
||||
peerUin,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
@@ -339,16 +339,16 @@ function isFriendMessageRecalled(
|
||||
return recalled;
|
||||
}
|
||||
|
||||
function cacheReaction(
|
||||
async function cacheReaction(
|
||||
ctx: OneBotInstanceContext,
|
||||
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
if (!event.groupId || !event.msgSeq || !event.emojiId || !event.operatorUin) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.isAdd) {
|
||||
ctx.reactionStore.recordAdd(
|
||||
await ctx.reactionStore.recordAdd(
|
||||
event.groupId,
|
||||
event.msgSeq,
|
||||
event.emojiId,
|
||||
@@ -358,7 +358,7 @@ function cacheReaction(
|
||||
event.time,
|
||||
);
|
||||
} else {
|
||||
ctx.reactionStore.recordRemove(
|
||||
await ctx.reactionStore.recordRemove(
|
||||
event.groupId,
|
||||
event.msgSeq,
|
||||
event.emojiId,
|
||||
@@ -367,23 +367,23 @@ function cacheReaction(
|
||||
}
|
||||
}
|
||||
|
||||
function handleGroupMessage(
|
||||
async function handleGroupMessage(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'group_message' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
cacheGroupMessageMeta(ctx, event);
|
||||
await cacheGroupMessageMeta(ctx, event);
|
||||
return convertAndDispatch(ctx, log, event, state);
|
||||
}
|
||||
|
||||
function handleFriendMessage(
|
||||
async function handleFriendMessage(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'friend_message' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
cachePrivateMessageMeta(
|
||||
await cachePrivateMessageMeta(
|
||||
ctx,
|
||||
event.peerUin ?? event.senderUin,
|
||||
event.msgSeq,
|
||||
@@ -397,13 +397,13 @@ function handleFriendMessage(
|
||||
return convertAndDispatch(ctx, log, event, state);
|
||||
}
|
||||
|
||||
function handleTempMessage(
|
||||
async function handleTempMessage(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'temp_message' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
cachePrivateMessageMeta(
|
||||
await cachePrivateMessageMeta(
|
||||
ctx,
|
||||
event.senderUin,
|
||||
event.msgSeq,
|
||||
@@ -418,14 +418,14 @@ function handleTempMessage(
|
||||
return convertAndDispatch(ctx, log, event, state);
|
||||
}
|
||||
|
||||
function handleFriendRecall(
|
||||
async function handleFriendRecall(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'friend_recall' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
const clientSequence = event.clientSeq ?? event.msgSeq;
|
||||
const recalled = ctx.messageStore.recordPrivateRecall(
|
||||
const recalled = await ctx.messageStore.recordPrivateRecall(
|
||||
event.userUin,
|
||||
clientSequence,
|
||||
event.recalledBySelf === true,
|
||||
@@ -442,13 +442,13 @@ function handleFriendRecall(
|
||||
return convertAndDispatch(ctx, log, event, state, messageIdOverride);
|
||||
}
|
||||
|
||||
function handleGroupMsgEmojiLike(
|
||||
async function handleGroupMsgEmojiLike(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
cacheReaction(ctx, event);
|
||||
await cacheReaction(ctx, event);
|
||||
return convertAndDispatch(ctx, log, event, state);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,12 +9,12 @@ import type { JsonObject } from './types';
|
||||
* Private history needs the conversation peer explicitly because `user_id`
|
||||
* names the sender and therefore equals the bot account on outgoing messages.
|
||||
*/
|
||||
export function persistHistoryEvent(
|
||||
export async function persistHistoryEvent(
|
||||
store: MessageStore,
|
||||
event: JsonObject,
|
||||
privatePeerId?: number,
|
||||
source?: FriendMessage,
|
||||
): void {
|
||||
): Promise<boolean> {
|
||||
const messageId = toHistoryInt(event.message_id);
|
||||
|
||||
if (!Number.isSafeInteger(messageId) || messageId === 0) {
|
||||
@@ -63,7 +63,7 @@ export function persistHistoryEvent(
|
||||
timestamp: source.time,
|
||||
} satisfies Parameters<MessageStore['storeMeta']>[1])
|
||||
: undefined;
|
||||
store.storeHistoryEvent(messageId, isGroup, sessionId, sequence, eventName, event, {
|
||||
return store.storeHistoryEvent(messageId, isGroup, sessionId, sequence, eventName, event, {
|
||||
sequenceAuthoritative,
|
||||
meta,
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import {
|
||||
@@ -136,8 +137,11 @@ export class LoginHistorySyncCoordinator {
|
||||
})),
|
||||
signal,
|
||||
);
|
||||
const groupCandidates = selectGroupCandidates(ref.messageStore, state.groups);
|
||||
const privateCandidates = selectPrivateCandidates(ref.messageStore, state.privateUsers);
|
||||
const groupCandidates = await selectGroupCandidates(ref.messageStore, state.groups);
|
||||
const privateCandidates = await selectPrivateCandidates(
|
||||
ref.messageStore,
|
||||
state.privateUsers,
|
||||
);
|
||||
// URL resolvers may issue additional QQ requests for rkeys or media
|
||||
// download addresses. Automatic backfill must stay inside its one-probe
|
||||
// plus six-page packet budget, so persist only URLs already present in the
|
||||
@@ -151,9 +155,9 @@ export class LoginHistorySyncCoordinator {
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
mediaSegmentSink: mediaSegmentSink
|
||||
? (mediaType, element, data, isGroup, sessionId) => {
|
||||
? async (mediaType, element, data, isGroup, sessionId) => {
|
||||
throwIfAborted(signal);
|
||||
mediaSegmentSink(mediaType, element, data, isGroup, sessionId);
|
||||
await mediaSegmentSink(mediaType, element, data, isGroup, sessionId);
|
||||
}
|
||||
: null,
|
||||
},
|
||||
@@ -257,18 +261,21 @@ export class LoginHistorySyncCoordinator {
|
||||
|
||||
export const loginHistorySyncCoordinator = new LoginHistorySyncCoordinator();
|
||||
|
||||
function selectGroupCandidates(
|
||||
async function selectGroupCandidates(
|
||||
store: MessageStore,
|
||||
states: readonly GroupHistorySyncState[],
|
||||
): GroupCandidate[] {
|
||||
return states
|
||||
.flatMap((state): GroupCandidate[] => {
|
||||
): Promise<GroupCandidate[]> {
|
||||
return (
|
||||
await mapWithConcurrency(states, 8, async (state): Promise<GroupCandidate[]> => {
|
||||
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const observedSequence = store.findLatestAuthoritativeSequence(true, state.groupId);
|
||||
const localSequence = store.findLatestPersistedAuthoritativeSequence(
|
||||
const observedSequence = await store.findLatestAuthoritativeSequence(
|
||||
true,
|
||||
state.groupId,
|
||||
);
|
||||
const localSequence = await store.findLatestPersistedAuthoritativeSequence(
|
||||
true,
|
||||
state.groupId,
|
||||
);
|
||||
@@ -312,22 +319,27 @@ function selectGroupCandidates(
|
||||
},
|
||||
];
|
||||
})
|
||||
)
|
||||
.flat()
|
||||
.sort(compareCandidates)
|
||||
.slice(0, LOGIN_HISTORY_SYNC_LIMITS.maxGroups);
|
||||
}
|
||||
|
||||
function selectPrivateCandidates(
|
||||
async function selectPrivateCandidates(
|
||||
store: MessageStore,
|
||||
states: readonly PrivateHistorySyncState[],
|
||||
): PrivateCandidate[] {
|
||||
return states
|
||||
.flatMap((state): PrivateCandidate[] => {
|
||||
): Promise<PrivateCandidate[]> {
|
||||
return (
|
||||
await mapWithConcurrency(states, 8, async (state): Promise<PrivateCandidate[]> => {
|
||||
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const observedSequence = store.findLatestAuthoritativeSequence(false, state.userId);
|
||||
const localSequence = store.findLatestPersistedAuthoritativeSequence(
|
||||
const observedSequence = await store.findLatestAuthoritativeSequence(
|
||||
false,
|
||||
state.userId,
|
||||
);
|
||||
const localSequence = await store.findLatestPersistedAuthoritativeSequence(
|
||||
false,
|
||||
state.userId,
|
||||
);
|
||||
@@ -360,6 +372,8 @@ function selectPrivateCandidates(
|
||||
},
|
||||
];
|
||||
})
|
||||
)
|
||||
.flat()
|
||||
.sort(compareCandidates)
|
||||
.slice(0, LOGIN_HISTORY_SYNC_LIMITS.maxPrivateUsers);
|
||||
}
|
||||
@@ -452,7 +466,7 @@ async function persistGroupMessage(
|
||||
);
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, converted);
|
||||
await persistHistoryEvent(ref.messageStore, converted);
|
||||
}
|
||||
|
||||
async function persistPrivateMessage(
|
||||
@@ -489,7 +503,12 @@ async function persistPrivateMessage(
|
||||
}
|
||||
|
||||
if (
|
||||
ref.messageStore.isPrivateMessageRecalled(peerUin, clientSequence, sentBySelf, message.time)
|
||||
await ref.messageStore.isPrivateMessageRecalled(
|
||||
peerUin,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
message.time,
|
||||
)
|
||||
) {
|
||||
log.debug(
|
||||
'login history sync omitted recalled private message: UIN=%d peer=%d clientSeq=%d self=%s',
|
||||
@@ -505,8 +524,7 @@ async function persistPrivateMessage(
|
||||
converted.target_id = peerUin;
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, converted, peerUin, message);
|
||||
return true;
|
||||
return persistHistoryEvent(ref.messageStore, converted, peerUin, message);
|
||||
}
|
||||
|
||||
function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
fetchPttText as fetchPttTextAction,
|
||||
getImageInfo as getCachedImageInfo,
|
||||
getRecordInfo as getCachedRecordInfo,
|
||||
refreshMessageMedia,
|
||||
} from './modules/media-actions';
|
||||
import {
|
||||
deleteMessage,
|
||||
@@ -58,8 +59,12 @@ export interface OneBotInstanceContext {
|
||||
config: OneBotConfig;
|
||||
musicSignUrl?: string;
|
||||
getUptimeMs(): number;
|
||||
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
|
||||
dispatchEvent(event: JsonObject, source?: 'bridge' | 'send', startedAt?: number): void;
|
||||
cacheMessageMeta(messageId: number, meta: MessageMeta): void | Promise<void>;
|
||||
dispatchEvent(
|
||||
event: JsonObject,
|
||||
source?: 'bridge' | 'send',
|
||||
startedAt?: number,
|
||||
): void | Promise<void>;
|
||||
}
|
||||
|
||||
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
@@ -71,11 +76,14 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
getLoginInfo: () => getLoginInfo(ref),
|
||||
isOnline: () => true,
|
||||
getUptimeMs: () => ref.getUptimeMs(),
|
||||
getMessage: (messageId) => messageStore.findEvent(messageId),
|
||||
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||
cacheMessageMetas: (entries) => messageStore.storeMetas(entries),
|
||||
listReadSessions: () =>
|
||||
messageStore.listReadSessions(bridge.identity.groups.map((group) => group.groupId)),
|
||||
getMessage: async (messageId) => await messageStore.findEvent(messageId),
|
||||
refreshMessageMedia: (messageId, event) => refreshMessageMedia(ref, messageId, event),
|
||||
getMessageMeta: async (messageId) => await messageStore.findMeta(messageId),
|
||||
cacheMessageMetas: async (entries) => await messageStore.storeMetas(entries),
|
||||
listReadSessions: async () =>
|
||||
await messageStore.listReadSessions(
|
||||
bridge.identity.groups.map((group) => group.groupId),
|
||||
),
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) =>
|
||||
@@ -85,7 +93,9 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
message,
|
||||
autoEscape,
|
||||
tempGroupId,
|
||||
tempGroupId === undefined ? (event) => ref.dispatchEvent(event, 'send') : undefined,
|
||||
tempGroupId === undefined
|
||||
? async (event) => await ref.dispatchEvent(event, 'send')
|
||||
: undefined,
|
||||
),
|
||||
sendGroupMessage: (groupId, message, autoEscape) =>
|
||||
sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
@@ -109,8 +119,12 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
sendGroupForwardMsg: (groupId, messages, meta) =>
|
||||
sendGroupForwardMessage(ref, groupId, messages, meta),
|
||||
sendPrivateForwardMsg: (userId, messages, meta) =>
|
||||
sendPrivateForwardMessage(ref, userId, messages, meta, (event) =>
|
||||
ref.dispatchEvent(event, 'send'),
|
||||
sendPrivateForwardMessage(
|
||||
ref,
|
||||
userId,
|
||||
messages,
|
||||
meta,
|
||||
async (event) => await ref.dispatchEvent(event, 'send'),
|
||||
),
|
||||
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
|
||||
getForwardMsg: (resId) => getForwardMessage(ref, resId),
|
||||
@@ -120,13 +134,13 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
messageId,
|
||||
target,
|
||||
target.userId !== undefined
|
||||
? (event) => ref.dispatchEvent(event, 'send')
|
||||
? async (event) => await ref.dispatchEvent(event, 'send')
|
||||
: undefined,
|
||||
),
|
||||
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
|
||||
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
|
||||
setMsgEmojiLike: async (messageId, emojiId, set) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
const meta = await messageStore.findMeta(messageId);
|
||||
|
||||
if (!meta) {
|
||||
throw new Error('message not found');
|
||||
@@ -144,7 +158,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
const emojiType = emojiId.length > 3 ? 2 : 1;
|
||||
|
||||
if (set) {
|
||||
reactionStore.recordAdd(
|
||||
await reactionStore.recordAdd(
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
emojiId,
|
||||
@@ -154,11 +168,11 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
Math.floor(Date.now() / 1000),
|
||||
);
|
||||
} else {
|
||||
reactionStore.recordRemove(meta.targetId, meta.sequence, emojiId, ref.selfId);
|
||||
await reactionStore.recordRemove(meta.targetId, meta.sequence, emojiId, ref.selfId);
|
||||
}
|
||||
},
|
||||
fetchEmojiLikeSummary: async (messageId) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
const meta = await messageStore.findMeta(messageId);
|
||||
|
||||
if (!meta) {
|
||||
throw new Error('message not found');
|
||||
@@ -172,7 +186,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
throw new Error('message has no authoritative QQ sequence');
|
||||
}
|
||||
|
||||
const summary = reactionStore.summarizeMessage(meta.targetId, meta.sequence);
|
||||
const summary = await reactionStore.summarizeMessage(meta.targetId, meta.sequence);
|
||||
const out: Array<{
|
||||
emoji_id: string;
|
||||
emoji_type: number;
|
||||
@@ -182,9 +196,15 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
}> = [];
|
||||
|
||||
for (const entry of summary) {
|
||||
let users = reactionStore
|
||||
.listUsers(meta.targetId, meta.sequence, entry.emojiId, 1000, 0)
|
||||
.map((user) => ({ user_id: user.operatorUin }));
|
||||
let users = (
|
||||
await reactionStore.listUsers(
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
entry.emojiId,
|
||||
1000,
|
||||
0,
|
||||
)
|
||||
).map((user) => ({ user_id: user.operatorUin }));
|
||||
|
||||
try {
|
||||
const remote = await bridge.apis.interaction.getEmojiLikes(
|
||||
@@ -214,7 +234,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
return out;
|
||||
},
|
||||
fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
const meta = await messageStore.findMeta(messageId);
|
||||
|
||||
if (!meta) {
|
||||
throw new Error('message not found');
|
||||
@@ -228,7 +248,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
throw new Error('message has no authoritative QQ sequence');
|
||||
}
|
||||
|
||||
const raw = reactionStore.listUsers(
|
||||
const raw = await reactionStore.listUsers(
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
emojiId,
|
||||
@@ -240,7 +260,11 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
uid: r.operatorUid,
|
||||
setAt: r.setAt,
|
||||
}));
|
||||
const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId);
|
||||
const cachedCount = await reactionStore.countUsers(
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
emojiId,
|
||||
);
|
||||
let serverCount = cachedCount;
|
||||
|
||||
try {
|
||||
|
||||
@@ -161,7 +161,7 @@ export class OneBotInstance {
|
||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
|
||||
mediaUrlResolver: (element, isGroup, sessionId) =>
|
||||
mediaUrlResolver.resolve(element, isGroup, sessionId),
|
||||
messageIdResolver: (
|
||||
messageIdResolver: async (
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
@@ -178,7 +178,7 @@ export class OneBotInstance {
|
||||
(resolvedEventName === PRIVATE_MESSAGE_EVENT ||
|
||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT)
|
||||
) {
|
||||
const storedId = this.messageStore.resolvePrivateReplyMessageId(
|
||||
const storedId = await this.messageStore.resolvePrivateReplyMessageId(
|
||||
sessionId,
|
||||
sequence,
|
||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
|
||||
@@ -199,8 +199,8 @@ export class OneBotInstance {
|
||||
: resolvedEventName,
|
||||
);
|
||||
},
|
||||
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
|
||||
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
|
||||
mediaSegmentSink: async (mediaType, element, data, isGroup, sessionId) =>
|
||||
await mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
|
||||
};
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: this.uin,
|
||||
@@ -214,7 +214,8 @@ export class OneBotInstance {
|
||||
config,
|
||||
musicSignUrl: globalSettings.musicSignUrl,
|
||||
getUptimeMs: () => Math.max(0, Date.now() - this.startedAt),
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
cacheMessageMeta: async (messageId, meta) =>
|
||||
await this.cacheMessageMeta(messageId, meta),
|
||||
dispatchEvent: (event, source = 'bridge', startedAt) =>
|
||||
this.dispatchEvent(event, source, startedAt),
|
||||
};
|
||||
@@ -225,7 +226,12 @@ export class OneBotInstance {
|
||||
this.networkManager = new OneBotNetworkManager((desired) =>
|
||||
this.createNetworkAdapter(desired, networkCtx),
|
||||
);
|
||||
this.networkReady = this.networkManager.reconcile(config);
|
||||
this.networkReady = Promise.all([
|
||||
bridge.identity.initialization,
|
||||
this.messageStore.initialization,
|
||||
this.mediaStore.initialization,
|
||||
this.reactionStore.initialization,
|
||||
]).then(() => this.networkManager.reconcile(config));
|
||||
this.lifecycleTail = this.networkReady.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
@@ -400,9 +406,9 @@ export class OneBotInstance {
|
||||
// reconcile and every transport have actually closed.
|
||||
const closeErrors: unknown[] = [];
|
||||
const stores = [
|
||||
['message', () => this.messageStore.close()],
|
||||
['media', () => this.mediaStore.close()],
|
||||
['reaction', () => this.reactionStore.close()],
|
||||
['message', async () => await this.messageStore.close()],
|
||||
['media', async () => await this.mediaStore.close()],
|
||||
['reaction', async () => await this.reactionStore.close()],
|
||||
] as const;
|
||||
|
||||
for (const [name, close] of stores) {
|
||||
@@ -411,7 +417,7 @@ export class OneBotInstance {
|
||||
}
|
||||
|
||||
try {
|
||||
close();
|
||||
await close();
|
||||
this.storeCloseState[name] = true;
|
||||
} catch (error) {
|
||||
closeErrors.push(error);
|
||||
@@ -466,9 +472,12 @@ export class OneBotInstance {
|
||||
source: 'bridge' | 'send' = 'bridge',
|
||||
startedAt = Date.now(),
|
||||
): Promise<void> {
|
||||
if (source === 'bridge') {
|
||||
this.cacheMessageEvent(event);
|
||||
if (!(await this.cacheMessageEvent(event))) {
|
||||
this.traceEventHandoffTerminal(event, startedAt, 'suppressed', 'private_recall');
|
||||
return;
|
||||
}
|
||||
|
||||
if (source === 'bridge') {
|
||||
if (this.consumePendingSelfSentEcho(event)) {
|
||||
this.log.trace(
|
||||
'duplicate self-message echo suppressed message_id=%d message_seq=%d',
|
||||
@@ -484,7 +493,6 @@ export class OneBotInstance {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
this.cacheMessageEvent(event);
|
||||
this.rememberPendingSelfSentEcho(event);
|
||||
}
|
||||
|
||||
@@ -492,7 +500,7 @@ export class OneBotInstance {
|
||||
// synthetic event here would produce a second, less accurate "received"
|
||||
// line whose private user_id points at the bot itself.
|
||||
if (source === 'bridge') {
|
||||
this.logReceivedMessage(event);
|
||||
await this.logReceivedMessage(event);
|
||||
}
|
||||
|
||||
// Built-in `#sl` only consumes events observed from QQ. Action-originated
|
||||
@@ -518,7 +526,7 @@ export class OneBotInstance {
|
||||
event: JsonObject,
|
||||
startedAt: number,
|
||||
outcome: 'suppressed' | 'reporting_started',
|
||||
reason?: 'duplicate_self_echo' | 'status_command',
|
||||
reason?: 'duplicate_self_echo' | 'status_command' | 'private_recall',
|
||||
): void {
|
||||
this.log.trace(() => [
|
||||
'event_terminal post_type=%s outcome=%s%s ms=%d',
|
||||
@@ -702,7 +710,7 @@ export class OneBotInstance {
|
||||
return rejected;
|
||||
}
|
||||
|
||||
private logReceivedMessage(event: JsonObject): void {
|
||||
private async logReceivedMessage(event: JsonObject): Promise<void> {
|
||||
const isSelf = event.post_type === 'message_sent';
|
||||
|
||||
if (event.post_type !== 'message' && !isSelf) {
|
||||
@@ -738,7 +746,7 @@ export class OneBotInstance {
|
||||
|
||||
if (type === 'reply') {
|
||||
const replyId = toInt(data.id);
|
||||
renderedParts.push(formatReply(this.messageStore, identity, replyId));
|
||||
renderedParts.push(await formatReply(this.messageStore, identity, replyId));
|
||||
} else {
|
||||
renderedParts.push(formatMessageSegments([seg as JsonValue]));
|
||||
}
|
||||
@@ -781,15 +789,15 @@ export class OneBotInstance {
|
||||
}
|
||||
}
|
||||
|
||||
private cacheMessageEvent(event: JsonObject): void {
|
||||
private async cacheMessageEvent(event: JsonObject): Promise<boolean> {
|
||||
if (event.post_type !== 'message' && event.post_type !== 'message_sent') {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
|
||||
if (messageId === 0) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
const isGroup = event.message_type === 'group';
|
||||
@@ -806,18 +814,25 @@ export class OneBotInstance {
|
||||
: PRIVATE_MESSAGE_EVENT;
|
||||
|
||||
if (sessionId === 0) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
|
||||
return this.messageStore.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
);
|
||||
}
|
||||
|
||||
private cacheMessageMeta(messageId: number, meta: MessageMeta): void {
|
||||
private async cacheMessageMeta(messageId: number, meta: MessageMeta): Promise<void> {
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.messageStore.storeMeta(messageId, meta);
|
||||
await this.messageStore.storeMeta(messageId, meta);
|
||||
}
|
||||
|
||||
private makeLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject {
|
||||
|
||||
@@ -7,18 +7,18 @@ export type MediaType = 'image' | 'record' | 'video';
|
||||
export class MediaIndexer {
|
||||
constructor(private readonly mediaStore: MediaStore) {}
|
||||
|
||||
remember(
|
||||
async remember(
|
||||
mediaType: MediaType,
|
||||
element: MessageElement,
|
||||
data: JsonObject,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const url = typeof data.url === 'string' ? data.url : '';
|
||||
const file = typeof data.file === 'string' ? data.file : '';
|
||||
|
||||
if (mediaType === 'image') {
|
||||
this.mediaStore.rememberImage({
|
||||
await this.mediaStore.rememberImage({
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
@@ -38,7 +38,7 @@ export class MediaIndexer {
|
||||
}
|
||||
|
||||
if (mediaType === 'record') {
|
||||
this.mediaStore.rememberRecord({
|
||||
await this.mediaStore.rememberRecord({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
@@ -57,7 +57,7 @@ export class MediaIndexer {
|
||||
}
|
||||
|
||||
// video
|
||||
this.mediaStore.rememberVideo({
|
||||
await this.mediaStore.rememberVideo({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { SqliteDatabase } from '@snowluma/sqlite';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
import {
|
||||
@@ -22,17 +22,17 @@ export async function migrateLegacyMedia(
|
||||
cancelled: () => boolean = () => false,
|
||||
): Promise<void> {
|
||||
const store = new MediaStore(messageDbPath);
|
||||
store.close();
|
||||
await store.close();
|
||||
const destination = openSqliteDb(messageDbPath);
|
||||
let source: DatabaseSync | undefined;
|
||||
let source: SqliteDatabase | undefined;
|
||||
|
||||
try {
|
||||
destination.exec(`CREATE TABLE IF NOT EXISTS media_migration_state (
|
||||
await destination.exec(`CREATE TABLE IF NOT EXISTS media_migration_state (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1), phase TEXT NOT NULL, cursor INTEGER NOT NULL
|
||||
); INSERT OR IGNORE INTO media_migration_state VALUES (1, 'entries', 0)`);
|
||||
const state = destination
|
||||
const state = (await destination
|
||||
.prepare('SELECT phase, cursor FROM media_migration_state WHERE id = 1')
|
||||
.get() as { phase: string; cursor: number };
|
||||
.get()) as { phase: string; cursor: number };
|
||||
|
||||
if (state.phase === 'complete') {
|
||||
return;
|
||||
@@ -41,11 +41,13 @@ export async function migrateLegacyMedia(
|
||||
const sourcePath = path.join(path.dirname(messageDbPath), 'media.db');
|
||||
|
||||
if (!fs.existsSync(sourcePath)) {
|
||||
destination.exec("UPDATE media_migration_state SET phase = 'complete' WHERE id = 1");
|
||||
await destination.exec(
|
||||
"UPDATE media_migration_state SET phase = 'complete' WHERE id = 1",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
source = new DatabaseSync(sourcePath, { readOnly: true });
|
||||
source = new SqliteDatabase(sourcePath, { readOnly: true });
|
||||
log.info('preserving legacy media metadata: migration started');
|
||||
const insertEntry =
|
||||
destination.prepare(`INSERT INTO legacy_media_entries (type, primary_key, data, last_seen)
|
||||
@@ -59,11 +61,11 @@ export async function migrateLegacyMedia(
|
||||
|
||||
while (!cancelled() && state.phase !== 'complete') {
|
||||
const table = state.phase === 'entries' ? 'media_entries' : 'media_keys';
|
||||
const rows = source
|
||||
const rows = (await source
|
||||
.prepare(
|
||||
`SELECT rowid AS migration_rowid, * FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT ?`,
|
||||
)
|
||||
.all(state.cursor, BATCH_SIZE) as Array<{
|
||||
.all(state.cursor, BATCH_SIZE)) as Array<{
|
||||
migration_rowid: number;
|
||||
type: string;
|
||||
primary_key: string;
|
||||
@@ -74,7 +76,7 @@ export async function migrateLegacyMedia(
|
||||
const nextPhase =
|
||||
rows.length === 0 ? (state.phase === 'entries' ? 'keys' : 'complete') : state.phase;
|
||||
const nextCursor = rows.at(-1)?.migration_rowid ?? 0;
|
||||
destination.exec('BEGIN IMMEDIATE');
|
||||
await destination.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
for (const row of rows) {
|
||||
@@ -93,14 +95,14 @@ export async function migrateLegacyMedia(
|
||||
);
|
||||
}
|
||||
|
||||
insertEntry.run(
|
||||
await insertEntry.run(
|
||||
row.type,
|
||||
foldMediaKey(row.primary_key),
|
||||
serializeMediaInfo(info),
|
||||
row.last_seen,
|
||||
);
|
||||
} else {
|
||||
insertKey.run(
|
||||
await insertKey.run(
|
||||
row.type,
|
||||
foldMediaKey(row.key),
|
||||
foldMediaKey(row.primary_key),
|
||||
@@ -108,10 +110,10 @@ export async function migrateLegacyMedia(
|
||||
}
|
||||
}
|
||||
|
||||
saveState.run(nextPhase, nextCursor);
|
||||
destination.exec('COMMIT');
|
||||
await saveState.run(nextPhase, nextCursor);
|
||||
await destination.exec('COMMIT');
|
||||
} catch (error) {
|
||||
rollbackMediaTransaction(destination, error);
|
||||
await rollbackMediaTransaction(destination, error);
|
||||
}
|
||||
|
||||
state.phase = nextPhase;
|
||||
@@ -129,7 +131,7 @@ export async function migrateLegacyMedia(
|
||||
log.info('preserving legacy media metadata: migration complete; source retained');
|
||||
}
|
||||
} finally {
|
||||
source?.close();
|
||||
destination.close();
|
||||
await source?.close();
|
||||
await destination.close();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import { SqliteDatabase, type SqliteStatement } from '@snowluma/sqlite';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
|
||||
export interface CachedImage {
|
||||
@@ -71,107 +71,163 @@ const INLINE_MEDIA_SOURCE = /^(base64:\/\/|data:)/i;
|
||||
* Only the in-memory lookup cache is bounded; history dependencies never expire.
|
||||
*/
|
||||
export class MediaStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly db: SqliteDatabase;
|
||||
private readonly cache = new Map<string, string>();
|
||||
private readonly upsertEntry: StatementSync;
|
||||
private readonly upsertKey: StatementSync;
|
||||
private readonly findEntry: StatementSync;
|
||||
private readonly findLegacyEntry: StatementSync;
|
||||
private upsertEntry!: SqliteStatement;
|
||||
private upsertKey!: SqliteStatement;
|
||||
private findEntry!: SqliteStatement;
|
||||
private findLegacyEntry!: SqliteStatement;
|
||||
|
||||
readonly initialization: Promise<void>;
|
||||
|
||||
constructor(
|
||||
dbPath: string,
|
||||
private readonly maxCachedEntries = DEFAULT_KEEP_ENTRIES,
|
||||
) {
|
||||
this.db = openSqliteDb(dbPath);
|
||||
this.initialization = this.db.serial(async () => {
|
||||
for (const prefix of ['', 'legacy_']) {
|
||||
await this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS ${prefix}media_entries (
|
||||
type TEXT NOT NULL, primary_key TEXT NOT NULL, data TEXT NOT NULL,
|
||||
last_seen INTEGER NOT NULL, PRIMARY KEY (type, primary_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS ${prefix}media_keys (
|
||||
type TEXT NOT NULL, key TEXT NOT NULL, primary_key TEXT NOT NULL,
|
||||
PRIMARY KEY (type, key)
|
||||
);
|
||||
`);
|
||||
}
|
||||
|
||||
for (const prefix of ['', 'legacy_']) {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS ${prefix}media_entries (
|
||||
type TEXT NOT NULL, primary_key TEXT NOT NULL, data TEXT NOT NULL,
|
||||
last_seen INTEGER NOT NULL, PRIMARY KEY (type, primary_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS ${prefix}media_keys (
|
||||
type TEXT NOT NULL, key TEXT NOT NULL, primary_key TEXT NOT NULL,
|
||||
PRIMARY KEY (type, key)
|
||||
);
|
||||
this.upsertEntry = this.db.prepare(`
|
||||
INSERT INTO media_entries (type, primary_key, data, last_seen) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(type, primary_key) DO UPDATE SET data = excluded.data, last_seen = excluded.last_seen
|
||||
`);
|
||||
}
|
||||
|
||||
this.upsertEntry = this.db.prepare(`
|
||||
INSERT INTO media_entries (type, primary_key, data, last_seen) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(type, primary_key) DO UPDATE SET data = excluded.data, last_seen = excluded.last_seen
|
||||
`);
|
||||
this.upsertKey = this.db.prepare(`
|
||||
INSERT INTO media_keys (type, key, primary_key) VALUES (?, ?, ?)
|
||||
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key
|
||||
`);
|
||||
this.findEntry = this.db.prepare(`
|
||||
SELECT data FROM media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
this.findLegacyEntry = this.db.prepare(`
|
||||
SELECT data FROM legacy_media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM legacy_media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
this.upsertKey = this.db.prepare(`
|
||||
INSERT INTO media_keys (type, key, primary_key) VALUES (?, ?, ?)
|
||||
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key
|
||||
`);
|
||||
this.findEntry = this.db.prepare(`
|
||||
SELECT data FROM media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
this.findLegacyEntry = this.db.prepare(`
|
||||
SELECT data FROM legacy_media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM legacy_media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
});
|
||||
void this.initialization.catch(() => undefined);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.cache.clear();
|
||||
this.db.close();
|
||||
async close(): Promise<void> {
|
||||
await this.initialization.catch(() => undefined);
|
||||
await this.db.close();
|
||||
}
|
||||
|
||||
rememberImage(info: CachedImage): void {
|
||||
this.remember(TYPE_IMAGE, info, [info.file, info.fileName, info.url]);
|
||||
async rememberImage(info: CachedImage): Promise<void> {
|
||||
info = structuredClone(info);
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.remember(TYPE_IMAGE, info, [info.file, info.fileName, info.url]);
|
||||
});
|
||||
}
|
||||
|
||||
rememberRecord(info: CachedRecord): void {
|
||||
this.remember(TYPE_RECORD, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
async rememberRecord(info: CachedRecord): Promise<void> {
|
||||
info = structuredClone(info);
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.remember(TYPE_RECORD, info, [
|
||||
info.file,
|
||||
info.fileName,
|
||||
info.fileId,
|
||||
info.url,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
rememberVideo(info: CachedVideo): void {
|
||||
this.remember(TYPE_VIDEO, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
async rememberVideo(info: CachedVideo): Promise<void> {
|
||||
info = structuredClone(info);
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.remember(TYPE_VIDEO, info, [
|
||||
info.file,
|
||||
info.fileName,
|
||||
info.fileId,
|
||||
info.url,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
findImage(key: string, source: MediaLookupSource = 'current'): CachedImage | null {
|
||||
return this.find(TYPE_IMAGE, key, source);
|
||||
async findImage(
|
||||
key: string,
|
||||
source: MediaLookupSource = 'current',
|
||||
): Promise<CachedImage | null> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
return await this.find(TYPE_IMAGE, key, source);
|
||||
});
|
||||
}
|
||||
findRecord(key: string, source: MediaLookupSource = 'current'): CachedRecord | null {
|
||||
return this.find(TYPE_RECORD, key, source);
|
||||
async findRecord(
|
||||
key: string,
|
||||
source: MediaLookupSource = 'current',
|
||||
): Promise<CachedRecord | null> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
return await this.find(TYPE_RECORD, key, source);
|
||||
});
|
||||
}
|
||||
findVideo(key: string, source: MediaLookupSource = 'current'): CachedVideo | null {
|
||||
return this.find(TYPE_VIDEO, key, source);
|
||||
async findVideo(
|
||||
key: string,
|
||||
source: MediaLookupSource = 'current',
|
||||
): Promise<CachedVideo | null> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
return await this.find(TYPE_VIDEO, key, source);
|
||||
});
|
||||
}
|
||||
|
||||
updateImageUrl(key: string, url: string): void {
|
||||
this.updateUrl(TYPE_IMAGE, key, url);
|
||||
async updateImageUrl(key: string, url: string): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.updateUrl(TYPE_IMAGE, key, url);
|
||||
});
|
||||
}
|
||||
updateRecordUrl(key: string, url: string): void {
|
||||
this.updateUrl(TYPE_RECORD, key, url);
|
||||
async updateRecordUrl(key: string, url: string): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.updateUrl(TYPE_RECORD, key, url);
|
||||
});
|
||||
}
|
||||
updateVideoUrl(key: string, url: string): void {
|
||||
this.updateUrl(TYPE_VIDEO, key, url);
|
||||
async updateVideoUrl(key: string, url: string): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.updateUrl(TYPE_VIDEO, key, url);
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts durable records, not the bounded lookup cache. */
|
||||
size(): { images: number; records: number; videos: number } {
|
||||
const counts = this.db
|
||||
.prepare(
|
||||
`SELECT type, COUNT(*) AS n FROM (
|
||||
SELECT type FROM media_entries UNION ALL SELECT type FROM legacy_media_entries
|
||||
) GROUP BY type`,
|
||||
)
|
||||
.all() as Array<{ type: string; n: number }>;
|
||||
const count = (type: string) => counts.find((row) => row.type === type)?.n ?? 0;
|
||||
return {
|
||||
images: count(TYPE_IMAGE),
|
||||
records: count(TYPE_RECORD),
|
||||
videos: count(TYPE_VIDEO),
|
||||
};
|
||||
async size(): Promise<{ images: number; records: number; videos: number }> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const counts = (await this.db
|
||||
.prepare(
|
||||
`SELECT type, COUNT(*) AS n FROM (
|
||||
SELECT type FROM media_entries UNION ALL SELECT type FROM legacy_media_entries
|
||||
) GROUP BY type`,
|
||||
)
|
||||
.all()) as Array<{ type: string; n: number }>;
|
||||
const count = (type: string) => counts.find((row) => row.type === type)?.n ?? 0;
|
||||
return {
|
||||
images: await count(TYPE_IMAGE),
|
||||
records: await count(TYPE_RECORD),
|
||||
videos: await count(TYPE_VIDEO),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private remember(type: string, info: object, aliases: string[]): void {
|
||||
private async remember(type: string, info: object, aliases: string[]): Promise<void> {
|
||||
const primary = pickPrimary(aliases);
|
||||
|
||||
if (!primary) {
|
||||
@@ -179,18 +235,18 @@ export class MediaStore {
|
||||
}
|
||||
|
||||
const data = serializeMediaInfo(info);
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
await this.db.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
this.upsertEntry.run(type, primary, data, Math.floor(Date.now() / 1000));
|
||||
await this.upsertEntry.run(type, primary, data, Math.floor(Date.now() / 1000));
|
||||
|
||||
for (const key of new Set(aliases.filter(Boolean).map(foldMediaKey))) {
|
||||
this.upsertKey.run(type, key, primary);
|
||||
await this.upsertKey.run(type, key, primary);
|
||||
}
|
||||
|
||||
this.db.exec('COMMIT');
|
||||
await this.db.exec('COMMIT');
|
||||
} catch (error) {
|
||||
rollbackMediaTransaction(this.db, error);
|
||||
await rollbackMediaTransaction(this.db, error);
|
||||
}
|
||||
|
||||
// Alias remapping can invalidate any cached lookup. JSON strings ensure
|
||||
@@ -198,7 +254,11 @@ export class MediaStore {
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
private find<T>(type: string, key: string, source: MediaLookupSource = 'current'): T | null {
|
||||
private async find<T>(
|
||||
type: string,
|
||||
key: string,
|
||||
source: MediaLookupSource = 'current',
|
||||
): Promise<T | null> {
|
||||
const lookup = foldMediaKey(key);
|
||||
|
||||
if (!lookup) {
|
||||
@@ -212,8 +272,11 @@ export class MediaStore {
|
||||
// Legacy history has no per-message snapshots. Its frozen migration
|
||||
// index must never resolve through a later, mutable filename alias.
|
||||
const current =
|
||||
source === 'current' ? this.findEntry.get(type, type, lookup, lookup) : undefined;
|
||||
const row = (current ?? this.findLegacyEntry.get(type, type, lookup, lookup)) as
|
||||
source === 'current'
|
||||
? await this.findEntry.get(type, type, lookup, lookup)
|
||||
: undefined;
|
||||
const row = (current ??
|
||||
(await this.findLegacyEntry.get(type, type, lookup, lookup))) as
|
||||
{ data: string } | undefined;
|
||||
|
||||
if (!row) {
|
||||
@@ -240,18 +303,18 @@ export class MediaStore {
|
||||
return result as T;
|
||||
}
|
||||
|
||||
private updateUrl(type: string, key: string, url: string): void {
|
||||
private async updateUrl(type: string, key: string, url: string): Promise<void> {
|
||||
if (!url || mustFoldMediaKey(url)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const info = this.find<Record<string, unknown>>(type, key);
|
||||
const info = await this.find<Record<string, unknown>>(type, key);
|
||||
|
||||
if (!info || info.url === url) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.remember(
|
||||
await this.remember(
|
||||
type,
|
||||
{ ...info, url },
|
||||
[info.file, info.fileName, info.fileId, url].filter(
|
||||
@@ -271,9 +334,9 @@ export function serializeMediaInfo(info: object): string {
|
||||
return data;
|
||||
}
|
||||
|
||||
export function rollbackMediaTransaction(db: DatabaseSync, error: unknown): never {
|
||||
export async function rollbackMediaTransaction(db: SqliteDatabase, error: unknown): Promise<never> {
|
||||
try {
|
||||
db.exec('ROLLBACK');
|
||||
await db.exec('ROLLBACK');
|
||||
} catch (rollbackError) {
|
||||
throw new AggregateError([error, rollbackError], 'media write and rollback failed', {
|
||||
cause: error,
|
||||
|
||||
@@ -1,7 +1,30 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import type { RKeyCache } from './instance-rkey';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
export function resolveRemoteMediaUrl(
|
||||
bridge: BridgeInterface,
|
||||
type: 'record' | 'video',
|
||||
node: MessageElement['mediaNode'],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): Promise<string> {
|
||||
if (!node) {
|
||||
throw new Error(`${type} media metadata is missing`);
|
||||
}
|
||||
|
||||
const api = bridge.apis.groupFile;
|
||||
|
||||
if (type === 'record') {
|
||||
return isGroup ? api.getPttUrl(sessionId, node) : api.getPrivatePttUrl(node);
|
||||
}
|
||||
|
||||
return isGroup ? api.getVideoUrl(sessionId, node) : api.getPrivateVideoUrl(node);
|
||||
}
|
||||
|
||||
export class MediaUrlResolver {
|
||||
constructor(
|
||||
private readonly bridge: BridgeInterface,
|
||||
@@ -12,9 +35,14 @@ export class MediaUrlResolver {
|
||||
if (!element.url) {
|
||||
try {
|
||||
await this.populateUrl(element, isGroup, sessionId);
|
||||
} catch {
|
||||
// Best-effort: a URL fetch hiccup should never block the
|
||||
// outgoing segment. The RKey pass below still runs.
|
||||
} catch (err) {
|
||||
// Preserve the media segment when its download URL is unavailable.
|
||||
log.warn(
|
||||
'media URL resolution failed type=%s is_group=%s: %s',
|
||||
element.type,
|
||||
isGroup,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,20 +70,13 @@ export class MediaUrlResolver {
|
||||
}
|
||||
|
||||
if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
|
||||
if (isGroup) {
|
||||
element.url =
|
||||
element.type === 'record'
|
||||
? await this.bridge.apis.groupFile.getPttUrl(sessionId, element.mediaNode)
|
||||
: await this.bridge.apis.groupFile.getVideoUrl(
|
||||
sessionId,
|
||||
element.mediaNode,
|
||||
);
|
||||
} else {
|
||||
element.url =
|
||||
element.type === 'record'
|
||||
? await this.bridge.apis.groupFile.getPrivatePttUrl(element.mediaNode)
|
||||
: await this.bridge.apis.groupFile.getPrivateVideoUrl(element.mediaNode);
|
||||
}
|
||||
element.url = await resolveRemoteMediaUrl(
|
||||
this.bridge,
|
||||
element.type,
|
||||
element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,28 @@ export type MessageMedia = Extract<MessageElement, { type: 'image' | 'record' |
|
||||
const mediaSnapshot = Symbol('message media snapshot');
|
||||
type MediaSegment = JsonObject & { [mediaSnapshot]?: MessageMedia };
|
||||
|
||||
/** Snapshot queued writes, including metadata that is deliberately absent from JSON. */
|
||||
export function snapshotMessageEvent(event: JsonObject): JsonObject {
|
||||
const snapshot = structuredClone(event);
|
||||
|
||||
if (Array.isArray(event.message) && Array.isArray(snapshot.message)) {
|
||||
for (const [index, segment] of event.message.entries()) {
|
||||
if (!segment || typeof segment !== 'object' || Array.isArray(segment)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const media = (segment as MediaSegment)[mediaSnapshot];
|
||||
const copied = snapshot.message[index];
|
||||
|
||||
if (media && copied && typeof copied === 'object') {
|
||||
Object.defineProperty(copied, mediaSnapshot, { value: structuredClone(media) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export function isMessageMedia(element: MessageElement): element is MessageMedia {
|
||||
return element.type === 'image' || element.type === 'record' || element.type === 'video';
|
||||
}
|
||||
|
||||
@@ -11,20 +11,39 @@ import {
|
||||
import { parseFromCQString } from './helper/cq';
|
||||
import { getElementCodec, intOr } from './event-converter/element-codecs';
|
||||
import type { JsonValue } from './types';
|
||||
import { assertReplyPreviewType, elementsToReplyPreview } from './reply-preview';
|
||||
|
||||
const log = createLogger('MsgParser');
|
||||
|
||||
export { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
|
||||
interface ForwardReplyContext {
|
||||
senderUin: number;
|
||||
time?: number;
|
||||
}
|
||||
|
||||
export interface ParseMessageOptions {
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||
resolveReplyMeta?: (replyMessageId: number) => {
|
||||
senderUin: number;
|
||||
time: number;
|
||||
random: number;
|
||||
elements?: MessageElement[];
|
||||
sequenceAuthoritative?: boolean;
|
||||
} | null;
|
||||
/** Custom quote defaults, supplied only while parsing a merged-forward node. */
|
||||
forwardReply?: ForwardReplyContext;
|
||||
/** Internal: quote content cannot nest replies or invoke action-like codecs. */
|
||||
replyPreview?: boolean;
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null | Promise<number | null>;
|
||||
resolveReplyMeta?: (replyMessageId: number) =>
|
||||
| {
|
||||
senderUin: number;
|
||||
time: number;
|
||||
random: number;
|
||||
elements?: MessageElement[];
|
||||
sequenceAuthoritative?: boolean;
|
||||
}
|
||||
| null
|
||||
| Promise<{
|
||||
senderUin: number;
|
||||
time: number;
|
||||
random: number;
|
||||
elements?: MessageElement[];
|
||||
sequenceAuthoritative?: boolean;
|
||||
} | null>;
|
||||
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
|
||||
resolveContactArk?: (
|
||||
contactType: string,
|
||||
@@ -95,15 +114,6 @@ function isExplicitEmptyTextPlaceholder(segment: MessageSegment): boolean {
|
||||
return normalizeSegmentType(segment.type) === 'text' && segmentPayload(segment).text === '';
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the OneBot payload is a forward: every effective segment is
|
||||
* `node` (explicit empty-text placeholders ignored). `send_msg` routes
|
||||
* this list through the forward upload path instead of parseMessage.
|
||||
*/
|
||||
export function isExclusiveForwardNodeMessage(message: JsonValue, autoEscape: boolean): boolean {
|
||||
return exclusiveForwardNodeList(message, autoEscape) !== null;
|
||||
}
|
||||
|
||||
/** Node segments from an exclusive forward payload, or null if it is not one. */
|
||||
export function exclusiveForwardNodeList(
|
||||
message: JsonValue,
|
||||
@@ -318,6 +328,55 @@ function requireCoordinate(data: Record<string, unknown>, field: 'lat' | 'lon'):
|
||||
return text;
|
||||
}
|
||||
|
||||
function replyInteger(
|
||||
data: Record<string, unknown>,
|
||||
field: string,
|
||||
defaultValue: number,
|
||||
max: number,
|
||||
min = 1,
|
||||
): number {
|
||||
const raw = data[field];
|
||||
const value = raw === undefined ? defaultValue : intOr(raw);
|
||||
|
||||
if (raw === null || (typeof raw === 'string' && !raw.trim()) || value < min || value > max) {
|
||||
throw new MessageElementValidationError(
|
||||
'INVALID_FIELD',
|
||||
`reply.${field} must be an integer between ${min} and ${max}`,
|
||||
'reply',
|
||||
field,
|
||||
);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
async function parseForwardReply(
|
||||
data: Record<string, unknown>,
|
||||
context: ForwardReplyContext,
|
||||
): Promise<MessageElement> {
|
||||
const { message, ...metadata } = data;
|
||||
assertScalarSegmentData('reply', metadata);
|
||||
const replySenderUin = replyInteger(data, 'qq', context.senderUin, Number.MAX_SAFE_INTEGER);
|
||||
const replyTime = replyInteger(
|
||||
data,
|
||||
'time',
|
||||
context.time ?? Math.floor(Date.now() / 1000),
|
||||
0xffffffff,
|
||||
0,
|
||||
);
|
||||
// A synthetic quote has no live message to navigate to; QQ still needs a
|
||||
// positive origSeqs entry to render its inline preview.
|
||||
const replySeq = replyInteger(data, 'seq', 1, 0xffffffff);
|
||||
const elements = await parseMessage(message, false, { replyPreview: true });
|
||||
return validatedOutboundElement({
|
||||
type: 'reply',
|
||||
replySeq,
|
||||
replySenderUin,
|
||||
replyTime,
|
||||
replyElements: elementsToReplyPreview(elements),
|
||||
});
|
||||
}
|
||||
|
||||
export async function segmentToElement(
|
||||
type: string,
|
||||
data: Record<string, unknown>,
|
||||
@@ -325,6 +384,23 @@ export async function segmentToElement(
|
||||
): Promise<MessageElement | null> {
|
||||
const normalizedType = normalizeSegmentType(type);
|
||||
|
||||
if (options?.replyPreview) {
|
||||
assertReplyPreviewType(normalizedType);
|
||||
}
|
||||
|
||||
if (normalizedType === 'reply' && Object.hasOwn(data, 'message')) {
|
||||
if (!options?.forwardReply) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'reply.message is only supported inside a forward node',
|
||||
'reply',
|
||||
'message',
|
||||
);
|
||||
}
|
||||
|
||||
return parseForwardReply(data, options.forwardReply);
|
||||
}
|
||||
|
||||
// Ordinary OneBot segment fields are scalar. JSON deliberately accepts its
|
||||
// object-valued data/config compatibility fields; every other object/array
|
||||
// is rejected before a codec can coerce it and alter caller intent. Forward
|
||||
@@ -593,7 +669,7 @@ function segmentPayload(seg: MessageSegment): Record<string, unknown> {
|
||||
// --- Public API ---
|
||||
|
||||
export async function parseMessage(
|
||||
message: JsonValue,
|
||||
message: unknown,
|
||||
autoEscape: boolean,
|
||||
options?: ParseMessageOptions,
|
||||
): Promise<MessageElement[]> {
|
||||
@@ -658,7 +734,7 @@ export async function parseMessage(
|
||||
|
||||
// Single segment object
|
||||
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
|
||||
const seg = message as unknown as MessageSegment;
|
||||
const seg = message as MessageSegment;
|
||||
|
||||
if (typeof seg.type === 'string' && seg.type.trim()) {
|
||||
const data = segmentPayload(seg);
|
||||
|
||||
@@ -65,7 +65,7 @@ export async function runMessageStoreMigrationWorker(
|
||||
port.on('message', handleControlMessage);
|
||||
|
||||
try {
|
||||
prepareMessageStoreDatabase(data.dbPath);
|
||||
await prepareMessageStoreDatabase(data.dbPath);
|
||||
await migrateLegacyMedia(data.dbPath, () => cancelled);
|
||||
|
||||
if (cancelled) {
|
||||
@@ -88,7 +88,7 @@ export async function runMessageStoreMigrationWorker(
|
||||
let lastProgressAt: number | null = null;
|
||||
|
||||
while (!cancelled) {
|
||||
const status = migrator.runBatch(DEFAULT_BATCH_SIZE);
|
||||
const status = await migrator.runBatch(DEFAULT_BATCH_SIZE);
|
||||
const progressAt = performance.now();
|
||||
port.postMessage({
|
||||
kind: 'progress',
|
||||
@@ -110,7 +110,7 @@ export async function runMessageStoreMigrationWorker(
|
||||
} satisfies MessageStoreMigrationWorkerMessage);
|
||||
} finally {
|
||||
port.off('message', handleControlMessage);
|
||||
migrator?.close();
|
||||
await migrator?.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import { SqliteDatabase, type SqliteStatement } from '@snowluma/sqlite';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
|
||||
const CLASSIFICATION_VERSION = 1;
|
||||
@@ -38,149 +38,158 @@ interface PendingMessageRow {
|
||||
}
|
||||
|
||||
export class MessageStoreMigrator {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly selectInitialBatch: StatementSync;
|
||||
private readonly selectNextBatch: StatementSync;
|
||||
private readonly updateRow: StatementSync;
|
||||
private readonly updateState: StatementSync;
|
||||
private state: MigrationStateRow;
|
||||
private readonly db: SqliteDatabase;
|
||||
private selectInitialBatch!: SqliteStatement;
|
||||
private selectNextBatch!: SqliteStatement;
|
||||
private updateRow!: SqliteStatement;
|
||||
private updateState!: SqliteStatement;
|
||||
private state!: MigrationStateRow;
|
||||
|
||||
readonly initialization: Promise<void>;
|
||||
|
||||
constructor(
|
||||
dbPath: string,
|
||||
reportPreparation?: (progress: MessageStoreMigrationPreparation) => void,
|
||||
) {
|
||||
this.db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
|
||||
|
||||
try {
|
||||
createMigrationStateTable(this.db);
|
||||
this.state = this.loadOrCreateState(reportPreparation);
|
||||
this.initialization = this.db.serial(async () => {
|
||||
await createMigrationStateTable(this.db);
|
||||
this.state = await this.loadOrCreateState(reportPreparation);
|
||||
this.selectInitialBatch = this.db.prepare(`
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
this.selectNextBatch = this.db.prepare(`
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ? AND message_hash > ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ? AND message_hash > ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
this.updateRow = this.db.prepare(`
|
||||
UPDATE messages
|
||||
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
|
||||
WHERE message_hash = ?
|
||||
AND classification_version < ?
|
||||
AND is_group = ?
|
||||
AND sequence = ?
|
||||
AND sequence_authoritative = ?
|
||||
AND client_sequence = ?
|
||||
AND private_direction = ?
|
||||
AND random = ?
|
||||
AND data IS ?
|
||||
`);
|
||||
UPDATE messages
|
||||
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
|
||||
WHERE message_hash = ?
|
||||
AND classification_version < ?
|
||||
AND is_group = ?
|
||||
AND sequence = ?
|
||||
AND sequence_authoritative = ?
|
||||
AND client_sequence = ?
|
||||
AND private_direction = ?
|
||||
AND random = ?
|
||||
AND data IS ?
|
||||
`);
|
||||
this.updateState = this.db.prepare(`
|
||||
UPDATE message_store_migration_state
|
||||
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
|
||||
WHERE name = ?
|
||||
`);
|
||||
} catch (error) {
|
||||
this.db.close();
|
||||
throw error;
|
||||
}
|
||||
UPDATE message_store_migration_state
|
||||
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
|
||||
WHERE name = ?
|
||||
`);
|
||||
});
|
||||
void this.initialization.catch(() => undefined);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
async close(): Promise<void> {
|
||||
await this.initialization.catch(() => undefined);
|
||||
await this.db.close();
|
||||
}
|
||||
|
||||
getStatus(): MessageStoreMigrationStatus {
|
||||
return publicStatus(this.state);
|
||||
async getStatus(): Promise<MessageStoreMigrationStatus> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
return publicStatus(this.state);
|
||||
});
|
||||
}
|
||||
|
||||
runBatch(batchSize: number): MessageStoreMigrationStatus {
|
||||
const limit = normalizeBatchSize(batchSize);
|
||||
async runBatch(batchSize: number): Promise<MessageStoreMigrationStatus> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const limit = normalizeBatchSize(batchSize);
|
||||
|
||||
if (this.state.phase === 'complete') {
|
||||
return this.getStatus();
|
||||
}
|
||||
|
||||
let rows = this.readBatch(limit, this.state.cursor);
|
||||
|
||||
if (rows.length === 0 && this.state.cursor !== null) {
|
||||
rows = this.readBatch(limit, null);
|
||||
}
|
||||
|
||||
if (rows.length === 0) {
|
||||
const remaining = this.countPending();
|
||||
this.persistState({
|
||||
...this.state,
|
||||
phase: remaining === 0 ? 'complete' : 'migrating',
|
||||
processed: remaining === 0 ? this.state.total : this.state.total - remaining,
|
||||
cursor: null,
|
||||
});
|
||||
return this.getStatus();
|
||||
}
|
||||
|
||||
const lastMessageHash = rows[rows.length - 1].message_hash;
|
||||
const classified = rows.map((row) => ({ row, classification: classifyLegacyMessage(row) }));
|
||||
let updatedRows = 0;
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
for (const { row, classification } of classified) {
|
||||
const result = this.updateRow.run(
|
||||
classification.sequenceAuthoritative ? 1 : 0,
|
||||
classification.privateDirection,
|
||||
CLASSIFICATION_VERSION,
|
||||
row.message_hash,
|
||||
CLASSIFICATION_VERSION,
|
||||
row.is_group,
|
||||
row.sequence,
|
||||
row.sequence_authoritative,
|
||||
row.client_sequence,
|
||||
row.private_direction,
|
||||
row.random,
|
||||
row.data,
|
||||
);
|
||||
updatedRows += Number(result.changes);
|
||||
if (this.state.phase === 'complete') {
|
||||
return this.getStatus();
|
||||
}
|
||||
|
||||
const nextState: MigrationStateRow = {
|
||||
...this.state,
|
||||
processed: Math.min(this.state.total, this.state.processed + updatedRows),
|
||||
cursor: lastMessageHash,
|
||||
};
|
||||
this.writeState(nextState);
|
||||
this.db.exec('COMMIT');
|
||||
this.state = nextState;
|
||||
} catch (error) {
|
||||
this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
let rows = await this.readBatch(limit, this.state.cursor);
|
||||
|
||||
if (rows.length < limit) {
|
||||
const remaining = this.countPending();
|
||||
if (rows.length === 0 && this.state.cursor !== null) {
|
||||
rows = await this.readBatch(limit, null);
|
||||
}
|
||||
|
||||
if (remaining === 0) {
|
||||
this.persistState({
|
||||
if (rows.length === 0) {
|
||||
const remaining = await this.countPending();
|
||||
await this.persistState({
|
||||
...this.state,
|
||||
phase: 'complete',
|
||||
processed: this.state.total,
|
||||
phase: remaining === 0 ? 'complete' : 'migrating',
|
||||
processed: remaining === 0 ? this.state.total : this.state.total - remaining,
|
||||
cursor: null,
|
||||
});
|
||||
return this.getStatus();
|
||||
}
|
||||
}
|
||||
|
||||
return this.getStatus();
|
||||
const lastMessageHash = rows[rows.length - 1].message_hash;
|
||||
const classified = rows.map((row) => ({
|
||||
row,
|
||||
classification: classifyLegacyMessage(row),
|
||||
}));
|
||||
let updatedRows = 0;
|
||||
await this.db.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
for (const { row, classification } of classified) {
|
||||
const result = await this.updateRow.run(
|
||||
classification.sequenceAuthoritative ? 1 : 0,
|
||||
classification.privateDirection,
|
||||
CLASSIFICATION_VERSION,
|
||||
row.message_hash,
|
||||
CLASSIFICATION_VERSION,
|
||||
row.is_group,
|
||||
row.sequence,
|
||||
row.sequence_authoritative,
|
||||
row.client_sequence,
|
||||
row.private_direction,
|
||||
row.random,
|
||||
row.data,
|
||||
);
|
||||
updatedRows += Number(result.changes);
|
||||
}
|
||||
|
||||
const nextState: MigrationStateRow = {
|
||||
...this.state,
|
||||
processed: Math.min(this.state.total, this.state.processed + updatedRows),
|
||||
cursor: lastMessageHash,
|
||||
};
|
||||
await this.writeState(nextState);
|
||||
await this.db.exec('COMMIT');
|
||||
this.state = nextState;
|
||||
} catch (error) {
|
||||
await this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (rows.length < limit) {
|
||||
const remaining = await this.countPending();
|
||||
|
||||
if (remaining === 0) {
|
||||
await this.persistState({
|
||||
...this.state,
|
||||
phase: 'complete',
|
||||
processed: this.state.total,
|
||||
cursor: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return this.getStatus();
|
||||
});
|
||||
}
|
||||
|
||||
private loadOrCreateState(
|
||||
private async loadOrCreateState(
|
||||
reportPreparation?: (progress: MessageStoreMigrationPreparation) => void,
|
||||
): MigrationStateRow {
|
||||
const existing = this.db
|
||||
): Promise<MigrationStateRow> {
|
||||
const existing = (await this.db
|
||||
.prepare(
|
||||
`
|
||||
SELECT phase, processed, total, cursor
|
||||
@@ -188,7 +197,7 @@ export class MessageStoreMigrator {
|
||||
WHERE name = ?
|
||||
`,
|
||||
)
|
||||
.get(MIGRATION_NAME) as MigrationStateRow | undefined;
|
||||
.get(MIGRATION_NAME)) as MigrationStateRow | undefined;
|
||||
|
||||
if (existing?.phase === 'complete') {
|
||||
return existing;
|
||||
@@ -196,7 +205,7 @@ export class MessageStoreMigrator {
|
||||
|
||||
reportPreparation?.({ stage: 'started' });
|
||||
const preparationStartedAt = performance.now();
|
||||
this.db.exec(`
|
||||
await this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS ${PENDING_INDEX_NAME}
|
||||
ON messages(message_hash, classification_version)
|
||||
WHERE classification_version < ${CLASSIFICATION_VERSION}
|
||||
@@ -211,7 +220,7 @@ export class MessageStoreMigrator {
|
||||
}
|
||||
|
||||
const countStartedAt = performance.now();
|
||||
const row = this.db
|
||||
const row = (await this.db
|
||||
.prepare(
|
||||
`
|
||||
SELECT COUNT(*) AS total
|
||||
@@ -219,7 +228,7 @@ export class MessageStoreMigrator {
|
||||
WHERE classification_version < ?
|
||||
`,
|
||||
)
|
||||
.get(CLASSIFICATION_VERSION) as { total: number };
|
||||
.get(CLASSIFICATION_VERSION)) as { total: number };
|
||||
const total = Number(row.total);
|
||||
reportPreparation?.({
|
||||
stage: 'counted',
|
||||
@@ -233,7 +242,7 @@ export class MessageStoreMigrator {
|
||||
total,
|
||||
cursor: null,
|
||||
};
|
||||
this.db
|
||||
await this.db
|
||||
.prepare(
|
||||
`
|
||||
INSERT INTO message_store_migration_state
|
||||
@@ -245,8 +254,8 @@ export class MessageStoreMigrator {
|
||||
return state;
|
||||
}
|
||||
|
||||
private countPending(): number {
|
||||
const row = this.db
|
||||
private async countPending(): Promise<number> {
|
||||
const row = (await this.db
|
||||
.prepare(
|
||||
`
|
||||
SELECT COUNT(*) AS total
|
||||
@@ -254,35 +263,35 @@ export class MessageStoreMigrator {
|
||||
WHERE classification_version < ?
|
||||
`,
|
||||
)
|
||||
.get(CLASSIFICATION_VERSION) as { total: number };
|
||||
.get(CLASSIFICATION_VERSION)) as { total: number };
|
||||
return Number(row.total);
|
||||
}
|
||||
|
||||
private readBatch(limit: number, cursor: number | null): PendingMessageRow[] {
|
||||
private async readBatch(limit: number, cursor: number | null): Promise<PendingMessageRow[]> {
|
||||
return (cursor === null
|
||||
? this.selectInitialBatch.all(CLASSIFICATION_VERSION, limit)
|
||||
: this.selectNextBatch.all(
|
||||
? await this.selectInitialBatch.all(CLASSIFICATION_VERSION, limit)
|
||||
: await this.selectNextBatch.all(
|
||||
CLASSIFICATION_VERSION,
|
||||
cursor,
|
||||
limit,
|
||||
)) as unknown as PendingMessageRow[];
|
||||
}
|
||||
|
||||
private persistState(state: MigrationStateRow): void {
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
private async persistState(state: MigrationStateRow): Promise<void> {
|
||||
await this.db.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
this.writeState(state);
|
||||
this.db.exec('COMMIT');
|
||||
await this.writeState(state);
|
||||
await this.db.exec('COMMIT');
|
||||
this.state = state;
|
||||
} catch (error) {
|
||||
this.db.exec('ROLLBACK');
|
||||
await this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private writeState(state: MigrationStateRow): void {
|
||||
this.updateState.run(
|
||||
private async writeState(state: MigrationStateRow): Promise<void> {
|
||||
await this.updateState.run(
|
||||
state.phase,
|
||||
state.processed,
|
||||
state.total,
|
||||
@@ -293,12 +302,12 @@ export class MessageStoreMigrator {
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareMessageStoreDatabase(dbPath: string): void {
|
||||
export async function prepareMessageStoreDatabase(dbPath: string): Promise<void> {
|
||||
const db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
|
||||
|
||||
try {
|
||||
const messagesTableExists =
|
||||
db
|
||||
(await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT 1 AS present
|
||||
@@ -306,8 +315,8 @@ export function prepareMessageStoreDatabase(dbPath: string): void {
|
||||
WHERE type = 'table' AND name = 'messages'
|
||||
`,
|
||||
)
|
||||
.get() !== undefined;
|
||||
db.exec(`
|
||||
.get()) !== undefined;
|
||||
await db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
message_hash INTEGER PRIMARY KEY,
|
||||
is_group INTEGER NOT NULL,
|
||||
@@ -323,22 +332,24 @@ export function prepareMessageStoreDatabase(dbPath: string): void {
|
||||
classification_version INTEGER NOT NULL DEFAULT 1
|
||||
)
|
||||
`);
|
||||
prepareMessageStoreSchema(db);
|
||||
await prepareMessageStoreSchema(db);
|
||||
|
||||
if (!messagesTableExists) {
|
||||
createMessageStoreIndexes(db);
|
||||
await createMessageStoreIndexes(db);
|
||||
}
|
||||
} finally {
|
||||
db.close();
|
||||
await db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrationStatus {
|
||||
export async function inspectMessageStoreMigration(
|
||||
dbPath: string,
|
||||
): Promise<MessageStoreMigrationStatus> {
|
||||
const db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
|
||||
|
||||
try {
|
||||
createMigrationStateTable(db);
|
||||
const row = db
|
||||
await createMigrationStateTable(db);
|
||||
const row = (await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT phase, processed, total
|
||||
@@ -346,13 +357,13 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
|
||||
WHERE name = ?
|
||||
`,
|
||||
)
|
||||
.get(MIGRATION_NAME) as MessageStoreMigrationStatus | undefined;
|
||||
.get(MIGRATION_NAME)) as MessageStoreMigrationStatus | undefined;
|
||||
|
||||
if (row) {
|
||||
return row;
|
||||
}
|
||||
|
||||
const pending = db
|
||||
const pending = (await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT COUNT(*) AS total
|
||||
@@ -360,62 +371,66 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
|
||||
WHERE classification_version < ?
|
||||
`,
|
||||
)
|
||||
.get(CLASSIFICATION_VERSION) as { total: number };
|
||||
.get(CLASSIFICATION_VERSION)) as { total: number };
|
||||
const total = Number(pending.total);
|
||||
return { phase: total === 0 ? 'complete' : 'migrating', processed: 0, total };
|
||||
} finally {
|
||||
db.close();
|
||||
await db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareMessageStoreSchema(db: DatabaseSync): void {
|
||||
const before = db.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }>;
|
||||
export async function prepareMessageStoreSchema(db: SqliteDatabase): Promise<void> {
|
||||
const before = (await db.prepare('PRAGMA table_info(messages)').all()) as Array<{
|
||||
name: string;
|
||||
}>;
|
||||
const existingColumns = new Set(before.map((column) => column.name));
|
||||
|
||||
if (!existingColumns.has('media_data')) {
|
||||
db.exec('ALTER TABLE messages ADD COLUMN media_data TEXT');
|
||||
await db.exec('ALTER TABLE messages ADD COLUMN media_data TEXT');
|
||||
}
|
||||
|
||||
const existingRowsAreCurrent =
|
||||
existingColumns.has('sequence_authoritative') &&
|
||||
existingColumns.has('private_direction') &&
|
||||
hasLegacyPrivateSequenceMigration(db);
|
||||
(await hasLegacyPrivateSequenceMigration(db));
|
||||
|
||||
if (!existingColumns.has('sequence_authoritative')) {
|
||||
db.exec(
|
||||
await db.exec(
|
||||
'ALTER TABLE messages ADD COLUMN sequence_authoritative INTEGER NOT NULL DEFAULT 1',
|
||||
);
|
||||
}
|
||||
|
||||
if (!existingColumns.has('private_direction')) {
|
||||
db.exec('ALTER TABLE messages ADD COLUMN private_direction INTEGER NOT NULL DEFAULT -1');
|
||||
await db.exec(
|
||||
'ALTER TABLE messages ADD COLUMN private_direction INTEGER NOT NULL DEFAULT -1',
|
||||
);
|
||||
}
|
||||
|
||||
if (!existingColumns.has('classification_version')) {
|
||||
db.exec(
|
||||
await db.exec(
|
||||
`ALTER TABLE messages ADD COLUMN classification_version INTEGER NOT NULL DEFAULT ${existingRowsAreCurrent ? CLASSIFICATION_VERSION : 0}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function createMessageStoreIndexes(db: DatabaseSync): void {
|
||||
db.exec(
|
||||
export async function createMessageStoreIndexes(db: SqliteDatabase): Promise<void> {
|
||||
await db.exec(
|
||||
'CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)',
|
||||
);
|
||||
db.exec(
|
||||
await db.exec(
|
||||
'CREATE INDEX IF NOT EXISTS idx_messages_session_authoritative_seq ON messages(is_group, session_id, sequence_authoritative, sequence)',
|
||||
);
|
||||
db.exec(
|
||||
await db.exec(
|
||||
'CREATE INDEX IF NOT EXISTS idx_messages_private_client_seq ON messages(is_group, session_id, client_sequence)',
|
||||
);
|
||||
db.exec(
|
||||
await db.exec(
|
||||
'CREATE INDEX IF NOT EXISTS idx_messages_private_client_direction ON messages(is_group, session_id, client_sequence, private_direction)',
|
||||
);
|
||||
}
|
||||
|
||||
function hasLegacyPrivateSequenceMigration(db: DatabaseSync): boolean {
|
||||
async function hasLegacyPrivateSequenceMigration(db: SqliteDatabase): Promise<boolean> {
|
||||
const tableExists =
|
||||
db
|
||||
(await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT 1 AS present
|
||||
@@ -423,14 +438,14 @@ function hasLegacyPrivateSequenceMigration(db: DatabaseSync): boolean {
|
||||
WHERE type = 'table' AND name = 'message_store_migrations'
|
||||
`,
|
||||
)
|
||||
.get() !== undefined;
|
||||
.get()) !== undefined;
|
||||
|
||||
if (!tableExists) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
db
|
||||
(await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT 1 AS applied
|
||||
@@ -438,12 +453,12 @@ function hasLegacyPrivateSequenceMigration(db: DatabaseSync): boolean {
|
||||
WHERE name = ?
|
||||
`,
|
||||
)
|
||||
.get(LEGACY_PRIVATE_SEQUENCE_MIGRATION) !== undefined
|
||||
.get(LEGACY_PRIVATE_SEQUENCE_MIGRATION)) !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
function createMigrationStateTable(db: DatabaseSync): void {
|
||||
db.exec(`
|
||||
async function createMigrationStateTable(db: SqliteDatabase): Promise<void> {
|
||||
await db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS message_store_migration_state (
|
||||
name TEXT PRIMARY KEY,
|
||||
phase TEXT NOT NULL,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,19 +1,137 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { ImageUrlResolver } from '../event-converter';
|
||||
import type { MediaStore } from '../media-store';
|
||||
import type { CachedImage, MediaStore } from '../media-store';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import { resolveRemoteMediaUrl } from '../media-url-resolver';
|
||||
import { segmentsToRawMessage } from '../helper/cq';
|
||||
import {
|
||||
deliverPttTransText,
|
||||
failPttTransWaiter,
|
||||
pttTransKey,
|
||||
waitPttTransText,
|
||||
} from './ptt-trans-waiter';
|
||||
import type { JsonObject } from '../types';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
type StoredMediaSegment = JsonObject & { type: 'image' | 'record' | 'video'; data: JsonObject };
|
||||
|
||||
function isStoredMediaSegment(segment: JsonValue): segment is StoredMediaSegment {
|
||||
return (
|
||||
segment !== null &&
|
||||
typeof segment === 'object' &&
|
||||
!Array.isArray(segment) &&
|
||||
(segment.type === 'image' || segment.type === 'record' || segment.type === 'video') &&
|
||||
segment.data !== null &&
|
||||
typeof segment.data === 'object' &&
|
||||
!Array.isArray(segment.data)
|
||||
);
|
||||
}
|
||||
|
||||
export async function refreshMessageMedia(
|
||||
ref: Pick<OneBotInstanceContext, 'bridge' | 'messageStore' | 'mediaStore' | 'converterCtx'>,
|
||||
messageId: number,
|
||||
event: JsonObject,
|
||||
): Promise<void> {
|
||||
if (!Array.isArray(event.message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const segments = event.message.filter(isStoredMediaSegment);
|
||||
const voiceVideoSegments = segments.filter((segment) => segment.type !== 'image');
|
||||
const media =
|
||||
voiceVideoSegments.length > 0
|
||||
? (await ref.messageStore.findMedia(messageId))?.filter(
|
||||
(element) => element.type !== 'image',
|
||||
)
|
||||
: null;
|
||||
const meta = voiceVideoSegments.length > 0 ? await ref.messageStore.findMeta(messageId) : null;
|
||||
// Validate the ordered association once; a filename lookup can select another upload.
|
||||
const voiceVideo =
|
||||
meta &&
|
||||
media &&
|
||||
media.length === voiceVideoSegments.length &&
|
||||
media.every((element, index) => element.type === voiceVideoSegments[index]!.type)
|
||||
? { media, meta }
|
||||
: null;
|
||||
|
||||
if (voiceVideoSegments.length > 0 && !voiceVideo) {
|
||||
log.warn('[get_msg] media metadata missing or inconsistent message_id=%d', messageId);
|
||||
}
|
||||
|
||||
let voiceVideoIndex = 0;
|
||||
let changed = false;
|
||||
|
||||
for (const [index, segment] of segments.entries()) {
|
||||
try {
|
||||
let url: string | null;
|
||||
|
||||
if (segment.type === 'image') {
|
||||
const file =
|
||||
typeof segment.data.file === 'string'
|
||||
? segment.data.file
|
||||
: segment.data.file_id;
|
||||
|
||||
if (typeof file !== 'string' || !file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
url = await resolveImageUrl(
|
||||
await ref.mediaStore.findImage(file),
|
||||
ref.converterCtx.imageUrlResolver,
|
||||
);
|
||||
} else {
|
||||
if (!voiceVideo) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const element = voiceVideo.media[voiceVideoIndex++]!;
|
||||
url = await resolveRemoteMediaUrl(
|
||||
ref.bridge,
|
||||
element.type,
|
||||
element.mediaNode,
|
||||
voiceVideo.meta.isGroup,
|
||||
voiceVideo.meta.targetId,
|
||||
);
|
||||
}
|
||||
|
||||
if (url && url !== segment.data.url) {
|
||||
segment.data.url = url;
|
||||
changed = true;
|
||||
}
|
||||
} catch (err) {
|
||||
// Refresh failure preserves this message's URL, never a different cached URL.
|
||||
log.warn(
|
||||
'[get_msg] media URL refresh failed message_id=%d type=%s media_index=%d: %s',
|
||||
messageId,
|
||||
segment.type,
|
||||
index,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
event.raw_message = segmentsToRawMessage(event.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveImageUrl(
|
||||
cached: CachedImage | null,
|
||||
resolver?: ImageUrlResolver | null,
|
||||
): Promise<string | null> {
|
||||
if (!cached?.imageUrl || !resolver) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return resolver(
|
||||
{ type: 'image', imageUrl: cached.imageUrl, subType: cached.subType },
|
||||
cached.isGroup,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Voice-to-text for a received ptt (issue #79 / NapCat `fetch_ptt_text`).
|
||||
* Resolves the message's `record` segment to its cached fingerprint
|
||||
@@ -27,7 +145,7 @@ export async function fetchPttText(
|
||||
selfId: number,
|
||||
messageId: number,
|
||||
): Promise<{ text: string }> {
|
||||
const event = messageStore.findEvent(messageId);
|
||||
const event = await messageStore.findEvent(messageId);
|
||||
|
||||
if (!event) {
|
||||
throw new Error('消息不存在或已被撤回');
|
||||
@@ -59,16 +177,16 @@ export async function fetchPttText(
|
||||
throw new Error('消息中不包含语音');
|
||||
}
|
||||
|
||||
const snapshot = messageStore
|
||||
.findMedia(messageId)
|
||||
?.find((element) => element.type === 'record');
|
||||
const snapshot = (await messageStore.findMedia(messageId))?.find(
|
||||
(element) => element.type === 'record',
|
||||
);
|
||||
const cached = snapshot
|
||||
? {
|
||||
...snapshot,
|
||||
isGroup: event.message_type === 'group',
|
||||
sessionId: Number(event.group_id) || selfId,
|
||||
}
|
||||
: mediaStore.findRecord(file, 'legacy');
|
||||
: await mediaStore.findRecord(file, 'legacy');
|
||||
|
||||
if (!cached) {
|
||||
throw new Error('语音不在缓存中,无法转写');
|
||||
@@ -114,7 +232,7 @@ export async function getImageInfo(
|
||||
file: string,
|
||||
imageUrlResolver?: ImageUrlResolver | null,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findImage(file);
|
||||
const cached = await mediaStore.findImage(file);
|
||||
|
||||
if (!cached) {
|
||||
return null;
|
||||
@@ -122,27 +240,17 @@ export async function getImageInfo(
|
||||
|
||||
let url = cached.url || cached.imageUrl || '';
|
||||
|
||||
// Re-sign with a current rkey at lookup time. The stored `url` was signed
|
||||
// when the message first arrived and its rkey may have since expired — the
|
||||
// CDN then rejects the download with
|
||||
// `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw
|
||||
// (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which
|
||||
// re-signs on every getImageUrl call instead of handing back a baked URL.
|
||||
if (imageUrlResolver && cached.imageUrl) {
|
||||
try {
|
||||
const element: MessageElement = {
|
||||
type: 'image',
|
||||
imageUrl: cached.imageUrl,
|
||||
subType: cached.subType,
|
||||
};
|
||||
const fresh = await imageUrlResolver(element, cached.isGroup);
|
||||
try {
|
||||
const fresh = await resolveImageUrl(cached, imageUrlResolver);
|
||||
|
||||
if (fresh) {
|
||||
url = fresh;
|
||||
}
|
||||
} catch {
|
||||
// Best-effort: fall back to the stored URL on any resolver failure.
|
||||
if (fresh) {
|
||||
url = fresh;
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'get_image URL refresh failed: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -158,34 +266,23 @@ export async function getRecordInfo(
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findRecord(file);
|
||||
const cached = await mediaStore.findRecord(file);
|
||||
|
||||
if (!cached) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let url = cached.url;
|
||||
|
||||
if (!url && cached.mediaNode) {
|
||||
try {
|
||||
url = cached.isGroup
|
||||
? await bridge.apis.groupFile.getPttUrl(cached.sessionId, cached.mediaNode)
|
||||
: await bridge.apis.groupFile.getPrivatePttUrl(cached.mediaNode);
|
||||
|
||||
if (url) {
|
||||
mediaStore.updateRecordUrl(file, url);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'get_record url refetch failed: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const url = await resolveRemoteMediaUrl(
|
||||
bridge,
|
||||
'record',
|
||||
cached.mediaNode,
|
||||
cached.isGroup,
|
||||
cached.sessionId,
|
||||
);
|
||||
await mediaStore.updateRecordUrl(file, url);
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url: url || '',
|
||||
file: url,
|
||||
url,
|
||||
file_size: String(cached.fileSize ?? 0),
|
||||
file_name: cached.fileName || cached.file,
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { isMessageMedia, type MessageMedia } from '../message-media';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
} from '../message-parser';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import { sameSelfSentMessage } from '../self-sent-event';
|
||||
import { replyPreviewElements } from '../reply-preview';
|
||||
import {
|
||||
hasAuthoritativeSequence,
|
||||
type JsonArray,
|
||||
@@ -36,49 +38,6 @@ import {
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
function replyPreviewElements(message: unknown): MessageElement[] {
|
||||
if (!Array.isArray(message)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
image: '[图片]',
|
||||
record: '[语音]',
|
||||
video: '[视频]',
|
||||
file: '[文件]',
|
||||
face: '[表情]',
|
||||
mface: '[表情]',
|
||||
forward: '[聊天记录]',
|
||||
json: '[卡片]',
|
||||
xml: '[卡片]',
|
||||
markdown: '[Markdown]',
|
||||
};
|
||||
const parts: string[] = [];
|
||||
|
||||
for (const segment of message) {
|
||||
if (!segment || typeof segment !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = segment.data;
|
||||
|
||||
if (!data || typeof data !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segment.type === 'text' && typeof data.text === 'string') {
|
||||
parts.push(data.text);
|
||||
} else if (segment.type === 'at') {
|
||||
parts.push(data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`);
|
||||
} else if (typeof segment.type === 'string' && labels[segment.type]) {
|
||||
parts.push(labels[segment.type]);
|
||||
}
|
||||
}
|
||||
|
||||
const text = parts.join('');
|
||||
return text ? [{ type: 'text', text }] : [];
|
||||
}
|
||||
|
||||
// A video larger than QQ's Highway video ceiling can't be sent through the
|
||||
// element pipeline — it must fall back to a regular file upload. The fallback
|
||||
// is decided at the OneBot layer (not element-builder) because building a
|
||||
@@ -167,7 +126,7 @@ export async function getGroupMsgHistory(
|
||||
let anchorSequence: number | undefined;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = messageStore.findMeta(messageId as number);
|
||||
const meta = await messageStore.findMeta(messageId as number);
|
||||
|
||||
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) {
|
||||
return [];
|
||||
@@ -176,7 +135,7 @@ export async function getGroupMsgHistory(
|
||||
anchorSequence = meta.sequence;
|
||||
}
|
||||
|
||||
const events = messageStore.listSessionEvents(
|
||||
const events = await messageStore.listSessionEvents(
|
||||
true,
|
||||
groupId,
|
||||
limit,
|
||||
@@ -212,7 +171,7 @@ export async function getFriendMsgHistory(
|
||||
let anchorSequence: number | undefined;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = messageStore.findMeta(messageId as number);
|
||||
const meta = await messageStore.findMeta(messageId as number);
|
||||
|
||||
if (!hasAuthoritativeSequence(meta) || meta.isGroup || meta.targetId !== userId) {
|
||||
return [];
|
||||
@@ -221,7 +180,7 @@ export async function getFriendMsgHistory(
|
||||
anchorSequence = meta.sequence;
|
||||
}
|
||||
|
||||
const events = messageStore.listSessionEvents(
|
||||
const events = await messageStore.listSessionEvents(
|
||||
false,
|
||||
userId,
|
||||
limit,
|
||||
@@ -272,7 +231,7 @@ export async function getGroupHistory(
|
||||
let anchorSeq = 0;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = ref.messageStore.findMeta(messageId as number);
|
||||
const meta = await ref.messageStore.findMeta(messageId as number);
|
||||
|
||||
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) {
|
||||
// Anchor we don't know — best effort from the local store.
|
||||
@@ -281,7 +240,7 @@ export async function getGroupHistory(
|
||||
|
||||
anchorSeq = meta.sequence;
|
||||
} else {
|
||||
anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(true, groupId) ?? 0;
|
||||
anchorSeq = (await ref.messageStore.findLatestAuthoritativeSequence(true, groupId)) ?? 0;
|
||||
}
|
||||
|
||||
log.debug(
|
||||
@@ -309,7 +268,7 @@ export async function getGroupHistory(
|
||||
continue;
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
|
||||
await persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
|
||||
out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path)
|
||||
}
|
||||
|
||||
@@ -365,13 +324,15 @@ export async function getFriendHistory(
|
||||
let anchorSeq = 0;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = ref.messageStore.findMeta(messageId as number);
|
||||
const meta = await ref.messageStore.findMeta(messageId as number);
|
||||
// Older self-sent rows may be keyed by selfId. Only accept one of those
|
||||
// when its stored target_id proves that it belongs to this peer; otherwise
|
||||
// a message_id from another private conversation could select the wrong
|
||||
// server sequence.
|
||||
const storedEvent =
|
||||
meta?.targetId === ref.selfId ? ref.messageStore.findEvent(messageId as number) : null;
|
||||
meta?.targetId === ref.selfId
|
||||
? await ref.messageStore.findEvent(messageId as number)
|
||||
: null;
|
||||
const belongsToPeer =
|
||||
meta?.targetId === userId ||
|
||||
(meta?.targetId === ref.selfId && toHistoryInt(storedEvent?.target_id) === userId);
|
||||
@@ -422,11 +383,15 @@ export async function getFriendHistory(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Conversion can await media resolution, so consult the tombstone only
|
||||
// after it settles. From this check through persistence/return there is no
|
||||
// async gap in which a recall could race past us.
|
||||
// Conversion can await media resolution, so check again after it settles.
|
||||
// Persistence also checks recalls queued while this lookup is in flight.
|
||||
if (
|
||||
ref.messageStore.isPrivateMessageRecalled(userId, clientSequence, sentBySelf, ev.time)
|
||||
await ref.messageStore.isPrivateMessageRecalled(
|
||||
userId,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
ev.time,
|
||||
)
|
||||
) {
|
||||
log.debug(
|
||||
'friend history omitted recalled message: user=%d clientSeq=%d self=%s',
|
||||
@@ -443,8 +408,9 @@ export async function getFriendHistory(
|
||||
json.target_id = userId;
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, json, userId, ev);
|
||||
out.push(sanitizeMessageEventForApi(json));
|
||||
if (await persistHistoryEvent(ref.messageStore, json, userId, ev)) {
|
||||
out.push(sanitizeMessageEventForApi(json));
|
||||
}
|
||||
}
|
||||
|
||||
log.debug(
|
||||
@@ -505,7 +471,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
const eventName = isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: privateMessageEventName(quotedSender === ref.selfId, false);
|
||||
const resolvedId = ref.converterCtx.messageIdResolver?.(
|
||||
const resolvedId = await ref.converterCtx.messageIdResolver?.(
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
@@ -517,7 +483,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
? (resolvedId as number)
|
||||
: hashMessageIdInt32(replySeq, session, eventName);
|
||||
|
||||
if (ref.messageStore.findEvent(targetId)) {
|
||||
if (await ref.messageStore.findEvent(targetId)) {
|
||||
return;
|
||||
} // Tier 0: already have the full event
|
||||
|
||||
@@ -568,12 +534,19 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
json.message_id = targetId;
|
||||
|
||||
if (fetched.kind === 'group_message') {
|
||||
ref.messageStore.storeEvent(targetId, true, session, replySeq, eventName, json);
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
true,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
json,
|
||||
);
|
||||
} else {
|
||||
const serverSequence = fetched.ntMsgSeq ?? 0;
|
||||
const sequenceAuthoritative =
|
||||
fetched.sequenceAuthoritative !== false && serverSequence > 0;
|
||||
ref.messageStore.storeMeta(targetId, {
|
||||
await ref.messageStore.storeMeta(targetId, {
|
||||
isGroup: false,
|
||||
targetId: session,
|
||||
sequence: serverSequence,
|
||||
@@ -585,16 +558,14 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
random: fetched.msgId,
|
||||
timestamp: fetched.time,
|
||||
});
|
||||
ref.messageStore.storeEvent(
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
false,
|
||||
session,
|
||||
serverSequence,
|
||||
eventName,
|
||||
json,
|
||||
{
|
||||
sequenceAuthoritative,
|
||||
},
|
||||
{ sequenceAuthoritative },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -632,9 +603,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
// Inline quote metadata proves what was displayed, but not that replySeq
|
||||
// still names a server-backed roam message. Keep it queryable via
|
||||
// get_msg without letting it become a history/recall/reply anchor.
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, fallback, {
|
||||
sequenceAuthoritative: false,
|
||||
});
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
fallback,
|
||||
{ sequenceAuthoritative: false },
|
||||
);
|
||||
return;
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
@@ -657,9 +634,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
isGroup,
|
||||
session,
|
||||
);
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, placeholder, {
|
||||
sequenceAuthoritative: false,
|
||||
});
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
placeholder,
|
||||
{ sequenceAuthoritative: false },
|
||||
);
|
||||
}
|
||||
|
||||
// Build a stored-message event for a backfilled reply target (Tier 2/3).
|
||||
@@ -743,7 +726,7 @@ export async function setEssenceMessage(
|
||||
messageId: number,
|
||||
enable: boolean,
|
||||
): Promise<void> {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
const meta = await messageStore.findMeta(messageId);
|
||||
|
||||
if (!meta || !meta.isGroup) {
|
||||
throw new Error('message not found or not a group message');
|
||||
@@ -757,30 +740,9 @@ export async function setEssenceMessage(
|
||||
}
|
||||
|
||||
/**
|
||||
* Build + store a synthetic OneBot event for a just-sent message so
|
||||
* `/get_msg` can find it.
|
||||
*
|
||||
* The QQ server doesn't always echo self-sent messages back on the
|
||||
* receive channel — Lagrange and NapCat both work around this by
|
||||
* writing a local copy at send time (Lagrange persists into Realm DB
|
||||
* inside `SendMessageOperation`; NapCat caches in-memory via its msg
|
||||
* service). Without it, callers that hit `/get_msg` with a freshly-
|
||||
* returned `message_id` get "message not found" even though the recall
|
||||
* path works fine (recall uses the lighter `cacheMessageMeta` already).
|
||||
*
|
||||
* Stored event has `post_type: 'message_sent'` so OneBot clients that
|
||||
* inspect it through `/get_msg` can distinguish their own outbound
|
||||
* messages from incoming ones.
|
||||
*/
|
||||
/**
|
||||
* The shared "record a self-sent message" tail: derive the OneBot message id
|
||||
* from (sequence, target, event), then cache both the meta and the self-sent
|
||||
* copy. Centralizes the `isGroup ↔ eventName ↔ hashMessageIdInt32 event
|
||||
* constant` coupling that was hand-paired in six send/forward paths — a
|
||||
* mismatch there silently produced a wrong message_id or wrong event
|
||||
* attribution. Returns the derived message id and, for an eligible plain C2C
|
||||
* Action send, an event for the OneBot dispatch path when QQ has not already
|
||||
* supplied the canonical echo.
|
||||
* Derive the same message id for send/receive paths and persist the sent
|
||||
* message for get_msg, since QQ does not always echo it. Eligible C2C sends
|
||||
* also return a message_sent event when no canonical echo has arrived.
|
||||
*/
|
||||
async function finalizeSend(
|
||||
ref: OneBotInstanceContext,
|
||||
@@ -810,7 +772,7 @@ async function finalizeSend(
|
||||
: Number.isInteger(opaqueMessageId) && opaqueMessageId !== 0
|
||||
? opaqueMessageId
|
||||
: hashMessageIdInt32(isGroup ? 0 : receipt.clientSequence, targetId, eventName);
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
await ref.cacheMessageMeta(messageId, {
|
||||
isGroup,
|
||||
targetId,
|
||||
sequence: receipt.sequence,
|
||||
@@ -865,35 +827,16 @@ async function cacheSelfSentMessage(
|
||||
elements,
|
||||
} = options;
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Defensive: tests may mock `ref.messageStore` without the full MessageStore
|
||||
// surface. Production always has it. Without storage, recall still works via
|
||||
// cacheMessageMeta, but `/get_msg` and the synthetic event are unavailable.
|
||||
const storeEvent = (ref.messageStore as { storeEvent?: typeof ref.messageStore.storeEvent })
|
||||
.storeEvent;
|
||||
|
||||
if (typeof storeEvent !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
// We deliberately pass no URL resolvers — for a synthetic self-sent
|
||||
// event the file/url fields in segments are best-effort (they're
|
||||
// already what the OneBot caller passed in). Image/video URLs would
|
||||
// need a real resolver to render in `/get_msg`, but the existing
|
||||
// resolver is async and bound to the receive pipeline; skipping it
|
||||
// means /get_msg returns the segment with the original `file` path
|
||||
// and an empty `url`, which is what Lagrange does too.
|
||||
// Persist upload metadata without another QQ request on the send path.
|
||||
// get_msg / get_record resolve remote media URLs when the consumer reads.
|
||||
const segments = (await elementsToOneBotSegments(
|
||||
{
|
||||
selfId: ref.selfId,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
mediaSegmentSink: ref.converterCtx.mediaSegmentSink,
|
||||
},
|
||||
elements,
|
||||
isGroup,
|
||||
@@ -939,7 +882,7 @@ async function cacheSelfSentMessage(
|
||||
// QQ can win the race between the send receipt and local event
|
||||
// construction. Keep its richer canonical event and let the already-run
|
||||
// bridge dispatch remain the single downstream notification.
|
||||
const existing = ref.messageStore.findEvent(messageId);
|
||||
const existing = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (existing && sameSelfSentMessage(existing, event)) {
|
||||
return null;
|
||||
@@ -947,17 +890,14 @@ async function cacheSelfSentMessage(
|
||||
|
||||
// Persist before dispatch so `/get_msg` is immediately consistent for a
|
||||
// client reacting to the synthetic message_sent notification.
|
||||
storeEvent.call(
|
||||
ref.messageStore,
|
||||
await ref.messageStore.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
{
|
||||
sequenceAuthoritative,
|
||||
},
|
||||
{ sequenceAuthoritative },
|
||||
);
|
||||
return event;
|
||||
} catch (err) {
|
||||
@@ -999,7 +939,7 @@ export async function sendPrivateMessage(
|
||||
/** When set, reply into this group's temp session instead of friend c2c. */
|
||||
tempGroupId?: number,
|
||||
/** Reports each actual friend message as soon as its authoritative receipt arrives. */
|
||||
onSelfSent?: (event: JsonObject) => void,
|
||||
onSelfSent?: (event: JsonObject) => void | Promise<void>,
|
||||
): Promise<MessageSendResult> {
|
||||
// A temp-session reply is only allowed into a session the peer opened.
|
||||
const isTempReply = tempGroupId !== undefined && ref.tempSessions.has(userId, tempGroupId);
|
||||
@@ -1030,10 +970,10 @@ export async function sendPrivateMessage(
|
||||
}
|
||||
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
resolveReplySequence: async (replyMessageId) => {
|
||||
return await ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
resolveReplyMeta: async (replyMessageId) => {
|
||||
// Prefer the cached event (it carries the REAL sender). When only
|
||||
// meta exists — typically because the message we're replying to was
|
||||
// sent by the bot itself and never round-tripped through dispatch
|
||||
@@ -1041,7 +981,7 @@ export async function sendPrivateMessage(
|
||||
// selfId. The previous code used `meta.targetId` here, which is the
|
||||
// conversation PEER and shows the wrong "回复 @某人" in QQ for any
|
||||
// self-reply.
|
||||
const event = ref.messageStore.findEvent(replyMessageId);
|
||||
const event = await ref.messageStore.findEvent(replyMessageId);
|
||||
|
||||
if (event) {
|
||||
const senderUin =
|
||||
@@ -1052,7 +992,7 @@ export async function sendPrivateMessage(
|
||||
typeof event.time === 'number'
|
||||
? event.time
|
||||
: parseInt(String(event.time || '0'), 10);
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
const meta = await ref.messageStore.findMeta(replyMessageId);
|
||||
return {
|
||||
senderUin,
|
||||
time,
|
||||
@@ -1062,7 +1002,7 @@ export async function sendPrivateMessage(
|
||||
};
|
||||
}
|
||||
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
const meta = await ref.messageStore.findMeta(replyMessageId);
|
||||
|
||||
if (meta) {
|
||||
return {
|
||||
@@ -1209,7 +1149,7 @@ export async function sendPrivateMessage(
|
||||
lastResult = result;
|
||||
|
||||
if (result.echoEvent) {
|
||||
onSelfSent?.(result.echoEvent);
|
||||
await onSelfSent?.(result.echoEvent);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1346,17 +1286,17 @@ export async function sendGroupMessage(
|
||||
}
|
||||
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
resolveReplySequence: async (replyMessageId) => {
|
||||
return await ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
resolveReplyMeta: async (replyMessageId) => {
|
||||
const meta = await ref.messageStore.findMeta(replyMessageId);
|
||||
|
||||
if (!meta || !meta.isGroup || meta.targetId !== groupId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const event = ref.messageStore.findEvent(replyMessageId);
|
||||
const event = await ref.messageStore.findEvent(replyMessageId);
|
||||
|
||||
if (event) {
|
||||
return {
|
||||
@@ -1527,7 +1467,7 @@ export async function sendPrivateForwardMessage(
|
||||
userId: number,
|
||||
messages: JsonValue,
|
||||
meta?: ForwardPreviewMeta,
|
||||
onSelfSent?: (event: JsonObject) => void,
|
||||
onSelfSent?: (event: JsonObject) => void | Promise<void>,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages, { userId });
|
||||
// userId is plumbed through so inner image/record/video can be uploaded
|
||||
@@ -1546,7 +1486,7 @@ export async function sendPrivateForwardMessage(
|
||||
);
|
||||
|
||||
if (result.echoEvent) {
|
||||
onSelfSent?.(result.echoEvent);
|
||||
await onSelfSent?.(result.echoEvent);
|
||||
}
|
||||
|
||||
return { messageId: result.messageId, forwardId };
|
||||
@@ -1577,13 +1517,13 @@ export async function forwardSingleMessage(
|
||||
ref: OneBotInstanceContext,
|
||||
messageId: number,
|
||||
target: { groupId?: number; userId?: number },
|
||||
onSelfSent?: (event: JsonObject) => void,
|
||||
onSelfSent?: (event: JsonObject) => void | Promise<void>,
|
||||
): Promise<{ messageId: number }> {
|
||||
if (!target.groupId && !target.userId) {
|
||||
throw new Error('forward target group_id or user_id is required');
|
||||
}
|
||||
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (!event) {
|
||||
throw new Error(`message not found: ${messageId}`);
|
||||
@@ -1599,7 +1539,7 @@ export async function forwardSingleMessage(
|
||||
|
||||
const elements = await prepareSingleForwardElements(
|
||||
ref,
|
||||
restoreHistoricalMedia(ref, parsed, messageId),
|
||||
await restoreHistoricalMedia(ref, parsed, messageId),
|
||||
target,
|
||||
);
|
||||
|
||||
@@ -1628,7 +1568,7 @@ export async function forwardSingleMessage(
|
||||
messageIdOut = result.messageId;
|
||||
|
||||
if (result.echoEvent) {
|
||||
onSelfSent?.(result.echoEvent);
|
||||
await onSelfSent?.(result.echoEvent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1644,7 +1584,7 @@ async function prepareSingleForwardElements(
|
||||
|
||||
for (const element of elements) {
|
||||
if (element.type !== 'forward') {
|
||||
out.push(isMessageMedia(element) ? element : enrichForForward(ref, element));
|
||||
out.push(isMessageMedia(element) ? element : await enrichForForward(ref, element));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1710,15 +1650,30 @@ async function expandForwardNodeForTarget(
|
||||
target: { groupId?: number; userId?: number },
|
||||
depth: number,
|
||||
): Promise<ForwardNodePayload> {
|
||||
const forwards = node.elements.filter(
|
||||
// Fetched nodes already carry protocol media metadata, but their URLs may
|
||||
// lack an rkey (or only be a file UUID). Reuse complete fingerprints in the
|
||||
// target's upload scene, just as historical single-message forwarding does.
|
||||
// Legacy/incomplete images still need the existing byte-source upload path.
|
||||
const preparedElements = await mapWithConcurrency(node.elements, 8, async (element) => {
|
||||
if (!isMessageMedia(element) || !element.md5Hex || !element.sha1Hex) {
|
||||
return element;
|
||||
}
|
||||
|
||||
if (element.type === 'image' && (!element.width || !element.height || !element.picFormat)) {
|
||||
return element;
|
||||
}
|
||||
|
||||
return await enrichForForward(ref, element, element);
|
||||
});
|
||||
const forwards = preparedElements.filter(
|
||||
(element): element is MessageElementOf<'forward'> => element.type === 'forward',
|
||||
);
|
||||
|
||||
if (forwards.length === 0) {
|
||||
return node;
|
||||
return { ...node, elements: preparedElements };
|
||||
}
|
||||
|
||||
if (forwards.length === node.elements.length && forwards.length === 1) {
|
||||
if (forwards.length === preparedElements.length && forwards.length === 1) {
|
||||
const innerId = forwards[0]!.resId.trim();
|
||||
|
||||
if (!innerId) {
|
||||
@@ -1734,7 +1689,7 @@ async function expandForwardNodeForTarget(
|
||||
|
||||
const elements: MessageElement[] = [];
|
||||
|
||||
for (const element of node.elements) {
|
||||
for (const element of preparedElements) {
|
||||
if (element.type !== 'forward') {
|
||||
elements.push(element);
|
||||
continue;
|
||||
@@ -1761,18 +1716,18 @@ async function expandForwardNodeForTarget(
|
||||
return { ...node, elements };
|
||||
}
|
||||
|
||||
function restoreHistoricalMedia(
|
||||
async function restoreHistoricalMedia(
|
||||
ref: OneBotInstanceContext,
|
||||
elements: MessageElement[],
|
||||
messageId: number,
|
||||
): MessageElement[] {
|
||||
): Promise<MessageElement[]> {
|
||||
if (!elements.some(isMessageMedia)) {
|
||||
return elements;
|
||||
}
|
||||
|
||||
const snapshots = ref.messageStore.findMedia(messageId);
|
||||
const snapshots = await ref.messageStore.findMedia(messageId);
|
||||
let index = 0;
|
||||
const restored = elements.map((element) => {
|
||||
const restored = await mapWithConcurrency(elements, 8, async (element) => {
|
||||
if (!isMessageMedia(element)) {
|
||||
return element;
|
||||
}
|
||||
@@ -1783,7 +1738,7 @@ function restoreHistoricalMedia(
|
||||
throw new Error(`historical media metadata does not match message ${messageId}`);
|
||||
}
|
||||
|
||||
return enrichForForward(ref, element, snapshot);
|
||||
return await enrichForForward(ref, element, snapshot);
|
||||
});
|
||||
|
||||
if (snapshots && index !== snapshots.length) {
|
||||
@@ -1793,11 +1748,11 @@ function restoreHistoricalMedia(
|
||||
return restored;
|
||||
}
|
||||
|
||||
function enrichForForward(
|
||||
async function enrichForForward(
|
||||
ref: OneBotInstanceContext,
|
||||
element: MessageElement,
|
||||
snapshot?: MessageMedia,
|
||||
): MessageElement {
|
||||
): Promise<MessageElement> {
|
||||
if (element.type === 'forward') {
|
||||
throw new Error('merged forward must be regenerated for the target chat');
|
||||
}
|
||||
@@ -1833,7 +1788,9 @@ function enrichForForward(
|
||||
|
||||
if (element.type === 'image') {
|
||||
const cached =
|
||||
snapshot?.type === 'image' ? snapshot : ref.mediaStore.findImage(lookupKey, 'legacy');
|
||||
snapshot?.type === 'image'
|
||||
? snapshot
|
||||
: await ref.mediaStore.findImage(lookupKey, 'legacy');
|
||||
|
||||
if (
|
||||
!cached ||
|
||||
@@ -1866,7 +1823,9 @@ function enrichForForward(
|
||||
|
||||
if (element.type === 'record') {
|
||||
const cached =
|
||||
snapshot?.type === 'record' ? snapshot : ref.mediaStore.findRecord(lookupKey, 'legacy');
|
||||
snapshot?.type === 'record'
|
||||
? snapshot
|
||||
: await ref.mediaStore.findRecord(lookupKey, 'legacy');
|
||||
|
||||
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
|
||||
throw new Error(
|
||||
@@ -1890,7 +1849,9 @@ function enrichForForward(
|
||||
|
||||
if (element.type === 'video') {
|
||||
const cached =
|
||||
snapshot?.type === 'video' ? snapshot : ref.mediaStore.findVideo(lookupKey, 'legacy');
|
||||
snapshot?.type === 'video'
|
||||
? snapshot
|
||||
: await ref.mediaStore.findVideo(lookupKey, 'legacy');
|
||||
|
||||
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
|
||||
throw new Error(
|
||||
@@ -1939,6 +1900,7 @@ export async function getForwardMessage(
|
||||
node.elements,
|
||||
isGroup,
|
||||
sessionId,
|
||||
{ includeReplyContent: true },
|
||||
);
|
||||
|
||||
const sender: JsonObject = {
|
||||
@@ -1966,7 +1928,7 @@ export async function getForwardMessage(
|
||||
raw_message: '',
|
||||
font: 14,
|
||||
sub_type: isGroup ? 'normal' : 'friend',
|
||||
message: segments as unknown as JsonValue,
|
||||
message: segments,
|
||||
message_format: 'array',
|
||||
post_type: 'message',
|
||||
};
|
||||
@@ -2111,7 +2073,7 @@ function isNestedNodeArray(value: JsonValue): boolean {
|
||||
for (const item of value) {
|
||||
const seg = asJsonObject(item);
|
||||
|
||||
if (!seg || String(seg.type ?? '') !== 'node') {
|
||||
if (!seg || seg.type !== 'node') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2119,7 +2081,13 @@ function isNestedNodeArray(value: JsonValue): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
function assertForwardNodeMetadata(nodeData: JsonObject, index: number): void {
|
||||
type ForwardNodeData = JsonObject &
|
||||
Pick<ForwardNodePayload, 'news' | 'title' | 'source' | 'summary' | 'prompt'>;
|
||||
|
||||
function assertForwardNodeMetadata(
|
||||
nodeData: JsonObject,
|
||||
index: number,
|
||||
): asserts nodeData is ForwardNodeData {
|
||||
for (const [field, value] of Object.entries(nodeData)) {
|
||||
if (field === 'content' || field === 'message') {
|
||||
continue;
|
||||
@@ -2190,11 +2158,11 @@ function isForwardNewsArray(value: JsonValue): value is Array<{ text: string }>
|
||||
return true;
|
||||
}
|
||||
|
||||
function assertForwardMessageInputPolicies(
|
||||
async function assertForwardMessageInputPolicies(
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
depth = 0,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
if (!Array.isArray(messages) || depth >= MAX_FORWARD_DEPTH) {
|
||||
return;
|
||||
}
|
||||
@@ -2217,11 +2185,11 @@ function assertForwardMessageInputPolicies(
|
||||
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
|
||||
|
||||
if (messageId !== 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (event) {
|
||||
assertOutboundMessageInput(
|
||||
(event.message ?? event.raw_message ?? '') as JsonValue,
|
||||
event.message ?? event.raw_message ?? '',
|
||||
false,
|
||||
'forward',
|
||||
);
|
||||
@@ -2230,10 +2198,10 @@ function assertForwardMessageInputPolicies(
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
const content = nodeData.content ?? nodeData.message ?? '';
|
||||
|
||||
if (isNestedNodeArray(content)) {
|
||||
assertForwardMessageInputPolicies(ref, content, depth + 1);
|
||||
await assertForwardMessageInputPolicies(ref, content, depth + 1);
|
||||
} else {
|
||||
assertOutboundMessageInput(content, false, 'forward');
|
||||
}
|
||||
@@ -2323,7 +2291,7 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
assertForwardNodeMetadata(nodeData, index);
|
||||
return { segment, nodeData };
|
||||
return nodeData;
|
||||
}
|
||||
|
||||
// Preserve the existing bare-node compatibility form, but require it to
|
||||
@@ -2338,22 +2306,22 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
assertForwardNodeMetadata(segment, index);
|
||||
return { segment, nodeData: segment };
|
||||
return segment;
|
||||
});
|
||||
|
||||
// Scan the complete raw tree before parsing any earlier node. Some segment
|
||||
// codecs perform identity lookups or HTTP signing, so discovering an
|
||||
// unsupported message combination during the normal loop would already be
|
||||
// too late.
|
||||
assertForwardMessageInputPolicies(ref, messages, depth);
|
||||
await assertForwardMessageInputPolicies(ref, messages, depth);
|
||||
|
||||
const nodes: ForwardNodePayload[] = [];
|
||||
|
||||
for (const { nodeData } of prepared) {
|
||||
for (const nodeData of prepared) {
|
||||
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
|
||||
|
||||
if (messageId !== 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (!event) {
|
||||
throw new MessageElementValidationError(
|
||||
@@ -2385,10 +2353,15 @@ async function parseForwardNodes(
|
||||
);
|
||||
}
|
||||
|
||||
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
||||
const elements = restoreHistoricalMedia(
|
||||
const content = event.message ?? event.raw_message ?? '';
|
||||
const elements = await restoreHistoricalMedia(
|
||||
ref,
|
||||
await parseMessage(content, false),
|
||||
await parseMessage(content, false, {
|
||||
forwardReply: {
|
||||
senderUin: userUin,
|
||||
time: toPositiveInt(event.time) || undefined,
|
||||
},
|
||||
}),
|
||||
messageId,
|
||||
);
|
||||
|
||||
@@ -2424,7 +2397,10 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
const content = nodeData.content ?? nodeData.message ?? '';
|
||||
// Preserve the node-time policy for both the node and its custom quotes.
|
||||
const nodeTime = toPositiveInt(nodeData.time);
|
||||
const time = nodeTime > 0 && nodeTime < 0xffffffff ? nodeTime : undefined;
|
||||
|
||||
let elements: MessageElement[];
|
||||
let innerForward: ForwardNodePayload[] | undefined;
|
||||
@@ -2455,7 +2431,9 @@ async function parseForwardNodes(
|
||||
// uuid in hand.
|
||||
elements = [];
|
||||
} else {
|
||||
elements = await parseMessage(content, false);
|
||||
elements = await parseMessage(content, false, {
|
||||
forwardReply: { senderUin: userUin, time },
|
||||
});
|
||||
}
|
||||
|
||||
if (!innerForward && elements.length === 0) {
|
||||
@@ -2464,41 +2442,18 @@ async function parseForwardNodes(
|
||||
|
||||
const node: ForwardNodePayload = { userUin, nickname, elements };
|
||||
|
||||
// Forward optional preview news lines (OneBot `data.news`) onto the
|
||||
// payload so nested-forward bubble previews can prefer caller-supplied
|
||||
// lines over auto-generated ones. Only accepted when the array shape
|
||||
// is valid (already asserted by assertForwardNodeMetadata).
|
||||
if (isForwardNewsArray(nodeData.news)) {
|
||||
if (nodeData.news !== undefined) {
|
||||
node.news = nodeData.news.map((item) => ({ text: item.text }));
|
||||
}
|
||||
|
||||
// Forward optional OneBot bubble-preview metadata so nested-forward
|
||||
// cards can prefer caller-supplied titles/source/summary/prompt over
|
||||
// auto-derived ones (types already asserted above).
|
||||
if (nodeData.title !== undefined && typeof nodeData.title === 'string') {
|
||||
node.title = nodeData.title;
|
||||
for (const field of ['title', 'source', 'summary', 'prompt'] as const) {
|
||||
if (nodeData[field] !== undefined) {
|
||||
node[field] = nodeData[field];
|
||||
}
|
||||
}
|
||||
|
||||
if (nodeData.source !== undefined && typeof nodeData.source === 'string') {
|
||||
node.source = nodeData.source;
|
||||
}
|
||||
|
||||
if (nodeData.summary !== undefined && typeof nodeData.summary === 'string') {
|
||||
node.summary = nodeData.summary;
|
||||
}
|
||||
|
||||
if (nodeData.prompt !== undefined && typeof nodeData.prompt === 'string') {
|
||||
node.prompt = nodeData.prompt;
|
||||
}
|
||||
|
||||
// Honour an explicit per-node display time (OneBot `data.time`, unix
|
||||
// seconds) so a custom forward can set/back-date each node's timestamp
|
||||
// (#209). The wire field is uint32, so reject a millisecond value or any
|
||||
// out-of-range input (it would overflow/throw) and fall back to now.
|
||||
const nodeTime = toPositiveInt(nodeData.time);
|
||||
|
||||
if (nodeTime > 0 && nodeTime < 0xffffffff) {
|
||||
node.time = nodeTime;
|
||||
if (time !== undefined) {
|
||||
node.time = time;
|
||||
}
|
||||
|
||||
if (innerForward) {
|
||||
|
||||
@@ -1,56 +1,61 @@
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import { SqliteDatabase, type SqliteStatement } from '@snowluma/sqlite';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
|
||||
export class ReactionStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly stmtUpsert: StatementSync;
|
||||
private readonly stmtRemove: StatementSync;
|
||||
private readonly stmtList: StatementSync;
|
||||
private readonly stmtCount: StatementSync;
|
||||
private readonly stmtCountByEmoji: StatementSync;
|
||||
private readonly db: SqliteDatabase;
|
||||
private stmtUpsert!: SqliteStatement;
|
||||
private stmtRemove!: SqliteStatement;
|
||||
private stmtList!: SqliteStatement;
|
||||
private stmtCount!: SqliteStatement;
|
||||
private stmtCountByEmoji!: SqliteStatement;
|
||||
|
||||
readonly initialization: Promise<void>;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
this.db = openSqliteDb(dbPath);
|
||||
this.initSchema();
|
||||
this.initialization = this.db.serial(async () => {
|
||||
await this.initSchema();
|
||||
|
||||
this.stmtUpsert = this.db.prepare(
|
||||
`INSERT INTO reactions
|
||||
(group_id, msg_seq, emoji_id, emoji_type, operator_uin, operator_uid, set_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(group_id, msg_seq, emoji_id, operator_uin) DO UPDATE SET
|
||||
emoji_type = excluded.emoji_type,
|
||||
operator_uid = excluded.operator_uid,
|
||||
set_at = excluded.set_at`,
|
||||
);
|
||||
this.stmtUpsert = this.db.prepare(
|
||||
`INSERT INTO reactions
|
||||
(group_id, msg_seq, emoji_id, emoji_type, operator_uin, operator_uid, set_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(group_id, msg_seq, emoji_id, operator_uin) DO UPDATE SET
|
||||
emoji_type = excluded.emoji_type,
|
||||
operator_uid = excluded.operator_uid,
|
||||
set_at = excluded.set_at`,
|
||||
);
|
||||
|
||||
this.stmtRemove = this.db.prepare(
|
||||
`DELETE FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ? AND operator_uin = ?`,
|
||||
);
|
||||
this.stmtRemove = this.db.prepare(
|
||||
`DELETE FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ? AND operator_uin = ?`,
|
||||
);
|
||||
|
||||
this.stmtList = this.db.prepare(
|
||||
`SELECT operator_uin, operator_uid, set_at
|
||||
FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ?
|
||||
ORDER BY set_at ASC
|
||||
LIMIT ? OFFSET ?`,
|
||||
);
|
||||
this.stmtList = this.db.prepare(
|
||||
`SELECT operator_uin, operator_uid, set_at
|
||||
FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ?
|
||||
ORDER BY set_at ASC
|
||||
LIMIT ? OFFSET ?`,
|
||||
);
|
||||
|
||||
this.stmtCount = this.db.prepare(
|
||||
`SELECT COUNT(*) AS n FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ?`,
|
||||
);
|
||||
this.stmtCount = this.db.prepare(
|
||||
`SELECT COUNT(*) AS n FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ?`,
|
||||
);
|
||||
|
||||
this.stmtCountByEmoji = this.db.prepare(
|
||||
`SELECT emoji_id, emoji_type, COUNT(*) AS n, MAX(set_at) AS last_at
|
||||
FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ?
|
||||
GROUP BY emoji_id`,
|
||||
);
|
||||
this.stmtCountByEmoji = this.db.prepare(
|
||||
`SELECT emoji_id, emoji_type, COUNT(*) AS n, MAX(set_at) AS last_at
|
||||
FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ?
|
||||
GROUP BY emoji_id`,
|
||||
);
|
||||
});
|
||||
void this.initialization.catch(() => undefined);
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
this.db.exec(`
|
||||
private async initSchema(): Promise<void> {
|
||||
await this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS reactions (
|
||||
group_id INTEGER NOT NULL,
|
||||
msg_seq INTEGER NOT NULL,
|
||||
@@ -66,7 +71,7 @@ export class ReactionStore {
|
||||
`);
|
||||
}
|
||||
|
||||
recordAdd(
|
||||
async recordAdd(
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
emojiId: string,
|
||||
@@ -74,68 +79,100 @@ export class ReactionStore {
|
||||
operatorUin: number,
|
||||
operatorUid: string,
|
||||
setAt: number,
|
||||
): void {
|
||||
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
|
||||
return;
|
||||
}
|
||||
): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
|
||||
this.stmtUpsert.run(groupId, msgSeq, emojiId, emojiType, operatorUin, operatorUid, setAt);
|
||||
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.stmtUpsert.run(
|
||||
groupId,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
emojiType,
|
||||
operatorUin,
|
||||
operatorUid,
|
||||
setAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
recordRemove(groupId: number, msgSeq: number, emojiId: string, operatorUin: number): void {
|
||||
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
|
||||
return;
|
||||
}
|
||||
async recordRemove(
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
emojiId: string,
|
||||
operatorUin: number,
|
||||
): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
|
||||
this.stmtRemove.run(groupId, msgSeq, emojiId, operatorUin);
|
||||
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.stmtRemove.run(groupId, msgSeq, emojiId, operatorUin);
|
||||
});
|
||||
}
|
||||
|
||||
listUsers(
|
||||
async listUsers(
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
emojiId: string,
|
||||
limit = 20,
|
||||
offset = 0,
|
||||
): Array<{ operatorUin: number; operatorUid: string; setAt: number }> {
|
||||
const rows = this.stmtList.all(
|
||||
groupId,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
Math.max(1, Math.min(limit, 500)),
|
||||
Math.max(0, offset),
|
||||
) as Array<{ operator_uin: number; operator_uid: string; set_at: number }>;
|
||||
return rows.map((r) => ({
|
||||
operatorUin: r.operator_uin,
|
||||
operatorUid: r.operator_uid,
|
||||
setAt: r.set_at,
|
||||
}));
|
||||
): Promise<Array<{ operatorUin: number; operatorUid: string; setAt: number }>> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const rows = (await this.stmtList.all(
|
||||
groupId,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
Math.max(1, Math.min(limit, 500)),
|
||||
Math.max(0, offset),
|
||||
)) as Array<{ operator_uin: number; operator_uid: string; set_at: number }>;
|
||||
return rows.map((r) => ({
|
||||
operatorUin: r.operator_uin,
|
||||
operatorUid: r.operator_uid,
|
||||
setAt: r.set_at,
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
countUsers(groupId: number, msgSeq: number, emojiId: string): number {
|
||||
const row = this.stmtCount.get(groupId, msgSeq, emojiId) as { n: number } | undefined;
|
||||
return row?.n ?? 0;
|
||||
async countUsers(groupId: number, msgSeq: number, emojiId: string): Promise<number> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const row = (await this.stmtCount.get(groupId, msgSeq, emojiId)) as
|
||||
{ n: number } | undefined;
|
||||
return row?.n ?? 0;
|
||||
});
|
||||
}
|
||||
|
||||
/** Summary of all cached reactions on a message, grouped by emoji. */
|
||||
summarizeMessage(
|
||||
async summarizeMessage(
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
): Array<{ emojiId: string; emojiType: number; count: number; lastSetAt: number }> {
|
||||
const rows = this.stmtCountByEmoji.all(groupId, msgSeq) as Array<{
|
||||
emoji_id: string;
|
||||
emoji_type: number;
|
||||
n: number;
|
||||
last_at: number;
|
||||
}>;
|
||||
return rows.map((r) => ({
|
||||
emojiId: r.emoji_id,
|
||||
emojiType: r.emoji_type,
|
||||
count: r.n,
|
||||
lastSetAt: r.last_at,
|
||||
}));
|
||||
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastSetAt: number }>> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const rows = (await this.stmtCountByEmoji.all(groupId, msgSeq)) as Array<{
|
||||
emoji_id: string;
|
||||
emoji_type: number;
|
||||
n: number;
|
||||
last_at: number;
|
||||
}>;
|
||||
return rows.map((r) => ({
|
||||
emojiId: r.emoji_id,
|
||||
emojiType: r.emoji_type,
|
||||
count: r.n,
|
||||
lastSetAt: r.last_at,
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
async close(): Promise<void> {
|
||||
await this.initialization.catch(() => undefined);
|
||||
await this.db.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
|
||||
const labels: Readonly<Record<string, string>> = {
|
||||
image: '[图片]',
|
||||
record: '[语音]',
|
||||
video: '[视频]',
|
||||
file: '[文件]',
|
||||
face: '[表情]',
|
||||
mface: '[表情]',
|
||||
forward: '[聊天记录]',
|
||||
json: '[卡片]',
|
||||
xml: '[卡片]',
|
||||
markdown: '[Markdown]',
|
||||
};
|
||||
|
||||
function previewLabel(type: string): string {
|
||||
if (!Object.hasOwn(labels, type)) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
`message segment "${type}" is not supported in a reply preview`,
|
||||
type,
|
||||
);
|
||||
}
|
||||
|
||||
return labels[type]!;
|
||||
}
|
||||
|
||||
export function assertReplyPreviewType(type: string): void {
|
||||
if (type !== 'text' && type !== 'at') {
|
||||
previewLabel(type);
|
||||
}
|
||||
}
|
||||
|
||||
/** Quotes carry display text; media must not be uploaded again for a preview. */
|
||||
export function elementsToReplyPreview(elements: readonly MessageElement[]): MessageElement[] {
|
||||
const text = elements
|
||||
.map((element) => {
|
||||
if (element.type === 'text') {
|
||||
return element.text;
|
||||
}
|
||||
|
||||
if (element.type === 'at') {
|
||||
return element.targetUin === 0 ? '@全体成员' : `@${element.targetUin}`;
|
||||
}
|
||||
|
||||
return previewLabel(element.type);
|
||||
})
|
||||
.join('');
|
||||
return [{ type: 'text', text }];
|
||||
}
|
||||
|
||||
export function replyPreviewElements(message: unknown): MessageElement[] {
|
||||
if (!Array.isArray(message)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
|
||||
for (const segment of message) {
|
||||
if (!segment || typeof segment !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = segment.data;
|
||||
|
||||
if (!data || typeof data !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segment.type === 'text' && typeof data.text === 'string') {
|
||||
parts.push(data.text);
|
||||
} else if (segment.type === 'at') {
|
||||
parts.push(data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`);
|
||||
} else if (typeof segment.type === 'string' && Object.hasOwn(labels, segment.type)) {
|
||||
parts.push(labels[segment.type]!);
|
||||
}
|
||||
}
|
||||
|
||||
const text = parts.join('');
|
||||
return text ? [{ type: 'text', text }] : [];
|
||||
}
|
||||
@@ -1,22 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { SqliteDatabase } from '@snowluma/sqlite';
|
||||
|
||||
/**
|
||||
* Open a SQLite database with the store-wide defaults: ensure the parent
|
||||
* directory exists, then open with WAL journaling + NORMAL synchronous — the
|
||||
* durability/throughput balance the message / media / reaction stores all
|
||||
* want. The caller owns schema init and any path munging.
|
||||
*
|
||||
* Concentrates the bootstrap each store previously hand-copied verbatim, so a
|
||||
* PRAGMA / journal-mode / busy-timeout change lands in one place instead of
|
||||
* three.
|
||||
*/
|
||||
export function openSqliteDb(dbPath: string): DatabaseSync {
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA synchronous = NORMAL');
|
||||
db.exec('PRAGMA busy_timeout = 1000');
|
||||
return db;
|
||||
/** Opens asynchronously with the shared WAL, durability and busy-timeout defaults. */
|
||||
export function openSqliteDb(dbPath: string): SqliteDatabase {
|
||||
return new SqliteDatabase(dbPath);
|
||||
}
|
||||
Reference in new issue
Block a user