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:
DrSmoothl committed 2026-05-22 22:08:45 +08:00
1 parent 65636953e7
commit c3675aef7c
10 files changed
+506 -70

No files matched your search

+22 -11
View File
@@ -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));
+20
View File
@@ -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 /
+37
View File
@@ -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,
);
}
}
+36 -1
View File
@@ -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),
+5
View 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 {
+159
View File
@@ -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();
}
}