Merge pull request #50 from SnowLuma/dev
chore: promote dev → main (941e60d)
This commit is contained in:
26 files changed
+1670
-667
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.8.4",
|
||||
"version": "1.8.5",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.8.4",
|
||||
"version": "1.8.5",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -66,6 +66,9 @@ export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<St
|
||||
request: {
|
||||
schema: OidbStrangerStatusReqSchema,
|
||||
value: { uin, key: [{ key: 27372 }] },
|
||||
// Same UIN-form flag fetchUserProfile sets — without it newer
|
||||
// QQ NT rejects with `[oidb] one of uid/openid is invaild`.
|
||||
isUid: true,
|
||||
},
|
||||
response: { schema: OidbStrangerStatusRespSchema },
|
||||
});
|
||||
|
||||
@@ -103,6 +103,19 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
|
||||
// The config flags ask QQ which per-group fields to include in the
|
||||
// response. Asking for everything looks innocent on small accounts
|
||||
// but on ~200+ groups it makes the QQ NT process write a payload
|
||||
// large enough to blow the named-pipe write buffer — we then read
|
||||
// EPIPE and the whole session dies. See issue #42.
|
||||
//
|
||||
// The user-verified safe combination: keep `config1.*` mostly on
|
||||
// (the response decoder pulls groupOwner / memberMax / memberCount /
|
||||
// groupName / description / question / announcement from this
|
||||
// group), but turn off the costly groups of bools that never map
|
||||
// back to a decoded field:
|
||||
// - config1.field5002, field5003 (expansive 5xxx-range descriptors)
|
||||
// - all of config2 (auxiliary per-group blob the decoder ignores)
|
||||
const allTrue = true;
|
||||
const body = {
|
||||
config: {
|
||||
@@ -114,11 +127,11 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
|
||||
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
|
||||
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
|
||||
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
|
||||
field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue,
|
||||
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
|
||||
},
|
||||
config2: {
|
||||
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
|
||||
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
|
||||
field1: false, field2: false, field3: false, field4: false,
|
||||
field5: false, field6: false, field7: false, field8: false,
|
||||
},
|
||||
config3: { field5: allTrue, field6: allTrue },
|
||||
},
|
||||
@@ -208,16 +221,23 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
|
||||
|
||||
export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<UserProfileInfo> {
|
||||
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
|
||||
// Only `uin` and `keys` — see OidbUserInfoRequestSchema for why
|
||||
// sending field 2 makes the server reject the request.
|
||||
const body = {
|
||||
uin,
|
||||
field2: 0,
|
||||
keys: keys.map(k => ({ key: k })),
|
||||
};
|
||||
|
||||
// Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the
|
||||
// name is historical, the wire semantic is "this is the UIN-form
|
||||
// variant of the call"). Without it newer QQ NT versions take the
|
||||
// UID-form validation path, find neither uid nor openid in the body
|
||||
// and bounce the request with `[oidb] one of uid/openid is invaild`.
|
||||
// Matches Lagrange.Core's FetchStrangerByUin (Reserved = 1).
|
||||
const resp = await runOidb<any>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
|
||||
oidbCmd: 0xFE1, subCmd: 2,
|
||||
request: { schema: OidbUserInfoRequestSchema, value: body },
|
||||
request: { schema: OidbUserInfoRequestSchema, value: body, isUid: true },
|
||||
response: { schema: OidbUserInfoResponseSchema },
|
||||
});
|
||||
|
||||
|
||||
@@ -20,10 +20,16 @@ export interface OidbCall<TResp = void> {
|
||||
schema: ProtoSchema;
|
||||
value: any;
|
||||
/**
|
||||
* Sets the OIDB envelope `reserved` field to 1 when true. A handful
|
||||
* of commands (group/friend list, rkey download) operate on
|
||||
* UID-keyed data and require this flag — the wire format is
|
||||
* otherwise identical.
|
||||
* Sets the OIDB envelope `reserved` field to 1 when true.
|
||||
*
|
||||
* The name is historical and misleading: empirically (see Lagrange
|
||||
* FetchStrangerByUin vs FetchStrangerByUid, fetchGroupList, our own
|
||||
* highway uploads) the `reserved = 1` flag indicates the UIN-form
|
||||
* variant of an OIDB call — it tells newer QQ NT to translate the
|
||||
* UIN in the body to an internal UID rather than running the
|
||||
* UID-form validator that expects a uid/openid string in the body.
|
||||
*
|
||||
* Omit (default false) for genuinely UID-keyed calls.
|
||||
*/
|
||||
isUid?: boolean;
|
||||
};
|
||||
|
||||
@@ -230,6 +230,22 @@ export interface FriendAddEvent extends QQEvent {
|
||||
userUin: number;
|
||||
}
|
||||
|
||||
export interface GroupMsgEmojiLikeEvent extends QQEvent {
|
||||
kind: 'group_msg_emoji_like';
|
||||
groupId: number;
|
||||
operatorUin: number;
|
||||
operatorUid: string;
|
||||
/** Sequence of the message that was reacted to (server-assigned msg_seq). */
|
||||
msgSeq: number;
|
||||
/** Emoji ID. QQ system faces are short numeric strings; market faces
|
||||
* are alphanumeric. We keep the wire string verbatim. */
|
||||
emojiId: string;
|
||||
/** Multiplicity of the reaction event. Usually 1. */
|
||||
count: number;
|
||||
/** True when the reaction is being added; false when removed. */
|
||||
isAdd: boolean;
|
||||
}
|
||||
|
||||
export type QQEventVariant =
|
||||
| FriendMessage
|
||||
| GroupMessage
|
||||
@@ -246,4 +262,5 @@ export type QQEventVariant =
|
||||
| GroupPokeEvent
|
||||
| GroupEssenceEvent
|
||||
| GroupFileUploadEvent
|
||||
| FriendAddEvent;
|
||||
| FriendAddEvent
|
||||
| GroupMsgEmojiLikeEvent;
|
||||
@@ -1,12 +1,14 @@
|
||||
// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches
|
||||
// to GroupMute (12) / GroupRecall (17) / GroupGreyTip (20) / GroupEssence (21).
|
||||
// to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) /
|
||||
// GroupGreyTip (20) / GroupEssence (21).
|
||||
|
||||
import { protoDecode } from '../../../protobuf/decode';
|
||||
import {
|
||||
GroupMuteSchema, NotifyMessageBodySchema,
|
||||
GroupMuteSchema, NotifyMessageBodySchema, GroupReactNotifySchema,
|
||||
} from '../../proto/notify';
|
||||
import type {
|
||||
GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent,
|
||||
GroupMsgEmojiLikeEvent,
|
||||
QQEventVariant,
|
||||
} from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
@@ -23,6 +25,7 @@ const unknownLog = createLogger('MsgPush.Unknown');
|
||||
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x2DCSubType) {
|
||||
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
|
||||
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
|
||||
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
|
||||
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
|
||||
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
|
||||
@@ -108,3 +111,51 @@ function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
// Magic prefix QQ prepends to the GroupReactNotify payload inside
|
||||
// body.msgContent for Event0x2DC subType=16. Same value NapCat strips
|
||||
// (see api/group.ts: `msgContent?.slice(7)`).
|
||||
const GROUP_REACT_PREFIX_BYTES = 7;
|
||||
// Discriminator on GroupReactNotify.field13 — same subType is reused
|
||||
// for other notify variants, only 35 means "emoji react". Anything
|
||||
// else falls through to MsgPush.Unknown for protocol-drift visibility.
|
||||
const GROUP_REACT_DISCRIMINATOR = 35;
|
||||
|
||||
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
|
||||
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
|
||||
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
|
||||
const notify = protoDecode(payload, GroupReactNotifySchema);
|
||||
if (!notify) return [];
|
||||
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
|
||||
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
|
||||
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
|
||||
return [];
|
||||
}
|
||||
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
|
||||
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
|
||||
if (!content) return [];
|
||||
|
||||
const groupId = Number(notify.groupUin ?? 0n);
|
||||
const operatorUid = content.operatorUid ?? '';
|
||||
const emojiId = content.code ?? '';
|
||||
const count = content.count ?? 1;
|
||||
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
|
||||
// removed. Older payloads occasionally omit it; default to "add"
|
||||
// since most clients can only generate add events.
|
||||
const isAdd = (content.type ?? 1) === 1;
|
||||
const msgSeq = Number(target?.seq ?? 0n);
|
||||
|
||||
const ev: GroupMsgEmojiLikeEvent = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin),
|
||||
operatorUid,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
count,
|
||||
isAdd,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export enum PkgType {
|
||||
|
||||
export enum Event0x2DCSubType {
|
||||
GroupMuteNotice = 12,
|
||||
GroupMsgEmojiLikeNotice = 16,
|
||||
GroupRecallNotice = 17,
|
||||
GroupGreyTipNotice = 20,
|
||||
GroupEssenceNotice = 21,
|
||||
|
||||
@@ -205,3 +205,41 @@ export const NotifyMessageBodySchema = {
|
||||
msgSequence: { field: 37, type: 'uint32' as const },
|
||||
field39: { field: 39, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// ─── Event0x2DC subType=16: GroupMsgEmojiLike ──────────────────────────────
|
||||
//
|
||||
// QQ pushes a Group message emoji reaction (someone tapped an emoji on a
|
||||
// message in a group). The payload nesting matches NapCat's transformer
|
||||
// (packet/transformer/proto/message/message.ts → GroupReactNotify); the
|
||||
// outermost message is preceded by a 7-byte prefix that must be stripped
|
||||
// before decoding (see the call site).
|
||||
|
||||
export const GroupReactionDataInnerDataTargetSchema = {
|
||||
seq: { field: 1, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataContentSchema = {
|
||||
code: { field: 1, type: 'string' as const },
|
||||
count: { field: 3, type: 'uint32' as const },
|
||||
operatorUid: { field: 4, type: 'string' as const },
|
||||
type: { field: 5, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataInnerDataSchema = {
|
||||
groupReactionTarget: { field: 2, type: 'message' as const, schema: GroupReactionDataInnerDataTargetSchema },
|
||||
groupReactionDataContent: { field: 3, type: 'message' as const, schema: GroupReactionDataContentSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataInnerSchema = {
|
||||
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerDataSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataSchema = {
|
||||
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactNotifySchema = {
|
||||
groupUin: { field: 4, type: 'uint64' as const },
|
||||
field13: { field: 13, type: 'uint32' as const },
|
||||
groupReactionData: { field: 44, type: 'message' as const, schema: GroupReactionDataSchema },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -190,10 +190,14 @@ export const OidbUserInfoKeySchema = {
|
||||
key: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// Field 2 USED to be `field2: uint32 = 0`, but newer QQ NT versions
|
||||
// reinterpret field 2 as `uid: string` / `openid: string` and reject
|
||||
// the request with "one of uid/openid is invaild" when a varint 0
|
||||
// shows up there. NapCat's schema (Oidb.0XFE1_2.ts) only emits `uin`
|
||||
// and `key[]`, so we match that exactly.
|
||||
export const OidbUserInfoRequestSchema = {
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbTwoNumberSchema = {
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
convertGroupFileUpload,
|
||||
convertGroupMemberJoin,
|
||||
convertGroupMemberLeave,
|
||||
convertGroupMsgEmojiLike,
|
||||
convertGroupMute,
|
||||
convertGroupPoke,
|
||||
convertGroupRecall,
|
||||
@@ -98,6 +99,7 @@ export async function convertEvent(
|
||||
case 'group_essence': return convertGroupEssence(ctx, event);
|
||||
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
|
||||
case 'friend_add': return convertFriendAdd(ctx, event);
|
||||
case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event);
|
||||
|
||||
// Requests.
|
||||
case 'friend_request': return convertFriendRequest(ctx, event);
|
||||
|
||||
@@ -21,6 +21,7 @@ type GroupPoke = Extract<QQEventVariant, { kind: 'group_poke' }>;
|
||||
type GroupEssence = Extract<QQEventVariant, { kind: 'group_essence' }>;
|
||||
type GroupFileUpload = Extract<QQEventVariant, { kind: 'group_file_upload' }>;
|
||||
type FriendAdd = Extract<QQEventVariant, { kind: 'friend_add' }>;
|
||||
type GroupMsgEmojiLike = Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>;
|
||||
|
||||
export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject {
|
||||
return {
|
||||
@@ -187,3 +188,32 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO
|
||||
user_id: event.userUin,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Group message emoji reaction notice. Matches the gocqhttp / NapCat
|
||||
* extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot
|
||||
* v11 standard has no slot for reactions and that's what every
|
||||
* downstream framework keys off.
|
||||
*/
|
||||
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
|
||||
// Reconstruct the OneBot message_id we originally minted for the
|
||||
// reacted-to message. hashMessageIdInt32 is deterministic so the ID
|
||||
// matches whatever the client received at receive-time, even when
|
||||
// the message has fallen out of our store.
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_msg_emoji_like',
|
||||
sub_type: event.isAdd ? 'add' : 'remove',
|
||||
group_id: event.groupId,
|
||||
user_id: event.operatorUin,
|
||||
operator_id: event.operatorUin,
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
likes: [{ emoji_id: event.emojiId, count: event.count }],
|
||||
};
|
||||
}
|
||||
@@ -73,6 +73,7 @@ const NOTICE_KINDS = [
|
||||
'group_essence',
|
||||
'group_file_upload',
|
||||
'friend_add',
|
||||
'group_msg_emoji_like',
|
||||
] as const satisfies readonly QQEventVariant['kind'][];
|
||||
|
||||
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
|
||||
|
||||
@@ -198,6 +198,8 @@ export function formatEvent(identity: IdentityService, event: QQEventVariant): s
|
||||
return `群邀请 ${formatUser(identity, undefined, event.fromUin)} -> ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_essence':
|
||||
return `精华 ${formatGroup(identity, event.groupId)} | ${event.set ? '+' : '-'}精华`;
|
||||
case 'group_msg_emoji_like':
|
||||
return `表情回应 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.operatorUin, event.operatorUid)} ${event.isAdd ? '+' : '-'}[${event.emojiId}] msgSeq=${event.msgSeq}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
// Tests for the Event0x2DC subType=16 (GroupMsgEmojiLike) end-to-end:
|
||||
// - decoder strips the 7-byte prefix and decodes GroupReactNotify
|
||||
// - field13==35 yields a GroupMsgEmojiLikeEvent
|
||||
// - field13!=35 surfaces under MsgPush.Unknown and emits nothing
|
||||
// - converter shape matches the gocqhttp / NapCat extension layout
|
||||
// - formatEvent prints something readable in the [Event] log
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { protoEncode } from '../src/protobuf/decode';
|
||||
import { GroupReactNotifySchema } from '../src/bridge/proto/notify';
|
||||
import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc';
|
||||
import type { MsgPushContext } from '../src/bridge/msg-push/context';
|
||||
import { IdentityService } from '../src/bridge/identity-service';
|
||||
import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '../src/bridge/events';
|
||||
import { convertGroupMsgEmojiLike } from '../src/onebot/event-converter/to-notice';
|
||||
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/onebot/message-id';
|
||||
import { formatEvent } from '../src/utils/event-format';
|
||||
import { subscribeLogs, type LogEntry } from '../src/utils/logger';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const GROUP_ID = 123456789;
|
||||
|
||||
function makeIdentity(): IdentityService {
|
||||
return IdentityService.memory(SELF_UIN);
|
||||
}
|
||||
|
||||
/** Build the raw bytes QQ would push into ctx.content for subType=16:
|
||||
* a 7-byte magic prefix followed by an encoded GroupReactNotify. */
|
||||
function buildReactContent(notify: Record<string, unknown>): Uint8Array {
|
||||
const prefix = new Uint8Array([0, 0, 0, 0, 0, 0, 0]);
|
||||
const body = protoEncode(notify as never, GroupReactNotifySchema);
|
||||
const out = new Uint8Array(prefix.length + body.length);
|
||||
out.set(prefix, 0);
|
||||
out.set(body, prefix.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext {
|
||||
return {
|
||||
head: { msgType: 732, subType: 16, sequence: 0, timestamp: 1735000000, msgId: 0 },
|
||||
fromUin: 0,
|
||||
fromUid: '',
|
||||
selfUin: Number(SELF_UIN),
|
||||
content,
|
||||
body: undefined,
|
||||
responseHead: undefined,
|
||||
identity,
|
||||
};
|
||||
}
|
||||
|
||||
describe('decodeEvent0x2DC subType=16 — GroupMsgEmojiLike', () => {
|
||||
it('decodes a field13=35 react add into a GroupMsgEmojiLikeEvent', () => {
|
||||
const content = buildReactContent({
|
||||
groupUin: BigInt(GROUP_ID),
|
||||
field13: 35,
|
||||
groupReactionData: {
|
||||
data: {
|
||||
data: {
|
||||
groupReactionTarget: { seq: 4242n },
|
||||
groupReactionDataContent: {
|
||||
code: '76',
|
||||
count: 1,
|
||||
operatorUid: 'u_operator_xxx',
|
||||
type: 1, // add
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
|
||||
expect(event).toBeDefined();
|
||||
expect(event.kind).toBe('group_msg_emoji_like');
|
||||
expect(event.groupId).toBe(GROUP_ID);
|
||||
expect(event.operatorUid).toBe('u_operator_xxx');
|
||||
expect(event.emojiId).toBe('76');
|
||||
expect(event.msgSeq).toBe(4242);
|
||||
expect(event.count).toBe(1);
|
||||
expect(event.isAdd).toBe(true);
|
||||
});
|
||||
|
||||
it('decodes type=2 as react remove (isAdd=false)', () => {
|
||||
const content = buildReactContent({
|
||||
groupUin: BigInt(GROUP_ID),
|
||||
field13: 35,
|
||||
groupReactionData: {
|
||||
data: {
|
||||
data: {
|
||||
groupReactionTarget: { seq: 1n },
|
||||
groupReactionDataContent: {
|
||||
code: '⭐',
|
||||
count: 1,
|
||||
operatorUid: 'u_x',
|
||||
type: 2,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
|
||||
expect(event.isAdd).toBe(false);
|
||||
expect(event.emojiId).toBe('⭐');
|
||||
});
|
||||
|
||||
it('drops the packet and logs to MsgPush.Unknown when field13 is not 35', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
|
||||
const content = buildReactContent({
|
||||
groupUin: BigInt(GROUP_ID),
|
||||
field13: 99, // not 35
|
||||
groupReactionData: {
|
||||
data: { data: { groupReactionDataContent: { code: 'x', operatorUid: 'u_y' } } },
|
||||
},
|
||||
});
|
||||
|
||||
const result = decodeEvent0x2DC(makeCtx(content));
|
||||
unsub();
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
const unknown = captured.find((e) =>
|
||||
e.scope === 'MsgPush.Unknown' && /field13=99/.test(e.message));
|
||||
expect(unknown).toBeDefined();
|
||||
});
|
||||
|
||||
it('returns empty when content is shorter than the prefix length', () => {
|
||||
const tooShort = new Uint8Array([1, 2, 3]); // < 7 bytes
|
||||
expect(decodeEvent0x2DC(makeCtx(tooShort))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertGroupMsgEmojiLike — OneBot notice shape', () => {
|
||||
const baseEvent: GroupMsgEmojiLikeEvent = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: 1735000000,
|
||||
selfUin: 10001,
|
||||
groupId: 123456789,
|
||||
operatorUin: 99999,
|
||||
operatorUid: 'u_x',
|
||||
msgSeq: 4242,
|
||||
emojiId: '76',
|
||||
count: 1,
|
||||
isAdd: true,
|
||||
};
|
||||
|
||||
// Real production wiring puts a hashMessageIdInt32-based resolver
|
||||
// on the ctx; mirror that so message_id is the same value the
|
||||
// bot would have minted for the original message.
|
||||
const ctx = {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: (_isGroup: boolean, sessionId: number, sequence: number, eventName: string) =>
|
||||
hashMessageIdInt32(sequence, sessionId, eventName),
|
||||
mediaSegmentSink: null,
|
||||
} as never;
|
||||
|
||||
it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', () => {
|
||||
const out = convertGroupMsgEmojiLike(ctx, baseEvent);
|
||||
expect(out.post_type).toBe('notice');
|
||||
expect(out.notice_type).toBe('group_msg_emoji_like');
|
||||
expect(out.sub_type).toBe('add');
|
||||
expect(out.group_id).toBe(123456789);
|
||||
expect(out.user_id).toBe(99999);
|
||||
expect(out.operator_id).toBe(99999);
|
||||
expect(out.message_seq).toBe(4242);
|
||||
expect(out.message_id).toBe(hashMessageIdInt32(4242, 123456789, GROUP_MESSAGE_EVENT));
|
||||
expect(out.likes).toEqual([{ emoji_id: '76', count: 1 }]);
|
||||
});
|
||||
|
||||
it('flips sub_type to remove when isAdd is false', () => {
|
||||
const out = convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false });
|
||||
expect(out.sub_type).toBe('remove');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatEvent — group_msg_emoji_like', () => {
|
||||
let savedLevel: string | undefined;
|
||||
beforeEach(() => { savedLevel = process.env.SNOWLUMA_LOG_LEVEL; });
|
||||
afterEach(() => {
|
||||
if (savedLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_LEVEL = savedLevel;
|
||||
});
|
||||
|
||||
it('renders a one-line summary with group, operator and emoji id', () => {
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.rememberGroups([{
|
||||
groupId: GROUP_ID, groupName: 'TestGroup', remark: '',
|
||||
memberCount: 1, memberMax: 500, members: new Map(),
|
||||
}]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [{
|
||||
uin: 99999, uid: 'u_x', nickname: 'Alice', card: '',
|
||||
role: 'member', level: 0, title: '',
|
||||
joinTime: 0, lastSentTime: 0, shutUpTime: 0,
|
||||
}]);
|
||||
|
||||
const event: QQEventVariant = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: 0, selfUin: Number(SELF_UIN),
|
||||
groupId: GROUP_ID,
|
||||
operatorUin: 99999, operatorUid: 'u_x',
|
||||
msgSeq: 100, emojiId: '76', count: 1, isAdd: true,
|
||||
};
|
||||
|
||||
const line = formatEvent(identity, event);
|
||||
expect(line).toBeDefined();
|
||||
expect(line).toContain('TestGroup');
|
||||
expect(line).toContain('Alice');
|
||||
expect(line).toContain('[76]');
|
||||
expect(line).toContain('msgSeq=100');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/runtime",
|
||||
"version": "1.8.4",
|
||||
"version": "1.8.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"version": "1.8.4",
|
||||
"version": "1.8.5",
|
||||
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"version": "1.8.4",
|
||||
"version": "1.8.5",
|
||||
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/websocket",
|
||||
"version": "1.8.4",
|
||||
"version": "1.8.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "webui",
|
||||
"private": true,
|
||||
"version": "1.8.4",
|
||||
"version": "1.8.5",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
// Account selector strip. Collapsing to a 56px avatar-only column keeps
|
||||
// the right-side editor breathing on smaller screens; expanded it shows
|
||||
// nickname + UIN like the original. Selection routes through
|
||||
// `requestSwitchUin` so the dirty-modify guard still gates the switch.
|
||||
|
||||
import { motion } from 'motion/react';
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { QQInfo } from '@/types';
|
||||
|
||||
function qqAvatarUrl(uin: string) {
|
||||
return `/avatar/${encodeURIComponent(uin)}`;
|
||||
}
|
||||
|
||||
interface AccountSidebarProps {
|
||||
accounts: QQInfo[];
|
||||
selectedUin: string | null;
|
||||
onSelect: (uin: string) => void;
|
||||
collapsed: boolean;
|
||||
onToggleCollapsed: () => void;
|
||||
}
|
||||
|
||||
export function AccountSidebar({
|
||||
accounts,
|
||||
selectedUin,
|
||||
onSelect,
|
||||
collapsed,
|
||||
onToggleCollapsed,
|
||||
}: AccountSidebarProps) {
|
||||
return (
|
||||
<motion.aside
|
||||
animate={{ width: collapsed ? 56 : 248 }}
|
||||
transition={{ type: 'spring', stiffness: 300, damping: 32 }}
|
||||
className="shrink-0 rounded-lg border bg-card/40"
|
||||
>
|
||||
<div className={cn('flex items-center', collapsed ? 'justify-center px-1.5 py-2' : 'justify-between px-3 py-2')}>
|
||||
{!collapsed && <span className="text-xs font-medium text-muted-foreground">在线连接</span>}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onToggleCollapsed}
|
||||
aria-label={collapsed ? '展开账号列表' : '收起账号列表'}
|
||||
className="text-muted-foreground"
|
||||
>
|
||||
{collapsed ? <ChevronRight className="size-4" /> : <ChevronLeft className="size-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{accounts.length === 0 ? (
|
||||
<p className={cn('py-6 text-center text-xs text-muted-foreground', collapsed && 'px-1')}>
|
||||
{collapsed ? '—' : '暂无在线会话'}
|
||||
</p>
|
||||
) : (
|
||||
<ScrollArea className="max-h-[70vh]" viewportClassName="[&>div]:!block">
|
||||
<TooltipProvider delayDuration={300}>
|
||||
<div className={cn('flex flex-col gap-1', collapsed ? 'px-1.5 pb-2' : 'px-2 pb-2')}>
|
||||
{accounts.map((q) => {
|
||||
const isActive = selectedUin === q.uin;
|
||||
const button = (
|
||||
<motion.button
|
||||
key={q.uin}
|
||||
type="button"
|
||||
whileHover={{ scale: 1.01 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
onClick={() => onSelect(q.uin)}
|
||||
className={cn(
|
||||
'flex items-center gap-2.5 rounded-lg border text-left transition-colors cursor-pointer',
|
||||
collapsed ? 'justify-center p-1.5' : 'px-2.5 py-2',
|
||||
isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<Avatar size={collapsed ? 32 : 28}>
|
||||
<AvatarImage src={qqAvatarUrl(q.uin)} alt={q.nickname || q.uin} />
|
||||
<AvatarFallback>{(q.nickname || q.uin).slice(0, 2)}</AvatarFallback>
|
||||
</Avatar>
|
||||
{!collapsed && (
|
||||
<div className="min-w-0 flex-1">
|
||||
<div
|
||||
className={cn('truncate text-sm font-medium', isActive ? 'text-primary' : 'text-foreground')}
|
||||
>
|
||||
{q.nickname || q.uin}
|
||||
</div>
|
||||
<div className="truncate font-mono text-[10px] text-muted-foreground tabular-nums">
|
||||
{q.uin}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.button>
|
||||
);
|
||||
return collapsed ? (
|
||||
<Tooltip key={q.uin}>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent side="right" sideOffset={8}>
|
||||
<div className="flex flex-col leading-tight">
|
||||
<span className="font-medium">{q.nickname || q.uin}</span>
|
||||
<span className="font-mono text-[10px] text-muted-foreground tabular-nums">{q.uin}</span>
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : (
|
||||
button
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</ScrollArea>
|
||||
)}
|
||||
</motion.aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// Per-network-kind metadata: localized title, summary projector for the
|
||||
// list view, and factory for "create new" defaults. Centralised here so the
|
||||
// page / list / dialog all agree on naming and shape and a new adapter
|
||||
// kind only needs one entry in NETWORK_TABS to wire end-to-end.
|
||||
|
||||
import type {
|
||||
HttpClientNetwork,
|
||||
HttpServerNetwork,
|
||||
MessageFormat,
|
||||
NetworkKind,
|
||||
OneBotNetworks,
|
||||
WsClientNetwork,
|
||||
WsRole,
|
||||
WsServerNetwork,
|
||||
} from '@/types';
|
||||
|
||||
export type TabKey = 'general' | NetworkKind;
|
||||
|
||||
export interface NetworkTabDescriptor<K extends NetworkKind> {
|
||||
key: K;
|
||||
/** Tab label and dialog title prefix. */
|
||||
title: string;
|
||||
/** Short subtitle shown under the tab when active. */
|
||||
description: string;
|
||||
/** Singular noun for "新建 / 编辑 X". */
|
||||
noun: string;
|
||||
/** Project the adapter into a short list-card summary string. */
|
||||
summarize: (item: OneBotNetworks[K][number]) => string;
|
||||
/** Factory producing a fresh adapter with a unique suffix in its name. */
|
||||
defaultEntry: (suffix: number) => OneBotNetworks[K][number];
|
||||
}
|
||||
|
||||
function genToken(): string {
|
||||
const bytes = new Uint8Array(32);
|
||||
globalThis.crypto.getRandomValues(bytes);
|
||||
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
const httpServersTab: NetworkTabDescriptor<'httpServers'> = {
|
||||
key: 'httpServers',
|
||||
title: 'HTTP API',
|
||||
description: '本地监听 HTTP 端口,OneBot 客户端发起请求',
|
||||
noun: 'HTTP API 服务',
|
||||
summarize: (it: HttpServerNetwork) => {
|
||||
const host = it.host?.trim() || '0.0.0.0';
|
||||
const path = (it.path?.trim() || '/').replace(/^\/?/, '/');
|
||||
return `${host}:${it.port}${path}`;
|
||||
},
|
||||
defaultEntry: (suffix): HttpServerNetwork => ({
|
||||
name: `http-${suffix}`,
|
||||
host: '0.0.0.0',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
accessToken: genToken(),
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
}),
|
||||
};
|
||||
|
||||
const httpClientsTab: NetworkTabDescriptor<'httpClients'> = {
|
||||
key: 'httpClients',
|
||||
title: 'HTTP 客户端',
|
||||
description: '主动向远端 URL POST 推送事件',
|
||||
noun: 'HTTP 推送客户端',
|
||||
summarize: (it: HttpClientNetwork) => it.url || '(未设置 URL)',
|
||||
defaultEntry: (suffix): HttpClientNetwork => ({
|
||||
name: `httppost-${suffix}`,
|
||||
url: 'http://127.0.0.1:5700',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
}),
|
||||
};
|
||||
|
||||
const wsServersTab: NetworkTabDescriptor<'wsServers'> = {
|
||||
key: 'wsServers',
|
||||
title: 'WS 服务端',
|
||||
description: '本地监听 WebSocket 端口,客户端建立持久连接',
|
||||
noun: 'WebSocket 服务',
|
||||
summarize: (it: WsServerNetwork) => {
|
||||
const host = it.host?.trim() || '0.0.0.0';
|
||||
const path = (it.path?.trim() || '/').replace(/^\/?/, '/');
|
||||
const role = it.role ?? 'Universal';
|
||||
return `${host}:${it.port}${path} · ${role}`;
|
||||
},
|
||||
defaultEntry: (suffix): WsServerNetwork => ({
|
||||
name: `ws-${suffix}`,
|
||||
host: '0.0.0.0',
|
||||
port: 3001,
|
||||
path: '/',
|
||||
role: 'Universal' as WsRole,
|
||||
accessToken: genToken(),
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
}),
|
||||
};
|
||||
|
||||
const wsClientsTab: NetworkTabDescriptor<'wsClients'> = {
|
||||
key: 'wsClients',
|
||||
title: 'WS 客户端',
|
||||
description: '主动连接到外部 WebSocket 服务器(reverse-ws)',
|
||||
noun: 'WebSocket 反向客户端',
|
||||
summarize: (it: WsClientNetwork) => {
|
||||
const role = it.role ?? 'Universal';
|
||||
return `${it.url || '(未设置 URL)'} · ${role}`;
|
||||
},
|
||||
defaultEntry: (suffix): WsClientNetwork => ({
|
||||
name: `wsclient-${suffix}`,
|
||||
url: 'ws://127.0.0.1:8080/ws',
|
||||
role: 'Universal' as WsRole,
|
||||
reconnectIntervalMs: 5000,
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* Order here drives both the tab strip order and the dialog/page wiring.
|
||||
* Each entry stays strictly typed on its kind so callers get the narrow
|
||||
* adapter shape (no NetworkBase widening).
|
||||
*/
|
||||
export const NETWORK_TABS = {
|
||||
httpServers: httpServersTab,
|
||||
httpClients: httpClientsTab,
|
||||
wsServers: wsServersTab,
|
||||
wsClients: wsClientsTab,
|
||||
} satisfies { [K in NetworkKind]: NetworkTabDescriptor<K> };
|
||||
|
||||
export const NETWORK_TAB_ORDER: NetworkKind[] = [
|
||||
'httpServers',
|
||||
'httpClients',
|
||||
'wsServers',
|
||||
'wsClients',
|
||||
];
|
||||
|
||||
export const ALL_TABS: TabKey[] = ['general', ...NETWORK_TAB_ORDER];
|
||||
|
||||
/**
|
||||
* Find the smallest suffix N (starting at list.length + 1) such that
|
||||
* `factory(N).name` doesn't collide with any existing adapter. Used by
|
||||
* the page to seed a fresh-default adapter when the user clicks "create".
|
||||
*/
|
||||
export function nextUniqueSuffix(
|
||||
networks: { name: string }[],
|
||||
factory: (suffix: number) => { name: string },
|
||||
): number {
|
||||
const used = new Set(networks.map((n) => n.name));
|
||||
let suffix = networks.length + 1;
|
||||
while (used.has(factory(suffix).name)) suffix += 1;
|
||||
return suffix;
|
||||
}
|
||||
|
||||
// Re-exported for callers that just need to type a generic adapter.
|
||||
export interface AdapterCommon {
|
||||
name: string;
|
||||
enabled?: boolean;
|
||||
accessToken?: string;
|
||||
messageFormat: MessageFormat;
|
||||
reportSelfMessage: boolean;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// "通用设置" tab — fields that apply to the whole OneBotInstance rather
|
||||
// than any specific adapter. Currently just the music-sign service URL,
|
||||
// but the layout has room for additional cross-cutting toggles.
|
||||
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import type { OneBotConfig } from '@/types';
|
||||
|
||||
interface GeneralSettingsTabProps {
|
||||
config: OneBotConfig;
|
||||
onChange: (next: OneBotConfig) => void;
|
||||
}
|
||||
|
||||
export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5 rounded-lg border bg-card/40 p-4">
|
||||
<Label>音乐签名服务 URL</Label>
|
||||
<Input
|
||||
type="url"
|
||||
placeholder="留空则不启用"
|
||||
value={config.musicSignUrl ?? ''}
|
||||
onChange={(e) => onChange({ ...config, musicSignUrl: e.target.value || undefined })}
|
||||
/>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
// Modal editor used for both "create" and "edit". Holds a local draft
|
||||
// copy of the adapter until the user clicks save (so cancel really does
|
||||
// throw away changes). Validation is minimal — blank-name and dup-name
|
||||
// disable the save button; everything else is best-effort coercion.
|
||||
|
||||
import { useRef, useState } from 'react';
|
||||
import { Check, Copy, Eye, EyeOff } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type {
|
||||
HttpClientNetwork,
|
||||
HttpServerNetwork,
|
||||
MessageFormat,
|
||||
NetworkKind,
|
||||
OneBotNetworks,
|
||||
WsClientNetwork,
|
||||
WsRole,
|
||||
WsServerNetwork,
|
||||
} from '@/types';
|
||||
import { NETWORK_TABS } from './defaults';
|
||||
|
||||
type AnyAdapter<K extends NetworkKind> = OneBotNetworks[K][number];
|
||||
|
||||
interface NodeEditDialogProps<K extends NetworkKind> {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
kind: K;
|
||||
/** Initial draft state — caller seeds it with `defaultEntry` for create
|
||||
* or the existing item for edit. */
|
||||
initial: AnyAdapter<K>;
|
||||
/** True when editing an existing adapter (drives title + button copy). */
|
||||
isEdit: boolean;
|
||||
/** Names of every other adapter in the same list, for duplicate check. */
|
||||
otherNames: string[];
|
||||
onSubmit: (item: AnyAdapter<K>) => void;
|
||||
}
|
||||
|
||||
export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps<K>) {
|
||||
const { open, onOpenChange, kind, initial, isEdit, otherNames, onSubmit } = props;
|
||||
const tab = NETWORK_TABS[kind];
|
||||
|
||||
// Local draft. The parent unmounts this component on close so each
|
||||
// open gets a fresh `initial` via useState's lazy init — no effect-based
|
||||
// resync needed, which keeps the lifecycle linear.
|
||||
const [draft, setDraft] = useState<AnyAdapter<K>>(initial);
|
||||
|
||||
const trimmedName = draft.name?.trim() ?? '';
|
||||
const blankName = trimmedName.length === 0;
|
||||
const duplicateName = !blankName && otherNames.includes(trimmedName);
|
||||
|
||||
const canSave = !blankName && !duplicateName;
|
||||
|
||||
const patch = (changes: Partial<AnyAdapter<K>>) => setDraft({ ...draft, ...changes } as AnyAdapter<K>);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? `编辑 ${tab.noun}` : `新建 ${tab.noun}`}</DialogTitle>
|
||||
<DialogDescription>{tab.description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<Field
|
||||
label="名称"
|
||||
placeholder="自定义"
|
||||
value={draft.name}
|
||||
onChange={(v) => patch({ name: v } as Partial<AnyAdapter<K>>)}
|
||||
error={blankName ? '请填写名称' : duplicateName ? '名称与其它节点重复' : undefined}
|
||||
/>
|
||||
|
||||
<KindFields kind={kind} draft={draft} patch={patch} />
|
||||
|
||||
<TokenField
|
||||
label="授权 Token"
|
||||
placeholder="不填则无密码"
|
||||
value={draft.accessToken}
|
||||
onChange={(v) => patch({ accessToken: v || undefined } as Partial<AnyAdapter<K>>)}
|
||||
/>
|
||||
|
||||
<div className="grid gap-3 border-t pt-3 sm:grid-cols-2">
|
||||
<SegmentedField
|
||||
label="消息格式"
|
||||
value={(draft.messageFormat ?? 'array') as MessageFormat}
|
||||
options={FORMAT_OPTIONS}
|
||||
onChange={(v) => patch({ messageFormat: v } as Partial<AnyAdapter<K>>)}
|
||||
/>
|
||||
<SegmentedField
|
||||
label="上报自身消息"
|
||||
value={draft.reportSelfMessage ? 'on' : 'off'}
|
||||
options={REPORT_OPTIONS}
|
||||
onChange={(v) => patch({ reportSelfMessage: v === 'on' } as Partial<AnyAdapter<K>>)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border bg-card/40 p-3">
|
||||
<div>
|
||||
<Label className="text-sm">启用</Label>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
|
||||
关闭后保存即可保留配置但不启动该节点
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={draft.enabled !== false}
|
||||
onChange={(v) =>
|
||||
patch({ enabled: v ? undefined : false } as Partial<AnyAdapter<K>>)
|
||||
}
|
||||
ariaLabel="启用"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
disabled={!canSave}
|
||||
onClick={() => {
|
||||
const cleaned = { ...draft, name: trimmedName } as AnyAdapter<K>;
|
||||
onSubmit(cleaned);
|
||||
onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
{isEdit ? '保存修改' : '创建节点'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── kind-specific field strips ───────────────
|
||||
|
||||
interface KindFieldsProps<K extends NetworkKind> {
|
||||
kind: K;
|
||||
draft: AnyAdapter<K>;
|
||||
patch: (changes: Partial<AnyAdapter<K>>) => void;
|
||||
}
|
||||
|
||||
function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsProps<K>) {
|
||||
// Per-branch narrowing — TS can't follow the generic relationship so
|
||||
// each arm casts once. Field components receive specific shapes.
|
||||
if (kind === 'httpServers') {
|
||||
const it = draft as HttpServerNetwork;
|
||||
const set = patch as (c: Partial<HttpServerNetwork>) => void;
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
|
||||
<Field
|
||||
label="主机"
|
||||
placeholder="0.0.0.0"
|
||||
value={it.host}
|
||||
onChange={(v) => set({ host: v || undefined })}
|
||||
/>
|
||||
<Field
|
||||
label="端口"
|
||||
type="number"
|
||||
value={it.port}
|
||||
onChange={(v) => set({ port: Number(v) || 0 })}
|
||||
/>
|
||||
<Field
|
||||
label="路径"
|
||||
placeholder="/"
|
||||
value={it.path}
|
||||
onChange={(v) => set({ path: v || undefined })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (kind === 'httpClients') {
|
||||
const it = draft as HttpClientNetwork;
|
||||
const set = patch as (c: Partial<HttpClientNetwork>) => void;
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_140px]">
|
||||
<Field
|
||||
label="目标 URL"
|
||||
type="url"
|
||||
placeholder="http://..."
|
||||
value={it.url}
|
||||
onChange={(v) => set({ url: v })}
|
||||
/>
|
||||
<Field
|
||||
label="超时 (ms)"
|
||||
type="number"
|
||||
placeholder="5000"
|
||||
value={it.timeoutMs}
|
||||
onChange={(v) => set({ timeoutMs: Number(v) || undefined })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (kind === 'wsServers') {
|
||||
const it = draft as WsServerNetwork;
|
||||
const set = patch as (c: Partial<WsServerNetwork>) => void;
|
||||
return (
|
||||
<>
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
|
||||
<Field
|
||||
label="主机"
|
||||
placeholder="0.0.0.0"
|
||||
value={it.host}
|
||||
onChange={(v) => set({ host: v || undefined })}
|
||||
/>
|
||||
<Field
|
||||
label="端口"
|
||||
type="number"
|
||||
value={it.port}
|
||||
onChange={(v) => set({ port: Number(v) || 0 })}
|
||||
/>
|
||||
<Field
|
||||
label="路径"
|
||||
placeholder="/"
|
||||
value={it.path}
|
||||
onChange={(v) => set({ path: v || undefined })}
|
||||
/>
|
||||
</div>
|
||||
<SelectField
|
||||
label="角色"
|
||||
value={(it.role ?? 'Universal') as WsRole}
|
||||
options={WS_ROLE_OPTIONS}
|
||||
onChange={(v) => set({ role: v })}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (kind === 'wsClients') {
|
||||
const it = draft as WsClientNetwork;
|
||||
const set = patch as (c: Partial<WsClientNetwork>) => void;
|
||||
return (
|
||||
<>
|
||||
<Field
|
||||
label="目标 URL"
|
||||
type="url"
|
||||
placeholder="ws://..."
|
||||
value={it.url}
|
||||
onChange={(v) => set({ url: v })}
|
||||
/>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<SelectField
|
||||
label="角色"
|
||||
value={(it.role ?? 'Universal') as WsRole}
|
||||
options={WS_ROLE_OPTIONS}
|
||||
onChange={(v) => set({ role: v })}
|
||||
/>
|
||||
<Field
|
||||
label="重连间隔 (ms)"
|
||||
type="number"
|
||||
value={it.reconnectIntervalMs}
|
||||
onChange={(v) => set({ reconnectIntervalMs: Number(v) || undefined })}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─────────────── shared form bits ───────────────
|
||||
|
||||
interface FieldProps {
|
||||
label: string;
|
||||
value: string | number | undefined;
|
||||
onChange: (v: string) => void;
|
||||
placeholder?: string;
|
||||
type?: 'text' | 'number' | 'url';
|
||||
error?: string;
|
||||
}
|
||||
|
||||
function Field({ label, value, onChange, placeholder, type = 'text', error }: FieldProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{label}</Label>
|
||||
<Input
|
||||
type={type}
|
||||
value={value ?? ''}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
className={cn(error && 'border-destructive focus-visible:ring-destructive/40')}
|
||||
/>
|
||||
{error && <p className="text-[11px] text-destructive">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface TokenFieldProps {
|
||||
label: string;
|
||||
value: string | undefined;
|
||||
onChange: (v: string) => void;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
/** Insecure-context clipboard fallback. Returns true on success.
|
||||
* Cast through a local alias so ts(6387) doesn't flag the call site —
|
||||
* the deprecation tag is on the live signature and we know we're using
|
||||
* the still-supported legacy form on purpose. */
|
||||
function legacyCopyToClipboard(value: string): boolean {
|
||||
try {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = value;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
const exec = (document as unknown as { execCommand(cmd: string): boolean }).execCommand;
|
||||
const ok = exec.call(document, 'copy');
|
||||
document.body.removeChild(ta);
|
||||
return ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Password-style input for the access token. Hidden by default to keep
|
||||
* the value out of over-the-shoulder reads / screenshots; an eye toggle
|
||||
* unmasks it and a copy button shoves the current value to the system
|
||||
* clipboard with a short "已复制" confirmation flash.
|
||||
*/
|
||||
function TokenField({ label, value, onChange, placeholder }: TokenFieldProps) {
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<number | null>(null);
|
||||
|
||||
const handleCopy = async () => {
|
||||
if (!value) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
} catch {
|
||||
// navigator.clipboard is undefined on insecure origins (LAN HTTP
|
||||
// outside localhost). Fall back to a transient textarea +
|
||||
// document.execCommand('copy'). The latter is deprecated but every
|
||||
// current browser still honours it and there is no modern
|
||||
// replacement for non-secure-context clipboard writes.
|
||||
if (!legacyCopyToClipboard(value)) return;
|
||||
}
|
||||
setCopied(true);
|
||||
if (copiedTimerRef.current != null) window.clearTimeout(copiedTimerRef.current);
|
||||
copiedTimerRef.current = window.setTimeout(() => {
|
||||
setCopied(false);
|
||||
copiedTimerRef.current = null;
|
||||
}, 1400);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{label}</Label>
|
||||
<div className="flex gap-1.5">
|
||||
<Input
|
||||
// Switch input type rather than masking the string so paste /
|
||||
// selection / autofill all behave like a native password field.
|
||||
type={visible ? 'text' : 'password'}
|
||||
value={value ?? ''}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className="flex-1 font-mono"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleCopy}
|
||||
disabled={!value}
|
||||
aria-label={copied ? '已复制' : '复制'}
|
||||
title={copied ? '已复制' : '复制'}
|
||||
>
|
||||
{copied ? <Check className="size-4 text-success" /> : <Copy className="size-4" />}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => setVisible((v) => !v)}
|
||||
aria-label={visible ? '隐藏' : '显示'}
|
||||
title={visible ? '隐藏' : '显示'}
|
||||
>
|
||||
{visible ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SegmentedOption<T extends string> {
|
||||
value: T;
|
||||
label: string;
|
||||
}
|
||||
|
||||
function SegmentedField<T extends string>({
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: T;
|
||||
options: ReadonlyArray<SegmentedOption<T>>;
|
||||
onChange: (v: T) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{label}</Label>
|
||||
<div className="flex flex-wrap gap-1 rounded-md border bg-muted/30 p-1">
|
||||
{options.map((opt) => {
|
||||
const active = value === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => onChange(opt.value)}
|
||||
className={cn(
|
||||
'flex-1 rounded px-2.5 py-1 text-xs transition-colors cursor-pointer',
|
||||
active ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:bg-accent/50',
|
||||
)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectField<T extends string>({
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: T;
|
||||
options: ReadonlyArray<SegmentedOption<T>>;
|
||||
onChange: (v: T) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{label}</Label>
|
||||
<select
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value as T)}
|
||||
className="h-9 rounded-md border bg-background px-2 text-sm shadow-xs"
|
||||
>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ToggleSwitchProps {
|
||||
value: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={value ? 'true' : 'false'}
|
||||
aria-label={ariaLabel}
|
||||
onClick={() => onChange(!value)}
|
||||
className={cn(
|
||||
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border transition-colors',
|
||||
value ? 'border-primary bg-primary' : 'border-input bg-muted',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'inline-block size-4 rounded-full bg-background shadow-sm transition-transform',
|
||||
value ? 'translate-x-[22px]' : 'translate-x-1',
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const FORMAT_OPTIONS: ReadonlyArray<SegmentedOption<MessageFormat>> = [
|
||||
{ value: 'array', label: '数组' },
|
||||
{ value: 'string', label: 'CQ 码' },
|
||||
];
|
||||
|
||||
const REPORT_OPTIONS: ReadonlyArray<SegmentedOption<'on' | 'off'>> = [
|
||||
{ value: 'on', label: '开启' },
|
||||
{ value: 'off', label: '关闭' },
|
||||
];
|
||||
|
||||
const WS_ROLE_OPTIONS: ReadonlyArray<SegmentedOption<WsRole>> = [
|
||||
{ value: 'Universal', label: 'Universal' },
|
||||
{ value: 'Event', label: 'Event' },
|
||||
{ value: 'Api', label: 'Api' },
|
||||
];
|
||||
@@ -0,0 +1,130 @@
|
||||
// One row in the per-kind list view. Shows just enough to identify the
|
||||
// adapter at a glance (name + projected summary + token state + the two
|
||||
// flags) plus the inline enable toggle. Real editing always goes through
|
||||
// the dialog — there are no live-typed inputs here.
|
||||
|
||||
import { motion } from 'motion/react';
|
||||
import { Pencil, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { AdapterCommon } from './defaults';
|
||||
|
||||
interface NodeSummaryCardProps<T extends AdapterCommon> {
|
||||
item: T;
|
||||
summary: string;
|
||||
duplicateName: boolean;
|
||||
onToggleEnabled: (next: boolean) => void;
|
||||
onEdit: () => void;
|
||||
onDelete: () => void;
|
||||
}
|
||||
|
||||
export function NodeSummaryCard<T extends AdapterCommon>({
|
||||
item,
|
||||
summary,
|
||||
duplicateName,
|
||||
onToggleEnabled,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: NodeSummaryCardProps<T>) {
|
||||
const enabled = item.enabled !== false;
|
||||
const blankName = !item.name?.trim();
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className={cn(
|
||||
'flex flex-col gap-2 rounded-lg border bg-card/40 p-3 transition-opacity sm:flex-row sm:items-center sm:gap-3',
|
||||
!enabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className={cn('font-medium', blankName && 'text-destructive')}>
|
||||
{item.name || '(未命名)'}
|
||||
</span>
|
||||
{duplicateName && (
|
||||
<Badge variant="destructive" className="font-normal">名称重复</Badge>
|
||||
)}
|
||||
{!enabled && (
|
||||
<Badge variant="secondary" className="font-normal">已停用</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground tabular-nums">{summary}</div>
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
|
||||
<Badge variant="outline" className="font-normal">
|
||||
{item.messageFormat === 'string' ? 'CQ 码' : '数组'}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="font-normal">
|
||||
{item.reportSelfMessage ? '上报自身' : '不上报自身'}
|
||||
</Badge>
|
||||
{item.accessToken ? (
|
||||
<Badge variant="outline" className="font-normal">
|
||||
已设 Token
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="font-normal text-muted-foreground">
|
||||
无 Token
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 sm:gap-2 sm:justify-end">
|
||||
<ToggleSwitch
|
||||
value={enabled}
|
||||
onChange={onToggleEnabled}
|
||||
ariaLabel={`启用 ${item.name || '该节点'}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onEdit}
|
||||
aria-label="编辑"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Pencil className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onDelete}
|
||||
aria-label="删除"
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ToggleSwitchProps {
|
||||
value: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={value ? 'true' : 'false'}
|
||||
aria-label={ariaLabel}
|
||||
onClick={() => onChange(!value)}
|
||||
className={cn(
|
||||
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border transition-colors',
|
||||
value ? 'border-primary bg-primary' : 'border-input bg-muted',
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
className="inline-block size-4 rounded-full bg-background shadow-sm"
|
||||
animate={{ x: value ? 22 : 4 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user