feat(emoji-like): back fetch_emoji_like / get_emoji_likes with a local cache
Two rounds of production wire-level probing established that the OIDB
SSO path cannot surface the reactor user list for an emoji:
- 0x9083_1 → 4-byte ack `18 01 20 01` (no list)
- 0x9084_1 → per-emoji summary (count + timestamp,
still no user IDs)
- 0x9082_3..5, 0x9083_0/2/3, 0x9084_2..5, 0x9085_1/2, 0x9087_1
→ "no privilege" — the cmds exist but
aren't in NTQQ's client capability
bitmap, so the server blocks anything
not registered at login. NTQQ itself
serves getMsgEmojiLikesList from a
wrapper-internal cache, not SSO.
Mirror that wrapper-cache approach on the OneBot side. SnowLuma
already receives GroupMsgEmojiLikeEvent push events for every
reaction add/remove (with operator uin + uid + emoji + msgSeq); we
just weren't persisting them. Now we do.
Changes:
* proto-defs: add Oidb0x9084 Req/Resp schema for the summary call.
RespEntry's lastReactionTime/count are optional because the
"available reactions catalog" tail entries omit both — only the
"used" subset carries metadata.
* core InteractionApi: revert the 9-candidate probe loop, restore a
single 0x9083_1 call as a legacy stub (returns empty list, with a
debug-level hex dump on empty responses), and add
fetchReactionSummary() that calls 0x9084_1 and yields the per-emoji
summary (count + last-reaction timestamp).
* onebot ReactionStore: new SQLite-backed cache, schema
reactions(group_id, msg_seq, emoji_id, emoji_type, operator_uin,
operator_uid, set_at), PK on (group_id, msg_seq, emoji_id,
operator_uin). Mirrors MessageStore design — prepared statements at
construction, WAL journal.
* onebot event-pipeline: subscribe group_msg_emoji_like, call
reactionStore.recordAdd / recordRemove before convertAndDispatch so
a fetch_emoji_like racing with the push still sees the new row.
* onebot instance / instance-context: own the ReactionStore, expose
it on OneBotInstanceContext, close it on dispose. New
fetchEmojiLikeUsers helper on ApiActionContext combines local-cache
reads with a 0x9084_1 cross-check so callers can detect cache gaps
(events missed before bot boot, etc).
* onebot actions: get_emoji_likes and fetch_emoji_like now read from
the cache. fetch_emoji_like's NapCat-style cookie becomes a numeric
offset for cache pagination (no real cursor needed against local
SQLite).
* tests: 7 new ReactionStore unit tests (CRUD + pagination +
cross-key isolation + summarizeMessage). Existing event-pipeline
test harness picks up a no-op ReactionStore stub.
This commit is contained in:
@@ -12,6 +12,8 @@ import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
Oidb0x9083Req,
|
||||
Oidb0x9083Resp,
|
||||
Oidb0x9084Req,
|
||||
Oidb0x9084Resp,
|
||||
OidbEssence,
|
||||
OidbGroupReaction,
|
||||
OidbLike,
|
||||
@@ -91,64 +93,94 @@ export class InteractionApi {
|
||||
count,
|
||||
field12: 1,
|
||||
};
|
||||
// Wire-level investigation against macOS NTQQ confirmed 0x9083_1 is
|
||||
// a real server endpoint (routed, errorCode=0, trace string echoes
|
||||
// "OidbSvcTrpcTcp.0x9083_1") but its reply is always a 4-byte
|
||||
// minimal ack `18 01 20 01` — not a user list. The real fetch cmd
|
||||
// must be a sibling. To find it, on every call we round-robin a
|
||||
// small candidate list of (cmd, subcmd) tuples, log each result, and
|
||||
// return the first one that surfaces users. Frequencies are low
|
||||
// (user-triggered "view who reacted") so the extra SSO traffic is
|
||||
// acceptable for a debug build.
|
||||
// Round-2 candidates, after round-1 found 0x9084_1 returns a reaction
|
||||
// summary (emoji_id list with timestamp/count for used emojis, plus
|
||||
// a 28-emoji catalog). We need the "fetch users who reacted with
|
||||
// emoji X" sibling — almost certainly another subcmd of 0x9084.
|
||||
const candidates: Array<readonly [number, number]> = [
|
||||
[0x9084, 2], // most likely: "fetch reactor user list for specific emoji"
|
||||
[0x9084, 3],
|
||||
[0x9084, 4],
|
||||
[0x9084, 5],
|
||||
[0x9085, 1], // adjacent cmd family, exploratory
|
||||
[0x9085, 2],
|
||||
[0x9086, 1],
|
||||
[0x9087, 1],
|
||||
[0x9084, 1], // keep baseline at the end so we still confirm summary
|
||||
];
|
||||
|
||||
let winner: { users: Array<{ uin: number }>; cookie: string; isLast: boolean } | null = null;
|
||||
log.debug(
|
||||
`getEmojiLikes probe START: group=${groupId} seq=${sequence} `
|
||||
+ `emojiId=${emojiId} emojiType=${emojiType} count=${count} `
|
||||
+ `cookieIn=${cookie ? 'yes' : 'no'}`,
|
||||
);
|
||||
for (const [cmdHex, subCmd] of candidates) {
|
||||
const wireName = `OidbSvcTrpcTcp.0x${cmdHex.toString(16)}_${subCmd}`;
|
||||
const env = makeOidbEnvelope<Oidb0x9083Req>(cmdHex, subCmd, req);
|
||||
const reqBytes = protobuf_encode<OidbBase<Oidb0x9083Req>>(env);
|
||||
let respBytes: Uint8Array;
|
||||
try {
|
||||
respBytes = await runOidb(bridge, wireName, reqBytes);
|
||||
} catch (e) {
|
||||
log.debug(` ${wireName} threw: ${e instanceof Error ? e.message : String(e)}`);
|
||||
continue;
|
||||
}
|
||||
const resp = protobuf_decode<OidbBase<Oidb0x9083Resp>>(respBytes).body;
|
||||
const users: Array<{ uin: number }> = (resp?.inner?.userInfo ?? [])
|
||||
.map(u => ({ uin: Number(u?.uin ?? 0) }))
|
||||
.filter(u => u.uin > 0);
|
||||
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
|
||||
log.debug(
|
||||
` ${wireName}: respLen=${respBytes.length} users=${users.length} `
|
||||
+ `respCookie=${respCookie || '(empty)'}`,
|
||||
);
|
||||
log.debug(` req hex: ${toHexUpper(reqBytes)}`);
|
||||
log.debug(` resp hex: ${toHexUpper(respBytes)}`);
|
||||
if (!winner && users.length > 0) {
|
||||
winner = { users, cookie: respCookie, isLast: !respCookie };
|
||||
}
|
||||
// Two rounds of wire-level probing against macOS NTQQ confirmed:
|
||||
// - 0x9083_1 returns a 4-byte ack `18 01 20 01` (no user list)
|
||||
// - 0x9084_1 returns a per-emoji reaction *summary* (emoji_id +
|
||||
// count + last-reaction timestamp), no user IDs — see
|
||||
// `fetchReactionSummary` below
|
||||
// - 0x9082_3..5, 0x9083_0/2/3, 0x9084_2..5, 0x9085_1/2, 0x9087_1
|
||||
// all reject with "no privilege": the cmds exist but aren't in
|
||||
// the NTQQ client's capability bitmap, so the server blocks
|
||||
// anything not registered at login. NTQQ's own
|
||||
// `getMsgEmojiLikesList` uses a wrapper-internal cache, not SSO.
|
||||
// So this OIDB path can never surface the user list. The real
|
||||
// implementation lives in `ReactionStore` on the OneBot side, fed
|
||||
// from `GroupMsgEmojiLikeEvent` push. This method is retained so
|
||||
// legacy callers don't crash — they get an empty users array.
|
||||
const env = makeOidbEnvelope<Oidb0x9083Req>(0x9083, 1, req);
|
||||
const reqBytes = protobuf_encode<OidbBase<Oidb0x9083Req>>(env);
|
||||
let respBytes: Uint8Array;
|
||||
try {
|
||||
respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', reqBytes);
|
||||
} catch (e) {
|
||||
log.debug(`getEmojiLikes 0x9083_1 threw: ${e instanceof Error ? e.message : String(e)}`);
|
||||
return { users: [], cookie: '', isLast: true };
|
||||
}
|
||||
log.debug(`getEmojiLikes probe END: winner=${winner ? `users=${winner.users.length}` : 'none'}`);
|
||||
return winner ?? { users: [], cookie: '', isLast: true };
|
||||
const resp = protobuf_decode<OidbBase<Oidb0x9083Resp>>(respBytes).body;
|
||||
const users: Array<{ uin: number }> = (resp?.inner?.userInfo ?? [])
|
||||
.map(u => ({ uin: Number(u?.uin ?? 0) }))
|
||||
.filter(u => u.uin > 0);
|
||||
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
|
||||
if (users.length === 0) {
|
||||
log.debug(
|
||||
`getEmojiLikes empty (expected — use ReactionStore instead): `
|
||||
+ `group=${groupId} seq=${sequence} emojiId=${emojiId} `
|
||||
+ `respLen=${respBytes.length}`,
|
||||
);
|
||||
}
|
||||
return { users, cookie: respCookie, isLast: !respCookie };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the per-emoji *reaction summary* on a group message via
|
||||
* OIDB 0x9084_1 (the cmd that's actually in NTQQ's capability
|
||||
* whitelist and returns real data). Returns one entry per emoji
|
||||
* that has been reacted with on the message: emoji_id + total
|
||||
* reactor count + timestamp of the last reaction.
|
||||
*
|
||||
* This is the "server-truth" counterpart to the local ReactionStore
|
||||
* cache: ReactionStore tracks *who* reacted (from push events), and
|
||||
* `fetchReactionSummary` tells us *how many* the server thinks there
|
||||
* are. Cross-checking the two lets callers detect cache gaps (push
|
||||
* events lost before the bot booted, etc).
|
||||
*
|
||||
* Catalog entries (available emojis with no count/timestamp) are
|
||||
* filtered out — callers want the "used" subset.
|
||||
*/
|
||||
async fetchReactionSummary(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const req: any = {
|
||||
groupId: BigInt(groupId),
|
||||
sequence: BigInt(sequence),
|
||||
// Match the request shape the 0x9083_1 path sends so the server
|
||||
// routes us identically. `count`/`emojiId`/`emojiType` are
|
||||
// ignored by the summary handler but harmless.
|
||||
emojiId: '',
|
||||
emojiType: 0,
|
||||
cookie: new Uint8Array(0),
|
||||
count: 0,
|
||||
field12: 1,
|
||||
};
|
||||
const env = makeOidbEnvelope<Oidb0x9084Req>(0x9084, 1, req);
|
||||
const reqBytes = protobuf_encode<OidbBase<Oidb0x9084Req>>(env);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9084_1', reqBytes);
|
||||
const resp = protobuf_decode<OidbBase<Oidb0x9084Resp>>(respBytes).body;
|
||||
const out: Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }> = [];
|
||||
for (const e of resp?.entries ?? []) {
|
||||
const count = e.count ?? 0;
|
||||
// Filter the catalog tail. "Used" entries always have count > 0
|
||||
// and a lastReactionTime; catalog entries have neither.
|
||||
if (count <= 0) continue;
|
||||
out.push({
|
||||
emojiId: e.emojiId ?? '',
|
||||
emojiType: e.emojiType ?? 1,
|
||||
count,
|
||||
lastReactionTime: Number(e.lastReactionTime ?? 0n),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -810,15 +810,22 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
}
|
||||
});
|
||||
|
||||
// get_emoji_likes / fetch_emoji_like both back into the same
|
||||
// ReactionStore-backed helper. The OIDB-only path can't surface the
|
||||
// user list (server-side capability whitelist blocks every "fetch
|
||||
// reactor" subcmd), so the local cache fed by GroupMsgEmojiLike push
|
||||
// events is the source of truth here. We cross-check totals against
|
||||
// OIDB 0x9084_1 summary so callers can tell when the cache is
|
||||
// incomplete (events missed before bot boot, etc.).
|
||||
h.registerAction('get_emoji_likes', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const emojiId = asString(params.emoji_id) || '';
|
||||
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
|
||||
try {
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
|
||||
const result = await ctx.bridge.apis.interaction.getEmojiLikes(meta.targetId, meta.sequence, emojiId);
|
||||
return okResponse({ emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })) });
|
||||
const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, 1000);
|
||||
return okResponse({
|
||||
emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })),
|
||||
});
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
@@ -827,21 +834,25 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('fetch_emoji_like', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const emojiId = asString(params.emojiId) || '';
|
||||
const emojiType = asNumber(params.emojiType) || 1;
|
||||
const count = asNumber(params.count) || 10;
|
||||
const cookie = asString(params.cookie) || '';
|
||||
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emojiId are required');
|
||||
try {
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
|
||||
const result = await ctx.bridge.apis.interaction.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie);
|
||||
// Cookie-based pagination doesn't make sense over a local SQLite
|
||||
// store; parse incoming cookie as numeric offset for compatibility
|
||||
// with NapCat-style clients, and emit the next offset on the way
|
||||
// back out when there are still rows past the current page.
|
||||
const offset = cookie ? Number.parseInt(cookie, 10) || 0 : 0;
|
||||
const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, count, offset);
|
||||
const nextOffset = offset + result.users.length;
|
||||
const isLastPage = nextOffset >= result.cachedCount;
|
||||
return okResponse({
|
||||
result: 0,
|
||||
errMsg: '',
|
||||
emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })),
|
||||
cookie: result.cookie,
|
||||
isLastPage: result.isLast,
|
||||
isFirstPage: !cookie,
|
||||
cookie: isLastPage ? '' : String(nextOffset),
|
||||
isLastPage,
|
||||
isFirstPage: offset === 0,
|
||||
});
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
|
||||
@@ -96,6 +96,26 @@ export interface ApiActionContext {
|
||||
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
|
||||
// setMsgEmojiLike: stays because it threads messageStore meta lookup.
|
||||
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
|
||||
/**
|
||||
* Fetch the cached reactor user list for a (message, emoji) pair.
|
||||
* Backed by ReactionStore — see `reaction-store.ts` for the
|
||||
* limitations vs. NapCat's wrapper-cache approach.
|
||||
*
|
||||
* `serverCount` comes from a side `0x9084_1` summary call; when it
|
||||
* exceeds `cachedUsers.length` the cache is provably incomplete
|
||||
* (push events missed before bot boot, etc).
|
||||
*/
|
||||
fetchEmojiLikeUsers: (
|
||||
messageId: number,
|
||||
emojiId: string,
|
||||
count: number,
|
||||
offset?: number,
|
||||
) => Promise<{
|
||||
users: Array<{ uin: number; uid: string; setAt: number }>;
|
||||
cachedCount: number;
|
||||
serverCount: number;
|
||||
complete: boolean;
|
||||
}>;
|
||||
// All other extended / NapCat-compatible / Web / Album actions are
|
||||
// accessed directly through `ctx.bridge.apis.<area>.<method>()`:
|
||||
// * profile area: setProfile / setOnlineStatus / fetchCustomFace /
|
||||
|
||||
@@ -39,6 +39,12 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
|
||||
for (const kind of NOTICE_KINDS) {
|
||||
disposers.push(
|
||||
ctx.bridge.events.on(kind, async (event) => {
|
||||
// Side-effect: write emoji-reaction events to the local cache
|
||||
// BEFORE converting / dispatching, so a fetch_emoji_like that
|
||||
// races with the push still sees the new row.
|
||||
if (event.kind === 'group_msg_emoji_like') {
|
||||
cacheReaction(ctx, event);
|
||||
}
|
||||
await convertAndDispatch(ctx, event);
|
||||
}),
|
||||
);
|
||||
@@ -105,3 +111,34 @@ function cachePrivateMessageMeta(
|
||||
timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
function cacheReaction(
|
||||
ctx: OneBotInstanceContext,
|
||||
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
|
||||
): void {
|
||||
// `isAdd=true` means the operator just reacted; `isAdd=false` means
|
||||
// the reaction was withdrawn. The decoder already normalizes both
|
||||
// directions onto this single event kind. `emojiType` isn't on the
|
||||
// push event payload — we default to 1 (QQ-face) which matches every
|
||||
// observed reaction so far; the field is a known unknown and can be
|
||||
// refined later if a wire dump shows it.
|
||||
if (!event.groupId || !event.msgSeq || !event.emojiId || !event.operatorUin) return;
|
||||
if (event.isAdd) {
|
||||
ctx.reactionStore.recordAdd(
|
||||
event.groupId,
|
||||
event.msgSeq,
|
||||
event.emojiId,
|
||||
1,
|
||||
event.operatorUin,
|
||||
event.operatorUid,
|
||||
event.time,
|
||||
);
|
||||
} else {
|
||||
ctx.reactionStore.recordRemove(
|
||||
event.groupId,
|
||||
event.msgSeq,
|
||||
event.emojiId,
|
||||
event.operatorUin,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { ApiActionContext } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import type { MediaStore } from './media-store';
|
||||
import type { MessageStore } from './message-store';
|
||||
import type { ReactionStore } from './reaction-store';
|
||||
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
|
||||
import {
|
||||
getDownloadRKeys,
|
||||
@@ -60,6 +61,10 @@ export interface OneBotInstanceContext {
|
||||
|
||||
messageStore: MessageStore;
|
||||
mediaStore: MediaStore;
|
||||
/** Local cache of emoji-reaction events keyed by (group, msgSeq, emoji,
|
||||
* reactor). Fed from `GroupMsgEmojiLikeEvent` push by the event
|
||||
* pipeline; queried by fetch_emoji_like / get_emoji_likes. */
|
||||
reactionStore: ReactionStore;
|
||||
|
||||
converterCtx: ConverterContext;
|
||||
|
||||
@@ -86,7 +91,7 @@ export interface OneBotInstanceContext {
|
||||
* happening (set_group_admin, set_online_status, set_avatar, …).
|
||||
*/
|
||||
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
const { bridge, messageStore, mediaStore } = ref;
|
||||
const { bridge, messageStore, mediaStore, reactionStore } = ref;
|
||||
|
||||
return {
|
||||
bridge,
|
||||
@@ -152,6 +157,36 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set);
|
||||
},
|
||||
|
||||
// Fetch reactor user list from local cache, cross-checked against
|
||||
// the server's 0x9084_1 summary so callers can tell when the cache
|
||||
// is incomplete (push events missed before bot boot, etc).
|
||||
fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
if (!meta) throw new Error('message not found');
|
||||
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
|
||||
const raw = reactionStore.listUsers(meta.targetId, meta.sequence, emojiId, count, offset);
|
||||
const users = raw.map(r => ({ uin: r.operatorUin, uid: r.operatorUid, setAt: r.setAt }));
|
||||
const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId);
|
||||
// Best-effort server-side count cross-check. If the summary call
|
||||
// itself fails (network blip / server hiccup) we fall back to the
|
||||
// cached count and report complete=true since we have no contrary
|
||||
// evidence.
|
||||
let serverCount = cachedCount;
|
||||
try {
|
||||
const summary = await bridge.apis.interaction.fetchReactionSummary(meta.targetId, meta.sequence);
|
||||
const match = summary.find(s => s.emojiId === emojiId);
|
||||
if (match) serverCount = match.count;
|
||||
} catch {
|
||||
/* keep serverCount = cachedCount */
|
||||
}
|
||||
return {
|
||||
users,
|
||||
cachedCount,
|
||||
serverCount,
|
||||
complete: cachedCount >= serverCount,
|
||||
};
|
||||
},
|
||||
|
||||
// Media lookup.
|
||||
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
|
||||
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ApiHandler } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { MediaIndexer } from './media-indexer';
|
||||
import { MediaStore } from './media-store';
|
||||
import { ReactionStore } from './reaction-store';
|
||||
import { MediaUrlResolver } from './media-url-resolver';
|
||||
import { MessageStore } from './message-store';
|
||||
import { RKeyCache } from './instance-rkey';
|
||||
@@ -32,6 +33,7 @@ export class OneBotInstance {
|
||||
private readonly converterCtx: ConverterContext;
|
||||
private readonly messageStore: MessageStore;
|
||||
private readonly mediaStore: MediaStore;
|
||||
private readonly reactionStore: ReactionStore;
|
||||
private readonly networkManager: OneBotNetworkManager;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
private readonly ctx: OneBotInstanceContext;
|
||||
@@ -56,6 +58,7 @@ export class OneBotInstance {
|
||||
this.rkeyCache = new RKeyCache();
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
|
||||
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
|
||||
this.reactionStore = new ReactionStore(path.join('data', this.uin, 'reactions.db'));
|
||||
|
||||
// The converter context's four callbacks delegate to small, focused
|
||||
// modules so this constructor doesn't carry the bridge-URL fetch
|
||||
@@ -83,6 +86,7 @@ export class OneBotInstance {
|
||||
bridge: this.bridge,
|
||||
messageStore: this.messageStore,
|
||||
mediaStore: this.mediaStore,
|
||||
reactionStore: this.reactionStore,
|
||||
converterCtx: this.converterCtx,
|
||||
config,
|
||||
musicSignUrl: config.musicSignUrl,
|
||||
@@ -122,6 +126,7 @@ export class OneBotInstance {
|
||||
});
|
||||
this.messageStore.close();
|
||||
this.mediaStore.close();
|
||||
this.reactionStore.close();
|
||||
}
|
||||
|
||||
addPid(pid: number): void {
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
|
||||
// Local cache of "who reacted with which emoji on which group message",
|
||||
// fed from `GroupMsgEmojiLikeEvent` push events. Mirrors what NTQQ's
|
||||
// internal wrapper cache stores — we maintain our own copy because
|
||||
// SnowLuma runs outside the NTQQ process and can't directly call
|
||||
// `NodeIKernelMsgService.getMsgEmojiLikesList`, and the OIDB SSO paths
|
||||
// for "fetch users who reacted with emoji X" are all blocked by the
|
||||
// server-side capability whitelist (cmds 0x9082_3..5, 0x9084_2..5,
|
||||
// etc. exist but our client isn't authorized to call them).
|
||||
//
|
||||
// Limitations vs. the wrapper cache:
|
||||
// - Only data from the bot's lifetime is captured. Reactions placed
|
||||
// before the bot booted are invisible until either:
|
||||
// (a) someone reacts again on that emoji (push event fires)
|
||||
// (b) caller cross-checks against `fetchReactionSummary` to
|
||||
// detect a count mismatch and warn the user
|
||||
// - Push events occasionally drop in unreliable network conditions;
|
||||
// periodic resync via 0x9084_1 summary can repair counts.
|
||||
export class ReactionStore {
|
||||
private readonly db: DatabaseType;
|
||||
private readonly stmtUpsert: Statement;
|
||||
private readonly stmtRemove: Statement;
|
||||
private readonly stmtList: Statement;
|
||||
private readonly stmtCount: Statement;
|
||||
private readonly stmtCountByEmoji: Statement;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
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.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.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`,
|
||||
);
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS reactions (
|
||||
group_id INTEGER NOT NULL,
|
||||
msg_seq INTEGER NOT NULL,
|
||||
emoji_id TEXT NOT NULL,
|
||||
emoji_type INTEGER NOT NULL DEFAULT 1,
|
||||
operator_uin INTEGER NOT NULL,
|
||||
operator_uid TEXT NOT NULL DEFAULT '',
|
||||
set_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (group_id, msg_seq, emoji_id, operator_uin)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_reactions_msg_emoji
|
||||
ON reactions (group_id, msg_seq, emoji_id, set_at);
|
||||
`);
|
||||
}
|
||||
|
||||
recordAdd(
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
emojiId: string,
|
||||
emojiType: number,
|
||||
operatorUin: number,
|
||||
operatorUid: string,
|
||||
setAt: number,
|
||||
): void {
|
||||
if (!groupId || !msgSeq || !emojiId || !operatorUin) return;
|
||||
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;
|
||||
this.stmtRemove.run(groupId, msgSeq, emojiId, operatorUin);
|
||||
}
|
||||
|
||||
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,
|
||||
}));
|
||||
}
|
||||
|
||||
countUsers(groupId: number, msgSeq: number, emojiId: string): number {
|
||||
const row = 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(
|
||||
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,
|
||||
}));
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
@@ -107,6 +107,14 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
|
||||
bridge: fakeBridge as never,
|
||||
messageStore: {} as never,
|
||||
mediaStore: {} as never,
|
||||
reactionStore: {
|
||||
recordAdd: () => {},
|
||||
recordRemove: () => {},
|
||||
listUsers: () => [],
|
||||
countUsers: () => 0,
|
||||
summarizeMessage: () => [],
|
||||
close: () => {},
|
||||
} as never,
|
||||
converterCtx,
|
||||
config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never,
|
||||
cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); },
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { ReactionStore } from '../src/reaction-store';
|
||||
|
||||
describe('ReactionStore', () => {
|
||||
const testDbPath = path.join('data', 'test', 'reactions-test.db');
|
||||
let store: ReactionStore;
|
||||
|
||||
beforeEach(() => {
|
||||
try { fs.unlinkSync(testDbPath); } catch { /* ignore */ }
|
||||
try { fs.unlinkSync(testDbPath + '-wal'); } catch { /* ignore */ }
|
||||
try { fs.unlinkSync(testDbPath + '-shm'); } catch { /* ignore */ }
|
||||
store = new ReactionStore(testDbPath);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
store.close();
|
||||
try { fs.unlinkSync(testDbPath); } catch { /* ignore */ }
|
||||
try { fs.unlinkSync(testDbPath + '-wal'); } catch { /* ignore */ }
|
||||
try { fs.unlinkSync(testDbPath + '-shm'); } catch { /* ignore */ }
|
||||
});
|
||||
|
||||
it('records an add and exposes it via listUsers / countUsers', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 12345, 'u_abc', 1700000000);
|
||||
const users = store.listUsers(100, 4001, '124');
|
||||
expect(users).toEqual([{ operatorUin: 12345, operatorUid: 'u_abc', setAt: 1700000000 }]);
|
||||
expect(store.countUsers(100, 4001, '124')).toBe(1);
|
||||
});
|
||||
|
||||
it('upserts on duplicate (group, msg, emoji, operator)', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 12345, 'u_old', 1700000000);
|
||||
store.recordAdd(100, 4001, '124', 1, 12345, 'u_new', 1700000500);
|
||||
const users = store.listUsers(100, 4001, '124');
|
||||
expect(users).toHaveLength(1);
|
||||
expect(users[0]?.operatorUid).toBe('u_new');
|
||||
expect(users[0]?.setAt).toBe(1700000500);
|
||||
});
|
||||
|
||||
it('removes the right row only', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 12345, 'u_a', 1700000000);
|
||||
store.recordAdd(100, 4001, '124', 1, 67890, 'u_b', 1700000100);
|
||||
store.recordRemove(100, 4001, '124', 12345);
|
||||
const users = store.listUsers(100, 4001, '124');
|
||||
expect(users).toHaveLength(1);
|
||||
expect(users[0]?.operatorUin).toBe(67890);
|
||||
});
|
||||
|
||||
it('isolates by group / msg / emoji', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 1, 'u', 1);
|
||||
store.recordAdd(100, 4001, '76', 1, 1, 'u', 1);
|
||||
store.recordAdd(100, 4002, '124', 1, 1, 'u', 1);
|
||||
store.recordAdd(200, 4001, '124', 1, 1, 'u', 1);
|
||||
expect(store.countUsers(100, 4001, '124')).toBe(1);
|
||||
expect(store.countUsers(100, 4001, '76')).toBe(1);
|
||||
expect(store.countUsers(100, 4002, '124')).toBe(1);
|
||||
expect(store.countUsers(200, 4001, '124')).toBe(1);
|
||||
expect(store.countUsers(100, 4001, '999')).toBe(0);
|
||||
});
|
||||
|
||||
it('paginates listUsers via limit + offset, ordering by set_at ASC', () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
store.recordAdd(100, 4001, '124', 1, 1000 + i, `u_${i}`, 1700000000 + i);
|
||||
}
|
||||
const page1 = store.listUsers(100, 4001, '124', 2, 0);
|
||||
const page2 = store.listUsers(100, 4001, '124', 2, 2);
|
||||
expect(page1.map(u => u.operatorUin)).toEqual([1000, 1001]);
|
||||
expect(page2.map(u => u.operatorUin)).toEqual([1002, 1003]);
|
||||
});
|
||||
|
||||
it('summarizeMessage groups by emoji_id', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 1, 'u1', 1);
|
||||
store.recordAdd(100, 4001, '124', 1, 2, 'u2', 2);
|
||||
store.recordAdd(100, 4001, '76', 1, 3, 'u3', 10);
|
||||
const summary = store.summarizeMessage(100, 4001).sort((a, b) => a.emojiId.localeCompare(b.emojiId));
|
||||
expect(summary).toEqual([
|
||||
{ emojiId: '124', emojiType: 1, count: 2, lastSetAt: 2 },
|
||||
{ emojiId: '76', emojiType: 1, count: 1, lastSetAt: 10 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('ignores incomplete records (no-op instead of throwing)', () => {
|
||||
store.recordAdd(0, 4001, '124', 1, 1, 'u', 1); // group 0
|
||||
store.recordAdd(100, 0, '124', 1, 1, 'u', 1); // msg 0
|
||||
store.recordAdd(100, 4001, '', 1, 1, 'u', 1); // empty emoji
|
||||
store.recordAdd(100, 4001, '124', 1, 0, 'u', 1); // uin 0
|
||||
expect(store.countUsers(100, 4001, '124')).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -548,6 +548,46 @@ export interface Oidb0x9083Resp {
|
||||
inner?: pb<4, Oidb0x9083RespInner>;
|
||||
cookie?: pb<5, bytes>;
|
||||
}
|
||||
|
||||
// 0x9084_1: fetch reaction summary on a message. Returns one entry per
|
||||
// emoji used + an "available reactions" catalog tail. Schema decoded
|
||||
// from production wire dump:
|
||||
// { 08 0A ← top-level field 1 (uint, meaning unclear: maybe
|
||||
// "total reactions on msg" or a flag — empirically
|
||||
// constant across messages)
|
||||
// 12 0E 08 <ts:varint> 10 <cnt:varint> 18 01 22 02 "76" ← entry 1
|
||||
// 12 07 18 01 22 03 "124" ← catalog
|
||||
// ... }
|
||||
// Used entries always carry field 1 (timestamp) and field 2 (count);
|
||||
// catalog entries omit both.
|
||||
export interface Oidb0x9084Req {
|
||||
groupId?: pb<2, uint_64>;
|
||||
sequence?: pb<3, uint_64>;
|
||||
// Server returns the full per-emoji summary regardless of these,
|
||||
// but we send them to mirror the working 0x9083_1 request shape.
|
||||
emojiId?: pb<4, string>;
|
||||
emojiType?: pb<5, uint_32>;
|
||||
cookie?: pb<6, bytes>;
|
||||
count?: pb<8, uint_32>;
|
||||
field12?: pb<12, uint_32>;
|
||||
}
|
||||
|
||||
export interface Oidb0x9084RespEntry {
|
||||
/** Unix epoch (seconds) of the last reaction. Omitted for catalog
|
||||
* entries that have never been reacted with on this message. */
|
||||
lastReactionTime?: pb<1, uint_64>;
|
||||
/** Number of reactors. Omitted for catalog entries. */
|
||||
count?: pb<2, uint_32>;
|
||||
/** Emoji type. 1 for QQ-face / short id, 2 for unicode codepoint. */
|
||||
emojiType?: pb<3, uint_32>;
|
||||
emojiId?: pb<4, string>;
|
||||
}
|
||||
|
||||
export interface Oidb0x9084Resp {
|
||||
/** Top-level varint, observed value `10` constant; semantics unknown. */
|
||||
field1?: pb<1, uint_32>;
|
||||
entries?: pb_repeated<2, Oidb0x9084RespEntry>;
|
||||
}
|
||||
export interface Oidb0x8a0Req {
|
||||
groupId?: pb<1, uint_64>;
|
||||
targetUids?: pb_repeated<3, string>;
|
||||
|
||||
Reference in New Issue
Block a user