Initial commit
This commit is contained in:
commit
b3ffbae005
118 files changed
+22436
No files matched your search
@@ -0,0 +1,94 @@
|
|||||||
|
name: Dev Build
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '**'
|
||||||
|
tags-ignore:
|
||||||
|
- 'v*'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: windows-latest
|
||||||
|
permissions:
|
||||||
|
actions: write
|
||||||
|
contents: read
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- name: "standard"
|
||||||
|
script: "build"
|
||||||
|
suffix: ""
|
||||||
|
- name: "webui"
|
||||||
|
script: "build:all"
|
||||||
|
suffix: "-WebUI"
|
||||||
|
steps:
|
||||||
|
- name: Delete old artifacts
|
||||||
|
uses: actions/github-script@v7
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
let page = 1;
|
||||||
|
while (true) {
|
||||||
|
const { data: { artifacts } } = await github.rest.actions.listArtifactsForRepo({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
per_page: 100,
|
||||||
|
page,
|
||||||
|
});
|
||||||
|
if (artifacts.length === 0) break;
|
||||||
|
for (const artifact of artifacts) {
|
||||||
|
await github.rest.actions.deleteArtifact({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
artifact_id: artifact.id,
|
||||||
|
});
|
||||||
|
console.log(`Deleted artifact: ${artifact.name}`);
|
||||||
|
}
|
||||||
|
page++;
|
||||||
|
}
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup pnpm
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 10.28.0
|
||||||
|
run_install: false
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22'
|
||||||
|
cache: 'pnpm'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Build project
|
||||||
|
run: pnpm run ${{ matrix.script }}
|
||||||
|
|
||||||
|
- name: Verify native files
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
if (!(Test-Path "dist\native\snowluma-win32-x64.node")) { throw "Missing dist\native\snowluma-win32-x64.node" }
|
||||||
|
if (!(Test-Path "dist\native\snowluma-win32-x64.dll")) { throw "Missing dist\native\snowluma-win32-x64.dll" }
|
||||||
|
|
||||||
|
- name: Bundle runtime dependencies
|
||||||
|
working-directory: dist
|
||||||
|
run: npm install --omit=dev
|
||||||
|
|
||||||
|
- name: Package artifact
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
|
||||||
|
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev${{ matrix.suffix }}.zip"
|
||||||
|
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: SnowLuma-dev-${{ github.sha }}${{ matrix.suffix }}
|
||||||
|
path: SnowLuma-dev${{ matrix.suffix }}.zip
|
||||||
|
retention-days: 3
|
||||||
|
overwrite: true
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
name: Build and Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- name: "win-x64"
|
||||||
|
script: "build"
|
||||||
|
- name: "win-x64-webui"
|
||||||
|
script: "build:all"
|
||||||
|
runs-on: windows-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup pnpm
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 10.28.0
|
||||||
|
run_install: false
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22'
|
||||||
|
cache: 'pnpm'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Build project
|
||||||
|
run: pnpm run ${{ matrix.script }}
|
||||||
|
|
||||||
|
- name: Verify native files
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
if (!(Test-Path "dist\native\snowluma-win32-x64.node")) { throw "Missing dist\native\snowluma-win32-x64.node" }
|
||||||
|
if (!(Test-Path "dist\native\snowluma-win32-x64.dll")) { throw "Missing dist\native\snowluma-win32-x64.dll" }
|
||||||
|
|
||||||
|
- name: Bundle runtime dependencies
|
||||||
|
working-directory: dist
|
||||||
|
run: npm install --omit=dev
|
||||||
|
|
||||||
|
- name: Package release
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
|
||||||
|
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.zip"
|
||||||
|
|
||||||
|
- name: Create GitHub Release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: SnowLuma-*.zip
|
||||||
|
generate_release_notes: true
|
||||||
|
draft: false
|
||||||
|
prerelease: ${{ contains(github.ref_name, '-') }}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
out
|
||||||
|
build
|
||||||
|
build-*
|
||||||
|
CMakePresets.json
|
||||||
|
|
||||||
|
# Compiled files
|
||||||
|
*.o
|
||||||
|
*.obj
|
||||||
|
*.exe
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
*.a
|
||||||
|
*.lib
|
||||||
|
|
||||||
|
# CMake
|
||||||
|
CMakeCache.txt
|
||||||
|
CMakeFiles/
|
||||||
|
cmake_install.cmake
|
||||||
|
compile_commands.json
|
||||||
|
_deps/
|
||||||
|
.claude
|
||||||
|
|
||||||
|
# Runtime generated
|
||||||
|
config.json
|
||||||
|
/node_modules
|
||||||
|
/dist
|
||||||
|
/.vscode
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# ❄️ SnowLuma
|
||||||
|
> Next Remote Protocol Framework.
|
||||||
|
|
||||||
|
|
||||||
|
## 关于项目
|
||||||
|
项目处于开发初期,仅支持部分功能,持续高速迭代中,仅支持有头。
|
||||||
|
|
||||||
|
## 鸣谢
|
||||||
|
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
|
||||||
|
|
||||||
|
[NapCatQQ](https://github.com/NapNeko/NapCatQQ) - Scaner/Packet
|
||||||
|
|
||||||
|
## 辅助编程
|
||||||
|
|
||||||
|
推荐 Opus4.6 + Gemini3.1pro 对本项目辅助开发
|
||||||
|
|
||||||
|
本项目大量使用Ai技术。
|
||||||
|
|
||||||
|
## 加入我们
|
||||||
|
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||||
|
|
||||||
|
[SnowLuma-Tg](https://t.me/napcatqq)
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
node ./index.mjs
|
||||||
|
pause
|
||||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"name": "snowluma",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"main": "index.mjs",
|
||||||
|
"dependencies": {
|
||||||
|
"ws": "^8.20.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,42 @@
|
|||||||
|
{
|
||||||
|
"name": "snowluma",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "SnowLuma - NTQQ packet sniffer with Node.js native addon",
|
||||||
|
"type": "module",
|
||||||
|
"main": "dist/index.mjs",
|
||||||
|
"scripts": {
|
||||||
|
"testtypes": "tsc --noEmit",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest",
|
||||||
|
"build": "vite build",
|
||||||
|
"build:webui": "pnpm --filter webui build",
|
||||||
|
"build:all": "cross-env BUILD_WEBUI=true vite build && pnpm --filter webui build",
|
||||||
|
"dev": "pnpm --parallel run dev",
|
||||||
|
"dev:core": "tsx src/index.ts",
|
||||||
|
"dev:web": "pnpm --filter webui dev",
|
||||||
|
"start": "node dist/index.mjs"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"ws": "^8.20.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@hono/node-server": "^1.19.14",
|
||||||
|
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||||
|
"@types/node": "^24.12.2",
|
||||||
|
"@types/ws": "^8.18.1",
|
||||||
|
"cross-env": "^10.1.0",
|
||||||
|
"hono": "^4.12.14",
|
||||||
|
"tsx": "^4.21.0",
|
||||||
|
"typescript": "^6.0.2",
|
||||||
|
"vite": "catalog:",
|
||||||
|
"vite-plugin-cp": "^6.0.3",
|
||||||
|
"vitest": "^4.1.4"
|
||||||
|
},
|
||||||
|
"pnpm": {
|
||||||
|
"peerDependencyRules": {
|
||||||
|
"allowedVersions": {
|
||||||
|
"eslint-plugin-react-hooks>eslint": "10"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+4287
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,9 @@
|
|||||||
|
packages:
|
||||||
|
- 'webui'
|
||||||
|
|
||||||
|
catalog:
|
||||||
|
vite: ^8.0.8
|
||||||
|
typescript: ~6.0.2
|
||||||
|
|
||||||
|
overrides:
|
||||||
|
tar: ^7.5.13
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,335 @@
|
|||||||
|
// Contact / info-fetching operations extracted from Bridge.
|
||||||
|
|
||||||
|
import type { Bridge } from './bridge';
|
||||||
|
import type { DownloadRKeyInfo } from './bridge';
|
||||||
|
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
|
||||||
|
import { protoDecode } from '../protobuf/decode';
|
||||||
|
import { sendOidbAndDecode } from './bridge-oidb';
|
||||||
|
import {
|
||||||
|
OidbSvcTrpcTcp0xFD4_1ResponseSchema,
|
||||||
|
OidbSvcTrpcTcp0xFE5_2ResponseSchema,
|
||||||
|
OidbSvcTrpcTcp0xFE7_3ResponseSchema,
|
||||||
|
OidbSvcTrpcTcp0x10C0ResponseSchema,
|
||||||
|
} from './proto/oidb';
|
||||||
|
import {
|
||||||
|
OidbFriendListRequestSchema,
|
||||||
|
OidbGroupListRequestSchema,
|
||||||
|
OidbGroupMemberListRequestSchema,
|
||||||
|
OidbUserInfoRequestSchema,
|
||||||
|
OidbUserInfoResponseSchema,
|
||||||
|
AvatarInfoSchema,
|
||||||
|
OidbGroupRequestListSchema,
|
||||||
|
NTV2RichMediaReqSchema,
|
||||||
|
NTV2RichMediaRespSchema,
|
||||||
|
} from './proto/oidb-action';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function buildFriendProperties(raw: any): Map<number, string> {
|
||||||
|
const props = new Map<number, string>();
|
||||||
|
for (const additional of raw.additional ?? []) {
|
||||||
|
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
|
||||||
|
for (const property of additional.layer1.properties ?? []) {
|
||||||
|
props.set(property.code ?? 0, property.value ?? '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return props;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function permissionToRole(permission: number): string {
|
||||||
|
switch (permission) {
|
||||||
|
case 1: return 'owner';
|
||||||
|
case 2: return 'admin';
|
||||||
|
default: return 'member';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Friend list
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
|
||||||
|
const friends: FriendInfo[] = [];
|
||||||
|
let nextUin: number | null = null;
|
||||||
|
|
||||||
|
do {
|
||||||
|
const body: any = {
|
||||||
|
friendCount: 300,
|
||||||
|
field4: 0,
|
||||||
|
field6: 1,
|
||||||
|
field7: 0x7FFFFFFF,
|
||||||
|
body: [
|
||||||
|
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
|
||||||
|
{ type: 4, number: { numbers: [100, 101, 102] } },
|
||||||
|
],
|
||||||
|
field10002: [13578, 13579, 13573, 13572, 13568],
|
||||||
|
field10003: 4051,
|
||||||
|
};
|
||||||
|
if (nextUin !== null) {
|
||||||
|
body.nextUin = { uin: nextUin };
|
||||||
|
}
|
||||||
|
|
||||||
|
const resp = await sendOidbAndDecode<any>(
|
||||||
|
bridge, 'OidbSvcTrpcTcp.0xfd4_1', 0xFD4, 1, body,
|
||||||
|
OidbFriendListRequestSchema, OidbSvcTrpcTcp0xFD4_1ResponseSchema);
|
||||||
|
|
||||||
|
if (resp?.friends) {
|
||||||
|
for (const raw of resp.friends) {
|
||||||
|
const props = buildFriendProperties(raw);
|
||||||
|
friends.push({
|
||||||
|
uin: raw.uin ?? 0,
|
||||||
|
uid: raw.uid ?? '',
|
||||||
|
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||||
|
remark: props.get(103) ?? '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nextUin = resp?.next?.uin ?? null;
|
||||||
|
if (nextUin === 0) nextUin = null;
|
||||||
|
} while (nextUin !== null);
|
||||||
|
|
||||||
|
bridge.qqInfo.setFriends(friends);
|
||||||
|
return friends;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Group list
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
|
||||||
|
const allTrue = true;
|
||||||
|
const body = {
|
||||||
|
config: {
|
||||||
|
config1: {
|
||||||
|
groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue,
|
||||||
|
groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue,
|
||||||
|
field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue,
|
||||||
|
field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue,
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
config2: {
|
||||||
|
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
|
||||||
|
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
|
||||||
|
},
|
||||||
|
config3: { field5: allTrue, field6: allTrue },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const resp = await sendOidbAndDecode<any>(
|
||||||
|
bridge, 'OidbSvcTrpcTcp.0xfe5_2', 0xFE5, 2, body,
|
||||||
|
OidbGroupListRequestSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema, true);
|
||||||
|
|
||||||
|
const groups: QQGroupInfo[] = [];
|
||||||
|
if (resp?.groups) {
|
||||||
|
for (const raw of resp.groups) {
|
||||||
|
groups.push({
|
||||||
|
groupId: raw.groupUin ?? 0,
|
||||||
|
groupName: raw.info?.groupName ?? '',
|
||||||
|
remark: raw.customInfo?.remark ?? '',
|
||||||
|
memberCount: raw.info?.memberCount ?? 0,
|
||||||
|
memberMax: raw.info?.memberMax ?? 0,
|
||||||
|
members: new Map(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bridge.qqInfo.setGroups(groups);
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Group member list
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Promise<GroupMemberInfo[]> {
|
||||||
|
const members: GroupMemberInfo[] = [];
|
||||||
|
let token = '';
|
||||||
|
|
||||||
|
do {
|
||||||
|
const body: any = {
|
||||||
|
groupUin: groupId,
|
||||||
|
field2: 5,
|
||||||
|
field3: 2,
|
||||||
|
body: {
|
||||||
|
memberName: true, memberCard: true, level: true, field13: true,
|
||||||
|
field16: true, specialTitle: true, field18: true, field20: true,
|
||||||
|
field21: true, joinTimestamp: true, lastMsgTimestamp: true,
|
||||||
|
shutUpTimestamp: true, field103: true, field104: true, field105: true,
|
||||||
|
field106: true, permission: true, field200: true, field201: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (token) body.token = token;
|
||||||
|
|
||||||
|
const resp = await sendOidbAndDecode<any>(
|
||||||
|
bridge, 'OidbSvcTrpcTcp.0xfe7_3', 0xFE7, 3, body,
|
||||||
|
OidbGroupMemberListRequestSchema, OidbSvcTrpcTcp0xFE7_3ResponseSchema);
|
||||||
|
|
||||||
|
if (resp?.members) {
|
||||||
|
for (const raw of resp.members) {
|
||||||
|
members.push({
|
||||||
|
uin: raw.uin?.uin ?? 0,
|
||||||
|
uid: raw.uin?.uid ?? '',
|
||||||
|
nickname: raw.memberName ?? '',
|
||||||
|
card: raw.memberCard?.memberCard ?? '',
|
||||||
|
role: permissionToRole(raw.permission ?? 0),
|
||||||
|
level: raw.level?.level ?? 0,
|
||||||
|
title: raw.specialTitle ?? '',
|
||||||
|
joinTime: raw.joinTimestamp ?? 0,
|
||||||
|
lastSentTime: raw.lastMsgTimestamp ?? 0,
|
||||||
|
shutUpTime: raw.shutUpTimestamp ?? 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
token = resp?.token ?? '';
|
||||||
|
} while (token);
|
||||||
|
|
||||||
|
bridge.qqInfo.setGroupMembers(groupId, members);
|
||||||
|
return members;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// User profile
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
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];
|
||||||
|
const body = {
|
||||||
|
uin,
|
||||||
|
field2: 0,
|
||||||
|
keys: keys.map(k => ({ key: k })),
|
||||||
|
};
|
||||||
|
|
||||||
|
const resp = await sendOidbAndDecode<any>(
|
||||||
|
bridge, 'OidbSvcTrpcTcp.0xfe1_2', 0xFE1, 2, body,
|
||||||
|
OidbUserInfoRequestSchema, OidbUserInfoResponseSchema);
|
||||||
|
|
||||||
|
if (!resp?.body) throw new Error('user info response body missing');
|
||||||
|
|
||||||
|
const info: UserProfileInfo = {
|
||||||
|
uin: resp.body.uin ?? uin,
|
||||||
|
uid: resp.body.uid ?? '',
|
||||||
|
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
if (resp.body.properties) {
|
||||||
|
const bytesMap = new Map<number, Uint8Array>();
|
||||||
|
const numMap = new Map<number, number>();
|
||||||
|
for (const bp of resp.body.properties.bytesProperties ?? []) {
|
||||||
|
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
|
||||||
|
}
|
||||||
|
for (const np of resp.body.properties.numberProperties ?? []) {
|
||||||
|
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const getString = (code: number) => {
|
||||||
|
const b = bytesMap.get(code);
|
||||||
|
return b ? Buffer.from(b).toString('utf8') : '';
|
||||||
|
};
|
||||||
|
|
||||||
|
info.nickname = getString(20002);
|
||||||
|
info.remark = getString(103);
|
||||||
|
info.qid = getString(27394);
|
||||||
|
info.sign = getString(102);
|
||||||
|
|
||||||
|
const avatarBytes = bytesMap.get(101);
|
||||||
|
if (avatarBytes) {
|
||||||
|
const av = protoDecode(avatarBytes, AvatarInfoSchema);
|
||||||
|
if (av?.url) info.avatar = av.url + '640';
|
||||||
|
}
|
||||||
|
|
||||||
|
const sexNum = numMap.get(20009) ?? 0;
|
||||||
|
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
|
||||||
|
info.age = numMap.get(20037) ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bridge.qqInfo.setUserProfile(info);
|
||||||
|
const selfUin = parseInt(bridge.qqInfo.uin, 10) || 0;
|
||||||
|
if (info.uin === selfUin) bridge.qqInfo.setSelfProfile(info);
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Group requests
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise<GroupRequestInfo[]> {
|
||||||
|
const subCmd = filtered ? 2 : 1;
|
||||||
|
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
|
||||||
|
const resp = await sendOidbAndDecode<any>(
|
||||||
|
bridge, cmd, 0x10C0, subCmd, { count: 20, field2: 0 },
|
||||||
|
OidbGroupRequestListSchema, OidbSvcTrpcTcp0x10C0ResponseSchema);
|
||||||
|
|
||||||
|
const requests: GroupRequestInfo[] = [];
|
||||||
|
for (const raw of resp?.requests ?? []) {
|
||||||
|
requests.push({
|
||||||
|
groupId: raw.group?.groupUin ?? 0,
|
||||||
|
groupName: raw.group?.groupName ?? '',
|
||||||
|
targetUid: raw.target?.uid ?? '',
|
||||||
|
targetUin: 0,
|
||||||
|
targetName: raw.target?.name ?? '',
|
||||||
|
invitorUid: raw.invitor?.uid ?? '',
|
||||||
|
invitorUin: 0,
|
||||||
|
invitorName: raw.invitor?.name ?? '',
|
||||||
|
operatorUid: raw.operatorUser?.uid ?? '',
|
||||||
|
operatorUin: 0,
|
||||||
|
operatorName: raw.operatorUser?.name ?? '',
|
||||||
|
sequence: Number(raw.sequence ?? 0),
|
||||||
|
state: raw.state ?? 0,
|
||||||
|
eventType: raw.eventType ?? 0,
|
||||||
|
comment: raw.comment ?? '',
|
||||||
|
filtered,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return requests;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Download RKeys
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyInfo[]> {
|
||||||
|
const PRIVATE_IMAGE = 10;
|
||||||
|
const GROUP_IMAGE = 20;
|
||||||
|
const FALLBACK_IMAGE = 2;
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
reqHead: {
|
||||||
|
common: { requestId: 1, command: 202 },
|
||||||
|
scene: { requestType: 2, businessType: 1, sceneType: 0 },
|
||||||
|
client: { agentType: 2 },
|
||||||
|
},
|
||||||
|
downloadRkey: {
|
||||||
|
types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const resp = await sendOidbAndDecode<any>(
|
||||||
|
bridge, 'OidbSvcTrpcTcp.0x9067_202', 0x9067, 202, body,
|
||||||
|
NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, true);
|
||||||
|
|
||||||
|
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
|
||||||
|
throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: DownloadRKeyInfo[] = [];
|
||||||
|
for (const entry of resp?.downloadRkey?.rkeys ?? []) {
|
||||||
|
const rkey = entry.rkey ?? '';
|
||||||
|
const type = entry.type ?? 0;
|
||||||
|
if (rkey && type) {
|
||||||
|
result.push({
|
||||||
|
rkey,
|
||||||
|
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
|
||||||
|
storeId: entry.storeId ?? 0,
|
||||||
|
createTime: entry.rkeyCreateTime ?? 0,
|
||||||
|
type,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
// OIDB protocol helpers -- encode requests, send+check, send+decode, UID resolution.
|
||||||
|
|
||||||
|
import type { Bridge } from './bridge';
|
||||||
|
import type { ProtoSchema } from '../protobuf/decode';
|
||||||
|
import { protoEncode, protoDecode } from '../protobuf/decode';
|
||||||
|
import { makeOidbBaseSchema } from './proto/oidb';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a raw OIDB request buffer (base envelope wrapping a typed body).
|
||||||
|
*/
|
||||||
|
export function makeOidbRequest(
|
||||||
|
command: number, subCommand: number,
|
||||||
|
body: any, bodySchema: ProtoSchema, isUid = false,
|
||||||
|
): Uint8Array {
|
||||||
|
const baseSchema = makeOidbBaseSchema(bodySchema);
|
||||||
|
return protoEncode({
|
||||||
|
command,
|
||||||
|
subCommand,
|
||||||
|
errorCode: 0,
|
||||||
|
body,
|
||||||
|
errorMsg: '',
|
||||||
|
reserved: isUid ? 1 : 0,
|
||||||
|
}, baseSchema);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send an OIDB packet and verify it succeeded (no decode of body).
|
||||||
|
*/
|
||||||
|
export async function sendOidbAndCheck(
|
||||||
|
bridge: Bridge,
|
||||||
|
serviceCmd: string, command: number, subCommand: number,
|
||||||
|
body: any, bodySchema: ProtoSchema, isUid = false,
|
||||||
|
): Promise<void> {
|
||||||
|
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
|
||||||
|
const result = await bridge.sendRawPacket(serviceCmd, request);
|
||||||
|
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
|
||||||
|
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
|
||||||
|
// Check OIDB error code if response present
|
||||||
|
if (result.responseData && result.responseData.length > 0) {
|
||||||
|
const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } });
|
||||||
|
const resp = protoDecode(result.responseData, emptyBase);
|
||||||
|
if (resp && (resp as any).errorCode && (resp as any).errorCode !== 0) {
|
||||||
|
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send an OIDB packet and decode the response body with the given schema.
|
||||||
|
*/
|
||||||
|
export async function sendOidbAndDecode<T>(
|
||||||
|
bridge: Bridge,
|
||||||
|
serviceCmd: string, command: number, subCommand: number,
|
||||||
|
body: any, bodySchema: ProtoSchema, responseSchema: ProtoSchema, isUid = false,
|
||||||
|
): Promise<T> {
|
||||||
|
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
|
||||||
|
const result = await bridge.sendRawPacket(serviceCmd, request);
|
||||||
|
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
|
||||||
|
if (!result.gotResponse || !result.responseData) throw new Error(result.errorMessage || 'no response');
|
||||||
|
|
||||||
|
const baseSchema = makeOidbBaseSchema(responseSchema);
|
||||||
|
const resp = protoDecode(result.responseData, baseSchema);
|
||||||
|
if (!resp) throw new Error('failed to decode OIDB response');
|
||||||
|
if ((resp as any).errorCode && (resp as any).errorCode !== 0) {
|
||||||
|
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
|
||||||
|
}
|
||||||
|
return (resp as any).body as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a UIN to a UID string, using cache or fetching as needed.
|
||||||
|
* Mirrors C++ resolve_user_uid_for_action.
|
||||||
|
*/
|
||||||
|
export async function resolveUserUid(bridge: Bridge, uin: number, groupId?: number): Promise<string> {
|
||||||
|
// Try group member first
|
||||||
|
if (groupId !== undefined) {
|
||||||
|
const uid = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
|
||||||
|
if (uid) return uid;
|
||||||
|
// Try fetching member list
|
||||||
|
try { await bridge.fetchGroupMemberList(groupId); } catch { /* ignore */ }
|
||||||
|
const uid2 = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
|
||||||
|
if (uid2) return uid2;
|
||||||
|
}
|
||||||
|
// Try cached
|
||||||
|
const uid = bridge.qqInfo.findUidByUin(uin);
|
||||||
|
if (uid) return uid;
|
||||||
|
// Fetch profile
|
||||||
|
const profile = await bridge.fetchUserProfile(uin);
|
||||||
|
if (profile.uid) return profile.uid;
|
||||||
|
throw new Error(`failed to resolve UID for UIN ${uin}`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,495 @@
|
|||||||
|
// Bridge — per-UIN session: handler registration, packet dispatch, event routing.
|
||||||
|
// Supports packet sending via native addon.
|
||||||
|
// Heavy OIDB / contact / action logic is split into bridge-oidb, bridge-contacts, bridge-actions.
|
||||||
|
|
||||||
|
import type { PacketInfo } from '../protocol/types';
|
||||||
|
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
|
||||||
|
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
|
||||||
|
import { QQInfo } from './qq-info';
|
||||||
|
import { MSG_PUSH_CMD, parseMsgPush } from './handlers/msg-push-handler';
|
||||||
|
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
|
||||||
|
import { protoEncode, protoDecode } from '../protobuf/decode';
|
||||||
|
import { buildSendElems } from './builders/element-builder';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
import {
|
||||||
|
SendMessageRequestSchema,
|
||||||
|
SendMessageResponseSchema,
|
||||||
|
} from './proto/action';
|
||||||
|
|
||||||
|
// Delegated modules
|
||||||
|
import { resolveUserUid as resolveUserUid_ } from './bridge-oidb';
|
||||||
|
import {
|
||||||
|
fetchFriendList as fetchFriendList_,
|
||||||
|
fetchGroupList as fetchGroupList_,
|
||||||
|
fetchGroupMemberList as fetchGroupMemberList_,
|
||||||
|
fetchUserProfile as fetchUserProfile_,
|
||||||
|
fetchGroupRequests as fetchGroupRequests_,
|
||||||
|
fetchDownloadRKeys as fetchDownloadRKeys_,
|
||||||
|
} from './bridge-contacts';
|
||||||
|
import {
|
||||||
|
muteGroupMember as muteGroupMember_,
|
||||||
|
muteGroupAll as muteGroupAll_,
|
||||||
|
kickGroupMember as kickGroupMember_,
|
||||||
|
leaveGroup as leaveGroup_,
|
||||||
|
setGroupAdmin as setGroupAdmin_,
|
||||||
|
setGroupCard as setGroupCard_,
|
||||||
|
setGroupName as setGroupName_,
|
||||||
|
setGroupSpecialTitle as setGroupSpecialTitle_,
|
||||||
|
setFriendAddRequest as setFriendAddRequest_,
|
||||||
|
deleteFriend as deleteFriend_,
|
||||||
|
uploadGroupFile as uploadGroupFile_,
|
||||||
|
uploadPrivateFile as uploadPrivateFile_,
|
||||||
|
fetchGroupFiles as fetchGroupFiles_,
|
||||||
|
fetchGroupFileUrl as fetchGroupFileUrl_,
|
||||||
|
fetchPrivateFileUrl as fetchPrivateFileUrl_,
|
||||||
|
fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_,
|
||||||
|
fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_,
|
||||||
|
fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_,
|
||||||
|
fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_,
|
||||||
|
uploadForwardNodes as uploadForwardNodes_,
|
||||||
|
fetchForwardNodes as fetchForwardNodes_,
|
||||||
|
deleteGroupFile as deleteGroupFile_,
|
||||||
|
moveGroupFile as moveGroupFile_,
|
||||||
|
createGroupFileFolder as createGroupFileFolder_,
|
||||||
|
deleteGroupFileFolder as deleteGroupFileFolder_,
|
||||||
|
renameGroupFileFolder as renameGroupFileFolder_,
|
||||||
|
setGroupAddRequest as setGroupAddRequest_,
|
||||||
|
sendPoke as sendPoke_,
|
||||||
|
sendLike as sendLike_,
|
||||||
|
setGroupEssence as setGroupEssence_,
|
||||||
|
setGroupReaction as setGroupReaction_,
|
||||||
|
recallGroupMessage as recallGroupMessage_,
|
||||||
|
recallPrivateMessage as recallPrivateMessage_,
|
||||||
|
setFriendRemark as setFriendRemark_,
|
||||||
|
fetchGroupFileCount as fetchGroupFileCount_,
|
||||||
|
} from './bridge-actions';
|
||||||
|
import type { GroupFilesResult } from './bridge-actions';
|
||||||
|
import type { MediaIndexNode } from './bridge-actions';
|
||||||
|
|
||||||
|
export type BridgeEventCallback = (event: QQEventVariant) => void;
|
||||||
|
|
||||||
|
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
|
||||||
|
|
||||||
|
export interface SendMessageReceipt {
|
||||||
|
messageId: number;
|
||||||
|
sequence: number;
|
||||||
|
clientSequence: number;
|
||||||
|
random: number;
|
||||||
|
timestamp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DownloadRKeyInfo {
|
||||||
|
rkey: string;
|
||||||
|
ttlSeconds: number;
|
||||||
|
storeId: number;
|
||||||
|
createTime: number;
|
||||||
|
type: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const log = createLogger('Bridge');
|
||||||
|
const eventLog = createLogger('Event');
|
||||||
|
|
||||||
|
export class Bridge {
|
||||||
|
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||||
|
|
||||||
|
private qqInfo_: QQInfo;
|
||||||
|
private pids_ = new Set<number>();
|
||||||
|
private eventCallback_: BridgeEventCallback | null = null;
|
||||||
|
private cmdHandlers_ = new Map<string, CmdParser[]>();
|
||||||
|
private packetClient_: PacketSender | null = null;
|
||||||
|
private memberRefreshTasks_ = new Map<number, Promise<void>>();
|
||||||
|
|
||||||
|
// Sequence and random generators for outgoing messages
|
||||||
|
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||||
|
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||||
|
|
||||||
|
constructor(qqInfo: QQInfo) {
|
||||||
|
this.qqInfo_ = qqInfo;
|
||||||
|
this.registerDefaultHandlers();
|
||||||
|
}
|
||||||
|
|
||||||
|
get qqInfo(): QQInfo { return this.qqInfo_; }
|
||||||
|
|
||||||
|
setPacketClient(client: PacketSender): void {
|
||||||
|
this.packetClient_ = client;
|
||||||
|
}
|
||||||
|
|
||||||
|
private registerDefaultHandlers(): void {
|
||||||
|
this.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||||
|
}
|
||||||
|
|
||||||
|
registerCmd(cmd: string, parser: CmdParser): void {
|
||||||
|
const arr = this.cmdHandlers_.get(cmd) ?? [];
|
||||||
|
arr.push(parser);
|
||||||
|
this.cmdHandlers_.set(cmd, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
setEventCallback(cb: BridgeEventCallback): void {
|
||||||
|
this.eventCallback_ = cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
handlesCmd(cmd: string): boolean {
|
||||||
|
return this.cmdHandlers_.has(cmd);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- PID management ---
|
||||||
|
|
||||||
|
attachPid(pid: number): void {
|
||||||
|
this.pids_.add(pid);
|
||||||
|
}
|
||||||
|
detachPid(pid: number): void {
|
||||||
|
this.pids_.delete(pid);
|
||||||
|
}
|
||||||
|
hasPid(pid: number): boolean { return this.pids_.has(pid); }
|
||||||
|
get empty(): boolean { return this.pids_.size === 0; }
|
||||||
|
get activePid(): number | null {
|
||||||
|
for (const pid of this.pids_) return pid;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Packet dispatch ---
|
||||||
|
|
||||||
|
onPacket(pkt: PacketInfo): void {
|
||||||
|
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
|
||||||
|
if (!handlers) return;
|
||||||
|
|
||||||
|
for (const handler of handlers) {
|
||||||
|
try {
|
||||||
|
const events = handler(pkt, this.qqInfo_);
|
||||||
|
for (const event of events) {
|
||||||
|
this.triggerMemberCacheRefresh(event);
|
||||||
|
printEvent(event);
|
||||||
|
this.emitEvent(event);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private emitEvent(event: QQEventVariant): void {
|
||||||
|
if (this.eventCallback_) {
|
||||||
|
try { this.eventCallback_(event); } catch (e) {
|
||||||
|
log.error('event callback error: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private triggerMemberCacheRefresh(event: QQEventVariant): void {
|
||||||
|
let groupId = 0;
|
||||||
|
let reason = '';
|
||||||
|
switch (event.kind) {
|
||||||
|
case 'group_member_join':
|
||||||
|
groupId = event.groupId;
|
||||||
|
reason = 'group_member_join';
|
||||||
|
break;
|
||||||
|
case 'group_member_leave':
|
||||||
|
groupId = event.groupId;
|
||||||
|
reason = 'group_member_leave';
|
||||||
|
break;
|
||||||
|
case 'group_admin':
|
||||||
|
groupId = event.groupId;
|
||||||
|
reason = 'group_admin';
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (groupId <= 0) return;
|
||||||
|
if (this.memberRefreshTasks_.has(groupId)) return;
|
||||||
|
|
||||||
|
const task = (async () => {
|
||||||
|
try {
|
||||||
|
if (!this.qqInfo_.findGroup(groupId)) {
|
||||||
|
try { await this.fetchGroupList(); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
await this.fetchGroupMemberList(groupId);
|
||||||
|
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||||
|
} catch (e) {
|
||||||
|
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||||
|
groupId, reason, e instanceof Error ? e.message : String(e));
|
||||||
|
} finally {
|
||||||
|
this.memberRefreshTasks_.delete(groupId);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
this.memberRefreshTasks_.set(groupId, task);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Sequence / random generators ---
|
||||||
|
|
||||||
|
private nextClientSequence(): number {
|
||||||
|
return ++this.clientSeq_;
|
||||||
|
}
|
||||||
|
|
||||||
|
private nextMessageRandom(): number {
|
||||||
|
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
|
||||||
|
return this.msgRandom_ & 0x7FFFFFFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Send packet (raw) ---
|
||||||
|
|
||||||
|
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||||
|
if (!this.packetClient_) {
|
||||||
|
return {
|
||||||
|
success: false, gotResponse: false, errorCode: -1,
|
||||||
|
errorMessage: 'no packet sender attached', responseData: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Send message (high-level) ---
|
||||||
|
|
||||||
|
async sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||||
|
if (elements.length === 0) throw new Error('message is empty');
|
||||||
|
|
||||||
|
const protoElems = await buildSendElems(elements, { bridge: this, groupId });
|
||||||
|
const random = this.nextMessageRandom();
|
||||||
|
|
||||||
|
const request = protoEncode({
|
||||||
|
routingHead: {
|
||||||
|
grp: { groupCode: BigInt(groupId) },
|
||||||
|
} as any,
|
||||||
|
contentHead: {
|
||||||
|
type: 1,
|
||||||
|
} as any,
|
||||||
|
messageBody: {
|
||||||
|
richText: {
|
||||||
|
elems: protoElems,
|
||||||
|
},
|
||||||
|
} as any,
|
||||||
|
clientSequence: 0,
|
||||||
|
random,
|
||||||
|
syncCookie: new Uint8Array(0),
|
||||||
|
via: 0,
|
||||||
|
dataStatist: 0,
|
||||||
|
multiSendSeq: 0,
|
||||||
|
}, SendMessageRequestSchema);
|
||||||
|
|
||||||
|
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
|
||||||
|
|
||||||
|
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||||
|
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = protoDecode(result.responseData, SendMessageResponseSchema);
|
||||||
|
if (!response) {
|
||||||
|
throw new Error('failed to decode SendMessageResponse');
|
||||||
|
}
|
||||||
|
if (response.result !== undefined && response.result !== 0) {
|
||||||
|
throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const seq = response.groupSequence ?? 0;
|
||||||
|
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||||
|
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
return {
|
||||||
|
messageId,
|
||||||
|
sequence: seq,
|
||||||
|
clientSequence: 0,
|
||||||
|
random,
|
||||||
|
timestamp,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||||
|
if (elements.length === 0) throw new Error('message is empty');
|
||||||
|
|
||||||
|
// Resolve UID for image upload (C++ resolves UID before building elems)
|
||||||
|
let userUid = '';
|
||||||
|
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
|
||||||
|
if (hasMedia) {
|
||||||
|
userUid = await this.resolveUserUid(userUin);
|
||||||
|
}
|
||||||
|
|
||||||
|
const protoElems = await buildSendElems(elements, { bridge: this, userUid });
|
||||||
|
const random = this.nextMessageRandom();
|
||||||
|
const clientSeq = this.nextClientSequence();
|
||||||
|
|
||||||
|
const request = protoEncode({
|
||||||
|
routingHead: {
|
||||||
|
c2c: {
|
||||||
|
uin: userUin,
|
||||||
|
},
|
||||||
|
} as any,
|
||||||
|
contentHead: {
|
||||||
|
type: 1,
|
||||||
|
subType: 0,
|
||||||
|
c2cCmd: 11,
|
||||||
|
} as any,
|
||||||
|
messageBody: {
|
||||||
|
richText: {
|
||||||
|
elems: protoElems,
|
||||||
|
},
|
||||||
|
} as any,
|
||||||
|
clientSequence: clientSeq,
|
||||||
|
random,
|
||||||
|
syncCookie: new Uint8Array(0),
|
||||||
|
via: 0,
|
||||||
|
dataStatist: 0,
|
||||||
|
ctrl: {
|
||||||
|
msgFlag: Math.floor(Date.now() / 1000),
|
||||||
|
} as any,
|
||||||
|
multiSendSeq: 0,
|
||||||
|
}, SendMessageRequestSchema);
|
||||||
|
|
||||||
|
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
|
||||||
|
|
||||||
|
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||||
|
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = protoDecode(result.responseData, SendMessageResponseSchema);
|
||||||
|
if (!response) {
|
||||||
|
throw new Error('failed to decode SendMessageResponse');
|
||||||
|
}
|
||||||
|
if (response.result !== undefined && response.result !== 0) {
|
||||||
|
throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const seq = response.privateSequence ?? 0;
|
||||||
|
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||||
|
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
return {
|
||||||
|
messageId,
|
||||||
|
sequence: seq,
|
||||||
|
clientSequence: clientSeq,
|
||||||
|
random,
|
||||||
|
timestamp,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Delegated: OIDB helpers ---
|
||||||
|
|
||||||
|
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||||
|
return resolveUserUid_(this, uin, groupId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Delegated: Contact / info queries ---
|
||||||
|
|
||||||
|
async fetchFriendList(): Promise<FriendInfo[]> { return fetchFriendList_(this); }
|
||||||
|
async fetchGroupList(): Promise<QQGroupInfo[]> { return fetchGroupList_(this); }
|
||||||
|
async fetchGroupMemberList(groupId: number): Promise<GroupMemberInfo[]> { return fetchGroupMemberList_(this, groupId); }
|
||||||
|
async fetchUserProfile(uin: number): Promise<UserProfileInfo> { return fetchUserProfile_(this, uin); }
|
||||||
|
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> { return fetchGroupRequests_(this, filtered); }
|
||||||
|
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> { return fetchDownloadRKeys_(this); }
|
||||||
|
|
||||||
|
// --- Delegated: Admin / action methods ---
|
||||||
|
|
||||||
|
async muteGroupMember(groupId: number, userId: number, duration: number): Promise<void> { return muteGroupMember_(this, groupId, userId, duration); }
|
||||||
|
async muteGroupAll(groupId: number, enable: boolean): Promise<void> { return muteGroupAll_(this, groupId, enable); }
|
||||||
|
async kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { return kickGroupMember_(this, groupId, userId, reject, reason); }
|
||||||
|
async leaveGroup(groupId: number): Promise<void> { return leaveGroup_(this, groupId); }
|
||||||
|
async setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void> { return setGroupAdmin_(this, groupId, userId, enable); }
|
||||||
|
async setGroupCard(groupId: number, userId: number, card: string): Promise<void> { return setGroupCard_(this, groupId, userId, card); }
|
||||||
|
async setGroupName(groupId: number, name: string): Promise<void> { return setGroupName_(this, groupId, name); }
|
||||||
|
async setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise<void> { return setGroupSpecialTitle_(this, groupId, userId, title); }
|
||||||
|
async setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise<void> { return setFriendAddRequest_(this, uidOrFlag, approve); }
|
||||||
|
async deleteFriend(userId: number, block = false): Promise<void> { return deleteFriend_(this, userId, block); }
|
||||||
|
async uploadGroupFile(groupId: number, file: string, name = '', folderId = '/', uploadFile = true): Promise<{ fileId: string | null }> {
|
||||||
|
return uploadGroupFile_(this, groupId, file, name, folderId, uploadFile);
|
||||||
|
}
|
||||||
|
async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> {
|
||||||
|
return uploadPrivateFile_(this, userId, file, name, uploadFile);
|
||||||
|
}
|
||||||
|
async fetchGroupFiles(groupId: number, folderId = '/'): Promise<GroupFilesResult> { return fetchGroupFiles_(this, groupId, folderId); }
|
||||||
|
async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise<string> { return fetchGroupFileUrl_(this, groupId, fileId, busId); }
|
||||||
|
async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string> { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); }
|
||||||
|
async fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupPttUrlByNode_(this, groupId, node); }
|
||||||
|
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
|
||||||
|
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
|
||||||
|
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivateVideoUrlByNode_(this, node); }
|
||||||
|
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId); }
|
||||||
|
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
|
||||||
|
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
|
||||||
|
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }
|
||||||
|
async createGroupFileFolder(groupId: number, name: string, parentId = '/'): Promise<void> { return createGroupFileFolder_(this, groupId, name, parentId); }
|
||||||
|
async deleteGroupFileFolder(groupId: number, folderId: string): Promise<void> { return deleteGroupFileFolder_(this, groupId, folderId); }
|
||||||
|
async renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> { return renameGroupFileFolder_(this, groupId, folderId, newFolderName); }
|
||||||
|
async setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason = '', filtered = false): Promise<void> { return setGroupAddRequest_(this, groupId, sequence, eventType, approve, reason, filtered); }
|
||||||
|
async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> { return sendPoke_(this, isGroup, peerUin, targetUin); }
|
||||||
|
async sendLike(userId: number, count: number): Promise<void> { return sendLike_(this, userId, count); }
|
||||||
|
async setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> { return setGroupEssence_(this, groupId, sequence, random, enable); }
|
||||||
|
async setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> { return setGroupReaction_(this, groupId, sequence, code, isSet); }
|
||||||
|
async recallGroupMessage(groupId: number, sequence: number): Promise<void> { return recallGroupMessage_(this, groupId, sequence); }
|
||||||
|
async recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void> { return recallPrivateMessage_(this, userUin, clientSeq, msgSeq, random, timestamp); }
|
||||||
|
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
|
||||||
|
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Module-level helper functions ---
|
||||||
|
|
||||||
|
function elementsToText(elements: MessageElement[]): string {
|
||||||
|
return elements.map(e => {
|
||||||
|
switch (e.type) {
|
||||||
|
case 'text': return e.text ?? '';
|
||||||
|
case 'at': return `@${e.targetUin ?? 'all'}`;
|
||||||
|
case 'face': return `[表情:${e.faceId}]`;
|
||||||
|
case 'mface': return `[${e.summary ?? '表情'}]`;
|
||||||
|
case 'image': return '[图片]';
|
||||||
|
case 'video': return '[视频]';
|
||||||
|
case 'record': return '[语音]';
|
||||||
|
case 'file': return `[文件:${e.fileName ?? ''}]`;
|
||||||
|
case 'json': return '[JSON卡片]';
|
||||||
|
case 'xml': return '[XML卡片]';
|
||||||
|
case 'reply': return `[回复:${e.replySeq}]`;
|
||||||
|
case 'poke': return '[戳一戳]';
|
||||||
|
case 'forward': return '[合并转发]';
|
||||||
|
case 'markdown': return '[Markdown]';
|
||||||
|
default: return `[${e.type}]`;
|
||||||
|
}
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function printEvent(event: QQEventVariant): void {
|
||||||
|
switch (event.kind) {
|
||||||
|
case 'group_message': {
|
||||||
|
const c = elementsToText(event.elements);
|
||||||
|
const s = event.senderCard || event.senderNick || String(event.senderUin);
|
||||||
|
eventLog.success('群 %d | %s(%d): %s', event.groupId, s, event.senderUin, c);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'friend_message':
|
||||||
|
eventLog.info('私聊 %s(%d): %s', event.senderNick || String(event.senderUin), event.senderUin, elementsToText(event.elements));
|
||||||
|
break;
|
||||||
|
case 'temp_message':
|
||||||
|
eventLog.info('临时 %d(群%d): %s', event.senderUin, event.groupId, elementsToText(event.elements));
|
||||||
|
break;
|
||||||
|
case 'group_recall':
|
||||||
|
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
|
||||||
|
break;
|
||||||
|
case 'friend_recall':
|
||||||
|
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
|
||||||
|
break;
|
||||||
|
case 'group_member_join':
|
||||||
|
eventLog.info('入群 %d 加入 %d', event.userUin, event.groupId);
|
||||||
|
break;
|
||||||
|
case 'group_member_leave':
|
||||||
|
eventLog.warn('退群 %d %s %d', event.userUin, event.isKick ? '被踢出' : '退出', event.groupId);
|
||||||
|
break;
|
||||||
|
case 'group_mute':
|
||||||
|
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
|
||||||
|
break;
|
||||||
|
case 'group_admin':
|
||||||
|
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
|
||||||
|
break;
|
||||||
|
case 'friend_poke':
|
||||||
|
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
|
||||||
|
break;
|
||||||
|
case 'group_poke':
|
||||||
|
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
|
||||||
|
break;
|
||||||
|
case 'friend_request':
|
||||||
|
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
|
||||||
|
break;
|
||||||
|
case 'group_invite':
|
||||||
|
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
|
||||||
|
break;
|
||||||
|
case 'group_essence':
|
||||||
|
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
// Element Builder — converts internal MessageElement[] into proto Elem objects
|
||||||
|
// for encoding with protoEncode(SendMessageRequestSchema).
|
||||||
|
// Port of src/bridge/src/bridge_messages.cpp build_send_elems()
|
||||||
|
|
||||||
|
import type { Bridge } from '../bridge';
|
||||||
|
import type { MessageElement } from '../events';
|
||||||
|
import type { ProtoDecoded } from '../../protobuf/decode';
|
||||||
|
import { protoEncode } from '../../protobuf/decode';
|
||||||
|
import {
|
||||||
|
ElemSchema,
|
||||||
|
} from '../proto/element';
|
||||||
|
import {
|
||||||
|
MentionExtraSendSchema,
|
||||||
|
MarkdownDataSchema,
|
||||||
|
} from '../proto/action';
|
||||||
|
import { uploadImageMsgInfo } from '../highway/image-upload';
|
||||||
|
|
||||||
|
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
|
||||||
|
|
||||||
|
export interface SendContext {
|
||||||
|
bridge: Bridge;
|
||||||
|
groupId?: number;
|
||||||
|
userUid?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeTextElem(text: string): ProtoElem {
|
||||||
|
return {
|
||||||
|
text: { str: text } as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeFaceElem(faceId: number): ProtoElem {
|
||||||
|
return {
|
||||||
|
face: { index: faceId } as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeMentionElem(element: MessageElement): ProtoElem {
|
||||||
|
const mentionAll = element.uid === 'all' || element.targetUin === 0;
|
||||||
|
|
||||||
|
const extra = protoEncode({
|
||||||
|
type: mentionAll ? 1 : 2,
|
||||||
|
uin: mentionAll ? 0 : (element.targetUin ?? 0),
|
||||||
|
field5: 0,
|
||||||
|
uid: mentionAll ? 'all' : (element.uid ?? ''),
|
||||||
|
}, MentionExtraSendSchema);
|
||||||
|
|
||||||
|
return {
|
||||||
|
text: {
|
||||||
|
str: element.text || (mentionAll ? '@全体成员 ' : `@${element.targetUin} `),
|
||||||
|
pbReserve: extra,
|
||||||
|
} as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeReplyElem(element: MessageElement): ProtoElem {
|
||||||
|
return {
|
||||||
|
srcMsg: {
|
||||||
|
origSeqs: [element.replySeq! & 0xFFFFFFFF],
|
||||||
|
} as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeJsonElem(element: MessageElement): ProtoElem {
|
||||||
|
const content = element.text ?? '';
|
||||||
|
const payload = new Uint8Array(content.length + 1);
|
||||||
|
payload[0] = 0x00;
|
||||||
|
const encoded = new TextEncoder().encode(content);
|
||||||
|
payload.set(encoded, 1);
|
||||||
|
|
||||||
|
return {
|
||||||
|
richMsg: {
|
||||||
|
serviceId: 1,
|
||||||
|
template1: payload,
|
||||||
|
} as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeXmlElem(element: MessageElement): ProtoElem {
|
||||||
|
const content = element.text ?? '';
|
||||||
|
const payload = new Uint8Array(content.length + 1);
|
||||||
|
payload[0] = 0x00;
|
||||||
|
const encoded = new TextEncoder().encode(content);
|
||||||
|
payload.set(encoded, 1);
|
||||||
|
|
||||||
|
return {
|
||||||
|
richMsg: {
|
||||||
|
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
|
||||||
|
template1: payload,
|
||||||
|
} as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeMarkdownElem(element: MessageElement): ProtoElem {
|
||||||
|
const data = protoEncode({ content: element.text ?? '' }, MarkdownDataSchema);
|
||||||
|
|
||||||
|
return {
|
||||||
|
commonElem: {
|
||||||
|
serviceType: 45,
|
||||||
|
pbElem: data,
|
||||||
|
businessType: 1,
|
||||||
|
} as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeForwardElem(element: MessageElement): ProtoElem {
|
||||||
|
const resId = (element.resId ?? '').trim();
|
||||||
|
if (!resId) {
|
||||||
|
throw new Error('forward resId is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const xml = `<?xml version="1.0" encoding="utf-8"?><msg templateID="1" action="viewMultiMsg" serviceID="35" brief="[聊天记录]" m_resid="${resId}" m_fileName="${resId}" actionData="${resId}" tSum="2" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0"><item layout="1"><title size="34" color="#000000">聊天记录</title><title size="26" color="#777777">查看转发消息</title><summary size="26" color="#808080">查看转发消息</summary></item><source name="" icon="" action="" appid="-1"/></msg>`;
|
||||||
|
const encodedXml = new TextEncoder().encode(xml);
|
||||||
|
const payload = new Uint8Array(encodedXml.length + 1);
|
||||||
|
payload[0] = 0x00;
|
||||||
|
payload.set(encodedXml, 1);
|
||||||
|
|
||||||
|
return {
|
||||||
|
richMsg: {
|
||||||
|
serviceId: 35,
|
||||||
|
template1: payload,
|
||||||
|
} as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function makeImageElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
|
||||||
|
const isGroup = ctx.groupId !== undefined;
|
||||||
|
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
|
||||||
|
if (!isGroup && !targetIdOrUid) {
|
||||||
|
throw new Error('private image target uid is missing');
|
||||||
|
}
|
||||||
|
|
||||||
|
const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
|
||||||
|
|
||||||
|
return {
|
||||||
|
commonElem: {
|
||||||
|
serviceType: 48,
|
||||||
|
pbElem: msgInfo,
|
||||||
|
businessType: isGroup ? 20 : 10,
|
||||||
|
} as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build proto Elem objects from an array of MessageElements.
|
||||||
|
* Supports: text, face, at, reply, json, xml, markdown, image.
|
||||||
|
* Image elements trigger highway upload via the SendContext.
|
||||||
|
*/
|
||||||
|
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
|
||||||
|
const result: ProtoElem[] = [];
|
||||||
|
|
||||||
|
for (const elem of elements) {
|
||||||
|
switch (elem.type) {
|
||||||
|
case 'text':
|
||||||
|
if (elem.text) result.push(makeTextElem(elem.text));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'face':
|
||||||
|
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'at':
|
||||||
|
result.push(makeMentionElem(elem));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'reply':
|
||||||
|
if (elem.replySeq) result.push(makeReplyElem(elem));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'json':
|
||||||
|
if (elem.text) result.push(makeJsonElem(elem));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'xml':
|
||||||
|
if (elem.text) result.push(makeXmlElem(elem));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'markdown':
|
||||||
|
if (elem.text) result.push(makeMarkdownElem(elem));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'image':
|
||||||
|
if (ctx) {
|
||||||
|
result.push(await makeImageElem(ctx, elem));
|
||||||
|
} else {
|
||||||
|
console.warn('[ElemBuilder] image send requires SendContext');
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'forward':
|
||||||
|
if (elem.resId) result.push(makeForwardElem(elem));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'record':
|
||||||
|
case 'video':
|
||||||
|
console.warn(`[ElemBuilder] ${elem.type} send not yet implemented`);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
// Bridge event types and MessageElement.
|
||||||
|
// Port of src/bridge/include/bridge/events.h
|
||||||
|
|
||||||
|
export interface MessageElement {
|
||||||
|
type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward'
|
||||||
|
text?: string;
|
||||||
|
faceId?: number;
|
||||||
|
targetUin?: number;
|
||||||
|
uid?: string;
|
||||||
|
imageUrl?: string;
|
||||||
|
fileId?: string;
|
||||||
|
thumbFileId?: string;
|
||||||
|
fileName?: string;
|
||||||
|
fileSize?: number;
|
||||||
|
replySeq?: number;
|
||||||
|
url?: string;
|
||||||
|
subType?: number;
|
||||||
|
duration?: number;
|
||||||
|
width?: number;
|
||||||
|
height?: number;
|
||||||
|
summary?: string;
|
||||||
|
flash?: boolean;
|
||||||
|
resId?: string;
|
||||||
|
fileHash?: string;
|
||||||
|
mediaNode?: {
|
||||||
|
fileUuid?: string;
|
||||||
|
storeId?: number;
|
||||||
|
uploadTime?: number;
|
||||||
|
ttl?: number;
|
||||||
|
subType?: number;
|
||||||
|
info?: {
|
||||||
|
fileSize?: number;
|
||||||
|
fileHash?: string;
|
||||||
|
fileSha1?: string;
|
||||||
|
fileName?: string;
|
||||||
|
width?: number;
|
||||||
|
height?: number;
|
||||||
|
time?: number;
|
||||||
|
original?: number;
|
||||||
|
type?: {
|
||||||
|
type?: number;
|
||||||
|
picFormat?: number;
|
||||||
|
videoFormat?: number;
|
||||||
|
voiceFormat?: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForwardNodePayload {
|
||||||
|
userUin: number;
|
||||||
|
nickname: string;
|
||||||
|
elements: MessageElement[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QQEvent {
|
||||||
|
time: number;
|
||||||
|
selfUin: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendMessage extends QQEvent {
|
||||||
|
kind: 'friend_message';
|
||||||
|
senderUin: number;
|
||||||
|
senderNick: string;
|
||||||
|
msgSeq: number;
|
||||||
|
msgId: number;
|
||||||
|
elements: MessageElement[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupMessage extends QQEvent {
|
||||||
|
kind: 'group_message';
|
||||||
|
groupId: number;
|
||||||
|
senderUin: number;
|
||||||
|
senderNick: string;
|
||||||
|
senderCard: string;
|
||||||
|
senderRole: string;
|
||||||
|
msgSeq: number;
|
||||||
|
msgId: number;
|
||||||
|
elements: MessageElement[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TempMessage extends QQEvent {
|
||||||
|
kind: 'temp_message';
|
||||||
|
senderUin: number;
|
||||||
|
groupId: number;
|
||||||
|
senderNick: string;
|
||||||
|
msgSeq: number;
|
||||||
|
elements: MessageElement[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupMemberJoin extends QQEvent {
|
||||||
|
kind: 'group_member_join';
|
||||||
|
groupId: number;
|
||||||
|
userUin: number;
|
||||||
|
operatorUin: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupMemberLeave extends QQEvent {
|
||||||
|
kind: 'group_member_leave';
|
||||||
|
groupId: number;
|
||||||
|
userUin: number;
|
||||||
|
operatorUin: number;
|
||||||
|
isKick: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupMuteEvent extends QQEvent {
|
||||||
|
kind: 'group_mute';
|
||||||
|
groupId: number;
|
||||||
|
userUin: number;
|
||||||
|
operatorUin: number;
|
||||||
|
duration: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupAdminEvent extends QQEvent {
|
||||||
|
kind: 'group_admin';
|
||||||
|
groupId: number;
|
||||||
|
userUin: number;
|
||||||
|
set: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendRecall extends QQEvent {
|
||||||
|
kind: 'friend_recall';
|
||||||
|
userUin: number;
|
||||||
|
msgSeq: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupRecallEvent extends QQEvent {
|
||||||
|
kind: 'group_recall';
|
||||||
|
groupId: number;
|
||||||
|
operatorUin: number;
|
||||||
|
authorUin: number;
|
||||||
|
msgSeq: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendRequestEvent extends QQEvent {
|
||||||
|
kind: 'friend_request';
|
||||||
|
fromUin: number;
|
||||||
|
message: string;
|
||||||
|
flag: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupInviteEvent extends QQEvent {
|
||||||
|
kind: 'group_invite';
|
||||||
|
groupId: number;
|
||||||
|
fromUin: number;
|
||||||
|
subType: string;
|
||||||
|
message: string;
|
||||||
|
flag: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendPokeEvent extends QQEvent {
|
||||||
|
kind: 'friend_poke';
|
||||||
|
userUin: number;
|
||||||
|
targetUin: number;
|
||||||
|
action: string;
|
||||||
|
suffix: string;
|
||||||
|
actionImgUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupPokeEvent extends QQEvent {
|
||||||
|
kind: 'group_poke';
|
||||||
|
groupId: number;
|
||||||
|
userUin: number;
|
||||||
|
targetUin: number;
|
||||||
|
action: string;
|
||||||
|
suffix: string;
|
||||||
|
actionImgUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupEssenceEvent extends QQEvent {
|
||||||
|
kind: 'group_essence';
|
||||||
|
groupId: number;
|
||||||
|
senderUin: number;
|
||||||
|
operatorUin: number;
|
||||||
|
msgSeq: number;
|
||||||
|
random: number;
|
||||||
|
set: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupFileUploadEvent extends QQEvent {
|
||||||
|
kind: 'group_file_upload';
|
||||||
|
groupId: number;
|
||||||
|
userUin: number;
|
||||||
|
fileId: string;
|
||||||
|
fileName: string;
|
||||||
|
fileSize: number;
|
||||||
|
busId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendAddEvent extends QQEvent {
|
||||||
|
kind: 'friend_add';
|
||||||
|
userUin: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type QQEventVariant =
|
||||||
|
| FriendMessage
|
||||||
|
| GroupMessage
|
||||||
|
| TempMessage
|
||||||
|
| GroupMemberJoin
|
||||||
|
| GroupMemberLeave
|
||||||
|
| GroupMuteEvent
|
||||||
|
| GroupAdminEvent
|
||||||
|
| FriendRecall
|
||||||
|
| GroupRecallEvent
|
||||||
|
| FriendRequestEvent
|
||||||
|
| GroupInviteEvent
|
||||||
|
| FriendPokeEvent
|
||||||
|
| GroupPokeEvent
|
||||||
|
| GroupEssenceEvent
|
||||||
|
| GroupFileUploadEvent
|
||||||
|
| FriendAddEvent;
|
||||||
@@ -0,0 +1,857 @@
|
|||||||
|
// MsgPush packet handler — parses trpc.msg.olpush.OlPushService.MsgPush
|
||||||
|
// into bridge events. Port of src/bridge/src/handlers/msg_push_handler.h/.cpp
|
||||||
|
|
||||||
|
import { inflateSync } from 'zlib';
|
||||||
|
import { protoDecode } from '../../protobuf/decode';
|
||||||
|
import { WireMessage } from '../../protobuf/wire';
|
||||||
|
import { PushMsgSchema } from '../proto/message';
|
||||||
|
import {
|
||||||
|
MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema,
|
||||||
|
MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema,
|
||||||
|
} from '../proto/element';
|
||||||
|
import { FileExtraSchema } from '../proto/message';
|
||||||
|
import {
|
||||||
|
GroupChangeSchema, GroupAdminSchema, GroupJoinSchema,
|
||||||
|
GroupInvitationSchema, GroupInviteSchema,
|
||||||
|
FriendRequestSchema, FriendRecallSchema,
|
||||||
|
GroupMuteSchema, NotifyMessageBodySchema,
|
||||||
|
GeneralGrayTipInfoSchema, OperatorInfoSchema,
|
||||||
|
} from '../proto/notify';
|
||||||
|
import type { QQInfo } from '../qq-info';
|
||||||
|
import type { PacketInfo } from '../../protocol/types';
|
||||||
|
import type {
|
||||||
|
QQEventVariant, MessageElement,
|
||||||
|
FriendMessage, GroupMessage, TempMessage,
|
||||||
|
GroupMemberJoin, GroupMemberLeave, GroupMuteEvent, GroupAdminEvent,
|
||||||
|
FriendRecall, GroupRecallEvent, FriendRequestEvent, GroupInviteEvent,
|
||||||
|
FriendPokeEvent, GroupPokeEvent, GroupEssenceEvent,
|
||||||
|
} from '../events';
|
||||||
|
import type { ProtoDecoded, ProtoSchema } from '../../protobuf/decode';
|
||||||
|
|
||||||
|
// --- PkgType enum ---
|
||||||
|
const enum PkgType {
|
||||||
|
ForwardFakePrivateMessage = 9,
|
||||||
|
PrivateMessage = 166,
|
||||||
|
GroupMessage = 82,
|
||||||
|
TempMessage = 141,
|
||||||
|
Event0x210 = 528,
|
||||||
|
Event0x2DC = 732,
|
||||||
|
PrivateRecordMessage = 208,
|
||||||
|
PrivateFileMessage = 529,
|
||||||
|
GroupRequestInvitationNotice = 525,
|
||||||
|
GroupRequestJoinNotice = 84,
|
||||||
|
GroupInviteNotice = 87,
|
||||||
|
GroupAdminChangedNotice = 44,
|
||||||
|
GroupMemberIncreaseNotice = 33,
|
||||||
|
GroupMemberDecreaseNotice = 34,
|
||||||
|
}
|
||||||
|
|
||||||
|
const enum Event0x2DCSubType {
|
||||||
|
GroupMuteNotice = 12,
|
||||||
|
GroupRecallNotice = 17,
|
||||||
|
GroupGreyTipNotice = 20,
|
||||||
|
GroupEssenceNotice = 21,
|
||||||
|
}
|
||||||
|
|
||||||
|
const enum Event0x210SubType {
|
||||||
|
FriendRequestNotice = 35,
|
||||||
|
FriendRecallNotice = 138,
|
||||||
|
FriendPokeNotice = 290,
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Helpers ---
|
||||||
|
|
||||||
|
function makeImageUrl(origUrl: string): string {
|
||||||
|
if (!origUrl) return '';
|
||||||
|
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
|
||||||
|
return 'http://gchat.qpic.cn' + origUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
const HEX_CHARS = '0123456789ABCDEF';
|
||||||
|
function bytesToHex(data: Uint8Array): string {
|
||||||
|
let r = '';
|
||||||
|
for (const b of data) { r += HEX_CHARS[b >> 4]; r += HEX_CHARS[b & 0x0f]; }
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decompressData(data: Uint8Array): string {
|
||||||
|
if (!data || data.length === 0) return '';
|
||||||
|
if (data[0] === 0x01 && data.length > 1) {
|
||||||
|
try {
|
||||||
|
const inflated = inflateSync(Buffer.from(data.subarray(1)));
|
||||||
|
return inflated.toString('utf8');
|
||||||
|
} catch { return ''; }
|
||||||
|
}
|
||||||
|
if (data[0] === 0x00 && data.length > 1) {
|
||||||
|
return Buffer.from(data.subarray(1)).toString('utf8');
|
||||||
|
}
|
||||||
|
return Buffer.from(data).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNumericUin(value: string): boolean {
|
||||||
|
return value.length > 0 && /^\d+$/.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseU64OrZero(value: string): number {
|
||||||
|
if (!value) return 0;
|
||||||
|
const n = parseInt(value, 10);
|
||||||
|
return isNaN(n) ? 0 : n;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveUidToUin(qqInfo: QQInfo, groupId: number, uid: string, fallback = 0): number {
|
||||||
|
if (!uid) return fallback;
|
||||||
|
if (isNumericUin(uid)) {
|
||||||
|
const n = parseInt(uid, 10);
|
||||||
|
if (!isNaN(n)) return n;
|
||||||
|
}
|
||||||
|
if (groupId) {
|
||||||
|
const uin = qqInfo.resolveGroupMemberUid(groupId, uid);
|
||||||
|
if (uin !== null) return uin;
|
||||||
|
}
|
||||||
|
const uin = qqInfo.resolveUid(uid);
|
||||||
|
if (uin !== null) return uin;
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeOperatorUid(bytes: Uint8Array): string {
|
||||||
|
if (!bytes || bytes.length === 0) return '';
|
||||||
|
const info = protoDecode(bytes, OperatorInfoSchema);
|
||||||
|
if (info?.operatorField?.uid) return info.operatorField.uid;
|
||||||
|
return Buffer.from(bytes).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map<string, string> {
|
||||||
|
const map = new Map<string, string>();
|
||||||
|
for (const p of params) {
|
||||||
|
if (p.name !== undefined) map.set(p.name, p.value ?? '');
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
|
||||||
|
for (const k of keys) {
|
||||||
|
const v = map.get(k);
|
||||||
|
if (v) return v;
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
|
||||||
|
if (content.length <= 7) return null;
|
||||||
|
const lenBe = (content[5] << 8) | content[6];
|
||||||
|
const lenLe = content[5] | (content[6] << 8);
|
||||||
|
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
|
||||||
|
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
|
||||||
|
return content.subarray(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Element conversion ---
|
||||||
|
|
||||||
|
type ElemDecoded = ProtoDecoded<typeof import('../proto/element').ElemSchema>;
|
||||||
|
|
||||||
|
function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||||
|
const result: MessageElement[] = [];
|
||||||
|
let skipNext = false;
|
||||||
|
|
||||||
|
for (const elem of elems) {
|
||||||
|
if (skipNext) { skipNext = false; continue; }
|
||||||
|
|
||||||
|
// Reply / quote
|
||||||
|
if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) {
|
||||||
|
result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text (with possible @ detection)
|
||||||
|
if (elem.text) {
|
||||||
|
const t = elem.text;
|
||||||
|
let mention: ProtoDecoded<typeof MentionExtraSchema> | null = null;
|
||||||
|
if (t.pbReserve && t.pbReserve.length > 0) {
|
||||||
|
mention = protoDecode(t.pbReserve, MentionExtraSchema);
|
||||||
|
}
|
||||||
|
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
|
||||||
|
const hasMention = mention && (mention.type === 1 || mention.type === 2);
|
||||||
|
|
||||||
|
if (hasAttr6 || hasMention) {
|
||||||
|
const me: MessageElement = { type: 'at', text: t.str ?? '' };
|
||||||
|
if (hasAttr6) {
|
||||||
|
const buf = t.attr6Buf!;
|
||||||
|
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
|
||||||
|
}
|
||||||
|
if (hasMention && mention) {
|
||||||
|
me.uid = mention.uid ?? '';
|
||||||
|
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
|
||||||
|
}
|
||||||
|
result.push(me);
|
||||||
|
} else {
|
||||||
|
const text = t.str ?? '';
|
||||||
|
if (text) result.push({ type: 'text', text });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Face
|
||||||
|
if (elem.face) {
|
||||||
|
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarketFace
|
||||||
|
if (elem.marketFace) {
|
||||||
|
result.push({
|
||||||
|
type: 'mface',
|
||||||
|
text: elem.marketFace.faceName ?? '',
|
||||||
|
faceId: elem.marketFace.tabId ?? 0,
|
||||||
|
subType: elem.marketFace.subType ?? 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// NotOnlineImage (C2C image)
|
||||||
|
if (elem.notOnlineImage) {
|
||||||
|
const img = elem.notOnlineImage;
|
||||||
|
if (img.picMd5 && img.picMd5.length > 0) {
|
||||||
|
const urlPath = img.origUrl || img.bigUrl || '';
|
||||||
|
result.push({
|
||||||
|
type: 'image',
|
||||||
|
imageUrl: makeImageUrl(urlPath),
|
||||||
|
fileId: img.filePath ?? '',
|
||||||
|
fileSize: img.fileLen ?? 0,
|
||||||
|
width: img.picWidth ?? 0,
|
||||||
|
height: img.picHeight ?? 0,
|
||||||
|
subType: img.pbRes?.subType ?? 0,
|
||||||
|
summary: img.pbRes?.summary ?? '[image]',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomFace (group image)
|
||||||
|
if (elem.customFace) {
|
||||||
|
const img = elem.customFace;
|
||||||
|
if (img.md5 && img.md5.length > 0) {
|
||||||
|
result.push({
|
||||||
|
type: 'image',
|
||||||
|
imageUrl: makeImageUrl(img.origUrl ?? ''),
|
||||||
|
fileId: img.filePath ?? '',
|
||||||
|
fileSize: img.size ?? 0,
|
||||||
|
width: img.width ?? 0,
|
||||||
|
height: img.height ?? 0,
|
||||||
|
subType: img.pbRes?.subType ?? 0,
|
||||||
|
summary: img.pbRes?.summary ?? '[image]',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// VideoFile
|
||||||
|
if (elem.videoFile) {
|
||||||
|
const v = elem.videoFile;
|
||||||
|
result.push({
|
||||||
|
type: 'video',
|
||||||
|
fileId: v.fileUuid ?? '',
|
||||||
|
fileName: v.fileName ?? '',
|
||||||
|
fileSize: v.fileSize ?? 0,
|
||||||
|
duration: v.fileTime ?? 0,
|
||||||
|
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '',
|
||||||
|
mediaNode: {
|
||||||
|
fileUuid: v.fileUuid ?? '',
|
||||||
|
info: {
|
||||||
|
fileSize: v.fileSize ?? 0,
|
||||||
|
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '',
|
||||||
|
fileName: v.fileName ?? '',
|
||||||
|
width: v.fileWidth ?? 0,
|
||||||
|
height: v.fileHeight ?? 0,
|
||||||
|
time: v.fileTime ?? 0,
|
||||||
|
type: {
|
||||||
|
type: 2,
|
||||||
|
videoFormat: v.fileFormat ?? 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// GroupFile
|
||||||
|
if (elem.groupFile) {
|
||||||
|
const f = elem.groupFile;
|
||||||
|
result.push({
|
||||||
|
type: 'file',
|
||||||
|
fileId: f.fileId ?? '',
|
||||||
|
fileName: f.filename ?? '',
|
||||||
|
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// TransElem type=24 (group file via transport)
|
||||||
|
if (elem.transElem) {
|
||||||
|
const te = elem.transElem;
|
||||||
|
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
|
||||||
|
const val = te.elemValue;
|
||||||
|
const len = (val[1] << 8) | val[2];
|
||||||
|
if (val.length >= 3 + len) {
|
||||||
|
const extra = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema);
|
||||||
|
if (extra?.inner?.info) {
|
||||||
|
const info = extra.inner.info;
|
||||||
|
result.push({
|
||||||
|
type: 'file',
|
||||||
|
fileName: info.fileName ?? '',
|
||||||
|
fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0,
|
||||||
|
fileId: info.fileId ?? '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RichMsg
|
||||||
|
if (elem.richMsg) {
|
||||||
|
const rm = elem.richMsg;
|
||||||
|
if (rm.template1 && rm.template1.length > 0) {
|
||||||
|
const content = decompressData(rm.template1);
|
||||||
|
if (content) {
|
||||||
|
const svcId = rm.serviceId ?? 0;
|
||||||
|
if (svcId === 35) {
|
||||||
|
const pos = content.indexOf('m_resid="');
|
||||||
|
if (pos !== -1) {
|
||||||
|
const start = pos + 9;
|
||||||
|
const end = content.indexOf('"', start);
|
||||||
|
if (end !== -1) {
|
||||||
|
result.push({ type: 'forward', resId: content.substring(start, end) });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.push({ type: 'xml', text: content, subType: svcId });
|
||||||
|
} else if (svcId === 1) {
|
||||||
|
result.push({ type: 'json', text: content });
|
||||||
|
} else {
|
||||||
|
result.push({ type: 'xml', text: content, subType: svcId });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// LightApp
|
||||||
|
if (elem.lightApp) {
|
||||||
|
const la = elem.lightApp;
|
||||||
|
if (la.data && la.data.length > 0) {
|
||||||
|
const content = decompressData(la.data);
|
||||||
|
if (content) result.push({ type: 'json', text: content });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CommonElem
|
||||||
|
if (elem.commonElem) {
|
||||||
|
const ce = elem.commonElem;
|
||||||
|
const svcType = ce.serviceType ?? 0;
|
||||||
|
const bizType = ce.businessType ?? 0;
|
||||||
|
|
||||||
|
if (svcType === 2) {
|
||||||
|
// Poke
|
||||||
|
result.push({ type: 'poke', subType: bizType });
|
||||||
|
} else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) {
|
||||||
|
// Flash image
|
||||||
|
const pb = ce.pbElem;
|
||||||
|
let pos = 1;
|
||||||
|
let length = 0, shift = 0;
|
||||||
|
while (pos < pb.length) {
|
||||||
|
const b = pb[pos++];
|
||||||
|
length |= (b & 0x7f) << shift;
|
||||||
|
shift += 7;
|
||||||
|
if ((b & 0x80) === 0) break;
|
||||||
|
}
|
||||||
|
if (pos + length <= pb.length) {
|
||||||
|
const img = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema);
|
||||||
|
if (img) {
|
||||||
|
const me: MessageElement = {
|
||||||
|
type: 'image', fileId: img.filePath ?? '',
|
||||||
|
fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0,
|
||||||
|
height: img.picHeight ?? 0, flash: true, summary: '[flash image]',
|
||||||
|
};
|
||||||
|
if (img.pbRes) me.subType = img.pbRes.subType ?? 0;
|
||||||
|
if (img.picMd5 && img.picMd5.length > 0) {
|
||||||
|
me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + bytesToHex(img.picMd5) + '/0';
|
||||||
|
}
|
||||||
|
result.push(me);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
skipNext = true;
|
||||||
|
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
|
||||||
|
// NTQQ new protocol image/record/video
|
||||||
|
const info = protoDecode(ce.pbElem, MsgInfoSchema);
|
||||||
|
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
|
||||||
|
const body = info.msgInfoBody[0];
|
||||||
|
if (body.index?.info) {
|
||||||
|
const idx = body.index;
|
||||||
|
const fi = idx.info!;
|
||||||
|
|
||||||
|
if (bizType === 10 || bizType === 20) {
|
||||||
|
// Image
|
||||||
|
let url = '';
|
||||||
|
if (body.picture) {
|
||||||
|
const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn';
|
||||||
|
const path = body.picture.urlPath ?? '';
|
||||||
|
if (path) {
|
||||||
|
url = 'https://' + domain + path;
|
||||||
|
if (body.picture.ext?.originalParameter) {
|
||||||
|
url += body.picture.ext.originalParameter;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const me: MessageElement = {
|
||||||
|
type: 'image', fileId: fi.fileName ?? '',
|
||||||
|
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
|
||||||
|
height: fi.height ?? 0, imageUrl: url,
|
||||||
|
};
|
||||||
|
if (info.extBizInfo?.pic) {
|
||||||
|
me.subType = info.extBizInfo.pic.bizType ?? 0;
|
||||||
|
me.summary = info.extBizInfo.pic.textSummary || '[image]';
|
||||||
|
}
|
||||||
|
result.push(me);
|
||||||
|
} else if (bizType === 12 || bizType === 22) {
|
||||||
|
// Record
|
||||||
|
result.push({
|
||||||
|
type: 'record', fileName: fi.fileName ?? '',
|
||||||
|
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
|
||||||
|
fileHash: fi.fileHash ?? '',
|
||||||
|
mediaNode: {
|
||||||
|
fileUuid: idx.fileUuid,
|
||||||
|
storeId: idx.storeId,
|
||||||
|
uploadTime: idx.uploadTime,
|
||||||
|
ttl: idx.ttl,
|
||||||
|
subType: idx.subType,
|
||||||
|
info: {
|
||||||
|
fileSize: fi.fileSize,
|
||||||
|
fileHash: fi.fileHash,
|
||||||
|
fileSha1: fi.fileSha1,
|
||||||
|
fileName: fi.fileName,
|
||||||
|
width: fi.width,
|
||||||
|
height: fi.height,
|
||||||
|
time: fi.time,
|
||||||
|
original: fi.original,
|
||||||
|
type: {
|
||||||
|
type: fi.type?.type,
|
||||||
|
picFormat: fi.type?.picFormat,
|
||||||
|
videoFormat: fi.type?.videoFormat,
|
||||||
|
voiceFormat: fi.type?.voiceFormat,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else if (bizType === 11 || bizType === 21) {
|
||||||
|
// Video
|
||||||
|
result.push({
|
||||||
|
type: 'video', fileName: fi.fileName ?? '',
|
||||||
|
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
|
||||||
|
duration: fi.time ?? 0,
|
||||||
|
fileHash: fi.fileHash ?? '',
|
||||||
|
mediaNode: {
|
||||||
|
fileUuid: idx.fileUuid,
|
||||||
|
storeId: idx.storeId,
|
||||||
|
uploadTime: idx.uploadTime,
|
||||||
|
ttl: idx.ttl,
|
||||||
|
subType: idx.subType,
|
||||||
|
info: {
|
||||||
|
fileSize: fi.fileSize,
|
||||||
|
fileHash: fi.fileHash,
|
||||||
|
fileSha1: fi.fileSha1,
|
||||||
|
fileName: fi.fileName,
|
||||||
|
width: fi.width,
|
||||||
|
height: fi.height,
|
||||||
|
time: fi.time,
|
||||||
|
original: fi.original,
|
||||||
|
type: {
|
||||||
|
type: fi.type?.type,
|
||||||
|
picFormat: fi.type?.picFormat,
|
||||||
|
videoFormat: fi.type?.videoFormat,
|
||||||
|
voiceFormat: fi.type?.voiceFormat,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (svcType === 33 && ce.pbElem) {
|
||||||
|
// Small face
|
||||||
|
const extra = protoDecode(ce.pbElem, QSmallFaceExtraSchema);
|
||||||
|
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
|
||||||
|
} else if (svcType === 37 && ce.pbElem) {
|
||||||
|
// Big face
|
||||||
|
const extra = protoDecode(ce.pbElem, QFaceExtraSchema);
|
||||||
|
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
|
||||||
|
skipNext = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractRichtextExtras(
|
||||||
|
rt: ProtoDecoded<typeof import('../proto/message').RichTextSchema>,
|
||||||
|
elements: MessageElement[],
|
||||||
|
isGroup = false
|
||||||
|
): void {
|
||||||
|
// Ptt (voice)
|
||||||
|
if (rt.ptt) {
|
||||||
|
const p = rt.ptt;
|
||||||
|
const me: MessageElement = {
|
||||||
|
type: 'record', fileName: p.fileName ?? '',
|
||||||
|
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
|
||||||
|
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '',
|
||||||
|
};
|
||||||
|
if (isGroup && (p.fileId ?? 0n) !== 0n) {
|
||||||
|
me.fileId = p.groupFileKey ?? '';
|
||||||
|
} else {
|
||||||
|
if (p.fileUuid && p.fileUuid.length > 0) {
|
||||||
|
me.fileId = Buffer.from(p.fileUuid).toString('utf8');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
me.mediaNode = {
|
||||||
|
fileUuid: me.fileId ?? '',
|
||||||
|
info: {
|
||||||
|
fileSize: p.fileSize ?? 0,
|
||||||
|
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '',
|
||||||
|
fileName: p.fileName ?? '',
|
||||||
|
time: p.time ?? 0,
|
||||||
|
type: {
|
||||||
|
type: 3,
|
||||||
|
voiceFormat: p.format ?? 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
elements.push(me);
|
||||||
|
}
|
||||||
|
|
||||||
|
// NotOnlineFile (C2C file)
|
||||||
|
if (rt.notOnlineFile) {
|
||||||
|
const f = rt.notOnlineFile;
|
||||||
|
elements.push({
|
||||||
|
type: 'file', fileId: f.fileUuid ?? '',
|
||||||
|
fileName: f.fileName ?? '',
|
||||||
|
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||||
|
fileHash: f.fileHash ?? '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
|
||||||
|
const extra = protoDecode(msgContent, FileExtraSchema);
|
||||||
|
if (!extra?.file) return;
|
||||||
|
const f = extra.file;
|
||||||
|
if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) {
|
||||||
|
elements.push({
|
||||||
|
type: 'file', fileName: f.fileName, fileId: f.fileUuid,
|
||||||
|
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
|
||||||
|
fileHash: f.fileHash,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Main handler ---
|
||||||
|
|
||||||
|
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
|
||||||
|
|
||||||
|
export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[] {
|
||||||
|
if (pkt.body.length === 0) return [];
|
||||||
|
|
||||||
|
const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema);
|
||||||
|
if (!push?.message) return [];
|
||||||
|
|
||||||
|
const msg = push.message;
|
||||||
|
if (!msg.contentHead) return [];
|
||||||
|
|
||||||
|
const head = msg.contentHead;
|
||||||
|
const msgType = head.msgType ?? 0;
|
||||||
|
const subType = head.subType ?? 0;
|
||||||
|
const sequence = head.sequence ?? 0;
|
||||||
|
const timestamp = head.timestamp ?? 0;
|
||||||
|
const msgId = head.msgId ?? 0;
|
||||||
|
|
||||||
|
let fromUin = 0;
|
||||||
|
let fromUid = '';
|
||||||
|
if (msg.responseHead) {
|
||||||
|
fromUin = msg.responseHead.fromUin ?? 0;
|
||||||
|
fromUid = msg.responseHead.fromUid ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
let selfUin = 0;
|
||||||
|
if (pkt.uin) {
|
||||||
|
const n = parseInt(pkt.uin, 10);
|
||||||
|
if (!isNaN(n)) selfUin = n;
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = (msg.body?.msgContent) ? msg.body.msgContent : new Uint8Array(0);
|
||||||
|
|
||||||
|
const buildElements = (isGroup: boolean): MessageElement[] => {
|
||||||
|
const elements: MessageElement[] = [];
|
||||||
|
if (msg.body?.richText) {
|
||||||
|
const rt = msg.body.richText;
|
||||||
|
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
|
||||||
|
extractRichtextExtras(rt, elements, isGroup);
|
||||||
|
}
|
||||||
|
if (msg.body?.msgContent && msg.body.msgContent.length > 0) {
|
||||||
|
extractMsgContent(msg.body.msgContent, elements);
|
||||||
|
}
|
||||||
|
return elements;
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Switch on msgType ---
|
||||||
|
|
||||||
|
switch (msgType as PkgType) {
|
||||||
|
case PkgType.GroupMemberIncreaseNotice: {
|
||||||
|
const change = protoDecode(content, GroupChangeSchema);
|
||||||
|
if (!change) return [];
|
||||||
|
const ev: GroupMemberJoin = {
|
||||||
|
kind: 'group_member_join', time: timestamp, selfUin,
|
||||||
|
groupId: change.groupUin ?? 0,
|
||||||
|
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
|
||||||
|
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
|
||||||
|
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
|
||||||
|
case PkgType.GroupMemberDecreaseNotice: {
|
||||||
|
const change = protoDecode(content, GroupChangeSchema);
|
||||||
|
if (!change) return [];
|
||||||
|
const dt = change.decreaseType ?? 0;
|
||||||
|
const ev: GroupMemberLeave = {
|
||||||
|
kind: 'group_member_leave', time: timestamp, selfUin,
|
||||||
|
groupId: change.groupUin ?? 0,
|
||||||
|
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
|
||||||
|
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
|
||||||
|
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
|
||||||
|
isKick: dt !== 0 && dt !== 130,
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
|
||||||
|
case PkgType.GroupAdminChangedNotice: {
|
||||||
|
const admin = protoDecode(content, GroupAdminSchema);
|
||||||
|
if (!admin?.body) return [];
|
||||||
|
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
|
||||||
|
if (!extra) return [];
|
||||||
|
const ev: GroupAdminEvent = {
|
||||||
|
kind: 'group_admin', time: timestamp, selfUin,
|
||||||
|
groupId: admin.groupUin ?? 0,
|
||||||
|
userUin: resolveUidToUin(qqInfo, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin),
|
||||||
|
set: admin.body.extraEnable !== undefined,
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
|
||||||
|
case PkgType.GroupRequestJoinNotice: {
|
||||||
|
const join = protoDecode(content, GroupJoinSchema);
|
||||||
|
if (!join) return [];
|
||||||
|
const ev: GroupInviteEvent = {
|
||||||
|
kind: 'group_invite', time: timestamp, selfUin,
|
||||||
|
groupId: join.groupUin ?? 0,
|
||||||
|
fromUin: resolveUidToUin(qqInfo, join.groupUin ?? 0, join.targetUid ?? '', fromUin),
|
||||||
|
subType: 'add', message: '',
|
||||||
|
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
|
||||||
|
case PkgType.GroupRequestInvitationNotice: {
|
||||||
|
const invitation = protoDecode(content, GroupInvitationSchema);
|
||||||
|
if (!invitation?.info?.inner) return [];
|
||||||
|
const inner = invitation.info.inner;
|
||||||
|
const ev: GroupInviteEvent = {
|
||||||
|
kind: 'group_invite', time: timestamp, selfUin,
|
||||||
|
groupId: inner.groupUin ?? 0,
|
||||||
|
fromUin: resolveUidToUin(qqInfo, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin),
|
||||||
|
subType: 'invite', message: '',
|
||||||
|
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
|
||||||
|
case PkgType.GroupInviteNotice: {
|
||||||
|
const invite = protoDecode(content, GroupInviteSchema);
|
||||||
|
if (!invite) return [];
|
||||||
|
const ev: GroupInviteEvent = {
|
||||||
|
kind: 'group_invite', time: timestamp, selfUin,
|
||||||
|
groupId: invite.groupUin ?? 0,
|
||||||
|
fromUin: resolveUidToUin(qqInfo, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin),
|
||||||
|
subType: 'invite', message: '',
|
||||||
|
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
|
||||||
|
case PkgType.Event0x210: {
|
||||||
|
switch (subType as Event0x210SubType) {
|
||||||
|
case Event0x210SubType.FriendRequestNotice: {
|
||||||
|
const request = protoDecode(content, FriendRequestSchema);
|
||||||
|
if (!request?.info) return [];
|
||||||
|
const sourceUid = request.info.newSource || request.info.sourceUid || '';
|
||||||
|
const ev: FriendRequestEvent = {
|
||||||
|
kind: 'friend_request', time: timestamp, selfUin,
|
||||||
|
fromUin: resolveUidToUin(qqInfo, 0, sourceUid, fromUin),
|
||||||
|
message: request.info.message ?? '', flag: sourceUid,
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
case Event0x210SubType.FriendRecallNotice: {
|
||||||
|
const recall = protoDecode(content, FriendRecallSchema);
|
||||||
|
if (!recall?.info) return [];
|
||||||
|
const ev: FriendRecall = {
|
||||||
|
kind: 'friend_recall', time: recall.info.time ?? timestamp, selfUin,
|
||||||
|
userUin: resolveUidToUin(qqInfo, 0, recall.info.fromUid ?? '', fromUin),
|
||||||
|
msgSeq: recall.info.clientSequence ?? 0,
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
case Event0x210SubType.FriendPokeNotice: {
|
||||||
|
const grayTip = protoDecode(content, GeneralGrayTipInfoSchema);
|
||||||
|
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
|
||||||
|
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
|
||||||
|
const actor = findTemplateValue(templates, 'uin_str1');
|
||||||
|
const target = findTemplateValue(templates, 'uin_str2');
|
||||||
|
const ev: FriendPokeEvent = {
|
||||||
|
kind: 'friend_poke', time: timestamp, selfUin,
|
||||||
|
userUin: resolveUidToUin(qqInfo, 0, actor, parseU64OrZero(actor)),
|
||||||
|
targetUin: resolveUidToUin(qqInfo, 0, target, parseU64OrZero(target)),
|
||||||
|
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||||
|
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||||
|
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case PkgType.Event0x2DC: {
|
||||||
|
switch (subType as Event0x2DCSubType) {
|
||||||
|
case Event0x2DCSubType.GroupMuteNotice: {
|
||||||
|
const mute = protoDecode(content, GroupMuteSchema);
|
||||||
|
if (!mute?.data?.state) return [];
|
||||||
|
const duration = mute.data.state.duration ?? 0;
|
||||||
|
const ev: GroupMuteEvent = {
|
||||||
|
kind: 'group_mute', time: mute.data.timestamp ?? timestamp, selfUin,
|
||||||
|
groupId: mute.groupUin ?? 0,
|
||||||
|
operatorUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin),
|
||||||
|
userUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
|
||||||
|
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
case Event0x2DCSubType.GroupRecallNotice: {
|
||||||
|
const payload = unwrapGroupNotifyPayload(content);
|
||||||
|
if (!payload) return [];
|
||||||
|
const notify = protoDecode(payload, NotifyMessageBodySchema);
|
||||||
|
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
|
||||||
|
const recalled = notify.recall.recallMessages[0];
|
||||||
|
const ev: GroupRecallEvent = {
|
||||||
|
kind: 'group_recall', time: recalled.time ?? timestamp, selfUin,
|
||||||
|
groupId: notify.groupUin ?? 0,
|
||||||
|
operatorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0,
|
||||||
|
notify.recall.operatorUid || notify.operatorUid || '', fromUin),
|
||||||
|
authorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin),
|
||||||
|
msgSeq: recalled.sequence ?? 0,
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
case Event0x2DCSubType.GroupGreyTipNotice: {
|
||||||
|
const payload = unwrapGroupNotifyPayload(content);
|
||||||
|
if (!payload) return [];
|
||||||
|
const notify = protoDecode(payload, NotifyMessageBodySchema);
|
||||||
|
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
|
||||||
|
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
|
||||||
|
const actor = findTemplateValue(templates, 'uin_str1');
|
||||||
|
const target = findTemplateValue(templates, 'uin_str2');
|
||||||
|
const ev: GroupPokeEvent = {
|
||||||
|
kind: 'group_poke', time: timestamp, selfUin,
|
||||||
|
groupId: notify.groupUin ?? 0,
|
||||||
|
userUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
|
||||||
|
targetUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, target, parseU64OrZero(target)),
|
||||||
|
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
|
||||||
|
suffix: findTemplateValue(templates, 'suffix_str'),
|
||||||
|
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
case Event0x2DCSubType.GroupEssenceNotice: {
|
||||||
|
const payload = unwrapGroupNotifyPayload(content);
|
||||||
|
if (!payload) return [];
|
||||||
|
const notify = protoDecode(payload, NotifyMessageBodySchema);
|
||||||
|
if (!notify?.essenceMessage) return [];
|
||||||
|
const essence = notify.essenceMessage;
|
||||||
|
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
|
||||||
|
const ev: GroupEssenceEvent = {
|
||||||
|
kind: 'group_essence', time: essence.timestamp ?? timestamp, selfUin,
|
||||||
|
groupId: essence.groupUin ?? notify.groupUin ?? 0,
|
||||||
|
senderUin: essence.memberUin ?? 0,
|
||||||
|
operatorUin: essence.operatorUin ?? fromUin,
|
||||||
|
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
|
||||||
|
random: essence.random ?? 0,
|
||||||
|
set: setFlag === 1,
|
||||||
|
};
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Message types ---
|
||||||
|
|
||||||
|
if (msgType === PkgType.GroupMessage) {
|
||||||
|
const ev: GroupMessage = {
|
||||||
|
kind: 'group_message', time: timestamp, selfUin,
|
||||||
|
senderUin: fromUin, msgSeq: sequence,
|
||||||
|
msgId: msgId & 0x7FFFFFFF,
|
||||||
|
elements: buildElements(true),
|
||||||
|
groupId: 0, senderNick: '', senderCard: '', senderRole: '',
|
||||||
|
};
|
||||||
|
if (msg.responseHead?.grp) {
|
||||||
|
ev.groupId = msg.responseHead.grp.groupUin ?? 0;
|
||||||
|
ev.senderNick = msg.responseHead.grp.memberName ?? '';
|
||||||
|
}
|
||||||
|
const member = qqInfo.findGroupMember(ev.groupId, fromUin);
|
||||||
|
if (member) {
|
||||||
|
if (!ev.senderNick) ev.senderNick = member.nickname;
|
||||||
|
ev.senderCard = member.card;
|
||||||
|
ev.senderRole = member.role;
|
||||||
|
}
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === PkgType.TempMessage) {
|
||||||
|
const ev: TempMessage = {
|
||||||
|
kind: 'temp_message', time: timestamp, selfUin,
|
||||||
|
senderUin: fromUin, msgSeq: sequence,
|
||||||
|
elements: buildElements(false),
|
||||||
|
groupId: 0, senderNick: '',
|
||||||
|
};
|
||||||
|
if (msg.responseHead?.grp) {
|
||||||
|
ev.groupId = msg.responseHead.grp.groupUin ?? 0;
|
||||||
|
ev.senderNick = msg.responseHead.grp.memberName ?? '';
|
||||||
|
}
|
||||||
|
if (!ev.senderNick) {
|
||||||
|
const friend = qqInfo.findFriend(fromUin);
|
||||||
|
if (friend) ev.senderNick = friend.nickname;
|
||||||
|
}
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === PkgType.PrivateMessage ||
|
||||||
|
msgType === PkgType.ForwardFakePrivateMessage ||
|
||||||
|
msgType === PkgType.PrivateRecordMessage ||
|
||||||
|
msgType === PkgType.PrivateFileMessage) {
|
||||||
|
const ev: FriendMessage = {
|
||||||
|
kind: 'friend_message', time: timestamp, selfUin,
|
||||||
|
senderUin: fromUin, msgSeq: sequence,
|
||||||
|
msgId: msgId & 0x7FFFFFFF,
|
||||||
|
elements: buildElements(false),
|
||||||
|
senderNick: '',
|
||||||
|
};
|
||||||
|
if (msg.responseHead?.forward?.friendName) {
|
||||||
|
ev.senderNick = msg.responseHead.forward.friendName;
|
||||||
|
}
|
||||||
|
const friend = qqInfo.findFriend(fromUin);
|
||||||
|
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
|
||||||
|
return [ev];
|
||||||
|
}
|
||||||
|
|
||||||
|
// const preview = bytesToHex(content.subarray(0, Math.min(content.length, 48)));
|
||||||
|
return [];
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
// Highway HTTP client: session fetch and chunked binary upload.
|
||||||
|
// Port of src/bridge/src/highway_client.cpp
|
||||||
|
|
||||||
|
import net from 'net';
|
||||||
|
import type { Bridge } from '../bridge';
|
||||||
|
import { protoEncode, protoDecode } from '../../protobuf/decode';
|
||||||
|
import {
|
||||||
|
HttpConn0x6FF501RequestSchema,
|
||||||
|
HttpConn0x6FF501ResponseSchema,
|
||||||
|
ReqDataHighwayHeadSchema,
|
||||||
|
RespDataHighwayHeadSchema,
|
||||||
|
NTV2RichMediaHighwayExtSchema,
|
||||||
|
HighwayMsgInfoBodySchema,
|
||||||
|
} from '../proto/highway';
|
||||||
|
import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils';
|
||||||
|
|
||||||
|
const HIGHWAY_APP_ID = 1600001604;
|
||||||
|
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||||
|
|
||||||
|
export const PRIVATE_IMAGE_CMD_ID = 1003;
|
||||||
|
export const GROUP_IMAGE_CMD_ID = 1004;
|
||||||
|
|
||||||
|
export interface HighwaySession {
|
||||||
|
sigSession: Uint8Array;
|
||||||
|
sessionKey: Uint8Array;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ipv4ToString(value: number): string {
|
||||||
|
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchHighwaySession(bridge: Bridge): Promise<HighwaySession> {
|
||||||
|
const request = protoEncode({
|
||||||
|
httpConn: {
|
||||||
|
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
|
||||||
|
serviceTypes: [1, 5, 10, 21],
|
||||||
|
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
|
||||||
|
},
|
||||||
|
}, HttpConn0x6FF501RequestSchema);
|
||||||
|
|
||||||
|
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
|
||||||
|
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||||
|
throw new Error(result.errorMessage || 'HttpConn request failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const resp = protoDecode(result.responseData, HttpConn0x6FF501ResponseSchema);
|
||||||
|
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
|
||||||
|
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
|
||||||
|
throw new Error('HttpConn response missing sig_session');
|
||||||
|
}
|
||||||
|
|
||||||
|
const session: HighwaySession = {
|
||||||
|
sigSession: resp.httpConn.sigSession as Uint8Array,
|
||||||
|
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
|
||||||
|
host: 'htdata3.qq.com',
|
||||||
|
port: 80,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const si of resp.httpConn.serverInfos ?? []) {
|
||||||
|
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
|
||||||
|
for (const addr of si.serverAddrs) {
|
||||||
|
const ip = addr.ip ?? 0;
|
||||||
|
const port = addr.port ?? 0;
|
||||||
|
if (ip && port) {
|
||||||
|
session.host = ipv4ToString(ip);
|
||||||
|
session.port = port;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeHighwayHead(
|
||||||
|
uin: string, commandId: number, fileSize: number, offset: number, length: number,
|
||||||
|
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
|
||||||
|
): Uint8Array {
|
||||||
|
return protoEncode({
|
||||||
|
msgBaseHead: {
|
||||||
|
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
|
||||||
|
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
|
||||||
|
},
|
||||||
|
msgSegHead: {
|
||||||
|
serviceId: 0, filesize: BigInt(fileSize), dataOffset: BigInt(offset), dataLength: length,
|
||||||
|
retCode: 0, serviceTicket: sigSession, flag: 0, md5: chunkMd5, fileMd5, cacheAddr: 0, cachePort: 0,
|
||||||
|
},
|
||||||
|
bytesReqExtendInfo: extend,
|
||||||
|
timestamp: 0n,
|
||||||
|
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
|
||||||
|
}, ReqDataHighwayHeadSchema);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildHighwayExtend(
|
||||||
|
uKey: string, msgInfo: any, ipv4s: any[], sha1: Uint8Array,
|
||||||
|
): Uint8Array {
|
||||||
|
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
|
||||||
|
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
|
||||||
|
|
||||||
|
const first = msgInfoBody[0];
|
||||||
|
const networkIpv4s: any[] = [];
|
||||||
|
for (const ipv4 of ipv4s ?? []) {
|
||||||
|
const ip = ipv4.outIp ?? 0;
|
||||||
|
const port = ipv4.outPort ?? 0;
|
||||||
|
if (ip && port) {
|
||||||
|
networkIpv4s.push({ domain: { isEnable: true, ip: ipv4ToString(ip) }, port });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return protoEncode({
|
||||||
|
fileUuid: first?.index?.fileUuid ?? '',
|
||||||
|
uKey,
|
||||||
|
network: { ipv4s: networkIpv4s },
|
||||||
|
msgInfoBody: msgInfoBody.map((b: any) => ({
|
||||||
|
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||||
|
})),
|
||||||
|
blockSize: HIGHWAY_BLOCK_SIZE,
|
||||||
|
hash: { fileSha1: [sha1] },
|
||||||
|
}, NTV2RichMediaHighwayExtSchema);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- TCP-based HTTP highway upload ---
|
||||||
|
|
||||||
|
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const socket = net.createConnection({ host, port }, () => resolve(socket));
|
||||||
|
socket.setTimeout(timeoutMs);
|
||||||
|
socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); });
|
||||||
|
socket.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function socketWrite(socket: net.Socket, data: Uint8Array): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
socket.write(data, (err) => err ? reject(err) : resolve());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
let headerEnd = -1;
|
||||||
|
let contentLength = 0;
|
||||||
|
let totalNeeded = 0;
|
||||||
|
|
||||||
|
const checkComplete = () => {
|
||||||
|
const buf = Buffer.concat(chunks);
|
||||||
|
if (headerEnd < 0) {
|
||||||
|
const idx = buf.indexOf('\r\n\r\n');
|
||||||
|
if (idx >= 0) {
|
||||||
|
headerEnd = idx + 4;
|
||||||
|
const headerStr = buf.subarray(0, headerEnd).toString('ascii').toLowerCase();
|
||||||
|
const clMatch = headerStr.match(/content-length:\s*(\d+)/);
|
||||||
|
contentLength = clMatch ? parseInt(clMatch[1], 10) : 0;
|
||||||
|
totalNeeded = headerEnd + contentLength;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (headerEnd >= 0 && buf.length >= totalNeeded) {
|
||||||
|
socket.removeAllListeners('data');
|
||||||
|
socket.removeAllListeners('error');
|
||||||
|
resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); });
|
||||||
|
socket.on('error', reject);
|
||||||
|
socket.on('close', () => {
|
||||||
|
const buf = Buffer.concat(chunks);
|
||||||
|
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||||
|
else reject(new Error('connection closed before response'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function httpPostFrame(
|
||||||
|
socket: net.Socket, host: string, path: string, body: Uint8Array,
|
||||||
|
): Promise<Uint8Array> {
|
||||||
|
const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`;
|
||||||
|
await socketWrite(socket, Buffer.from(header, 'ascii'));
|
||||||
|
if (body.length > 0) await socketWrite(socket, body);
|
||||||
|
return readHttpResponseBody(socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function uploadHighwayHttp(
|
||||||
|
bridge: Bridge, session: HighwaySession, commandId: number,
|
||||||
|
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
|
||||||
|
): Promise<void> {
|
||||||
|
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.qqInfo.uin}`;
|
||||||
|
const socket = await tcpConnect(session.host, session.port);
|
||||||
|
|
||||||
|
try {
|
||||||
|
let offset = 0;
|
||||||
|
while (offset < bytes.length) {
|
||||||
|
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
|
||||||
|
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||||
|
const chunkMd5 = computeMd5(chunk);
|
||||||
|
const head = makeHighwayHead(
|
||||||
|
bridge.qqInfo.uin, commandId, bytes.length, offset, chunkSize,
|
||||||
|
chunkMd5, fileMd5, session.sigSession, extend,
|
||||||
|
);
|
||||||
|
const frame = packHighwayFrame(head, chunk);
|
||||||
|
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||||
|
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||||
|
const resp = protoDecode(respHead, RespDataHighwayHeadSchema);
|
||||||
|
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||||
|
throw new Error(`highway upload error_code=${resp.errorCode}`);
|
||||||
|
}
|
||||||
|
offset += chunkSize;
|
||||||
|
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
socket.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
// Image upload pipeline: load image, OIDB upload request, highway upload, build message element.
|
||||||
|
// Port of src/bridge/src/highway_upload_req.cpp + highway_client.cpp (image parts)
|
||||||
|
|
||||||
|
import type { Bridge } from '../bridge';
|
||||||
|
import type { MessageElement } from '../events';
|
||||||
|
import { protoEncode, protoDecode } from '../../protobuf/decode';
|
||||||
|
import { makeOidbBaseSchema } from '../proto/oidb';
|
||||||
|
import {
|
||||||
|
NTV2UploadRichMediaReqSchema,
|
||||||
|
NTV2UploadRichMediaRespSchema,
|
||||||
|
EncodableMediaMsgInfoSchema,
|
||||||
|
} from '../proto/highway';
|
||||||
|
import {
|
||||||
|
loadBinarySource, computeHashes, detectImageFormat,
|
||||||
|
} from './utils';
|
||||||
|
import {
|
||||||
|
fetchHighwaySession, uploadHighwayHttp, buildHighwayExtend,
|
||||||
|
PRIVATE_IMAGE_CMD_ID, GROUP_IMAGE_CMD_ID,
|
||||||
|
} from './highway-client';
|
||||||
|
|
||||||
|
interface ImageData {
|
||||||
|
bytes: Uint8Array;
|
||||||
|
md5: Uint8Array;
|
||||||
|
sha1: Uint8Array;
|
||||||
|
md5Hex: string;
|
||||||
|
sha1Hex: string;
|
||||||
|
fileName: string;
|
||||||
|
summary: string;
|
||||||
|
subType: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
picFormat: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadImage(element: MessageElement): Promise<ImageData> {
|
||||||
|
return loadImageFromSource(
|
||||||
|
element.url || element.fileId || '',
|
||||||
|
element.fileName ?? '',
|
||||||
|
element.subType ?? 0,
|
||||||
|
element.summary ?? '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadImageFromSource(source: string, fileName: string, subType: number, summary: string): Promise<ImageData> {
|
||||||
|
const loaded = await loadBinarySource(source, 'image');
|
||||||
|
const hashes = computeHashes(loaded.bytes);
|
||||||
|
const fmt = detectImageFormat(loaded.bytes);
|
||||||
|
|
||||||
|
const extMap: Record<number, string> = { 1000: '.jpg', 1001: '.png', 1002: '.webp', 1005: '.bmp', 2000: '.gif' };
|
||||||
|
const ext = extMap[fmt.format] ?? '.jpg';
|
||||||
|
|
||||||
|
let finalName = fileName || loaded.fileName;
|
||||||
|
if (!finalName) finalName = hashes.md5Hex + ext;
|
||||||
|
|
||||||
|
return {
|
||||||
|
bytes: loaded.bytes,
|
||||||
|
md5: hashes.md5,
|
||||||
|
sha1: hashes.sha1,
|
||||||
|
md5Hex: hashes.md5Hex,
|
||||||
|
sha1Hex: hashes.sha1Hex,
|
||||||
|
fileName: finalName,
|
||||||
|
summary: summary || (subType === 0 ? '[image]' : '[sticker]'),
|
||||||
|
subType,
|
||||||
|
width: fmt.width,
|
||||||
|
height: fmt.height,
|
||||||
|
picFormat: fmt.format,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startImageUpload(bridge: Bridge, isGroup: boolean, targetIdOrUid: string | number, image: ImageData): Promise<any> {
|
||||||
|
const body: any = {
|
||||||
|
reqHead: {
|
||||||
|
common: { requestId: 1, command: 100 },
|
||||||
|
scene: {
|
||||||
|
requestType: 2,
|
||||||
|
businessType: 1,
|
||||||
|
sceneType: isGroup ? 2 : 1,
|
||||||
|
...(isGroup
|
||||||
|
? { group: { groupUin: Number(targetIdOrUid) } }
|
||||||
|
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
|
||||||
|
},
|
||||||
|
client: { agentType: 2 },
|
||||||
|
},
|
||||||
|
upload: {
|
||||||
|
uploadInfo: [{
|
||||||
|
fileInfo: {
|
||||||
|
fileSize: image.bytes.length,
|
||||||
|
fileHash: image.md5Hex,
|
||||||
|
fileSha1: image.sha1Hex,
|
||||||
|
fileName: image.fileName,
|
||||||
|
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
|
||||||
|
width: image.width,
|
||||||
|
height: image.height,
|
||||||
|
time: 0,
|
||||||
|
original: 1,
|
||||||
|
},
|
||||||
|
subFileType: 0,
|
||||||
|
}],
|
||||||
|
tryFastUploadCompleted: true,
|
||||||
|
srvSendMsg: false,
|
||||||
|
clientRandomId: BigInt(Math.floor(Math.random() * 0x7FFFFFFFFFFFFFFF)),
|
||||||
|
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||||
|
extBizInfo: {
|
||||||
|
pic: {
|
||||||
|
bizType: image.subType,
|
||||||
|
textSummary: image.summary,
|
||||||
|
...(isGroup
|
||||||
|
? { reserveTroop: { subType: image.subType } }
|
||||||
|
: { reserveC2c: { subType: image.subType } }),
|
||||||
|
},
|
||||||
|
video: { bytesPbReserve: new Uint8Array(0) },
|
||||||
|
ptt: {
|
||||||
|
bytesReserve: new Uint8Array(0),
|
||||||
|
bytesPbReserve: new Uint8Array(0),
|
||||||
|
bytesGeneralFlags: new Uint8Array(0),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
clientSeq: 0,
|
||||||
|
noNeedCompatMsg: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const oidbCmd = isGroup ? 0x11C4 : 0x11C5;
|
||||||
|
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100';
|
||||||
|
|
||||||
|
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
|
||||||
|
const request = protoEncode({
|
||||||
|
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
|
||||||
|
}, baseSchema);
|
||||||
|
|
||||||
|
const result = await bridge.sendRawPacket(serviceCmd, request);
|
||||||
|
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||||
|
throw new Error(result.errorMessage || 'image upload request failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
|
||||||
|
const resp: any = protoDecode(result.responseData, respBaseSchema);
|
||||||
|
if (!resp) throw new Error('failed to decode upload response');
|
||||||
|
if (resp.errorCode && resp.errorCode !== 0) {
|
||||||
|
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const uploadBody = resp.body;
|
||||||
|
if (!uploadBody) throw new Error('upload response body missing');
|
||||||
|
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
|
||||||
|
throw new Error(uploadBody.respHead.message ?? 'image upload failed');
|
||||||
|
}
|
||||||
|
return uploadBody.upload;
|
||||||
|
}
|
||||||
|
|
||||||
|
function finalizeImageMsgInfo(upload: any, image: ImageData): Uint8Array {
|
||||||
|
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
|
||||||
|
|
||||||
|
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
|
||||||
|
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const extBizInfo: any = {};
|
||||||
|
if (upload.msgInfo.extBizInfo?.pic) {
|
||||||
|
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
|
||||||
|
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? image.subType;
|
||||||
|
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? image.summary;
|
||||||
|
} else {
|
||||||
|
extBizInfo.pic = { bizType: image.subType, textSummary: image.summary };
|
||||||
|
}
|
||||||
|
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
|
||||||
|
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
|
||||||
|
if (upload.msgInfo.extBizInfo?.busiType !== undefined) extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
|
||||||
|
|
||||||
|
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upload an image and return the encoded MsgInfo bytes to embed in a CommonElem.
|
||||||
|
*/
|
||||||
|
export async function uploadImageMsgInfo(
|
||||||
|
bridge: Bridge,
|
||||||
|
isGroup: boolean,
|
||||||
|
targetIdOrUid: string | number,
|
||||||
|
element: MessageElement,
|
||||||
|
): Promise<Uint8Array> {
|
||||||
|
const image = await loadImage(element);
|
||||||
|
const upload = await startImageUpload(bridge, isGroup, targetIdOrUid, image);
|
||||||
|
|
||||||
|
// Upload binary if uKey is present (not fast-uploaded)
|
||||||
|
const uKey = upload?.uKey ?? '';
|
||||||
|
if (uKey && upload?.msgInfo) {
|
||||||
|
const session = await fetchHighwaySession(bridge);
|
||||||
|
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], image.sha1);
|
||||||
|
const commandId = isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID;
|
||||||
|
await uploadHighwayHttp(bridge, session, commandId, image.bytes, image.md5, extend);
|
||||||
|
}
|
||||||
|
|
||||||
|
return finalizeImageMsgInfo(upload, image);
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
// Highway utilities: binary source loading, hashing, image format detection, frame packing.
|
||||||
|
// Port of src/bridge/src/highway_utils.h/.cpp
|
||||||
|
|
||||||
|
import { createHash } from 'crypto';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
export interface LoadedBinary {
|
||||||
|
bytes: Uint8Array;
|
||||||
|
fileName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageHashes {
|
||||||
|
md5: Uint8Array;
|
||||||
|
sha1: Uint8Array;
|
||||||
|
md5Hex: string;
|
||||||
|
sha1Hex: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageFormat {
|
||||||
|
format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Binary source loading ---
|
||||||
|
|
||||||
|
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
|
||||||
|
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||||
|
|
||||||
|
if (source.startsWith('base64://')) {
|
||||||
|
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (source.startsWith('http://') || source.startsWith('https://')) {
|
||||||
|
const resp = await fetch(source);
|
||||||
|
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||||
|
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||||
|
const fileName = guessFileNameFromUrl(source);
|
||||||
|
return { bytes, fileName };
|
||||||
|
}
|
||||||
|
|
||||||
|
// File path (strip file:// prefix)
|
||||||
|
let filePath = source;
|
||||||
|
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
|
||||||
|
// Windows: strip leading / before drive letter
|
||||||
|
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||||
|
|
||||||
|
const bytes = fs.readFileSync(filePath);
|
||||||
|
const fileName = path.basename(filePath);
|
||||||
|
return { bytes, fileName };
|
||||||
|
}
|
||||||
|
|
||||||
|
function guessFileNameFromUrl(url: string): string {
|
||||||
|
const queryPos = url.search(/[?#]/);
|
||||||
|
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
|
||||||
|
const lastSlash = pathPart.lastIndexOf('/');
|
||||||
|
return lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Hashing ---
|
||||||
|
|
||||||
|
export function computeHashes(data: Uint8Array): ImageHashes {
|
||||||
|
const md5 = createHash('md5').update(data).digest();
|
||||||
|
const sha1 = createHash('sha1').update(data).digest();
|
||||||
|
return {
|
||||||
|
md5: new Uint8Array(md5),
|
||||||
|
sha1: new Uint8Array(sha1),
|
||||||
|
md5Hex: md5.toString('hex'),
|
||||||
|
sha1Hex: sha1.toString('hex'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function computeMd5(data: Uint8Array): Uint8Array {
|
||||||
|
return new Uint8Array(createHash('md5').update(data).digest());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Image format detection (port of C++ detect_image_format) ---
|
||||||
|
|
||||||
|
function readBE16(data: Uint8Array, offset: number): number {
|
||||||
|
return (data[offset] << 8) | data[offset + 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
function readBE32(data: Uint8Array, offset: number): number {
|
||||||
|
return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readLE16(data: Uint8Array, offset: number): number {
|
||||||
|
return data[offset] | (data[offset + 1] << 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readLE32(data: Uint8Array, offset: number): number {
|
||||||
|
return (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readBE24(data: Uint8Array, offset: number): number {
|
||||||
|
return (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||||
|
let width = 0;
|
||||||
|
let height = 0;
|
||||||
|
|
||||||
|
// PNG
|
||||||
|
if (bytes.length >= 24 &&
|
||||||
|
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
|
||||||
|
width = readBE32(bytes, 16);
|
||||||
|
height = readBE32(bytes, 20);
|
||||||
|
return { format: 1001, width, height };
|
||||||
|
}
|
||||||
|
|
||||||
|
// GIF
|
||||||
|
if (bytes.length >= 10 &&
|
||||||
|
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
|
||||||
|
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
|
||||||
|
width = readLE16(bytes, 6);
|
||||||
|
height = readLE16(bytes, 8);
|
||||||
|
return { format: 2000, width, height };
|
||||||
|
}
|
||||||
|
|
||||||
|
// BMP
|
||||||
|
if (bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4D) {
|
||||||
|
width = readLE32(bytes, 18);
|
||||||
|
height = readLE32(bytes, 22);
|
||||||
|
return { format: 1005, width, height };
|
||||||
|
}
|
||||||
|
|
||||||
|
// WebP
|
||||||
|
if (bytes.length >= 30 &&
|
||||||
|
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
|
||||||
|
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
|
||||||
|
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) {
|
||||||
|
width = readLE16(bytes, 26);
|
||||||
|
height = readLE16(bytes, 28);
|
||||||
|
return { format: 1002, width, height };
|
||||||
|
}
|
||||||
|
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x4C) {
|
||||||
|
const bits = readLE32(bytes, 21);
|
||||||
|
width = (bits & 0x3FFF) + 1;
|
||||||
|
height = ((bits >> 14) & 0x3FFF) + 1;
|
||||||
|
return { format: 1002, width, height };
|
||||||
|
}
|
||||||
|
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x58) {
|
||||||
|
width = readBE24(bytes, 24) + 1;
|
||||||
|
height = readBE24(bytes, 27) + 1;
|
||||||
|
return { format: 1002, width, height };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// JPEG
|
||||||
|
if (bytes.length >= 4 && bytes[0] === 0xFF && bytes[1] === 0xD8) {
|
||||||
|
let offset = 2;
|
||||||
|
while (offset + 9 <= bytes.length) {
|
||||||
|
if (bytes[offset] !== 0xFF) { offset++; continue; }
|
||||||
|
const marker = bytes[offset + 1];
|
||||||
|
if (marker === 0xD8 || marker === 0xD9) { offset += 2; continue; }
|
||||||
|
if (offset + 4 > bytes.length) break;
|
||||||
|
const segLen = readBE16(bytes, offset + 2);
|
||||||
|
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
|
||||||
|
if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) {
|
||||||
|
height = readBE16(bytes, offset + 5);
|
||||||
|
width = readBE16(bytes, offset + 7);
|
||||||
|
return { format: 1000, width, height };
|
||||||
|
}
|
||||||
|
offset += 2 + segLen;
|
||||||
|
}
|
||||||
|
return { format: 1000, width: 0, height: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { format: 1000, width: 0, height: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Highway frame packing/unpacking ---
|
||||||
|
|
||||||
|
export function packHighwayFrame(head: Uint8Array, body: Uint8Array): Uint8Array {
|
||||||
|
const frame = new Uint8Array(9 + head.length + body.length + 1);
|
||||||
|
frame[0] = 0x28;
|
||||||
|
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||||
|
dv.setUint32(1, head.length, false);
|
||||||
|
dv.setUint32(5, body.length, false);
|
||||||
|
frame.set(head, 9);
|
||||||
|
frame.set(body, 9 + head.length);
|
||||||
|
frame[frame.length - 1] = 0x29;
|
||||||
|
return frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unpackHighwayFrame(frame: Uint8Array): { head: Uint8Array; body: Uint8Array } {
|
||||||
|
if (frame.length < 10 || frame[0] !== 0x28 || frame[frame.length - 1] !== 0x29) {
|
||||||
|
throw new Error('invalid highway response frame');
|
||||||
|
}
|
||||||
|
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||||
|
const headLen = dv.getUint32(1, false);
|
||||||
|
const bodyLen = dv.getUint32(5, false);
|
||||||
|
return {
|
||||||
|
head: frame.subarray(9, 9 + headLen),
|
||||||
|
body: frame.subarray(9 + headLen, 9 + headLen + bodyLen),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
// BridgeManager — manages per-UIN Bridge sessions.
|
||||||
|
// Wires NtqqHandler packets to appropriate Bridge instances.
|
||||||
|
// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp
|
||||||
|
|
||||||
|
import type { NtqqHandler } from '../protocol/ntqq-handler';
|
||||||
|
import type { PacketInfo } from '../protocol/types';
|
||||||
|
import type { QQEventVariant } from './events';
|
||||||
|
import { Bridge } from './bridge';
|
||||||
|
import { QQInfo } from './qq-info';
|
||||||
|
import type { PacketSender } from '../protocol/packet-sender';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
|
export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void;
|
||||||
|
export type SessionClosedCallback = (uin: string) => void;
|
||||||
|
export type BridgeEventCallback = (uin: string, event: QQEventVariant) => void;
|
||||||
|
|
||||||
|
interface QQSession {
|
||||||
|
qqInfo: QQInfo;
|
||||||
|
bridge: Bridge;
|
||||||
|
}
|
||||||
|
|
||||||
|
const log = createLogger('Bridge');
|
||||||
|
|
||||||
|
export class BridgeManager {
|
||||||
|
private sessions_ = new Map<string, QQSession>();
|
||||||
|
private pidToUin_ = new Map<number, string>();
|
||||||
|
private pidPacketClients_ = new Map<number, PacketSender>();
|
||||||
|
|
||||||
|
private onSessionStarted_: SessionStartedCallback | null = null;
|
||||||
|
private onSessionClosed_: SessionClosedCallback | null = null;
|
||||||
|
private onBridgeEvent_: BridgeEventCallback | null = null;
|
||||||
|
|
||||||
|
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
|
||||||
|
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
|
||||||
|
setEventCallback(cb: BridgeEventCallback): void { this.onBridgeEvent_ = cb; }
|
||||||
|
|
||||||
|
bind(ntqq: NtqqHandler): void {
|
||||||
|
ntqq.registerCmdAll((pkt: PacketInfo) => this.onPacket(pkt));
|
||||||
|
}
|
||||||
|
|
||||||
|
onPidDisconnected(pid: number): void {
|
||||||
|
this.pidPacketClients_.delete(pid);
|
||||||
|
const uin = this.pidToUin_.get(pid);
|
||||||
|
if (!uin) return;
|
||||||
|
|
||||||
|
this.pidToUin_.delete(pid);
|
||||||
|
const session = this.sessions_.get(uin);
|
||||||
|
if (!session) return;
|
||||||
|
|
||||||
|
session.bridge.detachPid(pid);
|
||||||
|
if (session.bridge.empty) {
|
||||||
|
this.sessions_.delete(uin);
|
||||||
|
log.debug('session closed: UIN=%s', uin);
|
||||||
|
if (this.onSessionClosed_) this.onSessionClosed_(uin);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static isRealUin(uin: string): boolean {
|
||||||
|
if (!uin || uin === '0') return false;
|
||||||
|
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||||
|
if (!BridgeManager.isRealUin(uin)) return;
|
||||||
|
|
||||||
|
this.pidPacketClients_.set(pid, packetClient);
|
||||||
|
|
||||||
|
const { session, created } = this.ensureSession(uin);
|
||||||
|
session.bridge.attachPid(pid);
|
||||||
|
session.bridge.setPacketClient(packetClient);
|
||||||
|
this.pidToUin_.set(pid, uin);
|
||||||
|
|
||||||
|
if (created) {
|
||||||
|
log.debug('session started: UIN=%s', uin);
|
||||||
|
if (this.onSessionStarted_) {
|
||||||
|
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private onPacket(pkt: PacketInfo): void {
|
||||||
|
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
|
||||||
|
const uin = pkt.uin;
|
||||||
|
|
||||||
|
// Ensure session exists
|
||||||
|
const { session, created } = this.ensureSession(uin);
|
||||||
|
|
||||||
|
// Attach PID if known
|
||||||
|
if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) {
|
||||||
|
session.bridge.attachPid(pkt.pid);
|
||||||
|
this.pidToUin_.set(pkt.pid, uin);
|
||||||
|
|
||||||
|
const client = this.pidPacketClients_.get(pkt.pid);
|
||||||
|
if (client) session.bridge.setPacketClient(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Notify session started on first real packet
|
||||||
|
if (created) {
|
||||||
|
log.debug('session started: UIN=%s', uin);
|
||||||
|
if (this.onSessionStarted_) {
|
||||||
|
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dispatch packet to bridge
|
||||||
|
session.bridge.onPacket(pkt);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureSession(uin: string): { session: QQSession; created: boolean } {
|
||||||
|
let session = this.sessions_.get(uin);
|
||||||
|
if (session) return { session, created: false };
|
||||||
|
|
||||||
|
const qqInfo = new QQInfo(uin);
|
||||||
|
const bridge = new Bridge(qqInfo);
|
||||||
|
session = { qqInfo, bridge };
|
||||||
|
this.sessions_.set(uin, session);
|
||||||
|
|
||||||
|
// Wire event callback
|
||||||
|
bridge.setEventCallback((event) => {
|
||||||
|
if (this.onBridgeEvent_) this.onBridgeEvent_(uin, event);
|
||||||
|
});
|
||||||
|
|
||||||
|
return { session, created: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
getSession(uin: string): QQSession | null {
|
||||||
|
return this.sessions_.get(uin) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
get sessions(): Map<string, { qqInfo: QQInfo; bridge: Bridge }> {
|
||||||
|
return this.sessions_;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
// Proto schemas for outgoing message actions.
|
||||||
|
// Port of src/bridge/include/bridge/proto/action.h
|
||||||
|
|
||||||
|
import type { ProtoSchema } from '../../protobuf/decode';
|
||||||
|
import { ElemSchema } from './element';
|
||||||
|
|
||||||
|
// --- Routing ---
|
||||||
|
|
||||||
|
export const RoutingC2CSchema = {
|
||||||
|
uin: { field: 1, type: 'uint32' as const },
|
||||||
|
uid: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const RoutingGroupSchema = {
|
||||||
|
groupCode: { field: 1, type: 'uint64' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const RoutingHeadSchema = {
|
||||||
|
c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema },
|
||||||
|
grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Content Head (for send) ---
|
||||||
|
|
||||||
|
export const SendContentHeadSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
subType: { field: 2, type: 'uint32' as const },
|
||||||
|
c2cCmd: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Message Control ---
|
||||||
|
|
||||||
|
export const MessageControlSchema = {
|
||||||
|
msgFlag: { field: 1, type: 'int32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- RichText (for send — only elems) ---
|
||||||
|
|
||||||
|
export const SendRichTextSchema = {
|
||||||
|
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- MessageBody (for send) ---
|
||||||
|
|
||||||
|
export const SendMessageBodySchema = {
|
||||||
|
richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- SendMessageRequest ---
|
||||||
|
|
||||||
|
export const SendMessageRequestSchema = {
|
||||||
|
routingHead: { field: 1, type: 'message' as const, schema: RoutingHeadSchema },
|
||||||
|
contentHead: { field: 2, type: 'message' as const, schema: SendContentHeadSchema },
|
||||||
|
messageBody: { field: 3, type: 'message' as const, schema: SendMessageBodySchema },
|
||||||
|
clientSequence: { field: 4, type: 'uint32' as const },
|
||||||
|
random: { field: 5, type: 'uint32' as const },
|
||||||
|
syncCookie: { field: 6, type: 'bytes' as const },
|
||||||
|
via: { field: 8, type: 'uint32' as const },
|
||||||
|
dataStatist: { field: 9, type: 'uint32' as const },
|
||||||
|
ctrl: { field: 12, type: 'message' as const, schema: MessageControlSchema },
|
||||||
|
multiSendSeq: { field: 14, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- SendMessageResponse ---
|
||||||
|
|
||||||
|
export const SendMessageResponseSchema = {
|
||||||
|
result: { field: 1, type: 'int32' as const },
|
||||||
|
errMsg: { field: 2, type: 'string' as const },
|
||||||
|
timestamp1: { field: 3, type: 'uint32' as const },
|
||||||
|
field10: { field: 10, type: 'uint32' as const },
|
||||||
|
groupSequence: { field: 11, type: 'uint32' as const },
|
||||||
|
timestamp2: { field: 12, type: 'uint32' as const },
|
||||||
|
privateSequence: { field: 14, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- MentionExtra (for building @mention text element) ---
|
||||||
|
|
||||||
|
export const MentionExtraSendSchema = {
|
||||||
|
type: { field: 3, type: 'int32' as const },
|
||||||
|
uin: { field: 4, type: 'uint32' as const },
|
||||||
|
field5: { field: 5, type: 'int32' as const },
|
||||||
|
uid: { field: 9, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- MarkdownData ---
|
||||||
|
|
||||||
|
export const MarkdownDataSchema = {
|
||||||
|
content: { field: 1, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
@@ -0,0 +1,418 @@
|
|||||||
|
// Proto schemas for QQ message elements.
|
||||||
|
// Port of src/bridge/include/bridge/proto/element.h
|
||||||
|
|
||||||
|
import type { ProtoSchema } from '../../protobuf/decode';
|
||||||
|
|
||||||
|
// --- Nested / helper schemas ---
|
||||||
|
|
||||||
|
export const CustomFacePbReserveSchema = {
|
||||||
|
subType: { field: 1, type: 'int32' as const },
|
||||||
|
summary: { field: 9, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NotOnlineImagePbReserve2Schema = {
|
||||||
|
field1: { field: 1, type: 'int32' as const },
|
||||||
|
field2: { field: 2, type: 'string' as const },
|
||||||
|
field3: { field: 3, type: 'int32' as const },
|
||||||
|
field4: { field: 4, type: 'int32' as const },
|
||||||
|
field5: { field: 5, type: 'int32' as const },
|
||||||
|
field7: { field: 7, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NotOnlineImagePbReserveSchema = {
|
||||||
|
subType: { field: 1, type: 'int32' as const },
|
||||||
|
field3: { field: 3, type: 'int32' as const },
|
||||||
|
field4: { field: 4, type: 'int32' as const },
|
||||||
|
summary: { field: 8, type: 'string' as const },
|
||||||
|
field10: { field: 10, type: 'int32' as const },
|
||||||
|
field20: { field: 20, type: 'message' as const, schema: NotOnlineImagePbReserve2Schema },
|
||||||
|
url: { field: 30, type: 'string' as const },
|
||||||
|
md5Str: { field: 31, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Core element schemas ---
|
||||||
|
|
||||||
|
export const TextElemSchema = {
|
||||||
|
str: { field: 1, type: 'string' as const },
|
||||||
|
link: { field: 2, type: 'string' as const },
|
||||||
|
attr6Buf: { field: 3, type: 'bytes' as const },
|
||||||
|
attr7Buf: { field: 4, type: 'bytes' as const },
|
||||||
|
buf: { field: 11, type: 'bytes' as const },
|
||||||
|
pbReserve: { field: 12, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FaceElemSchema = {
|
||||||
|
index: { field: 1, type: 'int32' as const },
|
||||||
|
oldData: { field: 2, type: 'bytes' as const },
|
||||||
|
buf: { field: 11, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OnlineImageSchema = {
|
||||||
|
guid: { field: 1, type: 'bytes' as const },
|
||||||
|
filePath: { field: 2, type: 'bytes' as const },
|
||||||
|
oldVerSendFile: { field: 3, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NotOnlineImageSchema = {
|
||||||
|
filePath: { field: 1, type: 'string' as const },
|
||||||
|
fileLen: { field: 2, type: 'uint32' as const },
|
||||||
|
downloadPath: { field: 3, type: 'string' as const },
|
||||||
|
oldVerSendFile: { field: 4, type: 'bytes' as const },
|
||||||
|
imgType: { field: 5, type: 'int32' as const },
|
||||||
|
previewsImage: { field: 6, type: 'bytes' as const },
|
||||||
|
picMd5: { field: 7, type: 'bytes' as const },
|
||||||
|
picHeight: { field: 8, type: 'uint32' as const },
|
||||||
|
picWidth: { field: 9, type: 'uint32' as const },
|
||||||
|
resId: { field: 10, type: 'string' as const },
|
||||||
|
flag: { field: 11, type: 'bytes' as const },
|
||||||
|
thumbUrl: { field: 12, type: 'string' as const },
|
||||||
|
original: { field: 13, type: 'int32' as const },
|
||||||
|
bigUrl: { field: 14, type: 'string' as const },
|
||||||
|
origUrl: { field: 15, type: 'string' as const },
|
||||||
|
bizType: { field: 16, type: 'int32' as const },
|
||||||
|
result: { field: 17, type: 'int32' as const },
|
||||||
|
index: { field: 18, type: 'int32' as const },
|
||||||
|
opFaceBuf: { field: 19, type: 'bytes' as const },
|
||||||
|
oldPicMd5: { field: 20, type: 'bool' as const },
|
||||||
|
thumbWidth: { field: 21, type: 'int32' as const },
|
||||||
|
thumbHeight: { field: 22, type: 'int32' as const },
|
||||||
|
fileId: { field: 23, type: 'int32' as const },
|
||||||
|
showLen: { field: 24, type: 'uint32' as const },
|
||||||
|
downloadLen: { field: 25, type: 'uint32' as const },
|
||||||
|
x400Url: { field: 26, type: 'string' as const },
|
||||||
|
x400Width: { field: 27, type: 'int32' as const },
|
||||||
|
x400Height: { field: 28, type: 'int32' as const },
|
||||||
|
pbRes: { field: 29, type: 'message' as const, schema: NotOnlineImagePbReserveSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const TransElemSchema = {
|
||||||
|
elemType: { field: 1, type: 'int32' as const },
|
||||||
|
elemValue: { field: 2, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const MarketFaceSchema = {
|
||||||
|
faceName: { field: 1, type: 'string' as const },
|
||||||
|
itemType: { field: 2, type: 'uint32' as const },
|
||||||
|
faceInfo: { field: 3, type: 'uint32' as const },
|
||||||
|
faceId: { field: 4, type: 'bytes' as const },
|
||||||
|
tabId: { field: 5, type: 'uint32' as const },
|
||||||
|
subType: { field: 6, type: 'uint32' as const },
|
||||||
|
key: { field: 7, type: 'bytes' as const },
|
||||||
|
param: { field: 8, type: 'bytes' as const },
|
||||||
|
mediaType: { field: 9, type: 'uint32' as const },
|
||||||
|
imageWidth: { field: 10, type: 'uint32' as const },
|
||||||
|
imageHeight: { field: 11, type: 'uint32' as const },
|
||||||
|
mobileParam: { field: 12, type: 'bytes' as const },
|
||||||
|
pbReserve: { field: 13, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const CustomFaceSchema = {
|
||||||
|
guid: { field: 1, type: 'bytes' as const },
|
||||||
|
filePath: { field: 2, type: 'string' as const },
|
||||||
|
shortcut: { field: 3, type: 'string' as const },
|
||||||
|
buffer: { field: 4, type: 'bytes' as const },
|
||||||
|
flag: { field: 5, type: 'bytes' as const },
|
||||||
|
oldData: { field: 6, type: 'bytes' as const },
|
||||||
|
fileId: { field: 7, type: 'uint32' as const },
|
||||||
|
serverIp: { field: 8, type: 'int32' as const },
|
||||||
|
serverPort: { field: 9, type: 'int32' as const },
|
||||||
|
fileType: { field: 10, type: 'int32' as const },
|
||||||
|
signature: { field: 11, type: 'bytes' as const },
|
||||||
|
useful: { field: 12, type: 'int32' as const },
|
||||||
|
md5: { field: 13, type: 'bytes' as const },
|
||||||
|
thumbUrl: { field: 14, type: 'string' as const },
|
||||||
|
bigUrl: { field: 15, type: 'string' as const },
|
||||||
|
origUrl: { field: 16, type: 'string' as const },
|
||||||
|
bizType: { field: 17, type: 'int32' as const },
|
||||||
|
repeatIndex: { field: 18, type: 'int32' as const },
|
||||||
|
repeatImage: { field: 19, type: 'int32' as const },
|
||||||
|
imageType: { field: 20, type: 'int32' as const },
|
||||||
|
index: { field: 21, type: 'int32' as const },
|
||||||
|
width: { field: 22, type: 'int32' as const },
|
||||||
|
height: { field: 23, type: 'int32' as const },
|
||||||
|
source: { field: 24, type: 'int32' as const },
|
||||||
|
size: { field: 25, type: 'uint32' as const },
|
||||||
|
origin: { field: 26, type: 'int32' as const },
|
||||||
|
thumbWidth: { field: 27, type: 'int32' as const },
|
||||||
|
thumbHeight: { field: 28, type: 'int32' as const },
|
||||||
|
showLen: { field: 29, type: 'int32' as const },
|
||||||
|
downloadLen: { field: 30, type: 'int32' as const },
|
||||||
|
x400Url: { field: 31, type: 'string' as const },
|
||||||
|
x400Width: { field: 32, type: 'int32' as const },
|
||||||
|
x400Height: { field: 33, type: 'int32' as const },
|
||||||
|
pbRes: { field: 34, type: 'message' as const, schema: CustomFacePbReserveSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const RichMsgSchema = {
|
||||||
|
template1: { field: 1, type: 'bytes' as const },
|
||||||
|
serviceId: { field: 2, type: 'int32' as const },
|
||||||
|
msgResId: { field: 3, type: 'bytes' as const },
|
||||||
|
rand: { field: 4, type: 'int32' as const },
|
||||||
|
seq: { field: 5, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupFileElemSchema = {
|
||||||
|
filename: { field: 1, type: 'string' as const },
|
||||||
|
fileSize: { field: 2, type: 'uint64' as const },
|
||||||
|
fileId: { field: 3, type: 'string' as const },
|
||||||
|
batchId: { field: 4, type: 'string' as const },
|
||||||
|
fileKey: { field: 5, type: 'string' as const },
|
||||||
|
mark: { field: 6, type: 'bytes' as const },
|
||||||
|
sequence: { field: 7, type: 'uint64' as const },
|
||||||
|
batchItemId: { field: 8, type: 'bytes' as const },
|
||||||
|
feedMsgTime: { field: 9, type: 'int32' as const },
|
||||||
|
pbReserve: { field: 10, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const ExtraInfoSchema = {
|
||||||
|
nick: { field: 1, type: 'bytes' as const },
|
||||||
|
groupCard: { field: 2, type: 'bytes' as const },
|
||||||
|
level: { field: 3, type: 'int32' as const },
|
||||||
|
flags: { field: 4, type: 'int32' as const },
|
||||||
|
groupMask: { field: 5, type: 'int32' as const },
|
||||||
|
msgTailId: { field: 6, type: 'int32' as const },
|
||||||
|
senderTitle: { field: 7, type: 'bytes' as const },
|
||||||
|
apnsTips: { field: 8, type: 'bytes' as const },
|
||||||
|
uin: { field: 9, type: 'uint64' as const },
|
||||||
|
msgStateFlag: { field: 10, type: 'int32' as const },
|
||||||
|
apnsSoundType: { field: 11, type: 'int32' as const },
|
||||||
|
newGroupFlag: { field: 12, type: 'int32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const VideoFileSchema = {
|
||||||
|
fileUuid: { field: 1, type: 'string' as const },
|
||||||
|
fileMd5: { field: 2, type: 'bytes' as const },
|
||||||
|
fileName: { field: 3, type: 'string' as const },
|
||||||
|
fileFormat: { field: 4, type: 'int32' as const },
|
||||||
|
fileTime: { field: 5, type: 'int32' as const },
|
||||||
|
fileSize: { field: 6, type: 'int32' as const },
|
||||||
|
thumbWidth: { field: 7, type: 'int32' as const },
|
||||||
|
thumbHeight: { field: 8, type: 'int32' as const },
|
||||||
|
thumbFileMd5: { field: 9, type: 'bytes' as const },
|
||||||
|
source: { field: 10, type: 'bytes' as const },
|
||||||
|
thumbFileSize:{ field: 11, type: 'int32' as const },
|
||||||
|
busiType: { field: 12, type: 'int32' as const },
|
||||||
|
fromChatType: { field: 13, type: 'int32' as const },
|
||||||
|
toChatType: { field: 14, type: 'int32' as const },
|
||||||
|
supportProgressive: { field: 15, type: 'bool' as const },
|
||||||
|
fileWidth: { field: 16, type: 'int32' as const },
|
||||||
|
fileHeight: { field: 17, type: 'int32' as const },
|
||||||
|
subBusiType: { field: 18, type: 'int32' as const },
|
||||||
|
videoAttr: { field: 19, type: 'int32' as const },
|
||||||
|
pbReserve: { field: 24, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const SrcMsgSchema = {
|
||||||
|
origSeqs: { field: 1, type: 'repeated_uint32' as const },
|
||||||
|
senderUin: { field: 2, type: 'uint64' as const },
|
||||||
|
time: { field: 3, type: 'int32' as const },
|
||||||
|
flag: { field: 4, type: 'int32' as const },
|
||||||
|
elemsRaw: { field: 5, type: 'repeated_bytes' as const },
|
||||||
|
type: { field: 6, type: 'int32' as const },
|
||||||
|
richMsg: { field: 7, type: 'bytes' as const },
|
||||||
|
pbReserve: { field: 8, type: 'bytes' as const },
|
||||||
|
sourceMsg: { field: 9, type: 'bytes' as const },
|
||||||
|
toUin: { field: 10, type: 'uint64' as const },
|
||||||
|
troopName: { field: 11, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const LightAppElemSchema = {
|
||||||
|
data: { field: 1, type: 'bytes' as const },
|
||||||
|
msgResid: { field: 2, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const CommonElemSchema = {
|
||||||
|
serviceType: { field: 1, type: 'int32' as const },
|
||||||
|
pbElem: { field: 2, type: 'bytes' as const },
|
||||||
|
businessType: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GeneralFlagsSchema = {
|
||||||
|
bubbleDiyTextId: { field: 1, type: 'int32' as const },
|
||||||
|
groupFlagNew: { field: 2, type: 'int32' as const },
|
||||||
|
uin: { field: 3, type: 'uint64' as const },
|
||||||
|
longTextFlag: { field: 6, type: 'int32' as const },
|
||||||
|
longTextResId: { field: 7, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Elem (union of all element types) ---
|
||||||
|
|
||||||
|
export const ElemSchema = {
|
||||||
|
text: { field: 1, type: 'message' as const, schema: TextElemSchema },
|
||||||
|
face: { field: 2, type: 'message' as const, schema: FaceElemSchema },
|
||||||
|
onlineImage: { field: 3, type: 'message' as const, schema: OnlineImageSchema },
|
||||||
|
notOnlineImage: { field: 4, type: 'message' as const, schema: NotOnlineImageSchema },
|
||||||
|
transElem: { field: 5, type: 'message' as const, schema: TransElemSchema },
|
||||||
|
marketFace: { field: 6, type: 'message' as const, schema: MarketFaceSchema },
|
||||||
|
customFace: { field: 8, type: 'message' as const, schema: CustomFaceSchema },
|
||||||
|
richMsg: { field: 12, type: 'message' as const, schema: RichMsgSchema },
|
||||||
|
groupFile: { field: 13, type: 'message' as const, schema: GroupFileElemSchema },
|
||||||
|
extraInfo: { field: 16, type: 'message' as const, schema: ExtraInfoSchema },
|
||||||
|
videoFile: { field: 19, type: 'message' as const, schema: VideoFileSchema },
|
||||||
|
generalFlags: { field: 37, type: 'message' as const, schema: GeneralFlagsSchema },
|
||||||
|
srcMsg: { field: 45, type: 'message' as const, schema: SrcMsgSchema },
|
||||||
|
lightApp: { field: 51, type: 'message' as const, schema: LightAppElemSchema },
|
||||||
|
commonElem: { field: 53, type: 'message' as const, schema: CommonElemSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Extra decode types (for CommonElem.pbElem sub-messages) ---
|
||||||
|
|
||||||
|
export const MentionExtraSchema = {
|
||||||
|
type: { field: 3, type: 'int32' as const },
|
||||||
|
uin: { field: 4, type: 'uint32' as const },
|
||||||
|
field5: { field: 5, type: 'int32' as const },
|
||||||
|
uid: { field: 9, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const QFaceExtraSchema = {
|
||||||
|
packId: { field: 1, type: 'string' as const },
|
||||||
|
stickerId: { field: 2, type: 'string' as const },
|
||||||
|
qsid: { field: 3, type: 'int32' as const },
|
||||||
|
sourceType: { field: 4, type: 'int32' as const },
|
||||||
|
stickerType: { field: 5, type: 'int32' as const },
|
||||||
|
resultId: { field: 6, type: 'string' as const },
|
||||||
|
text: { field: 7, type: 'string' as const },
|
||||||
|
randomType: { field: 9, type: 'int32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const QSmallFaceExtraSchema = {
|
||||||
|
faceId: { field: 1, type: 'uint32' as const },
|
||||||
|
preview: { field: 2, type: 'string' as const },
|
||||||
|
preview2: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- NTQQ MsgInfo types (CommonElem service_type 48) ---
|
||||||
|
|
||||||
|
export const FileTypeSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
picFormat: { field: 2, type: 'uint32' as const },
|
||||||
|
videoFormat: { field: 3, type: 'uint32' as const },
|
||||||
|
voiceFormat: { field: 4, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileInfoSchema = {
|
||||||
|
fileSize: { field: 1, type: 'uint32' as const },
|
||||||
|
fileHash: { field: 2, type: 'string' as const },
|
||||||
|
fileSha1: { field: 3, type: 'string' as const },
|
||||||
|
fileName: { field: 4, type: 'string' as const },
|
||||||
|
type: { field: 5, type: 'message' as const, schema: FileTypeSchema },
|
||||||
|
width: { field: 6, type: 'uint32' as const },
|
||||||
|
height: { field: 7, type: 'uint32' as const },
|
||||||
|
time: { field: 8, type: 'uint32' as const },
|
||||||
|
original: { field: 9, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const IndexNodeSchema = {
|
||||||
|
info: { field: 1, type: 'message' as const, schema: FileInfoSchema },
|
||||||
|
fileUuid: { field: 2, type: 'string' as const },
|
||||||
|
storeId: { field: 3, type: 'uint32' as const },
|
||||||
|
uploadTime: { field: 4, type: 'uint32' as const },
|
||||||
|
ttl: { field: 5, type: 'uint32' as const },
|
||||||
|
subType: { field: 6, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const PicUrlExtInfoSchema = {
|
||||||
|
originalParameter: { field: 1, type: 'string' as const },
|
||||||
|
bigParameter: { field: 2, type: 'string' as const },
|
||||||
|
thumbParameter: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const PictureInfoSchema = {
|
||||||
|
urlPath: { field: 1, type: 'string' as const },
|
||||||
|
ext: { field: 2, type: 'message' as const, schema: PicUrlExtInfoSchema },
|
||||||
|
domain: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const PicExtDataSchema = {
|
||||||
|
subType: { field: 1, type: 'uint32' as const },
|
||||||
|
textSummary: { field: 9, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const PicExtBizInfoSchema = {
|
||||||
|
bizType: { field: 1, type: 'uint32' as const },
|
||||||
|
textSummary: { field: 2, type: 'string' as const },
|
||||||
|
bytesPbReserveC2c: { field: 11, type: 'bytes' as const },
|
||||||
|
extData: { field: 12, type: 'message' as const, schema: PicExtDataSchema },
|
||||||
|
fromScene: { field: 1001, type: 'uint32' as const },
|
||||||
|
toScene: { field: 1002, type: 'uint32' as const },
|
||||||
|
oldFileId: { field: 1003, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const VideoExtBizInfoSchema = {
|
||||||
|
fromScene: { field: 1, type: 'uint32' as const },
|
||||||
|
toScene: { field: 2, type: 'uint32' as const },
|
||||||
|
bytesPbReserve: { field: 3, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const PttExtBizInfoSchema = {
|
||||||
|
srcUin: { field: 1, type: 'uint64' as const },
|
||||||
|
pttScene: { field: 2, type: 'uint32' as const },
|
||||||
|
pttType: { field: 3, type: 'uint32' as const },
|
||||||
|
changeVoice: { field: 4, type: 'uint32' as const },
|
||||||
|
waveform: { field: 5, type: 'bytes' as const },
|
||||||
|
autoConvertText: { field: 6, type: 'uint32' as const },
|
||||||
|
bytesReserve: { field: 11, type: 'bytes' as const },
|
||||||
|
bytesPbReserve: { field: 12, type: 'bytes' as const },
|
||||||
|
bytesGeneralFlags: { field: 13, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const ExtBizInfoSchema = {
|
||||||
|
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
|
||||||
|
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
|
||||||
|
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
|
||||||
|
busiType: { field: 10, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const C2cSourceSchema = {
|
||||||
|
friendUid: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const TroopSourceSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const HashSumSchema = {
|
||||||
|
bytesPbReserveC2c: { field: 201, type: 'message' as const, schema: C2cSourceSchema },
|
||||||
|
troopSource: { field: 202, type: 'message' as const, schema: TroopSourceSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const MsgInfoBodySchema = {
|
||||||
|
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
|
||||||
|
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
|
||||||
|
fileExist: { field: 5, type: 'bool' as const },
|
||||||
|
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const MsgInfoSchema = {
|
||||||
|
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: MsgInfoBodySchema },
|
||||||
|
extBizInfo: { field: 2, type: 'message' as const, schema: ExtBizInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- GroupFileExtra (TransElem type=24) ---
|
||||||
|
|
||||||
|
export const GroupFileInfoSchema = {
|
||||||
|
busId: { field: 1, type: 'uint32' as const },
|
||||||
|
fileId: { field: 2, type: 'string' as const },
|
||||||
|
fileSize: { field: 3, type: 'uint64' as const },
|
||||||
|
fileName: { field: 4, type: 'string' as const },
|
||||||
|
fileSha: { field: 5, type: 'bytes' as const },
|
||||||
|
extInfoString: { field: 6, type: 'string' as const },
|
||||||
|
fileMd5: { field: 7, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupFileExtraInnerSchema = {
|
||||||
|
info: { field: 2, type: 'message' as const, schema: GroupFileInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupFileExtraSchema = {
|
||||||
|
inner: { field: 7, type: 'message' as const, schema: GroupFileExtraInnerSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Preserve (for message receipt info) ---
|
||||||
|
|
||||||
|
export const PreserveSchema = {
|
||||||
|
messageId: { field: 3, type: 'uint64' as const },
|
||||||
|
senderUid: { field: 6, type: 'string' as const },
|
||||||
|
receiverUid: { field: 7, type: 'string' as const },
|
||||||
|
clientSequence: { field: 8, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
@@ -0,0 +1,354 @@
|
|||||||
|
// Proto schemas for highway upload protocol.
|
||||||
|
// Port of src/bridge/include/bridge/proto/highway.h + action.h (HttpConn)
|
||||||
|
|
||||||
|
import type { ProtoSchema } from '../../protobuf/decode';
|
||||||
|
import {
|
||||||
|
IndexNodeSchema,
|
||||||
|
PictureInfoSchema,
|
||||||
|
HashSumSchema,
|
||||||
|
PicExtBizInfoSchema,
|
||||||
|
VideoExtBizInfoSchema,
|
||||||
|
PttExtBizInfoSchema,
|
||||||
|
} from '../proto/element';
|
||||||
|
|
||||||
|
// --- DataHighwayHead ---
|
||||||
|
|
||||||
|
export const DataHighwayHeadSchema = {
|
||||||
|
version: { field: 1, type: 'uint32' as const },
|
||||||
|
uin: { field: 2, type: 'string' as const },
|
||||||
|
command: { field: 3, type: 'string' as const },
|
||||||
|
seq: { field: 4, type: 'uint32' as const },
|
||||||
|
retryTimes:{ field: 5, type: 'uint32' as const },
|
||||||
|
appId: { field: 6, type: 'uint32' as const },
|
||||||
|
dataFlag: { field: 7, type: 'uint32' as const },
|
||||||
|
commandId: { field: 8, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const SegHeadSchema = {
|
||||||
|
serviceId: { field: 1, type: 'uint32' as const },
|
||||||
|
filesize: { field: 2, type: 'uint64' as const },
|
||||||
|
dataOffset: { field: 3, type: 'uint64' as const },
|
||||||
|
dataLength: { field: 4, type: 'uint32' as const },
|
||||||
|
retCode: { field: 5, type: 'uint32' as const },
|
||||||
|
serviceTicket: { field: 6, type: 'bytes' as const },
|
||||||
|
flag: { field: 7, type: 'uint32' as const },
|
||||||
|
md5: { field: 8, type: 'bytes' as const },
|
||||||
|
fileMd5: { field: 9, type: 'bytes' as const },
|
||||||
|
cacheAddr: { field: 10, type: 'uint32' as const },
|
||||||
|
cachePort: { field: 13, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const LoginSigHeadSchema = {
|
||||||
|
loginSigType: { field: 1, type: 'uint32' as const },
|
||||||
|
appId: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const ReqDataHighwayHeadSchema = {
|
||||||
|
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
|
||||||
|
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
|
||||||
|
bytesReqExtendInfo: { field: 3, type: 'bytes' as const },
|
||||||
|
timestamp: { field: 4, type: 'uint64' as const },
|
||||||
|
msgLoginSigHead: { field: 5, type: 'message' as const, schema: LoginSigHeadSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const RespDataHighwayHeadSchema = {
|
||||||
|
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
|
||||||
|
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
|
||||||
|
errorCode: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Highway extend (NTV2RichMediaHighwayExt) ---
|
||||||
|
|
||||||
|
export const HighwayDomainSchema = {
|
||||||
|
isEnable: { field: 1, type: 'bool' as const },
|
||||||
|
ip: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const HighwayIPv4Schema = {
|
||||||
|
domain: { field: 1, type: 'message' as const, schema: HighwayDomainSchema },
|
||||||
|
port: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const HighwayNetworkSchema = {
|
||||||
|
ipv4s: { field: 1, type: 'repeated_message' as const, schema: HighwayIPv4Schema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const HighwayHashSchema = {
|
||||||
|
fileSha1: { field: 1, type: 'repeated_bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const HighwayMsgInfoBodySchema = {
|
||||||
|
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
|
||||||
|
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
|
||||||
|
fileExist: { field: 5, type: 'bool' as const },
|
||||||
|
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2RichMediaHighwayExtSchema = {
|
||||||
|
fileUuid: { field: 1, type: 'string' as const },
|
||||||
|
uKey: { field: 2, type: 'string' as const },
|
||||||
|
network: { field: 5, type: 'message' as const, schema: HighwayNetworkSchema },
|
||||||
|
msgInfoBody: { field: 6, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
|
||||||
|
blockSize: { field: 10, type: 'uint32' as const },
|
||||||
|
hash: { field: 11, type: 'message' as const, schema: HighwayHashSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- File upload extend (group/private file highway) ---
|
||||||
|
|
||||||
|
export const FileUploadUrlSchema = {
|
||||||
|
unknown: { field: 1, type: 'int32' as const },
|
||||||
|
host: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileUploadHostSchema = {
|
||||||
|
url: { field: 1, type: 'message' as const, schema: FileUploadUrlSchema },
|
||||||
|
port: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileUploadHostConfigSchema = {
|
||||||
|
hosts: { field: 200, type: 'repeated_message' as const, schema: FileUploadHostSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileUploadNameInfoSchema = {
|
||||||
|
fileName: { field: 100, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileUploadClientInfoSchema = {
|
||||||
|
clientType: { field: 100, type: 'int32' as const },
|
||||||
|
appId: { field: 200, type: 'string' as const },
|
||||||
|
terminalType: { field: 300, type: 'int32' as const },
|
||||||
|
clientVer: { field: 400, type: 'string' as const },
|
||||||
|
unknown: { field: 600, type: 'int32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileUploadFileEntrySchema = {
|
||||||
|
fileSize: { field: 100, type: 'uint64' as const },
|
||||||
|
md5: { field: 200, type: 'bytes' as const },
|
||||||
|
checkKey: { field: 300, type: 'bytes' as const },
|
||||||
|
md5S2: { field: 400, type: 'bytes' as const },
|
||||||
|
fileId: { field: 600, type: 'string' as const },
|
||||||
|
uploadKey: { field: 700, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileUploadBusiInfoSchema = {
|
||||||
|
busId: { field: 1, type: 'int32' as const },
|
||||||
|
senderUin: { field: 100, type: 'uint64' as const },
|
||||||
|
receiverUin: { field: 200, type: 'uint64' as const },
|
||||||
|
groupCode: { field: 400, type: 'uint64' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileUploadEntrySchema = {
|
||||||
|
busiBuff: { field: 100, type: 'message' as const, schema: FileUploadBusiInfoSchema },
|
||||||
|
fileEntry: { field: 200, type: 'message' as const, schema: FileUploadFileEntrySchema },
|
||||||
|
clientInfo: { field: 300, type: 'message' as const, schema: FileUploadClientInfoSchema },
|
||||||
|
fileNameInfo: { field: 400, type: 'message' as const, schema: FileUploadNameInfoSchema },
|
||||||
|
host: { field: 500, type: 'message' as const, schema: FileUploadHostConfigSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileUploadExtSchema = {
|
||||||
|
unknown1: { field: 1, type: 'int32' as const },
|
||||||
|
unknown2: { field: 2, type: 'int32' as const },
|
||||||
|
unknown3: { field: 3, type: 'int32' as const },
|
||||||
|
entry: { field: 100, type: 'message' as const, schema: FileUploadEntrySchema },
|
||||||
|
unknown200: { field: 200, type: 'int32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Encodable MsgInfo (for embedding in message element) ---
|
||||||
|
|
||||||
|
export const EncodableMediaExtBizInfoSchema = {
|
||||||
|
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
|
||||||
|
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
|
||||||
|
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
|
||||||
|
busiType: { field: 10, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const EncodableMediaMsgInfoSchema = {
|
||||||
|
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
|
||||||
|
extBizInfo: { field: 2, type: 'message' as const, schema: EncodableMediaExtBizInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- HttpConn.0x6ff_501 (highway session) ---
|
||||||
|
|
||||||
|
export const HttpConnSchema = {
|
||||||
|
field1: { field: 1, type: 'int32' as const },
|
||||||
|
field2: { field: 2, type: 'int32' as const },
|
||||||
|
field3: { field: 3, type: 'int32' as const },
|
||||||
|
field4: { field: 4, type: 'int32' as const },
|
||||||
|
field6: { field: 6, type: 'int32' as const },
|
||||||
|
serviceTypes: { field: 7, type: 'repeated_uint32' as const },
|
||||||
|
field9: { field: 9, type: 'int32' as const },
|
||||||
|
field10: { field: 10, type: 'int32' as const },
|
||||||
|
field11: { field: 11, type: 'int32' as const },
|
||||||
|
ver: { field: 15, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const HttpConn0x6FF501RequestSchema = {
|
||||||
|
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const ServerAddrSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
ip: { field: 2, type: 'uint32' as const }, // fixed32 as uint32
|
||||||
|
port: { field: 3, type: 'uint32' as const },
|
||||||
|
area: { field: 4, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const ServerInfoSchema = {
|
||||||
|
serviceType: { field: 1, type: 'uint32' as const },
|
||||||
|
serverAddrs: { field: 2, type: 'repeated_message' as const, schema: ServerAddrSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const HttpConnResponseSchema = {
|
||||||
|
sigSession: { field: 1, type: 'bytes' as const },
|
||||||
|
sessionKey: { field: 2, type: 'bytes' as const },
|
||||||
|
serverInfos: { field: 3, type: 'repeated_message' as const, schema: ServerInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const HttpConn0x6FF501ResponseSchema = {
|
||||||
|
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnResponseSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- NTV2 Upload Request (for OIDB 0x11C4/0x11C5) ---
|
||||||
|
|
||||||
|
export const NTV2FileTypeSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
picFormat: { field: 2, type: 'uint32' as const },
|
||||||
|
videoFormat: { field: 3, type: 'uint32' as const },
|
||||||
|
voiceFormat: { field: 4, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2FileInfoSchema = {
|
||||||
|
fileSize: { field: 1, type: 'uint32' as const },
|
||||||
|
fileHash: { field: 2, type: 'string' as const },
|
||||||
|
fileSha1: { field: 3, type: 'string' as const },
|
||||||
|
fileName: { field: 4, type: 'string' as const },
|
||||||
|
type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema },
|
||||||
|
width: { field: 6, type: 'uint32' as const },
|
||||||
|
height: { field: 7, type: 'uint32' as const },
|
||||||
|
time: { field: 8, type: 'uint32' as const },
|
||||||
|
original: { field: 9, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2UploadInfoSchema = {
|
||||||
|
fileInfo: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema },
|
||||||
|
subFileType: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2PicReserveC2CSchema = {
|
||||||
|
subType: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2PicReserveTroopSchema = {
|
||||||
|
subType: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2PicExtBizInfoSchema = {
|
||||||
|
bizType: { field: 1, type: 'uint32' as const },
|
||||||
|
textSummary: { field: 2, type: 'string' as const },
|
||||||
|
reserveC2c: { field: 11, type: 'message' as const, schema: NTV2PicReserveC2CSchema },
|
||||||
|
reserveTroop: { field: 12, type: 'message' as const, schema: NTV2PicReserveTroopSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2VideoExtBizInfoSchema = {
|
||||||
|
bytesPbReserve: { field: 3, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2PttExtBizInfoSchema = {
|
||||||
|
bytesReserve: { field: 11, type: 'bytes' as const },
|
||||||
|
bytesPbReserve: { field: 12, type: 'bytes' as const },
|
||||||
|
bytesGeneralFlags: { field: 13, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2ExtBizInfoSchema = {
|
||||||
|
pic: { field: 1, type: 'message' as const, schema: NTV2PicExtBizInfoSchema },
|
||||||
|
video: { field: 2, type: 'message' as const, schema: NTV2VideoExtBizInfoSchema },
|
||||||
|
ptt: { field: 3, type: 'message' as const, schema: NTV2PttExtBizInfoSchema },
|
||||||
|
busiType: { field: 10, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2UploadReqSchema = {
|
||||||
|
uploadInfo: { field: 1, type: 'repeated_message' as const, schema: NTV2UploadInfoSchema },
|
||||||
|
tryFastUploadCompleted: { field: 2, type: 'bool' as const },
|
||||||
|
srvSendMsg: { field: 3, type: 'bool' as const },
|
||||||
|
clientRandomId: { field: 4, type: 'uint64' as const },
|
||||||
|
compatQmsgSceneType: { field: 5, type: 'uint32' as const },
|
||||||
|
extBizInfo: { field: 6, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
|
||||||
|
clientSeq: { field: 7, type: 'uint32' as const },
|
||||||
|
noNeedCompatMsg: { field: 8, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2C2CUserInfoSchema = {
|
||||||
|
accountType: { field: 1, type: 'uint32' as const },
|
||||||
|
targetUid: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2GroupInfoSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2UploadSceneInfoSchema = {
|
||||||
|
requestType: { field: 101, type: 'uint32' as const },
|
||||||
|
businessType: { field: 102, type: 'uint32' as const },
|
||||||
|
sceneType: { field: 200, type: 'uint32' as const },
|
||||||
|
c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema },
|
||||||
|
group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2CommonHeadSchema = {
|
||||||
|
requestId: { field: 1, type: 'uint32' as const },
|
||||||
|
command: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2ClientMetaSchema = {
|
||||||
|
agentType: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2UploadReqHeadSchema = {
|
||||||
|
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
|
||||||
|
scene: { field: 2, type: 'message' as const, schema: NTV2UploadSceneInfoSchema },
|
||||||
|
client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2UploadRichMediaReqSchema = {
|
||||||
|
reqHead: { field: 1, type: 'message' as const, schema: NTV2UploadReqHeadSchema },
|
||||||
|
upload: { field: 2, type: 'message' as const, schema: NTV2UploadReqSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- NTV2 Upload Response ---
|
||||||
|
|
||||||
|
export const NTV2IPv4Schema = {
|
||||||
|
outIp: { field: 1, type: 'uint32' as const },
|
||||||
|
outPort: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2SubFileInfoRespSchema = {
|
||||||
|
subType: { field: 1, type: 'uint32' as const },
|
||||||
|
uKey: { field: 2, type: 'string' as const },
|
||||||
|
uKeyTtl: { field: 3, type: 'uint32' as const },
|
||||||
|
ipv4s: { field: 4, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2UploadRespMsgInfoSchema = {
|
||||||
|
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
|
||||||
|
extBizInfo: { field: 2, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2UploadRespBodySchema = {
|
||||||
|
uKey: { field: 1, type: 'string' as const },
|
||||||
|
uKeyTtl: { field: 2, type: 'uint32' as const },
|
||||||
|
ipv4s: { field: 3, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
|
||||||
|
msgSeq: { field: 5, type: 'uint64' as const },
|
||||||
|
msgInfo: { field: 6, type: 'message' as const, schema: NTV2UploadRespMsgInfoSchema },
|
||||||
|
subFileInfos: { field: 10, type: 'repeated_message' as const, schema: NTV2SubFileInfoRespSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2UploadRespHeadSchema = {
|
||||||
|
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
|
||||||
|
retCode: { field: 2, type: 'uint32' as const },
|
||||||
|
message: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2UploadRichMediaRespSchema = {
|
||||||
|
respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema },
|
||||||
|
upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import type { ProtoSchema } from '../../protobuf/decode';
|
||||||
|
import { PushMsgBodySchema } from './message';
|
||||||
|
|
||||||
|
export const LongMsgUidSchema = {
|
||||||
|
uid: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const LongMsgSettingsSchema = {
|
||||||
|
field1: { field: 1, type: 'uint32' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
field3: { field: 3, type: 'uint32' as const },
|
||||||
|
field4: { field: 4, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const SendLongMsgInfoSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
uid: { field: 2, type: 'message' as const, schema: LongMsgUidSchema },
|
||||||
|
groupUin: { field: 3, type: 'uint32' as const },
|
||||||
|
payload: { field: 4, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const SendLongMsgReqSchema = {
|
||||||
|
info: { field: 2, type: 'message' as const, schema: SendLongMsgInfoSchema },
|
||||||
|
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const SendLongMsgRespResultSchema = {
|
||||||
|
resId: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const SendLongMsgRespSchema = {
|
||||||
|
result: { field: 2, type: 'message' as const, schema: SendLongMsgRespResultSchema },
|
||||||
|
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const RecvLongMsgInfoSchema = {
|
||||||
|
uid: { field: 1, type: 'message' as const, schema: LongMsgUidSchema },
|
||||||
|
resId: { field: 2, type: 'string' as const },
|
||||||
|
acquire: { field: 3, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const RecvLongMsgReqSchema = {
|
||||||
|
info: { field: 1, type: 'message' as const, schema: RecvLongMsgInfoSchema },
|
||||||
|
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const RecvLongMsgRespResultSchema = {
|
||||||
|
resId: { field: 3, type: 'string' as const },
|
||||||
|
payload: { field: 4, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const RecvLongMsgRespSchema = {
|
||||||
|
result: { field: 1, type: 'message' as const, schema: RecvLongMsgRespResultSchema },
|
||||||
|
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const LongMsgContentSchema = {
|
||||||
|
msgBody: { field: 1, type: 'repeated_message' as const, schema: PushMsgBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const LongMsgActionSchema = {
|
||||||
|
actionCommand: { field: 1, type: 'string' as const },
|
||||||
|
actionData: { field: 2, type: 'message' as const, schema: LongMsgContentSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const LongMsgResultSchema = {
|
||||||
|
action: { field: 2, type: 'repeated_message' as const, schema: LongMsgActionSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// Proto schemas for message envelopes (PushMsg).
|
||||||
|
// Port of src/bridge/include/bridge/proto/message.h
|
||||||
|
|
||||||
|
import type { ProtoSchema } from '../../protobuf/decode';
|
||||||
|
import { ElemSchema } from './element';
|
||||||
|
|
||||||
|
// --- ResponseHead.Grp ---
|
||||||
|
|
||||||
|
export const ResponseGrpSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
memberName: { field: 2, type: 'string' as const },
|
||||||
|
groupName: { field: 4, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const ResponseForwardSchema = {
|
||||||
|
friendName: { field: 6, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- ResponseHead ---
|
||||||
|
|
||||||
|
export const ResponseHeadSchema = {
|
||||||
|
fromUin: { field: 1, type: 'uint32' as const },
|
||||||
|
fromUid: { field: 2, type: 'string' as const },
|
||||||
|
type: { field: 3, type: 'uint32' as const },
|
||||||
|
sigMap: { field: 4, type: 'uint32' as const },
|
||||||
|
toUin: { field: 5, type: 'uint32' as const },
|
||||||
|
toUid: { field: 6, type: 'string' as const },
|
||||||
|
forward: { field: 7, type: 'message' as const, schema: ResponseForwardSchema },
|
||||||
|
grp: { field: 8, type: 'message' as const, schema: ResponseGrpSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- ContentHead ---
|
||||||
|
|
||||||
|
export const ContentHeadSchema = {
|
||||||
|
msgType: { field: 1, type: 'uint32' as const },
|
||||||
|
subType: { field: 2, type: 'uint32' as const },
|
||||||
|
divSeq: { field: 3, type: 'uint32' as const },
|
||||||
|
msgId: { field: 4, type: 'uint32' as const },
|
||||||
|
sequence: { field: 5, type: 'uint32' as const },
|
||||||
|
timestamp: { field: 6, type: 'uint32' as const },
|
||||||
|
field7: { field: 7, type: 'uint64' as const },
|
||||||
|
newId: { field: 12, type: 'uint64' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Ptt (voice) ---
|
||||||
|
|
||||||
|
export const PttSchema = {
|
||||||
|
fileType: { field: 1, type: 'uint32' as const },
|
||||||
|
fileId: { field: 2, type: 'uint64' as const },
|
||||||
|
fileUuid: { field: 3, type: 'bytes' as const },
|
||||||
|
fileMd5: { field: 4, type: 'bytes' as const },
|
||||||
|
fileName: { field: 5, type: 'string' as const },
|
||||||
|
fileSize: { field: 6, type: 'uint32' as const },
|
||||||
|
groupFileKey: { field: 10, type: 'string' as const },
|
||||||
|
fileKey: { field: 14, type: 'bytes' as const },
|
||||||
|
time: { field: 19, type: 'uint32' as const },
|
||||||
|
format: { field: 29, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- NotOnlineFile (C2C file) ---
|
||||||
|
|
||||||
|
export const NotOnlineFileSchema = {
|
||||||
|
fileType: { field: 1, type: 'uint32' as const },
|
||||||
|
fileUuid: { field: 3, type: 'string' as const },
|
||||||
|
fileMd5: { field: 4, type: 'bytes' as const },
|
||||||
|
fileName: { field: 5, type: 'string' as const },
|
||||||
|
fileSize: { field: 6, type: 'uint64' as const },
|
||||||
|
fileHash: { field: 57, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- RichText ---
|
||||||
|
|
||||||
|
export const RichTextSchema = {
|
||||||
|
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
|
||||||
|
notOnlineFile: { field: 3, type: 'message' as const, schema: NotOnlineFileSchema },
|
||||||
|
ptt: { field: 4, type: 'message' as const, schema: PttSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- MessageBody ---
|
||||||
|
|
||||||
|
export const MessageBodySchema = {
|
||||||
|
richText: { field: 1, type: 'message' as const, schema: RichTextSchema },
|
||||||
|
msgContent: { field: 2, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- FileExtra (for C2C file in msg_content) ---
|
||||||
|
|
||||||
|
export const FileExtraInfoSchema = {
|
||||||
|
fileSize: { field: 1, type: 'uint64' as const },
|
||||||
|
fileName: { field: 2, type: 'string' as const },
|
||||||
|
fileMd5: { field: 3, type: 'bytes' as const },
|
||||||
|
fileUuid: { field: 4, type: 'string' as const },
|
||||||
|
fileHash: { field: 5, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FileExtraSchema = {
|
||||||
|
file: { field: 1, type: 'message' as const, schema: FileExtraInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- PushMsgBody ---
|
||||||
|
|
||||||
|
export const PushMsgBodySchema = {
|
||||||
|
responseHead: { field: 1, type: 'message' as const, schema: ResponseHeadSchema },
|
||||||
|
contentHead: { field: 2, type: 'message' as const, schema: ContentHeadSchema },
|
||||||
|
body: { field: 3, type: 'message' as const, schema: MessageBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- PushMsg (top-level) ---
|
||||||
|
|
||||||
|
export const PushMsgSchema = {
|
||||||
|
message: { field: 1, type: 'message' as const, schema: PushMsgBodySchema },
|
||||||
|
status: { field: 3, type: 'int32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
// Proto schemas for notification types.
|
||||||
|
// Port of src/bridge/include/bridge/proto/notify.h
|
||||||
|
|
||||||
|
import type { ProtoSchema } from '../../protobuf/decode';
|
||||||
|
|
||||||
|
export const OperatorField1Schema = {
|
||||||
|
uid: { field: 1, type: 'string' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
field3: { field: 3, type: 'bytes' as const },
|
||||||
|
field4: { field: 4, type: 'uint32' as const },
|
||||||
|
field5: { field: 5, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OperatorInfoSchema = {
|
||||||
|
operatorField: { field: 1, type: 'message' as const, schema: OperatorField1Schema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupChangeSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
flag: { field: 2, type: 'uint32' as const },
|
||||||
|
memberUid: { field: 3, type: 'string' as const },
|
||||||
|
decreaseType: { field: 4, type: 'uint32' as const },
|
||||||
|
operatorBytes: { field: 5, type: 'bytes' as const },
|
||||||
|
increaseType: { field: 6, type: 'uint32' as const },
|
||||||
|
field7: { field: 7, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupAdminExtraSchema = {
|
||||||
|
adminUid: { field: 1, type: 'string' as const },
|
||||||
|
isPromote: { field: 2, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupAdminBodySchema = {
|
||||||
|
extraDisable: { field: 1, type: 'message' as const, schema: GroupAdminExtraSchema },
|
||||||
|
extraEnable: { field: 2, type: 'message' as const, schema: GroupAdminExtraSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupAdminSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
flag: { field: 2, type: 'uint32' as const },
|
||||||
|
isPromote: { field: 3, type: 'bool' as const },
|
||||||
|
body: { field: 4, type: 'message' as const, schema: GroupAdminBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const InvitationInnerSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
field3: { field: 3, type: 'uint32' as const },
|
||||||
|
field4: { field: 4, type: 'uint32' as const },
|
||||||
|
targetUid: { field: 5, type: 'string' as const },
|
||||||
|
invitorUid: { field: 6, type: 'string' as const },
|
||||||
|
field7: { field: 7, type: 'uint32' as const },
|
||||||
|
field9: { field: 9, type: 'uint32' as const },
|
||||||
|
field10: { field: 10, type: 'bytes' as const },
|
||||||
|
field11: { field: 11, type: 'uint32' as const },
|
||||||
|
field12: { field: 12, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const InvitationInfoSchema = {
|
||||||
|
inner: { field: 1, type: 'message' as const, schema: InvitationInnerSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupInvitationSchema = {
|
||||||
|
cmd: { field: 1, type: 'int32' as const },
|
||||||
|
info: { field: 2, type: 'message' as const, schema: InvitationInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupInviteSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
field3: { field: 3, type: 'uint32' as const },
|
||||||
|
field4: { field: 4, type: 'uint32' as const },
|
||||||
|
invitorUid: { field: 5, type: 'string' as const },
|
||||||
|
hashes: { field: 6, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupJoinSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
targetUid: { field: 3, type: 'string' as const },
|
||||||
|
field4: { field: 4, type: 'uint32' as const },
|
||||||
|
field6: { field: 6, type: 'uint32' as const },
|
||||||
|
field7: { field: 7, type: 'string' as const },
|
||||||
|
field8: { field: 8, type: 'uint32' as const },
|
||||||
|
field9: { field: 9, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FriendRequestInfoSchema = {
|
||||||
|
targetUid: { field: 1, type: 'string' as const },
|
||||||
|
sourceUid: { field: 2, type: 'string' as const },
|
||||||
|
newSource: { field: 5, type: 'string' as const },
|
||||||
|
message: { field: 10, type: 'string' as const },
|
||||||
|
source: { field: 11, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FriendRequestSchema = {
|
||||||
|
info: { field: 1, type: 'message' as const, schema: FriendRequestInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FriendRecallTipInfoSchema = {
|
||||||
|
tip: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FriendRecallInfoSchema = {
|
||||||
|
fromUid: { field: 1, type: 'string' as const },
|
||||||
|
toUid: { field: 2, type: 'string' as const },
|
||||||
|
clientSequence: { field: 3, type: 'uint32' as const },
|
||||||
|
newId: { field: 4, type: 'uint64' as const },
|
||||||
|
time: { field: 5, type: 'uint32' as const },
|
||||||
|
random: { field: 6, type: 'uint32' as const },
|
||||||
|
pkgNum: { field: 7, type: 'uint32' as const },
|
||||||
|
pkgIndex: { field: 8, type: 'uint32' as const },
|
||||||
|
divSeq: { field: 9, type: 'uint32' as const },
|
||||||
|
tipInfo: { field: 13, type: 'message' as const, schema: FriendRecallTipInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const FriendRecallSchema = {
|
||||||
|
info: { field: 1, type: 'message' as const, schema: FriendRecallInfoSchema },
|
||||||
|
instId: { field: 2, type: 'uint32' as const },
|
||||||
|
appId: { field: 3, type: 'uint32' as const },
|
||||||
|
longMessageFlag: { field: 4, type: 'uint32' as const },
|
||||||
|
reserved: { field: 5, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupMuteStateSchema = {
|
||||||
|
targetUid: { field: 1, type: 'string' as const },
|
||||||
|
duration: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupMuteDataSchema = {
|
||||||
|
timestamp: { field: 1, type: 'uint32' as const },
|
||||||
|
type: { field: 2, type: 'uint32' as const },
|
||||||
|
state: { field: 3, type: 'message' as const, schema: GroupMuteStateSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupMuteSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
subType: { field: 2, type: 'uint32' as const },
|
||||||
|
field3: { field: 3, type: 'uint32' as const },
|
||||||
|
operatorUid: { field: 4, type: 'string' as const },
|
||||||
|
data: { field: 5, type: 'message' as const, schema: GroupMuteDataSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const RecallMessageSchema = {
|
||||||
|
sequence: { field: 1, type: 'uint32' as const },
|
||||||
|
time: { field: 2, type: 'uint32' as const },
|
||||||
|
random: { field: 3, type: 'uint32' as const },
|
||||||
|
type: { field: 4, type: 'uint32' as const },
|
||||||
|
flag: { field: 5, type: 'uint32' as const },
|
||||||
|
authorUid: { field: 6, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupRecallTipInfoSchema = {
|
||||||
|
tip: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupRecallSchema = {
|
||||||
|
operatorUid: { field: 1, type: 'string' as const },
|
||||||
|
recallMessages: { field: 3, type: 'repeated_message' as const, schema: RecallMessageSchema },
|
||||||
|
userDef: { field: 5, type: 'bytes' as const },
|
||||||
|
groupType: { field: 6, type: 'int32' as const },
|
||||||
|
opType: { field: 7, type: 'int32' as const },
|
||||||
|
tipInfo: { field: 9, type: 'message' as const, schema: GroupRecallTipInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const TemplParamSchema = {
|
||||||
|
name: { field: 1, type: 'string' as const },
|
||||||
|
value: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GeneralGrayTipInfoSchema = {
|
||||||
|
busiType: { field: 1, type: 'uint64' as const },
|
||||||
|
busiId: { field: 2, type: 'uint64' as const },
|
||||||
|
ctrlFlag: { field: 3, type: 'uint32' as const },
|
||||||
|
c2cType: { field: 4, type: 'uint32' as const },
|
||||||
|
serviceType: { field: 5, type: 'uint32' as const },
|
||||||
|
templId: { field: 6, type: 'uint64' as const },
|
||||||
|
msgTemplParam: { field: 7, type: 'repeated_message' as const, schema: TemplParamSchema },
|
||||||
|
content: { field: 8, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const EssenceMessageSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
msgSequence: { field: 2, type: 'uint32' as const },
|
||||||
|
random: { field: 3, type: 'uint32' as const },
|
||||||
|
setFlag: { field: 4, type: 'uint32' as const },
|
||||||
|
memberUin: { field: 5, type: 'uint32' as const },
|
||||||
|
operatorUin: { field: 6, type: 'uint32' as const },
|
||||||
|
timestamp: { field: 7, type: 'uint32' as const },
|
||||||
|
msgSequence2: { field: 8, type: 'uint32' as const },
|
||||||
|
operatorNickname: { field: 9, type: 'string' as const },
|
||||||
|
memberNickname: { field: 10, type: 'string' as const },
|
||||||
|
setFlag2: { field: 11, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NotifyMessageBodySchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
groupUin: { field: 4, type: 'uint32' as const },
|
||||||
|
eventParam: { field: 5, type: 'bytes' as const },
|
||||||
|
recall: { field: 11, type: 'message' as const, schema: GroupRecallSchema },
|
||||||
|
field13: { field: 13, type: 'uint32' as const },
|
||||||
|
operatorUid: { field: 21, type: 'string' as const },
|
||||||
|
generalGrayTip: { field: 26, type: 'message' as const, schema: GeneralGrayTipInfoSchema },
|
||||||
|
essenceMessage: { field: 33, type: 'message' as const, schema: EssenceMessageSchema },
|
||||||
|
msgSequence: { field: 37, type: 'uint32' as const },
|
||||||
|
field39: { field: 39, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
@@ -0,0 +1,788 @@
|
|||||||
|
// Proto schemas for OIDB action requests.
|
||||||
|
// Port of src/bridge/include/bridge/proto/oidb.h (action-related structs)
|
||||||
|
// and src/bridge/src/bridge.cpp (recall message structs)
|
||||||
|
|
||||||
|
import type { ProtoSchema } from '../../protobuf/decode';
|
||||||
|
|
||||||
|
// --- 0x1253_1: Mute group member ---
|
||||||
|
|
||||||
|
export const OidbMuteMemberBodySchema = {
|
||||||
|
targetUid: { field: 1, type: 'string' as const },
|
||||||
|
duration: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbMuteMemberSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
type: { field: 2, type: 'uint32' as const },
|
||||||
|
body: { field: 3, type: 'message' as const, schema: OidbMuteMemberBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x89A_0: Mute group all ---
|
||||||
|
|
||||||
|
export const OidbMuteAllStateSchema = {
|
||||||
|
state: { field: 17, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbMuteAllSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
muteState: { field: 2, type: 'message' as const, schema: OidbMuteAllStateSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x8A0_1: Kick group member ---
|
||||||
|
|
||||||
|
export const OidbKickMemberSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
targetUid: { field: 3, type: 'string' as const },
|
||||||
|
rejectAddRequest:{ field: 4, type: 'bool' as const },
|
||||||
|
reason: { field: 5, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x1097_1: Leave group ---
|
||||||
|
|
||||||
|
export const OidbLeaveGroupSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0xB5D_44: Friend add request ---
|
||||||
|
|
||||||
|
export const OidbFriendRequestActionSchema = {
|
||||||
|
accept: { field: 1, type: 'uint32' as const },
|
||||||
|
targetUid: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x126B_0: Delete friend ---
|
||||||
|
|
||||||
|
export const OidbDeleteFriendField2Field3Schema = {
|
||||||
|
field1: { field: 1, type: 'uint32' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
field3: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbDeleteFriendField2Schema = {
|
||||||
|
field1: { field: 1, type: 'uint32' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
field3: { field: 3, type: 'message' as const, schema: OidbDeleteFriendField2Field3Schema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbDeleteFriendField1Schema = {
|
||||||
|
targetUid: { field: 1, type: 'string' as const },
|
||||||
|
field2: { field: 2, type: 'message' as const, schema: OidbDeleteFriendField2Schema },
|
||||||
|
block: { field: 3, type: 'bool' as const },
|
||||||
|
field4: { field: 4, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbDeleteFriendSchema = {
|
||||||
|
field1: { field: 1, type: 'message' as const, schema: OidbDeleteFriendField1Schema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x10C8: Group request action ---
|
||||||
|
|
||||||
|
export const OidbGroupRequestBodySchema = {
|
||||||
|
sequence: { field: 1, type: 'uint64' as const },
|
||||||
|
eventType: { field: 2, type: 'uint32' as const },
|
||||||
|
groupUin: { field: 3, type: 'uint32' as const },
|
||||||
|
message: { field: 4, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupRequestActionSchema = {
|
||||||
|
accept: { field: 1, type: 'uint32' as const },
|
||||||
|
body: { field: 2, type: 'message' as const, schema: OidbGroupRequestBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0xED3_1: Poke ---
|
||||||
|
|
||||||
|
export const OidbPokeSchema = {
|
||||||
|
uin: { field: 1, type: 'uint32' as const },
|
||||||
|
groupUin: { field: 2, type: 'uint32' as const },
|
||||||
|
friendUin: { field: 5, type: 'uint32' as const },
|
||||||
|
ext: { field: 6, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0xEAC: Group essence ---
|
||||||
|
|
||||||
|
export const OidbEssenceSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
sequence: { field: 2, type: 'uint32' as const },
|
||||||
|
random: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x1096_1: Set group admin ---
|
||||||
|
|
||||||
|
export const OidbSetAdminSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
uid: { field: 2, type: 'string' as const },
|
||||||
|
isAdmin: { field: 3, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x8FC_3: Set group card (rename member) ---
|
||||||
|
|
||||||
|
export const OidbRenameMemberBodySchema = {
|
||||||
|
targetUid: { field: 1, type: 'string' as const },
|
||||||
|
targetName: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbRenameMemberSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
body: { field: 2, type: 'message' as const, schema: OidbRenameMemberBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x89A_15: Rename group ---
|
||||||
|
|
||||||
|
export const OidbRenameGroupBodySchema = {
|
||||||
|
targetName: { field: 1, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbRenameGroupSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
body: { field: 2, type: 'message' as const, schema: OidbRenameGroupBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x8FC_2: Set group special title ---
|
||||||
|
|
||||||
|
export const OidbSpecialTitleBodySchema = {
|
||||||
|
targetUid: { field: 1, type: 'string' as const },
|
||||||
|
specialTitle:{ field: 5, type: 'string' as const },
|
||||||
|
expireTime: { field: 6, type: 'int32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSpecialTitleSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
body: { field: 2, type: 'message' as const, schema: OidbSpecialTitleBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x7E5_104: Send like ---
|
||||||
|
|
||||||
|
export const OidbLikeSchema = {
|
||||||
|
targetUin: { field: 1, type: 'uint32' as const },
|
||||||
|
count: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x10C0_1 / 0x10C0_2: Group request list ---
|
||||||
|
|
||||||
|
export const OidbGroupRequestListSchema = {
|
||||||
|
count: { field: 1, type: 'uint32' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0xFE1_2: User profile info ---
|
||||||
|
|
||||||
|
export const OidbUserInfoKeySchema = {
|
||||||
|
key: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
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 },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbTwoNumberSchema = {
|
||||||
|
number1: { field: 1, type: 'uint32' as const },
|
||||||
|
number2: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbBytePropertySchema = {
|
||||||
|
code: { field: 1, type: 'uint32' as const },
|
||||||
|
value: { field: 2, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbUserInfoPropertySchema = {
|
||||||
|
numberProperties: { field: 1, type: 'repeated_message' as const, schema: OidbTwoNumberSchema },
|
||||||
|
bytesProperties: { field: 2, type: 'repeated_message' as const, schema: OidbBytePropertySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbUserInfoResponseBodySchema = {
|
||||||
|
uid: { field: 1, type: 'string' as const },
|
||||||
|
properties: { field: 2, type: 'message' as const, schema: OidbUserInfoPropertySchema },
|
||||||
|
uin: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbUserInfoResponseSchema = {
|
||||||
|
body: { field: 1, type: 'message' as const, schema: OidbUserInfoResponseBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const AvatarInfoSchema = {
|
||||||
|
url: { field: 5, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- FD4_1: Friend list request body fields ---
|
||||||
|
|
||||||
|
export const OidbFriendListNumberSchema = {
|
||||||
|
numbers: { field: 1, type: 'repeated_uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbFriendListBodyItemSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
number: { field: 2, type: 'message' as const, schema: OidbFriendListNumberSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbFriendListNextUinSchema = {
|
||||||
|
uin: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbFriendListRequestSchema = {
|
||||||
|
friendCount: { field: 2, type: 'uint32' as const },
|
||||||
|
field4: { field: 4, type: 'uint32' as const },
|
||||||
|
nextUin: { field: 5, type: 'message' as const, schema: OidbFriendListNextUinSchema },
|
||||||
|
field6: { field: 6, type: 'uint32' as const },
|
||||||
|
field7: { field: 7, type: 'uint32' as const },
|
||||||
|
body: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendListBodyItemSchema },
|
||||||
|
field10002: { field: 10002, type: 'repeated_uint32' as const },
|
||||||
|
field10003: { field: 10003, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- FE5_2: Group list request body (config fields) ---
|
||||||
|
|
||||||
|
export const OidbGroupListConfig1Schema = {
|
||||||
|
groupOwner: { field: 1, type: 'bool' as const },
|
||||||
|
field2: { field: 2, type: 'bool' as const },
|
||||||
|
memberMax: { field: 3, type: 'bool' as const },
|
||||||
|
memberCount: { field: 4, type: 'bool' as const },
|
||||||
|
groupName: { field: 5, type: 'bool' as const },
|
||||||
|
field8: { field: 8, type: 'bool' as const },
|
||||||
|
field9: { field: 9, type: 'bool' as const },
|
||||||
|
field10: { field: 10, type: 'bool' as const },
|
||||||
|
field11: { field: 11, type: 'bool' as const },
|
||||||
|
field12: { field: 12, type: 'bool' as const },
|
||||||
|
field13: { field: 13, type: 'bool' as const },
|
||||||
|
field14: { field: 14, type: 'bool' as const },
|
||||||
|
field15: { field: 15, type: 'bool' as const },
|
||||||
|
field16: { field: 16, type: 'bool' as const },
|
||||||
|
field17: { field: 17, type: 'bool' as const },
|
||||||
|
field18: { field: 18, type: 'bool' as const },
|
||||||
|
question: { field: 19, type: 'bool' as const },
|
||||||
|
field20: { field: 20, type: 'bool' as const },
|
||||||
|
field22: { field: 22, type: 'bool' as const },
|
||||||
|
field23: { field: 23, type: 'bool' as const },
|
||||||
|
field24: { field: 24, type: 'bool' as const },
|
||||||
|
field25: { field: 25, type: 'bool' as const },
|
||||||
|
field26: { field: 26, type: 'bool' as const },
|
||||||
|
field27: { field: 27, type: 'bool' as const },
|
||||||
|
field28: { field: 28, type: 'bool' as const },
|
||||||
|
field29: { field: 29, type: 'bool' as const },
|
||||||
|
field30: { field: 30, type: 'bool' as const },
|
||||||
|
field31: { field: 31, type: 'bool' as const },
|
||||||
|
field32: { field: 32, type: 'bool' as const },
|
||||||
|
field5001: { field: 5001, type: 'bool' as const },
|
||||||
|
field5002: { field: 5002, type: 'bool' as const },
|
||||||
|
field5003: { field: 5003, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupListConfig2Schema = {
|
||||||
|
field1: { field: 1, type: 'bool' as const },
|
||||||
|
field2: { field: 2, type: 'bool' as const },
|
||||||
|
field3: { field: 3, type: 'bool' as const },
|
||||||
|
field4: { field: 4, type: 'bool' as const },
|
||||||
|
field5: { field: 5, type: 'bool' as const },
|
||||||
|
field6: { field: 6, type: 'bool' as const },
|
||||||
|
field7: { field: 7, type: 'bool' as const },
|
||||||
|
field8: { field: 8, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupListConfig3Schema = {
|
||||||
|
field5: { field: 5, type: 'bool' as const },
|
||||||
|
field6: { field: 6, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupListConfigSchema = {
|
||||||
|
config1: { field: 1, type: 'message' as const, schema: OidbGroupListConfig1Schema },
|
||||||
|
config2: { field: 2, type: 'message' as const, schema: OidbGroupListConfig2Schema },
|
||||||
|
config3: { field: 3, type: 'message' as const, schema: OidbGroupListConfig3Schema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupListRequestSchema = {
|
||||||
|
config: { field: 1, type: 'message' as const, schema: OidbGroupListConfigSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- FE7_3: Group member list request body ---
|
||||||
|
|
||||||
|
export const OidbGroupMemberListBodySchema = {
|
||||||
|
memberName: { field: 10, type: 'bool' as const },
|
||||||
|
memberCard: { field: 11, type: 'bool' as const },
|
||||||
|
level: { field: 12, type: 'bool' as const },
|
||||||
|
field13: { field: 13, type: 'bool' as const },
|
||||||
|
field16: { field: 16, type: 'bool' as const },
|
||||||
|
specialTitle: { field: 17, type: 'bool' as const },
|
||||||
|
field18: { field: 18, type: 'bool' as const },
|
||||||
|
field20: { field: 20, type: 'bool' as const },
|
||||||
|
field21: { field: 21, type: 'bool' as const },
|
||||||
|
joinTimestamp: { field: 100, type: 'bool' as const },
|
||||||
|
lastMsgTimestamp: { field: 101, type: 'bool' as const },
|
||||||
|
shutUpTimestamp: { field: 102, type: 'bool' as const },
|
||||||
|
field103: { field: 103, type: 'bool' as const },
|
||||||
|
field104: { field: 104, type: 'bool' as const },
|
||||||
|
field105: { field: 105, type: 'bool' as const },
|
||||||
|
field106: { field: 106, type: 'bool' as const },
|
||||||
|
permission: { field: 107, type: 'bool' as const },
|
||||||
|
field200: { field: 200, type: 'bool' as const },
|
||||||
|
field201: { field: 201, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupMemberListRequestSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
field3: { field: 3, type: 'uint32' as const },
|
||||||
|
body: { field: 4, type: 'message' as const, schema: OidbGroupMemberListBodySchema },
|
||||||
|
token: { field: 15, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Group recall message (trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg) ---
|
||||||
|
|
||||||
|
export const GroupRecallInfoSchema = {
|
||||||
|
sequence: { field: 1, type: 'uint32' as const },
|
||||||
|
random: { field: 2, type: 'uint32' as const },
|
||||||
|
field3: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupRecallSettingsSchema = {
|
||||||
|
field1: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const GroupRecallRequestSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
groupUin: { field: 2, type: 'uint32' as const },
|
||||||
|
info: { field: 3, type: 'message' as const, schema: GroupRecallInfoSchema },
|
||||||
|
settings: { field: 4, type: 'message' as const, schema: GroupRecallSettingsSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- C2C (private) recall message (trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg) ---
|
||||||
|
|
||||||
|
export const C2CRecallInfoSchema = {
|
||||||
|
clientSequence: { field: 1, type: 'uint32' as const },
|
||||||
|
random: { field: 2, type: 'uint32' as const },
|
||||||
|
messageId: { field: 3, type: 'uint64' as const },
|
||||||
|
timestamp: { field: 4, type: 'uint32' as const },
|
||||||
|
field5: { field: 5, type: 'uint32' as const },
|
||||||
|
messageSequence: { field: 6, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const C2CRecallSettingsSchema = {
|
||||||
|
field1: { field: 1, type: 'bool' as const },
|
||||||
|
field2: { field: 2, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const C2CRecallRequestSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
targetUid:{ field: 3, type: 'string' as const },
|
||||||
|
info: { field: 4, type: 'message' as const, schema: C2CRecallInfoSchema },
|
||||||
|
settings: { field: 5, type: 'message' as const, schema: C2CRecallSettingsSchema },
|
||||||
|
field6: { field: 6, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x9082_1: Set group reaction ---
|
||||||
|
|
||||||
|
export const OidbGroupReactionSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
sequence: { field: 2, type: 'uint32' as const },
|
||||||
|
code: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x6D8_1: Group file list ---
|
||||||
|
|
||||||
|
export const OidbGroupFileListReqSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
appId: { field: 2, type: 'uint32' as const },
|
||||||
|
targetDirectory: { field: 3, type: 'string' as const },
|
||||||
|
fileCount: { field: 5, type: 'uint32' as const },
|
||||||
|
sortBy: { field: 9, type: 'uint32' as const },
|
||||||
|
startIndex: { field: 13, type: 'uint32' as const },
|
||||||
|
field17: { field: 17, type: 'uint32' as const },
|
||||||
|
field18: { field: 18, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileViewReqSchema = {
|
||||||
|
list: { field: 2, type: 'message' as const, schema: OidbGroupFileListReqSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileListFolderRespSchema = {
|
||||||
|
folderId: { field: 1, type: 'string' as const },
|
||||||
|
parentDirectoryId: { field: 2, type: 'string' as const },
|
||||||
|
folderName: { field: 3, type: 'string' as const },
|
||||||
|
createTime: { field: 4, type: 'uint32' as const },
|
||||||
|
modifiedTime: { field: 5, type: 'uint32' as const },
|
||||||
|
creatorUin: { field: 6, type: 'uint32' as const },
|
||||||
|
creatorName: { field: 7, type: 'string' as const },
|
||||||
|
totalFileCount: { field: 8, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileListFileRespSchema = {
|
||||||
|
fileId: { field: 1, type: 'string' as const },
|
||||||
|
fileName: { field: 2, type: 'string' as const },
|
||||||
|
fileSize: { field: 3, type: 'uint64' as const },
|
||||||
|
busId: { field: 4, type: 'uint32' as const },
|
||||||
|
uploadedTime: { field: 6, type: 'uint32' as const },
|
||||||
|
expireTime: { field: 7, type: 'uint32' as const },
|
||||||
|
modifiedTime: { field: 8, type: 'uint32' as const },
|
||||||
|
downloadedTimes: { field: 9, type: 'uint32' as const },
|
||||||
|
uploaderName: { field: 14, type: 'string' as const },
|
||||||
|
uploaderUin: { field: 15, type: 'uint32' as const },
|
||||||
|
parentDirectory: { field: 16, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileListItemRespSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
folderInfo: { field: 2, type: 'message' as const, schema: OidbGroupFileListFolderRespSchema },
|
||||||
|
fileInfo: { field: 3, type: 'message' as const, schema: OidbGroupFileListFileRespSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileListRespSchema = {
|
||||||
|
retCode: { field: 1, type: 'uint32' as const },
|
||||||
|
retMsg: { field: 2, type: 'string' as const },
|
||||||
|
clientWording: { field: 3, type: 'string' as const },
|
||||||
|
isEnd: { field: 4, type: 'bool' as const },
|
||||||
|
items: { field: 5, type: 'repeated_message' as const, schema: OidbGroupFileListItemRespSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileViewRespSchema = {
|
||||||
|
list: { field: 2, type: 'message' as const, schema: OidbGroupFileListRespSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x6D6_2 / 0x6D6_3: Group file url & delete ---
|
||||||
|
|
||||||
|
export const OidbGroupFileUploadReqSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
appId: { field: 2, type: 'uint32' as const },
|
||||||
|
busId: { field: 3, type: 'uint32' as const },
|
||||||
|
entrance: { field: 4, type: 'uint32' as const },
|
||||||
|
targetDirectory: { field: 5, type: 'string' as const },
|
||||||
|
fileName: { field: 6, type: 'string' as const },
|
||||||
|
localDirectory: { field: 7, type: 'string' as const },
|
||||||
|
fileSize: { field: 8, type: 'uint64' as const },
|
||||||
|
fileSha1: { field: 9, type: 'bytes' as const },
|
||||||
|
fileSha3: { field: 10, type: 'bytes' as const },
|
||||||
|
fileMd5: { field: 11, type: 'bytes' as const },
|
||||||
|
field15: { field: 15, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileDownloadReqSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
appId: { field: 2, type: 'uint32' as const },
|
||||||
|
busId: { field: 3, type: 'uint32' as const },
|
||||||
|
fileId: { field: 4, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileDeleteReqSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
busId: { field: 3, type: 'uint32' as const },
|
||||||
|
fileId: { field: 5, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileMoveReqSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
appId: { field: 2, type: 'uint32' as const },
|
||||||
|
busId: { field: 3, type: 'uint32' as const },
|
||||||
|
fileId: { field: 4, type: 'string' as const },
|
||||||
|
parentDirectory: { field: 5, type: 'string' as const },
|
||||||
|
targetDirectory: { field: 6, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileReqSchema = {
|
||||||
|
file: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadReqSchema },
|
||||||
|
download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadReqSchema },
|
||||||
|
delete: { field: 4, type: 'message' as const, schema: OidbGroupFileDeleteReqSchema },
|
||||||
|
move: { field: 6, type: 'message' as const, schema: OidbGroupFileMoveReqSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileUploadRespSchema = {
|
||||||
|
retCode: { field: 1, type: 'int32' as const },
|
||||||
|
retMsg: { field: 2, type: 'string' as const },
|
||||||
|
clientWording: { field: 3, type: 'string' as const },
|
||||||
|
uploadIp: { field: 4, type: 'string' as const },
|
||||||
|
serverDns: { field: 5, type: 'string' as const },
|
||||||
|
busId: { field: 6, type: 'int32' as const },
|
||||||
|
fileId: { field: 7, type: 'string' as const },
|
||||||
|
checkKey: { field: 8, type: 'bytes' as const },
|
||||||
|
fileKey: { field: 9, type: 'bytes' as const },
|
||||||
|
boolFileExist: { field: 10, type: 'bool' as const },
|
||||||
|
uploadPort: { field: 14, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileDownloadRespSchema = {
|
||||||
|
retCode: { field: 1, type: 'uint32' as const },
|
||||||
|
retMsg: { field: 2, type: 'string' as const },
|
||||||
|
clientWording: { field: 3, type: 'string' as const },
|
||||||
|
downloadIp: { field: 4, type: 'string' as const },
|
||||||
|
downloadDns: { field: 5, type: 'string' as const },
|
||||||
|
downloadUrl: { field: 6, type: 'bytes' as const },
|
||||||
|
saveFileName: { field: 11, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileRetRespSchema = {
|
||||||
|
retCode: { field: 1, type: 'uint32' as const },
|
||||||
|
retMsg: { field: 2, type: 'string' as const },
|
||||||
|
clientWording: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileRespSchema = {
|
||||||
|
upload: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadRespSchema },
|
||||||
|
download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadRespSchema },
|
||||||
|
delete: { field: 4, type: 'message' as const, schema: OidbGroupFileRetRespSchema },
|
||||||
|
move: { field: 6, type: 'message' as const, schema: OidbGroupFileRetRespSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops ---
|
||||||
|
|
||||||
|
export const OidbGroupFileCreateFolderReqSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
rootDirectory: { field: 3, type: 'string' as const },
|
||||||
|
folderName: { field: 4, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileDeleteFolderReqSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
folderId: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileRenameFolderReqSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
folderId: { field: 3, type: 'string' as const },
|
||||||
|
newFolderName: { field: 4, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileFolderReqSchema = {
|
||||||
|
create: { field: 1, type: 'message' as const, schema: OidbGroupFileCreateFolderReqSchema },
|
||||||
|
delete: { field: 2, type: 'message' as const, schema: OidbGroupFileDeleteFolderReqSchema },
|
||||||
|
rename: { field: 3, type: 'message' as const, schema: OidbGroupFileRenameFolderReqSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileFolderRetRespSchema = {
|
||||||
|
retcode: { field: 1, type: 'uint32' as const },
|
||||||
|
retMsg: { field: 2, type: 'string' as const },
|
||||||
|
clientWording: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileFolderRespSchema = {
|
||||||
|
create: { field: 1, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema },
|
||||||
|
delete: { field: 2, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema },
|
||||||
|
rename: { field: 3, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0xE37_1200: Private file download url ---
|
||||||
|
|
||||||
|
export const OidbPrivateFileDownloadReqBodySchema = {
|
||||||
|
receiverUid: { field: 10, type: 'string' as const },
|
||||||
|
fileUuid: { field: 20, type: 'string' as const },
|
||||||
|
type: { field: 30, type: 'uint32' as const },
|
||||||
|
fileHash: { field: 60, type: 'string' as const },
|
||||||
|
t2: { field: 601, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbPrivateFileDownloadReqSchema = {
|
||||||
|
subCommand: { field: 1, type: 'uint32' as const },
|
||||||
|
field2: { field: 2, type: 'uint32' as const },
|
||||||
|
body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadReqBodySchema },
|
||||||
|
field101: { field: 101, type: 'uint32' as const },
|
||||||
|
field102: { field: 102, type: 'uint32' as const },
|
||||||
|
field200: { field: 200, type: 'uint32' as const },
|
||||||
|
field99999: { field: 99999, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbPrivateFileDownloadRespResultSchema = {
|
||||||
|
server: { field: 20, type: 'string' as const },
|
||||||
|
port: { field: 40, type: 'uint32' as const },
|
||||||
|
url: { field: 50, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbPrivateFileDownloadRespBodySchema = {
|
||||||
|
state: { field: 20, type: 'string' as const },
|
||||||
|
result: { field: 30, type: 'message' as const, schema: OidbPrivateFileDownloadRespResultSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbPrivateFileDownloadRespSchema = {
|
||||||
|
body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadRespBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0xE37_1700: Private file upload ---
|
||||||
|
|
||||||
|
export const OidbPrivateFileUploadReqBodySchema = {
|
||||||
|
senderUid: { field: 10, type: 'string' as const },
|
||||||
|
receiverUid: { field: 20, type: 'string' as const },
|
||||||
|
fileSize: { field: 30, type: 'uint32' as const },
|
||||||
|
fileName: { field: 40, type: 'string' as const },
|
||||||
|
md510MCheckSum:{ field: 50, type: 'bytes' as const },
|
||||||
|
sha1CheckSum: { field: 60, type: 'bytes' as const },
|
||||||
|
localPath: { field: 70, type: 'string' as const },
|
||||||
|
md5CheckSum: { field: 110, type: 'bytes' as const },
|
||||||
|
sha3CheckSum: { field: 120, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbPrivateFileUploadReqSchema = {
|
||||||
|
command: { field: 1, type: 'uint32' as const },
|
||||||
|
seq: { field: 2, type: 'int32' as const },
|
||||||
|
upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadReqBodySchema },
|
||||||
|
businessId: { field: 101, type: 'int32' as const },
|
||||||
|
clientType: { field: 102, type: 'int32' as const },
|
||||||
|
flagSupportMediaPlatform: { field: 200, type: 'int32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbPrivateFileUploadRespBodySchema = {
|
||||||
|
retCode: { field: 10, type: 'int32' as const },
|
||||||
|
retMsg: { field: 20, type: 'string' as const },
|
||||||
|
uploadIp: { field: 60, type: 'string' as const },
|
||||||
|
uploadPort: { field: 80, type: 'uint32' as const },
|
||||||
|
uuid: { field: 90, type: 'string' as const },
|
||||||
|
uploadKey: { field: 100, type: 'bytes' as const },
|
||||||
|
boolFileExist: { field: 110, type: 'bool' as const },
|
||||||
|
fileAddon: { field: 200, type: 'string' as const },
|
||||||
|
mediaPlatformUploadKey: { field: 220, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbPrivateFileUploadRespSchema = {
|
||||||
|
upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadRespBodySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- NTV2 Rich Media (0x9067_202): Download RKey ---
|
||||||
|
|
||||||
|
export const NTV2CommonHeadSchema = {
|
||||||
|
requestId: { field: 1, type: 'uint32' as const },
|
||||||
|
command: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2C2CUserInfoSchema = {
|
||||||
|
accountType: { field: 1, type: 'uint32' as const },
|
||||||
|
targetUid: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2GroupInfoSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2SceneInfoSchema = {
|
||||||
|
requestType: { field: 101, type: 'uint32' as const },
|
||||||
|
businessType: { field: 102, type: 'uint32' as const },
|
||||||
|
sceneType: { field: 200, type: 'uint32' as const },
|
||||||
|
c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema },
|
||||||
|
group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2ClientMetaSchema = {
|
||||||
|
agentType: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2ReqHeadSchema = {
|
||||||
|
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
|
||||||
|
scene: { field: 2, type: 'message' as const, schema: NTV2SceneInfoSchema },
|
||||||
|
client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2DownloadRKeyReqSchema = {
|
||||||
|
types: { field: 1, type: 'repeated_uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2FileTypeSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
picFormat: { field: 2, type: 'uint32' as const },
|
||||||
|
videoFormat: { field: 3, type: 'uint32' as const },
|
||||||
|
voiceFormat: { field: 4, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2FileInfoSchema = {
|
||||||
|
fileSize: { field: 1, type: 'uint32' as const },
|
||||||
|
fileHash: { field: 2, type: 'string' as const },
|
||||||
|
fileSha1: { field: 3, type: 'string' as const },
|
||||||
|
fileName: { field: 4, type: 'string' as const },
|
||||||
|
type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema },
|
||||||
|
width: { field: 6, type: 'uint32' as const },
|
||||||
|
height: { field: 7, type: 'uint32' as const },
|
||||||
|
time: { field: 8, type: 'uint32' as const },
|
||||||
|
original: { field: 9, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2IndexNodeSchema = {
|
||||||
|
info: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema },
|
||||||
|
fileUuid: { field: 2, type: 'string' as const },
|
||||||
|
storeId: { field: 3, type: 'uint32' as const },
|
||||||
|
uploadTime: { field: 4, type: 'uint32' as const },
|
||||||
|
ttl: { field: 5, type: 'uint32' as const },
|
||||||
|
subType: { field: 6, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2VideoDownloadExtSchema = {
|
||||||
|
busiType: { field: 1, type: 'uint32' as const },
|
||||||
|
sceneType: { field: 2, type: 'uint32' as const },
|
||||||
|
subBusiType: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2DownloadExtSchema = {
|
||||||
|
video: { field: 2, type: 'message' as const, schema: NTV2VideoDownloadExtSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2DownloadReqSchema = {
|
||||||
|
node: { field: 1, type: 'message' as const, schema: NTV2IndexNodeSchema },
|
||||||
|
download: { field: 2, type: 'message' as const, schema: NTV2DownloadExtSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2RichMediaReqSchema = {
|
||||||
|
reqHead: { field: 1, type: 'message' as const, schema: NTV2ReqHeadSchema },
|
||||||
|
download: { field: 3, type: 'message' as const, schema: NTV2DownloadReqSchema },
|
||||||
|
downloadRkey: { field: 4, type: 'message' as const, schema: NTV2DownloadRKeyReqSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2RespHeadSchema = {
|
||||||
|
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
|
||||||
|
retCode: { field: 2, type: 'uint32' as const },
|
||||||
|
message: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2RKeyInfoSchema = {
|
||||||
|
rkey: { field: 1, type: 'string' as const },
|
||||||
|
rkeyTtlSec: { field: 2, type: 'uint64' as const },
|
||||||
|
storeId: { field: 3, type: 'uint32' as const },
|
||||||
|
rkeyCreateTime:{ field: 4, type: 'uint32' as const },
|
||||||
|
type: { field: 5, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2DownloadRKeyRespSchema = {
|
||||||
|
rkeys: { field: 1, type: 'repeated_message' as const, schema: NTV2RKeyInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2MediaDownloadInfoSchema = {
|
||||||
|
domain: { field: 1, type: 'string' as const },
|
||||||
|
urlPath: { field: 2, type: 'string' as const },
|
||||||
|
httpsPort: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2MediaDownloadRespSchema = {
|
||||||
|
rKeyParam: { field: 1, type: 'string' as const },
|
||||||
|
rKeyTtlSecond: { field: 2, type: 'uint32' as const },
|
||||||
|
info: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadInfoSchema },
|
||||||
|
rKeyCreateTime: { field: 4, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const NTV2RichMediaRespSchema = {
|
||||||
|
respHead: { field: 1, type: 'message' as const, schema: NTV2RespHeadSchema },
|
||||||
|
download: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadRespSchema },
|
||||||
|
downloadRkey:{ field: 4, type: 'message' as const, schema: NTV2DownloadRKeyRespSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0xB6E_2: Set friend remark ---
|
||||||
|
|
||||||
|
export const OidbSetFriendRemarkSchema = {
|
||||||
|
targetUid: { field: 1, type: 'string' as const },
|
||||||
|
remark: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- 0x9082_2: Set group reaction (remove) — same schema as set ---
|
||||||
|
// (0x9082_1 for add, 0x9082_2 for remove — both use OidbGroupReactionSchema)
|
||||||
|
|
||||||
|
// --- Group file count (0x6D8_3) ---
|
||||||
|
|
||||||
|
export const OidbGroupFileCountReqSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
appId: { field: 2, type: 'uint32' as const },
|
||||||
|
busId: { field: 3, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileCountRespSchema = {
|
||||||
|
fileCount: { field: 1, type: 'uint32' as const },
|
||||||
|
maxCount: { field: 2, type: 'uint32' as const },
|
||||||
|
isEnd: { field: 3, type: 'bool' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileCountViewReqSchema = {
|
||||||
|
count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountReqSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbGroupFileCountViewRespSchema = {
|
||||||
|
count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountRespSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
// Proto schemas for OidbSvc service types.
|
||||||
|
// Port of src/bridge/include/bridge/proto/oidb.h
|
||||||
|
|
||||||
|
import type { ProtoSchema } from '../../protobuf/decode';
|
||||||
|
|
||||||
|
// --- OidbSvcTrpcTcpBase wrapper ---
|
||||||
|
|
||||||
|
export const OidbPropertySchema = {
|
||||||
|
key: { field: 1, type: 'string' as const },
|
||||||
|
value: { field: 2, type: 'bytes' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// Factory for OidbSvcTrpcTcpBase<T>
|
||||||
|
export function makeOidbBaseSchema(bodySchema: ProtoSchema): ProtoSchema {
|
||||||
|
return {
|
||||||
|
command: { field: 1, type: 'uint32' as const },
|
||||||
|
subCommand: { field: 2, type: 'uint32' as const },
|
||||||
|
errorCode: { field: 3, type: 'uint32' as const },
|
||||||
|
body: { field: 4, type: 'message' as const, schema: bodySchema },
|
||||||
|
errorMsg: { field: 5, type: 'string' as const },
|
||||||
|
properties: { field: 11, type: 'repeated_message' as const, schema: OidbPropertySchema },
|
||||||
|
reserved: { field: 12, type: 'int32' as const },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Friend list (0xFD4_1) ---
|
||||||
|
|
||||||
|
export const OidbFriendPropertySchema = {
|
||||||
|
code: { field: 1, type: 'uint32' as const },
|
||||||
|
value: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbFriendLayer1Schema = {
|
||||||
|
properties: { field: 2, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbFriendAdditionalSchema = {
|
||||||
|
type: { field: 1, type: 'uint32' as const },
|
||||||
|
layer1: { field: 2, type: 'message' as const, schema: OidbFriendLayer1Schema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbFriendSchema = {
|
||||||
|
uid: { field: 1, type: 'string' as const },
|
||||||
|
customGroup:{ field: 2, type: 'uint32' as const },
|
||||||
|
uin: { field: 3, type: 'uint32' as const },
|
||||||
|
additional: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendAdditionalSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFD4_1ResponseUinSchema = {
|
||||||
|
uin: { field: 1, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFD4_1ResponseSchema = {
|
||||||
|
next: { field: 2, type: 'message' as const, schema: OidbSvcTrpcTcp0xFD4_1ResponseUinSchema },
|
||||||
|
displayFriendCount: { field: 3, type: 'uint32' as const },
|
||||||
|
timestamp: { field: 6, type: 'uint32' as const },
|
||||||
|
selfUin: { field: 7, type: 'uint32' as const },
|
||||||
|
friends: { field: 101, type: 'repeated_message' as const, schema: OidbFriendSchema },
|
||||||
|
groups: { field: 102, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Group list (0xFE5_2) ---
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE5_2MemberSchema = {
|
||||||
|
uid: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE5_2GroupInfoSchema = {
|
||||||
|
groupOwner: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2MemberSchema },
|
||||||
|
createdTime: { field: 2, type: 'uint32' as const },
|
||||||
|
memberMax: { field: 3, type: 'uint32' as const },
|
||||||
|
memberCount: { field: 4, type: 'uint32' as const },
|
||||||
|
groupName: { field: 5, type: 'string' as const },
|
||||||
|
description: { field: 18, type: 'string' as const },
|
||||||
|
question: { field: 19, type: 'string' as const },
|
||||||
|
announcement: { field: 30, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE5_2CustomInfoSchema = {
|
||||||
|
remark: { field: 3, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE5_2GroupSchema = {
|
||||||
|
groupUin: { field: 3, type: 'uint32' as const },
|
||||||
|
info: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupInfoSchema },
|
||||||
|
customInfo: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2CustomInfoSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE5_2ResponseSchema = {
|
||||||
|
groups: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupSchema },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Group member list (0xFE7_3) ---
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE7_3UinSchema = {
|
||||||
|
uid: { field: 2, type: 'string' as const },
|
||||||
|
uin: { field: 4, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE7_3CardSchema = {
|
||||||
|
memberCard: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE7_3LevelSchema = {
|
||||||
|
infos: { field: 1, type: 'repeated_uint32' as const },
|
||||||
|
level: { field: 2, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE7_3MemberSchema = {
|
||||||
|
uin: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3UinSchema },
|
||||||
|
memberName: { field: 10, type: 'string' as const },
|
||||||
|
specialTitle: { field: 17, type: 'string' as const },
|
||||||
|
memberCard: { field: 11, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3CardSchema },
|
||||||
|
level: { field: 12, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3LevelSchema },
|
||||||
|
joinTimestamp: { field: 100, type: 'uint32' as const },
|
||||||
|
lastMsgTimestamp: { field: 101, type: 'uint32' as const },
|
||||||
|
shutUpTimestamp: { field: 102, type: 'uint32' as const },
|
||||||
|
permission: { field: 107, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0xFE7_3ResponseSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
members: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE7_3MemberSchema },
|
||||||
|
field3: { field: 3, type: 'uint32' as const },
|
||||||
|
memberChangeSeq: { field: 5, type: 'uint32' as const },
|
||||||
|
memberCardChangeSeq:{ field: 6, type: 'uint32' as const },
|
||||||
|
token: { field: 15, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
// --- Group request (0x10C0) ---
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0x10C0ResponseUserSchema = {
|
||||||
|
uid: { field: 1, type: 'string' as const },
|
||||||
|
name: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0x10C0ResponseGroupSchema = {
|
||||||
|
groupUin: { field: 1, type: 'uint32' as const },
|
||||||
|
groupName: { field: 2, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0x10C0ResponseRequestSchema = {
|
||||||
|
sequence: { field: 1, type: 'uint64' as const },
|
||||||
|
eventType: { field: 2, type: 'uint32' as const },
|
||||||
|
state: { field: 3, type: 'uint32' as const },
|
||||||
|
group: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseGroupSchema },
|
||||||
|
target: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
|
||||||
|
invitor: { field: 6, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
|
||||||
|
operatorUser: { field: 7, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
|
||||||
|
field9: { field: 9, type: 'string' as const },
|
||||||
|
comment: { field: 10, type: 'string' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
|
|
||||||
|
export const OidbSvcTrpcTcp0x10C0ResponseSchema = {
|
||||||
|
requests: { field: 1, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseRequestSchema },
|
||||||
|
field2: { field: 2, type: 'uint64' as const },
|
||||||
|
newLatestSeq: { field: 3, type: 'uint64' as const },
|
||||||
|
field4: { field: 4, type: 'uint32' as const },
|
||||||
|
field5: { field: 5, type: 'uint64' as const },
|
||||||
|
field6: { field: 6, type: 'uint32' as const },
|
||||||
|
} satisfies ProtoSchema;
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
// QQ info store — per-UIN state for friends, groups, member lookup.
|
||||||
|
// Port of src/bridge/include/bridge/qq_info.h + src/bridge/src/qq_info.cpp
|
||||||
|
|
||||||
|
export interface UserProfileInfo {
|
||||||
|
uin: number;
|
||||||
|
uid: string;
|
||||||
|
nickname: string;
|
||||||
|
remark: string;
|
||||||
|
qid: string;
|
||||||
|
sex: string;
|
||||||
|
age: number;
|
||||||
|
sign: string;
|
||||||
|
avatar: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendInfo {
|
||||||
|
uin: number;
|
||||||
|
uid: string;
|
||||||
|
nickname: string;
|
||||||
|
remark: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupMemberInfo {
|
||||||
|
uin: number;
|
||||||
|
uid: string;
|
||||||
|
nickname: string;
|
||||||
|
card: string;
|
||||||
|
role: string; // 'owner' | 'admin' | 'member'
|
||||||
|
level: number;
|
||||||
|
title: string;
|
||||||
|
joinTime: number;
|
||||||
|
lastSentTime: number;
|
||||||
|
shutUpTime: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QQGroupInfo {
|
||||||
|
groupId: number;
|
||||||
|
groupName: string;
|
||||||
|
remark: string;
|
||||||
|
memberCount: number;
|
||||||
|
memberMax: number;
|
||||||
|
members: Map<number, GroupMemberInfo>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupRequestInfo {
|
||||||
|
groupId: number;
|
||||||
|
groupName: string;
|
||||||
|
targetUid: string;
|
||||||
|
targetUin: number;
|
||||||
|
targetName: string;
|
||||||
|
invitorUid: string;
|
||||||
|
invitorUin: number;
|
||||||
|
invitorName: string;
|
||||||
|
operatorUid: string;
|
||||||
|
operatorUin: number;
|
||||||
|
operatorName: string;
|
||||||
|
sequence: number;
|
||||||
|
state: number;
|
||||||
|
eventType: number;
|
||||||
|
comment: string;
|
||||||
|
filtered: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class QQInfo {
|
||||||
|
private uin_: string;
|
||||||
|
private nickname_ = '';
|
||||||
|
private selfProfile_: UserProfileInfo | null = null;
|
||||||
|
private userProfiles_ = new Map<number, UserProfileInfo>();
|
||||||
|
private friends_: FriendInfo[] = [];
|
||||||
|
private groups_ = new Map<number, QQGroupInfo>();
|
||||||
|
|
||||||
|
constructor(uin: string) {
|
||||||
|
this.uin_ = uin;
|
||||||
|
}
|
||||||
|
|
||||||
|
get uin(): string { return this.uin_; }
|
||||||
|
|
||||||
|
get nickname(): string { return this.nickname_; }
|
||||||
|
set nickname(v: string) { this.nickname_ = v; }
|
||||||
|
|
||||||
|
// --- Self profile ---
|
||||||
|
|
||||||
|
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
|
||||||
|
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
|
||||||
|
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
|
||||||
|
|
||||||
|
// --- User profiles ---
|
||||||
|
|
||||||
|
setUserProfile(info: UserProfileInfo): void {
|
||||||
|
this.userProfiles_.set(info.uin, info);
|
||||||
|
}
|
||||||
|
|
||||||
|
findUserProfile(uin: number): UserProfileInfo | null {
|
||||||
|
return this.userProfiles_.get(uin) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Friends ---
|
||||||
|
|
||||||
|
setFriends(friends: FriendInfo[]): void { this.friends_ = friends; }
|
||||||
|
get friends(): FriendInfo[] { return this.friends_; }
|
||||||
|
|
||||||
|
findFriend(uin: number): FriendInfo | null {
|
||||||
|
return this.friends_.find(f => f.uin === uin) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Groups ---
|
||||||
|
|
||||||
|
setGroups(groups: QQGroupInfo[]): void {
|
||||||
|
this.groups_.clear();
|
||||||
|
for (const g of groups) {
|
||||||
|
this.groups_.set(g.groupId, g);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
|
||||||
|
|
||||||
|
findGroup(groupId: number): QQGroupInfo | null {
|
||||||
|
return this.groups_.get(groupId) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
|
||||||
|
return this.groups_.get(groupId)?.members.get(uin) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
setGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
|
||||||
|
const g = this.groups_.get(groupId);
|
||||||
|
if (!g) return;
|
||||||
|
g.members.clear();
|
||||||
|
for (const m of members) {
|
||||||
|
g.members.set(m.uin, m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
|
||||||
|
const g = this.groups_.get(groupId);
|
||||||
|
if (!g) return;
|
||||||
|
g.members.set(member.uin, member);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- UID resolution ---
|
||||||
|
|
||||||
|
resolveUid(uid: string): number | null {
|
||||||
|
// Check self
|
||||||
|
if (this.selfProfile_?.uid === uid) {
|
||||||
|
return this.selfProfile_.uin || parseInt(this.uin_, 10) || null;
|
||||||
|
}
|
||||||
|
// Check friends
|
||||||
|
for (const f of this.friends_) {
|
||||||
|
if (f.uid === uid) return f.uin;
|
||||||
|
}
|
||||||
|
// Check user profiles
|
||||||
|
for (const [, p] of this.userProfiles_) {
|
||||||
|
if (p.uid === uid) return p.uin;
|
||||||
|
}
|
||||||
|
// Check all group members
|
||||||
|
for (const [, g] of this.groups_) {
|
||||||
|
for (const [, m] of g.members) {
|
||||||
|
if (m.uid === uid) return m.uin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolveGroupMemberUid(groupId: number, uid: string): number | null {
|
||||||
|
const g = this.groups_.get(groupId);
|
||||||
|
if (!g) return null;
|
||||||
|
for (const [, m] of g.members) {
|
||||||
|
if (m.uid === uid) return m.uin;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Reverse UID lookup (UIN → UID) ---
|
||||||
|
|
||||||
|
findUidByUin(uin: number): string | null {
|
||||||
|
// Check self
|
||||||
|
if (this.selfProfile_ && this.selfProfile_.uin === uin && this.selfProfile_.uid) {
|
||||||
|
return this.selfProfile_.uid;
|
||||||
|
}
|
||||||
|
// Check friends
|
||||||
|
for (const f of this.friends_) {
|
||||||
|
if (f.uin === uin && f.uid) return f.uid;
|
||||||
|
}
|
||||||
|
// Check user profiles
|
||||||
|
for (const [, p] of this.userProfiles_) {
|
||||||
|
if (p.uin === uin && p.uid) return p.uid;
|
||||||
|
}
|
||||||
|
// Check all group members
|
||||||
|
for (const [, g] of this.groups_) {
|
||||||
|
for (const [, m] of g.members) {
|
||||||
|
if (m.uin === uin && m.uid) return m.uid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
findUidByUinInGroup(groupId: number, uin: number): string | null {
|
||||||
|
const g = this.groups_.get(groupId);
|
||||||
|
if (!g) return null;
|
||||||
|
for (const [, m] of g.members) {
|
||||||
|
if (m.uin === uin && m.uid) return m.uid;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
export interface RuntimeConfig {
|
||||||
|
webuiPort?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CONFIG_DIR = 'config';
|
||||||
|
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||||
|
|
||||||
|
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||||
|
webuiPort: 8080,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function loadRuntimeConfig(): RuntimeConfig {
|
||||||
|
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||||
|
|
||||||
|
const loaded = tryLoadRuntimeConfig();
|
||||||
|
if (!loaded) {
|
||||||
|
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
|
||||||
|
return { ...DEFAULT_RUNTIME_CONFIG };
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalized: RuntimeConfig = {
|
||||||
|
webuiPort: normalizePort(loaded.webuiPort ?? 8080, 8080),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (
|
||||||
|
normalized.webuiPort !== loaded.webuiPort
|
||||||
|
) {
|
||||||
|
saveRuntimeConfig(normalized);
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||||
|
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8');
|
||||||
|
const parsed = JSON.parse(raw) as unknown;
|
||||||
|
if (!isObject(parsed)) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
webuiPort: normalizePort(parsed.webuiPort ?? 8080, 8080),
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||||
|
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePort(value: unknown, fallback: number): number {
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||||
|
const n = Math.trunc(value);
|
||||||
|
if (n > 0 && n <= 65535) return n;
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
if (typeof value === 'string' && value.trim()) {
|
||||||
|
const n = Number(value);
|
||||||
|
if (Number.isFinite(n)) {
|
||||||
|
const port = Math.trunc(n);
|
||||||
|
if (port > 0 && port <= 65535) return port;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isObject(value: unknown): value is Record<string, unknown> {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
declare const __BUILD_WEBUI__: boolean;
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
import type { BridgeManager } from '../bridge/manager';
|
||||||
|
import type { NtqqHandler } from '../protocol/ntqq-handler';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
import { HookPacketClient } from './hook-packet-client';
|
||||||
|
import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjectResult, type HookProcessBaseInfo } from './injector';
|
||||||
|
import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client';
|
||||||
|
|
||||||
|
const log = createLogger('Hook');
|
||||||
|
const CONNECT_RETRY_COUNT = 30;
|
||||||
|
const CONNECT_RETRY_INTERVAL_MS = 1000;
|
||||||
|
|
||||||
|
export type HookProcessStatus = 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected';
|
||||||
|
|
||||||
|
export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||||
|
injected: boolean;
|
||||||
|
connected: boolean;
|
||||||
|
loggedIn: boolean;
|
||||||
|
uin: string;
|
||||||
|
status: HookProcessStatus;
|
||||||
|
error: string;
|
||||||
|
method: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HookProcessState extends HookProcessInfo {
|
||||||
|
client: QqHookClient | null;
|
||||||
|
sender: HookPacketClient | null;
|
||||||
|
injectResult: HookInjectResult | null;
|
||||||
|
connectTask: Promise<void> | null;
|
||||||
|
bound: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class HookManager {
|
||||||
|
private readonly states = new Map<number, HookProcessState>();
|
||||||
|
private readonly loadTasks = new Map<number, Promise<HookProcessInfo>>();
|
||||||
|
private readonly unloadTasks = new Map<number, Promise<HookProcessInfo>>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly ntqq: NtqqHandler,
|
||||||
|
private readonly bridgeManager: BridgeManager,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||||
|
const processes = await listHookProcesses();
|
||||||
|
for (const proc of processes) {
|
||||||
|
const state = this.ensureState(proc.pid);
|
||||||
|
state.name = proc.name;
|
||||||
|
state.path = proc.path;
|
||||||
|
}
|
||||||
|
|
||||||
|
const seen = new Set(processes.map(proc => proc.pid));
|
||||||
|
const result: HookProcessInfo[] = [];
|
||||||
|
for (const proc of processes) {
|
||||||
|
result.push(this.toPublicInfo(this.ensureState(proc.pid)));
|
||||||
|
}
|
||||||
|
for (const state of this.states.values()) {
|
||||||
|
if (!seen.has(state.pid) && state.injected) {
|
||||||
|
result.push(this.toPublicInfo(state));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result.sort((a, b) => a.pid - b.pid);
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||||
|
if (!Number.isInteger(pid) || pid <= 0) {
|
||||||
|
throw new Error('invalid pid');
|
||||||
|
}
|
||||||
|
const runningTask = this.loadTasks.get(pid);
|
||||||
|
if (runningTask) return runningTask;
|
||||||
|
|
||||||
|
const task = this.loadProcessInternal(pid);
|
||||||
|
this.loadTasks.set(pid, task);
|
||||||
|
try {
|
||||||
|
return await task;
|
||||||
|
} finally {
|
||||||
|
this.loadTasks.delete(pid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||||
|
if (!Number.isInteger(pid) || pid <= 0) {
|
||||||
|
throw new Error('invalid pid');
|
||||||
|
}
|
||||||
|
const runningTask = this.unloadTasks.get(pid);
|
||||||
|
if (runningTask) return runningTask;
|
||||||
|
|
||||||
|
const task = this.unloadProcessInternal(pid);
|
||||||
|
this.unloadTasks.set(pid, task);
|
||||||
|
try {
|
||||||
|
return await task;
|
||||||
|
} finally {
|
||||||
|
this.unloadTasks.delete(pid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
for (const state of this.states.values()) {
|
||||||
|
state.client?.close();
|
||||||
|
state.client = null;
|
||||||
|
state.connected = false;
|
||||||
|
state.loggedIn = false;
|
||||||
|
state.status = state.injected ? 'disconnected' : 'available';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadProcessInternal(pid: number): Promise<HookProcessInfo> {
|
||||||
|
const state = this.ensureState(pid);
|
||||||
|
state.status = 'loading';
|
||||||
|
state.error = '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!state.injected) {
|
||||||
|
state.injectResult = injectHookProcess(pid);
|
||||||
|
state.injected = true;
|
||||||
|
state.method = state.injectResult.method;
|
||||||
|
log.info('SnowLuma loaded into PID=%d via %s', pid, state.method);
|
||||||
|
}
|
||||||
|
state.status = state.connected ? (state.loggedIn ? 'online' : 'loaded') : 'loaded';
|
||||||
|
this.startClient(state);
|
||||||
|
} catch (error) {
|
||||||
|
state.status = 'error';
|
||||||
|
state.error = error instanceof Error ? error.message : String(error);
|
||||||
|
log.error('load failed: PID=%d err=%s', pid, state.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.toPublicInfo(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async unloadProcessInternal(pid: number): Promise<HookProcessInfo> {
|
||||||
|
const state = this.ensureState(pid);
|
||||||
|
state.error = '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
state.client?.close();
|
||||||
|
state.client = null;
|
||||||
|
state.sender = null;
|
||||||
|
state.connectTask = null;
|
||||||
|
state.bound = false;
|
||||||
|
state.connected = false;
|
||||||
|
state.loggedIn = false;
|
||||||
|
this.bridgeManager.onPidDisconnected(pid);
|
||||||
|
|
||||||
|
const handle = state.injectResult?.handle;
|
||||||
|
if (state.injected && handle) {
|
||||||
|
unloadHookProcess(pid, handle);
|
||||||
|
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
|
||||||
|
}
|
||||||
|
|
||||||
|
state.injected = false;
|
||||||
|
state.injectResult = null;
|
||||||
|
state.method = '';
|
||||||
|
state.uin = '0';
|
||||||
|
state.status = 'available';
|
||||||
|
} catch (error) {
|
||||||
|
state.status = 'error';
|
||||||
|
state.error = error instanceof Error ? error.message : String(error);
|
||||||
|
log.error('unload failed: PID=%d err=%s', pid, state.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.toPublicInfo(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureState(pid: number): HookProcessState {
|
||||||
|
let state = this.states.get(pid);
|
||||||
|
if (!state) {
|
||||||
|
state = {
|
||||||
|
pid,
|
||||||
|
name: 'QQ.exe',
|
||||||
|
path: '',
|
||||||
|
injected: false,
|
||||||
|
connected: false,
|
||||||
|
loggedIn: false,
|
||||||
|
uin: '0',
|
||||||
|
status: 'available',
|
||||||
|
error: '',
|
||||||
|
method: '',
|
||||||
|
client: null,
|
||||||
|
sender: null,
|
||||||
|
injectResult: null,
|
||||||
|
connectTask: null,
|
||||||
|
bound: false,
|
||||||
|
};
|
||||||
|
this.states.set(pid, state);
|
||||||
|
}
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
private startClient(state: HookProcessState): void {
|
||||||
|
if (!state.client) {
|
||||||
|
state.client = new QqHookClient(state.pid);
|
||||||
|
state.sender = new HookPacketClient(state.client);
|
||||||
|
}
|
||||||
|
if (!state.bound) {
|
||||||
|
this.bindClient(state, state.client);
|
||||||
|
state.bound = true;
|
||||||
|
}
|
||||||
|
if (!state.connectTask) {
|
||||||
|
state.connectTask = this.connectClient(state).finally(() => {
|
||||||
|
state.connectTask = null;
|
||||||
|
});
|
||||||
|
void state.connectTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bindClient(state: HookProcessState, client: QqHookClient): void {
|
||||||
|
client.on('packet', packet => this.handlePacket(state, packet));
|
||||||
|
client.on('loginState', loginState => this.handleLoginState(state, loginState));
|
||||||
|
client.on('error', error => {
|
||||||
|
state.error = error instanceof Error ? error.message : String(error);
|
||||||
|
if (!state.connected) state.status = 'error';
|
||||||
|
log.warn('pipe error: PID=%d err=%s', state.pid, state.error);
|
||||||
|
});
|
||||||
|
client.on('close', () => {
|
||||||
|
state.connected = false;
|
||||||
|
if (state.loggedIn) {
|
||||||
|
state.loggedIn = false;
|
||||||
|
state.status = 'disconnected';
|
||||||
|
this.bridgeManager.onPidDisconnected(state.pid);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async connectClient(state: HookProcessState): Promise<void> {
|
||||||
|
const client = state.client;
|
||||||
|
if (!client) return;
|
||||||
|
|
||||||
|
for (let attempt = 1; attempt <= CONNECT_RETRY_COUNT; attempt++) {
|
||||||
|
try {
|
||||||
|
await client.connectAll({ recv: true });
|
||||||
|
state.connected = true;
|
||||||
|
state.status = client.isLoggedIn ? 'online' : 'loaded';
|
||||||
|
state.error = '';
|
||||||
|
const loginState = client.getLoginState();
|
||||||
|
if (loginState.loggedIn) {
|
||||||
|
this.handleLoginState(state, loginState);
|
||||||
|
}
|
||||||
|
log.info('pipe connected: PID=%d', state.pid);
|
||||||
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
state.error = error instanceof Error ? error.message : String(error);
|
||||||
|
if (attempt >= CONNECT_RETRY_COUNT) {
|
||||||
|
state.status = 'error';
|
||||||
|
log.error('pipe connect failed: PID=%d err=%s', state.pid, state.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await delay(CONNECT_RETRY_INTERVAL_MS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
|
||||||
|
state.uin = loginState.uin || loginState.uinNumber.toString();
|
||||||
|
state.loggedIn = loginState.loggedIn && isRealUin(state.uin);
|
||||||
|
state.status = state.loggedIn ? 'online' : (state.connected ? 'loaded' : state.status);
|
||||||
|
|
||||||
|
if (!state.loggedIn || !state.sender) return;
|
||||||
|
|
||||||
|
this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender);
|
||||||
|
log.success('login detected: PID=%d UIN=%s', state.pid, state.uin);
|
||||||
|
}
|
||||||
|
|
||||||
|
private handlePacket(state: HookProcessState, packet: QqHookPacket): void {
|
||||||
|
if (!state.loggedIn) return;
|
||||||
|
const uin = packet.uin || state.uin;
|
||||||
|
if (!isRealUin(uin)) return;
|
||||||
|
this.ntqq.onHookPacket(state.pid, { ...packet, uin });
|
||||||
|
}
|
||||||
|
|
||||||
|
private toPublicInfo(state: HookProcessState): HookProcessInfo {
|
||||||
|
return {
|
||||||
|
pid: state.pid,
|
||||||
|
name: state.name,
|
||||||
|
path: state.path,
|
||||||
|
injected: state.injected,
|
||||||
|
connected: state.connected,
|
||||||
|
loggedIn: state.loggedIn,
|
||||||
|
uin: state.uin,
|
||||||
|
status: state.status,
|
||||||
|
error: state.error,
|
||||||
|
method: state.method,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRealUin(uin: string): boolean {
|
||||||
|
if (!uin || uin === '0') return false;
|
||||||
|
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
function delay(ms: number): Promise<void> {
|
||||||
|
return new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
|
||||||
|
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
|
||||||
|
|
||||||
|
export class HookPacketClient implements PacketSender {
|
||||||
|
constructor(private readonly client: QqHookClient) {}
|
||||||
|
|
||||||
|
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||||
|
if (!this.client.isLoggedIn) {
|
||||||
|
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const reply = await this.client.send(serviceCmd, body, {
|
||||||
|
wantReply: true,
|
||||||
|
replyTimeoutMs: timeoutMs,
|
||||||
|
}) as QqHookSendReply;
|
||||||
|
return {
|
||||||
|
success: reply.error === 0,
|
||||||
|
gotResponse: true,
|
||||||
|
errorCode: reply.error,
|
||||||
|
errorMessage: reply.message || '',
|
||||||
|
responseData: reply.body,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
gotResponse: false,
|
||||||
|
errorCode: -1,
|
||||||
|
errorMessage: error instanceof Error ? error.message : String(error),
|
||||||
|
responseData: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import { existsSync } from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
export interface ManualMapHandle {
|
||||||
|
base: bigint;
|
||||||
|
entry: bigint;
|
||||||
|
size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NativeHookAddon {
|
||||||
|
getAllMainProcess(): number[];
|
||||||
|
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle;
|
||||||
|
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HookProcessBaseInfo {
|
||||||
|
pid: number;
|
||||||
|
name: string;
|
||||||
|
path: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HookInjectResult {
|
||||||
|
method: 'loadModuleManual';
|
||||||
|
handle?: ManualMapHandle;
|
||||||
|
}
|
||||||
|
|
||||||
|
let nativeAddon: NativeHookAddon | null = null;
|
||||||
|
let nativeLoadError: string | null = null;
|
||||||
|
|
||||||
|
function loadNativeAddon(addonPath: string): NativeHookAddon {
|
||||||
|
const mod = { exports: {} as Record<string, unknown> };
|
||||||
|
process.dlopen(mod, addonPath);
|
||||||
|
return mod.exports as unknown as NativeHookAddon;
|
||||||
|
}
|
||||||
|
|
||||||
|
function platformBinaryName(ext: 'node' | 'dll'): string {
|
||||||
|
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
|
||||||
|
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function nativeSearchDirs(): string[] {
|
||||||
|
return [
|
||||||
|
path.resolve(__dirname, '..', '..', 'native'),
|
||||||
|
path.resolve(__dirname, '..', 'native'),
|
||||||
|
path.resolve(process.cwd(), 'dist', 'native'),
|
||||||
|
path.resolve(process.cwd(), 'native'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveHookNativePath(ext: 'node' | 'dll'): string | null {
|
||||||
|
const fileName = platformBinaryName(ext);
|
||||||
|
for (const dir of nativeSearchDirs()) {
|
||||||
|
const fullPath = path.join(dir, fileName);
|
||||||
|
if (existsSync(fullPath)) return fullPath;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getNativeHookAddon(): NativeHookAddon | null {
|
||||||
|
if (nativeAddon) return nativeAddon;
|
||||||
|
const addonPath = resolveHookNativePath('node');
|
||||||
|
if (!addonPath) {
|
||||||
|
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
nativeAddon = loadNativeAddon(addonPath);
|
||||||
|
nativeLoadError = null;
|
||||||
|
return nativeAddon;
|
||||||
|
} catch (error) {
|
||||||
|
nativeLoadError = error instanceof Error ? error.message : String(error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getNativeHookLoadError(): string | null {
|
||||||
|
return nativeLoadError;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||||
|
const addon = getNativeHookAddon();
|
||||||
|
if (!addon) return [];
|
||||||
|
return [...new Set(addon.getAllMainProcess())]
|
||||||
|
.filter(pid => Number.isInteger(pid) && pid > 0)
|
||||||
|
.sort((a, b) => a - b)
|
||||||
|
.map(pid => ({ pid, name: 'QQ.exe', path: '' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function injectHookProcess(pid: number): HookInjectResult {
|
||||||
|
const addon = getNativeHookAddon();
|
||||||
|
if (!addon) {
|
||||||
|
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||||
|
}
|
||||||
|
const dllPath = resolveHookNativePath('dll');
|
||||||
|
if (!dllPath) {
|
||||||
|
throw new Error(`No hook DLL found for ${process.platform}-${process.arch}`);
|
||||||
|
}
|
||||||
|
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
|
||||||
|
const addon = getNativeHookAddon();
|
||||||
|
if (!addon) {
|
||||||
|
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||||
|
}
|
||||||
|
addon.unloadModuleManual(pid, handle);
|
||||||
|
}
|
||||||
@@ -0,0 +1,652 @@
|
|||||||
|
import net from 'net';
|
||||||
|
import { EventEmitter } from 'events';
|
||||||
|
|
||||||
|
export const PIPE_MAGIC = 0x31504851;
|
||||||
|
export const PIPE_VERSION = 1;
|
||||||
|
export const HEADER_SIZE = 40;
|
||||||
|
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
|
||||||
|
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
|
||||||
|
|
||||||
|
export enum PipeOp {
|
||||||
|
hello = 1,
|
||||||
|
sendRequest = 2,
|
||||||
|
sendAck = 3,
|
||||||
|
sendReply = 4,
|
||||||
|
error = 5,
|
||||||
|
recvPacket = 6,
|
||||||
|
loginState = 7,
|
||||||
|
}
|
||||||
|
|
||||||
|
const PipeFlagWantReply = 1 << 0;
|
||||||
|
const PipeFlagLoggedIn = 1 << 2;
|
||||||
|
|
||||||
|
export interface QqHookLoginState {
|
||||||
|
loggedIn: boolean;
|
||||||
|
uin: string;
|
||||||
|
uinNumber: bigint;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QqHookPacket {
|
||||||
|
seq: number;
|
||||||
|
error: number;
|
||||||
|
cmd: string;
|
||||||
|
uin: string;
|
||||||
|
body: Buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QqHookHello {
|
||||||
|
pipeName: string;
|
||||||
|
pid: number;
|
||||||
|
recvPipe: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QqHookSendReply {
|
||||||
|
requestId: number;
|
||||||
|
error: number;
|
||||||
|
message: string;
|
||||||
|
body: Buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QqHookClientOptions {
|
||||||
|
ackTimeoutMs?: number;
|
||||||
|
replyTimeoutMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QqHookSendOptions {
|
||||||
|
wantReply?: boolean;
|
||||||
|
ackTimeoutMs?: number;
|
||||||
|
replyTimeoutMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PipeFrame {
|
||||||
|
op: number;
|
||||||
|
requestId: number;
|
||||||
|
status: number;
|
||||||
|
flags: number;
|
||||||
|
value0: bigint;
|
||||||
|
cmd: string;
|
||||||
|
msg: string;
|
||||||
|
body: Buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Deferred<T> {
|
||||||
|
promise: Promise<T>;
|
||||||
|
resolve: (value: T | PromiseLike<T>) => void;
|
||||||
|
reject: (reason?: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PendingAck {
|
||||||
|
resolve: (value: { requestId: number; wantReply: boolean }) => void;
|
||||||
|
reject: (reason?: unknown) => void;
|
||||||
|
wantReply: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mojoPipeName(pid: number, suffix: string): string {
|
||||||
|
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
|
||||||
|
if (Buffer.isBuffer(body)) return body;
|
||||||
|
if (body instanceof Uint8Array) return Buffer.from(body);
|
||||||
|
if (typeof body === 'string') return Buffer.from(body, 'utf8');
|
||||||
|
if (body == null) return Buffer.alloc(0);
|
||||||
|
throw new TypeError('body must be Buffer, Uint8Array, string, or null');
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDeferred<T>(): Deferred<T> {
|
||||||
|
let resolve!: (value: T | PromiseLike<T>) => void;
|
||||||
|
let reject!: (reason?: unknown) => void;
|
||||||
|
const promise = new Promise<T>((res, rej) => {
|
||||||
|
resolve = res;
|
||||||
|
reject = rej;
|
||||||
|
});
|
||||||
|
return { promise, resolve, reject };
|
||||||
|
}
|
||||||
|
|
||||||
|
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
|
||||||
|
if (!timeoutMs || timeoutMs <= 0) return promise;
|
||||||
|
return new Promise<T>((resolve, reject) => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
reject(new Error(`${label} timed out after ${timeoutMs} ms`));
|
||||||
|
}, timeoutMs);
|
||||||
|
promise.then(
|
||||||
|
value => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
resolve(value);
|
||||||
|
},
|
||||||
|
error => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeFrame({
|
||||||
|
op,
|
||||||
|
requestId = 0,
|
||||||
|
status = 0,
|
||||||
|
flags = 0,
|
||||||
|
value0 = 0n,
|
||||||
|
cmd = '',
|
||||||
|
msg = '',
|
||||||
|
body = Buffer.alloc(0),
|
||||||
|
}: {
|
||||||
|
op: number;
|
||||||
|
requestId?: number;
|
||||||
|
status?: number;
|
||||||
|
flags?: number;
|
||||||
|
value0?: bigint | number;
|
||||||
|
cmd?: string;
|
||||||
|
msg?: string;
|
||||||
|
body?: Buffer | Uint8Array | string | null;
|
||||||
|
}): Buffer {
|
||||||
|
const cmdBuf = Buffer.from(cmd, 'utf8');
|
||||||
|
const msgBuf = Buffer.from(msg, 'utf8');
|
||||||
|
const bodyBuf = toBuffer(body);
|
||||||
|
const header = Buffer.alloc(HEADER_SIZE);
|
||||||
|
header.writeUInt32LE(PIPE_MAGIC, 0);
|
||||||
|
header.writeUInt16LE(PIPE_VERSION, 4);
|
||||||
|
header.writeUInt16LE(op, 6);
|
||||||
|
header.writeUInt32LE(requestId >>> 0, 8);
|
||||||
|
header.writeInt32LE(status | 0, 12);
|
||||||
|
header.writeUInt32LE(flags >>> 0, 16);
|
||||||
|
header.writeUInt32LE(cmdBuf.length >>> 0, 20);
|
||||||
|
header.writeUInt32LE(msgBuf.length >>> 0, 24);
|
||||||
|
header.writeUInt32LE(bodyBuf.length >>> 0, 28);
|
||||||
|
header.writeBigUInt64LE(BigInt(value0), 32);
|
||||||
|
return Buffer.concat([header, cmdBuf, msgBuf, bodyBuf]);
|
||||||
|
}
|
||||||
|
|
||||||
|
class FrameReader {
|
||||||
|
private buffer = Buffer.alloc(0);
|
||||||
|
|
||||||
|
constructor(private readonly onFrame: (frame: PipeFrame) => void) {}
|
||||||
|
|
||||||
|
push(chunk: Buffer): void {
|
||||||
|
this.buffer = Buffer.concat([this.buffer, chunk]);
|
||||||
|
while (this.buffer.length >= HEADER_SIZE) {
|
||||||
|
const magic = this.buffer.readUInt32LE(0);
|
||||||
|
const version = this.buffer.readUInt16LE(4);
|
||||||
|
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
|
||||||
|
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cmdLen = this.buffer.readUInt32LE(20);
|
||||||
|
const msgLen = this.buffer.readUInt32LE(24);
|
||||||
|
const bodyLen = this.buffer.readUInt32LE(28);
|
||||||
|
const total = HEADER_SIZE + cmdLen + msgLen + bodyLen;
|
||||||
|
if (this.buffer.length < total) return;
|
||||||
|
|
||||||
|
const frame: PipeFrame = {
|
||||||
|
op: this.buffer.readUInt16LE(6),
|
||||||
|
requestId: this.buffer.readUInt32LE(8),
|
||||||
|
status: this.buffer.readInt32LE(12),
|
||||||
|
flags: this.buffer.readUInt32LE(16),
|
||||||
|
value0: this.buffer.readBigUInt64LE(32),
|
||||||
|
cmd: '',
|
||||||
|
msg: '',
|
||||||
|
body: Buffer.alloc(0),
|
||||||
|
};
|
||||||
|
|
||||||
|
let offset = HEADER_SIZE;
|
||||||
|
frame.cmd = this.buffer.subarray(offset, offset + cmdLen).toString('utf8');
|
||||||
|
offset += cmdLen;
|
||||||
|
frame.msg = this.buffer.subarray(offset, offset + msgLen).toString('utf8');
|
||||||
|
offset += msgLen;
|
||||||
|
frame.body = Buffer.from(this.buffer.subarray(offset, offset + bodyLen));
|
||||||
|
|
||||||
|
this.buffer = this.buffer.subarray(total);
|
||||||
|
this.onFrame(frame);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class QqHookClient extends EventEmitter {
|
||||||
|
readonly pid: number;
|
||||||
|
readonly defaultAckTimeoutMs: number;
|
||||||
|
readonly defaultReplyTimeoutMs: number;
|
||||||
|
|
||||||
|
private controlSocket: net.Socket | null = null;
|
||||||
|
private recvSocket: net.Socket | null = null;
|
||||||
|
private controlConnectPromise: Promise<QqHookHello> | null = null;
|
||||||
|
private recvConnectPromise: Promise<QqHookHello> | null = null;
|
||||||
|
private nextRequestId = 1;
|
||||||
|
private pendingAcks = new Map<number, PendingAck>();
|
||||||
|
private pendingReplies = new Map<number, Deferred<QqHookSendReply>>();
|
||||||
|
private controlHello: QqHookHello | null = null;
|
||||||
|
private recvHello: QqHookHello | null = null;
|
||||||
|
private controlHelloResolver: Deferred<QqHookHello> | null = null;
|
||||||
|
private recvHelloResolver: Deferred<QqHookHello> | null = null;
|
||||||
|
private controlWriteChain: Promise<unknown> = Promise.resolve();
|
||||||
|
private closed = false;
|
||||||
|
private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||||
|
private loginWaiters: Deferred<QqHookLoginState>[] = [];
|
||||||
|
|
||||||
|
constructor(pid: number, {
|
||||||
|
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
|
||||||
|
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
|
||||||
|
}: QqHookClientOptions = {}) {
|
||||||
|
super();
|
||||||
|
this.pid = pid;
|
||||||
|
this.defaultAckTimeoutMs = ackTimeoutMs;
|
||||||
|
this.defaultReplyTimeoutMs = replyTimeoutMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
get isLoggedIn(): boolean {
|
||||||
|
return this.loginState.loggedIn;
|
||||||
|
}
|
||||||
|
|
||||||
|
get currentUin(): string {
|
||||||
|
return this.loginState.uin;
|
||||||
|
}
|
||||||
|
|
||||||
|
get currentUinNumber(): bigint {
|
||||||
|
return this.loginState.uinNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
getLoginState(): QqHookLoginState {
|
||||||
|
return { ...this.loginState };
|
||||||
|
}
|
||||||
|
|
||||||
|
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
|
||||||
|
await this.connect();
|
||||||
|
if (this.loginState.loggedIn) {
|
||||||
|
return this.getLoginState();
|
||||||
|
}
|
||||||
|
const deferred = createDeferred<QqHookLoginState>();
|
||||||
|
this.loginWaiters.push(deferred);
|
||||||
|
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
|
||||||
|
}
|
||||||
|
|
||||||
|
static controlPipeName(pid: number): string {
|
||||||
|
return mojoPipeName(pid, 'control');
|
||||||
|
}
|
||||||
|
|
||||||
|
static recvPipeName(pid: number): string {
|
||||||
|
return mojoPipeName(pid, 'recv');
|
||||||
|
}
|
||||||
|
|
||||||
|
async connect(): Promise<QqHookHello> {
|
||||||
|
if (this.closed) {
|
||||||
|
throw new Error('qq_hook client is closed');
|
||||||
|
}
|
||||||
|
if (this.controlSocket && this.controlHello) {
|
||||||
|
return this.controlHello;
|
||||||
|
}
|
||||||
|
if (this.controlConnectPromise) {
|
||||||
|
return this.controlConnectPromise;
|
||||||
|
}
|
||||||
|
this.controlConnectPromise = (async () => {
|
||||||
|
this.controlSocket = await this.connectSocket(
|
||||||
|
QqHookClient.controlPipeName(this.pid),
|
||||||
|
'control',
|
||||||
|
frame => this.handleControlFrame(frame));
|
||||||
|
this.controlHello = await this.waitForHello(false);
|
||||||
|
return this.controlHello;
|
||||||
|
})();
|
||||||
|
try {
|
||||||
|
return await this.controlConnectPromise;
|
||||||
|
} finally {
|
||||||
|
this.controlConnectPromise = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async startRecv(onPacket?: (packet: QqHookPacket) => void): Promise<QqHookHello> {
|
||||||
|
if (this.closed) {
|
||||||
|
throw new Error('qq_hook client is closed');
|
||||||
|
}
|
||||||
|
if (typeof onPacket === 'function') {
|
||||||
|
this.on('packet', onPacket);
|
||||||
|
}
|
||||||
|
if (this.recvSocket && this.recvHello) {
|
||||||
|
return this.recvHello;
|
||||||
|
}
|
||||||
|
if (this.recvConnectPromise) {
|
||||||
|
return this.recvConnectPromise;
|
||||||
|
}
|
||||||
|
this.recvConnectPromise = (async () => {
|
||||||
|
this.recvSocket = await this.connectSocket(
|
||||||
|
QqHookClient.recvPipeName(this.pid),
|
||||||
|
'recv',
|
||||||
|
frame => this.handleRecvFrame(frame));
|
||||||
|
this.recvHello = await this.waitForHello(true);
|
||||||
|
return this.recvHello;
|
||||||
|
})();
|
||||||
|
try {
|
||||||
|
return await this.recvConnectPromise;
|
||||||
|
} finally {
|
||||||
|
this.recvConnectPromise = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async connectAll({ recv = true } = {}): Promise<{ control: QqHookHello; recv: QqHookHello | null }> {
|
||||||
|
const control = await this.connect();
|
||||||
|
const recvInfo = recv ? await this.startRecv() : null;
|
||||||
|
return { control, recv: recvInfo };
|
||||||
|
}
|
||||||
|
|
||||||
|
async send(cmd: string, body: Buffer | Uint8Array | string | null | undefined, {
|
||||||
|
wantReply = true,
|
||||||
|
ackTimeoutMs = this.defaultAckTimeoutMs,
|
||||||
|
replyTimeoutMs = this.defaultReplyTimeoutMs,
|
||||||
|
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
|
||||||
|
await this.connect();
|
||||||
|
|
||||||
|
const requestId = this.nextRequestId++ >>> 0;
|
||||||
|
const payload = encodeFrame({
|
||||||
|
op: PipeOp.sendRequest,
|
||||||
|
requestId,
|
||||||
|
flags: wantReply ? PipeFlagWantReply : 0,
|
||||||
|
cmd,
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
|
||||||
|
this.pendingAcks.set(requestId, {
|
||||||
|
resolve: ackDeferred.resolve,
|
||||||
|
reject: ackDeferred.reject,
|
||||||
|
wantReply,
|
||||||
|
});
|
||||||
|
|
||||||
|
let replyDeferred: Deferred<QqHookSendReply> | null = null;
|
||||||
|
if (wantReply) {
|
||||||
|
replyDeferred = createDeferred<QqHookSendReply>();
|
||||||
|
this.pendingReplies.set(requestId, replyDeferred);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.writeControl(payload);
|
||||||
|
await withTimeout(ackDeferred.promise, ackTimeoutMs, `send ack ${requestId}`);
|
||||||
|
if (!wantReply) {
|
||||||
|
return { requestId };
|
||||||
|
}
|
||||||
|
return await withTimeout(
|
||||||
|
replyDeferred!.promise,
|
||||||
|
replyTimeoutMs,
|
||||||
|
`send reply ${requestId}`);
|
||||||
|
} catch (error) {
|
||||||
|
this.pendingAcks.delete(requestId);
|
||||||
|
this.pendingReplies.delete(requestId);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendNoReply(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<{ requestId: number }> {
|
||||||
|
return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{ requestId: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendAndWait(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<QqHookSendReply> {
|
||||||
|
return this.send(cmd, body, { ...options, wantReply: true }) as Promise<QqHookSendReply>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendMany(items: Array<{ cmd: string; body?: Buffer | Uint8Array | string | null; wantReply?: boolean; ackTimeoutMs?: number; replyTimeoutMs?: number }>, {
|
||||||
|
concurrency = 64,
|
||||||
|
wantReply = true,
|
||||||
|
ackTimeoutMs = this.defaultAckTimeoutMs,
|
||||||
|
replyTimeoutMs = this.defaultReplyTimeoutMs,
|
||||||
|
}: QqHookSendOptions & { concurrency?: number } = {}): Promise<Array<QqHookSendReply | { requestId: number }>> {
|
||||||
|
const results = new Array<QqHookSendReply | { requestId: number }>(items.length);
|
||||||
|
let nextIndex = 0;
|
||||||
|
const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1));
|
||||||
|
|
||||||
|
const worker = async () => {
|
||||||
|
for (;;) {
|
||||||
|
const index = nextIndex;
|
||||||
|
nextIndex += 1;
|
||||||
|
if (index >= items.length) return;
|
||||||
|
const item = items[index];
|
||||||
|
const itemWantReply = item.wantReply ?? wantReply;
|
||||||
|
results[index] = await this.send(item.cmd, item.body, {
|
||||||
|
wantReply: itemWantReply,
|
||||||
|
ackTimeoutMs: item.ackTimeoutMs ?? ackTimeoutMs,
|
||||||
|
replyTimeoutMs: item.replyTimeoutMs ?? replyTimeoutMs,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
await Promise.all(Array.from({ length: workerCount }, () => worker()));
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
waitForPacket(predicate: (packet: QqHookPacket) => boolean = () => true, { timeoutMs = 0 } = {}): Promise<QqHookPacket> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let timer: NodeJS.Timeout | null = null;
|
||||||
|
const cleanup = () => {
|
||||||
|
this.off('packet', onPacket);
|
||||||
|
if (timer) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onPacket = (packet: QqHookPacket) => {
|
||||||
|
try {
|
||||||
|
if (!predicate(packet)) return;
|
||||||
|
cleanup();
|
||||||
|
resolve(packet);
|
||||||
|
} catch (error) {
|
||||||
|
cleanup();
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
this.on('packet', onPacket);
|
||||||
|
if (timeoutMs > 0) {
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
cleanup();
|
||||||
|
reject(new Error(`recv packet timed out after ${timeoutMs} ms`));
|
||||||
|
}, timeoutMs);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
if (this.closed) return;
|
||||||
|
this.closed = true;
|
||||||
|
this.rejectControlPending(new Error('qq_hook client closed'));
|
||||||
|
this.rejectRecvPending(new Error('qq_hook client closed'));
|
||||||
|
this.rejectLoginWaiters(new Error('qq_hook client closed'));
|
||||||
|
|
||||||
|
if (this.controlSocket) {
|
||||||
|
this.controlSocket.destroy();
|
||||||
|
this.controlSocket = null;
|
||||||
|
}
|
||||||
|
if (this.recvSocket) {
|
||||||
|
this.recvSocket.destroy();
|
||||||
|
this.recvSocket = null;
|
||||||
|
}
|
||||||
|
this.controlHello = null;
|
||||||
|
this.recvHello = null;
|
||||||
|
this.controlWriteChain = Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
private rejectLoginWaiters(error: Error): void {
|
||||||
|
const waiters = this.loginWaiters;
|
||||||
|
this.loginWaiters = [];
|
||||||
|
for (const waiter of waiters) waiter.reject(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
private rejectControlPending(error: Error): void {
|
||||||
|
for (const pending of this.pendingAcks.values()) {
|
||||||
|
pending.reject(error);
|
||||||
|
}
|
||||||
|
for (const pending of this.pendingReplies.values()) {
|
||||||
|
pending.reject(error);
|
||||||
|
}
|
||||||
|
this.pendingAcks.clear();
|
||||||
|
this.pendingReplies.clear();
|
||||||
|
if (this.controlHelloResolver) {
|
||||||
|
this.controlHelloResolver.reject(error);
|
||||||
|
this.controlHelloResolver = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private rejectRecvPending(error: Error): void {
|
||||||
|
if (this.recvHelloResolver) {
|
||||||
|
this.recvHelloResolver.reject(error);
|
||||||
|
this.recvHelloResolver = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private writeControl(payload: Buffer): Promise<void> {
|
||||||
|
const socket = this.controlSocket;
|
||||||
|
if (!socket || socket.destroyed) {
|
||||||
|
return Promise.reject(new Error('control pipe is not connected'));
|
||||||
|
}
|
||||||
|
const writePromise = this.controlWriteChain.then(() => new Promise<void>((resolve, reject) => {
|
||||||
|
if (!this.controlSocket || this.controlSocket.destroyed) {
|
||||||
|
reject(new Error('control pipe is not connected'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
socket.write(payload, error => {
|
||||||
|
if (error) reject(error);
|
||||||
|
else resolve();
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
this.controlWriteChain = writePromise.catch(() => {});
|
||||||
|
return writePromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise<net.Socket> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const socket = net.createConnection(pipeName);
|
||||||
|
const reader = new FrameReader(onFrame);
|
||||||
|
const onInitialError = (error: Error) => reject(error);
|
||||||
|
socket.once('error', onInitialError);
|
||||||
|
socket.once('connect', () => {
|
||||||
|
socket.off('error', onInitialError);
|
||||||
|
socket.on('data', chunk => {
|
||||||
|
try {
|
||||||
|
reader.push(chunk);
|
||||||
|
} catch (error) {
|
||||||
|
this.emit('error', error);
|
||||||
|
socket.destroy(error instanceof Error ? error : undefined);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
socket.on('error', error => {
|
||||||
|
this.emit('error', error);
|
||||||
|
});
|
||||||
|
socket.on('close', () => {
|
||||||
|
this.handleSocketClose(kind);
|
||||||
|
this.emit('close', kind);
|
||||||
|
});
|
||||||
|
resolve(socket);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private waitForHello(recvPipe: boolean): Promise<QqHookHello> {
|
||||||
|
const deferred = createDeferred<QqHookHello>();
|
||||||
|
if (recvPipe) {
|
||||||
|
this.recvHelloResolver = deferred;
|
||||||
|
} else {
|
||||||
|
this.controlHelloResolver = deferred;
|
||||||
|
}
|
||||||
|
return deferred.promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveHello(frame: PipeFrame, recvPipe: boolean): void {
|
||||||
|
const resolver = recvPipe ? this.recvHelloResolver : this.controlHelloResolver;
|
||||||
|
if (!resolver) return;
|
||||||
|
if (recvPipe) this.recvHelloResolver = null;
|
||||||
|
else this.controlHelloResolver = null;
|
||||||
|
resolver.resolve({
|
||||||
|
pipeName: frame.msg,
|
||||||
|
pid: Number(frame.value0),
|
||||||
|
recvPipe,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleSocketClose(kind: 'control' | 'recv'): void {
|
||||||
|
if (kind === 'control') {
|
||||||
|
this.controlSocket = null;
|
||||||
|
this.controlHello = null;
|
||||||
|
this.rejectControlPending(new Error('control pipe closed'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.recvSocket = null;
|
||||||
|
this.recvHello = null;
|
||||||
|
this.rejectRecvPending(new Error('recv pipe closed'));
|
||||||
|
}
|
||||||
|
|
||||||
|
private applyLoginStateFrame(frame: PipeFrame): void {
|
||||||
|
const flaggedLoggedIn = (frame.flags & PipeFlagLoggedIn) !== 0;
|
||||||
|
const statusLoggedIn = frame.status !== 0;
|
||||||
|
const loggedIn = flaggedLoggedIn || statusLoggedIn;
|
||||||
|
const uinNumber = BigInt(frame.value0);
|
||||||
|
const uin = frame.msg || uinNumber.toString();
|
||||||
|
const previous = this.loginState;
|
||||||
|
const next = { loggedIn, uin, uinNumber };
|
||||||
|
this.loginState = next;
|
||||||
|
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
|
||||||
|
this.emit('loginState', next);
|
||||||
|
if (next.loggedIn) {
|
||||||
|
const waiters = this.loginWaiters;
|
||||||
|
this.loginWaiters = [];
|
||||||
|
for (const waiter of waiters) waiter.resolve({ ...next });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleControlFrame(frame: PipeFrame): void {
|
||||||
|
if (frame.op === PipeOp.hello) {
|
||||||
|
this.resolveHello(frame, false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.op === PipeOp.loginState) {
|
||||||
|
this.applyLoginStateFrame(frame);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.op === PipeOp.sendAck) {
|
||||||
|
const pending = this.pendingAcks.get(frame.requestId);
|
||||||
|
if (!pending) return;
|
||||||
|
this.pendingAcks.delete(frame.requestId);
|
||||||
|
pending.resolve({ requestId: frame.requestId, wantReply: pending.wantReply });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.op === PipeOp.sendReply) {
|
||||||
|
const pending = this.pendingReplies.get(frame.requestId);
|
||||||
|
if (!pending) return;
|
||||||
|
this.pendingReplies.delete(frame.requestId);
|
||||||
|
pending.resolve({
|
||||||
|
requestId: frame.requestId,
|
||||||
|
error: frame.status,
|
||||||
|
message: frame.msg,
|
||||||
|
body: Buffer.from(frame.body),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.op === PipeOp.error) {
|
||||||
|
const error = new Error(frame.msg || `pipe error ${frame.status}`);
|
||||||
|
const ack = this.pendingAcks.get(frame.requestId);
|
||||||
|
if (ack) {
|
||||||
|
this.pendingAcks.delete(frame.requestId);
|
||||||
|
ack.reject(error);
|
||||||
|
}
|
||||||
|
const reply = this.pendingReplies.get(frame.requestId);
|
||||||
|
if (reply) {
|
||||||
|
this.pendingReplies.delete(frame.requestId);
|
||||||
|
reply.reject(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleRecvFrame(frame: PipeFrame): void {
|
||||||
|
if (frame.op === PipeOp.hello) {
|
||||||
|
this.resolveHello(frame, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.op === PipeOp.loginState) {
|
||||||
|
this.applyLoginStateFrame(frame);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.op !== PipeOp.recvPacket) return;
|
||||||
|
this.emit('packet', {
|
||||||
|
seq: Number(frame.value0),
|
||||||
|
error: frame.status,
|
||||||
|
cmd: frame.cmd,
|
||||||
|
uin: frame.msg,
|
||||||
|
body: Buffer.from(frame.body),
|
||||||
|
} satisfies QqHookPacket);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { mojoPipeName };
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { NtqqHandler } from './protocol/ntqq-handler';
|
||||||
|
import { BridgeManager } from './bridge/manager';
|
||||||
|
import { OneBotManager } from './onebot/manager';
|
||||||
|
import { loadRuntimeConfig } from './common/runtime';
|
||||||
|
import { createLogger } from './utils/logger';
|
||||||
|
import { HookManager } from './hook/hook-manager';
|
||||||
|
|
||||||
|
const runtimeConfig = loadRuntimeConfig();
|
||||||
|
const log = createLogger('App');
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
log.info('SnowLuma starting');
|
||||||
|
|
||||||
|
const ntqq = new NtqqHandler();
|
||||||
|
const bridgeManager = new BridgeManager();
|
||||||
|
const oneBotManager = new OneBotManager();
|
||||||
|
const hookManager = new HookManager(ntqq, bridgeManager);
|
||||||
|
|
||||||
|
// Bind bridge manager to NTQQ handler (receives all parsed packets)
|
||||||
|
bridgeManager.bind(ntqq);
|
||||||
|
oneBotManager.bind(bridgeManager);
|
||||||
|
|
||||||
|
if (typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) {
|
||||||
|
try {
|
||||||
|
log.info('WebUI is enabled, starting...');
|
||||||
|
const { initWebUI } = await import('./webui/server');
|
||||||
|
initWebUI(runtimeConfig.webuiPort || 8080, oneBotManager, hookManager);
|
||||||
|
} catch (err) {
|
||||||
|
log.error('Failed to start WebUI: ', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Graceful shutdown
|
||||||
|
process.on('SIGINT', () => {
|
||||||
|
log.warn('Shutting down...');
|
||||||
|
oneBotManager.dispose();
|
||||||
|
hookManager.dispose();
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error) => {
|
||||||
|
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,601 @@
|
|||||||
|
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||||
|
import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
|
||||||
|
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||||
|
|
||||||
|
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||||
|
// --- Likes & Pokes ---
|
||||||
|
|
||||||
|
h.registerAction('send_like', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const times = asNumber(params.times) || 1;
|
||||||
|
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
if (!ctx.sendLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.sendLike(userId, times);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('friend_poke', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const targetId = asNumber(params.target_id) || undefined;
|
||||||
|
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.sendFriendPoke(userId, targetId);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('group_poke', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||||
|
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.sendGroupPoke(groupId, userId);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('send_poke', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
if (groupId) {
|
||||||
|
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.sendGroupPoke(groupId, userId);
|
||||||
|
} else {
|
||||||
|
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.sendFriendPoke(userId);
|
||||||
|
}
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Essence ---
|
||||||
|
|
||||||
|
h.registerAction('set_essence_msg', async (params) => {
|
||||||
|
const messageId = asNumber(params.message_id);
|
||||||
|
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||||
|
}
|
||||||
|
if (!ctx.setEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setEssenceMsg(messageId);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('delete_essence_msg', async (params) => {
|
||||||
|
const messageId = asNumber(params.message_id);
|
||||||
|
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||||
|
}
|
||||||
|
if (!ctx.deleteEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.deleteEssenceMsg(messageId);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_essence_msg_list', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
// Essence list fetch requires web ticket/cookie flow not wired yet.
|
||||||
|
// Keep API-compatible output shape for callers.
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Reactions ---
|
||||||
|
|
||||||
|
h.registerAction('set_group_reaction', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const messageId = asNumber(params.message_id);
|
||||||
|
const code = asString(params.code);
|
||||||
|
const isSet = asBoolean(params.is_set, true);
|
||||||
|
|
||||||
|
if (!Number.isInteger(messageId) || messageId === 0 || !code) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'message_id and code are required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta = ctx.getMessageMeta(messageId);
|
||||||
|
if (!meta || !meta.isGroup) {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (groupId && groupId !== meta.targetId) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ctx.setGroupReaction) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setGroupReaction(meta.targetId, meta.sequence, code, isSet);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- History ---
|
||||||
|
|
||||||
|
h.registerAction('get_group_msg_history', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const messageId = asNumber(params.message_id) || 0;
|
||||||
|
const count = asNumber(params.count) || 20;
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
if (!ctx.getGroupMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
const messages = await ctx.getGroupMsgHistory(groupId, messageId, count);
|
||||||
|
return okResponse({ messages });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_friend_msg_history', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const messageId = asNumber(params.message_id) || 0;
|
||||||
|
const count = asNumber(params.count) || 20;
|
||||||
|
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
if (!ctx.getFriendMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
const messages = await ctx.getFriendMsgHistory(userId, messageId, count);
|
||||||
|
return okResponse({ messages });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('mark_msg_as_read', async () => {
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- RKey ---
|
||||||
|
|
||||||
|
h.registerAction('get_rkey', async () => {
|
||||||
|
if (ctx.getDownloadRKeys) {
|
||||||
|
return okResponse(await ctx.getDownloadRKeys());
|
||||||
|
}
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- OCR stubs ---
|
||||||
|
|
||||||
|
h.registerAction('ocr_image', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('.ocr_image', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Group notice stubs ---
|
||||||
|
|
||||||
|
h.registerAction('_send_group_notice', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('_get_group_notice', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('_del_group_notice', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Forward messages ---
|
||||||
|
|
||||||
|
h.registerAction('upload_forward_msg', async (params) => {
|
||||||
|
const messages = asMessage(params.messages ?? params.message);
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||||
|
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
|
||||||
|
const result = await ctx.sendForwardMsg(messages);
|
||||||
|
const data: Record<string, unknown> = {
|
||||||
|
res_id: result.forwardId,
|
||||||
|
forward_id: result.forwardId,
|
||||||
|
message_id: 0,
|
||||||
|
};
|
||||||
|
if (groupId > 0) data.group_id = groupId;
|
||||||
|
return okResponse(data as any);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('upload_foward_msg', async (params) => {
|
||||||
|
const messages = asMessage(params.messages ?? params.message);
|
||||||
|
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||||
|
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
const result = await ctx.sendForwardMsg(messages);
|
||||||
|
return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('send_forward_msg', async (params) => {
|
||||||
|
const messageType = asString(params.message_type);
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const messages = asMessage(params.messages ?? params.message);
|
||||||
|
|
||||||
|
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||||
|
|
||||||
|
if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) {
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
const result = await ctx.sendGroupForwardMsg(groupId, messages);
|
||||||
|
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) {
|
||||||
|
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
const result = await ctx.sendPrivateForwardMsg(userId, messages);
|
||||||
|
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
const result = await ctx.sendForwardMsg(messages);
|
||||||
|
return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('send_group_forward_msg', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const messages = asMessage(params.messages ?? params.message);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||||
|
if (!ctx.sendGroupForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
|
||||||
|
const result = await ctx.sendGroupForwardMsg(groupId, messages);
|
||||||
|
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('send_private_forward_msg', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const messages = asMessage(params.messages ?? params.message);
|
||||||
|
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||||
|
if (!ctx.sendPrivateForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
|
||||||
|
const result = await ctx.sendPrivateForwardMsg(userId, messages);
|
||||||
|
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_forward_msg', async (params) => {
|
||||||
|
let id = asString(params.id);
|
||||||
|
if (!id) {
|
||||||
|
const rawMessageId = params.message_id;
|
||||||
|
const numericMessageId = asNumber(rawMessageId);
|
||||||
|
if (numericMessageId > 0) {
|
||||||
|
const event = ctx.getMessage(numericMessageId);
|
||||||
|
const segments = Array.isArray(event?.message) ? event.message : [];
|
||||||
|
for (const seg of segments) {
|
||||||
|
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||||
|
const so = seg as Record<string, unknown>;
|
||||||
|
if (String(so.type ?? '') !== 'forward') continue;
|
||||||
|
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data))
|
||||||
|
? so.data as Record<string, unknown>
|
||||||
|
: null;
|
||||||
|
const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id);
|
||||||
|
if (candidate) {
|
||||||
|
id = candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!id) {
|
||||||
|
id = asString(rawMessageId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required');
|
||||||
|
if (!ctx.getForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
|
||||||
|
const messages = await ctx.getForwardMsg(id);
|
||||||
|
return okResponse({ messages });
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Media ---
|
||||||
|
|
||||||
|
h.registerAction('get_image', async (params) => {
|
||||||
|
const file = asString(params.file);
|
||||||
|
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||||
|
const imageInfo = findMediaInStore('image', file, ctx);
|
||||||
|
if (imageInfo) {
|
||||||
|
return okResponse(imageInfo as unknown as import('../types').JsonValue);
|
||||||
|
}
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_record', async (params) => {
|
||||||
|
const file = asString(params.file);
|
||||||
|
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||||
|
const recordInfo = findMediaInStore('record', file, ctx);
|
||||||
|
if (recordInfo) {
|
||||||
|
return okResponse(recordInfo as unknown as import('../types').JsonValue);
|
||||||
|
}
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Credentials ---
|
||||||
|
|
||||||
|
h.registerAction('get_cookies', async () => {
|
||||||
|
return okResponse({ cookies: '' });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_csrf_token', async () => {
|
||||||
|
return okResponse({ token: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_credentials', async () => {
|
||||||
|
return okResponse({ cookies: '', csrf_token: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Utility ---
|
||||||
|
|
||||||
|
h.registerAction('set_restart', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not supported');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('clean_cache', async () => {
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('.handle_quick_operation', async (params) => {
|
||||||
|
const context = params.context as import('../types').JsonObject | undefined;
|
||||||
|
const operation = params.operation as Record<string, unknown> | undefined;
|
||||||
|
if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required');
|
||||||
|
const { executeQuickOperation } = await import('../http-post-transport');
|
||||||
|
await executeQuickOperation(context, operation, h);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- NapCat-compatible extended APIs ---
|
||||||
|
|
||||||
|
h.registerAction('set_friend_remark', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const remark = asString(params.remark) ?? '';
|
||||||
|
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
if (!ctx.setFriendRemark) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setFriendRemark(userId, remark);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_msg_emoji_like', async (params) => {
|
||||||
|
const messageId = asNumber(params.message_id);
|
||||||
|
const emojiId = asString(params.emoji_id);
|
||||||
|
const set = asBoolean(params.set, true);
|
||||||
|
if (!Number.isInteger(messageId) || messageId === 0 || !emojiId) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
|
||||||
|
}
|
||||||
|
if (!ctx.setMsgEmojiLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setMsgEmojiLike(messageId, emojiId, set);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('mark_private_msg_as_read', async () => {
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('mark_group_msg_as_read', async () => {
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('_mark_all_as_read', async () => {
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_file_system_info', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
if (ctx.getGroupFileCount) {
|
||||||
|
const info = await ctx.getGroupFileCount(groupId);
|
||||||
|
return okResponse({
|
||||||
|
file_count: info.fileCount,
|
||||||
|
limit_count: info.maxCount,
|
||||||
|
used_space: 0,
|
||||||
|
total_space: 10737418240,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return okResponse({
|
||||||
|
file_count: 0,
|
||||||
|
limit_count: 10000,
|
||||||
|
used_space: 0,
|
||||||
|
total_space: 10737418240,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('check_url_safely', async () => {
|
||||||
|
return okResponse({ level: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('download_file', async (params) => {
|
||||||
|
const url = asString(params.url);
|
||||||
|
const base64 = asString(params.base64);
|
||||||
|
const name = asString(params.name);
|
||||||
|
if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required');
|
||||||
|
|
||||||
|
const fs = await import('fs');
|
||||||
|
const pathMod = await import('path');
|
||||||
|
const cryptoMod = await import('crypto');
|
||||||
|
const tempDir = pathMod.join('data', 'downloads');
|
||||||
|
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
|
||||||
|
|
||||||
|
let filePath: string;
|
||||||
|
if (base64) {
|
||||||
|
const buf = Buffer.from(base64, 'base64');
|
||||||
|
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
|
||||||
|
filePath = pathMod.join(tempDir, fileName);
|
||||||
|
fs.writeFileSync(filePath, buf);
|
||||||
|
} else {
|
||||||
|
const response = await fetch(url!, {
|
||||||
|
headers: parseDownloadHeaders(params.headers),
|
||||||
|
});
|
||||||
|
if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`);
|
||||||
|
const buf = Buffer.from(await response.arrayBuffer());
|
||||||
|
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
|
||||||
|
filePath = pathMod.join(tempDir, fileName);
|
||||||
|
fs.writeFileSync(filePath, buf);
|
||||||
|
}
|
||||||
|
return okResponse({ file: pathMod.resolve(filePath) });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_qq_profile', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_online_status', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_ignored_notifies', async () => {
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_shut_list', async () => {
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('forward_friend_single_msg', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('forward_group_single_msg', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_recent_contact', async () => {
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_profile_like', async () => {
|
||||||
|
return okResponse({});
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_friends_with_category', async () => {
|
||||||
|
if (ctx.getFriendList) {
|
||||||
|
return okResponse(await ctx.getFriendList());
|
||||||
|
}
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Additional NapCat-compatible stubs ---
|
||||||
|
|
||||||
|
h.registerAction('get_online_clients', async () => {
|
||||||
|
return okResponse({ clients: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('_get_model_show', async () => {
|
||||||
|
return okResponse({ variants: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('_set_model_show', async () => {
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('.get_word_slices', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_at_all_remain', async () => {
|
||||||
|
return okResponse({ can_at_all: false, remain_at_all_count_for_group: 0, remain_at_all_count_for_uin: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_unidirectional_friend_list', async () => {
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_self_longnick', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_collection_list', async () => {
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('create_collection', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_qq_avatar', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_input_status', async () => {
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('translate_en2zh', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_clientkey', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_mini_app_ark', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('click_inline_keyboard_button', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_sign', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('send_group_sign', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_info_ex', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
if (ctx.getGroupInfo) {
|
||||||
|
return okResponse(await ctx.getGroupInfo(groupId));
|
||||||
|
}
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_detail_info', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
if (ctx.getGroupInfo) {
|
||||||
|
return okResponse(await ctx.getGroupInfo(groupId));
|
||||||
|
}
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('trans_group_file', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('rename_group_file', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_file', async (params) => {
|
||||||
|
const fileId = asString(params.file_id) || asString(params.file);
|
||||||
|
if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required');
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('.send_packet', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search through cached message segments to find a media element (image/record)
|
||||||
|
* that matches the given file identifier.
|
||||||
|
*/
|
||||||
|
function findMediaInStore(
|
||||||
|
mediaType: 'image' | 'record',
|
||||||
|
file: string,
|
||||||
|
ctx: ApiActionContext,
|
||||||
|
): Record<string, unknown> | null {
|
||||||
|
// The file param can match a file id, a URL, or a filename stored in segments.
|
||||||
|
// We don't have a reverse index, so this is best-effort from stored events.
|
||||||
|
// Most callers will pass the `file` field from a received message segment.
|
||||||
|
// Just return the info if we can look it up from any recent cached message.
|
||||||
|
// This is a known limitation — full implementation would require a media cache.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse download_file headers parameter into a Record.
|
||||||
|
*/
|
||||||
|
function parseDownloadHeaders(headers: unknown): Record<string, string> {
|
||||||
|
const result: Record<string, string> = {};
|
||||||
|
if (!headers) return result;
|
||||||
|
const headerList: string[] = [];
|
||||||
|
if (typeof headers === 'string') {
|
||||||
|
headerList.push(...headers.split(/\r?\n/).filter(Boolean));
|
||||||
|
} else if (Array.isArray(headers)) {
|
||||||
|
for (const h of headers) {
|
||||||
|
if (typeof h === 'string') headerList.push(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const line of headerList) {
|
||||||
|
const idx = line.indexOf('=');
|
||||||
|
if (idx > 0) {
|
||||||
|
result[line.substring(0, idx).trim()] = line.substring(idx + 1).trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||||
|
import { asNumber, asBoolean } from '../api-handler';
|
||||||
|
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||||
|
|
||||||
|
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||||
|
h.registerAction('get_friend_list', async () => {
|
||||||
|
if (ctx.getFriendList) {
|
||||||
|
return okResponse(await ctx.getFriendList());
|
||||||
|
}
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_stranger_info', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
if (ctx.getStrangerInfo) {
|
||||||
|
const info = await ctx.getStrangerInfo(userId);
|
||||||
|
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||||
|
}
|
||||||
|
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('delete_friend', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const block = asBoolean(params.block, false);
|
||||||
|
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
if (!ctx.handleDeleteFriend) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.handleDeleteFriend(userId, block);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||||
|
import { asNumber, asString, asBoolean } from '../api-handler';
|
||||||
|
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||||
|
|
||||||
|
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||||
|
h.registerAction('set_group_kick', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const reject = asBoolean(params.reject_add_request, false);
|
||||||
|
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||||
|
if (!ctx.setGroupKick) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setGroupKick(groupId, userId, reject);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_ban', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const duration = asNumber(params.duration) || 1800;
|
||||||
|
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||||
|
if (!ctx.setGroupBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setGroupBan(groupId, userId, duration);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_whole_ban', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const enable = asBoolean(params.enable, true);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
if (!ctx.setGroupWholeBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setGroupWholeBan(groupId, enable);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_admin', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const enable = asBoolean(params.enable, true);
|
||||||
|
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||||
|
if (!ctx.setGroupAdmin) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setGroupAdmin(groupId, userId, enable);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_card', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const card = asString(params.card);
|
||||||
|
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||||
|
if (!ctx.setGroupCard) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setGroupCard(groupId, userId, card);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_name', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const name = asString(params.group_name);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
if (!ctx.setGroupName) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setGroupName(groupId, name);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_leave', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
if (!ctx.setGroupLeave) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setGroupLeave(groupId);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_special_title', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const title = asString(params.special_title);
|
||||||
|
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||||
|
if (!ctx.setGroupSpecialTitle) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.setGroupSpecialTitle(groupId, userId, title);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_anonymous', async () => {
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_anonymous_ban', async () => {
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_portrait', async () => {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||||
|
import { asBoolean, asNumber, asString } from '../api-handler';
|
||||||
|
import { RETCODE, failedResponse } from '../types';
|
||||||
|
import { okResponse } from '../types';
|
||||||
|
|
||||||
|
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||||
|
h.registerAction('upload_group_file', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const file = asString(params.file);
|
||||||
|
const name = asString(params.name);
|
||||||
|
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
|
||||||
|
const uploadFile = asBoolean(params.upload_file, true);
|
||||||
|
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
|
||||||
|
if (!ctx.uploadGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
const fileId = await ctx.uploadGroupFile(groupId, file, name, folderId, uploadFile);
|
||||||
|
return okResponse({ file_id: fileId });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('upload_private_file', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const file = asString(params.file);
|
||||||
|
const name = asString(params.name);
|
||||||
|
const uploadFile = asBoolean(params.upload_file, true);
|
||||||
|
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
|
||||||
|
if (!ctx.uploadPrivateFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
const fileId = await ctx.uploadPrivateFile(userId, file, name, uploadFile);
|
||||||
|
return okResponse({ file_id: fileId });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_file_url', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const fileId = asString(params.file_id);
|
||||||
|
const busId = asNumber(params.busid) || 102;
|
||||||
|
if (!groupId || !fileId) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||||
|
}
|
||||||
|
if (!ctx.getGroupFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
return okResponse({ url: await ctx.getGroupFileUrl(groupId, fileId, busId) });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_root_files', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!groupId) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
}
|
||||||
|
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
return okResponse(await ctx.getGroupFiles(groupId, '/'));
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_files_by_folder', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const folderId = asString(params.folder_id) || asString(params.folder) || '/';
|
||||||
|
if (!groupId) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
}
|
||||||
|
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
return okResponse(await ctx.getGroupFiles(groupId, folderId));
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('delete_group_file', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const fileId = asString(params.file_id);
|
||||||
|
if (!groupId || !fileId) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||||
|
}
|
||||||
|
if (!ctx.deleteGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.deleteGroupFile(groupId, fileId);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('move_group_file', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const fileId = asString(params.file_id);
|
||||||
|
const parentDirectory = asString(params.parent_directory);
|
||||||
|
const targetDirectory = asString(params.target_directory);
|
||||||
|
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
|
||||||
|
}
|
||||||
|
if (!ctx.moveGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('create_group_file_folder', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const name = asString(params.name);
|
||||||
|
const parentId = asString(params.parent_id) || '/';
|
||||||
|
if (!groupId || !name) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
|
||||||
|
}
|
||||||
|
if (!ctx.createGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.createGroupFileFolder(groupId, name, parentId);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('delete_group_file_folder', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const folderId = asString(params.folder_id);
|
||||||
|
if (!groupId || !folderId) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
|
||||||
|
}
|
||||||
|
if (!ctx.deleteGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.deleteGroupFileFolder(groupId, folderId);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('rename_group_file_folder', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const folderId = asString(params.folder_id);
|
||||||
|
const newName = asString(params.new_folder_name) || asString(params.name);
|
||||||
|
if (!groupId || !folderId || !newName) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
|
||||||
|
}
|
||||||
|
if (!ctx.renameGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.renameGroupFileFolder(groupId, folderId, newName);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_private_file_url', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const fileId = asString(params.file_id);
|
||||||
|
const fileHash = asString(params.file_hash);
|
||||||
|
if (!userId || !fileId || !fileHash) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
|
||||||
|
}
|
||||||
|
if (!ctx.getPrivateFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
return okResponse({ url: await ctx.getPrivateFileUrl(userId, fileId, fileHash) });
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||||
|
import { asNumber, asBoolean } from '../api-handler';
|
||||||
|
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||||
|
|
||||||
|
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||||
|
h.registerAction('get_group_list', async (params) => {
|
||||||
|
const noCache = asBoolean(params.no_cache, false);
|
||||||
|
if (ctx.getGroupList) {
|
||||||
|
return okResponse(await ctx.getGroupList(noCache));
|
||||||
|
}
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_info', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
const noCache = asBoolean(params.no_cache, false);
|
||||||
|
if (ctx.getGroupInfo) {
|
||||||
|
const info = await ctx.getGroupInfo(groupId, noCache);
|
||||||
|
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||||
|
}
|
||||||
|
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_member_list', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
const noCache = asBoolean(params.no_cache, false);
|
||||||
|
if (ctx.getGroupMemberList) {
|
||||||
|
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
|
||||||
|
}
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_member_info', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||||
|
const noCache = asBoolean(params.no_cache, false);
|
||||||
|
if (ctx.getGroupMemberInfo) {
|
||||||
|
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
|
||||||
|
return okResponse(info ?? {
|
||||||
|
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||||
|
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||||
|
level: '0', role: 'member', title: '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return okResponse({
|
||||||
|
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||||
|
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||||
|
level: '0', role: 'member', title: '',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_honor_info', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
return okResponse({
|
||||||
|
group_id: groupId, current_talkative: null, talkative_list: [],
|
||||||
|
performer_list: [], legend_list: [], strong_newbie_list: [], emotion_list: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_group_system_msg', async () => {
|
||||||
|
if (ctx.handleGetGroupSystemMsg) {
|
||||||
|
return okResponse(await ctx.handleGetGroupSystemMsg());
|
||||||
|
}
|
||||||
|
return okResponse([]);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||||
|
import { okResponse } from '../types';
|
||||||
|
|
||||||
|
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||||
|
h.registerAction('get_login_info', async () => {
|
||||||
|
const login = ctx.getLoginInfo();
|
||||||
|
return okResponse({ user_id: login.userId, nickname: login.nickname });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_status', async () => {
|
||||||
|
const online = ctx.isOnline();
|
||||||
|
return okResponse({ online, good: online });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_version_info', async () => {
|
||||||
|
return okResponse({
|
||||||
|
app_name: 'SnowLuma',
|
||||||
|
app_version: '0.1.0-node',
|
||||||
|
protocol_version: 'v11',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('can_send_image', async () => {
|
||||||
|
return okResponse({ yes: ctx.canSendImage?.() ?? false });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('can_send_record', async () => {
|
||||||
|
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import type { JsonObject, JsonValue } from '../types';
|
||||||
|
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||||
|
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
|
||||||
|
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||||
|
|
||||||
|
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||||
|
h.registerAction('send_msg', async (params) => {
|
||||||
|
const messageType = asString(params.message_type);
|
||||||
|
const message = asMessage(params.message);
|
||||||
|
const autoEscape = asBoolean(params.auto_escape, false);
|
||||||
|
|
||||||
|
if (message === undefined) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageType === 'group' || params.group_id !== undefined) {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
}
|
||||||
|
if (!ctx.sendGroupMessage) {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
|
||||||
|
}
|
||||||
|
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||||
|
return okResponse({ message_id: result.messageId });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
if (!Number.isInteger(userId) || userId <= 0) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
}
|
||||||
|
if (!ctx.sendPrivateMessage) {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
|
||||||
|
}
|
||||||
|
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||||
|
return okResponse({ message_id: result.messageId });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('send_private_msg', async (params) => {
|
||||||
|
const userId = asNumber(params.user_id);
|
||||||
|
const message = asMessage(params.message);
|
||||||
|
const autoEscape = asBoolean(params.auto_escape, false);
|
||||||
|
|
||||||
|
if (!Number.isInteger(userId) || userId <= 0) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||||
|
}
|
||||||
|
if (message === undefined) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||||
|
}
|
||||||
|
if (!ctx.sendPrivateMessage) {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||||
|
return okResponse({ message_id: result.messageId });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('send_group_msg', async (params) => {
|
||||||
|
const groupId = asNumber(params.group_id);
|
||||||
|
const message = asMessage(params.message);
|
||||||
|
const autoEscape = asBoolean(params.auto_escape, false);
|
||||||
|
|
||||||
|
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||||
|
}
|
||||||
|
if (message === undefined) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||||
|
}
|
||||||
|
if (!ctx.sendGroupMessage) {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||||
|
return okResponse({ message_id: result.messageId });
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('get_msg', async (params) => {
|
||||||
|
const messageId = asNumber(params.message_id);
|
||||||
|
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = ctx.getMessage(messageId);
|
||||||
|
if (!data) {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: JsonObject = { ...data };
|
||||||
|
delete result.post_type;
|
||||||
|
delete result.self_id;
|
||||||
|
result.real_id = (result.message_id ?? messageId) as JsonValue;
|
||||||
|
return okResponse(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('delete_msg', async (params) => {
|
||||||
|
const messageId = asNumber(params.message_id);
|
||||||
|
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||||
|
}
|
||||||
|
if (!ctx.deleteMessage) {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'delete_msg is not implemented');
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta = ctx.getMessageMeta(messageId);
|
||||||
|
if (!meta) {
|
||||||
|
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
|
||||||
|
}
|
||||||
|
|
||||||
|
await ctx.deleteMessage(messageId, meta);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||||
|
import { asString, asBoolean } from '../api-handler';
|
||||||
|
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||||
|
|
||||||
|
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||||
|
h.registerAction('set_friend_add_request', async (params) => {
|
||||||
|
const flag = asString(params.flag);
|
||||||
|
const approve = asBoolean(params.approve, true);
|
||||||
|
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||||
|
if (!ctx.handleFriendRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.handleFriendRequest(flag, approve);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
|
||||||
|
h.registerAction('set_group_add_request', async (params) => {
|
||||||
|
const flag = asString(params.flag);
|
||||||
|
const subType = asString(params.sub_type, asString(params.type, 'add'));
|
||||||
|
const approve = asBoolean(params.approve, true);
|
||||||
|
const reason = asString(params.reason);
|
||||||
|
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||||
|
if (!ctx.handleGroupRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||||
|
await ctx.handleGroupRequest(flag, subType, approve, reason);
|
||||||
|
return okResponse();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||||
|
import { RETCODE, failedResponse } from './types';
|
||||||
|
|
||||||
|
import { register as registerInfo } from './actions/info';
|
||||||
|
import { register as registerMessage } from './actions/message';
|
||||||
|
import { register as registerFriend } from './actions/friend';
|
||||||
|
import { register as registerGroupInfo } from './actions/group-info';
|
||||||
|
import { register as registerGroupAdmin } from './actions/group-admin';
|
||||||
|
import { register as registerGroupFile } from './actions/group-file';
|
||||||
|
import { register as registerRequest } from './actions/request';
|
||||||
|
import { register as registerExtended } from './actions/extended';
|
||||||
|
|
||||||
|
export interface MessageSendResult {
|
||||||
|
messageId: number;
|
||||||
|
meta?: MessageMeta;
|
||||||
|
echoEvent?: JsonObject;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiActionContext {
|
||||||
|
getLoginInfo: () => { userId: number; nickname: string };
|
||||||
|
isOnline: () => boolean;
|
||||||
|
getMessage: (messageId: number) => JsonObject | null;
|
||||||
|
getMessageMeta: (messageId: number) => MessageMeta | null;
|
||||||
|
sendPrivateMessage?: (userId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||||
|
sendGroupMessage?: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||||
|
deleteMessage?: (messageId: number, meta: MessageMeta) => Promise<void>;
|
||||||
|
canSendImage?: () => boolean;
|
||||||
|
canSendRecord?: () => boolean;
|
||||||
|
// Info retrieval (async — triggers OIDB fetch)
|
||||||
|
getFriendList?: () => Promise<JsonObject[]>;
|
||||||
|
getGroupList?: (noCache?: boolean) => Promise<JsonObject[]>;
|
||||||
|
getGroupInfo?: (groupId: number, noCache?: boolean) => Promise<JsonObject | null>;
|
||||||
|
getGroupMemberList?: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
|
||||||
|
getGroupMemberInfo?: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
|
||||||
|
getStrangerInfo?: (userId: number) => Promise<JsonObject | null>;
|
||||||
|
// Group admin
|
||||||
|
setGroupKick?: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
|
||||||
|
setGroupBan?: (groupId: number, userId: number, duration: number) => Promise<void>;
|
||||||
|
setGroupWholeBan?: (groupId: number, enable: boolean) => Promise<void>;
|
||||||
|
setGroupAdmin?: (groupId: number, userId: number, enable: boolean) => Promise<void>;
|
||||||
|
setGroupCard?: (groupId: number, userId: number, card: string) => Promise<void>;
|
||||||
|
setGroupName?: (groupId: number, name: string) => Promise<void>;
|
||||||
|
setGroupLeave?: (groupId: number) => Promise<void>;
|
||||||
|
setGroupSpecialTitle?: (groupId: number, userId: number, title: string) => Promise<void>;
|
||||||
|
// Group file
|
||||||
|
uploadGroupFile?: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
|
||||||
|
uploadPrivateFile?: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
|
||||||
|
getGroupFileUrl?: (groupId: number, fileId: string, busId?: number) => Promise<string>;
|
||||||
|
getGroupFiles?: (groupId: number, folderId?: string) => Promise<JsonObject>;
|
||||||
|
deleteGroupFile?: (groupId: number, fileId: string) => Promise<void>;
|
||||||
|
moveGroupFile?: (groupId: number, fileId: string, parentDirectory: string, targetDirectory: string) => Promise<void>;
|
||||||
|
createGroupFileFolder?: (groupId: number, name: string, parentId?: string) => Promise<void>;
|
||||||
|
deleteGroupFileFolder?: (groupId: number, folderId: string) => Promise<void>;
|
||||||
|
renameGroupFileFolder?: (groupId: number, folderId: string, newName: string) => Promise<void>;
|
||||||
|
getPrivateFileUrl?: (userId: number, fileId: string, fileHash: string) => Promise<string>;
|
||||||
|
// Requests
|
||||||
|
handleFriendRequest?: (flag: string, approve: boolean) => Promise<void>;
|
||||||
|
handleGroupRequest?: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
|
||||||
|
// Extended
|
||||||
|
sendLike?: (userId: number, times: number) => Promise<void>;
|
||||||
|
sendFriendPoke?: (userId: number, targetId?: number) => Promise<void>;
|
||||||
|
sendGroupPoke?: (groupId: number, userId: number) => Promise<void>;
|
||||||
|
setEssenceMsg?: (messageId: number) => Promise<void>;
|
||||||
|
deleteEssenceMsg?: (messageId: number) => Promise<void>;
|
||||||
|
// New context methods
|
||||||
|
setGroupReaction?: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
|
||||||
|
handleDeleteFriend?: (userId: number, block?: boolean) => Promise<void>;
|
||||||
|
getGroupMsgHistory?: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
|
||||||
|
getFriendMsgHistory?: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
|
||||||
|
handleGetGroupSystemMsg?: () => Promise<JsonObject[]>;
|
||||||
|
getDownloadRKeys?: () => Promise<JsonObject[]>;
|
||||||
|
// Forward message
|
||||||
|
sendGroupForwardMsg?: (groupId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
|
||||||
|
sendPrivateForwardMsg?: (userId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
|
||||||
|
sendForwardMsg?: (messages: JsonValue) => Promise<{ forwardId: string }>;
|
||||||
|
getForwardMsg?: (resId: string) => Promise<JsonObject[]>;
|
||||||
|
// Extended NapCat-compatible
|
||||||
|
setFriendRemark?: (userId: number, remark: string) => Promise<void>;
|
||||||
|
getGroupFileCount?: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
|
||||||
|
setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
|
||||||
|
|
||||||
|
export class ApiHandler {
|
||||||
|
private readonly handlers = new Map<string, ActionHandler>();
|
||||||
|
|
||||||
|
constructor(context: ApiActionContext) {
|
||||||
|
registerInfo(this, context);
|
||||||
|
registerMessage(this, context);
|
||||||
|
registerFriend(this, context);
|
||||||
|
registerGroupInfo(this, context);
|
||||||
|
registerGroupAdmin(this, context);
|
||||||
|
registerGroupFile(this, context);
|
||||||
|
registerRequest(this, context);
|
||||||
|
registerExtended(this, context);
|
||||||
|
}
|
||||||
|
|
||||||
|
registerAction(action: string, handler: ActionHandler): void {
|
||||||
|
this.handlers.set(action, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
async handle(action: string, params: JsonObject): Promise<import('./types').ApiResponse> {
|
||||||
|
const handler = this.handlers.get(action);
|
||||||
|
if (!handler) {
|
||||||
|
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await handler(params);
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : 'internal error';
|
||||||
|
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async processRequest(rawRequest: string): Promise<string> {
|
||||||
|
if (!rawRequest.trim()) {
|
||||||
|
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(rawRequest) as unknown;
|
||||||
|
if (!isJsonObject(parsed)) {
|
||||||
|
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const action = asString(parsed.action);
|
||||||
|
if (!action) {
|
||||||
|
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const params = isJsonObject(parsed.params) ? parsed.params : {};
|
||||||
|
const echo = parsed.echo;
|
||||||
|
const response = await this.handle(action, params);
|
||||||
|
if (echo !== undefined) {
|
||||||
|
response.echo = toJsonValue(echo);
|
||||||
|
}
|
||||||
|
|
||||||
|
return JSON.stringify(response);
|
||||||
|
} catch {
|
||||||
|
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isJsonObject(value: unknown): value is JsonObject {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function asString(value: unknown, fallback = ''): string {
|
||||||
|
if (typeof value === 'string') return value;
|
||||||
|
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function asNumber(value: unknown): number {
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||||
|
if (typeof value === 'string' && value.trim()) {
|
||||||
|
const n = Number(value);
|
||||||
|
if (Number.isFinite(n)) return Math.trunc(n);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function asBoolean(value: unknown, fallback: boolean): boolean {
|
||||||
|
if (typeof value === 'boolean') return value;
|
||||||
|
if (typeof value === 'number') return value !== 0;
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const text = value.trim().toLowerCase();
|
||||||
|
if (text === 'true' || text === '1' || text === 'yes' || text === 'on') return true;
|
||||||
|
if (text === 'false' || text === '0' || text === 'no' || text === 'off') return false;
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toJsonValue(value: unknown): JsonValue {
|
||||||
|
if (value === null) return null;
|
||||||
|
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value;
|
||||||
|
if (Array.isArray(value)) return value.map(toJsonValue);
|
||||||
|
if (isJsonObject(value)) {
|
||||||
|
const obj: JsonObject = {};
|
||||||
|
for (const [key, item] of Object.entries(value)) {
|
||||||
|
obj[key] = toJsonValue(item);
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function asMessage(value: unknown): import('./types').JsonValue | undefined {
|
||||||
|
if (value === undefined) return undefined;
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(trimmed);
|
||||||
|
if (Array.isArray(parsed)) {
|
||||||
|
return toJsonValue(parsed);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Fallback to literal text if it just looks like an array but is invalid JSON
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return toJsonValue(value);
|
||||||
|
}
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { randomBytes } from 'crypto';
|
||||||
|
import type {
|
||||||
|
HttpPostEndpoint,
|
||||||
|
HttpServerEndpoint,
|
||||||
|
JsonObject,
|
||||||
|
OneBotConfig,
|
||||||
|
WsClientEndpoint,
|
||||||
|
WsRole,
|
||||||
|
WsServerEndpoint,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
const CONFIG_DIR = 'config';
|
||||||
|
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||||
|
|
||||||
|
export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||||
|
return {
|
||||||
|
httpServers: [{ host: '0.0.0.0', port: 3000, path: '/' }],
|
||||||
|
httpPostEndpoints: [],
|
||||||
|
wsServers: [{ host: '0.0.0.0', port: 3001 }],
|
||||||
|
wsClients: [],
|
||||||
|
musicSignUrl: '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadOneBotConfig(uin: string): OneBotConfig {
|
||||||
|
ensureConfigDir();
|
||||||
|
|
||||||
|
const merged = deepClone(toJsonObject(makeDefaultOneBotConfig()));
|
||||||
|
const globalConfig = tryLoadJson(DEFAULT_CONFIG_PATH);
|
||||||
|
if (globalConfig) {
|
||||||
|
deepMerge(merged, globalConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||||
|
const perUinConfig = tryLoadJson(perUinPath);
|
||||||
|
if (perUinConfig) {
|
||||||
|
deepMerge(merged, perUinConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = fromJson(merged);
|
||||||
|
let shouldSave = !perUinConfig;
|
||||||
|
|
||||||
|
// Auto-generate per-endpoint accessToken if not set.
|
||||||
|
for (const s of config.httpServers) {
|
||||||
|
if (!s.accessToken) {
|
||||||
|
s.accessToken = generateRandomKey();
|
||||||
|
shouldSave = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const s of config.wsServers) {
|
||||||
|
if (!s.accessToken) {
|
||||||
|
s.accessToken = generateRandomKey();
|
||||||
|
shouldSave = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const c of config.wsClients) {
|
||||||
|
if (!c.accessToken) {
|
||||||
|
c.accessToken = generateRandomKey();
|
||||||
|
shouldSave = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist normalized endpoints and generated keys.
|
||||||
|
merged.httpServers = config.httpServers.map((s) => {
|
||||||
|
const out: JsonObject = {
|
||||||
|
host: s.host,
|
||||||
|
port: s.port,
|
||||||
|
path: s.path ?? '/',
|
||||||
|
accessToken: s.accessToken ?? '',
|
||||||
|
};
|
||||||
|
if (s.name) out.name = s.name;
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
merged.httpPostEndpoints = config.httpPostEndpoints.map((e) => {
|
||||||
|
const out: JsonObject = { url: e.url };
|
||||||
|
if (e.name) out.name = e.name;
|
||||||
|
if (e.accessToken) out.accessToken = e.accessToken;
|
||||||
|
if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs;
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
merged.wsServers = config.wsServers.map((s) => {
|
||||||
|
const out: JsonObject = {
|
||||||
|
host: s.host,
|
||||||
|
port: s.port,
|
||||||
|
path: s.path ?? '/',
|
||||||
|
role: s.role ?? 'universal',
|
||||||
|
accessToken: s.accessToken ?? '',
|
||||||
|
};
|
||||||
|
if (s.name) out.name = s.name;
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
merged.wsClients = config.wsClients.map((c) => {
|
||||||
|
const out: JsonObject = {
|
||||||
|
url: c.url,
|
||||||
|
role: c.role ?? 'universal',
|
||||||
|
accessToken: c.accessToken ?? '',
|
||||||
|
};
|
||||||
|
if (c.name) out.name = c.name;
|
||||||
|
if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) {
|
||||||
|
out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
merged.musicSignUrl = config.musicSignUrl ?? '';
|
||||||
|
|
||||||
|
if (shouldSave) {
|
||||||
|
saveJson(perUinPath, merged);
|
||||||
|
}
|
||||||
|
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveOneBotConfig(uin: string, config: OneBotConfig): void {
|
||||||
|
ensureConfigDir();
|
||||||
|
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||||
|
const jsonObj = toJsonObject(config);
|
||||||
|
saveJson(perUinPath, jsonObj);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureConfigDir(): void {
|
||||||
|
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function toJsonObject(config: OneBotConfig): JsonObject {
|
||||||
|
return {
|
||||||
|
httpServers: config.httpServers.map((s) => {
|
||||||
|
const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', accessToken: s.accessToken ?? '' };
|
||||||
|
if (s.name) out.name = s.name;
|
||||||
|
return out;
|
||||||
|
}),
|
||||||
|
httpPostEndpoints: config.httpPostEndpoints.map((e) => {
|
||||||
|
const out: JsonObject = { url: e.url };
|
||||||
|
if (e.name) out.name = e.name;
|
||||||
|
if (e.accessToken) out.accessToken = e.accessToken;
|
||||||
|
if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs;
|
||||||
|
return out;
|
||||||
|
}),
|
||||||
|
wsServers: config.wsServers.map((s) => {
|
||||||
|
const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', role: s.role ?? 'universal', accessToken: s.accessToken ?? '' };
|
||||||
|
if (s.name) out.name = s.name;
|
||||||
|
return out;
|
||||||
|
}),
|
||||||
|
wsClients: config.wsClients.map((c) => {
|
||||||
|
const out: JsonObject = {
|
||||||
|
url: c.url,
|
||||||
|
role: c.role ?? 'universal',
|
||||||
|
accessToken: c.accessToken ?? '',
|
||||||
|
};
|
||||||
|
if (c.name) out.name = c.name;
|
||||||
|
if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) {
|
||||||
|
out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}),
|
||||||
|
musicSignUrl: config.musicSignUrl ?? '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function fromJson(json: JsonObject): OneBotConfig {
|
||||||
|
const httpServers = toHttpServers(json.httpServers);
|
||||||
|
const httpPostEndpoints = toHttpPostEndpoints(json.httpPostEndpoints);
|
||||||
|
const wsServers = toWsServers(json.wsServers);
|
||||||
|
const wsClients = toWsClients(json.wsClients);
|
||||||
|
|
||||||
|
return {
|
||||||
|
httpServers: httpServers.length > 0 ? httpServers : [{ host: '0.0.0.0', port: 3000, path: '/' }],
|
||||||
|
httpPostEndpoints,
|
||||||
|
wsServers: wsServers.length > 0 ? wsServers : [{ host: '0.0.0.0', port: 3001 }],
|
||||||
|
wsClients,
|
||||||
|
musicSignUrl: typeof json.musicSignUrl === 'string' ? json.musicSignUrl : '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toHttpServers(value: unknown): HttpServerEndpoint[] {
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
const result: HttpServerEndpoint[] = [];
|
||||||
|
|
||||||
|
for (const item of value) {
|
||||||
|
if (!isObject(item)) continue;
|
||||||
|
const host = asString(item.host, '0.0.0.0');
|
||||||
|
const port = asNumber(item.port, 3000);
|
||||||
|
const pathValue = asString(item.path, '/');
|
||||||
|
const endpoint: HttpServerEndpoint = { host, port, path: pathValue };
|
||||||
|
const name = asString(item.name);
|
||||||
|
if (name) endpoint.name = name;
|
||||||
|
const token = asString(item.accessToken);
|
||||||
|
if (token) endpoint.accessToken = token;
|
||||||
|
result.push(endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toHttpPostEndpoints(value: unknown): HttpPostEndpoint[] {
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
const result: HttpPostEndpoint[] = [];
|
||||||
|
|
||||||
|
for (const item of value) {
|
||||||
|
if (!isObject(item)) continue;
|
||||||
|
const url = asString(item.url);
|
||||||
|
if (!url) continue;
|
||||||
|
const endpoint: HttpPostEndpoint = { url };
|
||||||
|
const name = asString(item.name);
|
||||||
|
if (name) endpoint.name = name;
|
||||||
|
const token = asString(item.accessToken);
|
||||||
|
if (token) endpoint.accessToken = token;
|
||||||
|
const timeout = asNumber(item.timeoutMs, 0);
|
||||||
|
if (timeout > 0) endpoint.timeoutMs = timeout;
|
||||||
|
result.push(endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toWsServers(value: unknown): WsServerEndpoint[] {
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
const result: WsServerEndpoint[] = [];
|
||||||
|
|
||||||
|
for (const item of value) {
|
||||||
|
if (!isObject(item)) continue;
|
||||||
|
const host = asString(item.host, '0.0.0.0');
|
||||||
|
const port = asNumber(item.port, 3001);
|
||||||
|
const pathValue = asString(item.path, '/');
|
||||||
|
const role = asRole(item.role, 'universal');
|
||||||
|
const endpoint: WsServerEndpoint = { host, port, path: pathValue, role };
|
||||||
|
const name = asString(item.name);
|
||||||
|
if (name) endpoint.name = name;
|
||||||
|
const token = asString(item.accessToken);
|
||||||
|
if (token) endpoint.accessToken = token;
|
||||||
|
result.push(endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toWsClients(value: unknown): WsClientEndpoint[] {
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
const result: WsClientEndpoint[] = [];
|
||||||
|
|
||||||
|
for (const item of value) {
|
||||||
|
if (!isObject(item)) continue;
|
||||||
|
const url = asString(item.url);
|
||||||
|
if (!url) continue;
|
||||||
|
const role = asRole(item.role, 'universal');
|
||||||
|
const reconnectIntervalMs = asNumber(item.reconnectIntervalMs, 5000);
|
||||||
|
const endpoint: WsClientEndpoint = { url, role, reconnectIntervalMs };
|
||||||
|
const name = asString(item.name);
|
||||||
|
if (name) endpoint.name = name;
|
||||||
|
const token = asString(item.accessToken);
|
||||||
|
if (token) endpoint.accessToken = token;
|
||||||
|
result.push(endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asRole(value: unknown, fallback: WsRole): WsRole {
|
||||||
|
const text = asString(value, fallback);
|
||||||
|
return text === 'api' || text === 'event' || text === 'universal' ? text : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asString(value: unknown, fallback = ''): string {
|
||||||
|
if (typeof value === 'string') return value;
|
||||||
|
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asNumber(value: unknown, fallback = 0): number {
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
|
||||||
|
if (typeof value === 'string' && value.trim()) {
|
||||||
|
const n = Number(value);
|
||||||
|
if (Number.isFinite(n)) return Math.max(0, Math.trunc(n));
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateRandomKey(byteLength = 18): string {
|
||||||
|
return randomBytes(byteLength).toString('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryLoadJson(filePath: string): JsonObject | null {
|
||||||
|
if (!fs.existsSync(filePath)) return null;
|
||||||
|
try {
|
||||||
|
const raw = fs.readFileSync(filePath, 'utf8');
|
||||||
|
const parsed = JSON.parse(raw) as unknown;
|
||||||
|
return isObject(parsed) ? parsed : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveJson(filePath: string, json: JsonObject): void {
|
||||||
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||||
|
fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
function deepClone(obj: JsonObject): JsonObject {
|
||||||
|
return JSON.parse(JSON.stringify(obj)) as JsonObject;
|
||||||
|
}
|
||||||
|
|
||||||
|
function deepMerge(base: JsonObject, override: JsonObject): void {
|
||||||
|
for (const [key, value] of Object.entries(override)) {
|
||||||
|
if (isObject(base[key]) && isObject(value)) {
|
||||||
|
deepMerge(base[key] as JsonObject, value);
|
||||||
|
} else {
|
||||||
|
base[key] = value as never;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isObject(value: unknown): value is JsonObject {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
@@ -0,0 +1,513 @@
|
|||||||
|
import type { MessageElement, QQEventVariant } from '../bridge/events';
|
||||||
|
import type { JsonArray, JsonObject } from './types';
|
||||||
|
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from './message-id';
|
||||||
|
|
||||||
|
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
|
||||||
|
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
|
||||||
|
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
|
||||||
|
|
||||||
|
export class EventConverter {
|
||||||
|
private imageUrlResolver_: ImageUrlResolver | null = null;
|
||||||
|
private mediaUrlResolver_: MediaUrlResolver | null = null;
|
||||||
|
private messageIdResolver_: MessageIdResolver | null = null;
|
||||||
|
|
||||||
|
setImageUrlResolver(resolver: ImageUrlResolver): void {
|
||||||
|
this.imageUrlResolver_ = resolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
setMediaUrlResolver(resolver: MediaUrlResolver): void {
|
||||||
|
this.mediaUrlResolver_ = resolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
setMessageIdResolver(resolver: MessageIdResolver): void {
|
||||||
|
this.messageIdResolver_ = resolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
async convert(instanceUin: string, event: QQEventVariant): Promise<JsonObject | null> {
|
||||||
|
const selfId = parseSelfId(instanceUin);
|
||||||
|
|
||||||
|
switch (event.kind) {
|
||||||
|
case 'friend_message':
|
||||||
|
{
|
||||||
|
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
|
||||||
|
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'message',
|
||||||
|
message_type: 'private',
|
||||||
|
sub_type: 'friend',
|
||||||
|
message_id: messageId,
|
||||||
|
message_seq: event.msgSeq,
|
||||||
|
user_id: event.senderUin,
|
||||||
|
message: segments,
|
||||||
|
raw_message: segmentsToRawMessage(segments),
|
||||||
|
font: 0,
|
||||||
|
sender: {
|
||||||
|
user_id: event.senderUin,
|
||||||
|
nickname: event.senderNick,
|
||||||
|
sex: 'unknown',
|
||||||
|
age: 0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'group_message':
|
||||||
|
{
|
||||||
|
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
|
||||||
|
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'message',
|
||||||
|
message_type: 'group',
|
||||||
|
sub_type: 'normal',
|
||||||
|
message_id: messageId,
|
||||||
|
message_seq: event.msgSeq,
|
||||||
|
group_id: event.groupId,
|
||||||
|
user_id: event.senderUin,
|
||||||
|
message: segments,
|
||||||
|
raw_message: segmentsToRawMessage(segments),
|
||||||
|
font: 0,
|
||||||
|
sender: {
|
||||||
|
user_id: event.senderUin,
|
||||||
|
nickname: event.senderNick,
|
||||||
|
card: event.senderCard,
|
||||||
|
role: event.senderRole || 'member',
|
||||||
|
sex: 'unknown',
|
||||||
|
age: 0,
|
||||||
|
},
|
||||||
|
anonymous: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'temp_message':
|
||||||
|
{
|
||||||
|
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
|
||||||
|
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'message',
|
||||||
|
message_type: 'private',
|
||||||
|
sub_type: 'group',
|
||||||
|
message_id: messageId,
|
||||||
|
message_seq: event.msgSeq,
|
||||||
|
user_id: event.senderUin,
|
||||||
|
message: segments,
|
||||||
|
raw_message: segmentsToRawMessage(segments),
|
||||||
|
font: 0,
|
||||||
|
sender: {
|
||||||
|
user_id: event.senderUin,
|
||||||
|
nickname: event.senderNick,
|
||||||
|
sex: 'unknown',
|
||||||
|
age: 0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'group_member_join':
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'group_increase',
|
||||||
|
sub_type: event.operatorUin === event.userUin ? 'approve' : 'invite',
|
||||||
|
group_id: event.groupId,
|
||||||
|
operator_id: event.operatorUin,
|
||||||
|
user_id: event.userUin,
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'group_member_leave':
|
||||||
|
{
|
||||||
|
let subType: string;
|
||||||
|
if (event.isKick) {
|
||||||
|
subType = event.userUin === parseSelfId(instanceUin) ? 'kick_me' : 'kick';
|
||||||
|
} else {
|
||||||
|
subType = 'leave';
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'group_decrease',
|
||||||
|
sub_type: subType,
|
||||||
|
group_id: event.groupId,
|
||||||
|
operator_id: event.operatorUin,
|
||||||
|
user_id: event.userUin,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'group_mute':
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'group_ban',
|
||||||
|
sub_type: event.duration > 0 ? 'ban' : 'lift_ban',
|
||||||
|
group_id: event.groupId,
|
||||||
|
operator_id: event.operatorUin,
|
||||||
|
user_id: event.userUin,
|
||||||
|
duration: event.duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'group_admin':
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'group_admin',
|
||||||
|
sub_type: event.set ? 'set' : 'unset',
|
||||||
|
group_id: event.groupId,
|
||||||
|
user_id: event.userUin,
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'friend_recall':
|
||||||
|
{
|
||||||
|
const messageId = this.resolveMessageId(false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'friend_recall',
|
||||||
|
user_id: event.userUin,
|
||||||
|
message_id: messageId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'group_recall':
|
||||||
|
{
|
||||||
|
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'group_recall',
|
||||||
|
group_id: event.groupId,
|
||||||
|
operator_id: event.operatorUin,
|
||||||
|
user_id: event.authorUin,
|
||||||
|
message_id: messageId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'friend_request':
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'request',
|
||||||
|
request_type: 'friend',
|
||||||
|
user_id: event.fromUin,
|
||||||
|
comment: event.message,
|
||||||
|
flag: event.flag,
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'group_invite':
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'request',
|
||||||
|
request_type: 'group',
|
||||||
|
sub_type: event.subType || 'invite',
|
||||||
|
group_id: event.groupId,
|
||||||
|
user_id: event.fromUin,
|
||||||
|
comment: event.message,
|
||||||
|
flag: event.flag,
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'friend_poke':
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'notify',
|
||||||
|
sub_type: 'poke',
|
||||||
|
user_id: event.userUin,
|
||||||
|
target_id: event.targetUin,
|
||||||
|
action: event.action,
|
||||||
|
suffix: event.suffix,
|
||||||
|
action_img_url: event.actionImgUrl,
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'group_poke':
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'notify',
|
||||||
|
sub_type: 'poke',
|
||||||
|
group_id: event.groupId,
|
||||||
|
user_id: event.userUin,
|
||||||
|
target_id: event.targetUin,
|
||||||
|
action: event.action,
|
||||||
|
suffix: event.suffix,
|
||||||
|
action_img_url: event.actionImgUrl,
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'group_essence':
|
||||||
|
{
|
||||||
|
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'essence',
|
||||||
|
sub_type: event.set ? 'add' : 'delete',
|
||||||
|
group_id: event.groupId,
|
||||||
|
user_id: event.senderUin,
|
||||||
|
sender_id: event.senderUin,
|
||||||
|
operator_id: event.operatorUin,
|
||||||
|
message_id: messageId,
|
||||||
|
message_seq: event.msgSeq,
|
||||||
|
random: event.random,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'group_file_upload':
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'group_upload',
|
||||||
|
group_id: event.groupId,
|
||||||
|
user_id: event.userUin,
|
||||||
|
file: {
|
||||||
|
id: event.fileId,
|
||||||
|
name: event.fileName,
|
||||||
|
size: event.fileSize,
|
||||||
|
busid: event.busId,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'friend_add':
|
||||||
|
return {
|
||||||
|
time: event.time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'friend_add',
|
||||||
|
user_id: event.userUin,
|
||||||
|
};
|
||||||
|
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveMessageId(isGroup: boolean, sessionId: number, sequence: number, eventName: string): number {
|
||||||
|
if (this.messageIdResolver_) {
|
||||||
|
const resolved = this.messageIdResolver_(isGroup, sessionId, sequence, eventName);
|
||||||
|
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||||
|
}
|
||||||
|
const seq = Math.trunc(sequence);
|
||||||
|
return seq === 0 ? 0 : seq;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseSelfId(instanceUin: string): number {
|
||||||
|
const parsed = Number.parseInt(instanceUin, 10);
|
||||||
|
return Number.isNaN(parsed) ? 0 : parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function elementsToJson(
|
||||||
|
elements: MessageElement[],
|
||||||
|
isGroup: boolean,
|
||||||
|
sessionId: number,
|
||||||
|
resolver?: ImageUrlResolver | null,
|
||||||
|
mediaResolver?: MediaUrlResolver | null,
|
||||||
|
messageIdResolver?: MessageIdResolver | null,
|
||||||
|
): Promise<JsonArray> {
|
||||||
|
const result: JsonArray = [];
|
||||||
|
for (const element of elements) {
|
||||||
|
result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function elementsToOneBotSegments(
|
||||||
|
elements: MessageElement[],
|
||||||
|
isGroup: boolean,
|
||||||
|
sessionId: number,
|
||||||
|
resolver?: ImageUrlResolver | null,
|
||||||
|
mediaResolver?: MediaUrlResolver | null,
|
||||||
|
messageIdResolver?: MessageIdResolver | null,
|
||||||
|
): Promise<JsonArray> {
|
||||||
|
return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function elementToSegment(
|
||||||
|
element: MessageElement,
|
||||||
|
isGroup: boolean,
|
||||||
|
sessionId: number,
|
||||||
|
resolver?: ImageUrlResolver | null,
|
||||||
|
mediaResolver?: MediaUrlResolver | null,
|
||||||
|
messageIdResolver?: MessageIdResolver | null,
|
||||||
|
): Promise<JsonObject> {
|
||||||
|
if (element.type === 'text') {
|
||||||
|
return { type: 'text', data: { text: element.text ?? '' } };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'face') {
|
||||||
|
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'image') {
|
||||||
|
const url = resolver ? resolver(element, isGroup) : (element.imageUrl ?? '');
|
||||||
|
return {
|
||||||
|
type: 'image',
|
||||||
|
data: {
|
||||||
|
url,
|
||||||
|
file: element.fileId ?? '',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'at') {
|
||||||
|
const qq = (element.uid === 'all' || element.targetUin === 0)
|
||||||
|
? 'all'
|
||||||
|
: String(element.targetUin ?? 0);
|
||||||
|
return { type: 'at', data: { qq } };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'reply') {
|
||||||
|
const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver);
|
||||||
|
return { type: 'reply', data: { id: String(id) } };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'record') {
|
||||||
|
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||||
|
return {
|
||||||
|
type: 'record',
|
||||||
|
data: {
|
||||||
|
file: element.fileName ?? element.fileId ?? '',
|
||||||
|
url,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'video') {
|
||||||
|
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||||
|
return {
|
||||||
|
type: 'video',
|
||||||
|
data: {
|
||||||
|
file: element.fileName ?? element.fileId ?? '',
|
||||||
|
url,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'json') {
|
||||||
|
return { type: 'json', data: { data: element.text ?? '' } };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'xml') {
|
||||||
|
return {
|
||||||
|
type: 'xml',
|
||||||
|
data: {
|
||||||
|
data: element.text ?? '',
|
||||||
|
resid: element.subType ?? 35,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'file') {
|
||||||
|
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||||
|
return {
|
||||||
|
type: 'file',
|
||||||
|
data: {
|
||||||
|
name: element.fileName ?? '',
|
||||||
|
size: element.fileSize ?? 0,
|
||||||
|
id: element.fileId ?? '',
|
||||||
|
url,
|
||||||
|
file_hash: element.fileHash ?? '',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'mface') {
|
||||||
|
return {
|
||||||
|
type: 'mface',
|
||||||
|
data: {
|
||||||
|
name: element.text ?? '',
|
||||||
|
tab_id: element.faceId ?? 0,
|
||||||
|
sub_type: element.subType ?? 0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.type === 'poke') {
|
||||||
|
return {
|
||||||
|
type: 'poke',
|
||||||
|
data: {
|
||||||
|
type: element.subType ?? 0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isGroup && element.type === 'at') {
|
||||||
|
return { type: 'text', data: { text: element.text ?? '' } };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { type: element.type, data: {} };
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- CQ code raw_message generation (from already-resolved JSON segments) ---
|
||||||
|
|
||||||
|
function cqEscape(text: string): string {
|
||||||
|
return text.replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']').replace(/,/g, ',');
|
||||||
|
}
|
||||||
|
|
||||||
|
function segmentsToRawMessage(segments: JsonArray): string {
|
||||||
|
return segments.map(seg => segmentToCQ(seg as JsonObject)).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function segmentToCQ(seg: JsonObject): string {
|
||||||
|
const type = String(seg.type ?? '');
|
||||||
|
const data = (seg.data ?? {}) as Record<string, unknown>;
|
||||||
|
switch (type) {
|
||||||
|
case 'text':
|
||||||
|
return cqEscape(String(data.text ?? ''));
|
||||||
|
case 'face':
|
||||||
|
return `[CQ:face,id=${data.id ?? 0}]`;
|
||||||
|
case 'image':
|
||||||
|
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||||
|
case 'at':
|
||||||
|
return `[CQ:at,qq=${data.qq ?? ''}]`;
|
||||||
|
case 'reply':
|
||||||
|
return `[CQ:reply,id=${data.id ?? 0}]`;
|
||||||
|
case 'record':
|
||||||
|
return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||||
|
case 'video':
|
||||||
|
return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||||
|
case 'json':
|
||||||
|
return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`;
|
||||||
|
case 'xml':
|
||||||
|
return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`;
|
||||||
|
case 'forward':
|
||||||
|
return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`;
|
||||||
|
case 'mface':
|
||||||
|
return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`;
|
||||||
|
case 'poke':
|
||||||
|
return `[CQ:poke,type=${data.type ?? 0}]`;
|
||||||
|
case 'file':
|
||||||
|
return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||||
|
default:
|
||||||
|
return `[CQ:${type}]`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveReplyId(
|
||||||
|
isGroup: boolean,
|
||||||
|
sessionId: number,
|
||||||
|
sequence: number,
|
||||||
|
resolver?: MessageIdResolver | null,
|
||||||
|
): number {
|
||||||
|
const seq = Math.trunc(sequence);
|
||||||
|
if (seq === 0) return 0;
|
||||||
|
|
||||||
|
if (resolver) {
|
||||||
|
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||||
|
const resolved = resolver(isGroup, sessionId, seq, eventName);
|
||||||
|
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||||
|
}
|
||||||
|
|
||||||
|
return seq;
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import type { JsonObject, OneBotConfig } from './types';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
|
export interface HttpPostEndpoint {
|
||||||
|
name?: string;
|
||||||
|
url: string;
|
||||||
|
accessToken?: string;
|
||||||
|
timeoutMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HttpPostTransportContext {
|
||||||
|
uin: string;
|
||||||
|
api: import('./api-handler').ApiHandler;
|
||||||
|
}
|
||||||
|
|
||||||
|
const log = createLogger('OneBot.POST');
|
||||||
|
const DEFAULT_TIMEOUT_MS = 5000;
|
||||||
|
|
||||||
|
export class HttpPostTransport {
|
||||||
|
private readonly config: OneBotConfig;
|
||||||
|
private readonly context: HttpPostTransportContext;
|
||||||
|
private stopped = false;
|
||||||
|
|
||||||
|
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
|
||||||
|
this.config = config;
|
||||||
|
this.context = context;
|
||||||
|
}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
this.stopped = false;
|
||||||
|
const count = this.config.httpPostEndpoints?.length ?? 0;
|
||||||
|
if (count > 0) {
|
||||||
|
log.info('configured %d HTTP POST endpoint(s)', count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
this.stopped = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
publishEvent(event: JsonObject): void {
|
||||||
|
const endpoints = this.config.httpPostEndpoints;
|
||||||
|
if (!endpoints || endpoints.length === 0) return;
|
||||||
|
|
||||||
|
const payload = JSON.stringify(event);
|
||||||
|
for (const endpoint of endpoints) {
|
||||||
|
void this.postEvent(endpoint, payload, event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async postEvent(endpoint: HttpPostEndpoint, payload: string, event: JsonObject): Promise<void> {
|
||||||
|
if (this.stopped) return;
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'User-Agent': 'OneBot',
|
||||||
|
'X-Self-ID': this.context.uin,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (endpoint.accessToken) {
|
||||||
|
headers['X-Signature'] = await computeHmacSha1(endpoint.accessToken, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeoutMs = endpoint.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(endpoint.url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body: payload,
|
||||||
|
signal: AbortSignal.timeout(timeoutMs),
|
||||||
|
});
|
||||||
|
|
||||||
|
// OneBot v11: if the response has a JSON body, it's a quick operation
|
||||||
|
if (response.ok) {
|
||||||
|
const contentType = response.headers.get('content-type') ?? '';
|
||||||
|
if (contentType.includes('application/json')) {
|
||||||
|
const body = await response.text();
|
||||||
|
if (body.trim()) {
|
||||||
|
await this.handleQuickOperation(event, body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.warn('POST %s returned %d', endpoint.url, response.status);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (!this.stopped) {
|
||||||
|
log.warn('POST %s failed: %s', endpoint.url, error instanceof Error ? error.message : String(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
const operation = JSON.parse(responseBody) as Record<string, unknown>;
|
||||||
|
if (!operation || typeof operation !== 'object') return;
|
||||||
|
|
||||||
|
await executeQuickOperation(event, operation, this.context.api);
|
||||||
|
} catch (error) {
|
||||||
|
log.warn('quick operation failed: %s', error instanceof Error ? error.message : String(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
|
||||||
|
const { createHmac } = await import('crypto');
|
||||||
|
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a quick operation based on the event type and the response body.
|
||||||
|
* This implements the .handle_quick_operation hidden API behavior.
|
||||||
|
* See: https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md
|
||||||
|
*/
|
||||||
|
export async function executeQuickOperation(
|
||||||
|
event: JsonObject,
|
||||||
|
operation: Record<string, unknown>,
|
||||||
|
api: import('./api-handler').ApiHandler,
|
||||||
|
): Promise<void> {
|
||||||
|
const postType = event.post_type as string;
|
||||||
|
|
||||||
|
if (postType === 'message') {
|
||||||
|
// Quick reply
|
||||||
|
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
|
||||||
|
const messageType = event.message_type as string;
|
||||||
|
const autoEscape = !!operation.auto_escape;
|
||||||
|
|
||||||
|
if (messageType === 'group') {
|
||||||
|
const params: JsonObject = {
|
||||||
|
group_id: event.group_id as number,
|
||||||
|
message: operation.reply as import('./types').JsonValue,
|
||||||
|
auto_escape: autoEscape,
|
||||||
|
};
|
||||||
|
// at_sender defaults to true for group messages
|
||||||
|
if (operation.at_sender !== false && event.user_id) {
|
||||||
|
// Prepend an @ segment
|
||||||
|
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
|
||||||
|
if (typeof operation.reply === 'string') {
|
||||||
|
params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as import('./types').JsonValue;
|
||||||
|
params.auto_escape = false;
|
||||||
|
} else if (Array.isArray(operation.reply)) {
|
||||||
|
params.message = [atSegment, ...(operation.reply as unknown[])] as import('./types').JsonValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await api.handle('send_group_msg', params);
|
||||||
|
} else if (messageType === 'private') {
|
||||||
|
await api.handle('send_private_msg', {
|
||||||
|
user_id: event.user_id as number,
|
||||||
|
message: operation.reply as import('./types').JsonValue,
|
||||||
|
auto_escape: autoEscape,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quick delete
|
||||||
|
if (operation.delete) {
|
||||||
|
await api.handle('delete_msg', { message_id: event.message_id as number });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quick ban (group only)
|
||||||
|
if (operation.ban && event.message_type === 'group') {
|
||||||
|
const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
|
||||||
|
await api.handle('set_group_ban', {
|
||||||
|
group_id: event.group_id as number,
|
||||||
|
user_id: event.user_id as number,
|
||||||
|
duration: duration as import('./types').JsonValue,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quick kick (group only)
|
||||||
|
if (operation.kick && event.message_type === 'group') {
|
||||||
|
await api.handle('set_group_kick', {
|
||||||
|
group_id: event.group_id as number,
|
||||||
|
user_id: event.user_id as number,
|
||||||
|
reject_add_request: !!operation.reject_add_request as unknown as import('./types').JsonValue,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (postType === 'request') {
|
||||||
|
if (operation.approve !== undefined) {
|
||||||
|
const requestType = event.request_type as string;
|
||||||
|
if (requestType === 'friend') {
|
||||||
|
await api.handle('set_friend_add_request', {
|
||||||
|
flag: event.flag as string,
|
||||||
|
approve: operation.approve as import('./types').JsonValue,
|
||||||
|
remark: (operation.remark ?? '') as import('./types').JsonValue,
|
||||||
|
});
|
||||||
|
} else if (requestType === 'group') {
|
||||||
|
await api.handle('set_group_add_request', {
|
||||||
|
flag: event.flag as string,
|
||||||
|
sub_type: event.sub_type as string,
|
||||||
|
approve: operation.approve as import('./types').JsonValue,
|
||||||
|
reason: (operation.reason ?? '') as import('./types').JsonValue,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
import {
|
||||||
|
createServer,
|
||||||
|
type IncomingHttpHeaders,
|
||||||
|
type IncomingMessage,
|
||||||
|
type Server,
|
||||||
|
type ServerResponse,
|
||||||
|
} from 'http';
|
||||||
|
import type { ApiHandler } from './api-handler';
|
||||||
|
import type { OneBotConfig } from './types';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
|
export interface HttpTransportContext {
|
||||||
|
api: ApiHandler;
|
||||||
|
}
|
||||||
|
|
||||||
|
const log = createLogger('OneBot.HTTP');
|
||||||
|
|
||||||
|
export class HttpTransport {
|
||||||
|
private readonly config: OneBotConfig;
|
||||||
|
private readonly context: HttpTransportContext;
|
||||||
|
private readonly servers: Server[] = [];
|
||||||
|
|
||||||
|
constructor(config: OneBotConfig, context: HttpTransportContext) {
|
||||||
|
this.config = config;
|
||||||
|
this.context = context;
|
||||||
|
}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
for (const endpoint of this.config.httpServers) {
|
||||||
|
const expectedPath = normalizePath(endpoint.path ?? '/');
|
||||||
|
const endpointToken = endpoint.accessToken ?? '';
|
||||||
|
const server = createServer((req, res) => {
|
||||||
|
void this.handleRequest(expectedPath, endpointToken, req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
server.on('listening', () => {
|
||||||
|
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
||||||
|
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath);
|
||||||
|
});
|
||||||
|
|
||||||
|
server.on('error', (error) => {
|
||||||
|
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||||
|
});
|
||||||
|
|
||||||
|
server.listen(endpoint.port, endpoint.host);
|
||||||
|
this.servers.push(server);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
for (const server of this.servers) {
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
this.servers.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||||
|
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
|
||||||
|
const incomingPath = parsedUrl.pathname;
|
||||||
|
|
||||||
|
// Determine the expected prefix (e.g., "/" or "/api/")
|
||||||
|
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
|
||||||
|
let action = '';
|
||||||
|
|
||||||
|
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
|
||||||
|
action = ''; // No action in URL (legacy body mode)
|
||||||
|
} else if (incomingPath.startsWith(ep)) {
|
||||||
|
action = incomingPath.substring(ep.length); // Extract action from URL
|
||||||
|
} else {
|
||||||
|
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAuthorized(req, accessToken)) {
|
||||||
|
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.method === 'GET' && !action) {
|
||||||
|
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
let params: Record<string, unknown> = {};
|
||||||
|
let echo: unknown;
|
||||||
|
|
||||||
|
if (req.method === 'GET') {
|
||||||
|
parsedUrl.searchParams.forEach((value, key) => {
|
||||||
|
try {
|
||||||
|
params[key] = JSON.parse(value);
|
||||||
|
} catch {
|
||||||
|
params[key] = value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (req.method === 'POST') {
|
||||||
|
const bodyContent = await readRequestBody(req);
|
||||||
|
if (bodyContent.trim()) {
|
||||||
|
try {
|
||||||
|
const parsedBody = JSON.parse(bodyContent);
|
||||||
|
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
|
||||||
|
// Legacy format: { action: "...", params: {...} } vs standard raw params
|
||||||
|
if (parsedBody.action && !action) {
|
||||||
|
action = String(parsedBody.action);
|
||||||
|
}
|
||||||
|
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
|
||||||
|
params = parsedBody.params as Record<string, unknown>;
|
||||||
|
} else {
|
||||||
|
params = parsedBody as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
echo = parsedBody.echo;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!action) {
|
||||||
|
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle the API call
|
||||||
|
const response = await this.context.api.handle(action, params as import('./types').JsonObject);
|
||||||
|
|
||||||
|
if (echo !== undefined) {
|
||||||
|
response.echo = echo as import('./types').JsonValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJson(res, 200, response);
|
||||||
|
} catch (error) {
|
||||||
|
const wording = error instanceof Error ? error.message : 'internal error';
|
||||||
|
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRequestPath(urlValue: string): string {
|
||||||
|
try {
|
||||||
|
return new URL(urlValue, 'http://127.0.0.1').pathname;
|
||||||
|
} catch {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePath(pathValue: string): string {
|
||||||
|
const path = pathValue.trim() || '/';
|
||||||
|
if (path === '/') return '/';
|
||||||
|
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||||
|
if (!token) return true;
|
||||||
|
// 1. Header auth
|
||||||
|
const rawAuth = request.headers.authorization;
|
||||||
|
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
|
||||||
|
if (auth === `Bearer ${token}`) return true;
|
||||||
|
|
||||||
|
// 2. Query string auth
|
||||||
|
try {
|
||||||
|
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
|
||||||
|
if (url.searchParams.get('access_token') === token) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
let total = 0;
|
||||||
|
|
||||||
|
req.on('data', (chunk: Buffer) => {
|
||||||
|
total += chunk.length;
|
||||||
|
if (total > maxBytes) {
|
||||||
|
reject(new Error('request body too large'));
|
||||||
|
req.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
chunks.push(chunk);
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on('end', () => {
|
||||||
|
resolve(Buffer.concat(chunks).toString('utf8'));
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
|
||||||
|
res.statusCode = statusCode;
|
||||||
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||||
|
res.end(JSON.stringify(data));
|
||||||
|
}
|
||||||
@@ -0,0 +1,614 @@
|
|||||||
|
import type { Bridge } from '../bridge/bridge';
|
||||||
|
import type { ForwardNodePayload } from '../bridge/events';
|
||||||
|
import type { QQInfo } from '../bridge/qq-info';
|
||||||
|
import type { ApiActionContext, MessageSendResult } from './api-handler';
|
||||||
|
import { elementsToOneBotSegments } from './event-converter';
|
||||||
|
import { MessageStore } from './message-store';
|
||||||
|
import { parseMessage } from './message-parser';
|
||||||
|
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||||
|
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||||
|
|
||||||
|
export interface InstanceRef {
|
||||||
|
uin: string;
|
||||||
|
qqInfo: QQInfo;
|
||||||
|
bridge: Bridge;
|
||||||
|
messageStore: MessageStore;
|
||||||
|
musicSignUrl?: string;
|
||||||
|
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildApiContext(ref: InstanceRef): ApiActionContext {
|
||||||
|
const { bridge, qqInfo, messageStore } = ref;
|
||||||
|
|
||||||
|
return {
|
||||||
|
getLoginInfo: () => getLoginInfo(ref),
|
||||||
|
isOnline: () => true,
|
||||||
|
getMessage: (messageId) => messageStore.findEvent(messageId),
|
||||||
|
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||||
|
canSendImage: () => true,
|
||||||
|
canSendRecord: () => false,
|
||||||
|
sendPrivateMessage: (userId, message, autoEscape) => handleSendPrivate(ref, userId, message, autoEscape),
|
||||||
|
sendGroupMessage: (groupId, message, autoEscape) => handleSendGroup(ref, groupId, message, autoEscape),
|
||||||
|
deleteMessage: (messageId, meta) => handleDeleteMessage(bridge, meta),
|
||||||
|
// Info retrieval (async, triggers OIDB fetch)
|
||||||
|
getFriendList: () => handleGetFriendList(bridge, qqInfo),
|
||||||
|
getGroupList: (noCache) => handleGetGroupList(bridge, qqInfo, noCache),
|
||||||
|
getGroupInfo: (groupId, noCache) => handleGetGroupInfo(bridge, qqInfo, groupId, noCache),
|
||||||
|
getGroupMemberList: (groupId, noCache) => handleGetGroupMemberList(bridge, qqInfo, groupId, noCache),
|
||||||
|
getGroupMemberInfo: (groupId, userId, noCache) => handleGetGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache),
|
||||||
|
getStrangerInfo: (userId) => handleGetStrangerInfo(bridge, qqInfo, userId),
|
||||||
|
// Group admin
|
||||||
|
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
|
||||||
|
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
|
||||||
|
setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable),
|
||||||
|
setGroupAdmin: (groupId, userId, enable) => bridge.setGroupAdmin(groupId, userId, enable),
|
||||||
|
setGroupCard: (groupId, userId, card) => bridge.setGroupCard(groupId, userId, card),
|
||||||
|
setGroupName: (groupId, name) => bridge.setGroupName(groupId, name),
|
||||||
|
setGroupLeave: (groupId) => bridge.leaveGroup(groupId),
|
||||||
|
setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title),
|
||||||
|
// Group file
|
||||||
|
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
|
||||||
|
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
|
||||||
|
return result.fileId;
|
||||||
|
},
|
||||||
|
uploadPrivateFile: async (userId, file, name, uploadFile) => {
|
||||||
|
const result = await bridge.uploadPrivateFile(userId, file, name ?? '', uploadFile ?? true);
|
||||||
|
return result.fileId;
|
||||||
|
},
|
||||||
|
getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102),
|
||||||
|
getGroupFiles: (groupId, folderId) => handleGetGroupFiles(bridge, groupId, folderId),
|
||||||
|
deleteGroupFile: (groupId, fileId) => bridge.deleteGroupFile(groupId, fileId),
|
||||||
|
moveGroupFile: (groupId, fileId, parentDirectory, targetDirectory) => bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory),
|
||||||
|
createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'),
|
||||||
|
deleteGroupFileFolder: (groupId, folderId) => bridge.deleteGroupFileFolder(groupId, folderId),
|
||||||
|
renameGroupFileFolder: (groupId, folderId, newName) => bridge.renameGroupFileFolder(groupId, folderId, newName),
|
||||||
|
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash),
|
||||||
|
// Requests
|
||||||
|
handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve),
|
||||||
|
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
|
||||||
|
// Extended
|
||||||
|
sendLike: (userId, times) => bridge.sendLike(userId, times),
|
||||||
|
sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId),
|
||||||
|
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
|
||||||
|
setEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, true),
|
||||||
|
deleteEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, false),
|
||||||
|
// New extended
|
||||||
|
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet),
|
||||||
|
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
|
||||||
|
getGroupMsgHistory: (groupId, messageId, count) => handleGetGroupMsgHistory(messageStore, groupId, messageId, count),
|
||||||
|
getFriendMsgHistory: (userId, messageId, count) => handleGetFriendMsgHistory(messageStore, userId, messageId, count),
|
||||||
|
handleGetGroupSystemMsg: async () => {
|
||||||
|
try {
|
||||||
|
const reqs = await bridge.fetchGroupRequests();
|
||||||
|
return reqs.map(r => ({
|
||||||
|
group_id: r.groupId, group_name: r.groupName,
|
||||||
|
request_id: r.sequence, requester_uin: r.targetUin,
|
||||||
|
requester_nick: r.targetName, message: r.comment,
|
||||||
|
flag: `${r.eventType}:${r.groupId}:${r.targetUid}`,
|
||||||
|
} as JsonObject));
|
||||||
|
} catch { return []; }
|
||||||
|
},
|
||||||
|
getDownloadRKeys: async () => {
|
||||||
|
try {
|
||||||
|
const rkeys = await bridge.fetchDownloadRKeys();
|
||||||
|
return rkeys.map(r => ({
|
||||||
|
rkey: r.rkey, type: r.type, ttl: r.ttlSeconds, create_time: r.createTime,
|
||||||
|
} as JsonObject));
|
||||||
|
} catch { return []; }
|
||||||
|
},
|
||||||
|
sendGroupForwardMsg: async (groupId, messages) => {
|
||||||
|
return handleSendGroupForward(ref, groupId, messages);
|
||||||
|
},
|
||||||
|
sendPrivateForwardMsg: async (userId, messages) => {
|
||||||
|
return handleSendPrivateForward(ref, userId, messages);
|
||||||
|
},
|
||||||
|
sendForwardMsg: async (messages) => {
|
||||||
|
return handleUploadForward(ref, messages);
|
||||||
|
},
|
||||||
|
getForwardMsg: async (resId) => {
|
||||||
|
return handleGetForward(ref, resId);
|
||||||
|
},
|
||||||
|
// Extended NapCat-compatible
|
||||||
|
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
|
||||||
|
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
|
||||||
|
setMsgEmojiLike: async (messageId, emojiId, set) => {
|
||||||
|
const meta = messageStore.findMeta(messageId);
|
||||||
|
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
|
||||||
|
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Login info ---
|
||||||
|
|
||||||
|
function getLoginInfo(ref: InstanceRef): { userId: number; nickname: string } {
|
||||||
|
const userId = parseInt(ref.uin, 10) || 0;
|
||||||
|
const nickname = ref.qqInfo.nickname || ref.uin;
|
||||||
|
return { userId, nickname };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshAllGroupMembersCache(bridge: Bridge, qqInfo: QQInfo): Promise<void> {
|
||||||
|
let groups = qqInfo.groups;
|
||||||
|
try {
|
||||||
|
groups = await bridge.fetchGroupList();
|
||||||
|
} catch { /* use cached groups */ }
|
||||||
|
|
||||||
|
for (const g of groups) {
|
||||||
|
try {
|
||||||
|
await bridge.fetchGroupMemberList(g.groupId);
|
||||||
|
} catch { /* best effort */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeHistoryCount(count?: number): number {
|
||||||
|
if (!Number.isFinite(count)) return 20;
|
||||||
|
const n = Math.trunc(count as number);
|
||||||
|
if (n <= 0) return 20;
|
||||||
|
if (n > 200) return 200;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeMessageEventForApi(event: JsonObject): JsonObject {
|
||||||
|
const result: JsonObject = { ...event };
|
||||||
|
delete result.post_type;
|
||||||
|
delete result.self_id;
|
||||||
|
result.real_id = (result.message_id ?? 0) as JsonValue;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Info retrieval ---
|
||||||
|
|
||||||
|
async function handleGetFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<JsonObject[]> {
|
||||||
|
try {
|
||||||
|
const friends = await bridge.fetchFriendList();
|
||||||
|
return friends.map(f => ({
|
||||||
|
user_id: f.uin as any,
|
||||||
|
nickname: f.nickname as any,
|
||||||
|
remark: f.remark as any,
|
||||||
|
}));
|
||||||
|
} catch {
|
||||||
|
return qqInfo.friends.map(f => ({
|
||||||
|
user_id: f.uin as any,
|
||||||
|
nickname: f.nickname as any,
|
||||||
|
remark: f.remark as any,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGetGroupList(bridge: Bridge, qqInfo: QQInfo, noCache?: boolean): Promise<JsonObject[]> {
|
||||||
|
try {
|
||||||
|
if (noCache) {
|
||||||
|
await refreshAllGroupMembersCache(bridge, qqInfo);
|
||||||
|
} else if (qqInfo.groups.length === 0) {
|
||||||
|
await bridge.fetchGroupList();
|
||||||
|
}
|
||||||
|
} catch { /* use cached */ }
|
||||||
|
return qqInfo.groups.map(g => ({
|
||||||
|
group_id: g.groupId as any,
|
||||||
|
group_name: g.groupName as any,
|
||||||
|
member_count: g.memberCount as any,
|
||||||
|
max_member_count: g.memberMax as any,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGetGroupInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise<JsonObject | null> {
|
||||||
|
if (noCache) {
|
||||||
|
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
|
||||||
|
} else if (!qqInfo.findGroup(groupId)) {
|
||||||
|
try { await bridge.fetchGroupList(); } catch { /* use cached */ }
|
||||||
|
}
|
||||||
|
const g = qqInfo.findGroup(groupId);
|
||||||
|
if (!g) return null;
|
||||||
|
return {
|
||||||
|
group_id: g.groupId as any,
|
||||||
|
group_name: g.groupName as any,
|
||||||
|
member_count: g.memberCount as any,
|
||||||
|
max_member_count: g.memberMax as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGetGroupMemberList(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise<JsonObject[]> {
|
||||||
|
if (noCache) {
|
||||||
|
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
|
||||||
|
|
||||||
|
const g = qqInfo.findGroup(groupId);
|
||||||
|
if (!g) return [];
|
||||||
|
const result: JsonObject[] = [];
|
||||||
|
for (const [, m] of g.members) {
|
||||||
|
result.push({
|
||||||
|
group_id: groupId as any, user_id: m.uin as any,
|
||||||
|
nickname: m.nickname as any, card: m.card as any,
|
||||||
|
sex: 'unknown' as any, age: 0 as any,
|
||||||
|
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
|
||||||
|
level: String(m.level) as any, role: m.role as any, title: m.title as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const members = await bridge.fetchGroupMemberList(groupId);
|
||||||
|
return members.map(m => ({
|
||||||
|
group_id: groupId as any,
|
||||||
|
user_id: m.uin as any,
|
||||||
|
nickname: m.nickname as any,
|
||||||
|
card: m.card as any,
|
||||||
|
sex: 'unknown' as any,
|
||||||
|
age: 0 as any,
|
||||||
|
join_time: m.joinTime as any,
|
||||||
|
last_sent_time: m.lastSentTime as any,
|
||||||
|
level: String(m.level) as any,
|
||||||
|
role: m.role as any,
|
||||||
|
title: m.title as any,
|
||||||
|
}));
|
||||||
|
} catch {
|
||||||
|
const g = qqInfo.findGroup(groupId);
|
||||||
|
if (!g) return [];
|
||||||
|
const result: JsonObject[] = [];
|
||||||
|
for (const [, m] of g.members) {
|
||||||
|
result.push({
|
||||||
|
group_id: groupId as any, user_id: m.uin as any,
|
||||||
|
nickname: m.nickname as any, card: m.card as any,
|
||||||
|
sex: 'unknown' as any, age: 0 as any,
|
||||||
|
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
|
||||||
|
level: String(m.level) as any, role: m.role as any, title: m.title as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGetGroupMemberInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, userId: number, noCache?: boolean): Promise<JsonObject | null> {
|
||||||
|
if (noCache) {
|
||||||
|
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
|
||||||
|
} else if (!qqInfo.findGroupMember(groupId, userId)) {
|
||||||
|
try { await bridge.fetchGroupMemberList(groupId); } catch { /* use cached */ }
|
||||||
|
}
|
||||||
|
const m = qqInfo.findGroupMember(groupId, userId);
|
||||||
|
if (!m) return null;
|
||||||
|
return {
|
||||||
|
group_id: groupId as any, user_id: m.uin as any,
|
||||||
|
nickname: m.nickname as any, card: m.card as any,
|
||||||
|
sex: 'unknown' as any, age: 0 as any,
|
||||||
|
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
|
||||||
|
level: String(m.level) as any, role: m.role as any, title: m.title as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGetGroupFiles(bridge: Bridge, groupId: number, folderId?: string): Promise<JsonObject> {
|
||||||
|
const result = await bridge.fetchGroupFiles(groupId, folderId ?? '/');
|
||||||
|
return {
|
||||||
|
files: result.files.map((file) => ({
|
||||||
|
group_id: groupId as any,
|
||||||
|
file_id: file.fileId as any,
|
||||||
|
file_name: file.fileName as any,
|
||||||
|
busid: file.busId as any,
|
||||||
|
file_size: file.fileSize as any,
|
||||||
|
upload_time: file.uploadTime as any,
|
||||||
|
dead_time: file.deadTime as any,
|
||||||
|
modify_time: file.modifyTime as any,
|
||||||
|
download_times: file.downloadTimes as any,
|
||||||
|
uploader: file.uploader as any,
|
||||||
|
uploader_name: file.uploaderName as any,
|
||||||
|
} as JsonObject)) as any,
|
||||||
|
folders: result.folders.map((folder) => ({
|
||||||
|
group_id: groupId as any,
|
||||||
|
folder_id: folder.folderId as any,
|
||||||
|
folder_name: folder.folderName as any,
|
||||||
|
create_time: folder.createTime as any,
|
||||||
|
creator: folder.creator as any,
|
||||||
|
create_name: folder.creatorName as any,
|
||||||
|
total_file_count: folder.totalFileCount as any,
|
||||||
|
} as JsonObject)) as any,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGetStrangerInfo(bridge: Bridge, qqInfo: QQInfo, userId: number): Promise<JsonObject | null> {
|
||||||
|
try {
|
||||||
|
const p = await bridge.fetchUserProfile(userId);
|
||||||
|
return {
|
||||||
|
user_id: p.uin as any,
|
||||||
|
nickname: p.nickname as any,
|
||||||
|
sex: p.sex as any,
|
||||||
|
age: p.age as any,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
const p = qqInfo.findUserProfile(userId);
|
||||||
|
if (!p) return null;
|
||||||
|
return { user_id: p.uin as any, nickname: p.nickname as any, sex: p.sex as any, age: p.age as any };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Message history ---
|
||||||
|
|
||||||
|
async function handleGetGroupMsgHistory(
|
||||||
|
messageStore: MessageStore,
|
||||||
|
groupId: number,
|
||||||
|
messageId?: number,
|
||||||
|
count?: number,
|
||||||
|
): Promise<JsonObject[]> {
|
||||||
|
if (!Number.isInteger(groupId) || groupId <= 0) return [];
|
||||||
|
const limit = normalizeHistoryCount(count);
|
||||||
|
|
||||||
|
let anchorSequence: number | undefined;
|
||||||
|
if (Number.isInteger(messageId) && messageId !== 0) {
|
||||||
|
const meta = messageStore.findMeta(messageId as number);
|
||||||
|
if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) return [];
|
||||||
|
anchorSequence = meta.sequence;
|
||||||
|
}
|
||||||
|
|
||||||
|
const events = messageStore.listSessionEvents(true, groupId, limit, anchorSequence);
|
||||||
|
return events
|
||||||
|
.filter((event) => {
|
||||||
|
if (event.message_type !== 'group') return false;
|
||||||
|
const gid = Number(event.group_id ?? 0);
|
||||||
|
return Number.isFinite(gid) && Math.trunc(gid) === groupId;
|
||||||
|
})
|
||||||
|
.map(sanitizeMessageEventForApi);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGetFriendMsgHistory(
|
||||||
|
messageStore: MessageStore,
|
||||||
|
userId: number,
|
||||||
|
messageId?: number,
|
||||||
|
count?: number,
|
||||||
|
): Promise<JsonObject[]> {
|
||||||
|
if (!Number.isInteger(userId) || userId <= 0) return [];
|
||||||
|
const limit = normalizeHistoryCount(count);
|
||||||
|
|
||||||
|
let anchorSequence: number | undefined;
|
||||||
|
if (Number.isInteger(messageId) && messageId !== 0) {
|
||||||
|
const meta = messageStore.findMeta(messageId as number);
|
||||||
|
if (!meta || meta.isGroup || meta.targetId !== userId || meta.sequence <= 0) return [];
|
||||||
|
anchorSequence = meta.sequence;
|
||||||
|
}
|
||||||
|
|
||||||
|
const events = messageStore.listSessionEvents(false, userId, limit, anchorSequence);
|
||||||
|
return events
|
||||||
|
.filter((event) => {
|
||||||
|
if (event.message_type !== 'private') return false;
|
||||||
|
const uid = Number(event.user_id ?? 0);
|
||||||
|
return Number.isFinite(uid) && Math.trunc(uid) === userId;
|
||||||
|
})
|
||||||
|
.map(sanitizeMessageEventForApi);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Delete message ---
|
||||||
|
|
||||||
|
async function handleDeleteMessage(bridge: Bridge, meta: MessageMeta): Promise<void> {
|
||||||
|
if (meta.isGroup) {
|
||||||
|
await bridge.recallGroupMessage(meta.targetId, meta.sequence);
|
||||||
|
} else {
|
||||||
|
await bridge.recallPrivateMessage(
|
||||||
|
meta.targetId, meta.clientSequence, meta.sequence, meta.random, meta.timestamp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Group request ---
|
||||||
|
|
||||||
|
async function handleGroupAddRequest(bridge: Bridge, flag: string, approve: boolean, reason: string): Promise<void> {
|
||||||
|
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
|
||||||
|
const parts = flag.split(':');
|
||||||
|
if (parts.length < 3) throw new Error('invalid group request flag');
|
||||||
|
const groupId = parseInt(parts[1], 10);
|
||||||
|
if (!groupId) throw new Error('invalid group_id in flag');
|
||||||
|
// We need sequence and eventType -- fetch from group requests
|
||||||
|
const requests = await bridge.fetchGroupRequests();
|
||||||
|
const matching = requests.find(r => r.groupId === groupId);
|
||||||
|
if (matching) {
|
||||||
|
await bridge.setGroupAddRequest(groupId, matching.sequence, matching.eventType, approve, reason, matching.filtered);
|
||||||
|
} else {
|
||||||
|
throw new Error('matching group request not found');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Essence ---
|
||||||
|
|
||||||
|
async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, messageId: number, enable: boolean): Promise<void> {
|
||||||
|
const meta = messageStore.findMeta(messageId);
|
||||||
|
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
|
||||||
|
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Send message ---
|
||||||
|
|
||||||
|
async function handleSendPrivate(
|
||||||
|
ref: InstanceRef,
|
||||||
|
userId: number,
|
||||||
|
message: JsonValue,
|
||||||
|
autoEscape: boolean,
|
||||||
|
): Promise<MessageSendResult> {
|
||||||
|
const elements = await parseMessage(message, autoEscape, {
|
||||||
|
resolveReplySequence: (replyMessageId) =>
|
||||||
|
ref.messageStore.resolveReplySequence(false, userId, replyMessageId),
|
||||||
|
musicSignUrl: ref.musicSignUrl,
|
||||||
|
});
|
||||||
|
if (elements.length === 0) throw new Error('message is empty');
|
||||||
|
|
||||||
|
const receipt = await ref.bridge.sendPrivateMessage(userId, elements);
|
||||||
|
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||||
|
|
||||||
|
// Cache the sent message meta
|
||||||
|
ref.cacheMessageMeta(messageId, {
|
||||||
|
isGroup: false,
|
||||||
|
targetId: userId,
|
||||||
|
sequence: receipt.sequence,
|
||||||
|
eventName: PRIVATE_MESSAGE_EVENT,
|
||||||
|
clientSequence: receipt.clientSequence,
|
||||||
|
random: receipt.random,
|
||||||
|
timestamp: receipt.timestamp,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { messageId };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSendGroup(
|
||||||
|
ref: InstanceRef,
|
||||||
|
groupId: number,
|
||||||
|
message: JsonValue,
|
||||||
|
autoEscape: boolean,
|
||||||
|
): Promise<MessageSendResult> {
|
||||||
|
const elements = await parseMessage(message, autoEscape, {
|
||||||
|
resolveReplySequence: (replyMessageId) =>
|
||||||
|
ref.messageStore.resolveReplySequence(true, groupId, replyMessageId),
|
||||||
|
musicSignUrl: ref.musicSignUrl,
|
||||||
|
});
|
||||||
|
if (elements.length === 0) throw new Error('message is empty');
|
||||||
|
|
||||||
|
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
|
||||||
|
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||||
|
|
||||||
|
// Cache the sent message meta
|
||||||
|
ref.cacheMessageMeta(messageId, {
|
||||||
|
isGroup: true,
|
||||||
|
targetId: groupId,
|
||||||
|
sequence: receipt.sequence,
|
||||||
|
eventName: GROUP_MESSAGE_EVENT,
|
||||||
|
clientSequence: receipt.clientSequence,
|
||||||
|
random: receipt.random,
|
||||||
|
timestamp: receipt.timestamp,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { messageId };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSendGroupForward(
|
||||||
|
ref: InstanceRef,
|
||||||
|
groupId: number,
|
||||||
|
messages: JsonValue,
|
||||||
|
): Promise<{ messageId: number; forwardId: string }> {
|
||||||
|
const nodes = await parseForwardNodes(ref, messages);
|
||||||
|
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
|
||||||
|
const receipt = await ref.bridge.sendGroupMessage(groupId, [{ type: 'forward', resId: forwardId }]);
|
||||||
|
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||||
|
|
||||||
|
ref.cacheMessageMeta(messageId, {
|
||||||
|
isGroup: true,
|
||||||
|
targetId: groupId,
|
||||||
|
sequence: receipt.sequence,
|
||||||
|
eventName: GROUP_MESSAGE_EVENT,
|
||||||
|
clientSequence: receipt.clientSequence,
|
||||||
|
random: receipt.random,
|
||||||
|
timestamp: receipt.timestamp,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { messageId, forwardId };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSendPrivateForward(
|
||||||
|
ref: InstanceRef,
|
||||||
|
userId: number,
|
||||||
|
messages: JsonValue,
|
||||||
|
): Promise<{ messageId: number; forwardId: string }> {
|
||||||
|
const nodes = await parseForwardNodes(ref, messages);
|
||||||
|
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
|
||||||
|
const receipt = await ref.bridge.sendPrivateMessage(userId, [{ type: 'forward', resId: forwardId }]);
|
||||||
|
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||||
|
|
||||||
|
ref.cacheMessageMeta(messageId, {
|
||||||
|
isGroup: false,
|
||||||
|
targetId: userId,
|
||||||
|
sequence: receipt.sequence,
|
||||||
|
eventName: PRIVATE_MESSAGE_EVENT,
|
||||||
|
clientSequence: receipt.clientSequence,
|
||||||
|
random: receipt.random,
|
||||||
|
timestamp: receipt.timestamp,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { messageId, forwardId };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleUploadForward(
|
||||||
|
ref: InstanceRef,
|
||||||
|
messages: JsonValue,
|
||||||
|
): Promise<{ forwardId: string }> {
|
||||||
|
const nodes = await parseForwardNodes(ref, messages);
|
||||||
|
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
|
||||||
|
return { forwardId };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGetForward(
|
||||||
|
ref: InstanceRef,
|
||||||
|
resId: string,
|
||||||
|
): Promise<JsonObject[]> {
|
||||||
|
const nodes = await ref.bridge.fetchForwardNodes(resId);
|
||||||
|
const results: JsonObject[] = [];
|
||||||
|
for (const node of nodes) {
|
||||||
|
results.push({
|
||||||
|
type: 'node' as any,
|
||||||
|
data: {
|
||||||
|
user_id: node.userUin as any,
|
||||||
|
nickname: node.nickname as any,
|
||||||
|
uin: String(node.userUin) as any,
|
||||||
|
name: node.nickname as any,
|
||||||
|
content: await elementsToOneBotSegments(node.elements, false, node.userUin) as any,
|
||||||
|
} as any,
|
||||||
|
} as JsonObject);
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function parseForwardNodes(ref: InstanceRef, messages: JsonValue): Promise<ForwardNodePayload[]> {
|
||||||
|
if (!Array.isArray(messages)) {
|
||||||
|
throw new Error('forward messages must be an array');
|
||||||
|
}
|
||||||
|
|
||||||
|
const nodes: ForwardNodePayload[] = [];
|
||||||
|
for (const item of messages) {
|
||||||
|
const segment = asJsonObject(item);
|
||||||
|
if (!segment) continue;
|
||||||
|
|
||||||
|
let nodeData: JsonObject | null = null;
|
||||||
|
if (String(segment.type ?? '') === 'node') {
|
||||||
|
nodeData = asJsonObject(segment.data);
|
||||||
|
} else if (segment.content !== undefined || segment.message !== undefined) {
|
||||||
|
nodeData = segment;
|
||||||
|
}
|
||||||
|
if (!nodeData) continue;
|
||||||
|
|
||||||
|
const messageId = toPositiveInt(nodeData.id ?? nodeData.message_id);
|
||||||
|
if (messageId > 0) {
|
||||||
|
const event = ref.messageStore.findEvent(messageId);
|
||||||
|
if (!event) throw new Error(`forward node message_id not found: ${messageId}`);
|
||||||
|
|
||||||
|
const eventSender = asJsonObject(event.sender) ?? {};
|
||||||
|
const nickname = String(eventSender.card ?? eventSender.nickname ?? nodeData.nickname ?? nodeData.name ?? '');
|
||||||
|
const userUin = toPositiveInt(event.user_id);
|
||||||
|
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
||||||
|
const elements = await parseMessage(content, false);
|
||||||
|
if (userUin > 0 && elements.length > 0) {
|
||||||
|
nodes.push({ userUin, nickname: nickname || String(userUin), elements });
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userUin = toPositiveInt(nodeData.user_id ?? nodeData.uin);
|
||||||
|
if (userUin <= 0) throw new Error('forward node user_id/uin is required');
|
||||||
|
|
||||||
|
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
|
||||||
|
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||||
|
const elements = await parseMessage(content, false);
|
||||||
|
if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`);
|
||||||
|
|
||||||
|
nodes.push({ userUin, nickname, elements });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nodes.length === 0) {
|
||||||
|
throw new Error('forward node list is empty');
|
||||||
|
}
|
||||||
|
return nodes;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asJsonObject(value: JsonValue | undefined): JsonObject | null {
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
|
||||||
|
return value as JsonObject;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toPositiveInt(value: JsonValue | undefined): number {
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
|
||||||
|
if (typeof value === 'string' && value.trim()) {
|
||||||
|
const parsed = Number(value);
|
||||||
|
if (Number.isFinite(parsed)) return Math.max(0, Math.trunc(parsed));
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import type { MessageElement } from '../bridge/events';
|
||||||
|
import type { Bridge, DownloadRKeyInfo } from '../bridge/bridge';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
|
const log = createLogger('OneBot');
|
||||||
|
|
||||||
|
interface CachedRKey {
|
||||||
|
value: string;
|
||||||
|
type: number;
|
||||||
|
createTime: number;
|
||||||
|
ttlSeconds: number;
|
||||||
|
expiresAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const RKEY_REFRESH_SKEW = 60;
|
||||||
|
const RKEY_REFRESH_COOLDOWN = 30;
|
||||||
|
const PRIVATE_IMAGE_RKEY_TYPE = 10;
|
||||||
|
const GROUP_IMAGE_RKEY_TYPE = 20;
|
||||||
|
const PRIVATE_VIDEO_RKEY_TYPE = 12;
|
||||||
|
const GROUP_VIDEO_RKEY_TYPE = 22;
|
||||||
|
const PRIVATE_PTT_RKEY_TYPE = 14;
|
||||||
|
const GROUP_PTT_RKEY_TYPE = 24;
|
||||||
|
const FALLBACK_IMAGE_RKEY_TYPE = 2;
|
||||||
|
|
||||||
|
export class RKeyCache {
|
||||||
|
private cache = new Map<number, CachedRKey>();
|
||||||
|
private lastRefreshAttempt = 0;
|
||||||
|
|
||||||
|
warmUp(bridge: Bridge, uin: string): void {
|
||||||
|
bridge.fetchDownloadRKeys().then(
|
||||||
|
(rkeys) => {
|
||||||
|
this.updateCache(rkeys);
|
||||||
|
log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length);
|
||||||
|
},
|
||||||
|
(err) => {
|
||||||
|
log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
resolveImageUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string {
|
||||||
|
const url = element.imageUrl ?? '';
|
||||||
|
if (!urlNeedsRKey(url)) return url;
|
||||||
|
|
||||||
|
const rkey = this.findRKey(bridge, isGroup);
|
||||||
|
if (!rkey) return url;
|
||||||
|
|
||||||
|
const cleanRKey = stripRKeyPrefix(rkey);
|
||||||
|
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
|
||||||
|
return url + separator + encodeURIComponent(cleanRKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a URL for video/record/file media elements.
|
||||||
|
* Appends the correct RKey type based on media kind and group/private context.
|
||||||
|
*/
|
||||||
|
resolveMediaUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string {
|
||||||
|
const url = element.url ?? '';
|
||||||
|
if (!url || !urlNeedsRKey(url)) return url;
|
||||||
|
|
||||||
|
const mediaType = element.type;
|
||||||
|
let primaryType: number;
|
||||||
|
if (mediaType === 'video') {
|
||||||
|
primaryType = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
|
||||||
|
} else if (mediaType === 'record') {
|
||||||
|
primaryType = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
|
||||||
|
} else {
|
||||||
|
// For file types, try image rkeys as a fallback (file URLs typically use image rkeys)
|
||||||
|
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rkey = this.findRKeyForType(bridge, primaryType);
|
||||||
|
if (!rkey) return url;
|
||||||
|
|
||||||
|
const cleanRKey = stripRKeyPrefix(rkey);
|
||||||
|
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
|
||||||
|
return url + separator + encodeURIComponent(cleanRKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateCache(rkeys: DownloadRKeyInfo[]): void {
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
for (const rk of rkeys) {
|
||||||
|
if (!rk.rkey || !rk.type) continue;
|
||||||
|
const baseTime = rk.createTime || now;
|
||||||
|
const ttl = rk.ttlSeconds || 3600;
|
||||||
|
this.cache.set(rk.type, {
|
||||||
|
value: rk.rkey,
|
||||||
|
type: rk.type,
|
||||||
|
createTime: rk.createTime,
|
||||||
|
ttlSeconds: rk.ttlSeconds,
|
||||||
|
expiresAt: baseTime + ttl,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private findRKey(bridge: Bridge, isGroup: boolean): string | null {
|
||||||
|
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||||
|
return this.findRKeyForType(bridge, primaryType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private findRKeyForType(bridge: Bridge, primaryType: number): string | null {
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
const tryFind = (type: number): string | null => {
|
||||||
|
const cached = this.cache.get(type);
|
||||||
|
if (!cached || !cached.value) return null;
|
||||||
|
if (cached.expiresAt !== 0 && now + RKEY_REFRESH_SKEW >= cached.expiresAt) return null;
|
||||||
|
return cached.value;
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||||
|
if (result) return result;
|
||||||
|
|
||||||
|
// Refresh check cooldown
|
||||||
|
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null;
|
||||||
|
this.lastRefreshAttempt = now;
|
||||||
|
|
||||||
|
// Schedule async refresh
|
||||||
|
bridge.fetchDownloadRKeys().then(
|
||||||
|
(rkeys) => this.updateCache(rkeys),
|
||||||
|
() => { /* ignore */ },
|
||||||
|
);
|
||||||
|
|
||||||
|
// Try again (won't be ready yet for this call, but future calls will benefit)
|
||||||
|
result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function urlNeedsRKey(url: string): boolean {
|
||||||
|
if (!url || url.includes('rkey=')) return false;
|
||||||
|
if (url.includes('gchat.qpic.cn')) return false;
|
||||||
|
return url.includes('multimedia.nt.qq.com.cn') ||
|
||||||
|
url.includes('.nt.qq.com.cn') ||
|
||||||
|
url.includes('/download');
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripRKeyPrefix(rkey: string): string {
|
||||||
|
for (const prefix of ['&rkey=', '?rkey=']) {
|
||||||
|
if (rkey.startsWith(prefix)) return rkey.slice(prefix.length);
|
||||||
|
}
|
||||||
|
return rkey;
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
import path from 'path';
|
||||||
|
import type { QQEventVariant } from '../bridge/events';
|
||||||
|
import type { Bridge } from '../bridge/bridge';
|
||||||
|
import type { QQInfo } from '../bridge/qq-info';
|
||||||
|
import { ApiHandler } from './api-handler';
|
||||||
|
import { EventConverter } from './event-converter';
|
||||||
|
import { MessageStore } from './message-store';
|
||||||
|
import { RKeyCache } from './instance-rkey';
|
||||||
|
import { buildApiContext } from './instance-context';
|
||||||
|
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||||
|
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
|
||||||
|
import { HttpTransport } from './http-transport';
|
||||||
|
import { HttpPostTransport } from './http-post-transport';
|
||||||
|
import { WsTransport } from './ws-transport';
|
||||||
|
|
||||||
|
export class OneBotInstance {
|
||||||
|
readonly uin: string;
|
||||||
|
|
||||||
|
readonly qqInfo: QQInfo;
|
||||||
|
private readonly bridge: Bridge;
|
||||||
|
private readonly apiHandler: ApiHandler;
|
||||||
|
private readonly eventConverter: EventConverter;
|
||||||
|
private readonly messageStore: MessageStore;
|
||||||
|
private readonly httpTransport: HttpTransport;
|
||||||
|
private readonly httpPostTransport: HttpPostTransport;
|
||||||
|
private readonly wsTransport: WsTransport;
|
||||||
|
private readonly rkeyCache: RKeyCache;
|
||||||
|
|
||||||
|
private readonly pids = new Set<number>();
|
||||||
|
private online = true;
|
||||||
|
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||||
|
private static readonly HEARTBEAT_INTERVAL = 30000;
|
||||||
|
|
||||||
|
constructor(uin: string, qqInfo: QQInfo, bridge: Bridge, config: OneBotConfig) {
|
||||||
|
this.uin = uin;
|
||||||
|
this.qqInfo = qqInfo;
|
||||||
|
this.bridge = bridge;
|
||||||
|
|
||||||
|
this.eventConverter = new EventConverter();
|
||||||
|
this.rkeyCache = new RKeyCache();
|
||||||
|
this.eventConverter.setImageUrlResolver((element, isGroup) =>
|
||||||
|
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup));
|
||||||
|
this.eventConverter.setMediaUrlResolver(async (element, isGroup, sessionId) => {
|
||||||
|
// Fetch URL from bridge if not already present
|
||||||
|
if (!element.url) {
|
||||||
|
try {
|
||||||
|
if (element.type === 'file' && element.fileId) {
|
||||||
|
element.url = isGroup
|
||||||
|
? await this.bridge.fetchGroupFileUrl(sessionId, element.fileId)
|
||||||
|
: element.fileHash
|
||||||
|
? await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash)
|
||||||
|
: '';
|
||||||
|
} else if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
|
||||||
|
if (isGroup) {
|
||||||
|
element.url = element.type === 'record'
|
||||||
|
? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode)
|
||||||
|
: await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode);
|
||||||
|
} else {
|
||||||
|
element.url = element.type === 'record'
|
||||||
|
? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode)
|
||||||
|
: await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch { /* best-effort */ }
|
||||||
|
}
|
||||||
|
// Then apply RKey if needed
|
||||||
|
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
|
||||||
|
});
|
||||||
|
this.eventConverter.setMessageIdResolver((isGroup, sessionId, sequence, eventName) =>
|
||||||
|
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)));
|
||||||
|
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
|
||||||
|
|
||||||
|
const context = buildApiContext({
|
||||||
|
uin: this.uin,
|
||||||
|
qqInfo: this.qqInfo,
|
||||||
|
bridge: this.bridge,
|
||||||
|
messageStore: this.messageStore,
|
||||||
|
musicSignUrl: config.musicSignUrl,
|
||||||
|
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||||
|
});
|
||||||
|
this.apiHandler = new ApiHandler(context);
|
||||||
|
|
||||||
|
this.httpTransport = new HttpTransport(config, {
|
||||||
|
api: this.apiHandler,
|
||||||
|
});
|
||||||
|
|
||||||
|
this.httpPostTransport = new HttpPostTransport(config, {
|
||||||
|
uin: this.uin,
|
||||||
|
api: this.apiHandler,
|
||||||
|
});
|
||||||
|
|
||||||
|
this.wsTransport = new WsTransport(config, {
|
||||||
|
uin: this.uin,
|
||||||
|
api: this.apiHandler,
|
||||||
|
buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType),
|
||||||
|
buildHeartbeatEvent: () => this.makeHeartbeatEvent(),
|
||||||
|
});
|
||||||
|
|
||||||
|
this.httpTransport.start();
|
||||||
|
this.httpPostTransport.start();
|
||||||
|
this.wsTransport.start();
|
||||||
|
this.startHeartbeat();
|
||||||
|
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
this.online = false;
|
||||||
|
this.stopHeartbeat();
|
||||||
|
this.httpTransport.stop();
|
||||||
|
this.httpPostTransport.stop();
|
||||||
|
this.wsTransport.stop();
|
||||||
|
this.messageStore.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
onBridgeEvent(event: QQEventVariant): void {
|
||||||
|
this.cacheMessageMetaFromBridgeEvent(event);
|
||||||
|
|
||||||
|
void this.dispatchBridgeEventAsync(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async dispatchBridgeEventAsync(event: QQEventVariant): Promise<void> {
|
||||||
|
const converted = await this.eventConverter.convert(this.uin, event);
|
||||||
|
if (!converted) return;
|
||||||
|
|
||||||
|
this.dispatchEvent(converted);
|
||||||
|
}
|
||||||
|
|
||||||
|
addPid(pid: number): void {
|
||||||
|
this.pids.add(pid);
|
||||||
|
}
|
||||||
|
|
||||||
|
removePid(pid: number): void {
|
||||||
|
this.pids.delete(pid);
|
||||||
|
}
|
||||||
|
|
||||||
|
hasPid(pid: number): boolean {
|
||||||
|
return this.pids.has(pid);
|
||||||
|
}
|
||||||
|
|
||||||
|
get empty(): boolean {
|
||||||
|
return this.pids.size === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private dispatchEvent(event: JsonObject): void {
|
||||||
|
this.cacheMessageEvent(event);
|
||||||
|
this.wsTransport.publishEvent(event);
|
||||||
|
this.httpPostTransport.publishEvent(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
private cacheMessageEvent(event: JsonObject): void {
|
||||||
|
if (event.post_type !== 'message') return;
|
||||||
|
|
||||||
|
const messageId = toInt(event.message_id);
|
||||||
|
if (messageId === 0) return;
|
||||||
|
|
||||||
|
const isGroup = event.message_type === 'group';
|
||||||
|
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);
|
||||||
|
const sequence = toInt(event.message_seq);
|
||||||
|
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||||
|
|
||||||
|
if (sessionId === 0) return;
|
||||||
|
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
|
||||||
|
}
|
||||||
|
|
||||||
|
private cacheMessageMetaFromBridgeEvent(event: QQEventVariant): void {
|
||||||
|
if (event.kind === 'group_message') {
|
||||||
|
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
|
||||||
|
this.cacheMessageMeta(messageId, {
|
||||||
|
isGroup: true,
|
||||||
|
targetId: event.groupId,
|
||||||
|
sequence: event.msgSeq,
|
||||||
|
eventName: GROUP_MESSAGE_EVENT,
|
||||||
|
clientSequence: 0,
|
||||||
|
random: event.msgId,
|
||||||
|
timestamp: event.time,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event.kind === 'friend_message') {
|
||||||
|
const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT);
|
||||||
|
this.cacheMessageMeta(messageId, {
|
||||||
|
isGroup: false,
|
||||||
|
targetId: event.senderUin,
|
||||||
|
sequence: event.msgSeq,
|
||||||
|
eventName: PRIVATE_MESSAGE_EVENT,
|
||||||
|
clientSequence: 0,
|
||||||
|
random: event.msgId,
|
||||||
|
timestamp: event.time,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event.kind === 'temp_message') {
|
||||||
|
const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT);
|
||||||
|
this.cacheMessageMeta(messageId, {
|
||||||
|
isGroup: false,
|
||||||
|
targetId: event.senderUin,
|
||||||
|
sequence: event.msgSeq,
|
||||||
|
eventName: PRIVATE_MESSAGE_EVENT,
|
||||||
|
clientSequence: 0,
|
||||||
|
random: 0,
|
||||||
|
timestamp: event.time,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private cacheMessageMeta(messageId: number, meta: MessageMeta): void {
|
||||||
|
if (!Number.isInteger(messageId) || messageId === 0) return;
|
||||||
|
this.messageStore.storeMeta(messageId, meta);
|
||||||
|
}
|
||||||
|
|
||||||
|
private makeLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject {
|
||||||
|
const selfId = parseInt(this.uin, 10) || 0;
|
||||||
|
const time = Math.floor(Date.now() / 1000);
|
||||||
|
return {
|
||||||
|
time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'meta_event',
|
||||||
|
meta_event_type: 'lifecycle',
|
||||||
|
sub_type: subType,
|
||||||
|
status: {
|
||||||
|
online: this.online,
|
||||||
|
good: this.online,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Heartbeat ---
|
||||||
|
|
||||||
|
private startHeartbeat(): void {
|
||||||
|
this.heartbeatTimer = setInterval(() => {
|
||||||
|
this.dispatchEvent(this.makeHeartbeatEvent());
|
||||||
|
}, OneBotInstance.HEARTBEAT_INTERVAL);
|
||||||
|
this.heartbeatTimer.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
private makeHeartbeatEvent(): JsonObject {
|
||||||
|
const selfId = parseInt(this.uin, 10) || 0;
|
||||||
|
const time = Math.floor(Date.now() / 1000);
|
||||||
|
return {
|
||||||
|
time,
|
||||||
|
self_id: selfId,
|
||||||
|
post_type: 'meta_event',
|
||||||
|
meta_event_type: 'heartbeat',
|
||||||
|
status: { online: this.online, good: this.online },
|
||||||
|
interval: OneBotInstance.HEARTBEAT_INTERVAL,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private stopHeartbeat(): void {
|
||||||
|
if (this.heartbeatTimer) {
|
||||||
|
clearInterval(this.heartbeatTimer);
|
||||||
|
this.heartbeatTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toInt(value: unknown): number {
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||||
|
if (typeof value === 'string' && value.trim()) {
|
||||||
|
const parsed = Number(value);
|
||||||
|
if (Number.isFinite(parsed)) return Math.trunc(parsed);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import type { QQEventVariant } from '../bridge/events';
|
||||||
|
import type { Bridge } from '../bridge/bridge';
|
||||||
|
import type { QQInfo } from '../bridge/qq-info';
|
||||||
|
import type { BridgeManager } from '../bridge/manager';
|
||||||
|
import { loadOneBotConfig } from './config';
|
||||||
|
import { OneBotInstance } from './instance';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
|
const log = createLogger('OneBot');
|
||||||
|
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
||||||
|
|
||||||
|
export class OneBotManager {
|
||||||
|
private readonly instances = new Map<string, OneBotInstance>();
|
||||||
|
|
||||||
|
bind(bridgeManager: BridgeManager): void {
|
||||||
|
bridgeManager.setSessionStartedCallback((uin, qqInfo, bridge) => {
|
||||||
|
this.onSessionStarted(uin, qqInfo, bridge);
|
||||||
|
});
|
||||||
|
|
||||||
|
bridgeManager.setSessionClosedCallback((uin) => {
|
||||||
|
this.onSessionClosed(uin);
|
||||||
|
});
|
||||||
|
|
||||||
|
bridgeManager.setEventCallback((uin, event) => {
|
||||||
|
this.onBridgeEvent(uin, event);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
getInstance(uin: string): OneBotInstance | null {
|
||||||
|
return this.instances.get(uin) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getInstances(): OneBotInstance[] {
|
||||||
|
return [...this.instances.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
for (const instance of this.instances.values()) {
|
||||||
|
instance.dispose();
|
||||||
|
}
|
||||||
|
this.instances.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private onSessionStarted(uin: string, qqInfo: QQInfo, bridge: Bridge): void {
|
||||||
|
if (this.instances.has(uin)) return;
|
||||||
|
|
||||||
|
const config = loadOneBotConfig(uin);
|
||||||
|
const instance = new OneBotInstance(uin, qqInfo, bridge, config);
|
||||||
|
|
||||||
|
const activePid = bridge.activePid;
|
||||||
|
if (activePid !== null) {
|
||||||
|
instance.addPid(activePid);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.instances.set(uin, instance);
|
||||||
|
log.info('session started: UIN=%s', uin);
|
||||||
|
|
||||||
|
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state)
|
||||||
|
warmUpBridgeState(uin, qqInfo, bridge).catch((err) => {
|
||||||
|
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private onSessionClosed(uin: string): void {
|
||||||
|
const instance = this.instances.get(uin);
|
||||||
|
if (!instance) return;
|
||||||
|
|
||||||
|
instance.dispose();
|
||||||
|
this.instances.delete(uin);
|
||||||
|
log.info('session closed: UIN=%s', uin);
|
||||||
|
}
|
||||||
|
|
||||||
|
private onBridgeEvent(uin: string, event: QQEventVariant): void {
|
||||||
|
const instance = this.instances.get(uin);
|
||||||
|
if (!instance) return;
|
||||||
|
|
||||||
|
instance.onBridgeEvent(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): Promise<void> {
|
||||||
|
// Step 1: Fetch friend list + derive self profile
|
||||||
|
try {
|
||||||
|
const friends = await bridge.fetchFriendList();
|
||||||
|
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
|
||||||
|
|
||||||
|
const selfUin = parseInt(uin, 10) || 0;
|
||||||
|
for (const f of friends) {
|
||||||
|
if (f.uin === selfUin) {
|
||||||
|
qqInfo.setSelfProfile({
|
||||||
|
uin: f.uin, uid: f.uid,
|
||||||
|
nickname: f.nickname || uin,
|
||||||
|
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
|
||||||
|
});
|
||||||
|
qqInfo.nickname = f.nickname || uin;
|
||||||
|
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: Fetch group list
|
||||||
|
let groups: { groupId: number }[] = [];
|
||||||
|
try {
|
||||||
|
groups = await bridge.fetchGroupList();
|
||||||
|
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
|
||||||
|
} catch (e) {
|
||||||
|
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 3: Fetch members for each group
|
||||||
|
let loadedGroupCount = 0;
|
||||||
|
let loadedMemberCount = 0;
|
||||||
|
let failedGroupCount = 0;
|
||||||
|
for (const g of groups) {
|
||||||
|
try {
|
||||||
|
const members = await bridge.fetchGroupMemberList(g.groupId);
|
||||||
|
loadedGroupCount += 1;
|
||||||
|
loadedMemberCount += members.length;
|
||||||
|
if (VERBOSE_WARMUP) {
|
||||||
|
log.debug('members loaded: group=%d count=%d', g.groupId, members.length);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
failedGroupCount += 1;
|
||||||
|
log.warn('failed to load members for group %d: %s', g.groupId, e instanceof Error ? e.message : String(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
|
||||||
|
uin,
|
||||||
|
loadedGroupCount,
|
||||||
|
groups.length,
|
||||||
|
loadedMemberCount,
|
||||||
|
failedGroupCount,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
|
||||||
|
export const GROUP_MESSAGE_EVENT = 'group_message';
|
||||||
|
export const PRIVATE_MESSAGE_EVENT = 'private_message';
|
||||||
|
|
||||||
|
export function hashMessageIdInt32(sequence: number, sessionId: number, eventName: string): number {
|
||||||
|
const seq = Number.isFinite(sequence) ? Math.trunc(sequence) : 0;
|
||||||
|
const session = Number.isFinite(sessionId) ? Math.trunc(sessionId) : 0;
|
||||||
|
const key = `${seq}:${session}:${eventName}`;
|
||||||
|
const digest = createHash('sha1').update(key).digest();
|
||||||
|
|
||||||
|
let id = digest.readInt32BE(0);
|
||||||
|
if (id === 0) id = 1;
|
||||||
|
return id;
|
||||||
|
}
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
// OneBot11 message segment parser.
|
||||||
|
// Converts OneBot message format (string with CQ codes or JSON segment arrays)
|
||||||
|
// into internal MessageElement arrays for sending.
|
||||||
|
|
||||||
|
import type { MessageElement } from '../bridge/events';
|
||||||
|
import type { JsonValue, JsonObject } from './types';
|
||||||
|
|
||||||
|
export interface ParseMessageOptions {
|
||||||
|
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||||
|
musicSignUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- CQ Code parsing ---
|
||||||
|
|
||||||
|
const CQ_REGEX = /\[CQ:([a-z]+)(?:,([^\]]*))?\]/g;
|
||||||
|
|
||||||
|
function parseCQParams(raw: string): Record<string, string> {
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
if (!raw) return params;
|
||||||
|
for (const pair of raw.split(',')) {
|
||||||
|
const eq = pair.indexOf('=');
|
||||||
|
if (eq > 0) {
|
||||||
|
params[pair.substring(0, eq)] = pair.substring(eq + 1)
|
||||||
|
.replace(/[/g, '[')
|
||||||
|
.replace(/]/g, ']')
|
||||||
|
.replace(/,/g, ',')
|
||||||
|
.replace(/&/g, '&');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cqUnescape(text: string): string {
|
||||||
|
return text
|
||||||
|
.replace(/[/g, '[')
|
||||||
|
.replace(/]/g, ']')
|
||||||
|
.replace(/&/g, '&');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise<MessageElement[]> {
|
||||||
|
const elements: MessageElement[] = [];
|
||||||
|
let lastIndex = 0;
|
||||||
|
|
||||||
|
for (const match of message.matchAll(CQ_REGEX)) {
|
||||||
|
// Text before this CQ code
|
||||||
|
if (match.index! > lastIndex) {
|
||||||
|
const text = cqUnescape(message.substring(lastIndex, match.index!));
|
||||||
|
if (text) elements.push({ type: 'text', text });
|
||||||
|
}
|
||||||
|
lastIndex = match.index! + match[0].length;
|
||||||
|
|
||||||
|
const cqType = match[1];
|
||||||
|
const params = parseCQParams(match[2] || '');
|
||||||
|
const elem = await segmentToElement(cqType, params, options);
|
||||||
|
if (elem) elements.push(elem);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trailing text
|
||||||
|
if (lastIndex < message.length) {
|
||||||
|
const text = cqUnescape(message.substring(lastIndex));
|
||||||
|
if (text) elements.push({ type: 'text', text });
|
||||||
|
}
|
||||||
|
|
||||||
|
return elements;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- JSON segment parsing ---
|
||||||
|
|
||||||
|
interface MessageSegment {
|
||||||
|
type: string;
|
||||||
|
data?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSegmentArray(val: unknown): val is MessageSegment[] {
|
||||||
|
return Array.isArray(val) && val.every(
|
||||||
|
(item) => typeof item === 'object' && item !== null && 'type' in item
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
|
||||||
|
switch (type) {
|
||||||
|
case 'text': {
|
||||||
|
const text = String(data.text ?? '');
|
||||||
|
return text ? { type: 'text', text } : null;
|
||||||
|
}
|
||||||
|
case 'face': {
|
||||||
|
const id = parseInt(String(data.id ?? '0'), 10);
|
||||||
|
return { type: 'face', faceId: id };
|
||||||
|
}
|
||||||
|
case 'at': {
|
||||||
|
const qq = String(data.qq ?? '');
|
||||||
|
if (qq === 'all') {
|
||||||
|
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
|
||||||
|
}
|
||||||
|
const uin = parseInt(qq, 10);
|
||||||
|
return uin > 0 ? { type: 'at', targetUin: uin, text: `@${uin} ` } : null;
|
||||||
|
}
|
||||||
|
case 'reply': {
|
||||||
|
const id = parseInt(String(data.id ?? '0'), 10);
|
||||||
|
if (!Number.isInteger(id) || id === 0) return null;
|
||||||
|
|
||||||
|
if (options?.resolveReplySequence) {
|
||||||
|
const resolved = options.resolveReplySequence(id);
|
||||||
|
if (typeof resolved === 'number' && resolved > 0) {
|
||||||
|
return { type: 'reply', replySeq: resolved };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backward-compatible path: allow direct seq reply IDs.
|
||||||
|
return id > 0 ? { type: 'reply', replySeq: id } : null;
|
||||||
|
}
|
||||||
|
case 'image': {
|
||||||
|
return {
|
||||||
|
type: 'image',
|
||||||
|
url: String(data.file ?? data.url ?? ''),
|
||||||
|
flash: data.type === 'flash',
|
||||||
|
subType: parseInt(String(data.subType ?? '0'), 10),
|
||||||
|
summary: data.summary ? String(data.summary) : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'record': {
|
||||||
|
return {
|
||||||
|
type: 'record',
|
||||||
|
url: String(data.file ?? data.url ?? ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'video': {
|
||||||
|
return {
|
||||||
|
type: 'video',
|
||||||
|
url: String(data.file ?? data.url ?? ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'json': {
|
||||||
|
return {
|
||||||
|
type: 'json',
|
||||||
|
text: String(data.data ?? ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'xml': {
|
||||||
|
return {
|
||||||
|
type: 'xml',
|
||||||
|
text: String(data.data ?? ''),
|
||||||
|
subType: parseInt(String(data.id ?? '0'), 10),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'poke': {
|
||||||
|
return {
|
||||||
|
type: 'poke',
|
||||||
|
faceId: parseInt(String(data.type ?? data.id ?? '0'), 10),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'forward': {
|
||||||
|
return {
|
||||||
|
type: 'forward',
|
||||||
|
resId: String(data.id ?? ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'node': {
|
||||||
|
// Fake forward node segment — store the raw data for later processing
|
||||||
|
// The content field may be a segment array, a single segment, or a CQ string
|
||||||
|
const uin = String(data.user_id ?? data.uin ?? '0');
|
||||||
|
const name = String(data.nickname ?? data.name ?? '');
|
||||||
|
return {
|
||||||
|
type: 'node',
|
||||||
|
targetUin: parseInt(uin, 10) || 0,
|
||||||
|
text: name,
|
||||||
|
// Raw content is stored as JSON string in resId for later processing
|
||||||
|
resId: JSON.stringify(data.content ?? ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'markdown': {
|
||||||
|
return {
|
||||||
|
type: 'markdown',
|
||||||
|
text: String(data.content ?? ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'share': {
|
||||||
|
// Link share — map to json card message
|
||||||
|
const url = String(data.url ?? '');
|
||||||
|
const title = String(data.title ?? '');
|
||||||
|
const content = String(data.content ?? '');
|
||||||
|
const image = String(data.image ?? '');
|
||||||
|
const jsonData = JSON.stringify({
|
||||||
|
app: 'com.tencent.structmsg',
|
||||||
|
view: 'news',
|
||||||
|
prompt: title,
|
||||||
|
meta: { news: { title, desc: content, jumpUrl: url, preview: image } },
|
||||||
|
});
|
||||||
|
return { type: 'json', text: jsonData };
|
||||||
|
}
|
||||||
|
case 'music': {
|
||||||
|
// Music share — uses external signing service (NapCat-compatible)
|
||||||
|
const musicType = String(data.type ?? '');
|
||||||
|
const signUrl = options?.musicSignUrl || 'https://ss.xingzhige.com/music_card/card';
|
||||||
|
try {
|
||||||
|
let postData: Record<string, unknown>;
|
||||||
|
if (musicType === 'custom') {
|
||||||
|
postData = {
|
||||||
|
type: 'custom',
|
||||||
|
id: undefined,
|
||||||
|
url: String(data.url ?? ''),
|
||||||
|
audio: String(data.audio ?? ''),
|
||||||
|
title: String(data.title ?? ''),
|
||||||
|
image: String(data.image ?? ''),
|
||||||
|
singer: String(data.content ?? ''),
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
postData = { type: musicType, id: String(data.id ?? '') };
|
||||||
|
}
|
||||||
|
const resp = await fetch(signUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(postData),
|
||||||
|
});
|
||||||
|
if (!resp.ok) throw new Error(`music sign HTTP ${resp.status}`);
|
||||||
|
const musicJson = await resp.text();
|
||||||
|
return { type: 'json', text: musicJson };
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`[MsgParser] music sign failed: ${e}, falling back to local card`);
|
||||||
|
// Fallback: build a basic card locally
|
||||||
|
const title = String(data.title ?? 'Music');
|
||||||
|
const jsonData = JSON.stringify({
|
||||||
|
app: 'com.tencent.structmsg',
|
||||||
|
view: 'music',
|
||||||
|
prompt: `[音乐]${title}`,
|
||||||
|
meta: {
|
||||||
|
music: {
|
||||||
|
title,
|
||||||
|
desc: String(data.content ?? ''),
|
||||||
|
jumpUrl: String(data.url ?? ''),
|
||||||
|
musicUrl: String(data.audio ?? ''),
|
||||||
|
preview: String(data.image ?? ''),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { type: 'json', text: jsonData };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 'location': {
|
||||||
|
// Location — map to json card
|
||||||
|
const lat = String(data.lat ?? '');
|
||||||
|
const lon = String(data.lon ?? '');
|
||||||
|
const title = String(data.title ?? '位置');
|
||||||
|
const content = String(data.content ?? `${lat},${lon}`);
|
||||||
|
const jsonData = JSON.stringify({
|
||||||
|
app: 'com.tencent.map',
|
||||||
|
view: 'LocationShare',
|
||||||
|
prompt: `[位置]${title}`,
|
||||||
|
meta: { Location: { lat, lng: lon, title, address: content } },
|
||||||
|
});
|
||||||
|
return { type: 'json', text: jsonData };
|
||||||
|
}
|
||||||
|
case 'contact': {
|
||||||
|
// Contact card — map to json card
|
||||||
|
const contactType = String(data.type ?? 'qq');
|
||||||
|
const contactId = String(data.id ?? '');
|
||||||
|
const jsonData = JSON.stringify({
|
||||||
|
app: 'com.tencent.contact.lua',
|
||||||
|
view: 'contact',
|
||||||
|
prompt: `[推荐${contactType === 'group' ? '群' : '好友'}]`,
|
||||||
|
meta: { contact: { type: contactType, id: contactId } },
|
||||||
|
});
|
||||||
|
return { type: 'json', text: jsonData };
|
||||||
|
}
|
||||||
|
case 'rps': {
|
||||||
|
// Rock-paper-scissors — map to dice-like face
|
||||||
|
return { type: 'face', faceId: 359 };
|
||||||
|
}
|
||||||
|
case 'dice': {
|
||||||
|
// Dice — map to dice face
|
||||||
|
return { type: 'face', faceId: 358 };
|
||||||
|
}
|
||||||
|
case 'shake': {
|
||||||
|
// Window shake — map to poke
|
||||||
|
return { type: 'poke', faceId: 1 };
|
||||||
|
}
|
||||||
|
case 'anonymous': {
|
||||||
|
// Anonymous flag — ignored during send, the protocol handles anonymity
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
console.warn(`[MsgParser] unsupported segment type: ${type}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Public API ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse an OneBot11 message value into internal MessageElement array.
|
||||||
|
* Supports:
|
||||||
|
* - string (plain text or CQ code string)
|
||||||
|
* - array of { type, data } segments (JSON segment format)
|
||||||
|
*
|
||||||
|
* If autoEscape is true, the string is treated as plain text (no CQ parsing).
|
||||||
|
*/
|
||||||
|
export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise<MessageElement[]> {
|
||||||
|
if (typeof message === 'string') {
|
||||||
|
if (autoEscape) {
|
||||||
|
return message ? [{ type: 'text', text: message }] : [];
|
||||||
|
}
|
||||||
|
return parseFromCQString(message, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isSegmentArray(message)) {
|
||||||
|
const elements: MessageElement[] = [];
|
||||||
|
for (const seg of message) {
|
||||||
|
const data = (seg.data ?? {}) as Record<string, unknown>;
|
||||||
|
const elem = await segmentToElement(seg.type, data, options);
|
||||||
|
if (elem) elements.push(elem);
|
||||||
|
}
|
||||||
|
return elements;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Single segment object
|
||||||
|
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
|
||||||
|
const seg = message as unknown as MessageSegment;
|
||||||
|
if (seg.type) {
|
||||||
|
const data = (seg.data ?? {}) as Record<string, unknown>;
|
||||||
|
const elem = await segmentToElement(seg.type, data, options);
|
||||||
|
return elem ? [elem] : [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
// SQLite-backed message store using node:sqlite (DatabaseSync).
|
||||||
|
// Refactored to use a single unified `messages` table for all message types.
|
||||||
|
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
|
import type { JsonObject, MessageMeta } from './types';
|
||||||
|
|
||||||
|
export class MessageStore {
|
||||||
|
private readonly db: DatabaseSync;
|
||||||
|
|
||||||
|
constructor(dbPath: string) {
|
||||||
|
const dir = path.dirname(dbPath);
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
|
||||||
|
// Replace .json extension with .db if present
|
||||||
|
const finalPath = dbPath.replace(/\.json$/, '.db');
|
||||||
|
this.db = new DatabaseSync(finalPath);
|
||||||
|
this.db.exec('PRAGMA journal_mode = WAL');
|
||||||
|
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||||
|
this.initSchema();
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
this.db.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
storeEvent(
|
||||||
|
messageId: number,
|
||||||
|
isGroup: boolean,
|
||||||
|
sessionId: number,
|
||||||
|
sequence: number,
|
||||||
|
eventName: string,
|
||||||
|
event: JsonObject
|
||||||
|
): void {
|
||||||
|
if (!isValidMessageId(messageId)) return;
|
||||||
|
const json = JSON.stringify(event);
|
||||||
|
const timestamp = toInt(event.time);
|
||||||
|
|
||||||
|
this.db.prepare(
|
||||||
|
`INSERT INTO messages
|
||||||
|
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?)
|
||||||
|
ON CONFLICT(message_hash) DO UPDATE SET
|
||||||
|
is_group = excluded.is_group,
|
||||||
|
session_id = excluded.session_id,
|
||||||
|
sequence = excluded.sequence,
|
||||||
|
event_name = excluded.event_name,
|
||||||
|
timestamp = excluded.timestamp,
|
||||||
|
data = excluded.data`
|
||||||
|
).run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json);
|
||||||
|
}
|
||||||
|
|
||||||
|
storeMeta(messageId: number, meta: MessageMeta): void {
|
||||||
|
if (!isValidMessageId(messageId)) return;
|
||||||
|
this.db.prepare(
|
||||||
|
`INSERT INTO messages
|
||||||
|
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(message_hash) DO UPDATE SET
|
||||||
|
is_group = excluded.is_group,
|
||||||
|
session_id = excluded.session_id,
|
||||||
|
sequence = excluded.sequence,
|
||||||
|
event_name = excluded.event_name,
|
||||||
|
client_sequence = excluded.client_sequence,
|
||||||
|
random = excluded.random,
|
||||||
|
timestamp = excluded.timestamp`
|
||||||
|
).run(
|
||||||
|
messageId,
|
||||||
|
meta.isGroup ? 1 : 0,
|
||||||
|
meta.targetId,
|
||||||
|
meta.sequence,
|
||||||
|
meta.eventName,
|
||||||
|
meta.clientSequence,
|
||||||
|
meta.random,
|
||||||
|
meta.timestamp
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
findEvent(messageId: number): JsonObject | null {
|
||||||
|
if (!isValidMessageId(messageId)) return null;
|
||||||
|
const row = this.db.prepare(
|
||||||
|
'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL',
|
||||||
|
).get(messageId) as { data: string } | undefined;
|
||||||
|
|
||||||
|
if (!row?.data) return null;
|
||||||
|
try {
|
||||||
|
return JSON.parse(row.data) as JsonObject;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
findMeta(messageId: number): MessageMeta | null {
|
||||||
|
if (!isValidMessageId(messageId)) return null;
|
||||||
|
|
||||||
|
const row = this.db.prepare(
|
||||||
|
'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
|
||||||
|
).get(messageId) as {
|
||||||
|
is_group: number;
|
||||||
|
session_id: number;
|
||||||
|
sequence: number;
|
||||||
|
event_name: string;
|
||||||
|
client_sequence: number;
|
||||||
|
random: number;
|
||||||
|
timestamp: number;
|
||||||
|
} | undefined;
|
||||||
|
|
||||||
|
if (!row) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
isGroup: row.is_group === 1,
|
||||||
|
targetId: row.session_id,
|
||||||
|
sequence: row.sequence,
|
||||||
|
eventName: row.event_name,
|
||||||
|
clientSequence: row.client_sequence,
|
||||||
|
random: row.random,
|
||||||
|
timestamp: row.timestamp,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
resolveReplySequence(isGroup: boolean, sessionId: number, messageId: number): number | null {
|
||||||
|
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) return null;
|
||||||
|
const row = this.db.prepare(
|
||||||
|
`SELECT sequence
|
||||||
|
FROM messages
|
||||||
|
WHERE is_group = ? AND session_id = ? AND message_hash = ?
|
||||||
|
LIMIT 1`
|
||||||
|
).get(isGroup ? 1 : 0, sessionId, messageId) as { sequence: number } | undefined;
|
||||||
|
|
||||||
|
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null;
|
||||||
|
return row.sequence;
|
||||||
|
}
|
||||||
|
|
||||||
|
listSessionEvents(
|
||||||
|
isGroup: boolean,
|
||||||
|
sessionId: number,
|
||||||
|
count = 20,
|
||||||
|
anchorSequence?: number,
|
||||||
|
): JsonObject[] {
|
||||||
|
if (!Number.isInteger(sessionId) || sessionId <= 0) return [];
|
||||||
|
|
||||||
|
const limit = normalizePositiveInt(count, 20, 200);
|
||||||
|
const hasAnchor = Number.isInteger(anchorSequence) && (anchorSequence as number) > 0;
|
||||||
|
const anchor = hasAnchor ? (anchorSequence as number) : 0;
|
||||||
|
|
||||||
|
const rows = hasAnchor
|
||||||
|
? this.db.prepare(
|
||||||
|
`SELECT data
|
||||||
|
FROM messages
|
||||||
|
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ?
|
||||||
|
ORDER BY sequence DESC
|
||||||
|
LIMIT ?`
|
||||||
|
).all(isGroup ? 1 : 0, sessionId, anchor, limit)
|
||||||
|
: this.db.prepare(
|
||||||
|
`SELECT data
|
||||||
|
FROM messages
|
||||||
|
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
|
||||||
|
ORDER BY sequence DESC
|
||||||
|
LIMIT ?`
|
||||||
|
).all(isGroup ? 1 : 0, sessionId, limit);
|
||||||
|
|
||||||
|
const result: JsonObject[] = [];
|
||||||
|
for (const row of rows as Array<{ data: string }>) {
|
||||||
|
if (!row?.data) continue;
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(row.data) as JsonObject;
|
||||||
|
result.push(parsed);
|
||||||
|
} catch {
|
||||||
|
// Ignore malformed rows to avoid breaking history APIs.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep chronological order (oldest -> newest) for API consumers.
|
||||||
|
result.reverse();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
private initSchema(): void {
|
||||||
|
this.db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
message_hash INTEGER PRIMARY KEY,
|
||||||
|
is_group INTEGER NOT NULL,
|
||||||
|
session_id INTEGER NOT NULL,
|
||||||
|
sequence INTEGER NOT NULL,
|
||||||
|
event_name TEXT NOT NULL,
|
||||||
|
client_sequence INTEGER NOT NULL DEFAULT 0,
|
||||||
|
random INTEGER NOT NULL DEFAULT 0,
|
||||||
|
timestamp INTEGER NOT NULL DEFAULT 0,
|
||||||
|
data TEXT
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidMessageId(messageId: number): boolean {
|
||||||
|
return Number.isInteger(messageId) && messageId !== 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toInt(value: unknown): number {
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||||
|
if (typeof value === 'string' && value.trim()) {
|
||||||
|
const parsed = Number(value);
|
||||||
|
if (Number.isFinite(parsed)) return Math.trunc(parsed);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePositiveInt(value: number, fallback: number, max: number): number {
|
||||||
|
if (!Number.isFinite(value)) return fallback;
|
||||||
|
const n = Math.trunc(value);
|
||||||
|
if (n <= 0) return fallback;
|
||||||
|
if (n > max) return max;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
export type JsonPrimitive = string | number | boolean | null;
|
||||||
|
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
|
||||||
|
export interface JsonObject {
|
||||||
|
[key: string]: JsonValue;
|
||||||
|
}
|
||||||
|
export type JsonArray = JsonValue[];
|
||||||
|
|
||||||
|
export interface ApiResponse {
|
||||||
|
status: 'ok' | 'failed';
|
||||||
|
retcode: number;
|
||||||
|
data: JsonValue;
|
||||||
|
echo?: JsonValue;
|
||||||
|
wording?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OneBotRequest {
|
||||||
|
action: string;
|
||||||
|
params?: JsonObject;
|
||||||
|
echo?: JsonValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WsServerEndpoint {
|
||||||
|
name?: string;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
path?: string;
|
||||||
|
role?: WsRole;
|
||||||
|
accessToken?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HttpServerEndpoint {
|
||||||
|
name?: string;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
path?: string;
|
||||||
|
accessToken?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WsClientEndpoint {
|
||||||
|
name?: string;
|
||||||
|
url: string;
|
||||||
|
role?: WsRole;
|
||||||
|
reconnectIntervalMs?: number;
|
||||||
|
accessToken?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HttpPostEndpoint {
|
||||||
|
name?: string;
|
||||||
|
url: string;
|
||||||
|
accessToken?: string;
|
||||||
|
timeoutMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OneBotConfig {
|
||||||
|
httpServers: HttpServerEndpoint[];
|
||||||
|
httpPostEndpoints: HttpPostEndpoint[];
|
||||||
|
wsServers: WsServerEndpoint[];
|
||||||
|
wsClients: WsClientEndpoint[];
|
||||||
|
musicSignUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WsRole = 'api' | 'event' | 'universal';
|
||||||
|
|
||||||
|
export interface MessageMeta {
|
||||||
|
isGroup: boolean;
|
||||||
|
targetId: number;
|
||||||
|
sequence: number;
|
||||||
|
eventName: string;
|
||||||
|
clientSequence: number;
|
||||||
|
random: number;
|
||||||
|
timestamp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RETCODE = {
|
||||||
|
ACTION_FAILED: 100,
|
||||||
|
INTERNAL_ERROR: 1200,
|
||||||
|
BAD_REQUEST: 1400,
|
||||||
|
UNKNOWN_ACTION: 1404,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function okResponse(data: JsonValue = null): ApiResponse {
|
||||||
|
return {
|
||||||
|
status: 'ok',
|
||||||
|
retcode: 0,
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function failedResponse(retcode: number, wording: string): ApiResponse {
|
||||||
|
return {
|
||||||
|
status: 'failed',
|
||||||
|
retcode,
|
||||||
|
data: null,
|
||||||
|
wording,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
import WebSocket, { WebSocketServer } from 'ws';
|
||||||
|
import type { IncomingHttpHeaders, IncomingMessage } from 'http';
|
||||||
|
import type { ApiHandler } from './api-handler';
|
||||||
|
import type { JsonObject, OneBotConfig, WsRole } from './types';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
|
interface ForwardConnection {
|
||||||
|
socket: WebSocket;
|
||||||
|
role: WsRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ReverseConnection {
|
||||||
|
socket: WebSocket;
|
||||||
|
role: WsRole;
|
||||||
|
endpointUrl: string;
|
||||||
|
reconnectIntervalMs: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WsTransportContext {
|
||||||
|
uin: string;
|
||||||
|
api: ApiHandler;
|
||||||
|
buildLifecycleEvent: (subType: 'connect' | 'enable' | 'disable') => JsonObject;
|
||||||
|
buildHeartbeatEvent: () => JsonObject;
|
||||||
|
}
|
||||||
|
|
||||||
|
const log = createLogger('OneBot.WS');
|
||||||
|
|
||||||
|
export class WsTransport {
|
||||||
|
private readonly config: OneBotConfig;
|
||||||
|
private readonly context: WsTransportContext;
|
||||||
|
|
||||||
|
private readonly servers: WebSocketServer[] = [];
|
||||||
|
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
|
||||||
|
private readonly reverseConnections = new Set<ReverseConnection>();
|
||||||
|
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
||||||
|
private stopped = false;
|
||||||
|
|
||||||
|
constructor(config: OneBotConfig, context: WsTransportContext) {
|
||||||
|
this.config = config;
|
||||||
|
this.context = context;
|
||||||
|
}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
this.stopped = false;
|
||||||
|
this.startServers();
|
||||||
|
this.startReverseClients();
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
this.stopped = true;
|
||||||
|
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
||||||
|
|
||||||
|
for (const timer of this.reconnectTimers) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
this.reconnectTimers.clear();
|
||||||
|
|
||||||
|
for (const [socket] of this.forwardConnections) {
|
||||||
|
safeClose(socket);
|
||||||
|
}
|
||||||
|
this.forwardConnections.clear();
|
||||||
|
|
||||||
|
for (const conn of this.reverseConnections) {
|
||||||
|
safeClose(conn.socket);
|
||||||
|
}
|
||||||
|
this.reverseConnections.clear();
|
||||||
|
|
||||||
|
for (const server of this.servers) {
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
this.servers.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
publishEvent(event: JsonObject): void {
|
||||||
|
const payload = JSON.stringify(event);
|
||||||
|
|
||||||
|
for (const { socket, role } of this.forwardConnections.values()) {
|
||||||
|
if (role === 'event' || role === 'universal') {
|
||||||
|
safeSend(socket, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const { socket, role } of this.reverseConnections.values()) {
|
||||||
|
if (role === 'event' || role === 'universal') {
|
||||||
|
safeSend(socket, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private startServers(): void {
|
||||||
|
for (const endpoint of this.config.wsServers) {
|
||||||
|
const wss = new WebSocketServer({
|
||||||
|
host: endpoint.host,
|
||||||
|
port: endpoint.port,
|
||||||
|
path: endpoint.path ?? '/',
|
||||||
|
});
|
||||||
|
|
||||||
|
wss.on('listening', () => {
|
||||||
|
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
||||||
|
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, endpoint.path ?? '/');
|
||||||
|
});
|
||||||
|
|
||||||
|
wss.on('connection', (socket, request) => {
|
||||||
|
if (!isAuthorized(request, endpoint.accessToken ?? '')) {
|
||||||
|
safeClose(socket, 1008, 'invalid access token');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const role = endpoint.role ?? classifyForwardRole(request);
|
||||||
|
const conn: ForwardConnection = { socket, role };
|
||||||
|
this.forwardConnections.set(socket, conn);
|
||||||
|
|
||||||
|
socket.on('message', (raw) => {
|
||||||
|
void this.handleApiMessage(socket, role, raw);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('close', () => {
|
||||||
|
this.forwardConnections.delete(socket);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('error', (error) => {
|
||||||
|
log.warn('forward socket error: %s', error instanceof Error ? error.message : String(error));
|
||||||
|
});
|
||||||
|
|
||||||
|
this.sendBootstrapMetaEvents(socket, role);
|
||||||
|
});
|
||||||
|
|
||||||
|
wss.on('error', (error) => {
|
||||||
|
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||||
|
});
|
||||||
|
|
||||||
|
this.servers.push(wss);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private startReverseClients(): void {
|
||||||
|
for (const endpoint of this.config.wsClients) {
|
||||||
|
const role = endpoint.role ?? 'universal';
|
||||||
|
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
||||||
|
this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private connectReverseClient(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string, name?: string): void {
|
||||||
|
if (this.stopped) return;
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
'User-Agent': 'OneBot',
|
||||||
|
'X-Self-ID': this.context.uin,
|
||||||
|
'X-Client-Role': role,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (accessToken) {
|
||||||
|
headers.Authorization = `Bearer ${accessToken}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const socket = new WebSocket(endpointUrl, { headers });
|
||||||
|
const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs };
|
||||||
|
this.reverseConnections.add(conn);
|
||||||
|
|
||||||
|
socket.on('open', () => {
|
||||||
|
const label = name ? `[${name}] ` : '';
|
||||||
|
log.info('%sreverse connected %s', label, endpointUrl);
|
||||||
|
this.sendBootstrapMetaEvents(socket, role);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('message', (raw) => {
|
||||||
|
void this.handleApiMessage(socket, role, raw);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('close', () => {
|
||||||
|
this.reverseConnections.delete(conn);
|
||||||
|
if (this.stopped) return;
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
this.reconnectTimers.delete(timer);
|
||||||
|
this.connectReverseClient(endpointUrl, role, reconnectIntervalMs, accessToken, name);
|
||||||
|
}, reconnectIntervalMs);
|
||||||
|
timer.unref?.();
|
||||||
|
this.reconnectTimers.add(timer);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('error', (error) => {
|
||||||
|
log.warn('reverse error %s: %s', endpointUrl, error instanceof Error ? error.message : String(error));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: WebSocket.RawData): Promise<void> {
|
||||||
|
if (role !== 'api' && role !== 'universal') return;
|
||||||
|
|
||||||
|
const text = rawDataToString(raw);
|
||||||
|
if (!text) return;
|
||||||
|
|
||||||
|
const response = await this.context.api.processRequest(text);
|
||||||
|
safeSend(socket, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendBootstrapMetaEvents(socket: WebSocket, role: WsRole): void {
|
||||||
|
if (role !== 'event' && role !== 'universal') return;
|
||||||
|
|
||||||
|
const connectEvent = this.context.buildLifecycleEvent('connect');
|
||||||
|
const enableEvent = this.context.buildLifecycleEvent('enable');
|
||||||
|
const heartbeatEvent = this.context.buildHeartbeatEvent();
|
||||||
|
|
||||||
|
safeSend(socket, JSON.stringify(connectEvent));
|
||||||
|
safeSend(socket, JSON.stringify(enableEvent));
|
||||||
|
safeSend(socket, JSON.stringify(heartbeatEvent));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function classifyForwardRole(request: IncomingMessage): WsRole {
|
||||||
|
const path = parseRequestPath(request.url ?? '/');
|
||||||
|
if (path.endsWith('/api')) return 'api';
|
||||||
|
if (path.endsWith('/event')) return 'event';
|
||||||
|
return 'universal';
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRequestPath(urlValue: string): string {
|
||||||
|
try {
|
||||||
|
return new URL(urlValue, 'ws://127.0.0.1').pathname;
|
||||||
|
} catch {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||||
|
if (!token) return true;
|
||||||
|
// 1. Header auth
|
||||||
|
const rawAuth = request.headers.authorization;
|
||||||
|
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
|
||||||
|
if (auth === `Bearer ${token}`) return true;
|
||||||
|
|
||||||
|
// 2. Query string auth
|
||||||
|
try {
|
||||||
|
const url = new URL(request.url ?? '/', 'ws://127.0.0.1');
|
||||||
|
if (url.searchParams.get('access_token') === token) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rawDataToString(raw: WebSocket.RawData): string {
|
||||||
|
if (typeof raw === 'string') return raw;
|
||||||
|
if (raw instanceof Buffer) return raw.toString('utf8');
|
||||||
|
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
|
||||||
|
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
|
||||||
|
if (ArrayBuffer.isView(raw)) {
|
||||||
|
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeSend(socket: WebSocket, payload: string): void {
|
||||||
|
if (socket.readyState !== WebSocket.OPEN) return;
|
||||||
|
socket.send(payload, (error) => {
|
||||||
|
if (error) {
|
||||||
|
log.warn('send error: %s', error instanceof Error ? error.message : String(error));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
|
||||||
|
if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return;
|
||||||
|
socket.close(code, reason);
|
||||||
|
}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
// Runtime schema-based protobuf decode/encode.
|
||||||
|
// TypeScript equivalent of the C++ proto_field<N,T> DSL using plain schema objects.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
// const MyMessageSchema = {
|
||||||
|
// fromUin: { field: 1, type: 'uint32' as const },
|
||||||
|
// fromUid: { field: 2, type: 'string' as const },
|
||||||
|
// grp: { field: 8, type: 'message' as const, schema: GrpSchema },
|
||||||
|
// elements: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
|
||||||
|
// };
|
||||||
|
// type MyMessage = ProtoDecoded<typeof MyMessageSchema>;
|
||||||
|
// const msg = protoDecode(rawBytes, MyMessageSchema);
|
||||||
|
|
||||||
|
import { WireMessage, WireType, encodeVarint, encodeKey, decodeVarint } from './wire';
|
||||||
|
|
||||||
|
// --- Schema types ---
|
||||||
|
|
||||||
|
export type FieldType =
|
||||||
|
| 'bool' | 'int32' | 'uint32' | 'int64' | 'uint64'
|
||||||
|
| 'string' | 'bytes' | 'message'
|
||||||
|
| 'repeated_varint' | 'repeated_uint32' | 'repeated_string'
|
||||||
|
| 'repeated_bytes' | 'repeated_message';
|
||||||
|
|
||||||
|
export interface FieldDef {
|
||||||
|
field: number;
|
||||||
|
type: FieldType;
|
||||||
|
schema?: ProtoSchema; // required for 'message' / 'repeated_message'
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ProtoSchema = { [key: string]: FieldDef };
|
||||||
|
|
||||||
|
// --- Decoded type inference ---
|
||||||
|
|
||||||
|
type FieldTypeToTS<T extends FieldType, S extends ProtoSchema | undefined> =
|
||||||
|
T extends 'bool' ? boolean :
|
||||||
|
T extends 'int32' | 'uint32' ? number :
|
||||||
|
T extends 'int64' | 'uint64' ? bigint :
|
||||||
|
T extends 'string' ? string :
|
||||||
|
T extends 'bytes' ? Uint8Array :
|
||||||
|
T extends 'message' ? (S extends ProtoSchema ? ProtoDecoded<S> : Record<string, unknown>) :
|
||||||
|
T extends 'repeated_varint' | 'repeated_uint32' ? number[] :
|
||||||
|
T extends 'repeated_string' ? string[] :
|
||||||
|
T extends 'repeated_bytes' ? Uint8Array[] :
|
||||||
|
T extends 'repeated_message' ? (S extends ProtoSchema ? ProtoDecoded<S>[] : Record<string, unknown>[]) :
|
||||||
|
never;
|
||||||
|
|
||||||
|
type IsRepeated<T extends FieldType> = T extends `repeated_${string}` ? true : false;
|
||||||
|
|
||||||
|
type FieldValue<F extends FieldDef> =
|
||||||
|
IsRepeated<F['type']> extends true
|
||||||
|
? FieldTypeToTS<F['type'], F['schema']>
|
||||||
|
: FieldTypeToTS<F['type'], F['schema']> | undefined;
|
||||||
|
|
||||||
|
export type ProtoDecoded<S extends ProtoSchema> = {
|
||||||
|
[K in keyof S]: FieldValue<S[K]>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Decode ---
|
||||||
|
|
||||||
|
export function protoDecode<S extends ProtoSchema>(
|
||||||
|
data: Uint8Array | WireMessage,
|
||||||
|
schema: S
|
||||||
|
): ProtoDecoded<S> | null {
|
||||||
|
const wire = data instanceof WireMessage ? data : WireMessage.decode(data);
|
||||||
|
if (!wire) return null;
|
||||||
|
|
||||||
|
const result: Record<string, unknown> = {};
|
||||||
|
|
||||||
|
for (const [key, def] of Object.entries(schema)) {
|
||||||
|
switch (def.type) {
|
||||||
|
case 'bool': {
|
||||||
|
const v = wire.getVarint(def.field);
|
||||||
|
if (v !== null) result[key] = v !== 0n;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'int32': {
|
||||||
|
const v = wire.getInt32(def.field);
|
||||||
|
if (v !== null) result[key] = v;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'uint32': {
|
||||||
|
const v = wire.getUint32(def.field);
|
||||||
|
if (v !== null) result[key] = v;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'int64': {
|
||||||
|
const v = wire.getInt64(def.field);
|
||||||
|
if (v !== null) result[key] = v;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'uint64': {
|
||||||
|
const v = wire.getUint64(def.field);
|
||||||
|
if (v !== null) result[key] = v;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'string': {
|
||||||
|
const v = wire.getString(def.field);
|
||||||
|
if (v !== null) result[key] = v;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'bytes': {
|
||||||
|
const v = wire.getBytes(def.field);
|
||||||
|
if (v !== null) result[key] = v;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'message': {
|
||||||
|
const sub = wire.getMessage(def.field);
|
||||||
|
if (sub && def.schema) {
|
||||||
|
result[key] = protoDecode(sub, def.schema);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'repeated_varint': {
|
||||||
|
const vals = wire.getRepeatedVarint(def.field);
|
||||||
|
result[key] = vals.map(v => Number(BigInt.asIntN(32, v)));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'repeated_uint32': {
|
||||||
|
const vals = wire.getRepeatedVarint(def.field);
|
||||||
|
result[key] = vals.map(v => Number(BigInt.asUintN(32, v)));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'repeated_string': {
|
||||||
|
result[key] = wire.getRepeatedString(def.field);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'repeated_bytes': {
|
||||||
|
const flds = wire.fields(def.field);
|
||||||
|
result[key] = flds
|
||||||
|
.filter(f => f.wireType === WireType.LengthDelimited)
|
||||||
|
.map(f => f.bytes);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'repeated_message': {
|
||||||
|
if (!def.schema) { result[key] = []; break; }
|
||||||
|
const msgs = wire.getRepeatedMessage(def.field);
|
||||||
|
result[key] = msgs
|
||||||
|
.map(m => protoDecode(m, def.schema!))
|
||||||
|
.filter((m): m is NonNullable<typeof m> => m !== null);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result as ProtoDecoded<S>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Encode ---
|
||||||
|
|
||||||
|
export function protoEncode<S extends ProtoSchema>(
|
||||||
|
obj: Partial<ProtoDecoded<S>>,
|
||||||
|
schema: S
|
||||||
|
): Uint8Array {
|
||||||
|
const out: number[] = [];
|
||||||
|
const record = obj as Record<string, any>;
|
||||||
|
|
||||||
|
for (const [key, def] of Object.entries(schema)) {
|
||||||
|
const val = record[key];
|
||||||
|
if (val === undefined || val === null) continue;
|
||||||
|
|
||||||
|
switch (def.type) {
|
||||||
|
case 'bool': {
|
||||||
|
encodeKey(def.field, WireType.Varint, out);
|
||||||
|
encodeVarint(val ? 1 : 0, out);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'int32':
|
||||||
|
case 'uint32': {
|
||||||
|
encodeKey(def.field, WireType.Varint, out);
|
||||||
|
encodeVarint(val as number, out);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'int64':
|
||||||
|
case 'uint64': {
|
||||||
|
encodeKey(def.field, WireType.Varint, out);
|
||||||
|
encodeVarint(val as bigint, out);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'string': {
|
||||||
|
const encoded = new TextEncoder().encode(val as string);
|
||||||
|
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||||
|
encodeVarint(encoded.length, out);
|
||||||
|
for (const b of encoded) out.push(b);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'bytes': {
|
||||||
|
const buf = val as Uint8Array;
|
||||||
|
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||||
|
encodeVarint(buf.length, out);
|
||||||
|
for (const b of buf) out.push(b);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'message': {
|
||||||
|
if (!def.schema) break;
|
||||||
|
const nested = protoEncode(val as any, def.schema);
|
||||||
|
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||||
|
encodeVarint(nested.length, out);
|
||||||
|
for (const b of nested) out.push(b);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'repeated_varint':
|
||||||
|
case 'repeated_uint32': {
|
||||||
|
for (const v of val as number[]) {
|
||||||
|
encodeKey(def.field, WireType.Varint, out);
|
||||||
|
encodeVarint(v, out);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'repeated_string': {
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
for (const s of val as string[]) {
|
||||||
|
const encoded = encoder.encode(s);
|
||||||
|
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||||
|
encodeVarint(encoded.length, out);
|
||||||
|
for (const b of encoded) out.push(b);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'repeated_bytes': {
|
||||||
|
for (const buf of val as Uint8Array[]) {
|
||||||
|
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||||
|
encodeVarint(buf.length, out);
|
||||||
|
for (const b of buf) out.push(b);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'repeated_message': {
|
||||||
|
if (!def.schema) break;
|
||||||
|
for (const item of val as any[]) {
|
||||||
|
const nested = protoEncode(item, def.schema);
|
||||||
|
encodeKey(def.field, WireType.LengthDelimited, out);
|
||||||
|
encodeVarint(nested.length, out);
|
||||||
|
for (const b of nested) out.push(b);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Uint8Array(out);
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
// Protobuf wire-format decoder/encoder.
|
||||||
|
// Generic decoder that works without .proto schemas — decodes any protobuf
|
||||||
|
// binary into a field_number → value tree structure.
|
||||||
|
// Port of src/protobuf/wire.h + wire.cpp
|
||||||
|
|
||||||
|
export enum WireType {
|
||||||
|
Varint = 0,
|
||||||
|
Fixed64 = 1,
|
||||||
|
LengthDelimited = 2,
|
||||||
|
Fixed32 = 5,
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WireField {
|
||||||
|
fieldNumber: number;
|
||||||
|
wireType: WireType;
|
||||||
|
varint: bigint; // Varint, Fixed64, Fixed32
|
||||||
|
bytes: Uint8Array; // LengthDelimited
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Varint decode ---
|
||||||
|
export function decodeVarint(data: Uint8Array, offset: number): [bigint, number] | null {
|
||||||
|
let result = 0n;
|
||||||
|
for (let i = 0; i < 10 && offset + i < data.length; i++) {
|
||||||
|
result |= BigInt(data[offset + i] & 0x7f) << BigInt(7 * i);
|
||||||
|
if ((data[offset + i] & 0x80) === 0) {
|
||||||
|
return [result, i + 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Varint encode ---
|
||||||
|
export function encodeVarint(value: bigint | number, out: number[]): void {
|
||||||
|
let v = typeof value === 'number' ? BigInt(value >>> 0) : value;
|
||||||
|
if (v < 0n) v = v + (1n << 64n); // treat as unsigned 64-bit
|
||||||
|
while (v >= 0x80n) {
|
||||||
|
out.push(Number(v & 0x7Fn) | 0x80);
|
||||||
|
v >>= 7n;
|
||||||
|
}
|
||||||
|
out.push(Number(v));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Key encode ---
|
||||||
|
export function encodeKey(fieldNumber: number, wireType: WireType, out: number[]): void {
|
||||||
|
encodeVarint(BigInt(fieldNumber) << 3n | BigInt(wireType), out);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Field value helpers ---
|
||||||
|
export function fieldAsInt32(f: WireField): number { return Number(BigInt.asIntN(32, f.varint)); }
|
||||||
|
export function fieldAsUint32(f: WireField): number { return Number(BigInt.asUintN(32, f.varint)); }
|
||||||
|
export function fieldAsInt64(f: WireField): bigint { return BigInt.asIntN(64, f.varint); }
|
||||||
|
export function fieldAsUint64(f: WireField): bigint { return f.varint; }
|
||||||
|
export function fieldAsBool(f: WireField): boolean { return f.varint !== 0n; }
|
||||||
|
export function fieldAsString(f: WireField): string {
|
||||||
|
return new TextDecoder().decode(f.bytes);
|
||||||
|
}
|
||||||
|
export function fieldAsBytes(f: WireField): Uint8Array {
|
||||||
|
return f.bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WireMessage {
|
||||||
|
private fields_: WireField[];
|
||||||
|
|
||||||
|
private constructor(fields: WireField[]) {
|
||||||
|
this.fields_ = fields;
|
||||||
|
}
|
||||||
|
|
||||||
|
static decode(data: Uint8Array): WireMessage | null {
|
||||||
|
if (!data || data.length === 0) return null;
|
||||||
|
|
||||||
|
const fields: WireField[] = [];
|
||||||
|
let pos = 0;
|
||||||
|
|
||||||
|
while (pos < data.length) {
|
||||||
|
const tagResult = decodeVarint(data, pos);
|
||||||
|
if (!tagResult) break;
|
||||||
|
const [tag, tagLen] = tagResult;
|
||||||
|
pos += tagLen;
|
||||||
|
|
||||||
|
const fieldNum = Number(tag >> 3n);
|
||||||
|
const wireType = Number(tag & 0x07n) as WireType;
|
||||||
|
|
||||||
|
if (fieldNum === 0) break;
|
||||||
|
|
||||||
|
const field: WireField = {
|
||||||
|
fieldNumber: fieldNum,
|
||||||
|
wireType,
|
||||||
|
varint: 0n,
|
||||||
|
bytes: new Uint8Array(0),
|
||||||
|
};
|
||||||
|
|
||||||
|
switch (wireType) {
|
||||||
|
case WireType.Varint: {
|
||||||
|
const valResult = decodeVarint(data, pos);
|
||||||
|
if (!valResult) return null;
|
||||||
|
field.varint = valResult[0];
|
||||||
|
pos += valResult[1];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case WireType.Fixed64: {
|
||||||
|
if (pos + 8 > data.length) return null;
|
||||||
|
const dv = new DataView(data.buffer, data.byteOffset + pos, 8);
|
||||||
|
field.varint = dv.getBigUint64(0, true);
|
||||||
|
pos += 8;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case WireType.Fixed32: {
|
||||||
|
if (pos + 4 > data.length) return null;
|
||||||
|
const dv = new DataView(data.buffer, data.byteOffset + pos, 4);
|
||||||
|
field.varint = BigInt(dv.getUint32(0, true));
|
||||||
|
pos += 4;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case WireType.LengthDelimited: {
|
||||||
|
const lenResult = decodeVarint(data, pos);
|
||||||
|
if (!lenResult) return null;
|
||||||
|
const fieldLen = Number(lenResult[0]);
|
||||||
|
pos += lenResult[1];
|
||||||
|
if (pos + fieldLen > data.length) return null;
|
||||||
|
field.bytes = data.subarray(pos, pos + fieldLen);
|
||||||
|
pos += fieldLen;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
fields.push(field);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new WireMessage(fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Single field access ---
|
||||||
|
|
||||||
|
field(num: number): WireField | null {
|
||||||
|
for (const f of this.fields_) {
|
||||||
|
if (f.fieldNumber === num) return f;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
has(num: number): boolean {
|
||||||
|
return this.field(num) !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getVarint(num: number): bigint | null {
|
||||||
|
const f = this.field(num);
|
||||||
|
if (!f || f.wireType !== WireType.Varint) return null;
|
||||||
|
return f.varint;
|
||||||
|
}
|
||||||
|
|
||||||
|
getInt32(num: number): number | null {
|
||||||
|
const v = this.getVarint(num);
|
||||||
|
return v !== null ? Number(BigInt.asIntN(32, v)) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getUint32(num: number): number | null {
|
||||||
|
const v = this.getVarint(num);
|
||||||
|
return v !== null ? Number(BigInt.asUintN(32, v)) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getInt64(num: number): bigint | null {
|
||||||
|
const v = this.getVarint(num);
|
||||||
|
return v !== null ? BigInt.asIntN(64, v) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getUint64(num: number): bigint | null {
|
||||||
|
return this.getVarint(num);
|
||||||
|
}
|
||||||
|
|
||||||
|
getString(num: number): string | null {
|
||||||
|
const f = this.field(num);
|
||||||
|
if (!f || f.wireType !== WireType.LengthDelimited) return null;
|
||||||
|
return fieldAsString(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
getBytes(num: number): Uint8Array | null {
|
||||||
|
const f = this.field(num);
|
||||||
|
if (!f || f.wireType !== WireType.LengthDelimited) return null;
|
||||||
|
return f.bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
getMessage(num: number): WireMessage | null {
|
||||||
|
const f = this.field(num);
|
||||||
|
if (!f || f.wireType !== WireType.LengthDelimited) return null;
|
||||||
|
return WireMessage.decode(f.bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Repeated field access ---
|
||||||
|
|
||||||
|
fields(num: number): WireField[] {
|
||||||
|
return this.fields_.filter(f => f.fieldNumber === num);
|
||||||
|
}
|
||||||
|
|
||||||
|
getRepeatedVarint(num: number): bigint[] {
|
||||||
|
const result: bigint[] = [];
|
||||||
|
for (const f of this.fields_) {
|
||||||
|
if (f.fieldNumber !== num) continue;
|
||||||
|
if (f.wireType === WireType.Varint) {
|
||||||
|
result.push(f.varint);
|
||||||
|
} else if (f.wireType === WireType.LengthDelimited) {
|
||||||
|
// Packed repeated varint
|
||||||
|
let pos = 0;
|
||||||
|
while (pos < f.bytes.length) {
|
||||||
|
const r = decodeVarint(f.bytes, pos);
|
||||||
|
if (!r) break;
|
||||||
|
result.push(r[0]);
|
||||||
|
pos += r[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
getRepeatedString(num: number): string[] {
|
||||||
|
const result: string[] = [];
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
for (const f of this.fields_) {
|
||||||
|
if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) {
|
||||||
|
result.push(decoder.decode(f.bytes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
getRepeatedMessage(num: number): WireMessage[] {
|
||||||
|
const result: WireMessage[] = [];
|
||||||
|
for (const f of this.fields_) {
|
||||||
|
if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) {
|
||||||
|
const sub = WireMessage.decode(f.bytes);
|
||||||
|
if (sub) result.push(sub);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Raw iteration ---
|
||||||
|
|
||||||
|
get allFields(): WireField[] { return this.fields_; }
|
||||||
|
get empty(): boolean { return this.fields_.length === 0; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
import type { PacketInfo } from './types';
|
||||||
|
|
||||||
|
const log = createLogger('NTQQ');
|
||||||
|
|
||||||
|
export type CmdCallback = (pkt: PacketInfo) => void;
|
||||||
|
|
||||||
|
export interface HookPacketInput {
|
||||||
|
seq: number;
|
||||||
|
error: number;
|
||||||
|
cmd: string;
|
||||||
|
uin: string;
|
||||||
|
body: Uint8Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NtqqHandler {
|
||||||
|
private cmdHandlers = new Map<string, CmdCallback[]>();
|
||||||
|
private cmdAllHandlers: CmdCallback[] = [];
|
||||||
|
|
||||||
|
registerCmd(cmd: string, cb: CmdCallback): void {
|
||||||
|
const arr = this.cmdHandlers.get(cmd) ?? [];
|
||||||
|
arr.push(cb);
|
||||||
|
this.cmdHandlers.set(cmd, arr);
|
||||||
|
}
|
||||||
|
registerCmdAll(cb: CmdCallback): void { this.cmdAllHandlers.push(cb); }
|
||||||
|
|
||||||
|
onHookPacket(pid: number, packet: HookPacketInput): void {
|
||||||
|
this.dispatchPacket({
|
||||||
|
pid,
|
||||||
|
uin: packet.uin,
|
||||||
|
serviceCmd: packet.cmd,
|
||||||
|
seqId: packet.seq,
|
||||||
|
retCode: packet.error,
|
||||||
|
fromClient: false,
|
||||||
|
body: Buffer.from(packet.body),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private dispatchPacket(pkt: PacketInfo): void {
|
||||||
|
const specific = this.cmdHandlers.get(pkt.serviceCmd);
|
||||||
|
if (specific) {
|
||||||
|
for (const cb of specific) {
|
||||||
|
try { cb(pkt); } catch (e) {
|
||||||
|
log.error('dispatch error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const cb of this.cmdAllHandlers) {
|
||||||
|
try { cb(pkt); } catch (e) {
|
||||||
|
log.error('dispatch error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export interface SendPacketResult {
|
||||||
|
success: boolean;
|
||||||
|
gotResponse: boolean;
|
||||||
|
errorCode: number;
|
||||||
|
errorMessage: string;
|
||||||
|
responseData: Buffer | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PacketSender {
|
||||||
|
sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise<SendPacketResult>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
export interface PacketInfo {
|
||||||
|
pid: number;
|
||||||
|
uin: string;
|
||||||
|
packetType?: number;
|
||||||
|
serviceCmd: string;
|
||||||
|
seqId: number;
|
||||||
|
retCode: number;
|
||||||
|
fromClient: boolean;
|
||||||
|
body: Uint8Array;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { loadOneBotConfig, makeDefaultOneBotConfig } from '../onebot/config';
|
||||||
|
|
||||||
|
describe('makeDefaultOneBotConfig', () => {
|
||||||
|
it('returns default config structure', () => {
|
||||||
|
const config = makeDefaultOneBotConfig();
|
||||||
|
expect(config.httpServers).toHaveLength(1);
|
||||||
|
expect(config.httpServers[0].host).toBe('0.0.0.0');
|
||||||
|
expect(config.httpServers[0].port).toBe(3000);
|
||||||
|
expect(config.httpPostEndpoints).toEqual([]);
|
||||||
|
expect(config.wsServers).toHaveLength(1);
|
||||||
|
expect(config.wsServers[0].port).toBe(3001);
|
||||||
|
expect(config.wsClients).toEqual([]);
|
||||||
|
expect(config.musicSignUrl).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { protoDecode, protoEncode, type ProtoSchema } from '../protobuf/decode';
|
||||||
|
import { WireMessage, encodeKey, encodeVarint, WireType } from '../protobuf/wire';
|
||||||
|
|
||||||
|
describe('protoDecode', () => {
|
||||||
|
const SimpleSchema = {
|
||||||
|
name: { field: 1, type: 'string' as const },
|
||||||
|
age: { field: 2, type: 'uint32' as const },
|
||||||
|
active: { field: 3, type: 'bool' as const },
|
||||||
|
};
|
||||||
|
|
||||||
|
function buildProto(): Uint8Array {
|
||||||
|
const out: number[] = [];
|
||||||
|
// field 1 string "Alice"
|
||||||
|
encodeKey(1, WireType.LengthDelimited, out);
|
||||||
|
const str = new TextEncoder().encode('Alice');
|
||||||
|
encodeVarint(str.length, out);
|
||||||
|
out.push(...str);
|
||||||
|
// field 2 uint32 = 30
|
||||||
|
encodeKey(2, WireType.Varint, out);
|
||||||
|
encodeVarint(30, out);
|
||||||
|
// field 3 bool = true
|
||||||
|
encodeKey(3, WireType.Varint, out);
|
||||||
|
encodeVarint(1, out);
|
||||||
|
return new Uint8Array(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
it('decodes all fields', () => {
|
||||||
|
const result = protoDecode(buildProto(), SimpleSchema);
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result!.name).toBe('Alice');
|
||||||
|
expect(result!.age).toBe(30);
|
||||||
|
expect(result!.active).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles missing fields', () => {
|
||||||
|
// Only field 1
|
||||||
|
const out: number[] = [];
|
||||||
|
encodeKey(1, WireType.LengthDelimited, out);
|
||||||
|
const str = new TextEncoder().encode('Bob');
|
||||||
|
encodeVarint(str.length, out);
|
||||||
|
out.push(...str);
|
||||||
|
|
||||||
|
const result = protoDecode(new Uint8Array(out), SimpleSchema);
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result!.name).toBe('Bob');
|
||||||
|
expect(result!.age).toBeUndefined();
|
||||||
|
expect(result!.active).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null for empty data', () => {
|
||||||
|
expect(protoDecode(new Uint8Array(0), SimpleSchema)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes nested messages', () => {
|
||||||
|
const InnerSchema = {
|
||||||
|
value: { field: 1, type: 'uint32' as const },
|
||||||
|
};
|
||||||
|
const OuterSchema = {
|
||||||
|
inner: { field: 1, type: 'message' as const, schema: InnerSchema },
|
||||||
|
};
|
||||||
|
|
||||||
|
// Build inner
|
||||||
|
const innerOut: number[] = [];
|
||||||
|
encodeKey(1, WireType.Varint, innerOut);
|
||||||
|
encodeVarint(99, innerOut);
|
||||||
|
|
||||||
|
// Build outer
|
||||||
|
const outerOut: number[] = [];
|
||||||
|
encodeKey(1, WireType.LengthDelimited, outerOut);
|
||||||
|
encodeVarint(innerOut.length, outerOut);
|
||||||
|
outerOut.push(...innerOut);
|
||||||
|
|
||||||
|
const result = protoDecode(new Uint8Array(outerOut), OuterSchema);
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result!.inner).not.toBeUndefined();
|
||||||
|
expect(result!.inner!.value).toBe(99);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes repeated messages', () => {
|
||||||
|
const ItemSchema = {
|
||||||
|
id: { field: 1, type: 'uint32' as const },
|
||||||
|
};
|
||||||
|
const ListSchema = {
|
||||||
|
items: { field: 1, type: 'repeated_message' as const, schema: ItemSchema },
|
||||||
|
};
|
||||||
|
|
||||||
|
const out: number[] = [];
|
||||||
|
for (const id of [1, 2, 3]) {
|
||||||
|
const itemOut: number[] = [];
|
||||||
|
encodeKey(1, WireType.Varint, itemOut);
|
||||||
|
encodeVarint(id, itemOut);
|
||||||
|
|
||||||
|
encodeKey(1, WireType.LengthDelimited, out);
|
||||||
|
encodeVarint(itemOut.length, out);
|
||||||
|
out.push(...itemOut);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = protoDecode(new Uint8Array(out), ListSchema);
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result!.items).toHaveLength(3);
|
||||||
|
expect(result!.items.map((i) => i.id)).toEqual([1, 2, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts WireMessage directly', () => {
|
||||||
|
const wire = WireMessage.decode(buildProto());
|
||||||
|
const result = protoDecode(wire!, SimpleSchema);
|
||||||
|
expect(result!.name).toBe('Alice');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('protoEncode', () => {
|
||||||
|
const SimpleSchema = {
|
||||||
|
name: { field: 1, type: 'string' as const },
|
||||||
|
age: { field: 2, type: 'uint32' as const },
|
||||||
|
active: { field: 3, type: 'bool' as const },
|
||||||
|
};
|
||||||
|
|
||||||
|
it('encodes and decodes roundtrip', () => {
|
||||||
|
const data = { name: 'Charlie', age: 25, active: true };
|
||||||
|
const encoded = protoEncode(data, SimpleSchema);
|
||||||
|
const decoded = protoDecode(encoded, SimpleSchema);
|
||||||
|
expect(decoded).not.toBeNull();
|
||||||
|
expect(decoded!.name).toBe('Charlie');
|
||||||
|
expect(decoded!.age).toBe(25);
|
||||||
|
expect(decoded!.active).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips undefined fields', () => {
|
||||||
|
const data = { name: 'Dave', age: undefined, active: undefined };
|
||||||
|
const encoded = protoEncode(data as any, SimpleSchema);
|
||||||
|
const decoded = protoDecode(encoded, SimpleSchema);
|
||||||
|
expect(decoded!.name).toBe('Dave');
|
||||||
|
expect(decoded!.age).toBeUndefined();
|
||||||
|
expect(decoded!.active).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes bytes', () => {
|
||||||
|
const ByteSchema = {
|
||||||
|
payload: { field: 1, type: 'bytes' as const },
|
||||||
|
};
|
||||||
|
const data = { payload: new Uint8Array([0xDE, 0xAD]) };
|
||||||
|
const encoded = protoEncode(data, ByteSchema);
|
||||||
|
const decoded = protoDecode(encoded, ByteSchema);
|
||||||
|
expect(decoded!.payload).toEqual(new Uint8Array([0xDE, 0xAD]));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes nested messages', () => {
|
||||||
|
const InnerSchema = {
|
||||||
|
value: { field: 1, type: 'uint32' as const },
|
||||||
|
};
|
||||||
|
const OuterSchema = {
|
||||||
|
inner: { field: 1, type: 'message' as const, schema: InnerSchema },
|
||||||
|
};
|
||||||
|
|
||||||
|
const data = { inner: { value: 42 } };
|
||||||
|
const encoded = protoEncode(data, OuterSchema);
|
||||||
|
const decoded = protoDecode(encoded, OuterSchema);
|
||||||
|
expect(decoded!.inner!.value).toBe(42);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes int64/uint64', () => {
|
||||||
|
const BigSchema = {
|
||||||
|
signed: { field: 1, type: 'int64' as const },
|
||||||
|
unsigned: { field: 2, type: 'uint64' as const },
|
||||||
|
};
|
||||||
|
const data = { signed: -1n, unsigned: 0xFFFFFFFFFFFFFFFFn };
|
||||||
|
const encoded = protoEncode(data, BigSchema);
|
||||||
|
const decoded = protoDecode(encoded, BigSchema);
|
||||||
|
expect(decoded!.signed).toBe(-1n);
|
||||||
|
expect(decoded!.unsigned).toBe(0xFFFFFFFFFFFFFFFFn);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { toHex, fromHex, hexPreview } from '../utils/hex';
|
||||||
|
|
||||||
|
describe('toHex', () => {
|
||||||
|
it('converts empty buffer', () => {
|
||||||
|
expect(toHex(new Uint8Array(0))).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('converts single byte', () => {
|
||||||
|
expect(toHex(new Uint8Array([0xff]))).toBe('ff');
|
||||||
|
expect(toHex(new Uint8Array([0x00]))).toBe('00');
|
||||||
|
expect(toHex(new Uint8Array([0x0a]))).toBe('0a');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('converts multiple bytes', () => {
|
||||||
|
expect(toHex(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))).toBe('deadbeef');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('works with Buffer', () => {
|
||||||
|
expect(toHex(Buffer.from([0x01, 0x23, 0x45]))).toBe('012345');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('fromHex', () => {
|
||||||
|
it('converts empty string', () => {
|
||||||
|
expect(fromHex('')).toEqual(Buffer.alloc(0));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('converts hex string', () => {
|
||||||
|
const buf = fromHex('deadbeef');
|
||||||
|
expect(buf).toEqual(Buffer.from([0xde, 0xad, 0xbe, 0xef]));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles uppercase', () => {
|
||||||
|
const buf = fromHex('DEADBEEF');
|
||||||
|
expect(buf).toEqual(Buffer.from([0xde, 0xad, 0xbe, 0xef]));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws on odd-length string', () => {
|
||||||
|
expect(() => fromHex('abc')).toThrow('Invalid hex string length');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('roundtrips with toHex', () => {
|
||||||
|
const original = Buffer.from([0x00, 0x7f, 0x80, 0xff]);
|
||||||
|
expect(fromHex(toHex(original))).toEqual(original);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('hexPreview', () => {
|
||||||
|
it('shows full hex for small data', () => {
|
||||||
|
const data = new Uint8Array([0xab, 0xcd]);
|
||||||
|
expect(hexPreview(data)).toBe('abcd');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('truncates with ellipsis', () => {
|
||||||
|
const data = new Uint8Array(128).fill(0xaa);
|
||||||
|
const preview = hexPreview(data, 4);
|
||||||
|
expect(preview).toBe('aaaaaaaa...');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('no ellipsis when exactly at limit', () => {
|
||||||
|
const data = new Uint8Array(4).fill(0xbb);
|
||||||
|
expect(hexPreview(data, 4)).toBe('bbbbbbbb');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../onebot/message-id';
|
||||||
|
|
||||||
|
describe('hashMessageIdInt32', () => {
|
||||||
|
it('returns consistent hash for same inputs', () => {
|
||||||
|
const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
|
||||||
|
const id2 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
|
||||||
|
expect(id1).toBe(id2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns non-zero', () => {
|
||||||
|
// The function ensures id !== 0 by setting it to 1
|
||||||
|
const id = hashMessageIdInt32(0, 0, '');
|
||||||
|
expect(id).not.toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns different values for different sequences', () => {
|
||||||
|
const id1 = hashMessageIdInt32(1, 12345, GROUP_MESSAGE_EVENT);
|
||||||
|
const id2 = hashMessageIdInt32(2, 12345, GROUP_MESSAGE_EVENT);
|
||||||
|
expect(id1).not.toBe(id2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns different values for different sessions', () => {
|
||||||
|
const id1 = hashMessageIdInt32(100, 11111, GROUP_MESSAGE_EVENT);
|
||||||
|
const id2 = hashMessageIdInt32(100, 22222, GROUP_MESSAGE_EVENT);
|
||||||
|
expect(id1).not.toBe(id2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns different values for different event names', () => {
|
||||||
|
const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
|
||||||
|
const id2 = hashMessageIdInt32(100, 12345, PRIVATE_MESSAGE_EVENT);
|
||||||
|
expect(id1).not.toBe(id2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 32-bit integer', () => {
|
||||||
|
const id = hashMessageIdInt32(999999, 123456789, GROUP_MESSAGE_EVENT);
|
||||||
|
expect(id).toBeGreaterThanOrEqual(-2147483648);
|
||||||
|
expect(id).toBeLessThanOrEqual(2147483647);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles non-finite inputs gracefully', () => {
|
||||||
|
const id1 = hashMessageIdInt32(NaN, 0, 'test');
|
||||||
|
const id2 = hashMessageIdInt32(Infinity, 0, 'test');
|
||||||
|
expect(typeof id1).toBe('number');
|
||||||
|
expect(typeof id2).toBe('number');
|
||||||
|
// Both should map to sequence=0
|
||||||
|
expect(id1).toBe(id2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { parseMessage } from '../onebot/message-parser';
|
||||||
|
|
||||||
|
describe('parseMessage', () => {
|
||||||
|
describe('plain text', () => {
|
||||||
|
it('parses simple text', async () => {
|
||||||
|
const result = await parseMessage('hello world', false);
|
||||||
|
expect(result).toEqual([{ type: 'text', text: 'hello world' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty for empty string', async () => {
|
||||||
|
const result = await parseMessage('', false);
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('autoEscape treats CQ codes as text', async () => {
|
||||||
|
const result = await parseMessage('[CQ:face,id=123]', true);
|
||||||
|
expect(result).toEqual([{ type: 'text', text: '[CQ:face,id=123]' }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('CQ code parsing', () => {
|
||||||
|
it('parses face CQ code', async () => {
|
||||||
|
const result = await parseMessage('[CQ:face,id=123]', false);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('face');
|
||||||
|
expect(result[0].faceId).toBe(123);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses at CQ code', async () => {
|
||||||
|
const result = await parseMessage('[CQ:at,qq=12345]', false);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('at');
|
||||||
|
expect(result[0].targetUin).toBe(12345);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses at all', async () => {
|
||||||
|
const result = await parseMessage('[CQ:at,qq=all]', false);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('at');
|
||||||
|
expect(result[0].targetUin).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses mixed text and CQ codes', async () => {
|
||||||
|
const result = await parseMessage('Hello [CQ:face,id=1] World', false);
|
||||||
|
expect(result).toHaveLength(3);
|
||||||
|
expect(result[0]).toEqual({ type: 'text', text: 'Hello ' });
|
||||||
|
expect(result[1].type).toBe('face');
|
||||||
|
expect(result[2]).toEqual({ type: 'text', text: ' World' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('unescapes CQ special chars', async () => {
|
||||||
|
const result = await parseMessage('a&b[c]d', false);
|
||||||
|
expect(result).toEqual([{ type: 'text', text: 'a&b[c]d' }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('JSON segment array', () => {
|
||||||
|
it('parses text segment', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'text', data: { text: 'hello' } }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toEqual([{ type: 'text', text: 'hello' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses face segment', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'face', data: { id: 123 } }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('face');
|
||||||
|
expect(result[0].faceId).toBe(123);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses image segment', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'image', data: { file: 'https://example.com/img.png' } }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('image');
|
||||||
|
expect(result[0].url).toBe('https://example.com/img.png');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses at segment', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'at', data: { qq: 12345 } }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('at');
|
||||||
|
expect(result[0].targetUin).toBe(12345);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses multiple segments', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[
|
||||||
|
{ type: 'text', data: { text: 'hi ' } },
|
||||||
|
{ type: 'at', data: { qq: 999 } },
|
||||||
|
{ type: 'text', data: { text: ' there' } },
|
||||||
|
] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(3);
|
||||||
|
expect(result[0].type).toBe('text');
|
||||||
|
expect(result[1].type).toBe('at');
|
||||||
|
expect(result[2].type).toBe('text');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips unknown segment types', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[
|
||||||
|
{ type: 'text', data: { text: 'ok' } },
|
||||||
|
{ type: 'unknown_type_xyz', data: {} },
|
||||||
|
] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('text');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('special segments', () => {
|
||||||
|
it('parses json segment', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'json', data: { data: '{"app":"test"}' } }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('json');
|
||||||
|
expect(result[0].text).toBe('{"app":"test"}');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses reply segment with resolveReplySequence', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'reply', data: { id: 42 } }] as any,
|
||||||
|
false,
|
||||||
|
{ resolveReplySequence: (id) => id === 42 ? 100 : null },
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('reply');
|
||||||
|
expect(result[0].replySeq).toBe(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses share as json card', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'share', data: { url: 'https://example.com', title: 'Test' } }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('json');
|
||||||
|
const parsed = JSON.parse(result[0].text);
|
||||||
|
expect(parsed.app).toBe('com.tencent.structmsg');
|
||||||
|
expect(parsed.meta.news.title).toBe('Test');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses rps as face', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'rps', data: {} }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('face');
|
||||||
|
expect(result[0].faceId).toBe(359);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses dice as face', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'dice', data: {} }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('face');
|
||||||
|
expect(result[0].faceId).toBe(358);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses shake as poke', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'shake', data: {} }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('poke');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores anonymous segment', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[
|
||||||
|
{ type: 'anonymous', data: {} },
|
||||||
|
{ type: 'text', data: { text: 'hi' } },
|
||||||
|
] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('text');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses location as json card', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'location', data: { lat: '39.9', lon: '116.3', title: 'Beijing' } }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('json');
|
||||||
|
const parsed = JSON.parse(result[0].text);
|
||||||
|
expect(parsed.app).toBe('com.tencent.map');
|
||||||
|
expect(parsed.meta.Location.lat).toBe('39.9');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses contact as json card', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'contact', data: { type: 'group', id: '12345' } }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].type).toBe('json');
|
||||||
|
const parsed = JSON.parse(result[0].text);
|
||||||
|
expect(parsed.meta.contact.type).toBe('group');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('single segment object', () => {
|
||||||
|
it('parses single segment object', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
{ type: 'text', data: { text: 'single' } } as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toEqual([{ type: 'text', text: 'single' }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('edge cases', () => {
|
||||||
|
it('returns empty for null', async () => {
|
||||||
|
const result = await parseMessage(null as any, false);
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty for number', async () => {
|
||||||
|
const result = await parseMessage(42 as any, false);
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import {
|
||||||
|
WireType,
|
||||||
|
WireMessage,
|
||||||
|
decodeVarint,
|
||||||
|
encodeVarint,
|
||||||
|
encodeKey,
|
||||||
|
fieldAsInt32,
|
||||||
|
fieldAsUint32,
|
||||||
|
fieldAsString,
|
||||||
|
fieldAsBool,
|
||||||
|
} from '../protobuf/wire';
|
||||||
|
|
||||||
|
// Helper to build bytes from number array
|
||||||
|
function bytes(...vals: number[]): Uint8Array {
|
||||||
|
return new Uint8Array(vals);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('decodeVarint', () => {
|
||||||
|
it('decodes single-byte varint', () => {
|
||||||
|
const result = decodeVarint(bytes(0x05), 0);
|
||||||
|
expect(result).toEqual([5n, 1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes zero', () => {
|
||||||
|
const result = decodeVarint(bytes(0x00), 0);
|
||||||
|
expect(result).toEqual([0n, 1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes multi-byte varint (300)', () => {
|
||||||
|
// 300 = 0b100101100 => 0xAC 0x02
|
||||||
|
const result = decodeVarint(bytes(0xac, 0x02), 0);
|
||||||
|
expect(result).toEqual([300n, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes with offset', () => {
|
||||||
|
const result = decodeVarint(bytes(0xff, 0x01), 1);
|
||||||
|
expect(result).toEqual([1n, 1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null on empty data', () => {
|
||||||
|
const result = decodeVarint(bytes(), 0);
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('encodeVarint', () => {
|
||||||
|
it('encodes small number', () => {
|
||||||
|
const out: number[] = [];
|
||||||
|
encodeVarint(5, out);
|
||||||
|
expect(out).toEqual([5]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes 300', () => {
|
||||||
|
const out: number[] = [];
|
||||||
|
encodeVarint(300, out);
|
||||||
|
expect(out).toEqual([0xac, 0x02]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes bigint', () => {
|
||||||
|
const out: number[] = [];
|
||||||
|
encodeVarint(300n, out);
|
||||||
|
expect(out).toEqual([0xac, 0x02]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('roundtrips', () => {
|
||||||
|
for (const val of [0, 1, 127, 128, 300, 65535, 2147483647]) {
|
||||||
|
const out: number[] = [];
|
||||||
|
encodeVarint(val, out);
|
||||||
|
const [decoded] = decodeVarint(new Uint8Array(out), 0)!;
|
||||||
|
expect(Number(decoded)).toBe(val);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('encodeKey', () => {
|
||||||
|
it('encodes field 1 varint', () => {
|
||||||
|
const out: number[] = [];
|
||||||
|
encodeKey(1, WireType.Varint, out);
|
||||||
|
expect(out).toEqual([0x08]); // (1 << 3) | 0 = 8
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes field 2 length-delimited', () => {
|
||||||
|
const out: number[] = [];
|
||||||
|
encodeKey(2, WireType.LengthDelimited, out);
|
||||||
|
expect(out).toEqual([0x12]); // (2 << 3) | 2 = 18
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('WireMessage', () => {
|
||||||
|
// Build a simple protobuf: field 1 = varint 150, field 2 = string "testing"
|
||||||
|
function buildSimpleMessage(): Uint8Array {
|
||||||
|
const out: number[] = [];
|
||||||
|
// field 1, varint = 150
|
||||||
|
encodeKey(1, WireType.Varint, out);
|
||||||
|
encodeVarint(150, out);
|
||||||
|
// field 2, string = "testing"
|
||||||
|
encodeKey(2, WireType.LengthDelimited, out);
|
||||||
|
const str = new TextEncoder().encode('testing');
|
||||||
|
encodeVarint(str.length, out);
|
||||||
|
out.push(...str);
|
||||||
|
return new Uint8Array(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
it('decodes empty data returns null', () => {
|
||||||
|
expect(WireMessage.decode(new Uint8Array(0))).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes varint field', () => {
|
||||||
|
const msg = WireMessage.decode(buildSimpleMessage());
|
||||||
|
expect(msg).not.toBeNull();
|
||||||
|
expect(msg!.getUint32(1)).toBe(150);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes string field', () => {
|
||||||
|
const msg = WireMessage.decode(buildSimpleMessage());
|
||||||
|
expect(msg).not.toBeNull();
|
||||||
|
expect(msg!.getString(2)).toBe('testing');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null for missing fields', () => {
|
||||||
|
const msg = WireMessage.decode(buildSimpleMessage());
|
||||||
|
expect(msg!.getUint32(99)).toBeNull();
|
||||||
|
expect(msg!.getString(99)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('has() works', () => {
|
||||||
|
const msg = WireMessage.decode(buildSimpleMessage());
|
||||||
|
expect(msg!.has(1)).toBe(true);
|
||||||
|
expect(msg!.has(2)).toBe(true);
|
||||||
|
expect(msg!.has(3)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes nested message', () => {
|
||||||
|
const inner: number[] = [];
|
||||||
|
encodeKey(1, WireType.Varint, inner);
|
||||||
|
encodeVarint(42, inner);
|
||||||
|
|
||||||
|
const outer: number[] = [];
|
||||||
|
encodeKey(3, WireType.LengthDelimited, outer);
|
||||||
|
encodeVarint(inner.length, outer);
|
||||||
|
outer.push(...inner);
|
||||||
|
|
||||||
|
const msg = WireMessage.decode(new Uint8Array(outer));
|
||||||
|
const nested = msg!.getMessage(3);
|
||||||
|
expect(nested).not.toBeNull();
|
||||||
|
expect(nested!.getUint32(1)).toBe(42);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles repeated fields', () => {
|
||||||
|
const out: number[] = [];
|
||||||
|
for (const v of [10, 20, 30]) {
|
||||||
|
encodeKey(1, WireType.Varint, out);
|
||||||
|
encodeVarint(v, out);
|
||||||
|
}
|
||||||
|
const msg = WireMessage.decode(new Uint8Array(out));
|
||||||
|
const vals = msg!.getRepeatedVarint(1);
|
||||||
|
expect(vals.map(Number)).toEqual([10, 20, 30]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('field helpers work correctly', () => {
|
||||||
|
const out: number[] = [];
|
||||||
|
encodeKey(1, WireType.Varint, out);
|
||||||
|
encodeVarint(1, out); // bool true
|
||||||
|
encodeKey(2, WireType.Varint, out);
|
||||||
|
encodeVarint(0xFFFFFFFF, out); // uint32 max
|
||||||
|
|
||||||
|
const msg = WireMessage.decode(new Uint8Array(out))!;
|
||||||
|
const f1 = msg.field(1)!;
|
||||||
|
const f2 = msg.field(2)!;
|
||||||
|
|
||||||
|
expect(fieldAsBool(f1)).toBe(true);
|
||||||
|
expect(fieldAsUint32(f2)).toBe(0xFFFFFFFF);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
const HEX_CHARS = '0123456789abcdef';
|
||||||
|
|
||||||
|
export function toHex(data: Uint8Array | Buffer): string {
|
||||||
|
let h = '';
|
||||||
|
for (const b of data) {
|
||||||
|
h += HEX_CHARS[b >> 4];
|
||||||
|
h += HEX_CHARS[b & 0xf];
|
||||||
|
}
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
|
||||||
|
const limit = Math.max(0, Math.min(maxBytes, data.length));
|
||||||
|
const head = toHex(data.subarray(0, limit));
|
||||||
|
return data.length > limit ? `${head}...` : head;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fromHex(hex: string): Buffer {
|
||||||
|
if (hex.length % 2 !== 0) throw new Error('Invalid hex string length');
|
||||||
|
const buf = Buffer.alloc(hex.length / 2);
|
||||||
|
for (let i = 0; i < buf.length; i++) {
|
||||||
|
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||||
|
}
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import { format } from 'util';
|
||||||
|
|
||||||
|
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||||
|
|
||||||
|
interface LogOptions {
|
||||||
|
scope: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||||
|
debug: 10,
|
||||||
|
info: 20,
|
||||||
|
success: 25,
|
||||||
|
warn: 30,
|
||||||
|
error: 40,
|
||||||
|
};
|
||||||
|
|
||||||
|
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||||
|
debug: 'DEBUG',
|
||||||
|
info: 'INFO',
|
||||||
|
success: 'OK',
|
||||||
|
warn: 'WARN',
|
||||||
|
error: 'ERROR',
|
||||||
|
};
|
||||||
|
|
||||||
|
const COLOR_CODE: Record<LogLevel, number> = {
|
||||||
|
debug: 90,
|
||||||
|
info: 36,
|
||||||
|
success: 32,
|
||||||
|
warn: 33,
|
||||||
|
error: 31,
|
||||||
|
};
|
||||||
|
|
||||||
|
const COLOR_SCOPE = 35;
|
||||||
|
const COLOR_DIM = 2;
|
||||||
|
const COLOR_RESET = '\x1b[0m';
|
||||||
|
|
||||||
|
function resolveMinLevel(): LogLevel {
|
||||||
|
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||||
|
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
return 'info';
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIN_LEVEL = resolveMinLevel();
|
||||||
|
|
||||||
|
function shouldLog(level: LogLevel): boolean {
|
||||||
|
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[MIN_LEVEL];
|
||||||
|
}
|
||||||
|
|
||||||
|
function useColor(): boolean {
|
||||||
|
if (process.env.NO_COLOR === '1') return false;
|
||||||
|
return Boolean(process.stdout.isTTY);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ansi(code: number, text: string): string {
|
||||||
|
return `\x1b[${code}m${text}${COLOR_RESET}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentTime(): string {
|
||||||
|
const d = new Date();
|
||||||
|
const hh = String(d.getHours()).padStart(2, '0');
|
||||||
|
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||||
|
const ss = String(d.getSeconds()).padStart(2, '0');
|
||||||
|
return `${hh}:${mm}:${ss}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(level: LogLevel, scope: string, args: unknown[]): string {
|
||||||
|
const message = format(...args);
|
||||||
|
const ts = currentTime();
|
||||||
|
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||||
|
|
||||||
|
if (!useColor()) {
|
||||||
|
return `${ts} ${label} [${scope}] ${message}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cTs = ansi(COLOR_DIM, ts);
|
||||||
|
const cLabel = ansi(COLOR_CODE[level], label);
|
||||||
|
const cScope = ansi(COLOR_SCOPE, `[${scope}]`);
|
||||||
|
return `${cTs} ${cLabel} ${cScope} ${message}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||||
|
if (!shouldLog(level)) return;
|
||||||
|
const line = render(level, options.scope, args);
|
||||||
|
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||||
|
stream.write(line + '\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Logger {
|
||||||
|
debug: (...args: unknown[]) => void;
|
||||||
|
info: (...args: unknown[]) => void;
|
||||||
|
success: (...args: unknown[]) => void;
|
||||||
|
warn: (...args: unknown[]) => void;
|
||||||
|
error: (...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createLogger(scope: string): Logger {
|
||||||
|
const options: LogOptions = { scope };
|
||||||
|
return {
|
||||||
|
debug: (...args: unknown[]) => emit('debug', options, args),
|
||||||
|
info: (...args: unknown[]) => emit('info', options, args),
|
||||||
|
success: (...args: unknown[]) => emit('success', options, args),
|
||||||
|
warn: (...args: unknown[]) => emit('warn', options, args),
|
||||||
|
error: (...args: unknown[]) => emit('error', options, args),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import { serve } from '@hono/node-server';
|
||||||
|
import { serveStatic } from '@hono/node-server/serve-static';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
import { randomBytes } from 'crypto';
|
||||||
|
import type { OneBotManager } from '../onebot/manager';
|
||||||
|
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
||||||
|
import type { OneBotConfig } from '../onebot/types';
|
||||||
|
import type { HookManager } from '../hook/hook-manager';
|
||||||
|
import path from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
|
const log = createLogger('WebUI');
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
// Session token store: token -> expiry timestamp (24h)
|
||||||
|
const sessionTokens = new Map<string, number>();
|
||||||
|
|
||||||
|
// Login attempt tracker: ip -> { count, resetAt }
|
||||||
|
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
|
||||||
|
|
||||||
|
const LOGIN_MAX_ATTEMPTS = 5;
|
||||||
|
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000; // 15 minutes
|
||||||
|
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
|
||||||
|
function purgeExpiredTokens() {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [token, expiry] of sessionTokens) {
|
||||||
|
if (now > expiry) sessionTokens.delete(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getClientIp(req: Request): string {
|
||||||
|
return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hookManager?: HookManager) {
|
||||||
|
const app = new Hono();
|
||||||
|
|
||||||
|
// Generate random password (printed once at startup)
|
||||||
|
const randomPassword = randomBytes(8).toString('hex');
|
||||||
|
log.info(`=========================================`);
|
||||||
|
log.info(`WebUI 安全认证`);
|
||||||
|
log.info(`默认用户: admin`);
|
||||||
|
log.info(`临时密码: ${randomPassword}`);
|
||||||
|
log.info(`=========================================`);
|
||||||
|
|
||||||
|
// API Auth middleware
|
||||||
|
app.use('/api/*', async (c, next) => {
|
||||||
|
if (c.req.path === '/api/login') {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const authHeader = c.req.header('Authorization');
|
||||||
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||||
|
return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
purgeExpiredTokens();
|
||||||
|
const token = authHeader.slice(7);
|
||||||
|
const expiry = sessionTokens.get(token);
|
||||||
|
if (!expiry || Date.now() > expiry) {
|
||||||
|
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Login Endpoint with rate limiting
|
||||||
|
app.post('/api/login', async (c) => {
|
||||||
|
const ip = getClientIp(c.req.raw);
|
||||||
|
const now = Date.now();
|
||||||
|
const attempt = loginAttempts.get(ip);
|
||||||
|
|
||||||
|
if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) {
|
||||||
|
const waitSec = Math.ceil((attempt.resetAt - now) / 1000);
|
||||||
|
return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { password } = await c.req.json();
|
||||||
|
if (password === randomPassword) {
|
||||||
|
loginAttempts.delete(ip);
|
||||||
|
purgeExpiredTokens();
|
||||||
|
const token = randomBytes(32).toString('hex');
|
||||||
|
sessionTokens.set(token, now + TOKEN_TTL_MS);
|
||||||
|
return c.json({ success: true, token });
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS };
|
||||||
|
current.count += 1;
|
||||||
|
if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS;
|
||||||
|
loginAttempts.set(ip, current);
|
||||||
|
|
||||||
|
return c.json({ success: false, message: '密码错误' }, 401);
|
||||||
|
} catch {
|
||||||
|
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// API Routes
|
||||||
|
app.get('/api/status', (c) => {
|
||||||
|
return c.json({ status: 'running' });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/qq-list', (c) => {
|
||||||
|
const instances = oneBotManager.getInstances();
|
||||||
|
const list = instances.map(inst => ({
|
||||||
|
uin: inst.uin,
|
||||||
|
nickname: inst.qqInfo.nickname
|
||||||
|
}));
|
||||||
|
return c.json({ list });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/processes', async (c) => {
|
||||||
|
if (!hookManager) return c.json({ list: [] });
|
||||||
|
try {
|
||||||
|
return c.json({ list: await hookManager.listProcesses() });
|
||||||
|
} catch (err) {
|
||||||
|
return c.json({ list: [], message: err instanceof Error ? err.message : String(err) }, 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/processes/:pid/load', async (c) => {
|
||||||
|
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||||
|
const pid = Number(c.req.param('pid'));
|
||||||
|
if (!Number.isInteger(pid) || pid <= 0) {
|
||||||
|
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const processInfo = await hookManager.loadProcess(pid);
|
||||||
|
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||||
|
} catch (err) {
|
||||||
|
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/processes/:pid/unload', async (c) => {
|
||||||
|
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||||
|
const pid = Number(c.req.param('pid'));
|
||||||
|
if (!Number.isInteger(pid) || pid <= 0) {
|
||||||
|
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const processInfo = await hookManager.unloadProcess(pid);
|
||||||
|
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||||
|
} catch (err) {
|
||||||
|
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/config/:uin', (c) => {
|
||||||
|
const uin = c.req.param('uin');
|
||||||
|
const config = loadOneBotConfig(uin);
|
||||||
|
return c.json({ config });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/config/:uin', async (c) => {
|
||||||
|
try {
|
||||||
|
const uin = c.req.param('uin');
|
||||||
|
const body = await c.req.json() as OneBotConfig;
|
||||||
|
saveOneBotConfig(uin, body);
|
||||||
|
log.info(`Updated OneBot config for UIN: ${uin}`);
|
||||||
|
return c.json({ success: true, message: '配置保存成功,将在下次会话重连时生效。' });
|
||||||
|
} catch (err) {
|
||||||
|
return c.json({ success: false, message: String(err) }, 400);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Serve static files generated by the React frontend
|
||||||
|
const staticRoot = path.join(__dirname, 'client');
|
||||||
|
app.use('/*', serveStatic({ root: staticRoot }));
|
||||||
|
|
||||||
|
serve({
|
||||||
|
fetch: app.fetch,
|
||||||
|
port
|
||||||
|
}, (info) => {
|
||||||
|
log.info(`WebUI server is listening on http://localhost:${info.port}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
try:
|
||||||
|
import websockets
|
||||||
|
except ImportError:
|
||||||
|
print("Missing dependency: websockets")
|
||||||
|
print("Install with: pip install websockets")
|
||||||
|
sys.exit(2)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(description="OneBot WS API smoke test")
|
||||||
|
parser.add_argument("--url", default="ws://127.0.0.1:3001/", help="OneBot WebSocket URL")
|
||||||
|
parser.add_argument("--token", default="", help="Bearer token if OneBot accessToken is set")
|
||||||
|
parser.add_argument("--group-id", type=int, default=1081372778, help="Target group_id for send_group_msg")
|
||||||
|
parser.add_argument("--message", default="hello from snowluma from refactor", help="Message text to send")
|
||||||
|
parser.add_argument("--timeout", type=float, default=20.0, help="Per-request timeout seconds")
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
async def recv_json(ws: Any, timeout: float) -> Dict[str, Any]:
|
||||||
|
raw = await asyncio.wait_for(ws.recv(), timeout)
|
||||||
|
if isinstance(raw, bytes):
|
||||||
|
raw = raw.decode("utf-8", errors="replace")
|
||||||
|
return json.loads(raw)
|
||||||
|
|
||||||
|
|
||||||
|
async def call_api(ws: Any, action: str, params: Dict[str, Any], timeout: float) -> Dict[str, Any]:
|
||||||
|
echo = f"py-{action}-{uuid.uuid4().hex[:8]}"
|
||||||
|
payload = {
|
||||||
|
"action": action,
|
||||||
|
"params": params,
|
||||||
|
"echo": echo,
|
||||||
|
}
|
||||||
|
await ws.send(json.dumps(payload, ensure_ascii=False))
|
||||||
|
|
||||||
|
while True:
|
||||||
|
resp = await recv_json(ws, timeout)
|
||||||
|
if resp.get("echo") == echo:
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
def short_json(data: Dict[str, Any], max_len: int = 240) -> str:
|
||||||
|
text = json.dumps(data, ensure_ascii=False)
|
||||||
|
if len(text) <= max_len:
|
||||||
|
return text
|
||||||
|
return text[:max_len] + "..."
|
||||||
|
|
||||||
|
|
||||||
|
async def main() -> int:
|
||||||
|
args = parse_args()
|
||||||
|
|
||||||
|
headers = {}
|
||||||
|
if args.token:
|
||||||
|
headers["Authorization"] = f"Bearer {args.token}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with websockets.connect(args.url, additional_headers=headers, max_size=20 * 1024 * 1024) as ws:
|
||||||
|
try:
|
||||||
|
first = await recv_json(ws, 1.0)
|
||||||
|
print("[WS] first event:", short_json(first))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
status = await call_api(ws, "get_status", {}, args.timeout)
|
||||||
|
print("[API] get_status:", short_json(status))
|
||||||
|
|
||||||
|
groups = await call_api(ws, "get_group_list", {}, args.timeout)
|
||||||
|
group_count = len(groups.get("data", [])) if isinstance(groups.get("data"), list) else -1
|
||||||
|
print(f"[API] get_group_list: group_count={group_count}")
|
||||||
|
|
||||||
|
send_resp = await call_api(
|
||||||
|
ws,
|
||||||
|
"send_group_msg",
|
||||||
|
{
|
||||||
|
"group_id": args.group_id,
|
||||||
|
"message": args.message,
|
||||||
|
},
|
||||||
|
args.timeout,
|
||||||
|
)
|
||||||
|
print("[API] send_group_msg:", short_json(send_resp))
|
||||||
|
|
||||||
|
ok = (
|
||||||
|
status.get("status") == "ok"
|
||||||
|
and groups.get("status") == "ok"
|
||||||
|
and send_resp.get("status") == "ok"
|
||||||
|
)
|
||||||
|
return 0 if ok else 1
|
||||||
|
except Exception as e:
|
||||||
|
print("[ERROR]", str(e))
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(asyncio.run(main()))
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"lib": ["ES2022"],
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"declaration": false,
|
||||||
|
"declarationMap": false,
|
||||||
|
"sourceMap": false,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"types": ["node"]
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist", "native", "src/tests"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { defineConfig, PluginOption, UserConfig } from 'vite';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
import path from 'path';
|
||||||
|
import { builtinModules } from 'module';
|
||||||
|
import cp from 'vite-plugin-cp';
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
const external = [
|
||||||
|
'ws'
|
||||||
|
];
|
||||||
|
|
||||||
|
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat();
|
||||||
|
|
||||||
|
const BaseConfigPlugin: PluginOption[] = [
|
||||||
|
cp({
|
||||||
|
targets: [
|
||||||
|
{ src: './launcher/*', dest: 'dist', flatten: true },
|
||||||
|
{ src: './native/*', dest: 'dist/native/', flatten: true },
|
||||||
|
]
|
||||||
|
})
|
||||||
|
];
|
||||||
|
|
||||||
|
const BaseConfig = (source_map: boolean = false) => defineConfig({
|
||||||
|
resolve: {
|
||||||
|
conditions: ['node', 'default'],
|
||||||
|
alias: {
|
||||||
|
'@': path.resolve(__dirname, 'src')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
build: {
|
||||||
|
sourcemap: source_map,
|
||||||
|
target: 'esnext',
|
||||||
|
minify: false,
|
||||||
|
lib: {
|
||||||
|
entry: {
|
||||||
|
index: path.resolve(__dirname, 'src/index.ts')
|
||||||
|
},
|
||||||
|
formats: ['es'],
|
||||||
|
fileName: (_, entryName) => `${entryName}.mjs`
|
||||||
|
},
|
||||||
|
rollupOptions: {
|
||||||
|
external: [...nodeModules, ...external]
|
||||||
|
},
|
||||||
|
outDir: 'dist',
|
||||||
|
emptyOutDir: true
|
||||||
|
},
|
||||||
|
define: {
|
||||||
|
__BUILD_WEBUI__: process.env.BUILD_WEBUI === 'true'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default defineConfig(({ mode }): UserConfig => {
|
||||||
|
if (mode === 'development') {
|
||||||
|
return {
|
||||||
|
...BaseConfig(true),
|
||||||
|
plugins: [...BaseConfigPlugin]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...BaseConfig(),
|
||||||
|
plugins: [...BaseConfigPlugin]
|
||||||
|
};
|
||||||
|
});
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# React + TypeScript + Vite
|
||||||
|
|
||||||
|
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||||
|
|
||||||
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||||
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||||
|
|
||||||
|
## React Compiler
|
||||||
|
|
||||||
|
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||||
|
|
||||||
|
## Expanding the ESLint configuration
|
||||||
|
|
||||||
|
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
|
||||||
|
// Remove tseslint.configs.recommended and replace with this
|
||||||
|
tseslint.configs.recommendedTypeChecked,
|
||||||
|
// Alternatively, use this for stricter rules
|
||||||
|
tseslint.configs.strictTypeChecked,
|
||||||
|
// Optionally, add this for stylistic rules
|
||||||
|
tseslint.configs.stylisticTypeChecked,
|
||||||
|
|
||||||
|
// Other configs...
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// eslint.config.js
|
||||||
|
import reactX from 'eslint-plugin-react-x'
|
||||||
|
import reactDom from 'eslint-plugin-react-dom'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
// Enable lint rules for React
|
||||||
|
reactX.configs['recommended-typescript'],
|
||||||
|
// Enable lint rules for React DOM
|
||||||
|
reactDom.configs.recommended,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
tseslint.configs.recommended,
|
||||||
|
reactHooks.configs.flat.recommended,
|
||||||
|
reactRefresh.configs.vite,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN" class="light" data-theme="light">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>SnowLuma</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&family=Noto+Sans+SC:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"name": "webui",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@heroui/react": "^3.0.2",
|
||||||
|
"@heroui/styles": "^3.0.2",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"framer-motion": "^12.38.0",
|
||||||
|
"lucide-react": "^1.8.0",
|
||||||
|
"react": "^19.2.5",
|
||||||
|
"react-dom": "^19.2.5",
|
||||||
|
"tailwind-merge": "^3.5.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^10.0.1",
|
||||||
|
"@tailwindcss/vite": "^4.2.2",
|
||||||
|
"@types/node": "^25.6.0",
|
||||||
|
"@types/react": "^19.2.14",
|
||||||
|
"@types/react-dom": "^19.2.3",
|
||||||
|
"@vitejs/plugin-react": "^6.0.1",
|
||||||
|
"eslint": "^10.2.0",
|
||||||
|
"eslint-plugin-react-hooks": "^7.0.1",
|
||||||
|
"eslint-plugin-react-refresh": "^0.5.2",
|
||||||
|
"globals": "^17.5.0",
|
||||||
|
"sass": "^1.99.0",
|
||||||
|
"tailwindcss": "^4.2.2",
|
||||||
|
"typescript": "catalog:",
|
||||||
|
"typescript-eslint": "^8.58.2",
|
||||||
|
"vite": "catalog:"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated
|
||||||
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||||
|
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||||
|
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||||
|
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 4.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
@@ -0,0 +1,469 @@
|
|||||||
|
.layout {
|
||||||
|
display: flex;
|
||||||
|
height: 100vh;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar {
|
||||||
|
width: 240px;
|
||||||
|
background: var(--bg-sidebar);
|
||||||
|
border-right: 1px solid var(--border-subtle);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
padding: 24px 0 0 0;
|
||||||
|
transition: background-color 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand {
|
||||||
|
padding: 0 24px;
|
||||||
|
margin-bottom: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand h1 {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-main);
|
||||||
|
background: linear-gradient(90deg, var(--color-primary), #818cf8);
|
||||||
|
-webkit-background-clip: text;
|
||||||
|
background-clip: text;
|
||||||
|
-webkit-text-fill-color: transparent;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-menu {
|
||||||
|
flex: 1;
|
||||||
|
padding: 0 16px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-item {
|
||||||
|
padding: 10px 16px;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-item:hover {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
color: var(--text-main);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-item.active {
|
||||||
|
background: var(--color-primary);
|
||||||
|
color: #fff;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar-footer {
|
||||||
|
padding: 16px;
|
||||||
|
border-top: 1px solid var(--border-subtle);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 8px 16px;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
transition: all 0.2s;
|
||||||
|
outline: none;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--color-primary);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
background: var(--color-primary-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ghost {
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ghost:hover {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
color: var(--text-main);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-outline {
|
||||||
|
background: transparent;
|
||||||
|
border-color: var(--border-subtle);
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-outline:hover {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
color: var(--text-main);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background: transparent;
|
||||||
|
border-color: var(--border-subtle);
|
||||||
|
color: var(--color-danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:hover {
|
||||||
|
background: var(--color-danger);
|
||||||
|
border-color: var(--color-danger);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-icon {
|
||||||
|
padding: 4px;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--bg-body);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
height: 60px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0 32px;
|
||||||
|
background: var(--bg-card);
|
||||||
|
border-bottom: 1px solid var(--border-subtle);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-input {
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
padding: 8px 14px;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
color: var(--text-main);
|
||||||
|
width: 260px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-input:focus {
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-dot {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--text-muted);
|
||||||
|
}
|
||||||
|
.status-dot.on { background: #10b981; }
|
||||||
|
.status-dot.off { background: var(--color-danger); }
|
||||||
|
|
||||||
|
.main-scroll {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
background: var(--bg-card);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
box-shadow: var(--shadow-sm);
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-label {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-value {
|
||||||
|
font-size: 2rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-main);
|
||||||
|
}
|
||||||
|
.status-ok {
|
||||||
|
color: #10b981;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Config Layout */
|
||||||
|
.config-layout {
|
||||||
|
display: flex;
|
||||||
|
gap: 24px;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.list-pane {
|
||||||
|
width: 280px;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pane-title {
|
||||||
|
font-size: 0.95rem;
|
||||||
|
color: var(--text-main);
|
||||||
|
margin-bottom: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qq-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qq-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qq-item:hover {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.qq-item.active {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
border-color: var(--border-active);
|
||||||
|
}
|
||||||
|
|
||||||
|
.qq-avatar {
|
||||||
|
width: 36px;
|
||||||
|
height: 36px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: linear-gradient(135deg, var(--color-primary), #818cf8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.qq-info {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qq-nik {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-main);
|
||||||
|
}
|
||||||
|
|
||||||
|
.qq-uin {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-pane {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 500px;
|
||||||
|
padding: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 100%;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-icon {
|
||||||
|
font-size: 2rem;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
margin-bottom: 32px;
|
||||||
|
border-bottom: 1px solid var(--border-subtle);
|
||||||
|
padding-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-title h2 {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
color: var(--text-main);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-subtitle {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-family: monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.save-status {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.save-status.ok { color: #10b981; }
|
||||||
|
|
||||||
|
.cfg-section {
|
||||||
|
margin-bottom: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cfg-section-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cfg-section-header h4 {
|
||||||
|
font-size: 1rem;
|
||||||
|
color: var(--text-main);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cfg-section-body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.endpoint-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
padding: 16px;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-group {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-group label {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-group input {
|
||||||
|
background: var(--bg-card);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
color: var(--text-main);
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-group input:focus {
|
||||||
|
border-color: var(--border-focus);
|
||||||
|
}
|
||||||
|
|
||||||
|
.endpoint-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
margin-top: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-muted {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Login Screen Override */
|
||||||
|
.login-screen {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 1000;
|
||||||
|
background: var(--bg-body);
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-card {
|
||||||
|
width: 380px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
padding: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-title {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
color: var(--text-main);
|
||||||
|
margin-bottom: 12px;
|
||||||
|
background: linear-gradient(90deg, var(--color-primary), #818cf8);
|
||||||
|
-webkit-background-clip: text;
|
||||||
|
background-clip: text;
|
||||||
|
-webkit-text-fill-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-desc {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-form {
|
||||||
|
width: 100%;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-submit-btn {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-error {
|
||||||
|
color: var(--color-danger);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// Token layer only — component styles live in Tailwind classes inside TSX
|
||||||
|
@use './styles/variables';
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { ThemeProvider } from './contexts/ThemeContext';
|
||||||
|
import { MainLayout } from './components/layout/MainLayout';
|
||||||
|
import { LoginPage } from './components/pages/LoginPage';
|
||||||
|
import { OverviewPage } from './components/pages/OverviewPage';
|
||||||
|
import { ConfigPage } from './components/pages/ConfigPage';
|
||||||
|
import type { QQInfo, OneBotConfig, HookProcessInfo } from './types';
|
||||||
|
|
||||||
|
const fetchApi = async (url: string, options: RequestInit = {}) => {
|
||||||
|
const token = localStorage.getItem('snowluma_token');
|
||||||
|
const headers = new Headers(options.headers || {});
|
||||||
|
if (token) headers.set('Authorization', `Bearer ${token}`);
|
||||||
|
return fetch(url, { ...options, headers });
|
||||||
|
};
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [status, setStatus] = useState('连接中');
|
||||||
|
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(
|
||||||
|
import.meta.env.VITE_SKIP_AUTH === 'true' ? true : null
|
||||||
|
);
|
||||||
|
const [activePage, setActivePage] = useState<'总览' | '配置'>('总览');
|
||||||
|
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
||||||
|
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
|
||||||
|
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
|
||||||
|
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
|
||||||
|
const [processActionStatus, setProcessActionStatus] = useState('');
|
||||||
|
const [selectedUin, setSelectedUin] = useState<string | null>(null);
|
||||||
|
const [config, setConfig] = useState<OneBotConfig | null>(null);
|
||||||
|
const [saveStatus, setSaveStatus] = useState('');
|
||||||
|
|
||||||
|
function checkStatus() {
|
||||||
|
fetchApi('/api/status')
|
||||||
|
.then(async (res) => {
|
||||||
|
if (res.status === 401) { setIsAuthenticated(false); setStatus('需要认证'); return; }
|
||||||
|
if (res.ok) {
|
||||||
|
setIsAuthenticated(true);
|
||||||
|
const data = await res.json();
|
||||||
|
setStatus(data.status === 'running' ? '已连接' : '已断开');
|
||||||
|
fetchQqList();
|
||||||
|
fetchProcesses();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Any other non-ok status (502, 500, etc.)
|
||||||
|
setIsAuthenticated(false);
|
||||||
|
setStatus('已断开');
|
||||||
|
})
|
||||||
|
.catch(() => { setStatus('已断开'); setIsAuthenticated(false); });
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (import.meta.env.VITE_SKIP_AUTH !== 'true') checkStatus();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isAuthenticated !== true) return;
|
||||||
|
fetchQqList();
|
||||||
|
fetchProcesses();
|
||||||
|
const timer = window.setInterval(() => {
|
||||||
|
fetchQqList();
|
||||||
|
fetchProcesses();
|
||||||
|
}, 3000);
|
||||||
|
return () => window.clearInterval(timer);
|
||||||
|
}, [isAuthenticated]);
|
||||||
|
|
||||||
|
const handleLogin = async (password: string) => {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ password }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (res.ok && data.success) {
|
||||||
|
localStorage.setItem('snowluma_token', data.token);
|
||||||
|
setIsAuthenticated(true);
|
||||||
|
checkStatus();
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
return { success: false, error: '认证失败,请检查控制台日志' };
|
||||||
|
} catch {
|
||||||
|
return { success: false, error: '内部错误,请检查后端运行状态' };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
localStorage.removeItem('snowluma_token');
|
||||||
|
setIsAuthenticated(false);
|
||||||
|
setStatus('需要认证');
|
||||||
|
setQqList([]);
|
||||||
|
setProcessList([]);
|
||||||
|
setConfig(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
async function fetchQqList() {
|
||||||
|
try {
|
||||||
|
const res = await fetchApi('/api/qq-list');
|
||||||
|
if (res.ok) { const data = await res.json(); setQqList(data.list || []); }
|
||||||
|
} catch (err) { console.error(err); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchProcesses() {
|
||||||
|
try {
|
||||||
|
const res = await fetchApi('/api/processes');
|
||||||
|
if (res.ok) { const data = await res.json(); setProcessList(data.list || []); }
|
||||||
|
} catch (err) { console.error(err); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadProcess = async (pid: number) => {
|
||||||
|
setProcessLoadingPid(pid);
|
||||||
|
setProcessActionStatus('正在手动映射加载 SnowLuma...');
|
||||||
|
try {
|
||||||
|
const res = await fetchApi(`/api/processes/${pid}/load`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({}),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
setProcessActionStatus(res.ok && data.success ? '已开始监听登录状态' : data.message || '加载失败');
|
||||||
|
await fetchProcesses();
|
||||||
|
await fetchQqList();
|
||||||
|
} catch {
|
||||||
|
setProcessActionStatus('网络错误,加载失败');
|
||||||
|
} finally {
|
||||||
|
setProcessLoadingPid(null);
|
||||||
|
setTimeout(() => setProcessActionStatus(''), 3000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const unloadProcess = async (pid: number) => {
|
||||||
|
setProcessUnloadingPid(pid);
|
||||||
|
setProcessActionStatus('正在卸载 SnowLuma...');
|
||||||
|
try {
|
||||||
|
const res = await fetchApi(`/api/processes/${pid}/unload`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({}),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
setProcessActionStatus(res.ok && data.success ? '已卸载 SnowLuma' : data.message || '卸载失败');
|
||||||
|
await fetchProcesses();
|
||||||
|
await fetchQqList();
|
||||||
|
} catch {
|
||||||
|
setProcessActionStatus('网络错误,卸载失败');
|
||||||
|
} finally {
|
||||||
|
setProcessUnloadingPid(null);
|
||||||
|
setTimeout(() => setProcessActionStatus(''), 3000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadConfig = async (uin: string) => {
|
||||||
|
setSelectedUin(uin);
|
||||||
|
setSaveStatus('');
|
||||||
|
setConfig(null);
|
||||||
|
try {
|
||||||
|
const res = await fetchApi(`/api/config/${uin}`);
|
||||||
|
if (res.ok) { const data = await res.json(); setConfig(data.config); }
|
||||||
|
} catch (err) { console.error(err); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveConfig = async () => {
|
||||||
|
if (!selectedUin || !config) return;
|
||||||
|
setSaveStatus('保存中...');
|
||||||
|
try {
|
||||||
|
const res = await fetchApi(`/api/config/${selectedUin}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(config),
|
||||||
|
});
|
||||||
|
setSaveStatus(res.ok ? '保存成功' : '保存出错');
|
||||||
|
setTimeout(() => setSaveStatus(''), 3000);
|
||||||
|
} catch {
|
||||||
|
setSaveStatus('网络错误');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Loading state
|
||||||
|
if (isAuthenticated === null) {
|
||||||
|
return (
|
||||||
|
<div className="h-screen flex items-center justify-center" style={{ background: 'var(--bg-body)' }}>
|
||||||
|
<div className="size-5 border-2 rounded-full animate-spin" style={{ borderColor: 'var(--border-subtle)', borderTopColor: 'var(--accent)' }} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login
|
||||||
|
if (isAuthenticated === false) {
|
||||||
|
return (
|
||||||
|
<ThemeProvider>
|
||||||
|
<LoginPage onLogin={handleLogin} />
|
||||||
|
</ThemeProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main app
|
||||||
|
return (
|
||||||
|
<ThemeProvider>
|
||||||
|
<MainLayout activePage={activePage} onNavigate={setActivePage} status={status} onLogout={handleLogout}>
|
||||||
|
{activePage === '总览' && (
|
||||||
|
<OverviewPage
|
||||||
|
qqList={qqList}
|
||||||
|
status={status}
|
||||||
|
processList={processList}
|
||||||
|
processLoadingPid={processLoadingPid}
|
||||||
|
processUnloadingPid={processUnloadingPid}
|
||||||
|
processActionStatus={processActionStatus}
|
||||||
|
onRefreshProcesses={fetchProcesses}
|
||||||
|
onLoadProcess={loadProcess}
|
||||||
|
onUnloadProcess={unloadProcess}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{activePage === '配置' && (
|
||||||
|
<ConfigPage
|
||||||
|
qqList={qqList}
|
||||||
|
selectedUin={selectedUin}
|
||||||
|
config={config}
|
||||||
|
saveStatus={saveStatus}
|
||||||
|
onSelectAccount={loadConfig}
|
||||||
|
onSave={saveConfig}
|
||||||
|
onConfigChange={setConfig}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</MainLayout>
|
||||||
|
</ThemeProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="usLine truncated
|
||||||
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,250 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { motion, AnimatePresence } from 'framer-motion';
|
||||||
|
import { Activity, LayoutDashboard, Settings, Sparkles } from 'lucide-react';
|
||||||
|
import { Sidebar } from './Sidebar';
|
||||||
|
import { useTheme } from '../../contexts/ThemeContext';
|
||||||
|
|
||||||
|
type Page = '总览' | '配置';
|
||||||
|
|
||||||
|
interface MainLayoutProps {
|
||||||
|
activePage: Page;
|
||||||
|
onNavigate: (page: Page) => void;
|
||||||
|
status: string;
|
||||||
|
onLogout: () => void;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageMeta: Record<Page, { title: string; subtitle: string; badge: string; icon: typeof LayoutDashboard }> = {
|
||||||
|
'总览': { title: '总览', subtitle: '查看当前接入的 QQ 账号及服务运行状态', badge: '控制台视图', icon: LayoutDashboard },
|
||||||
|
'配置': { title: '节点配置', subtitle: '管理 OneBot 协议端点与通信参数', badge: '协议编排', icon: Settings },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function MainLayout({ activePage, onNavigate, status, onLogout, children }: MainLayoutProps) {
|
||||||
|
const meta = pageMeta[activePage];
|
||||||
|
const { resolved } = useTheme();
|
||||||
|
const dark = resolved === 'dark';
|
||||||
|
const PageIcon = meta.icon;
|
||||||
|
const runtimeLabel = status === '已连接' ? '运行中' : status;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-screen w-screen flex overflow-hidden font-(--font-sans)" style={{ background: 'var(--bg-body)' }}>
|
||||||
|
{/* Full-screen ambient gradient — matches login page */}
|
||||||
|
<div
|
||||||
|
className="pointer-events-none fixed inset-0"
|
||||||
|
style={{
|
||||||
|
background: dark
|
||||||
|
? 'linear-gradient(135deg, rgba(8,11,18,1) 0%, rgba(10,16,27,1) 42%, rgba(7,10,17,1) 100%)'
|
||||||
|
: 'linear-gradient(135deg, #f8fbff 0%, #eef6ff 45%, #f9fafc 100%)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Animated orbs */}
|
||||||
|
<div className="pointer-events-none fixed inset-0 overflow-hidden">
|
||||||
|
<motion.div
|
||||||
|
className="absolute -left-24 -top-24 h-[60vh] w-[60vh] rounded-full"
|
||||||
|
style={{
|
||||||
|
background: dark
|
||||||
|
? 'radial-gradient(circle, rgba(56,189,248,0.12) 0%, transparent 68%)'
|
||||||
|
: 'radial-gradient(circle, rgba(56,189,248,0.18) 0%, transparent 70%)',
|
||||||
|
filter: 'blur(42px)',
|
||||||
|
}}
|
||||||
|
animate={{ scale: [1, 1.08, 1] }}
|
||||||
|
transition={{ duration: 10, ease: 'easeInOut', repeat: Infinity }}
|
||||||
|
/>
|
||||||
|
<motion.div
|
||||||
|
className="absolute -right-16 -bottom-32 h-[50vh] w-[50vh] rounded-full"
|
||||||
|
style={{
|
||||||
|
background: dark
|
||||||
|
? 'radial-gradient(circle, rgba(129,140,248,0.10) 0%, transparent 68%)'
|
||||||
|
: 'radial-gradient(circle, rgba(129,140,248,0.14) 0%, transparent 70%)',
|
||||||
|
filter: 'blur(52px)',
|
||||||
|
}}
|
||||||
|
animate={{ scale: [1, 1.12, 1] }}
|
||||||
|
transition={{ duration: 12, ease: 'easeInOut', repeat: Infinity, delay: 0.8 }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Sidebar */}
|
||||||
|
<Sidebar activePage={activePage} onNavigate={onNavigate} status={status} onLogout={onLogout} />
|
||||||
|
|
||||||
|
{/* Main content */}
|
||||||
|
<div className="flex-1 flex flex-col min-h-0 p-3 pl-0 z-10 relative">
|
||||||
|
<main
|
||||||
|
className="flex-1 overflow-y-auto rounded-2xl relative"
|
||||||
|
style={{
|
||||||
|
background: dark
|
||||||
|
? 'linear-gradient(135deg, rgba(8,13,22,0.72), rgba(14,20,32,0.82))'
|
||||||
|
: 'linear-gradient(135deg, rgba(255,255,255,0.68), rgba(255,255,255,0.85))',
|
||||||
|
border: '1px solid var(--glass-border)',
|
||||||
|
backdropFilter: 'blur(38px) saturate(1.35)',
|
||||||
|
WebkitBackdropFilter: 'blur(38px) saturate(1.35)',
|
||||||
|
boxShadow: dark
|
||||||
|
? '0 24px 80px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.05)'
|
||||||
|
: '0 20px 60px rgba(15,23,42,0.08), inset 0 1px 0 rgba(255,255,255,0.7)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Top highlight */}
|
||||||
|
<div className="absolute inset-x-0 top-0 h-px bg-linear-to-r from-transparent via-white/8 to-transparent rounded-t-2xl" />
|
||||||
|
|
||||||
|
{/* Grid texture overlay */}
|
||||||
|
<div
|
||||||
|
className="pointer-events-none absolute inset-0 rounded-2xl"
|
||||||
|
style={{
|
||||||
|
backgroundImage: dark
|
||||||
|
? 'linear-gradient(90deg, rgba(255,255,255,0.02) 1px, transparent 1px), linear-gradient(rgba(255,255,255,0.02) 1px, transparent 1px)'
|
||||||
|
: 'linear-gradient(90deg, rgba(15,23,42,0.03) 1px, transparent 1px), linear-gradient(rgba(15,23,42,0.03) 1px, transparent 1px)',
|
||||||
|
backgroundSize: '36px 36px',
|
||||||
|
maskImage: 'linear-gradient(180deg, rgba(0,0,0,0.35), transparent 60%)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Accent glow in corner */}
|
||||||
|
<motion.div
|
||||||
|
className="pointer-events-none absolute right-[12%] top-[8%] h-32 w-32 rounded-full"
|
||||||
|
style={{
|
||||||
|
background: 'radial-gradient(circle, rgba(56,189,248,0.18), transparent 68%)',
|
||||||
|
filter: 'blur(20px)',
|
||||||
|
}}
|
||||||
|
animate={{ scale: [1, 1.15, 1], opacity: [0.6, 1, 0.6] }}
|
||||||
|
transition={{ duration: 6, ease: 'easeInOut', repeat: Infinity }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="relative w-full min-h-full px-4 py-4 sm:px-6 sm:py-6 xl:px-8 2xl:px-10 flex flex-col">
|
||||||
|
{/* Page header */}
|
||||||
|
<AnimatePresence mode="wait">
|
||||||
|
<motion.header
|
||||||
|
key={meta.title + '_header'}
|
||||||
|
initial={{ opacity: 0, y: -10 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, y: 8 }}
|
||||||
|
transition={{ duration: 0.25 }}
|
||||||
|
className="mb-6"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="relative overflow-hidden rounded-[1.75rem] border px-4 py-4 sm:px-5 sm:py-5 xl:px-6"
|
||||||
|
style={{
|
||||||
|
background: dark
|
||||||
|
? 'linear-gradient(135deg, rgba(8,12,20,0.48), rgba(14,20,32,0.62))'
|
||||||
|
: 'linear-gradient(135deg, rgba(255,255,255,0.5), rgba(255,255,255,0.72))',
|
||||||
|
borderColor: 'var(--glass-border)',
|
||||||
|
boxShadow: dark
|
||||||
|
? '0 18px 48px rgba(0,0,0,0.26), inset 0 1px 0 rgba(255,255,255,0.04)'
|
||||||
|
: '0 14px 40px rgba(15,23,42,0.05), inset 0 1px 0 rgba(255,255,255,0.5)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="pointer-events-none absolute inset-0"
|
||||||
|
style={{
|
||||||
|
backgroundImage: dark
|
||||||
|
? 'linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px), linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px)'
|
||||||
|
: 'linear-gradient(90deg, rgba(15,23,42,0.03) 1px, transparent 1px), linear-gradient(rgba(15,23,42,0.03) 1px, transparent 1px)',
|
||||||
|
backgroundSize: '34px 34px',
|
||||||
|
maskImage: 'linear-gradient(90deg, rgba(0,0,0,0.45), transparent 85%)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<motion.div
|
||||||
|
className="pointer-events-none absolute -right-8 -top-10 h-28 w-28 rounded-full"
|
||||||
|
style={{
|
||||||
|
background: 'radial-gradient(circle, rgba(56,189,248,0.16), transparent 68%)',
|
||||||
|
filter: 'blur(18px)',
|
||||||
|
}}
|
||||||
|
animate={{ scale: [1, 1.12, 1], opacity: [0.45, 0.78, 0.45] }}
|
||||||
|
transition={{ duration: 6, ease: 'easeInOut', repeat: Infinity }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="relative flex items-center justify-between gap-6">
|
||||||
|
<div className="flex min-w-0 items-center gap-4">
|
||||||
|
{/* Icon */}
|
||||||
|
<div
|
||||||
|
className="relative flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl border"
|
||||||
|
style={{
|
||||||
|
borderColor: 'color-mix(in srgb, var(--accent) 26%, transparent)',
|
||||||
|
background: dark
|
||||||
|
? 'linear-gradient(135deg, rgba(56,189,248,0.16), rgba(129,140,248,0.14))'
|
||||||
|
: 'linear-gradient(135deg, rgba(56,189,248,0.16), rgba(129,140,248,0.12))',
|
||||||
|
boxShadow: '0 8px 22px color-mix(in srgb, var(--accent) 16%, transparent)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<PageIcon size={20} strokeWidth={2.2} style={{ color: 'var(--accent)' }} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Title block */}
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="flex items-center gap-2.5 flex-wrap">
|
||||||
|
<h1 className="text-xl font-bold tracking-[-0.03em]" style={{ color: 'var(--text-primary)' }}>
|
||||||
|
{meta.title}
|
||||||
|
</h1>
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium"
|
||||||
|
style={{
|
||||||
|
color: 'var(--accent)',
|
||||||
|
background: 'var(--accent-subtle)',
|
||||||
|
border: '1px solid color-mix(in srgb, var(--accent) 22%, transparent)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Sparkles size={10} className="mr-1" />
|
||||||
|
{meta.badge}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="mt-0.5 text-sm" style={{ color: 'var(--text-secondary)' }}>
|
||||||
|
{meta.subtitle}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<motion.div
|
||||||
|
whileHover={{ y: -1.5 }}
|
||||||
|
className="hidden sm:flex shrink-0 overflow-hidden rounded-2xl border px-4 py-3 items-center gap-3"
|
||||||
|
style={{
|
||||||
|
borderColor: dark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.82)',
|
||||||
|
background: dark ? 'rgba(255,255,255,0.03)' : 'rgba(255,255,255,0.52)',
|
||||||
|
backdropFilter: 'blur(18px)',
|
||||||
|
WebkitBackdropFilter: 'blur(18px)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Activity size={14} style={{ color: 'var(--accent)', flexShrink: 0 }} />
|
||||||
|
<div>
|
||||||
|
<div className="text-[11px] font-semibold uppercase tracking-widest mb-0.5" style={{ color: 'var(--text-tertiary)' }}>运行状态</div>
|
||||||
|
<div className="text-sm font-semibold" style={{ color: 'var(--accent)' }}>{runtimeLabel}</div>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</motion.header>
|
||||||
|
</AnimatePresence>
|
||||||
|
|
||||||
|
{/* Page content */}
|
||||||
|
<div className="flex-1 flex flex-col">
|
||||||
|
<AnimatePresence mode="wait">
|
||||||
|
<motion.div
|
||||||
|
key={activePage}
|
||||||
|
initial={{ opacity: 0, y: 12 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, y: -12 }}
|
||||||
|
transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</motion.div>
|
||||||
|
</AnimatePresence>
|
||||||
|
|
||||||
|
<motion.footer
|
||||||
|
initial={{ opacity: 0, y: 8 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ duration: 0.3, delay: 0.08 }}
|
||||||
|
className="mt-8 flex items-center justify-center border-t pt-5 text-[11px] tracking-wide"
|
||||||
|
style={{
|
||||||
|
color: 'var(--text-tertiary)',
|
||||||
|
borderColor: 'var(--border-subtle)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
© {new Date().getFullYear()} SnowLuma. All rights reserved.
|
||||||
|
</motion.footer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
import { LayoutDashboard, Settings, LogOut, Sun, Moon, Monitor } from 'lucide-react';
|
||||||
|
import { Avatar } from '@heroui/react';
|
||||||
|
import { StatusBadge } from '../ui/StatusBadge';
|
||||||
|
import { motion } from 'framer-motion';
|
||||||
|
import { useTheme, type ThemeMode } from '../../contexts/ThemeContext';
|
||||||
|
|
||||||
|
type Page = '总览' | '配置';
|
||||||
|
|
||||||
|
interface SidebarProps {
|
||||||
|
activePage: Page;
|
||||||
|
onNavigate: (page: Page) => void;
|
||||||
|
status: string;
|
||||||
|
onLogout: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const navItems: { page: Page; label: string; icon: typeof LayoutDashboard }[] = [
|
||||||
|
{ page: '总览', label: '总览', icon: LayoutDashboard },
|
||||||
|
{ page: '配置', label: '配置', icon: Settings },
|
||||||
|
];
|
||||||
|
|
||||||
|
const THEME_OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [
|
||||||
|
{ mode: 'system', icon: Monitor, label: '跟随系统' },
|
||||||
|
{ mode: 'light', icon: Sun, label: '浅色' },
|
||||||
|
{ mode: 'dark', icon: Moon, label: '深色' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function Sidebar({ activePage, onNavigate, status, onLogout }: SidebarProps) {
|
||||||
|
const { resolved, mode, setMode } = useTheme();
|
||||||
|
const dark = resolved === 'dark';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside
|
||||||
|
className="w-55 shrink-0 flex flex-col z-40 m-3 rounded-2xl overflow-hidden relative"
|
||||||
|
style={{
|
||||||
|
background: dark
|
||||||
|
? 'linear-gradient(135deg, rgba(8,13,22,0.78), rgba(14,20,32,0.88))'
|
||||||
|
: 'linear-gradient(135deg, rgba(255,255,255,0.72), rgba(255,255,255,0.9))',
|
||||||
|
border: '1px solid var(--glass-border)',
|
||||||
|
backdropFilter: 'blur(38px) saturate(1.35)',
|
||||||
|
WebkitBackdropFilter: 'blur(38px) saturate(1.35)',
|
||||||
|
boxShadow: dark
|
||||||
|
? '0 24px 80px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.05)'
|
||||||
|
: '0 20px 60px rgba(15,23,42,0.08), inset 0 1px 0 rgba(255,255,255,0.7)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Top highlight */}
|
||||||
|
<div className="absolute inset-x-0 top-0 h-px bg-linear-to-r from-transparent via-white/8 to-transparent" />
|
||||||
|
|
||||||
|
{/* Grid texture overlay */}
|
||||||
|
<div
|
||||||
|
className="pointer-events-none absolute inset-0"
|
||||||
|
style={{
|
||||||
|
backgroundImage: dark
|
||||||
|
? 'linear-gradient(90deg, rgba(255,255,255,0.02) 1px, transparent 1px), linear-gradient(rgba(255,255,255,0.02) 1px, transparent 1px)'
|
||||||
|
: 'linear-gradient(90deg, rgba(15,23,42,0.03) 1px, transparent 1px), linear-gradient(rgba(15,23,42,0.03) 1px, transparent 1px)',
|
||||||
|
backgroundSize: '36px 36px',
|
||||||
|
maskImage: 'linear-gradient(180deg, rgba(0,0,0,0.3), transparent 70%)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Accent glow at top-left */}
|
||||||
|
<motion.div
|
||||||
|
className="pointer-events-none absolute -left-6 -top-6 h-24 w-24 rounded-full"
|
||||||
|
style={{
|
||||||
|
background: 'radial-gradient(circle, rgba(56,189,248,0.2), transparent 68%)',
|
||||||
|
filter: 'blur(14px)',
|
||||||
|
}}
|
||||||
|
animate={{ scale: [1, 1.15, 1], opacity: [0.5, 0.8, 0.5] }}
|
||||||
|
transition={{ duration: 7, ease: 'easeInOut', repeat: Infinity }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Logo */}
|
||||||
|
<div className="relative h-16 px-5 flex items-center gap-2" style={{ borderBottom: '1px solid var(--border-subtle)' }}>
|
||||||
|
<div className="relative shrink-0">
|
||||||
|
<div
|
||||||
|
className="absolute -inset-1.5 rounded-full blur-lg"
|
||||||
|
style={{ background: 'linear-gradient(135deg, rgba(56,189,248,0.2), rgba(129,140,248,0.18))' }}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className="relative rounded-full border p-0.5"
|
||||||
|
style={{
|
||||||
|
borderColor: 'var(--glass-border)',
|
||||||
|
background: dark ? 'rgba(8,12,19,0.7)' : 'rgba(255,255,255,0.8)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Avatar
|
||||||
|
className="rounded-full"
|
||||||
|
style={{ width: 32, height: 32, borderRadius: '50%', overflow: 'hidden', flexShrink: 0 }}
|
||||||
|
>
|
||||||
|
<Avatar.Image src="/logo.png" alt="SnowLuma" className="object-cover" />
|
||||||
|
<Avatar.Fallback>SL</Avatar.Fallback>
|
||||||
|
</Avatar>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className="text-sm font-bold tracking-tight" style={{ color: 'var(--text-primary)' }}>
|
||||||
|
SnowLuma
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Navigation */}
|
||||||
|
<nav className="flex-1 px-3 pt-4 flex flex-col gap-1.5">
|
||||||
|
{navItems.map(({ page, label, icon: Icon }) => {
|
||||||
|
const isActive = activePage === page;
|
||||||
|
return (
|
||||||
|
<motion.button
|
||||||
|
whileHover={{ scale: 1.01 }}
|
||||||
|
whileTap={{ scale: 0.98 }}
|
||||||
|
key={page}
|
||||||
|
onClick={() => onNavigate(page)}
|
||||||
|
className="flex items-center gap-2.5 h-9 px-3 rounded-xl text-sm font-medium cursor-pointer relative overflow-hidden"
|
||||||
|
style={{
|
||||||
|
color: isActive ? 'var(--accent)' : 'var(--text-secondary)',
|
||||||
|
background: isActive ? 'var(--accent-subtle)' : 'transparent',
|
||||||
|
transition: 'var(--transition-fast)',
|
||||||
|
}}
|
||||||
|
onMouseEnter={e => { if (!isActive) (e.currentTarget.style.background = 'var(--bg-hover)'); }}
|
||||||
|
onMouseLeave={e => { if (!isActive) (e.currentTarget.style.background = 'transparent'); }}
|
||||||
|
>
|
||||||
|
{isActive && (
|
||||||
|
<motion.div
|
||||||
|
layoutId="sidebarActive"
|
||||||
|
className="absolute inset-0 rounded-xl"
|
||||||
|
style={{
|
||||||
|
background: 'var(--accent-subtle)',
|
||||||
|
border: '1px solid color-mix(in srgb, var(--accent) 24%, transparent)',
|
||||||
|
boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.06)',
|
||||||
|
}}
|
||||||
|
initial={false}
|
||||||
|
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Icon
|
||||||
|
size={16}
|
||||||
|
strokeWidth={isActive ? 2.2 : 1.8}
|
||||||
|
className="relative z-10 shrink-0"
|
||||||
|
style={{ color: isActive ? 'var(--accent)' : undefined }}
|
||||||
|
/>
|
||||||
|
<span className="relative z-10">{label}</span>
|
||||||
|
</motion.button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{/* Bottom */}
|
||||||
|
<div className="relative p-3 flex flex-col gap-2" style={{ borderTop: '1px solid var(--border-subtle)' }}>
|
||||||
|
<div className="flex items-center justify-between px-1">
|
||||||
|
<StatusBadge status={status} />
|
||||||
|
<div className="flex items-center gap-0.5">
|
||||||
|
{THEME_OPTIONS.map(({ mode: m, icon: Icon, label }) => {
|
||||||
|
const active = mode === m;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={m}
|
||||||
|
title={label}
|
||||||
|
onClick={() => setMode(m)}
|
||||||
|
className="relative flex size-7 cursor-pointer items-center justify-center rounded-lg transition-colors duration-200"
|
||||||
|
style={{ color: active ? 'var(--accent)' : 'var(--text-tertiary)' }}
|
||||||
|
>
|
||||||
|
{active && (
|
||||||
|
<motion.div
|
||||||
|
layoutId="sidebar-theme-pill"
|
||||||
|
className="absolute inset-0 rounded-lg"
|
||||||
|
style={{ background: 'var(--accent-subtle)' }}
|
||||||
|
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Icon size={13} className="relative z-10" />
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<motion.button
|
||||||
|
whileHover={{ scale: 1.01 }}
|
||||||
|
whileTap={{ scale: 0.98 }}
|
||||||
|
onClick={onLogout}
|
||||||
|
className="flex items-center justify-center gap-2 h-8 rounded-lg text-xs font-medium cursor-pointer"
|
||||||
|
style={{
|
||||||
|
color: 'var(--text-tertiary)',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
transition: 'var(--transition-fast)',
|
||||||
|
}}
|
||||||
|
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-danger)'; e.currentTarget.style.borderColor = 'rgba(248,113,113,0.2)'; e.currentTarget.style.background = 'rgba(248,113,113,0.06)'; }}
|
||||||
|
onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-tertiary)'; e.currentTarget.style.borderColor = 'var(--border-subtle)'; e.currentTarget.style.background = 'transparent'; }}
|
||||||
|
>
|
||||||
|
<LogOut size={13} strokeWidth={2} />
|
||||||
|
登出
|
||||||
|
</motion.button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { Moon, Sun } from 'lucide-react';
|
||||||
|
import { useTheme } from '../../contexts/ThemeContext';
|
||||||
|
|
||||||
|
interface TopBarProps {
|
||||||
|
title: string;
|
||||||
|
subtitle?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TopBar({ title, subtitle }: TopBarProps) {
|
||||||
|
const { resolved, mode, setMode } = useTheme();
|
||||||
|
const cycleTheme = () => setMode(mode === 'system' ? 'light' : mode === 'light' ? 'dark' : 'system');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<header className="h-14 shrink-0 flex items-center justify-between px-6 border-b border-zinc-200/60 dark:border-white/6 bg-white/60 dark:bg-zinc-900/60 backdrop-blur-xl">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100 tracking-tight">{title}</h1>
|
||||||
|
{subtitle && <p className="text-xs text-zinc-400 dark:text-zinc-500 mt-0.5">{subtitle}</p>}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={cycleTheme}
|
||||||
|
className="size-8 flex items-center justify-center rounded-lg text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-white/8 transition-all duration-150 cursor-pointer"
|
||||||
|
>
|
||||||
|
{resolved === 'light' ? <Moon size={16} /> : <Sun size={16} />}
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import { MousePointerClick } from 'lucide-react';
|
||||||
|
import { motion } from 'framer-motion';
|
||||||
|
import { SectionCard } from '../ui/SectionCard';
|
||||||
|
import { EndpointRow } from '../ui/EndpointRow';
|
||||||
|
import { FieldInput } from '../ui/FieldInput';
|
||||||
|
import { useTheme } from '../../contexts/ThemeContext';
|
||||||
|
import type { QQInfo, OneBotConfig } from '../../types';
|
||||||
|
|
||||||
|
interface ConfigPageProps {
|
||||||
|
qqList: QQInfo[];
|
||||||
|
selectedUin: string | null;
|
||||||
|
config: OneBotConfig | null;
|
||||||
|
saveStatus: string;
|
||||||
|
onSelectAccount: (uin: string) => void;
|
||||||
|
onSave: () => void;
|
||||||
|
onConfigChange: (config: OneBotConfig) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ConfigPage({
|
||||||
|
qqList, selectedUin, config, saveStatus,
|
||||||
|
onSelectAccount, onSave, onConfigChange,
|
||||||
|
}: ConfigPageProps) {
|
||||||
|
const { resolved } = useTheme();
|
||||||
|
const dark = resolved === 'dark';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-4 xl:flex-row xl:items-start">
|
||||||
|
{/* Account list panel */}
|
||||||
|
<div className="w-full shrink-0 xl:sticky xl:top-0 xl:w-60 2xl:w-64">
|
||||||
|
<div
|
||||||
|
className="rounded-xl overflow-hidden"
|
||||||
|
style={{
|
||||||
|
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
|
||||||
|
backdropFilter: 'blur(32px) saturate(1.2)',
|
||||||
|
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
|
||||||
|
boxShadow: dark
|
||||||
|
? '0 8px 32px rgba(0,0,0,0.3), inset 0 1px 1px rgba(255,255,255,0.06)'
|
||||||
|
: '0 8px 24px rgba(15,23,42,0.04), inset 0 1px 1px rgba(255,255,255,0.5)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="px-4 pt-4 pb-2">
|
||||||
|
<span className="text-[11px] font-semibold uppercase tracking-widest" style={{ color: 'var(--text-secondary)' }}>
|
||||||
|
在线连接
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="px-2 pb-3 flex flex-col gap-0.5 sm:grid sm:grid-cols-2 sm:gap-1.5 xl:flex">
|
||||||
|
{qqList.length === 0 ? (
|
||||||
|
<p className="text-xs text-center py-6" style={{ color: 'var(--text-tertiary)' }}>暂无在线会话</p>
|
||||||
|
) : qqList.map(q => {
|
||||||
|
const isActive = selectedUin === q.uin;
|
||||||
|
return (
|
||||||
|
<motion.button
|
||||||
|
whileHover={{ scale: 1.01 }}
|
||||||
|
whileTap={{ scale: 0.98 }}
|
||||||
|
key={q.uin}
|
||||||
|
onClick={() => onSelectAccount(q.uin)}
|
||||||
|
className="w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-left cursor-pointer"
|
||||||
|
style={{
|
||||||
|
background: isActive ? 'var(--accent-subtle)' : 'transparent',
|
||||||
|
transition: 'var(--transition-fast)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="size-7 rounded-md flex items-center justify-center text-white text-[11px] font-bold shrink-0"
|
||||||
|
style={{
|
||||||
|
background: isActive
|
||||||
|
? 'linear-gradient(135deg, var(--accent), #818cf8)'
|
||||||
|
: 'var(--bg-input)',
|
||||||
|
color: isActive ? '#fff' : 'var(--text-secondary)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{q.nickname[0]?.toUpperCase() || '?'}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div
|
||||||
|
className="text-sm font-medium truncate"
|
||||||
|
style={{ color: isActive ? 'var(--accent)' : 'var(--text-primary)' }}
|
||||||
|
>
|
||||||
|
{q.nickname}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="text-[11px] truncate"
|
||||||
|
style={{ color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' }}
|
||||||
|
>
|
||||||
|
{q.uin}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</motion.button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Editor panel */}
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
{!selectedUin ? (
|
||||||
|
<div className="flex flex-col items-center justify-center h-64 gap-3">
|
||||||
|
<MousePointerClick size={28} strokeWidth={1.2} style={{ color: 'var(--text-tertiary)', opacity: 0.5 }} />
|
||||||
|
<p className="text-sm" style={{ color: 'var(--text-secondary)' }}>在左栏选择会话以配置通信节点</p>
|
||||||
|
</div>
|
||||||
|
) : !config ? (
|
||||||
|
<div className="space-y-4 animate-pulse">
|
||||||
|
<div className="h-8 rounded-lg w-48" style={{ background: 'var(--bg-card)' }} />
|
||||||
|
<div className="h-32 rounded-xl" style={{ background: 'var(--bg-card)' }} />
|
||||||
|
<div className="h-32 rounded-xl" style={{ background: 'var(--bg-card)' }} />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-base font-semibold tracking-tight" style={{ color: 'var(--text-primary)' }}>
|
||||||
|
OneBot 协议端点
|
||||||
|
</h2>
|
||||||
|
<code
|
||||||
|
className="text-xs mt-1 block"
|
||||||
|
style={{ color: 'var(--text-secondary)', fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' }}
|
||||||
|
>
|
||||||
|
UIN {selectedUin}
|
||||||
|
</code>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2.5">
|
||||||
|
{saveStatus && (
|
||||||
|
<span
|
||||||
|
className="text-xs font-medium px-2.5 py-1 rounded-full"
|
||||||
|
style={{
|
||||||
|
color: saveStatus === '保存成功' ? 'var(--color-success)' : saveStatus === '保存中...' ? 'var(--text-secondary)' : 'var(--color-danger)',
|
||||||
|
background: saveStatus === '保存成功' ? 'rgba(52,211,153,0.1)' : saveStatus === '保存中...' ? 'var(--bg-card)' : 'rgba(248,113,113,0.1)',
|
||||||
|
border: `1px solid ${saveStatus === '保存成功' ? 'rgba(52,211,153,0.2)' : saveStatus === '保存中...' ? 'var(--border-subtle)' : 'rgba(248,113,113,0.2)'}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{saveStatus}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<motion.button
|
||||||
|
whileHover={{ scale: 1.02 }}
|
||||||
|
whileTap={{ scale: 0.98 }}
|
||||||
|
onClick={onSave}
|
||||||
|
className="h-8 px-4 rounded-lg text-white text-xs font-medium cursor-pointer"
|
||||||
|
style={{
|
||||||
|
background: 'linear-gradient(135deg, var(--accent), #818cf8)',
|
||||||
|
boxShadow: '0 2px 12px var(--accent-glow)',
|
||||||
|
transition: 'var(--transition-fast)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
保存设定
|
||||||
|
</motion.button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* HTTP Servers */}
|
||||||
|
<SectionCard title="HTTP 服务监听" onAdd={() => { const c = { ...config }; c.httpServers = [...c.httpServers, { port: 3000, host: '0.0.0.0', path: '/' }]; onConfigChange(c); }}>
|
||||||
|
{config.httpServers.length === 0 ? null : config.httpServers.map((s, idx) => (
|
||||||
|
<EndpointRow key={idx} onRemove={() => { const c = { ...config }; c.httpServers = c.httpServers.filter((_, i) => i !== idx); onConfigChange(c); }}>
|
||||||
|
<FieldInput label="端口" value={s.port} isNum flex="w-28" onChange={v => { const c = { ...config }; c.httpServers = c.httpServers.map((item, i) => i === idx ? { ...item, port: v as number } : item); onConfigChange(c); }} />
|
||||||
|
<FieldInput label="授权 Token" placeholder="不填则无密码" value={s.accessToken || ''} onChange={v => { const c = { ...config }; c.httpServers = c.httpServers.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} />
|
||||||
|
</EndpointRow>
|
||||||
|
))}
|
||||||
|
</SectionCard>
|
||||||
|
|
||||||
|
{/* HTTP Post */}
|
||||||
|
<SectionCard title="HTTP Post 推送端点" onAdd={() => { const c = { ...config }; c.httpPostEndpoints = [...c.httpPostEndpoints, { url: 'http://127.0.0.1:5700' }]; onConfigChange(c); }}>
|
||||||
|
{config.httpPostEndpoints.length === 0 ? null : config.httpPostEndpoints.map((s, idx) => (
|
||||||
|
<EndpointRow key={idx} onRemove={() => { const c = { ...config }; c.httpPostEndpoints = c.httpPostEndpoints.filter((_, i) => i !== idx); onConfigChange(c); }}>
|
||||||
|
<FieldInput label="目标 URL" placeholder="http://..." grow value={s.url || ''} onChange={v => { const c = { ...config }; c.httpPostEndpoints = c.httpPostEndpoints.map((item, i) => i === idx ? { ...item, url: v as string } : item); onConfigChange(c); }} />
|
||||||
|
<FieldInput label="授权 Token" placeholder="可选" value={s.accessToken || ''} onChange={v => { const c = { ...config }; c.httpPostEndpoints = c.httpPostEndpoints.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} />
|
||||||
|
</EndpointRow>
|
||||||
|
))}
|
||||||
|
</SectionCard>
|
||||||
|
|
||||||
|
{/* WS Servers */}
|
||||||
|
<SectionCard title="WebSocket 服务监听" onAdd={() => { const c = { ...config }; c.wsServers = [...c.wsServers, { port: 3001, host: '0.0.0.0', path: '/' }]; onConfigChange(c); }}>
|
||||||
|
{config.wsServers.length === 0 ? null : config.wsServers.map((s, idx) => (
|
||||||
|
<EndpointRow key={idx} onRemove={() => { const c = { ...config }; c.wsServers = c.wsServers.filter((_, i) => i !== idx); onConfigChange(c); }}>
|
||||||
|
<FieldInput label="端口" value={s.port} isNum flex="w-28" onChange={v => { const c = { ...config }; c.wsServers = c.wsServers.map((item, i) => i === idx ? { ...item, port: v as number } : item); onConfigChange(c); }} />
|
||||||
|
<FieldInput label="授权 Token" placeholder="不填则无密码" value={s.accessToken || ''} onChange={v => { const c = { ...config }; c.wsServers = c.wsServers.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} />
|
||||||
|
</EndpointRow>
|
||||||
|
))}
|
||||||
|
</SectionCard>
|
||||||
|
|
||||||
|
{/* WS Clients */}
|
||||||
|
<SectionCard title="WebSocket 客户端(反向连出)" onAdd={() => { const c = { ...config }; c.wsClients = [...c.wsClients, { url: 'ws://127.0.0.1:8080/ws', reconnectIntervalMs: 5000 }]; onConfigChange(c); }}>
|
||||||
|
{config.wsClients.length === 0 ? null : config.wsClients.map((c2, idx) => (
|
||||||
|
<EndpointRow key={idx} onRemove={() => { const c = { ...config }; c.wsClients = c.wsClients.filter((_, i) => i !== idx); onConfigChange(c); }}>
|
||||||
|
<FieldInput label="目标 URL" placeholder="ws://..." grow value={c2.url || ''} onChange={v => { const c = { ...config }; c.wsClients = c.wsClients.map((item, i) => i === idx ? { ...item, url: v as string } : item); onConfigChange(c); }} />
|
||||||
|
<FieldInput label="授权 Token" placeholder="可选" value={c2.accessToken || ''} onChange={v => { const c = { ...config }; c.wsClients = c.wsClients.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} />
|
||||||
|
</EndpointRow>
|
||||||
|
))}
|
||||||
|
</SectionCard>
|
||||||
|
|
||||||
|
{/* Music Sign URL */}
|
||||||
|
<SectionCard title="音乐签名 URL" onAdd={() => {}}>
|
||||||
|
<div className="px-5 py-4">
|
||||||
|
<FieldInput label="签名服务地址" placeholder="留空则不启用" value={config.musicSignUrl || ''} onChange={v => onConfigChange({ ...config, musicSignUrl: (v as string) || undefined })} />
|
||||||
|
</div>
|
||||||
|
</SectionCard>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,473 @@
|
|||||||
|
import { useState, useMemo, useRef, useCallback } from 'react';
|
||||||
|
import { Avatar } from '@heroui/react';
|
||||||
|
import { Sun, Moon, Monitor, Eye, EyeOff, ArrowRight, KeyRound } from 'lucide-react';
|
||||||
|
import { motion, AnimatePresence, useMotionValue, useSpring, useTransform } from 'framer-motion';
|
||||||
|
import { useTheme, type ThemeMode } from '../../contexts/ThemeContext';
|
||||||
|
|
||||||
|
interface LoginPageProps {
|
||||||
|
onLogin: (password: string) => Promise<{ success: boolean; error?: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const THEME_OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [
|
||||||
|
{ mode: 'system', icon: Monitor, label: '跟随系统' },
|
||||||
|
{ mode: 'light', icon: Sun, label: '浅色' },
|
||||||
|
{ mode: 'dark', icon: Moon, label: '深色' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const SPARKLES = Array.from({ length: 12 }, (_, i) => ({
|
||||||
|
id: i,
|
||||||
|
x: (i * 31 + 9) % 100,
|
||||||
|
y: (i * 47 + 13) % 100,
|
||||||
|
size: 2 + (i % 2),
|
||||||
|
delay: (i * 0.35) % 4,
|
||||||
|
duration: 3.5 + (i % 3),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const BRAND_TAGS = ['OneBot v11', '多账号', '实时面板'];
|
||||||
|
|
||||||
|
export function LoginPage({ onLogin }: LoginPageProps) {
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [showPwd, setShowPwd] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [shakeKey, setShakeKey] = useState(0);
|
||||||
|
const { mode, resolved, setMode } = useTheme();
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
const logoSrc = useMemo(() => '/logo.png', []);
|
||||||
|
|
||||||
|
const mouseX = useMotionValue(0);
|
||||||
|
const mouseY = useMotionValue(0);
|
||||||
|
const smoothX = useSpring(mouseX, { stiffness: 60, damping: 20 });
|
||||||
|
const smoothY = useSpring(mouseY, { stiffness: 60, damping: 20 });
|
||||||
|
|
||||||
|
const shellRotateX = useTransform(smoothY, [-0.5, 0.5], [4, -4]);
|
||||||
|
const shellRotateY = useTransform(smoothX, [-0.5, 0.5], [-5, 5]);
|
||||||
|
|
||||||
|
const orb1X = useTransform(smoothX, [-0.5, 0.5], [-45, 45]);
|
||||||
|
const orb1Y = useTransform(smoothY, [-0.5, 0.5], [-28, 28]);
|
||||||
|
const orb2X = useTransform(smoothX, [-0.5, 0.5], [35, -35]);
|
||||||
|
const orb2Y = useTransform(smoothY, [-0.5, 0.5], [30, -30]);
|
||||||
|
const accentX = useTransform(smoothX, [-0.5, 0.5], [-16, 16]);
|
||||||
|
const accentY = useTransform(smoothY, [-0.5, 0.5], [-12, 12]);
|
||||||
|
|
||||||
|
const handleMouseMove = useCallback((e: React.MouseEvent) => {
|
||||||
|
const rect = containerRef.current?.getBoundingClientRect();
|
||||||
|
if (!rect) return;
|
||||||
|
mouseX.set((e.clientX - rect.left) / rect.width - 0.5);
|
||||||
|
mouseY.set((e.clientY - rect.top) / rect.height - 0.5);
|
||||||
|
}, [mouseX, mouseY]);
|
||||||
|
|
||||||
|
const handleMouseLeave = useCallback(() => {
|
||||||
|
mouseX.set(0);
|
||||||
|
mouseY.set(0);
|
||||||
|
}, [mouseX, mouseY]);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setError('');
|
||||||
|
setLoading(true);
|
||||||
|
const result = await onLogin(password);
|
||||||
|
setLoading(false);
|
||||||
|
if (!result.success && result.error) {
|
||||||
|
setError(result.error);
|
||||||
|
setShakeKey(k => k + 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const darkMode = resolved === 'dark';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
className="relative min-h-screen overflow-hidden"
|
||||||
|
style={{ background: 'var(--bg-body)' }}
|
||||||
|
onMouseMove={handleMouseMove}
|
||||||
|
onMouseLeave={handleMouseLeave}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="pointer-events-none absolute inset-0"
|
||||||
|
style={{
|
||||||
|
background: darkMode
|
||||||
|
? 'linear-gradient(135deg, rgba(8,11,18,1) 0%, rgba(10,16,27,1) 42%, rgba(7,10,17,1) 100%)'
|
||||||
|
: 'linear-gradient(135deg, #f8fbff 0%, #eef6ff 45%, #f9fafc 100%)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="pointer-events-none absolute inset-0 overflow-hidden">
|
||||||
|
{SPARKLES.map(s => (
|
||||||
|
<motion.div
|
||||||
|
key={s.id}
|
||||||
|
className="absolute rounded-full"
|
||||||
|
style={{
|
||||||
|
width: s.size,
|
||||||
|
height: s.size,
|
||||||
|
left: `${s.x}%`,
|
||||||
|
top: `${s.y}%`,
|
||||||
|
background: darkMode
|
||||||
|
? `rgba(${s.id % 2 === 0 ? '56,189,248' : '129,140,248'},0.38)`
|
||||||
|
: `rgba(${s.id % 2 === 0 ? '14,165,233' : '99,102,241'},0.26)`,
|
||||||
|
}}
|
||||||
|
animate={{ y: [0, -16, 0], opacity: [0.18, 0.55, 0.18], scale: [1, 1.25, 1] }}
|
||||||
|
transition={{ duration: s.duration, delay: s.delay, ease: 'easeInOut', repeat: Infinity }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<motion.div
|
||||||
|
className="absolute -left-24 -top-24 h-120 w-120 rounded-full"
|
||||||
|
style={{
|
||||||
|
x: orb1X,
|
||||||
|
y: orb1Y,
|
||||||
|
background: darkMode
|
||||||
|
? 'radial-gradient(circle, rgba(56,189,248,0.16) 0%, transparent 68%)'
|
||||||
|
: 'radial-gradient(circle, rgba(56,189,248,0.22) 0%, transparent 70%)',
|
||||||
|
filter: 'blur(42px)',
|
||||||
|
}}
|
||||||
|
animate={{ scale: [1, 1.08, 1] }}
|
||||||
|
transition={{ duration: 10, ease: 'easeInOut', repeat: Infinity }}
|
||||||
|
/>
|
||||||
|
<motion.div
|
||||||
|
className="absolute -right-16 -bottom-32 h-112 w-md rounded-full"
|
||||||
|
style={{
|
||||||
|
x: orb2X,
|
||||||
|
y: orb2Y,
|
||||||
|
background: darkMode
|
||||||
|
? 'radial-gradient(circle, rgba(129,140,248,0.14) 0%, transparent 68%)'
|
||||||
|
: 'radial-gradient(circle, rgba(129,140,248,0.16) 0%, transparent 70%)',
|
||||||
|
filter: 'blur(52px)',
|
||||||
|
}}
|
||||||
|
animate={{ scale: [1, 1.12, 1] }}
|
||||||
|
transition={{ duration: 12, ease: 'easeInOut', repeat: Infinity, delay: 0.8 }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<div className="relative z-10 flex min-h-screen items-center justify-center px-5 py-10 sm:px-8 lg:px-12">
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 24, scale: 0.97 }}
|
||||||
|
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||||
|
transition={{ duration: 0.55, ease: [0.16, 1, 0.3, 1] }}
|
||||||
|
style={{ rotateX: shellRotateX, rotateY: shellRotateY, transformPerspective: 1200 }}
|
||||||
|
className="relative w-full max-w-6xl"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="absolute -inset-5 -z-10 rounded-4xl blur-3xl"
|
||||||
|
style={{ background: 'linear-gradient(135deg, rgba(56,189,248,0.12), rgba(129,140,248,0.14), rgba(34,211,238,0.08))' }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div
|
||||||
|
className="relative overflow-hidden rounded-4xl border"
|
||||||
|
style={{
|
||||||
|
background: darkMode
|
||||||
|
? 'linear-gradient(135deg, rgba(8,13,22,0.78), rgba(14,20,32,0.88))'
|
||||||
|
: 'linear-gradient(135deg, rgba(255,255,255,0.72), rgba(255,255,255,0.9))',
|
||||||
|
borderColor: 'var(--glass-border)',
|
||||||
|
backdropFilter: 'blur(38px) saturate(1.35)',
|
||||||
|
WebkitBackdropFilter: 'blur(38px) saturate(1.35)',
|
||||||
|
boxShadow: darkMode
|
||||||
|
? '0 38px 120px rgba(0,0,0,0.55), inset 0 1px 0 rgba(255,255,255,0.05)'
|
||||||
|
: '0 32px 90px rgba(15,23,42,0.12), inset 0 1px 0 rgba(255,255,255,0.7)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="absolute inset-0"
|
||||||
|
style={{
|
||||||
|
backgroundImage: darkMode
|
||||||
|
? 'linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px), linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px)'
|
||||||
|
: 'linear-gradient(90deg, rgba(15,23,42,0.04) 1px, transparent 1px), linear-gradient(rgba(15,23,42,0.04) 1px, transparent 1px)',
|
||||||
|
backgroundSize: '36px 36px',
|
||||||
|
maskImage: 'linear-gradient(180deg, rgba(0,0,0,0.45), transparent 82%)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<motion.div
|
||||||
|
className="pointer-events-none absolute right-[18%] top-[14%] h-28 w-28 rounded-full"
|
||||||
|
style={{
|
||||||
|
x: accentX,
|
||||||
|
y: accentY,
|
||||||
|
background: 'radial-gradient(circle, rgba(56,189,248,0.28), transparent 68%)',
|
||||||
|
filter: 'blur(18px)',
|
||||||
|
}}
|
||||||
|
animate={{ scale: [1, 1.12, 1] }}
|
||||||
|
transition={{ duration: 6, ease: 'easeInOut', repeat: Infinity }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="relative grid min-h-168 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]">
|
||||||
|
<div className="relative flex flex-col justify-center gap-12 p-6 sm:p-10 lg:p-14 xl:p-16">
|
||||||
|
<div className="max-w-2xl">
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 14 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ duration: 0.45, delay: 0.08 }}
|
||||||
|
className="flex items-center gap-4"
|
||||||
|
>
|
||||||
|
<motion.div whileHover={{ scale: 1.03 }} className="relative shrink-0">
|
||||||
|
<div
|
||||||
|
className="absolute -inset-2 rounded-full blur-xl"
|
||||||
|
style={{ background: 'linear-gradient(135deg, rgba(56,189,248,0.25), rgba(129,140,248,0.22))' }}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className="relative rounded-full border p-1"
|
||||||
|
style={{
|
||||||
|
borderColor: 'var(--glass-border)',
|
||||||
|
background: darkMode ? 'rgba(8,12,19,0.7)' : 'rgba(255,255,255,0.8)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Avatar
|
||||||
|
className="size-16 rounded-full"
|
||||||
|
style={{ width: 64, height: 64, borderRadius: '50%', overflow: 'hidden', flexShrink: 0 }}
|
||||||
|
>
|
||||||
|
<Avatar.Image src={logoSrc} alt="SnowLuma" className="object-cover" />
|
||||||
|
<Avatar.Fallback>SL</Avatar.Fallback>
|
||||||
|
</Avatar>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="text-sm font-medium" style={{ color: 'var(--accent)' }}>
|
||||||
|
SnowLuma 控制台
|
||||||
|
</div>
|
||||||
|
<h1
|
||||||
|
className="mt-1 text-4xl font-semibold tracking-[-0.04em] sm:text-5xl"
|
||||||
|
style={{ color: 'var(--text-primary)' }}
|
||||||
|
>
|
||||||
|
SnowLuma
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
<motion.p
|
||||||
|
initial={{ opacity: 0, y: 16 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ duration: 0.45, delay: 0.16 }}
|
||||||
|
className="mt-8 max-w-xl text-base leading-8"
|
||||||
|
style={{ color: 'var(--text-secondary)' }}
|
||||||
|
>
|
||||||
|
基于 OneBot v11 标准实现的高性能 QQ 协议网关。
|
||||||
|
</motion.p>
|
||||||
|
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 16 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ duration: 0.45, delay: 0.22 }}
|
||||||
|
className="mt-8 flex flex-wrap gap-2"
|
||||||
|
>
|
||||||
|
{BRAND_TAGS.map(tag => (
|
||||||
|
<span
|
||||||
|
key={tag}
|
||||||
|
className="rounded-full px-3.5 py-1.5 text-xs font-medium"
|
||||||
|
style={{
|
||||||
|
color: 'var(--accent)',
|
||||||
|
background: 'var(--accent-subtle)',
|
||||||
|
border: '1px solid color-mix(in srgb, var(--accent) 30%, transparent)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{tag}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</motion.div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="absolute bottom-6 left-6 sm:bottom-10 sm:left-10 lg:bottom-14 lg:left-14 xl:bottom-16 xl:left-16 pointer-events-none">
|
||||||
|
<motion.p
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
transition={{ duration: 0.6, delay: 0.4 }}
|
||||||
|
className="text-[11px] tracking-wide"
|
||||||
|
style={{ color: 'var(--text-tertiary)' }}
|
||||||
|
>
|
||||||
|
© {new Date().getFullYear()} SnowLuma. All rights reserved.
|
||||||
|
</motion.p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
className="relative flex items-center px-5 pb-5 pt-0 sm:px-8 sm:pb-8 lg:border-l lg:px-12 lg:py-12"
|
||||||
|
style={{ borderColor: 'var(--glass-border)' }}
|
||||||
|
>
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, x: 18 }}
|
||||||
|
animate={{ opacity: 1, x: 0 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.18 }}
|
||||||
|
className="relative w-full max-w-md mx-auto rounded-[1.75rem] p-7 sm:p-8 overflow-hidden"
|
||||||
|
style={{
|
||||||
|
background: darkMode ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
|
||||||
|
backdropFilter: 'blur(32px) saturate(1.2)',
|
||||||
|
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
|
||||||
|
boxShadow: darkMode
|
||||||
|
? '0 24px 64px rgba(0,0,0,0.4), inset 0 1px 1px rgba(255,255,255,0.08)'
|
||||||
|
: '0 24px 54px rgba(15,23,42,0.06), inset 0 1px 1px rgba(255,255,255,0.6)',
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: darkMode ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.8)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Subtle animated background glow for the card */}
|
||||||
|
<motion.div
|
||||||
|
className="absolute -top-32 -right-32 w-64 h-64 rounded-full pointer-events-none z-0"
|
||||||
|
style={{
|
||||||
|
background: 'var(--accent)',
|
||||||
|
opacity: 0.15,
|
||||||
|
filter: 'blur(60px)'
|
||||||
|
}}
|
||||||
|
animate={{ scale: [1, 1.2, 1], opacity: [0.1, 0.2, 0.1] }}
|
||||||
|
transition={{ duration: 8, repeat: Infinity, ease: 'easeInOut' }}
|
||||||
|
/>
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="text-xs font-medium uppercase tracking-widest" style={{ color: 'var(--accent)' }}>
|
||||||
|
安全登录
|
||||||
|
</div>
|
||||||
|
{/* <h2 className="mt-1 text-2xl font-semibold tracking-[-0.03em]" style={{ color: 'var(--text-primary)' }}>
|
||||||
|
验证访问令牌
|
||||||
|
</h2> */}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-0.5">
|
||||||
|
{THEME_OPTIONS.map(({ mode: m, icon: Icon, label }) => {
|
||||||
|
const active = mode === m;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={m}
|
||||||
|
title={label}
|
||||||
|
onClick={() => setMode(m)}
|
||||||
|
className="relative flex size-8 cursor-pointer items-center justify-center rounded-xl transition-colors duration-200"
|
||||||
|
style={{ color: active ? 'var(--accent)' : 'var(--text-tertiary)' }}
|
||||||
|
>
|
||||||
|
{active && (
|
||||||
|
<motion.div
|
||||||
|
layoutId="theme-pill"
|
||||||
|
className="absolute inset-0 rounded-xl"
|
||||||
|
style={{ background: 'var(--accent-subtle)' }}
|
||||||
|
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Icon size={14} className="relative z-10" />
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<motion.form
|
||||||
|
initial={{ opacity: 0, y: 12 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ duration: 0.45, delay: 0.26 }}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
className="relative z-10 mt-6 flex flex-col gap-5"
|
||||||
|
>
|
||||||
|
<motion.div
|
||||||
|
key={shakeKey}
|
||||||
|
className="relative flex items-center justify-between overflow-hidden rounded-2xl"
|
||||||
|
style={{
|
||||||
|
background: darkMode ? 'rgba(0,0,0,0.2)' : 'rgba(255,255,255,0.6)',
|
||||||
|
boxShadow: 'inset 0 2px 4px rgba(0,0,0,0.05)',
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: darkMode ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.04)',
|
||||||
|
transition: 'all 0.3s ease',
|
||||||
|
}}
|
||||||
|
whileFocus={{ borderColor: 'var(--accent)', boxShadow: '0 0 0 2px var(--accent-subtle)' }}
|
||||||
|
animate={shakeKey > 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}}
|
||||||
|
transition={{ duration: 0.45, ease: 'easeInOut' }}
|
||||||
|
>
|
||||||
|
<div className="flex h-14 flex-1 items-center px-4">
|
||||||
|
<div
|
||||||
|
className="mr-3 shrink-0"
|
||||||
|
style={{ color: 'var(--text-tertiary)', transition: 'color 0.3s' }}
|
||||||
|
>
|
||||||
|
<KeyRound size={16} />
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type={showPwd ? 'text' : 'password'}
|
||||||
|
placeholder="输入访问令牌"
|
||||||
|
value={password}
|
||||||
|
onChange={e => setPassword(e.target.value)}
|
||||||
|
autoFocus
|
||||||
|
className="h-full w-full bg-transparent text-sm font-medium outline-none placeholder:font-normal"
|
||||||
|
style={{
|
||||||
|
color: 'var(--text-primary)',
|
||||||
|
}}
|
||||||
|
onFocus={e => {
|
||||||
|
const icon = e.target.previousElementSibling as HTMLElement;
|
||||||
|
if (icon) icon.style.color = 'var(--accent)';
|
||||||
|
}}
|
||||||
|
onBlur={e => {
|
||||||
|
const icon = e.target.previousElementSibling as HTMLElement;
|
||||||
|
if (icon) icon.style.color = 'var(--text-tertiary)';
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
tabIndex={-1}
|
||||||
|
onClick={() => setShowPwd(v => !v)}
|
||||||
|
className="flex h-14 w-12 shrink-0 cursor-pointer items-center justify-center transition-colors hover:bg-black/5 dark:hover:bg-white/5"
|
||||||
|
style={{ color: 'var(--text-tertiary)' }}
|
||||||
|
>
|
||||||
|
{showPwd ? <EyeOff size={15} /> : <Eye size={15} />}
|
||||||
|
</button>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
<AnimatePresence>
|
||||||
|
{error && (
|
||||||
|
<motion.p
|
||||||
|
key="err"
|
||||||
|
initial={{ opacity: 0, y: -6, scale: 0.97 }}
|
||||||
|
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||||
|
exit={{ opacity: 0, y: -4, scale: 0.97 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
className="rounded-2xl px-4 py-3 text-center text-xs"
|
||||||
|
style={{
|
||||||
|
color: 'var(--color-danger)',
|
||||||
|
background: 'rgba(248,113,113,0.08)',
|
||||||
|
border: '1px solid rgba(248,113,113,0.18)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{error}
|
||||||
|
</motion.p>
|
||||||
|
)}
|
||||||
|
</AnimatePresence>
|
||||||
|
|
||||||
|
<motion.button
|
||||||
|
whileHover={{ scale: 1.015, borderColor: 'var(--accent)', color: 'var(--accent)' }}
|
||||||
|
whileTap={{ scale: 0.985 }}
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="relative mt-2 flex h-13 cursor-pointer items-center justify-center overflow-hidden rounded-2xl text-sm font-medium disabled:cursor-not-allowed disabled:opacity-75"
|
||||||
|
style={{
|
||||||
|
background: darkMode ? 'rgba(255, 255, 255, 0.04)' : 'rgba(0, 0, 0, 0.02)',
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: darkMode ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.06)',
|
||||||
|
color: 'var(--text-primary)',
|
||||||
|
transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span className="relative z-10 flex items-center justify-center gap-2 tracking-wide">
|
||||||
|
{loading ? (
|
||||||
|
<>
|
||||||
|
<motion.span
|
||||||
|
animate={{ rotate: 360 }}
|
||||||
|
transition={{ duration: 0.8, ease: 'linear', repeat: Infinity }}
|
||||||
|
className="inline-block size-4 rounded-full border-2 border-t-transparent"
|
||||||
|
style={{ borderColor: 'currentColor', borderTopColor: 'transparent' }}
|
||||||
|
/>
|
||||||
|
验证中…
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
进入控制台
|
||||||
|
<ArrowRight size={16} strokeWidth={2} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</motion.button>
|
||||||
|
</motion.form>
|
||||||
|
</motion.div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
import { Users, Activity, Cpu, RefreshCw, Loader2, CheckCircle2, AlertCircle, Unplug } from 'lucide-react';
|
||||||
|
import { motion } from 'framer-motion';
|
||||||
|
import { StatCard } from '../ui/StatCard';
|
||||||
|
import { useTheme } from '../../contexts/ThemeContext';
|
||||||
|
import type { QQInfo, HookProcessInfo } from '../../types';
|
||||||
|
|
||||||
|
interface OverviewPageProps {
|
||||||
|
qqList: QQInfo[];
|
||||||
|
status: string;
|
||||||
|
processList: HookProcessInfo[];
|
||||||
|
processLoadingPid: number | null;
|
||||||
|
processUnloadingPid: number | null;
|
||||||
|
processActionStatus: string;
|
||||||
|
onRefreshProcesses: () => void;
|
||||||
|
onLoadProcess: (pid: number) => void;
|
||||||
|
onUnloadProcess: (pid: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
|
||||||
|
available: '可加载',
|
||||||
|
loading: '加载中',
|
||||||
|
loaded: '等待登录',
|
||||||
|
online: '已在线',
|
||||||
|
error: '错误',
|
||||||
|
disconnected: '已断开',
|
||||||
|
};
|
||||||
|
|
||||||
|
function processStatusColor(status: HookProcessInfo['status']): string {
|
||||||
|
if (status === 'online') return 'var(--color-success)';
|
||||||
|
if (status === 'error' || status === 'disconnected') return 'var(--color-danger)';
|
||||||
|
if (status === 'loading' || status === 'loaded') return 'var(--accent)';
|
||||||
|
return 'var(--text-secondary)';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function OverviewPage({
|
||||||
|
qqList,
|
||||||
|
status,
|
||||||
|
processList,
|
||||||
|
processLoadingPid,
|
||||||
|
processUnloadingPid,
|
||||||
|
processActionStatus,
|
||||||
|
onRefreshProcesses,
|
||||||
|
onLoadProcess,
|
||||||
|
onUnloadProcess,
|
||||||
|
}: OverviewPageProps) {
|
||||||
|
const { resolved } = useTheme();
|
||||||
|
const dark = resolved === 'dark';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8">
|
||||||
|
{/* Stat cards */}
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||||
|
<StatCard
|
||||||
|
label="接入账号"
|
||||||
|
value={String(qqList.length)}
|
||||||
|
icon={<Users size={18} strokeWidth={2} />}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
label="服务状态"
|
||||||
|
value={status === '已连接' ? '运行中' : status}
|
||||||
|
icon={<Activity size={18} strokeWidth={2} />}
|
||||||
|
accent={status === '已连接' ? 'success' : 'danger'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 12 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.05, duration: 0.3 }}
|
||||||
|
className="rounded-xl p-4"
|
||||||
|
style={{
|
||||||
|
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
|
||||||
|
backdropFilter: 'blur(32px) saturate(1.2)',
|
||||||
|
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
|
||||||
|
boxShadow: dark
|
||||||
|
? '0 8px 32px rgba(0,0,0,0.3), inset 0 1px 1px rgba(255,255,255,0.06)'
|
||||||
|
: '0 8px 24px rgba(15,23,42,0.04), inset 0 1px 1px rgba(255,255,255,0.5)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between gap-3 mb-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div
|
||||||
|
className="size-9 rounded-lg flex items-center justify-center"
|
||||||
|
style={{ background: 'var(--accent-subtle)', color: 'var(--accent)' }}
|
||||||
|
>
|
||||||
|
<Cpu size={17} strokeWidth={2} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2 className="text-sm font-semibold" style={{ color: 'var(--text-primary)' }}>
|
||||||
|
选择 QQ 进程
|
||||||
|
</h2>
|
||||||
|
<p className="text-xs mt-0.5" style={{ color: 'var(--text-secondary)' }}>
|
||||||
|
加载 SnowLuma 后会监听登录状态,登录成功后自动接入原有 OneBot 流程
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={onRefreshProcesses}
|
||||||
|
className="h-8 px-3 rounded-lg text-xs font-medium inline-flex items-center gap-1.5 cursor-pointer"
|
||||||
|
style={{
|
||||||
|
color: 'var(--text-secondary)',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
background: 'transparent',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<RefreshCw size={13} />
|
||||||
|
刷新
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{processActionStatus && (
|
||||||
|
<div
|
||||||
|
className="mb-3 rounded-lg px-3 py-2 text-xs"
|
||||||
|
style={{
|
||||||
|
color: 'var(--accent)',
|
||||||
|
background: 'var(--accent-subtle)',
|
||||||
|
border: '1px solid color-mix(in srgb, var(--accent) 20%, transparent)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{processActionStatus}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{processList.length > 0 ? (
|
||||||
|
<div className="grid grid-cols-1 xl:grid-cols-2 gap-3">
|
||||||
|
{processList.map((proc, idx) => {
|
||||||
|
const loading = processLoadingPid === proc.pid || proc.status === 'loading';
|
||||||
|
const unloading = processUnloadingPid === proc.pid;
|
||||||
|
const busy = loading || unloading;
|
||||||
|
const online = proc.status === 'online';
|
||||||
|
const canUnload = proc.injected || proc.status === 'loaded' || online || proc.status === 'disconnected';
|
||||||
|
const disabled = busy;
|
||||||
|
const actionLabel = canUnload
|
||||||
|
? unloading ? '卸载中' : '卸载'
|
||||||
|
: loading ? '加载中' : '加载';
|
||||||
|
const action = canUnload ? () => onUnloadProcess(proc.pid) : () => onLoadProcess(proc.pid);
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
key={proc.pid}
|
||||||
|
initial={{ opacity: 0, y: 8 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.08 + idx * 0.03, duration: 0.22 }}
|
||||||
|
className="flex items-center gap-3 rounded-xl p-3 overflow-hidden"
|
||||||
|
style={{
|
||||||
|
background: dark ? 'rgba(255,255,255,0.03)' : 'rgba(255,255,255,0.46)',
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="size-10 rounded-lg flex items-center justify-center shrink-0"
|
||||||
|
style={{ background: 'var(--accent-subtle)', color: 'var(--accent)' }}
|
||||||
|
>
|
||||||
|
{online ? <CheckCircle2 size={18} /> : proc.status === 'error' ? <AlertCircle size={18} /> : <Cpu size={18} />}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
|
<span className="text-sm font-semibold truncate" style={{ color: 'var(--text-primary)' }}>
|
||||||
|
{proc.name || 'QQ.exe'}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="text-[11px] px-1.5 py-0.5 rounded-md shrink-0"
|
||||||
|
style={{
|
||||||
|
color: processStatusColor(proc.status),
|
||||||
|
background: dark ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.6)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{processStatusLabel[proc.status]}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs mt-0.5 truncate" style={{ color: 'var(--text-secondary)', fontFamily: 'var(--font-mono)' }}>
|
||||||
|
PID {proc.pid}{proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''}
|
||||||
|
</div>
|
||||||
|
{proc.path && (
|
||||||
|
<div className="text-[11px] mt-0.5 truncate" title={proc.path} style={{ color: 'var(--text-tertiary)' }}>
|
||||||
|
{proc.path}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{proc.error && (
|
||||||
|
<div className="text-[11px] mt-1 truncate" title={proc.error} style={{ color: 'var(--color-danger)' }}>
|
||||||
|
{proc.error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={action}
|
||||||
|
disabled={disabled}
|
||||||
|
className="h-8 px-3 rounded-lg text-xs font-semibold inline-flex items-center gap-1.5 shrink-0"
|
||||||
|
style={{
|
||||||
|
color: disabled ? 'var(--text-tertiary)' : canUnload ? 'var(--color-danger)' : 'white',
|
||||||
|
background: disabled ? 'var(--bg-hover)' : canUnload ? 'rgba(248,113,113,0.08)' : 'linear-gradient(135deg, var(--accent), #818cf8)',
|
||||||
|
cursor: disabled ? 'default' : 'pointer',
|
||||||
|
border: canUnload ? '1px solid rgba(248,113,113,0.2)' : '1px solid transparent',
|
||||||
|
boxShadow: disabled || canUnload ? 'none' : '0 8px 18px var(--accent-glow)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{busy && <Loader2 size={13} className="animate-spin" />}
|
||||||
|
{!busy && canUnload && <Unplug size={13} />}
|
||||||
|
{actionLabel}
|
||||||
|
</button>
|
||||||
|
</motion.div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
className="flex flex-col items-center justify-center py-10 rounded-xl gap-2"
|
||||||
|
style={{
|
||||||
|
border: '1px dashed',
|
||||||
|
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.08)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Cpu size={30} strokeWidth={1.5} style={{ color: 'var(--text-tertiary)' }} />
|
||||||
|
<p className="text-sm font-medium" style={{ color: 'var(--text-secondary)' }}>未检测到可加载 QQ 主进程</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Account list */}
|
||||||
|
{qqList.length > 0 && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 12 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.1, duration: 0.3 }}
|
||||||
|
>
|
||||||
|
<h2 className="text-sm font-semibold mb-4" style={{ color: 'var(--text-primary)' }}>
|
||||||
|
在线会话
|
||||||
|
</h2>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3">
|
||||||
|
{qqList.map((q, idx) => (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 8 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.1 + idx * 0.04, duration: 0.25 }}
|
||||||
|
whileHover={{ y: -2 }}
|
||||||
|
key={q.uin}
|
||||||
|
className="flex items-center gap-3 p-4 rounded-xl cursor-default group overflow-hidden"
|
||||||
|
style={{
|
||||||
|
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
|
||||||
|
backdropFilter: 'blur(32px) saturate(1.2)',
|
||||||
|
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
|
||||||
|
boxShadow: dark
|
||||||
|
? '0 8px 32px rgba(0,0,0,0.3), inset 0 1px 1px rgba(255,255,255,0.06)'
|
||||||
|
: '0 8px 24px rgba(15,23,42,0.04), inset 0 1px 1px rgba(255,255,255,0.5)',
|
||||||
|
transition: 'var(--transition-base)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="size-10 rounded-lg flex items-center justify-center text-white text-sm font-bold shrink-0"
|
||||||
|
style={{
|
||||||
|
background: 'linear-gradient(135deg, var(--accent), #818cf8)',
|
||||||
|
boxShadow: '0 0 12px var(--accent-glow)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{q.nickname[0]?.toUpperCase() || '?'}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="text-sm font-semibold truncate" style={{ color: 'var(--text-primary)' }}>
|
||||||
|
{q.nickname}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="text-xs mt-0.5 truncate"
|
||||||
|
style={{ color: 'var(--text-secondary)', fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' }}
|
||||||
|
>
|
||||||
|
{q.uin}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
className="size-2 rounded-full shrink-0 animate-pulse"
|
||||||
|
style={{ background: 'var(--color-success)', boxShadow: '0 0 8px rgba(52,211,153,0.5)' }}
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{qqList.length === 0 && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }} animate={{ opacity: 1 }}
|
||||||
|
className="flex flex-col items-center justify-center py-16 rounded-xl gap-3"
|
||||||
|
style={{
|
||||||
|
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
|
||||||
|
border: '1px dashed',
|
||||||
|
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.08)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Users size={36} strokeWidth={1.5} style={{ color: 'var(--text-tertiary)' }} />
|
||||||
|
<p className="text-sm font-medium" style={{ color: 'var(--text-secondary)' }}>暂无在线会话</p>
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { X } from 'lucide-react';
|
||||||
|
import { motion } from 'framer-motion';
|
||||||
|
|
||||||
|
interface EndpointRowProps {
|
||||||
|
onRemove: () => void;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EndpointRow({ onRemove, children }: EndpointRowProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="flex items-end gap-3 px-5 py-4"
|
||||||
|
style={{ borderBottom: '1px solid var(--border-subtle)', transition: 'var(--transition-fast)' }}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<motion.button
|
||||||
|
whileHover={{ scale: 1.1 }}
|
||||||
|
whileTap={{ scale: 0.9 }}
|
||||||
|
onClick={onRemove}
|
||||||
|
className="size-7 shrink-0 flex items-center justify-center rounded-lg cursor-pointer mb-0.5"
|
||||||
|
style={{ color: 'var(--text-tertiary)', transition: 'var(--transition-fast)' }}
|
||||||
|
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-danger)'; e.currentTarget.style.background = 'rgba(248,113,113,0.08)'; }}
|
||||||
|
onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-tertiary)'; e.currentTarget.style.background = 'transparent'; }}
|
||||||
|
>
|
||||||
|
<X size={14} />
|
||||||
|
</motion.button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user