Compare commits
70 Commits
v1.6.0
...
chore.reco
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c39b3f5c4e | ||
|
|
2af273b9e2 | ||
|
|
144e0fdd59 | ||
|
|
1565749105 | ||
|
|
e53a8a01b7 | ||
|
|
3afbcfaae5 | ||
|
|
c3b328f91d | ||
|
|
7942c47808 | ||
|
|
46d93e715a | ||
|
|
a9027a8610 | ||
|
|
5853dc63ff | ||
|
|
ca14cb5437 | ||
|
|
a978d27f3a | ||
|
|
5a5b9d13d1 | ||
|
|
b62a6edd37 | ||
|
|
4d97f02fe9 | ||
|
|
c8dd520d65 | ||
|
|
8b313fe088 | ||
|
|
049ef2960c | ||
|
|
a0d584375a | ||
|
|
51c2fa285a | ||
|
|
c862a157db | ||
|
|
d708be4627 | ||
|
|
3791addb43 | ||
|
|
a40cbdc316 | ||
|
|
7e2ba60073 | ||
|
|
e3e364db63 | ||
|
|
4a51e3d686 | ||
|
|
84de00e6ac | ||
|
|
08d02c6303 | ||
|
|
e008920f39 | ||
|
|
99c74b4a66 | ||
|
|
92c6234b4f | ||
|
|
0d8e52ee77 | ||
|
|
2a4ca46a99 | ||
|
|
19a564991c | ||
|
|
466a10a00a | ||
|
|
f7cfec1a93 | ||
|
|
3ac4bc79f0 | ||
|
|
3f4b389e6d | ||
|
|
0d84e3b99e | ||
|
|
d8d7fa2ede | ||
|
|
8d33c1f76c | ||
|
|
946c1c6981 | ||
|
|
5f8fd26a28 | ||
|
|
64178893e4 | ||
|
|
6aa067f495 | ||
|
|
85298444eb | ||
|
|
758d21cc79 | ||
|
|
4b02367a5f | ||
|
|
de7533ca81 | ||
|
|
2e340f58a8 | ||
|
|
682d40b239 | ||
|
|
4a92292e49 | ||
|
|
60189d9c1d | ||
|
|
52f2528271 | ||
|
|
e67e0ea497 | ||
|
|
db8f0bdf50 | ||
|
|
8068f1893e | ||
|
|
34a572f153 | ||
|
|
5746dc628f | ||
|
|
1426d7adb2 | ||
|
|
f52a84d53f | ||
|
|
550cfa5cec | ||
|
|
d6a22d62ae | ||
|
|
a2b1d252d7 | ||
|
|
69b8dd7165 | ||
|
|
f04ec3ec36 | ||
|
|
82c1721466 | ||
|
|
df73f58598 |
114
.github/workflows/dev-build.yml
vendored
114
.github/workflows/dev-build.yml
vendored
@@ -8,14 +8,14 @@ on:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
cleanup:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
steps:
|
||||
- name: Delete old artifacts
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
let page = 1;
|
||||
@@ -38,17 +38,65 @@ jobs:
|
||||
page++;
|
||||
}
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# Runs `tsc --noEmit` (or `tsc -b`) in every workspace package that
|
||||
# exposes a `typecheck` script. Platform-independent, so a single
|
||||
# ubuntu runner is sufficient.
|
||||
- name: Type check all packages
|
||||
run: pnpm typecheck
|
||||
|
||||
build:
|
||||
needs: [cleanup, typecheck]
|
||||
permissions:
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- name: win-x64
|
||||
os: windows-latest
|
||||
target: win32-x64
|
||||
- name: linux-x64
|
||||
os: ubuntu-latest
|
||||
target: linux-x64
|
||||
- name: linux-arm64
|
||||
os: ubuntu-24.04-arm
|
||||
target: linux-arm64
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
@@ -58,45 +106,41 @@ jobs:
|
||||
|
||||
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||
- name: Build project
|
||||
env:
|
||||
SNOWLUMA_TARGET: ${{ matrix.target }}
|
||||
run: pnpm run build:all
|
||||
|
||||
- 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" }
|
||||
if (!(Test-Path "dist\native\websocket-win32-x64.node")) { throw "Missing dist\native\websocket-win32-x64.node" }
|
||||
|
||||
- name: Bundle runtime dependencies
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
# Two artifacts:
|
||||
# * SnowLuma-dev.zip – full bundle, ships node.exe (zero-install)
|
||||
# * SnowLuma-dev-no-node.zip – same bundle without node.exe (user provides Node >= 22)
|
||||
- name: Package artifact (no-node)
|
||||
shell: pwsh
|
||||
run: |
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-no-node.zip"
|
||||
|
||||
- name: Package artifact (with node.exe)
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
run: |
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-${{ matrix.name }}-lite.zip"
|
||||
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev.zip"
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-${{ matrix.name }}.zip"
|
||||
|
||||
- name: Upload artifact (with node.exe)
|
||||
uses: actions/upload-artifact@v4
|
||||
- name: Package (linux)
|
||||
if: startsWith(matrix.os, 'ubuntu')
|
||||
run: |
|
||||
chmod +x dist/launcher.sh
|
||||
tar -czf "SnowLuma-dev-${{ matrix.name }}-lite.tar.gz" -C dist .
|
||||
cp "$(command -v node)" dist/node
|
||||
chmod +x dist/node
|
||||
tar -czf "SnowLuma-dev-${{ matrix.name }}.tar.gz" -C dist .
|
||||
|
||||
# Single upload step — glob picks up both variants (.zip on Windows,
|
||||
# .tar.gz on Linux) for this matrix row.
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: SnowLuma-dev-${{ github.sha }}
|
||||
path: SnowLuma-dev.zip
|
||||
retention-days: 3
|
||||
overwrite: true
|
||||
|
||||
- name: Upload artifact (no-node)
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: SnowLuma-dev-${{ github.sha }}-no-node
|
||||
path: SnowLuma-dev-no-node.zip
|
||||
name: SnowLuma-dev-${{ github.sha }}-${{ matrix.name }}
|
||||
path: SnowLuma-dev-${{ matrix.name }}*
|
||||
retention-days: 3
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
|
||||
78
.github/workflows/dispatch-docker-release.yml
vendored
Normal file
78
.github/workflows/dispatch-docker-release.yml
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
name: Re-dispatch Docker Release
|
||||
|
||||
# Manual-only re-dispatcher for SnowLuma.Docker.Framework's docker-image.yml.
|
||||
#
|
||||
# The normal flow is automatic: release.yml's `dispatch-docker` job fires
|
||||
# after a tag-triggered release is published. This workflow exists for
|
||||
# rebuilding an existing release's Docker image without re-tagging — for
|
||||
# example after fixing the Dockerfile, rotating a Docker Hub credential,
|
||||
# or backfilling an older tag.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
snowluma_tag:
|
||||
description: 'SnowLuma release tag to rebuild (e.g. v0.5.0)'
|
||||
required: true
|
||||
docker_image_override:
|
||||
description: 'Override Docker image name (defaults to vars.DOCKER_IMAGE)'
|
||||
required: false
|
||||
default: ''
|
||||
platforms_override:
|
||||
description: 'Override platforms (defaults to vars.DOCKER_PLATFORMS or linux/amd64,linux/arm64)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Dispatch Docker rebuild
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
|
||||
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
|
||||
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
|
||||
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
|
||||
DOCKER_REF: ${{ vars.DOCKER_REF }}
|
||||
SNOWLUMA_TAG: ${{ inputs.snowluma_tag }}
|
||||
IMAGE_OVERRIDE: ${{ inputs.docker_image_override }}
|
||||
PLATFORMS_OVERRIDE: ${{ inputs.platforms_override }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
const target = process.env.RELEASE_REPOSITORY;
|
||||
if (!target || !target.includes('/')) {
|
||||
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
|
||||
}
|
||||
|
||||
const tag = process.env.SNOWLUMA_TAG;
|
||||
if (!tag) throw new Error('snowluma_tag input is required.');
|
||||
|
||||
const [owner, repo] = target.split('/');
|
||||
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
|
||||
const image = process.env.IMAGE_OVERRIDE || process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
|
||||
const platforms = process.env.PLATFORMS_OVERRIDE || process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: workflowId,
|
||||
ref,
|
||||
inputs: {
|
||||
image,
|
||||
tag,
|
||||
push: 'true',
|
||||
platforms,
|
||||
snowluma_tag: tag,
|
||||
snowluma_repository: sourceRepo,
|
||||
},
|
||||
});
|
||||
|
||||
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
|
||||
245
.github/workflows/promote-dev-to-main.yml
vendored
Normal file
245
.github/workflows/promote-dev-to-main.yml
vendored
Normal file
@@ -0,0 +1,245 @@
|
||||
name: Promote Dev to Main
|
||||
on:
|
||||
push:
|
||||
branches: [dev]
|
||||
tags: ['chore.*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
auto_merge:
|
||||
description: Enable auto-merge on the resulting PR
|
||||
type: choice
|
||||
options: ['true', 'false']
|
||||
default: 'true'
|
||||
merge_method:
|
||||
description: Merge strategy when auto-merging
|
||||
type: choice
|
||||
options: ['merge', 'squash', 'rebase']
|
||||
default: 'merge'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: promote-dev-to-main
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
decide:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
run: ${{ steps.check.outputs.run }}
|
||||
auto_merge: ${{ steps.check.outputs.auto_merge }}
|
||||
merge_method: ${{ steps.check.outputs.merge_method }}
|
||||
reason: ${{ steps.check.outputs.reason }}
|
||||
steps:
|
||||
- name: Decide whether to promote
|
||||
id: check
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
REF: ${{ github.ref }}
|
||||
REF_TYPE: ${{ github.ref_type }}
|
||||
HEAD_COMMIT_MSG: ${{ github.event.head_commit.message }}
|
||||
INPUT_AUTO_MERGE: ${{ inputs.auto_merge }}
|
||||
INPUT_MERGE_METHOD: ${{ inputs.merge_method }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
run='false'
|
||||
auto_merge='true'
|
||||
merge_method='merge'
|
||||
reason=''
|
||||
|
||||
case "${EVENT_NAME}" in
|
||||
workflow_dispatch)
|
||||
run='true'
|
||||
auto_merge="${INPUT_AUTO_MERGE:-true}"
|
||||
merge_method="${INPUT_MERGE_METHOD:-merge}"
|
||||
reason='Manual workflow_dispatch'
|
||||
;;
|
||||
push)
|
||||
if [ "${REF_TYPE}" = 'tag' ]; then
|
||||
run='true'
|
||||
merge_method='merge'
|
||||
reason="Tag push: ${REF}"
|
||||
elif [ "${REF}" = 'refs/heads/dev' ]; then
|
||||
msg="${HEAD_COMMIT_MSG:-}"
|
||||
if printf '%s' "${msg}" | grep -qiE '^\[merge\]|^chore\(release\):'; then
|
||||
run='true'
|
||||
merge_method='merge'
|
||||
reason='Commit message prefix on dev ([merge] or chore(release):)'
|
||||
else
|
||||
reason='Commit on dev without [merge] / chore(release): prefix'
|
||||
fi
|
||||
else
|
||||
reason="Push event on unhandled ref: ${REF}"
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
reason="Unhandled event: ${EVENT_NAME}"
|
||||
;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "run=${run}"
|
||||
echo "auto_merge=${auto_merge}"
|
||||
echo "merge_method=${merge_method}"
|
||||
echo "reason=${reason}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
{
|
||||
echo "## Promote decision"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Event | \`${EVENT_NAME}\` |"
|
||||
echo "| Ref | \`${REF}\` |"
|
||||
echo "| Run | \`${run}\` |"
|
||||
echo "| Auto-merge | \`${auto_merge}\` |"
|
||||
echo "| Merge method | \`${merge_method}\` |"
|
||||
echo "| Reason | ${reason} |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
promote:
|
||||
needs: decide
|
||||
if: needs.decide.outputs.run == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Validate GitHub App credentials
|
||||
env:
|
||||
APP_ID: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
|
||||
PRIVATE_KEY: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
|
||||
run: |
|
||||
if [ -z "${APP_ID}" ] || [ -z "${PRIVATE_KEY}" ]; then
|
||||
echo 'Missing SNOWLUMA_BOT_APP_ID and/or SNOWLUMA_BOT_PRIVATE_KEY secrets.' >&2
|
||||
echo 'Configure the same GitHub App used by the nnphook native PR flow.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Mint GitHub App installation token
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
repositories: ${{ github.event.repository.name }}
|
||||
|
||||
- name: Resolve bot identity
|
||||
id: bot
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bot_login="${APP_SLUG}[bot]"
|
||||
bot_id="$(gh api "/users/${bot_login}" --jq .id)"
|
||||
bot_email="${bot_id}+${bot_login}@users.noreply.github.com"
|
||||
{
|
||||
echo "login=${bot_login}"
|
||||
echo "id=${bot_id}"
|
||||
echo "email=${bot_email}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
echo "Resolved bot: ${bot_login} <${bot_email}>"
|
||||
|
||||
- name: Checkout main
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
- name: Compare dev to main
|
||||
id: diff
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin dev:dev
|
||||
ahead="$(git rev-list --count main..dev)"
|
||||
behind="$(git rev-list --count dev..main)"
|
||||
dev_sha="$(git rev-parse dev)"
|
||||
dev_short="$(git rev-parse --short dev)"
|
||||
{
|
||||
echo "ahead=${ahead}"
|
||||
echo "behind=${behind}"
|
||||
echo "dev_sha=${dev_sha}"
|
||||
echo "dev_short=${dev_short}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
if [ "${ahead}" = '0' ]; then
|
||||
echo "skip=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::dev has no commits ahead of main; nothing to promote."
|
||||
else
|
||||
echo "skip=false" >> "${GITHUB_OUTPUT}"
|
||||
echo "dev is ${ahead} ahead, ${behind} behind main."
|
||||
fi
|
||||
|
||||
- name: Ensure automation label exists
|
||||
if: steps.diff.outputs.skip != 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
run: |
|
||||
gh label create automation --color 0E8A16 --description 'Automated bot PRs' 2>/dev/null || true
|
||||
|
||||
- name: Create or update Pull Request
|
||||
id: pr
|
||||
if: steps.diff.outputs.skip != 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
DEV_SHA: ${{ steps.diff.outputs.dev_sha }}
|
||||
DEV_SHORT: ${{ steps.diff.outputs.dev_short }}
|
||||
AHEAD: ${{ steps.diff.outputs.ahead }}
|
||||
BEHIND: ${{ steps.diff.outputs.behind }}
|
||||
REASON: ${{ needs.decide.outputs.reason }}
|
||||
REF: ${{ github.ref }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
title="chore: promote dev → main (${DEV_SHORT})"
|
||||
|
||||
{
|
||||
echo "Automated promotion of \`dev\` into \`main\`."
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Source | \`dev\` @ \`${DEV_SHA}\` |"
|
||||
echo "| Trigger ref | \`${REF}\` |"
|
||||
echo "| Trigger reason | ${REASON} |"
|
||||
echo "| Workflow run | ${RUN_URL} |"
|
||||
echo "| Ahead / Behind | ${AHEAD} / ${BEHIND} |"
|
||||
echo
|
||||
echo "Created by SnowLuma Bot."
|
||||
} > pr-body.md
|
||||
|
||||
existing="$(gh pr list --base main --head dev --state open --json number --jq '.[0].number' 2>/dev/null || true)"
|
||||
if [ -n "${existing}" ]; then
|
||||
gh pr edit "${existing}" --title "${title}" --body-file pr-body.md
|
||||
pr_number="${existing}"
|
||||
echo "Updated existing PR #${pr_number}"
|
||||
else
|
||||
url="$(gh pr create --base main --head dev --title "${title}" --body-file pr-body.md --label automation)"
|
||||
pr_number="${url##*/}"
|
||||
echo "Opened new PR #${pr_number} (${url})"
|
||||
fi
|
||||
|
||||
echo "number=${pr_number}" >> "${GITHUB_OUTPUT}"
|
||||
{
|
||||
echo "## Promote PR"
|
||||
echo
|
||||
echo "- Number: #${pr_number}"
|
||||
echo "- Source: \`dev@${DEV_SHORT}\`"
|
||||
echo "- Ahead/Behind: ${AHEAD}/${BEHIND}"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
- name: Enable auto-merge
|
||||
if: steps.diff.outputs.skip != 'true' && needs.decide.outputs.auto_merge == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
PR_NUMBER: ${{ steps.pr.outputs.number }}
|
||||
MERGE_METHOD: ${{ needs.decide.outputs.merge_method }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
method_flag='--merge'
|
||||
case "${MERGE_METHOD}" in
|
||||
squash) method_flag='--squash' ;;
|
||||
rebase) method_flag='--rebase' ;;
|
||||
*) method_flag='--merge' ;;
|
||||
esac
|
||||
gh pr merge "${PR_NUMBER}" --auto ${method_flag}
|
||||
echo "::notice::Auto-merge enabled on PR #${PR_NUMBER} with strategy: ${MERGE_METHOD}"
|
||||
198
.github/workflows/release.yml
vendored
198
.github/workflows/release.yml
vendored
@@ -10,21 +10,34 @@ permissions:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- name: win-x64
|
||||
os: windows-latest
|
||||
target: win32-x64
|
||||
- name: linux-x64
|
||||
os: ubuntu-latest
|
||||
target: linux-x64
|
||||
- name: linux-arm64
|
||||
os: ubuntu-24.04-arm
|
||||
target: linux-arm64
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
@@ -34,71 +47,168 @@ jobs:
|
||||
|
||||
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||
- name: Build project
|
||||
env:
|
||||
SNOWLUMA_TARGET: ${{ matrix.target }}
|
||||
run: pnpm run build:all
|
||||
|
||||
- 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" }
|
||||
if (!(Test-Path "dist\native\websocket-win32-x64.node")) { throw "Missing dist\native\websocket-win32-x64.node" }
|
||||
|
||||
- name: Bundle runtime dependencies
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
# Two release archives:
|
||||
# * SnowLuma-<tag>-win-x64.zip – zero-install bundle (ships node.exe)
|
||||
# * SnowLuma-<tag>-win-x64-no-node.zip – same bundle without node.exe
|
||||
- name: Package release (no-node)
|
||||
shell: pwsh
|
||||
run: |
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-win-x64-no-node.zip"
|
||||
|
||||
- name: Package release (with node.exe)
|
||||
# Naming convention:
|
||||
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
run: |
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}-lite.zip"
|
||||
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-win-x64.zip"
|
||||
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.zip"
|
||||
|
||||
- name: Package (linux)
|
||||
if: startsWith(matrix.os, 'ubuntu')
|
||||
run: |
|
||||
chmod +x dist/launcher.sh
|
||||
tar -czf "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}-lite.tar.gz" -C dist .
|
||||
cp "$(command -v node)" dist/node
|
||||
chmod +x dist/node
|
||||
tar -czf "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.tar.gz" -C dist .
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: release-${{ matrix.name }}
|
||||
path: SnowLuma-${{ github.ref_name }}-${{ matrix.name }}*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout (for git log)
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Collect release assets
|
||||
run: |
|
||||
mkdir -p release
|
||||
find artifacts -type f \( -name '*.zip' -o -name '*.tar.gz' \) -exec cp {} release/ \;
|
||||
ls -lh release/
|
||||
|
||||
- name: Generate release note
|
||||
shell: pwsh
|
||||
shell: bash
|
||||
run: |
|
||||
$tag = "${{ github.ref_name }}"
|
||||
$previousTag = git describe --tags --abbrev=0 "$tag^" 2>$null
|
||||
if ($LASTEXITCODE -ne 0) { $previousTag = "" }
|
||||
if ($previousTag) {
|
||||
$range = "$previousTag..$tag"
|
||||
$changes = git log --pretty=format:"- %s (%h)" $range
|
||||
} else {
|
||||
$changes = git log --pretty=format:"- %s (%h)" $tag
|
||||
}
|
||||
if (!$changes) { $changes = "- No commit changes detected." }
|
||||
$body = @"
|
||||
# SnowLuma $tag
|
||||
tag="${GITHUB_REF_NAME}"
|
||||
previousTag="$(git describe --tags --abbrev=0 "${tag}^" 2>/dev/null || true)"
|
||||
if [[ -n "$previousTag" ]]; then
|
||||
changes="$(git log --pretty=format:'- %s (%h)' "$previousTag..$tag")"
|
||||
else
|
||||
changes="$(git log --pretty=format:'- %s (%h)' "$tag")"
|
||||
fi
|
||||
[[ -z "$changes" ]] && changes="- No commit changes detected."
|
||||
cat > release-notes.md <<EOF
|
||||
# SnowLuma ${tag}
|
||||
|
||||
## 发布概览
|
||||
本次发布提供 SnowLuma 的 Windows x64 构建产物,默认包含 WebUI。
|
||||
本次发布提供 SnowLuma 的 Windows x64 / Linux x64 / Linux arm64 构建产物,默认包含 WebUI。
|
||||
|
||||
## 下载说明
|
||||
- ``SnowLuma-$tag-win-x64.zip``:完整版本,内置 ``node.exe`` 与运行时依赖,解压即可使用。
|
||||
- ``SnowLuma-$tag-win-x64-no-node.zip``:不含 ``node.exe``,需自行安装 Node.js 22 及以上版本后再运行 ``launcher.bat`` 或 ``node index.mjs``。
|
||||
命名约定:
|
||||
- 无后缀 \`.zip/.tar.gz\`:完整版本,内置 \`node\`/\`node.exe\` 与运行时依赖,解压即可使用。
|
||||
- \`-lite\` 后缀:精简版本,不含 Node.js 运行时,需自行安装 Node.js 22+。
|
||||
|
||||
Windows:
|
||||
- \`SnowLuma-${tag}-win-x64.zip\`
|
||||
- \`SnowLuma-${tag}-win-x64-lite.zip\`
|
||||
|
||||
Linux x64:
|
||||
- \`SnowLuma-${tag}-linux-x64.tar.gz\`
|
||||
- \`SnowLuma-${tag}-linux-x64-lite.tar.gz\`
|
||||
|
||||
Linux arm64:
|
||||
- \`SnowLuma-${tag}-linux-arm64.tar.gz\`
|
||||
- \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\`
|
||||
|
||||
## 更新内容
|
||||
$changes
|
||||
${changes}
|
||||
|
||||
## 使用说明
|
||||
- 仅支持 Windows x64 环境。
|
||||
- 两个压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:8080 选择进程、调整配置或查看日志。
|
||||
- ``no-node`` 版本要求系统 ``node`` 可执行文件版本 >= 22。
|
||||
"@
|
||||
$body -replace "(?m)^ ", "" | Set-Content -Path "release-notes.md" -Encoding utf8
|
||||
- Windows x64:\`launcher.bat\` 或 \`node index.mjs\`。
|
||||
- Linux:\`./launcher.sh\` 或 \`node index.mjs\`。
|
||||
- 所有压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:5099。
|
||||
- Linux 版本仅提供 OneBot 桥接能力,NTQQ 进程注入仅在 Windows 下生效。
|
||||
EOF
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: SnowLuma-*.zip
|
||||
files: |
|
||||
release/*.zip
|
||||
release/*.tar.gz
|
||||
body_path: release-notes.md
|
||||
overwrite_files: true
|
||||
draft: false
|
||||
prerelease: ${{ contains(github.ref_name, '-') }}
|
||||
|
||||
# Triggers the Docker image build on SnowLuma.Docker.Framework once the
|
||||
# GitHub Release (and its per-arch tarballs) is published, so the Docker
|
||||
# workflow can pull the matching `SnowLuma-<tag>-linux-<arch>-lite.tar.gz`
|
||||
# asset and bake it into the container.
|
||||
#
|
||||
# Chained as a job dependency rather than via `on: release: published`
|
||||
# because workflows triggered by GITHUB_TOKEN cannot fire downstream
|
||||
# workflow events (GitHub anti-loop safeguard). Doing it as `needs: release`
|
||||
# keeps the dispatch under our PAT.
|
||||
dispatch-docker:
|
||||
needs: release
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Trigger Docker.Framework workflow_dispatch
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
|
||||
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
|
||||
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
|
||||
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
|
||||
DOCKER_REF: ${{ vars.DOCKER_REF }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
const target = process.env.RELEASE_REPOSITORY;
|
||||
if (!target || !target.includes('/')) {
|
||||
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
|
||||
}
|
||||
|
||||
const [owner, repo] = target.split('/');
|
||||
const tag = context.ref.replace('refs/tags/', '');
|
||||
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
|
||||
const image = process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
|
||||
const platforms = process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: workflowId,
|
||||
ref,
|
||||
inputs: {
|
||||
image,
|
||||
tag,
|
||||
push: 'true',
|
||||
platforms,
|
||||
snowluma_tag: tag,
|
||||
snowluma_repository: sourceRepo,
|
||||
},
|
||||
});
|
||||
|
||||
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
|
||||
|
||||
31
.gitignore
vendored
31
.gitignore
vendored
@@ -1,31 +1,16 @@
|
||||
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/
|
||||
# Ignore files generated by Claude
|
||||
.claude
|
||||
|
||||
# Runtime generated
|
||||
config.json
|
||||
|
||||
# Node / pnpm / monorepo
|
||||
node_modules/
|
||||
**/node_modules/
|
||||
dist/
|
||||
**/dist/
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
/config/
|
||||
/data/
|
||||
|
||||
# macOS metadata
|
||||
.DS_Store
|
||||
|
||||
106
CONTRIBUTING.md
Normal file
106
CONTRIBUTING.md
Normal file
@@ -0,0 +1,106 @@
|
||||
# 贡献指南
|
||||
|
||||
## 分支模型
|
||||
|
||||
SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
|
||||
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
|
||||
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先提交到 `dev`。
|
||||
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
|
||||
|
||||
## 把 `dev` 合并到 `main`
|
||||
|
||||
新增工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。三种触发方式:
|
||||
|
||||
无论使用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
|
||||
|
||||
### 1. 提交信息前缀(推荐日常使用)
|
||||
|
||||
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
|
||||
|
||||
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
|
||||
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
|
||||
|
||||
> 注意:是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
|
||||
|
||||
### 2. 推送 `chore.*` Tag
|
||||
|
||||
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发本工作流。这是和发布 tag 解耦的「合并触发 tag」:
|
||||
|
||||
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
|
||||
- `v*` → 仅触发 `release.yml`(构建发布产物)
|
||||
|
||||
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已经过完所有检查的 `main` HEAD 构建。
|
||||
|
||||
### 3. 手动触发
|
||||
|
||||
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
|
||||
|
||||
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
|
||||
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
|
||||
|
||||
工作流会按照当前 `dev` 与 `main` 的差异开 / 更新 PR。
|
||||
|
||||
## 启用 `main` 分支保护(必做)
|
||||
|
||||
仓库管理员需要在 GitHub 上为 `main` 配置一条规则集(Repository Rules)或经典分支保护,至少满足:
|
||||
|
||||
1. **Settings → Rules → Rulesets**(推荐)或 **Settings → Branches → Branch protection rules**。
|
||||
2. 选择 `main` 作为目标分支。
|
||||
3. 勾选:
|
||||
- **Restrict deletions** — 禁止删除 `main`。
|
||||
- **Require a pull request before merging** — 所有合并必须走 PR。
|
||||
- **Block force pushes** — 禁止强推。
|
||||
- **Require status checks to pass before merging(必勾)** — 把以下来自 `dev-build.yml` 的 check 全部加为 required:
|
||||
- `typecheck`
|
||||
- `build (win-x64)`
|
||||
- `build (linux-x64)`
|
||||
- `build (linux-arm64)`
|
||||
- **Require branches to be up to date before merging** — 保证 PR 合并前已 rebase 过最新 `main`。
|
||||
4. 在 **Bypass list / Allow specified actors to bypass** 中加入 `SnowLuma Bot` GitHub App。这样 `gh pr merge --auto` 才能在所有 required check 通过后由机器人自动完成合并;否则 PR 会一直卡在 auto-merge 等待人工 review。
|
||||
5. **不要**把任何用户加入 push 白名单,确保「禁止向 `main` 直接提交」的约束生效。第一次设置完后,连仓库管理员也只能通过 PR 改 `main`。
|
||||
|
||||
效果:任何对 `dev` 的推送都会先在 `dev-build.yml` 上跑 typecheck + 三个架构的 build;只有全部成功,promote 工作流的 `--auto` 合并才会真正发生。失败时 PR 会保留在 open 状态,修复后再次推到 `dev` 即可重新触发检查。
|
||||
|
||||
## 必需的 Secrets
|
||||
|
||||
`promote-dev-to-main.yml` 复用 `SnowLumaNative/build-native.yml` 同一个 GitHub App。请确认 SnowLuma 仓库(或 organization)级别已经配置:
|
||||
|
||||
- `SNOWLUMA_BOT_APP_ID` — 数字类型的 App ID。
|
||||
- `SNOWLUMA_BOT_PRIVATE_KEY` — 该 App 的 PEM 私钥。
|
||||
|
||||
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
|
||||
|
||||
## 本地工作流速查
|
||||
|
||||
```bash
|
||||
# 切到 dev 开发
|
||||
git checkout dev
|
||||
git pull
|
||||
|
||||
# 写代码 / 跑测试
|
||||
pnpm install
|
||||
pnpm typecheck
|
||||
pnpm -s --filter @snowluma/core test
|
||||
|
||||
# 普通提交(不会触发 promote)
|
||||
git commit -m "fix: something"
|
||||
git push
|
||||
|
||||
# 把 dev 合入 main(三选一)
|
||||
|
||||
# 方式 A:commit-msg 前缀
|
||||
git commit -m "chore(release): v1.7.0" # 或 "[merge] fix: hotfix"
|
||||
git push # → 触发 promote-dev-to-main
|
||||
|
||||
# 方式 B:chore.* 合并 tag(与发布 tag 解耦)
|
||||
git tag chore.merge-20240509 # 或 chore.promote-v1.7.0 等
|
||||
git push origin chore.merge-20240509 # → 触发 promote-dev-to-main
|
||||
|
||||
# 方式 C:在 Actions 页面手动 Run workflow
|
||||
|
||||
# 合并完成后,发布版本(在 main 上打 v* tag)
|
||||
git checkout main && git pull
|
||||
git tag v1.7.0
|
||||
git push origin v1.7.0 # → 仅触发 release.yml
|
||||
```
|
||||
57
README.md
57
README.md
@@ -3,60 +3,7 @@
|
||||
|
||||
|
||||
## 关于项目
|
||||
项目处于开发初期,仅支持部分功能,持续高速迭代中,仅支持有头。
|
||||
|
||||
## 仓库结构
|
||||
|
||||
本仓库使用 **pnpm workspace** 进行多包管理。
|
||||
|
||||
```
|
||||
SnowLuma/
|
||||
├─ packages/
|
||||
│ ├─ core/ @snowluma/core - Node.js 运行时(NTQQ packet sniffer + Hook + OneBot)
|
||||
│ ├─ webui/ webui - React + Vite 前端
|
||||
│ └─ runtime/ @snowluma/runtime - 发行包资源
|
||||
│ ├─ launcher.bat
|
||||
│ ├─ package.json (随 dist 一起发布的运行时依赖清单)
|
||||
│ └─ native/ 平台预编译产物 (snowluma-win32-x64.{dll,node})
|
||||
├─ tools/ 辅助脚本(如 Python OneBot WS 测试)
|
||||
├─ tsconfig.base.json
|
||||
├─ tsconfig.json monorepo 根 TS 项目(仅含 references)
|
||||
├─ pnpm-workspace.yaml
|
||||
└─ package.json monorepo 根(脚本委托给 pnpm filter)
|
||||
```
|
||||
|
||||
构建产物统一输出到仓库根 `dist/`,与发行流水线保持兼容。
|
||||
|
||||
## 常用命令
|
||||
|
||||
```bash
|
||||
# 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 开发 — 核心运行时(tsx)
|
||||
pnpm dev
|
||||
|
||||
# 开发 — WebUI 前端(vite dev server)
|
||||
pnpm dev:web
|
||||
|
||||
# 仅构建核心
|
||||
pnpm build
|
||||
|
||||
# 仅构建 WebUI
|
||||
pnpm build:webui
|
||||
|
||||
# 一次构建核心 + WebUI 完整发行版(顺序固定 core → webui)
|
||||
pnpm build:all
|
||||
|
||||
# 单元测试 / 类型检查 / Lint
|
||||
pnpm test
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
|
||||
# 直接对单个包操作
|
||||
pnpm --filter @snowluma/core dev
|
||||
pnpm --filter webui build
|
||||
```
|
||||
项目处于开发初期,仅支持部分功能,高速迭代中,随时可能出现破坏性更新。
|
||||
|
||||
## 鸣谢
|
||||
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
|
||||
@@ -72,4 +19,4 @@ pnpm --filter webui build
|
||||
## 加入我们
|
||||
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
|
||||
[SnowLuma-Tg](https://t.me/napcatqq)
|
||||
[SnowLuma-TG](https://t.me/napcatqq)
|
||||
3
RoadMap.md
Normal file
3
RoadMap.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# V2.0.0 前计划
|
||||
- [ ] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
|
||||
- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。
|
||||
@@ -9,6 +9,7 @@
|
||||
"build:webui": "pnpm --filter webui build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter webui build",
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
"test": "pnpm --filter @snowluma/core test",
|
||||
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
||||
@@ -17,6 +18,7 @@
|
||||
"start": "node dist/index.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"cross-env": "^10.1.0",
|
||||
"typescript": "catalog:"
|
||||
},
|
||||
"pnpm": {
|
||||
|
||||
3
packages/core/config/runtime.json
Normal file
3
packages/core/config/runtime.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"webuiPort": 8080
|
||||
}
|
||||
@@ -43,6 +43,10 @@ import {
|
||||
NTV2RichMediaRespSchema,
|
||||
GroupRecallRequestSchema,
|
||||
C2CRecallRequestSchema,
|
||||
SsoReadedReportReqSchema,
|
||||
SetStatusReqSchema,
|
||||
SetStatusRespSchema,
|
||||
OidbSetProfileSchema,
|
||||
} from './proto/oidb-action';
|
||||
import { FileUploadExtSchema } from './proto/highway';
|
||||
import {
|
||||
@@ -1242,3 +1246,116 @@ export async function recallPrivateMessage(
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
|
||||
}
|
||||
|
||||
// --- Mark message as read ---
|
||||
|
||||
export async function markPrivateMessageRead(
|
||||
bridge: Bridge,
|
||||
userId: number,
|
||||
msgSeq: number,
|
||||
timestamp: number = Math.floor(Date.now() / 1000)
|
||||
): Promise<void> {
|
||||
const uid = await resolveUserUid(bridge, userId);
|
||||
|
||||
const request = protoEncode({
|
||||
c2cList: [
|
||||
{
|
||||
uid,
|
||||
lastReadTime: BigInt(timestamp),
|
||||
lastReadSeq: BigInt(msgSeq),
|
||||
}
|
||||
]
|
||||
}, SsoReadedReportReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark private message read failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function markGroupMessageRead(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
msgSeq: number
|
||||
): Promise<void> {
|
||||
const request = protoEncode({
|
||||
groupList: [
|
||||
{
|
||||
groupUin: BigInt(groupId),
|
||||
lastReadSeq: BigInt(msgSeq),
|
||||
}
|
||||
]
|
||||
}, SsoReadedReportReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'mark group message read failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function setOnlineStatus(
|
||||
bridge: Bridge,
|
||||
status: number,
|
||||
extStatus: number = 0,
|
||||
batteryStatus: number = 100
|
||||
): Promise<void> {
|
||||
const request = protoEncode({
|
||||
status,
|
||||
extStatus,
|
||||
batteryStatus,
|
||||
}, SetStatusReqSchema);
|
||||
|
||||
const result = await bridge.sendRawPacket('trpc.qq_new_tech.status_svc.StatusService.SetStatus', request);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
|
||||
if (result.responseData && result.responseData.length > 0) {
|
||||
const resp = protoDecode(result.responseData, SetStatusRespSchema);
|
||||
if (!resp) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
if (resp.errCode !== undefined && resp.errCode !== 0) {
|
||||
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function setProfile(
|
||||
bridge: Bridge,
|
||||
nickname?: string,
|
||||
personalNote?: string
|
||||
): Promise<void> {
|
||||
const uin = BigInt(bridge.qqInfo.uin);
|
||||
const stringProfiles: any[] = [];
|
||||
const intProfiles: any[] = [];
|
||||
|
||||
if (nickname !== undefined) {
|
||||
stringProfiles.push({ fieldId: 20002, value: nickname });
|
||||
}
|
||||
|
||||
if (personalNote !== undefined) {
|
||||
stringProfiles.push({ fieldId: 102, value: personalNote });
|
||||
}
|
||||
|
||||
if (stringProfiles.length === 0 && intProfiles.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const req = {
|
||||
uin,
|
||||
stringProfiles,
|
||||
};
|
||||
|
||||
await sendOidbAndCheck(
|
||||
bridge,
|
||||
'OidbSvcTrpcTcp.0x112a_2',
|
||||
0x112A,
|
||||
2,
|
||||
req,
|
||||
OidbSetProfileSchema
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
fetchGroupRequests as fetchGroupRequests_,
|
||||
fetchDownloadRKeys as fetchDownloadRKeys_,
|
||||
} from './bridge-contacts';
|
||||
import type { WebHonorType } from './web/group-honor';
|
||||
import {
|
||||
muteGroupMember as muteGroupMember_,
|
||||
muteGroupAll as muteGroupAll_,
|
||||
@@ -60,13 +61,27 @@ import {
|
||||
setGroupReaction as setGroupReaction_,
|
||||
recallGroupMessage as recallGroupMessage_,
|
||||
recallPrivateMessage as recallPrivateMessage_,
|
||||
markPrivateMessageRead as markGroupMsgAsRead_,
|
||||
markGroupMessageRead as markPrivateMsgAsRead_,
|
||||
setFriendRemark as setFriendRemark_,
|
||||
fetchGroupFileCount as fetchGroupFileCount_,
|
||||
setOnlineStatus as setOnlineStatus_,
|
||||
setProfile as setProfile_,
|
||||
} from './bridge-actions';
|
||||
import {
|
||||
getGroupHonorInfo as getGroupHonorInfo_,
|
||||
forceFetchClientKey as forceFetchClientKey_,
|
||||
getGroupEssence as getGroupEssence_,
|
||||
getGroupEssenceAll as getGroupEssenceAll_,
|
||||
sendGroupNotice as sendGroupNotice_,
|
||||
getGroupNotice as getGroupNotice_,
|
||||
getCookiesStr as getCookiesStr_,
|
||||
getCsrfToken as getCsrfToken_,
|
||||
getCredentials as getCredentials_,
|
||||
} from './web-actions';
|
||||
import type { GroupFilesResult } from './bridge-actions';
|
||||
import type { MediaIndexNode } from './bridge-actions';
|
||||
|
||||
export type BridgeEventCallback = (event: QQEventVariant) => void;
|
||||
import { BridgeEventBus } from './event-bus';
|
||||
|
||||
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
|
||||
|
||||
@@ -86,6 +101,12 @@ export interface DownloadRKeyInfo {
|
||||
type: number;
|
||||
}
|
||||
|
||||
export interface ClientKeyInfo {
|
||||
clientKey: string;
|
||||
expireTime: string;
|
||||
keyIndex: string
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const eventLog = createLogger('Event');
|
||||
|
||||
@@ -94,10 +115,24 @@ export class Bridge {
|
||||
|
||||
private qqInfo_: QQInfo;
|
||||
private pids_ = new Set<number>();
|
||||
private eventCallback_: BridgeEventCallback | null = null;
|
||||
/**
|
||||
* Per-kind event subscription. Replaces the legacy single-callback
|
||||
* firehose: downstream consumers now register exactly the kinds they
|
||||
* care about and `emitEvent` fans out in parallel.
|
||||
*/
|
||||
readonly events = new BridgeEventBus();
|
||||
private cmdHandlers_ = new Map<string, CmdParser[]>();
|
||||
private packetClient_: PacketSender | null = null;
|
||||
private memberRefreshTasks_ = new Map<number, Promise<void>>();
|
||||
// Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls
|
||||
// and serves a fresh result for `kMemberListTtlMs` to all callers.
|
||||
// Without this, a busy OneBot client (e.g. MaiBot calling
|
||||
// get_group_member_info(no_cache=true) per inbound message) would
|
||||
// trigger one OIDB 0xfe7_3 per chat message per group; sustained rate
|
||||
// (>1k/h) is detected by Tencent risk-control and gets the account
|
||||
// banned for 7 days.
|
||||
private memberListInflight_ = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch_ = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
|
||||
// Sequence and random generators for outgoing messages
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
@@ -124,10 +159,6 @@ export class Bridge {
|
||||
this.cmdHandlers_.set(cmd, arr);
|
||||
}
|
||||
|
||||
setEventCallback(cb: BridgeEventCallback): void {
|
||||
this.eventCallback_ = cb;
|
||||
}
|
||||
|
||||
handlesCmd(cmd: string): boolean {
|
||||
return this.cmdHandlers_.has(cmd);
|
||||
}
|
||||
@@ -168,11 +199,9 @@ export class Bridge {
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
|
||||
// own onError hook so one bad listener never blocks the others.
|
||||
void this.events.emit(event);
|
||||
}
|
||||
|
||||
private triggerMemberCacheRefresh(event: QQEventVariant): void {
|
||||
@@ -372,7 +401,27 @@ export class Bridge {
|
||||
|
||||
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 fetchGroupMemberList(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
const kMemberListTtlMs = 60_000;
|
||||
const now = Date.now();
|
||||
const last = this.memberListLastFetch_.get(groupId);
|
||||
if (last && now - last.at < kMemberListTtlMs) {
|
||||
return last.data;
|
||||
}
|
||||
const inflight = this.memberListInflight_.get(groupId);
|
||||
if (inflight) return inflight;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const data = await fetchGroupMemberList_(this, groupId);
|
||||
this.memberListLastFetch_.set(groupId, { at: Date.now(), data });
|
||||
return data;
|
||||
} finally {
|
||||
this.memberListInflight_.delete(groupId);
|
||||
}
|
||||
})();
|
||||
this.memberListInflight_.set(groupId, task);
|
||||
return task;
|
||||
}
|
||||
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); }
|
||||
@@ -416,8 +465,42 @@ export class Bridge {
|
||||
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 markGroupMsgAsRead(groupId: number, sequence: number): Promise<void> { return markGroupMsgAsRead_(this, groupId, sequence); }
|
||||
async markPrivateMsgAsRead(userId: number, sequence: number): Promise<void> { return markPrivateMsgAsRead_(this, userId, sequence); }
|
||||
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
|
||||
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
|
||||
return getGroupHonorInfo_(this, groupId, type);
|
||||
}
|
||||
async forceFetchClientKey(): Promise<ClientKeyInfo> { return forceFetchClientKey_(this)}
|
||||
async getGroupEssence(groupId: number, pageStart: number = 0, pageLimit: number = 50): Promise<any> {
|
||||
return getGroupEssence_(this, groupId, pageStart, pageLimit);
|
||||
}
|
||||
|
||||
async getGroupEssenceAll(groupId: number): Promise<any> {
|
||||
return getGroupEssenceAll_(this, groupId);
|
||||
}
|
||||
|
||||
async sendGroupNotice(groupId: number, content: string, options?: any) {
|
||||
return sendGroupNotice_(this, groupId, content, options);
|
||||
}
|
||||
|
||||
async getGroupNotice(groupId: number) {
|
||||
return getGroupNotice_(this, groupId);
|
||||
}
|
||||
|
||||
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
|
||||
|
||||
// extend
|
||||
async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise<void> {
|
||||
return setOnlineStatus_(this, status, extStatus, batteryStatus);
|
||||
}
|
||||
async setProfile(nickname?: string, personalNote?: string): Promise<void> {
|
||||
return setProfile_(this, nickname, personalNote);
|
||||
}
|
||||
async getCookiesStr(domain: string): Promise<string> { return getCookiesStr_(this, domain); }
|
||||
async getCsrfToken(): Promise<number> { return getCsrfToken_(this); }
|
||||
async getCredentials(domain: string) { return getCredentials_(this, domain); }
|
||||
|
||||
}
|
||||
|
||||
// --- Module-level helper functions ---
|
||||
@@ -446,17 +529,10 @@ function elementsToText(elements: MessageElement[]): string {
|
||||
|
||||
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 'group_message':
|
||||
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));
|
||||
// Message logging is handled by OneBot layer with message ID
|
||||
break;
|
||||
case 'group_recall':
|
||||
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
MarkdownDataSchema,
|
||||
} from '../proto/action';
|
||||
import { uploadImageMsgInfo } from '../highway/image-upload';
|
||||
import { uploadPttMsgInfo } from '../highway/ptt-upload';
|
||||
|
||||
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
|
||||
|
||||
@@ -54,11 +55,21 @@ function makeMentionElem(element: MessageElement): ProtoElem {
|
||||
}
|
||||
|
||||
function makeReplyElem(element: MessageElement): ProtoElem {
|
||||
return {
|
||||
srcMsg: {
|
||||
origSeqs: [element.replySeq! & 0xFFFFFFFF],
|
||||
} as any,
|
||||
const seq = element.replySeq! & 0xFFFFFFFF;
|
||||
|
||||
const srcMsg: any = {
|
||||
origSeqs: [seq],
|
||||
};
|
||||
|
||||
// Add additional fields if available for better reply display
|
||||
if (element.replySenderUin) {
|
||||
srcMsg.senderUin = BigInt(element.replySenderUin);
|
||||
}
|
||||
if (element.replyTime) {
|
||||
srcMsg.time = element.replyTime;
|
||||
}
|
||||
|
||||
return { srcMsg };
|
||||
}
|
||||
|
||||
function makeJsonElem(element: MessageElement): ProtoElem {
|
||||
@@ -141,10 +152,28 @@ async function makeImageElem(ctx: SendContext, element: MessageElement): Promise
|
||||
};
|
||||
}
|
||||
|
||||
async function makePttElem(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 record target uid is missing');
|
||||
}
|
||||
|
||||
const msgInfo = await uploadPttMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
|
||||
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: msgInfo,
|
||||
businessType: 22,
|
||||
} 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.
|
||||
* Supports: text, face, at, reply, json, xml, markdown, image, record, forward.
|
||||
* Image and record elements trigger NTV2 highway upload via the SendContext.
|
||||
*/
|
||||
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
|
||||
const result: ProtoElem[] = [];
|
||||
@@ -192,6 +221,13 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
||||
break;
|
||||
|
||||
case 'record':
|
||||
if (ctx) {
|
||||
result.push(await makePttElem(ctx, elem));
|
||||
} else {
|
||||
console.warn('[ElemBuilder] record send requires SendContext');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'video':
|
||||
console.warn(`[ElemBuilder] ${elem.type} send not yet implemented`);
|
||||
break;
|
||||
|
||||
130
packages/core/src/bridge/event-bus.ts
Normal file
130
packages/core/src/bridge/event-bus.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
// Typed, per-kind pub/sub for bridge-level events.
|
||||
//
|
||||
// Replaces the single-callback firehose where every consumer received every
|
||||
// event variant and had to switch on `event.kind`. Now each downstream
|
||||
// concern (OneBot dispatch, member cache refresh, etc.) registers exactly
|
||||
// the kinds it cares about, much closer to NapCat's per-listener pattern.
|
||||
//
|
||||
// `emit` is fire-and-forget: subscribers can be sync or async; async
|
||||
// rejections are surfaced via `Promise.allSettled` and reported through the
|
||||
// optional `onError` hook so one buggy handler never starves the others.
|
||||
|
||||
import type { QQEventVariant } from './events';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
type EventKind = QQEventVariant['kind'];
|
||||
type EventOf<K extends EventKind> = Extract<QQEventVariant, { kind: K }>;
|
||||
|
||||
export type EventHandler<K extends EventKind> = (event: EventOf<K>) => void | Promise<void>;
|
||||
export type AnyEventHandler = (event: QQEventVariant) => void | Promise<void>;
|
||||
|
||||
export interface EventBusOptions {
|
||||
/** Logger label for handler failures. Defaults to `Bridge.Events`. */
|
||||
loggerName?: string;
|
||||
/** Override the default error reporter (e.g. for tests). */
|
||||
onError?: (kind: EventKind | '*', err: unknown) => void;
|
||||
}
|
||||
|
||||
const DEFAULT_LOGGER = createLogger('Bridge.Events');
|
||||
|
||||
export class BridgeEventBus {
|
||||
// Per-kind subscribers are stored as `Set<unknown>` so the container
|
||||
// doesn't carry a contravariant function type that fights TS variance
|
||||
// rules. The runtime invariant is straightforward: handlers stored under
|
||||
// key `K` only ever see `EventOf<K>` events, which is what the single
|
||||
// narrowing cast at the dispatch site below relies on.
|
||||
private readonly handlers = new Map<EventKind, Set<unknown>>();
|
||||
private readonly anyHandlers = new Set<AnyEventHandler>();
|
||||
private readonly onError: (kind: EventKind | '*', err: unknown) => void;
|
||||
|
||||
constructor(opts: EventBusOptions = {}) {
|
||||
if (opts.onError) {
|
||||
this.onError = opts.onError;
|
||||
} else {
|
||||
const log = opts.loggerName ? createLogger(opts.loggerName) : DEFAULT_LOGGER;
|
||||
this.onError = (kind, err) => {
|
||||
log.error(
|
||||
'event handler error [%s]: %s',
|
||||
kind,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Subscribe to one kind. Returns an unsubscribe function. */
|
||||
on<K extends EventKind>(kind: K, handler: EventHandler<K>): () => void {
|
||||
let set = this.handlers.get(kind);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.handlers.set(kind, set);
|
||||
}
|
||||
set.add(handler);
|
||||
return () => {
|
||||
this.handlers.get(kind)?.delete(handler);
|
||||
};
|
||||
}
|
||||
|
||||
/** Subscribe to every kind (low-volume callers like loggers). */
|
||||
onAny(handler: AnyEventHandler): () => void {
|
||||
this.anyHandlers.add(handler);
|
||||
return () => {
|
||||
this.anyHandlers.delete(handler);
|
||||
};
|
||||
}
|
||||
|
||||
off<K extends EventKind>(kind: K, handler: EventHandler<K>): void {
|
||||
this.handlers.get(kind)?.delete(handler);
|
||||
}
|
||||
|
||||
has(kind: EventKind): boolean {
|
||||
return (this.handlers.get(kind)?.size ?? 0) + this.anyHandlers.size > 0;
|
||||
}
|
||||
|
||||
/** Drop every subscriber. Mostly useful for tests. */
|
||||
clear(): void {
|
||||
this.handlers.clear();
|
||||
this.anyHandlers.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch an event in parallel to every subscriber for its kind plus every
|
||||
* onAny handler. Rejections are isolated per-handler — one bad subscriber
|
||||
* never blocks the others, and the returned promise resolves once every
|
||||
* subscriber settles.
|
||||
*/
|
||||
async emit<K extends EventKind>(event: EventOf<K>): Promise<void> {
|
||||
const kindHandlers = this.handlers.get(event.kind);
|
||||
if ((!kindHandlers || kindHandlers.size === 0) && this.anyHandlers.size === 0) {
|
||||
return;
|
||||
}
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
if (kindHandlers) {
|
||||
for (const handler of kindHandlers) {
|
||||
// Single narrowing cast — the only place we re-assert that handlers
|
||||
// stored under `event.kind` accept `EventOf<event.kind>` events.
|
||||
const typed = handler as EventHandler<K>;
|
||||
tasks.push(invoke(this.onError, event.kind, () => typed(event)));
|
||||
}
|
||||
}
|
||||
for (const handler of this.anyHandlers) {
|
||||
tasks.push(invoke(this.onError, '*', () => handler(event)));
|
||||
}
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
}
|
||||
|
||||
async function invoke(
|
||||
onError: (kind: EventKind | '*', err: unknown) => void,
|
||||
kind: EventKind | '*',
|
||||
fn: () => unknown,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const ret = fn();
|
||||
if (ret && typeof (ret as Promise<unknown>).then === 'function') {
|
||||
await ret;
|
||||
}
|
||||
} catch (err) {
|
||||
onError(kind, err);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,10 @@ export interface MessageElement {
|
||||
fileName?: string;
|
||||
fileSize?: number;
|
||||
replySeq?: number;
|
||||
replyMessageId?: number; // For reply: original message ID (for logging)
|
||||
replySenderUin?: number; // For reply: original sender's UIN
|
||||
replyTime?: number; // For reply: original message timestamp
|
||||
replyRandom?: number; // For reply: original message random/msgId
|
||||
url?: string;
|
||||
subType?: number;
|
||||
duration?: number;
|
||||
|
||||
161
packages/core/src/bridge/highway/ffmpeg-addon.ts
Normal file
161
packages/core/src/bridge/highway/ffmpeg-addon.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
// FFmpeg native addon wrapper — port of NapCat's FFmpegAddonAdapter.
|
||||
// No fallback: throws if the addon isn't available on this platform/arch.
|
||||
//
|
||||
// The addon is shipped under `native/ffmpeg/ffmpegAddon.<platform>.<arch>.node`
|
||||
// to match the layout used by the upstream NapCat build so the binaries
|
||||
// can be dropped in as-is.
|
||||
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface FFmpegVideoInfo {
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
format: string;
|
||||
videoCodec: string;
|
||||
image: Buffer;
|
||||
}
|
||||
|
||||
interface FFmpegNativeAddon {
|
||||
convertFile(inputFile: string, outputFile: string, format: string): Promise<{ success: boolean }>;
|
||||
getVideoInfo(filePath: string, format?: 'bmp' | 'bmp24'): Promise<FFmpegVideoInfo>;
|
||||
getDuration(filePath: string): Promise<number>;
|
||||
convertToNTSilkTct(inputPath: string, outputPath: string): Promise<void>;
|
||||
decodeAudioToPCM(filePath: string, pcmPath: string, sampleRate?: number): Promise<{ result: boolean; sampleRate: number }>;
|
||||
decodeAudioToFmt(filePath: string, pcmPath: string, format: string): Promise<{ channels: number; sampleRate: number; format: string }>;
|
||||
}
|
||||
|
||||
let cachedAddon: FFmpegNativeAddon | null = null;
|
||||
let cachedLoadError: string | null = null;
|
||||
|
||||
function addonFileName(): string {
|
||||
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
|
||||
}
|
||||
|
||||
function addonSearchDirs(): string[] {
|
||||
// Mirrors the hook injector's resolution strategy so the addon is found
|
||||
// regardless of whether we're running from:
|
||||
// 1. A released zip (dist/native/ffmpeg/<file>.node), where __dirname is
|
||||
// the dist root.
|
||||
// 2. The bundled build (repoRoot/dist/native/ffmpeg/<file>.node).
|
||||
// 3. `tsx` dev mode (packages/runtime/native/ffmpeg/<file>.node), where
|
||||
// __dirname is `packages/core/src/bridge/highway` — four levels deep
|
||||
// under `packages/`. Note: the hook injector lives at
|
||||
// `packages/core/src/hook` so it only needs 3 `..`; we need 4.
|
||||
return [
|
||||
path.resolve(__dirname, 'native', 'ffmpeg'),
|
||||
path.resolve(__dirname, '..', '..', '..', '..', 'runtime', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'dist', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native', 'ffmpeg'),
|
||||
];
|
||||
}
|
||||
|
||||
function resolveAddonPath(): string | null {
|
||||
const fileName = addonFileName();
|
||||
for (const dir of addonSearchDirs()) {
|
||||
const full = path.join(dir, fileName);
|
||||
if (fs.existsSync(full)) return full;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the ffmpegAddon once and return a cached instance.
|
||||
* Throws on first-use failure; subsequent calls replay the same error message
|
||||
* so callers don't silently fall back.
|
||||
*/
|
||||
export function getFFmpegAddon(): FFmpegNativeAddon {
|
||||
if (cachedAddon) return cachedAddon;
|
||||
if (cachedLoadError) throw new Error(cachedLoadError);
|
||||
|
||||
const addonPath = resolveAddonPath();
|
||||
if (!addonPath) {
|
||||
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
|
||||
try {
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
cachedAddon = mod.exports as unknown as FFmpegNativeAddon;
|
||||
return cachedAddon;
|
||||
} catch (error) {
|
||||
cachedLoadError = `failed to load ffmpegAddon (${addonPath}): ${error instanceof Error ? error.message : String(error)}`;
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether `filePath` is already an NT SILK container. The addon can
|
||||
* read any input directly so the only reason we peek at the header is to
|
||||
* skip the conversion (and the temp file) when the caller already fed us
|
||||
* a ready-to-upload silk file.
|
||||
*/
|
||||
export function isSilkFile(filePath: string): boolean {
|
||||
try {
|
||||
const fd = fs.openSync(filePath, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(10);
|
||||
fs.readSync(fd, buf, 0, 10, 0);
|
||||
const header = buf.toString();
|
||||
return header.includes('#!SILK') || header.includes('\x02#!SILK');
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export interface EncodeSilkResult {
|
||||
/** Absolute path to the silk file ready for highway upload. */
|
||||
path: string;
|
||||
/** Voice duration in whole seconds (>= 1). */
|
||||
duration: number;
|
||||
/** `true` if we wrote a new silk file and the caller should unlink it. */
|
||||
converted: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert `inputFile` to NT SILK when necessary and return the output path
|
||||
* + duration. The caller is responsible for unlinking the returned path
|
||||
* when `converted === true`.
|
||||
*/
|
||||
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
|
||||
const addon = getFFmpegAddon();
|
||||
|
||||
// Already silk — trust the file, just measure duration via the addon.
|
||||
if (isSilkFile(inputFile)) {
|
||||
let duration = 1;
|
||||
try {
|
||||
duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
} catch {
|
||||
// getDuration on a silk file occasionally fails on certain encodings;
|
||||
// the upload path only needs a rough, non-zero value, so fall back
|
||||
// to the size-based heuristic used by NapCat's audio.ts.
|
||||
const stat = fs.statSync(inputFile);
|
||||
duration = Math.max(1, Math.floor(stat.size / 1024 / 3));
|
||||
}
|
||||
return { path: inputFile, duration, converted: false };
|
||||
}
|
||||
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
const outPath = path.join(tempDir, crypto.randomUUID());
|
||||
await addon.convertToNTSilkTct(inputFile, outPath);
|
||||
if (!fs.existsSync(outPath)) {
|
||||
throw new Error('convertToNTSilkTct produced no output file');
|
||||
}
|
||||
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
return { path: outPath, duration, converted: true };
|
||||
}
|
||||
|
||||
/** Default location for temporary silk files. */
|
||||
export function defaultPttTempDir(): string {
|
||||
return path.join(os.tmpdir(), 'snowluma-ptt');
|
||||
}
|
||||
274
packages/core/src/bridge/highway/ptt-upload.ts
Normal file
274
packages/core/src/bridge/highway/ptt-upload.ts
Normal file
@@ -0,0 +1,274 @@
|
||||
// Voice (PTT) upload pipeline:
|
||||
// 1. resolve / fetch the source audio bytes,
|
||||
// 2. convert to NT SILK via the ffmpegAddon (skip if already silk),
|
||||
// 3. NTV2 OIDB upload request — 0x126E (group) / 0x126D (private),
|
||||
// 4. highway HTTP upload — commandId 1008 (group) / 1007 (private),
|
||||
// 5. return the encoded `MsgInfo` bytes ready for the commonElem.
|
||||
//
|
||||
// Port of NapCat's `UploadGroupPtt` / `UploadPrivatePtt` transformer + the
|
||||
// `uploadGroupPtt` / `uploadC2CPtt` paths in `PacketHighwayContext`.
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
|
||||
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 } from './utils';
|
||||
import {
|
||||
fetchHighwaySession,
|
||||
uploadHighwayHttp,
|
||||
buildHighwayExtend,
|
||||
} from './highway-client';
|
||||
import { encodeSilk, defaultPttTempDir } from './ffmpeg-addon';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Ptt');
|
||||
|
||||
export const PRIVATE_PTT_CMD_ID = 1007;
|
||||
export const GROUP_PTT_CMD_ID = 1008;
|
||||
|
||||
interface PttPayload {
|
||||
/** Silk bytes that get uploaded to highway. */
|
||||
bytes: Uint8Array;
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
fileName: string;
|
||||
/** Whole seconds, >= 1. */
|
||||
duration: number;
|
||||
/** Cleanup hooks invoked once the OIDB request + highway upload finish. */
|
||||
cleanups: Array<() => void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether `source` looks like a local filesystem path. The shape
|
||||
* matches the heuristics used inside `loadBinarySource`: we only reuse the
|
||||
* caller-supplied path verbatim for things the addon can read directly.
|
||||
*/
|
||||
function asLocalFilePath(source: string): string | null {
|
||||
if (!source) return null;
|
||||
if (source.startsWith('base64://')) return null;
|
||||
if (source.startsWith('http://') || source.startsWith('https://')) return null;
|
||||
|
||||
let filePath = source;
|
||||
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
|
||||
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
|
||||
const source = element.url || element.fileId || '';
|
||||
if (!source) throw new Error('record source is empty');
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
// Run all queued cleanups; callable both on the success path (via the
|
||||
// returned `cleanups` array) and the failure path (try/catch below).
|
||||
const runCleanups = () => {
|
||||
while (cleanups.length > 0) {
|
||||
const fn = cleanups.pop();
|
||||
if (!fn) continue;
|
||||
try { fn(); } catch { /* best-effort */ }
|
||||
}
|
||||
};
|
||||
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
try {
|
||||
// Resolve the on-disk path the addon should read. Anything that isn't
|
||||
// already a local file (base64, HTTP) gets staged into the temp dir.
|
||||
let inputPath: string;
|
||||
const local = asLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
inputPath = local;
|
||||
} else {
|
||||
const loaded = await loadBinarySource(source, 'record');
|
||||
inputPath = path.join(tempDir, `snowluma-ptt-in-${crypto.randomUUID()}`);
|
||||
fs.writeFileSync(inputPath, Buffer.from(loaded.bytes));
|
||||
cleanups.push(() => { try { fs.unlinkSync(inputPath); } catch { /* ignore */ } });
|
||||
}
|
||||
|
||||
const silk = await encodeSilk(inputPath, tempDir);
|
||||
if (silk.converted) {
|
||||
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
|
||||
log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
}
|
||||
|
||||
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
|
||||
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
|
||||
|
||||
const hashes = computeHashes(silkBytes);
|
||||
return {
|
||||
bytes: silkBytes,
|
||||
md5: hashes.md5,
|
||||
sha1: hashes.sha1,
|
||||
md5Hex: hashes.md5Hex,
|
||||
sha1Hex: hashes.sha1Hex,
|
||||
fileName: `${hashes.md5Hex}.amr`,
|
||||
duration: silk.duration,
|
||||
cleanups: [...cleanups],
|
||||
};
|
||||
} catch (err) {
|
||||
runCleanups();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function makeClientRandomId(): bigint {
|
||||
// Same trick NapCat uses: 8 random bytes, masked into the positive int64
|
||||
// range so it survives proto signed-int64 encoding without surprises.
|
||||
const buf = crypto.randomBytes(8);
|
||||
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
|
||||
}
|
||||
|
||||
async function startPttUpload(
|
||||
bridge: Bridge,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
ptt: PttPayload,
|
||||
): Promise<any> {
|
||||
const body: any = {
|
||||
reqHead: {
|
||||
// NapCat uses requestId=1 for group / 4 for c2c. Mirror it.
|
||||
common: { requestId: isGroup ? 1 : 4, command: 100 },
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: 3,
|
||||
sceneType: isGroup ? 2 : 1,
|
||||
...(isGroup
|
||||
? { group: { groupUin: Number(targetIdOrUid) } }
|
||||
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
|
||||
},
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
upload: {
|
||||
uploadInfo: [{
|
||||
fileInfo: {
|
||||
fileSize: ptt.bytes.length,
|
||||
fileHash: ptt.md5Hex,
|
||||
fileSha1: ptt.sha1Hex,
|
||||
fileName: ptt.fileName,
|
||||
// type=3 voice, voiceFormat=1 (silk).
|
||||
type: { type: 3, picFormat: 0, videoFormat: 0, voiceFormat: 1 },
|
||||
width: 0,
|
||||
height: 0,
|
||||
time: ptt.duration,
|
||||
original: 0,
|
||||
},
|
||||
subFileType: 0,
|
||||
}],
|
||||
tryFastUploadCompleted: true,
|
||||
srvSendMsg: false,
|
||||
clientRandomId: makeClientRandomId(),
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
extBizInfo: {
|
||||
// NapCat fills in a placeholder textSummary so the legacy compat
|
||||
// QMsg path still has something to render. Mirror it.
|
||||
pic: { textSummary: 'Nya~' },
|
||||
video: { bytesPbReserve: new Uint8Array(0) },
|
||||
ptt: {
|
||||
bytesReserve: new Uint8Array([0x08, 0x00, 0x38, 0x00]),
|
||||
bytesPbReserve: new Uint8Array(0),
|
||||
// `bytesGeneralFlags` differs between group / c2c voice. Lifted
|
||||
// verbatim from NapCat (UploadGroupPtt.ts / UploadPrivatePtt.ts).
|
||||
bytesGeneralFlags: isGroup
|
||||
? new Uint8Array([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00])
|
||||
: new Uint8Array([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
|
||||
},
|
||||
},
|
||||
clientSeq: 0,
|
||||
noNeedCompatMsg: false,
|
||||
},
|
||||
};
|
||||
|
||||
const oidbCmd = isGroup ? 0x126E : 0x126D;
|
||||
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x126e_100' : 'OidbSvcTrpcTcp.0x126d_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 || 'ptt upload request failed');
|
||||
}
|
||||
|
||||
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
|
||||
const resp: any = protoDecode(result.responseData, respBaseSchema);
|
||||
if (!resp) throw new Error('failed to decode ptt 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('ptt upload response body missing');
|
||||
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
|
||||
throw new Error(uploadBody.respHead.message ?? 'ptt upload failed');
|
||||
}
|
||||
return uploadBody.upload;
|
||||
}
|
||||
|
||||
function finalizePttMsgInfo(upload: any): Uint8Array {
|
||||
if (!upload?.msgInfo) throw new Error('ptt 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;
|
||||
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 a voice clip and return the encoded `MsgInfo` bytes that go inside
|
||||
* a `commonElem { serviceType: 48, businessType: 22 }`.
|
||||
*/
|
||||
export async function uploadPttMsgInfo(
|
||||
bridge: Bridge,
|
||||
isGroup: boolean,
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const tempDir = defaultPttTempDir();
|
||||
const ptt = await loadPtt(element, tempDir);
|
||||
try {
|
||||
const upload = await startPttUpload(bridge, isGroup, targetIdOrUid, ptt);
|
||||
|
||||
// Highway upload only happens when the server didn't fast-path the file
|
||||
// (uKey present == "we want the bytes"). Otherwise we just embed the
|
||||
// returned MsgInfo and trust the dedupe.
|
||||
const uKey = upload?.uKey ?? '';
|
||||
if (uKey && upload?.msgInfo) {
|
||||
log.debug('highway upload: bytes=%d md5=%s scene=%s', ptt.bytes.length, ptt.md5Hex, isGroup ? 'group' : 'c2c');
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], ptt.sha1);
|
||||
const commandId = isGroup ? GROUP_PTT_CMD_ID : PRIVATE_PTT_CMD_ID;
|
||||
await uploadHighwayHttp(bridge, session, commandId, ptt.bytes, ptt.md5, extend);
|
||||
} else {
|
||||
log.debug('ptt fast-uploaded (server already has md5=%s)', ptt.md5Hex);
|
||||
}
|
||||
|
||||
return finalizePttMsgInfo(upload);
|
||||
} finally {
|
||||
for (const fn of ptt.cleanups) {
|
||||
try { fn(); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
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';
|
||||
@@ -12,7 +11,6 @@ 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;
|
||||
@@ -28,11 +26,9 @@ export class BridgeManager {
|
||||
|
||||
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));
|
||||
@@ -115,11 +111,9 @@ export class BridgeManager {
|
||||
session = { qqInfo, bridge };
|
||||
this.sessions_.set(uin, session);
|
||||
|
||||
// Wire event callback
|
||||
bridge.setEventCallback((event) => {
|
||||
if (this.onBridgeEvent_) this.onBridgeEvent_(uin, event);
|
||||
});
|
||||
|
||||
// Each downstream consumer (e.g. OneBotInstance) subscribes to
|
||||
// `bridge.events` directly via the per-kind bus — there is no longer a
|
||||
// generic firehose to wire here.
|
||||
return { session, created: true };
|
||||
}
|
||||
|
||||
|
||||
@@ -786,3 +786,80 @@ export const OidbGroupFileCountViewReqSchema = {
|
||||
export const OidbGroupFileCountViewRespSchema = {
|
||||
count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountRespSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
// --- trpc.msg.msg_svc.MsgService.SsoReadedReport ---
|
||||
|
||||
export const GroupReadedReportItemSchema = {
|
||||
groupUin: { field: 1, type: 'uint64' as const },
|
||||
lastReadSeq: { field: 2, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const C2CReadedReportItemSchema = {
|
||||
uid: { field: 2, type: 'string' as const },
|
||||
lastReadTime: { field: 3, type: 'uint64' as const },
|
||||
lastReadSeq: { field: 4, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SsoReadedReportReqSchema = {
|
||||
groupList: { field: 1, type: 'repeated_message' as const, schema: GroupReadedReportItemSchema },
|
||||
c2cList: { field: 2, type: 'repeated_message' as const, schema: C2CReadedReportItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
// --- 0x102A_1: Get Client Key ---
|
||||
|
||||
export const OidbClientKeyReqSchema = {
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbClientKeyRespSchema = {
|
||||
keyIndex: { field: 2, type: 'uint32' as const },
|
||||
clientKey: { field: 3, type: 'string' as const },
|
||||
expireTime: { field: 4, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
// --- 0x102A_0: Get PSKey ---
|
||||
|
||||
export const OidbGetPskeyReqSchema = {
|
||||
domainList: { field: 1, type: 'repeated_string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbPskeyItemSchema = {
|
||||
domain: { field: 1, type: 'string' as const },
|
||||
pskey: { field: 2, type: 'string' as const },
|
||||
expireTime: { field: 3, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbGetPskeyRespSchema = {
|
||||
pskeyItems: { field: 1, type: 'repeated_message' as const, schema: OidbPskeyItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
export const SetStatusReqSchema = {
|
||||
status: { field: 1, type: 'int32' as const },
|
||||
extStatus: { field: 2, type: 'int32' as const },
|
||||
batteryStatus: { field: 3, type: 'int32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const SetStatusRespSchema = {
|
||||
errCode: { field: 1, type: 'int32' as const }, // 盲猜字段 1 是错误码(虽然成功时没下发,默认 0)
|
||||
errMsg: { field: 2, type: 'string' as const }, // 返回的 "set status success"
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
|
||||
export const OidbProfileStringItemSchema = {
|
||||
fieldId: { field: 1, type: 'uint32' as const },
|
||||
value: { field: 2, type: 'string' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbProfileIntItemSchema = {
|
||||
fieldId: { field: 1, type: 'uint32' as const },
|
||||
value: { field: 2, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbSetProfileSchema = {
|
||||
uin: { field: 1, type: 'uint64' as const },
|
||||
stringProfiles: { field: 2, type: 'repeated_message' as const, schema: OidbProfileStringItemSchema },
|
||||
intProfiles: { field: 3, type: 'repeated_message' as const, schema: OidbProfileIntItemSchema },
|
||||
} satisfies ProtoSchema;
|
||||
315
packages/core/src/bridge/web-actions.ts
Normal file
315
packages/core/src/bridge/web-actions.ts
Normal file
@@ -0,0 +1,315 @@
|
||||
// Web API operations extracted from Bridge.
|
||||
|
||||
import type { Bridge } from './bridge';
|
||||
import { sendOidbAndDecode } from './bridge-oidb';
|
||||
import { resolveUserUid } from './bridge-oidb';
|
||||
import {
|
||||
OidbClientKeyRespSchema,
|
||||
OidbClientKeyReqSchema,
|
||||
OidbGetPskeyReqSchema,
|
||||
OidbGetPskeyRespSchema
|
||||
} from './proto/oidb-action';
|
||||
import { RequestUtil } from './web/request-util';
|
||||
import { getHonorListWebAPI, WebHonorType } from './web/group-honor';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from './web/group-essence';
|
||||
import { setGroupNoticeWebAPI, getGroupNoticeWebAPI } from './web/group-notice';
|
||||
|
||||
export async function forceFetchClientKey(bridge: Bridge) {
|
||||
const resp = await sendOidbAndDecode<any>(
|
||||
bridge,
|
||||
'OidbSvcTrpcTcp.0x102a_1',
|
||||
0x102A,
|
||||
1,
|
||||
{},
|
||||
OidbClientKeyReqSchema,
|
||||
OidbClientKeyRespSchema
|
||||
);
|
||||
|
||||
const clientKey = resp?.clientKey || '';
|
||||
const keyIndex = String(resp?.keyIndex || '19'); // 不知道是什么
|
||||
|
||||
return {
|
||||
clientKey,
|
||||
keyIndex,
|
||||
expireTime: String(resp?.expireTime || '1800')
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPSkey(bridge: Bridge, domainList: string[]) {
|
||||
const resp = await sendOidbAndDecode<any>(
|
||||
bridge,
|
||||
'OidbSvcTrpcTcp.0x102a_0',
|
||||
0x102A,
|
||||
0,
|
||||
{ domainList },
|
||||
OidbGetPskeyReqSchema,
|
||||
OidbGetPskeyRespSchema
|
||||
);
|
||||
|
||||
const domainPskeyMap = new Map<string, string>();
|
||||
|
||||
if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) {
|
||||
for (const item of resp.pskeyItems) {
|
||||
if (item.domain && item.pskey) {
|
||||
domainPskeyMap.set(item.domain, item.pskey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
domainPskeyMap,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getCookies(bridge: Bridge, domain: string) {
|
||||
const ClientKeyData = await forceFetchClientKey(bridge);
|
||||
|
||||
// 构造 ptlogin2 跳转 URL
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.qqInfo.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.qqInfo.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
const data = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
|
||||
if (!data['p_skey'] || data['p_skey'].length === 0) {
|
||||
try {
|
||||
const pskeyData = await getPSkey(bridge, [domain]);
|
||||
const pskey = pskeyData.domainPskeyMap.get(domain);
|
||||
if (pskey) {
|
||||
data['p_skey'] = pskey;
|
||||
}
|
||||
} catch {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getGroupHonorInfo(bridge: Bridge, groupId: number, type: WebHonorType | string) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const honorInfo: any = {
|
||||
group_id: groupId,
|
||||
current_talkative: null,
|
||||
talkative_list: [],
|
||||
performer_list: [],
|
||||
legend_list: [],
|
||||
emotion_list: [],
|
||||
strong_newbie_list: [],
|
||||
};
|
||||
|
||||
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
|
||||
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
|
||||
if (talkativeList.length > 0) {
|
||||
honorInfo.current_talkative = talkativeList[0];
|
||||
honorInfo.talkative_list = talkativeList;
|
||||
}
|
||||
}
|
||||
|
||||
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
|
||||
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
|
||||
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
|
||||
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
|
||||
}
|
||||
|
||||
return honorInfo;
|
||||
}
|
||||
|
||||
export async function getSKey(bridge: Bridge): Promise<string> {
|
||||
const ClientKeyData = await forceFetchClientKey(bridge);
|
||||
|
||||
if (!ClientKeyData.clientKey) {
|
||||
throw new Error('getClientKey Error: clientKey is empty');
|
||||
}
|
||||
|
||||
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
|
||||
'&clientuin=' + bridge.qqInfo.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=' + u1 +
|
||||
'&keyindex=' + ClientKeyData.keyIndex;
|
||||
|
||||
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
const skey = cookies['skey'];
|
||||
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
|
||||
return skey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取群精华消息
|
||||
*/
|
||||
export async function getGroupEssence(bridge: Bridge, groupId: number, pageStart: number = 0, pageLimit: number = 50) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
|
||||
|
||||
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有群精华消息
|
||||
*/
|
||||
export async function getGroupEssenceAll(bridge: Bridge, groupId: number) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const essenceDataAll = await getGroupEssenceMsgAll(cookieObject, groupCode);
|
||||
|
||||
return essenceDataAll;
|
||||
}
|
||||
|
||||
export async function sendGroupNotice(
|
||||
bridge: Bridge,
|
||||
groupId: number,
|
||||
content: string,
|
||||
options?: {
|
||||
image?: string; // 未来如果要发图片,传路径进来
|
||||
pinned?: number;
|
||||
type?: number;
|
||||
confirm_required?: number;
|
||||
}
|
||||
) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
let picId = '';
|
||||
let imgWidth = 540;
|
||||
let imgHeight = 300;
|
||||
|
||||
|
||||
// 暂时不知道怎么实现,后面有空再看看
|
||||
|
||||
// if (options?.image) {
|
||||
// const picInfo = await bridge.uploadGroupBulletinPic(groupCode, options.image);
|
||||
// picId = picInfo.id;
|
||||
// imgWidth = picInfo.width;
|
||||
// imgHeight = picInfo.height;
|
||||
// }
|
||||
|
||||
const ret = await setGroupNoticeWebAPI(
|
||||
cookieObject,
|
||||
groupCode,
|
||||
content,
|
||||
options?.pinned ?? 0,
|
||||
options?.type ?? 1,
|
||||
1,
|
||||
1,
|
||||
options?.confirm_required ?? 1,
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight
|
||||
);
|
||||
|
||||
if (!ret || ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
export async function getGroupNotice(bridge: Bridge, groupId: number) {
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
|
||||
if (!ret) {
|
||||
throw new Error('获取公告失败');
|
||||
}
|
||||
|
||||
const retNotices: any[] = [];
|
||||
|
||||
if (ret.feeds) {
|
||||
for (const key in ret.feeds) {
|
||||
const feed = ret.feeds[key];
|
||||
if (!feed) continue;
|
||||
|
||||
const image = feed.msg?.pics?.map((pic) => ({
|
||||
id: pic.id,
|
||||
height: pic.h,
|
||||
width: pic.w,
|
||||
})) || [];
|
||||
|
||||
retNotices.push({
|
||||
notice_id: feed.fid,
|
||||
sender_id: feed.u,
|
||||
publish_time: feed.pubt,
|
||||
message: {
|
||||
text: feed.msg?.text || '',
|
||||
image: image,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: feed.read_num,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return retNotices;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取的公共算法:根据 skey/p_skey 计算 bkn (也就是 token / csrf_token)
|
||||
*/
|
||||
export function getBknFromSKey(skey: string): number {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
return hash & 2147483647;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Cookies (字符串格式)
|
||||
*/
|
||||
export async function getCookiesStr(bridge: Bridge, domain: string): Promise<string> {
|
||||
const cookieObject = await getCookies(bridge, domain);
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 CSRF Token (即 BKN)
|
||||
*/
|
||||
export async function getCsrfToken(bridge: Bridge): Promise<number> {
|
||||
|
||||
const skey = await getSKey(bridge);
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
return getBknFromSKey(skey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取凭证 (Cookies 字符串 + Token)
|
||||
*/
|
||||
export async function getCredentials(bridge: Bridge, domain: string) {
|
||||
const cookieObject = await getCookies(bridge, domain);
|
||||
const cookiesStr = Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
|
||||
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
const token = skey ? getBknFromSKey(skey) : 0;
|
||||
|
||||
return {
|
||||
cookies: cookiesStr,
|
||||
token: token,
|
||||
csrf_token: token
|
||||
};
|
||||
}
|
||||
66
packages/core/src/bridge/web/group-essence.ts
Normal file
66
packages/core/src/bridge/web/group-essence.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
|
||||
// 定义接口返回类型
|
||||
export interface GroupEssenceMsgRet {
|
||||
retcode: number;
|
||||
data: {
|
||||
is_end: boolean;
|
||||
msg_list: any[]; // 具体结构视需要补充
|
||||
[key: string]: any;
|
||||
};
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 分页获取群精华消息
|
||||
*/
|
||||
export async function getGroupEssenceMsg(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
pageStart: number = 0,
|
||||
pageLimit: number = 50
|
||||
): Promise<GroupEssenceMsgRet | undefined> {
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
|
||||
bkn: bkn,
|
||||
page_start: pageStart.toString(),
|
||||
page_limit: pageLimit.toString(),
|
||||
group_code: groupCode,
|
||||
}).toString()}`;
|
||||
|
||||
try {
|
||||
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret.retcode === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有群精华消息 (最多循环 20 页)
|
||||
*/
|
||||
export async function getGroupEssenceMsgAll(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string
|
||||
): Promise<GroupEssenceMsgRet[]> {
|
||||
const ret: GroupEssenceMsgRet[] = [];
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
|
||||
|
||||
if (!data) break;
|
||||
|
||||
ret.push(data);
|
||||
|
||||
if (data.data?.is_end) break;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
49
packages/core/src/bridge/web/group-honor.ts
Normal file
49
packages/core/src/bridge/web/group-honor.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
|
||||
export enum WebHonorType {
|
||||
TALKATIVE = 'talkative',
|
||||
PERFORMER = 'performer',
|
||||
LEGEND = 'legend',
|
||||
EMOTION = 'emotion',
|
||||
ALL = 'all',
|
||||
}
|
||||
|
||||
|
||||
async function fetchHonorData(cookieObject: Record<string, string>, groupCode: string, type: number) {
|
||||
let resJson;
|
||||
try {
|
||||
const res = await RequestUtil.HttpGetText(
|
||||
`https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
|
||||
gc: groupCode,
|
||||
type: type.toString(),
|
||||
}).toString()}`,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
|
||||
if (match?.[1]) {
|
||||
resJson = JSON.parse(match[1].trim());
|
||||
}
|
||||
return type === 1 ? resJson?.talkativeList : resJson?.actorList;
|
||||
} catch (e) {
|
||||
throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getHonorListWebAPI(cookieObject: Record<string, string>, groupCode: string, type: number) {
|
||||
try {
|
||||
const data = await fetchHonorData(cookieObject, groupCode, type);
|
||||
if (!data) return [];
|
||||
|
||||
return data.map((item: any) => ({
|
||||
user_id: item?.uin,
|
||||
nickname: item?.name,
|
||||
avatar: item?.avatar,
|
||||
description: item?.desc,
|
||||
}));
|
||||
} catch (e) {
|
||||
// console.error(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
112
packages/core/src/bridge/web/group-notice.ts
Normal file
112
packages/core/src/bridge/web/group-notice.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
|
||||
export interface SetNoticeRetSuccess {
|
||||
ec?: number;
|
||||
em?: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface WebApiGroupNoticeFeed {
|
||||
fid: string;
|
||||
u: number;
|
||||
pubt: number;
|
||||
msg: {
|
||||
text: string;
|
||||
pics?: Array<{ id: string; w: number; h: number }>;
|
||||
};
|
||||
settings: any;
|
||||
read_num: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface WebApiGroupNoticeRet {
|
||||
ec: number;
|
||||
em?: string;
|
||||
feeds?: Record<string, WebApiGroupNoticeFeed>;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送群公告 Web API
|
||||
*/
|
||||
export async function setGroupNoticeWebAPI(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string,
|
||||
content: string,
|
||||
pinned: number = 0,
|
||||
type: number = 1,
|
||||
isShowEditCard: number = 1,
|
||||
tipWindowType: number = 1,
|
||||
confirmRequired: number = 1,
|
||||
picId: string = '',
|
||||
imgWidth: number = 540,
|
||||
imgHeight: number = 300
|
||||
): Promise<SetNoticeRetSuccess | undefined> {
|
||||
try {
|
||||
const settings = JSON.stringify({
|
||||
is_show_edit_card: isShowEditCard,
|
||||
tip_window_type: tipWindowType,
|
||||
confirm_required: confirmRequired,
|
||||
});
|
||||
|
||||
const externalParam = {
|
||||
pic: picId,
|
||||
imgWidth: imgWidth.toString(),
|
||||
imgHeight: imgHeight.toString(),
|
||||
};
|
||||
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?${new URLSearchParams({
|
||||
bkn: getBknFromCookie(cookieObject),
|
||||
qid: groupCode,
|
||||
text: content,
|
||||
pinned: pinned.toString(),
|
||||
type: type.toString(),
|
||||
settings,
|
||||
...(picId === '' ? {} : externalParam),
|
||||
}).toString()}`;
|
||||
|
||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||
url,
|
||||
'POST', // 注意这里必须是 POST
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret;
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupNoticeWebAPI(
|
||||
cookieObject: Record<string, string>,
|
||||
groupCode: string
|
||||
): Promise<WebApiGroupNoticeRet | undefined> {
|
||||
const bkn = getBknFromCookie(cookieObject);
|
||||
|
||||
|
||||
const params = new URLSearchParams({
|
||||
bkn: bkn,
|
||||
qid: groupCode,
|
||||
ft: '23',
|
||||
ni: '1',
|
||||
i: '1',
|
||||
log_read: '1',
|
||||
platform: '1',
|
||||
s: '-1',
|
||||
}).toString();
|
||||
|
||||
const url = `https://web.qun.qq.com/cgi-bin/announce/get_t_list?${params}&n=20`;
|
||||
|
||||
try {
|
||||
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
|
||||
url,
|
||||
'GET',
|
||||
'',
|
||||
{ Cookie: cookieToString(cookieObject) }
|
||||
);
|
||||
return ret?.ec === 0 ? ret : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
127
packages/core/src/bridge/web/request-util.ts
Normal file
127
packages/core/src/bridge/web/request-util.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import https from 'node:https';
|
||||
import http from 'node:http';
|
||||
|
||||
export class RequestUtil {
|
||||
static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> {
|
||||
const client = url.startsWith('https') ? https : http;
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = client.get(url, (res) => {
|
||||
const cookies: { [key: string]: string; } = {};
|
||||
|
||||
res.on('data', () => { }); // 必须消耗流
|
||||
res.on('end', () => {
|
||||
this.handleRedirect(res, url, cookies)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
});
|
||||
|
||||
if (res.headers['set-cookie']) {
|
||||
this.extractCookies(res.headers['set-cookie'], cookies);
|
||||
}
|
||||
});
|
||||
|
||||
req.on('error', (error: Error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> {
|
||||
if (res.statusCode === 301 || res.statusCode === 302) {
|
||||
if (res.headers.location) {
|
||||
const redirectUrl = new URL(res.headers.location, url);
|
||||
const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
|
||||
return { ...cookies, ...redirectCookies };
|
||||
}
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) {
|
||||
setCookieHeaders.forEach((cookie) => {
|
||||
const parts = cookie.split(';')[0]?.split('=');
|
||||
if (parts) {
|
||||
const key = parts[0];
|
||||
const value = parts[1];
|
||||
if (key && value && key.length > 0 && value.length > 0) {
|
||||
cookies[key] = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: {
|
||||
[key: string]: string;
|
||||
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise<T> {
|
||||
const option = new URL(url);
|
||||
const protocol = url.startsWith('https://') ? https : http;
|
||||
const options = {
|
||||
hostname: option.hostname,
|
||||
port: option.port,
|
||||
path: option.pathname + option.search,
|
||||
method,
|
||||
headers,
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = protocol.request(options, (res: http.IncomingMessage) => {
|
||||
if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
|
||||
if (maxRedirects <= 0) {
|
||||
reject(new Error('Too many redirects'));
|
||||
return;
|
||||
}
|
||||
const redirectUrl = new URL(res.headers.location, url).href;
|
||||
this.HttpGetJson<T>(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
return;
|
||||
}
|
||||
|
||||
let responseBody = '';
|
||||
res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); });
|
||||
|
||||
res.on('end', () => {
|
||||
try {
|
||||
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
|
||||
if (isJsonRet) {
|
||||
resolve(JSON.parse(responseBody) as T);
|
||||
} else {
|
||||
resolve(responseBody as T);
|
||||
}
|
||||
} else {
|
||||
reject(new Error(`Unexpected status code: ${res.statusCode}`));
|
||||
}
|
||||
} catch (parseError: any) {
|
||||
reject(new Error(parseError.message));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (error: Error) => reject(error));
|
||||
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
|
||||
req.write(isArgJson ? JSON.stringify(data) : data);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) {
|
||||
return this.HttpGetJson<string>(url, method, data, headers, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
export function cookieToString(cookieObject: Record<string, string>): string {
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
|
||||
export function getBknFromCookie(cookieObject: Record<string, string>): string {
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
return (hash & 2147483647).toString();
|
||||
}
|
||||
@@ -9,7 +9,7 @@ const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||
webuiPort: 8080,
|
||||
webuiPort: 5099,
|
||||
};
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
@@ -22,7 +22,7 @@ export function loadRuntimeConfig(): RuntimeConfig {
|
||||
}
|
||||
|
||||
const normalized: RuntimeConfig = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 8080, 8080),
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
};
|
||||
|
||||
if (
|
||||
@@ -43,7 +43,7 @@ function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||
if (!isObject(parsed)) return null;
|
||||
|
||||
return {
|
||||
webuiPort: normalizePort(parsed.webuiPort ?? 8080, 8080),
|
||||
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -6,10 +6,17 @@ import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjec
|
||||
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;
|
||||
const DEFAULT_WATCHER_INTERVAL_MS = 1500;
|
||||
const MIN_WATCHER_INTERVAL_MS = 250;
|
||||
|
||||
export type HookProcessStatus = 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected';
|
||||
export type HookProcessStatus =
|
||||
| 'available'
|
||||
| 'loading'
|
||||
| 'connecting'
|
||||
| 'loaded'
|
||||
| 'online'
|
||||
| 'error'
|
||||
| 'disconnected';
|
||||
|
||||
export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||
injected: boolean;
|
||||
@@ -25,103 +32,159 @@ interface HookProcessState extends HookProcessInfo {
|
||||
client: QqHookClient | null;
|
||||
sender: HookPacketClient | null;
|
||||
injectResult: HookInjectResult | null;
|
||||
connectTask: Promise<void> | null;
|
||||
bound: boolean;
|
||||
}
|
||||
|
||||
export interface HookManagerOptions {
|
||||
/** Background pipe-watcher polling interval. Lower = faster reconnect but
|
||||
* more frequent named-pipe directory listings. Defaults to 1500 ms. */
|
||||
watcherIntervalMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages SnowLuma hook injection and bridge connectivity for QQ.exe processes.
|
||||
*
|
||||
* Lifecycle: load -> inject DLL only (returns fast) -> background watcher
|
||||
* detects the named pipe coming up and connects -> on QQ login the bridge is
|
||||
* notified. The watcher also handles reconnect after a pipe drop and detects
|
||||
* hooks that survived a previous SnowLuma restart.
|
||||
*
|
||||
* Concurrency: every per-PID mutation (load / unload / refresh / connect /
|
||||
* close-handler / watcher reconcile) goes through a per-PID promise chain so
|
||||
* users can spam buttons without races.
|
||||
*/
|
||||
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>>();
|
||||
private readonly opsByPid = new Map<number, Promise<unknown>>();
|
||||
private readonly watcherIntervalMs: number;
|
||||
private watcherTimer: NodeJS.Timeout | null = null;
|
||||
private watcherTicking = false;
|
||||
private disposed = false;
|
||||
|
||||
constructor(
|
||||
private readonly ntqq: NtqqHandler,
|
||||
private readonly bridgeManager: BridgeManager,
|
||||
) {}
|
||||
options: HookManagerOptions = {},
|
||||
) {
|
||||
this.watcherIntervalMs = Math.max(
|
||||
MIN_WATCHER_INTERVAL_MS,
|
||||
options.watcherIntervalMs ?? DEFAULT_WATCHER_INTERVAL_MS,
|
||||
);
|
||||
// Boot the watcher on the next tick so callers can attach listeners first.
|
||||
this.scheduleWatcher(0);
|
||||
}
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
const processes = await listHookProcesses();
|
||||
const processes = listHookProcesses();
|
||||
const seen = new Set<number>();
|
||||
for (const proc of processes) {
|
||||
seen.add(proc.pid);
|
||||
const state = this.ensureState(proc.pid);
|
||||
state.name = proc.name;
|
||||
state.path = proc.path;
|
||||
state.name = proc.name || state.name;
|
||||
state.path = proc.path || state.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) {
|
||||
if (!seen.has(state.pid) && (state.injected || state.client)) {
|
||||
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);
|
||||
}
|
||||
loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
return this.serialize(pid, () => this.loadProcessInternal(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;
|
||||
unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
return this.serialize(pid, () => this.unloadProcessInternal(pid));
|
||||
}
|
||||
|
||||
const task = this.unloadProcessInternal(pid);
|
||||
this.unloadTasks.set(pid, task);
|
||||
try {
|
||||
return await task;
|
||||
} finally {
|
||||
this.unloadTasks.delete(pid);
|
||||
}
|
||||
/**
|
||||
* Re-probe the named pipe for `pid`, reconnect if it became available,
|
||||
* or tear down a stale connection if it disappeared. Safe to call at any
|
||||
* time; serialised against load/unload/watcher actions on the same PID.
|
||||
*/
|
||||
refreshProcess(pid: number): Promise<HookProcessInfo> {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
return this.serialize(pid, () => this.refreshProcessInternal(pid));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
if (this.watcherTimer) {
|
||||
clearTimeout(this.watcherTimer);
|
||||
this.watcherTimer = null;
|
||||
}
|
||||
for (const state of this.states.values()) {
|
||||
state.client?.close();
|
||||
state.client = null;
|
||||
state.connected = false;
|
||||
state.loggedIn = false;
|
||||
this.tearDownClient(state);
|
||||
state.status = state.injected ? 'disconnected' : 'available';
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── per-PID serialization ─────────────────────────
|
||||
|
||||
/**
|
||||
* Serialise an operation against a per-PID promise chain. Guarantees that
|
||||
* load / unload / refresh / watcher-driven connects for the same PID never
|
||||
* interleave even if the user mashes buttons.
|
||||
*/
|
||||
private async serialize<T>(pid: number, op: () => Promise<T>): Promise<T> {
|
||||
const previous = this.opsByPid.get(pid) ?? Promise.resolve();
|
||||
let release!: () => void;
|
||||
const completion = new Promise<void>(resolve => { release = resolve; });
|
||||
const chained = previous.then(() => completion);
|
||||
this.opsByPid.set(pid, chained);
|
||||
try {
|
||||
await previous.catch(() => undefined);
|
||||
return await op();
|
||||
} finally {
|
||||
release();
|
||||
// Drop the chain entry once nothing else is waiting on it.
|
||||
if (this.opsByPid.get(pid) === chained) this.opsByPid.delete(pid);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── load / unload ──────────────────────────────
|
||||
|
||||
private async loadProcessInternal(pid: number): Promise<HookProcessInfo> {
|
||||
const state = this.ensureState(pid);
|
||||
state.status = 'loading';
|
||||
state.error = '';
|
||||
state.status = 'loading';
|
||||
|
||||
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);
|
||||
// Fast path: a previous SnowLuma run may have left the hook DLL
|
||||
// resident in QQ.exe. If the control pipe is already listed we skip
|
||||
// re-injection and let the watcher reconnect instead.
|
||||
const livePipes = await QqHookClient.listLivePipes();
|
||||
if (livePipes.has(pid)) {
|
||||
state.injected = true;
|
||||
state.method = state.method || 'reconnect';
|
||||
log.info('PID=%d already has SnowLuma pipe; will reconnect via watcher', pid);
|
||||
} else {
|
||||
state.injectResult = injectHookProcess(pid);
|
||||
state.injected = true;
|
||||
state.method = state.injectResult.method;
|
||||
}
|
||||
}
|
||||
state.status = state.connected ? (state.loggedIn ? 'online' : 'loaded') : 'loaded';
|
||||
this.startClient(state);
|
||||
state.status = state.connected
|
||||
? (state.loggedIn ? 'online' : 'loaded')
|
||||
: 'connecting';
|
||||
} 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);
|
||||
}
|
||||
|
||||
// Wake the watcher so it can pick up the freshly-injected pipe asap
|
||||
// instead of waiting up to one full interval.
|
||||
this.scheduleWatcher(0);
|
||||
return this.toPublicInfo(state);
|
||||
}
|
||||
|
||||
@@ -130,14 +193,9 @@ export class HookManager {
|
||||
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 wasLoggedIn = state.loggedIn;
|
||||
this.tearDownClient(state);
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
|
||||
const handle = state.injectResult?.handle;
|
||||
if (state.injected && handle) {
|
||||
@@ -145,11 +203,24 @@ export class HookManager {
|
||||
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
|
||||
}
|
||||
|
||||
// Clear injection state first
|
||||
state.injected = false;
|
||||
state.injectResult = null;
|
||||
state.method = '';
|
||||
state.uin = '0';
|
||||
state.status = 'available';
|
||||
|
||||
// Verify unload succeeded by checking if pipe still exists
|
||||
const livePipes = await QqHookClient.listLivePipes();
|
||||
if (livePipes.has(pid)) {
|
||||
// Pipe still exists - unload failed, but let watcher handle reconnection
|
||||
state.error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
|
||||
state.status = 'connecting'; // Let watcher pick it up and reconnect
|
||||
log.warn('unload verification failed: PID=%d pipe still exists after unloadModuleManual, watcher will reconnect', pid);
|
||||
} else {
|
||||
// Successfully unloaded
|
||||
state.status = 'available';
|
||||
state.error = '';
|
||||
}
|
||||
} catch (error) {
|
||||
state.status = 'error';
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
@@ -159,6 +230,44 @@ export class HookManager {
|
||||
return this.toPublicInfo(state);
|
||||
}
|
||||
|
||||
private async refreshProcessInternal(pid: number): Promise<HookProcessInfo> {
|
||||
const state = this.ensureState(pid);
|
||||
state.error = '';
|
||||
|
||||
try {
|
||||
const livePipes = await QqHookClient.listLivePipes();
|
||||
const pipeUp = livePipes.has(pid);
|
||||
|
||||
if (pipeUp) {
|
||||
// A live pipe means a SnowLuma DLL is resident — even if we did not
|
||||
// inject it ourselves (e.g. left over from a prior run).
|
||||
if (!state.injected) {
|
||||
state.injected = true;
|
||||
state.method = state.method || 'reconnect';
|
||||
}
|
||||
if (state.client?.isClosed) this.tearDownClient(state);
|
||||
if (!state.connected) {
|
||||
await this.attemptConnect(state);
|
||||
} else {
|
||||
state.status = state.loggedIn ? 'online' : 'loaded';
|
||||
}
|
||||
} else {
|
||||
// Pipe is gone; if we still hold a client, drop it and surface the
|
||||
// appropriate disconnected/available state to the UI.
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
this.tearDownClient(state);
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
state.status = state.injected ? 'disconnected' : 'available';
|
||||
}
|
||||
} catch (error) {
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
state.status = state.injected ? 'disconnected' : 'error';
|
||||
log.warn('refresh 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) {
|
||||
@@ -176,7 +285,6 @@ export class HookManager {
|
||||
client: null,
|
||||
sender: null,
|
||||
injectResult: null,
|
||||
connectTask: null,
|
||||
bound: false,
|
||||
};
|
||||
this.states.set(pid, state);
|
||||
@@ -184,20 +292,139 @@ export class HookManager {
|
||||
return state;
|
||||
}
|
||||
|
||||
private startClient(state: HookProcessState): void {
|
||||
// ───────────────────────────── pipe watcher ──────────────────────────────
|
||||
|
||||
private scheduleWatcher(delayMs: number): void {
|
||||
if (this.disposed) return;
|
||||
if (this.watcherTimer) {
|
||||
clearTimeout(this.watcherTimer);
|
||||
this.watcherTimer = null;
|
||||
}
|
||||
this.watcherTimer = setTimeout(() => {
|
||||
this.watcherTimer = null;
|
||||
void this.tickWatcher();
|
||||
}, Math.max(0, delayMs));
|
||||
}
|
||||
|
||||
private async tickWatcher(): Promise<void> {
|
||||
if (this.disposed) return;
|
||||
if (this.watcherTicking) {
|
||||
this.scheduleWatcher(this.watcherIntervalMs);
|
||||
return;
|
||||
}
|
||||
this.watcherTicking = true;
|
||||
try {
|
||||
const livePipes = await QqHookClient.listLivePipes();
|
||||
const processes = listHookProcesses();
|
||||
|
||||
// Refresh metadata + ensure a state entry exists for each known PID.
|
||||
for (const proc of processes) {
|
||||
const state = this.ensureState(proc.pid);
|
||||
state.name = proc.name || state.name;
|
||||
state.path = proc.path || state.path;
|
||||
}
|
||||
// Auto-detect hooks that survived a SnowLuma restart or failed unload.
|
||||
for (const pid of livePipes) {
|
||||
const state = this.ensureState(pid);
|
||||
if (!state.injected) {
|
||||
state.injected = true;
|
||||
state.method = state.method || 'reconnect';
|
||||
if (state.status === 'available') state.status = 'connecting';
|
||||
log.info('Detected pre-existing SnowLuma pipe in PID=%d', pid);
|
||||
}
|
||||
}
|
||||
|
||||
const runningSet = new Set(processes.map(p => p.pid));
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
for (const state of [...this.states.values()]) {
|
||||
const alivePipe = livePipes.has(state.pid);
|
||||
const aliveProc = runningSet.has(state.pid);
|
||||
|
||||
// Reap stale state entries that have nothing left to do.
|
||||
if (!aliveProc && !alivePipe && !state.injected && !state.client) {
|
||||
this.states.delete(state.pid);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Pipe vanished but we still hold a client → schedule a teardown.
|
||||
if (state.connected && !alivePipe) {
|
||||
tasks.push(this.serialize(state.pid, async () => this.reconcileLostPipe(state.pid))
|
||||
.catch(err => log.warn('watcher teardown failed: PID=%d err=%s', state.pid, this.errMsg(err))));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Injected & pipe up but not connected → schedule a connect.
|
||||
if (state.injected && !state.connected && alivePipe) {
|
||||
tasks.push(this.serialize(state.pid, async () => this.reconcileConnect(state.pid))
|
||||
.catch(err => log.warn('watcher connect failed: PID=%d err=%s', state.pid, this.errMsg(err))));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Injected but pipe still pending → keep status visible to the UI.
|
||||
if (state.injected && !state.connected && !alivePipe) {
|
||||
if (state.status !== 'error' && state.status !== 'disconnected' && state.status !== 'loading') {
|
||||
state.status = 'connecting';
|
||||
}
|
||||
}
|
||||
}
|
||||
await Promise.all(tasks);
|
||||
} finally {
|
||||
this.watcherTicking = false;
|
||||
this.scheduleWatcher(this.watcherIntervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-check pipe and connect under the per-PID lock. */
|
||||
private async reconcileConnect(pid: number): Promise<void> {
|
||||
const state = this.states.get(pid);
|
||||
if (!state || !state.injected || state.connected) return;
|
||||
if (state.client?.isClosed) this.tearDownClient(state);
|
||||
const live = await QqHookClient.listLivePipes();
|
||||
if (!live.has(pid)) return;
|
||||
await this.attemptConnect(state);
|
||||
}
|
||||
|
||||
/** Tear down a client whose pipe disappeared. */
|
||||
private async reconcileLostPipe(pid: number): Promise<void> {
|
||||
const state = this.states.get(pid);
|
||||
if (!state || !state.connected) return;
|
||||
const live = await QqHookClient.listLivePipes();
|
||||
if (live.has(pid)) return;
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
this.tearDownClient(state);
|
||||
state.status = state.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available';
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
}
|
||||
|
||||
// ───────────────────────────── client plumbing ───────────────────────────
|
||||
|
||||
private async attemptConnect(state: HookProcessState): Promise<void> {
|
||||
if (state.connected) return;
|
||||
if (state.client?.isClosed) this.tearDownClient(state);
|
||||
if (!state.client) {
|
||||
state.client = new QqHookClient(state.pid);
|
||||
state.sender = new HookPacketClient(state.client);
|
||||
state.bound = false;
|
||||
}
|
||||
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;
|
||||
|
||||
const client = state.client;
|
||||
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);
|
||||
} catch (error) {
|
||||
state.error = this.errMsg(error);
|
||||
// Drop the client so the next attempt builds a fresh socket pair.
|
||||
this.tearDownClient(state);
|
||||
state.status = state.injected ? 'connecting' : 'available';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,54 +432,54 @@ export class HookManager {
|
||||
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);
|
||||
const msg = this.errMsg(error);
|
||||
state.error = msg;
|
||||
log.warn('pipe error: PID=%d err=%s', state.pid, msg);
|
||||
});
|
||||
client.on('close', () => {
|
||||
state.connected = false;
|
||||
if (state.loggedIn) {
|
||||
state.loggedIn = false;
|
||||
state.status = 'disconnected';
|
||||
this.bridgeManager.onPidDisconnected(state.pid);
|
||||
}
|
||||
if (this.disposed) return;
|
||||
// Only the client that is currently registered should drive a reconcile;
|
||||
// listeners may fire for an already-replaced client.
|
||||
if (state.client !== client) return;
|
||||
void this.serialize(state.pid, async () => {
|
||||
if (state.client !== client) return;
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
this.tearDownClient(state);
|
||||
if (!state.injected) {
|
||||
state.status = 'available';
|
||||
} else if (wasLoggedIn) {
|
||||
state.status = 'disconnected';
|
||||
this.bridgeManager.onPidDisconnected(state.pid);
|
||||
} else {
|
||||
state.status = 'connecting';
|
||||
}
|
||||
}).catch(err => log.warn('close reconcile failed: PID=%d err=%s', state.pid, this.errMsg(err)));
|
||||
});
|
||||
}
|
||||
|
||||
private async connectClient(state: HookProcessState): Promise<void> {
|
||||
/** Detach + close the current client and reset its associated fields. */
|
||||
private tearDownClient(state: HookProcessState): 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);
|
||||
}
|
||||
if (client) {
|
||||
client.removeAllListeners();
|
||||
try { client.close(); } catch { /* ignore */ }
|
||||
}
|
||||
state.client = null;
|
||||
state.sender = null;
|
||||
state.bound = false;
|
||||
state.connected = false;
|
||||
state.loggedIn = false;
|
||||
}
|
||||
|
||||
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
const previousUin = state.uin;
|
||||
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;
|
||||
if (wasLoggedIn && previousUin === state.uin) return;
|
||||
|
||||
this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender);
|
||||
log.success('login detected: PID=%d UIN=%s', state.pid, state.uin);
|
||||
@@ -279,13 +506,13 @@ export class HookManager {
|
||||
method: state.method,
|
||||
};
|
||||
}
|
||||
|
||||
private errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -37,11 +37,21 @@ function loadNativeAddon(addonPath: string): NativeHookAddon {
|
||||
return mod.exports as unknown as NativeHookAddon;
|
||||
}
|
||||
|
||||
function platformBinaryName(ext: 'node' | 'dll'): string {
|
||||
type HookBinaryExt = 'node' | 'dll' | 'so';
|
||||
|
||||
function platformBinaryName(ext: HookBinaryExt): string {
|
||||
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
}
|
||||
|
||||
function platformInjectableExt(): 'dll' | 'so' {
|
||||
return process.platform === 'win32' ? 'dll' : 'so';
|
||||
}
|
||||
|
||||
function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
@@ -56,7 +66,7 @@ function nativeSearchDirs(): string[] {
|
||||
];
|
||||
}
|
||||
|
||||
export function resolveHookNativePath(ext: 'node' | 'dll'): string | null {
|
||||
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
|
||||
const fileName = platformBinaryName(ext);
|
||||
for (const dir of nativeSearchDirs()) {
|
||||
const fullPath = path.join(dir, fileName);
|
||||
@@ -92,7 +102,7 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
return [...new Set(addon.getAllMainProcess())]
|
||||
.filter(pid => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: 'QQ.exe', path: '' }));
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
|
||||
export function injectHookProcess(pid: number): HookInjectResult {
|
||||
@@ -100,9 +110,10 @@ export function injectHookProcess(pid: number): HookInjectResult {
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
const dllPath = resolveHookNativePath('dll');
|
||||
const injectableExt = platformInjectableExt();
|
||||
const dllPath = resolveHookNativePath(injectableExt);
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook DLL found for ${process.platform}-${process.arch}`);
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import net from 'net';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
export const PIPE_MAGIC = 0x31504851;
|
||||
@@ -81,8 +84,22 @@ interface PendingAck {
|
||||
wantReply: boolean;
|
||||
}
|
||||
|
||||
function linuxRuntimeDir(): string {
|
||||
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
|
||||
if (explicit && explicit.length > 0) return explicit;
|
||||
const xdg = process.env.XDG_RUNTIME_DIR;
|
||||
if (xdg && xdg.length > 0) return xdg;
|
||||
// Mirrors hook_stub.cpp runtime_dir() fallback.
|
||||
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
|
||||
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
|
||||
return `/tmp/snowluma-${uid}`;
|
||||
}
|
||||
|
||||
function mojoPipeName(pid: number, suffix: string): string {
|
||||
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
|
||||
if (process.platform === 'win32') {
|
||||
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
|
||||
}
|
||||
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
|
||||
}
|
||||
|
||||
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
|
||||
@@ -236,6 +253,10 @@ export class QqHookClient extends EventEmitter {
|
||||
return this.loginState.loggedIn;
|
||||
}
|
||||
|
||||
get isClosed(): boolean {
|
||||
return this.closed;
|
||||
}
|
||||
|
||||
get currentUin(): string {
|
||||
return this.loginState.uin;
|
||||
}
|
||||
@@ -266,6 +287,43 @@ export class QqHookClient extends EventEmitter {
|
||||
return mojoPipeName(pid, 'recv');
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight liveness check for the control pipe. Used to detect whether an
|
||||
* existing SnowLuma hook is still hosted inside the QQ.exe process without
|
||||
* opening the pipe, so probing cannot disturb the first real client connect.
|
||||
*/
|
||||
static async probePipe(pid: number): Promise<boolean> {
|
||||
const live = await QqHookClient.listLivePipes();
|
||||
return live.has(pid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enumerate every PID currently hosting a SnowLuma `mojo.<pid>.control` pipe
|
||||
* in a single filesystem listing. The HookManager's pipe-watcher uses this
|
||||
* to drive connect/reconnect decisions without per-PID stat calls.
|
||||
*/
|
||||
static async listLivePipes(): Promise<Set<number>> {
|
||||
const result = new Set<number>();
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const names = await fs.readdir('\\\\.\\pipe\\');
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control$/i.exec(name);
|
||||
if (m) result.add(Number(m[1]));
|
||||
}
|
||||
} else {
|
||||
const names = await fs.readdir(linuxRuntimeDir());
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
|
||||
if (m) result.add(Number(m[1]));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* directory missing or inaccessible — treat as no live pipes */
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async connect(): Promise<QqHookHello> {
|
||||
if (this.closed) {
|
||||
throw new Error('qq_hook client is closed');
|
||||
@@ -576,8 +634,8 @@ export class QqHookClient extends EventEmitter {
|
||||
const previous = this.loginState;
|
||||
const next = { loggedIn, uin, uinNumber };
|
||||
this.loginState = next;
|
||||
this.emit('loginState', next);
|
||||
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
|
||||
this.emit('loginState', next);
|
||||
if (next.loggedIn) {
|
||||
const waiters = this.loginWaiters;
|
||||
this.loginWaiters = [];
|
||||
|
||||
@@ -20,11 +20,13 @@ async function main() {
|
||||
bridgeManager.bind(ntqq);
|
||||
oneBotManager.bind(bridgeManager);
|
||||
|
||||
if (typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) {
|
||||
if (
|
||||
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
|
||||
process.env.SNOWLUMA_DEV_WEBUI === '1'
|
||||
) {
|
||||
try {
|
||||
log.info('WebUI is enabled, starting...');
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
initWebUI(runtimeConfig.webuiPort || 8080, oneBotManager, hookManager);
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager);
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
}
|
||||
|
||||
@@ -71,9 +71,20 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
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([]);
|
||||
|
||||
if (!ctx.getGroupEssenceAll) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
const essenceDataAll = await ctx.getGroupEssenceAll(groupId);
|
||||
|
||||
const allMsgs = essenceDataAll.flatMap(res => res.data?.msg_list || []);
|
||||
|
||||
return okResponse(allMsgs);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `获取精华消息失败: ${e}`);
|
||||
}
|
||||
});
|
||||
|
||||
// --- Reactions ---
|
||||
@@ -124,10 +135,80 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return okResponse({ messages });
|
||||
});
|
||||
|
||||
h.registerAction('mark_msg_as_read', async () => {
|
||||
h.registerAction('mark_group_msg_as_read', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const groupId = asNumber(params.group_id);
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
|
||||
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.markGroupMsgAsRead) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
await ctx.markGroupMsgAsRead(groupId, meta.sequence);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_private_msg_as_read', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
|
||||
if (!meta || meta.isGroup) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message');
|
||||
}
|
||||
|
||||
if (userId && userId !== meta.targetId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session');
|
||||
}
|
||||
|
||||
if (!ctx.markPrivateMsgAsRead) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
await ctx.markPrivateMsgAsRead(userId, meta.sequence);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_msg_as_read', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const targetId = asNumber(params.target_id);
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
|
||||
|
||||
if (targetId && targetId !== meta.targetId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session');
|
||||
}
|
||||
|
||||
if (!(ctx.markPrivateMsgAsRead && ctx.markGroupMsgAsRead)) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
if (meta.isGroup) {
|
||||
await ctx.markGroupMsgAsRead(targetId, meta.sequence);
|
||||
} else {
|
||||
await ctx.markPrivateMsgAsRead(targetId, meta.sequence);
|
||||
}
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
|
||||
// --- RKey ---
|
||||
|
||||
h.registerAction('get_rkey', async () => {
|
||||
@@ -149,12 +230,51 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
|
||||
// --- Group notice stubs ---
|
||||
|
||||
h.registerAction('_send_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
h.registerAction('_send_group_notice', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const content = asString(params.content);
|
||||
const image = asString(params.image);
|
||||
|
||||
if (!groupId || !content) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and content are required');
|
||||
}
|
||||
|
||||
if (image) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented: image upload for group notice is not supported yet');
|
||||
}
|
||||
|
||||
if (!ctx.sendGroupNotice) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
const options = {
|
||||
pinned: params.pinned !== undefined ? Number(params.pinned) : 0,
|
||||
type: params.type !== undefined ? Number(params.type) : 1,
|
||||
confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1,
|
||||
};
|
||||
|
||||
await ctx.sendGroupNotice(groupId, content, options);
|
||||
return okResponse();
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('_get_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
h.registerAction('_get_group_notice', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
|
||||
if (!ctx.getGroupNotice) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
const notices = await ctx.getGroupNotice(groupId);
|
||||
return okResponse(notices);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('_del_group_notice', async () => {
|
||||
@@ -272,39 +392,61 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
// --- Media ---
|
||||
|
||||
h.registerAction('get_image', async (params) => {
|
||||
const file = asString(params.file);
|
||||
const file = asString(params.file) || asString(params.file_id);
|
||||
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);
|
||||
}
|
||||
if (!ctx.getImageInfo) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const info = await ctx.getImageInfo(file);
|
||||
if (info) return okResponse(info);
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache');
|
||||
});
|
||||
|
||||
h.registerAction('get_record', async (params) => {
|
||||
const file = asString(params.file);
|
||||
const file = asString(params.file) || asString(params.file_id);
|
||||
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);
|
||||
}
|
||||
if (!ctx.getRecordInfo) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const info = await ctx.getRecordInfo(file);
|
||||
if (info) return okResponse(info);
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
|
||||
});
|
||||
|
||||
// --- Credentials ---
|
||||
|
||||
h.registerAction('get_cookies', async () => {
|
||||
return okResponse({ cookies: '' });
|
||||
h.registerAction('get_cookies', async (params) => {
|
||||
const domain = asString(params.domain) || 'qun.qq.com';
|
||||
|
||||
if (!ctx.getCookiesStr) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
try {
|
||||
const cookies = await ctx.getCookiesStr(domain);
|
||||
return okResponse({ cookies });
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_csrf_token', async () => {
|
||||
return okResponse({ token: 0 });
|
||||
if (!ctx.getCsrfToken) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
try {
|
||||
const token = await ctx.getCsrfToken();
|
||||
return okResponse({ token });
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_credentials', async () => {
|
||||
return okResponse({ cookies: '', csrf_token: 0 });
|
||||
});
|
||||
h.registerAction('get_credentials', async (params) => {
|
||||
const domain = asString(params.domain) || 'qun.qq.com';
|
||||
|
||||
if (!ctx.getCredentials) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
try {
|
||||
const creds = await ctx.getCredentials(domain);
|
||||
return okResponse(creds);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
// --- Utility ---
|
||||
|
||||
h.registerAction('set_restart', async () => {
|
||||
@@ -319,7 +461,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
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');
|
||||
const { executeQuickOperation } = await import('../network/quick-operation');
|
||||
await executeQuickOperation(context, operation, h);
|
||||
return okResponse();
|
||||
});
|
||||
@@ -347,13 +489,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
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();
|
||||
@@ -414,12 +549,44 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return okResponse({ file: pathMod.resolve(filePath) });
|
||||
});
|
||||
|
||||
h.registerAction('set_qq_profile', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
h.registerAction('set_qq_profile', async (params) => {
|
||||
|
||||
const nickname = params.nickname !== undefined ? asString(params.nickname) : undefined;
|
||||
const personalNote = params.personal_note !== undefined ? asString(params.personal_note) : undefined;
|
||||
|
||||
if (!ctx.setProfile) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
await ctx.setProfile(nickname, personalNote);
|
||||
return okResponse();
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('set_online_status', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
h.registerAction('set_online_status', async (params) => {
|
||||
// 按 OneBot/NapCat 习惯提取参数,状态码默认为 11
|
||||
const status = asNumber(params.status);
|
||||
const extStatus = asNumber(params.ext_status) || 0;
|
||||
const batteryStatus = asNumber(params.battery_status) || 100;
|
||||
|
||||
// 参数校验
|
||||
if (status === undefined || status === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'status is required');
|
||||
}
|
||||
|
||||
if (!ctx.setOnlineStatus) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
}
|
||||
|
||||
try {
|
||||
await ctx.setOnlineStatus(status, extStatus, batteryStatus);
|
||||
return okResponse();
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, String(e));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_ignored_notifies', async () => {
|
||||
@@ -504,7 +671,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
});
|
||||
|
||||
h.registerAction('get_clientkey', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
if (!ctx.forceFetchClientKey) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
}
|
||||
const clientKeyInfo = await ctx.forceFetchClientKey();
|
||||
if (!clientKeyInfo.clientKey) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error');
|
||||
}
|
||||
return okResponse(clientKeyInfo);
|
||||
});
|
||||
|
||||
h.registerAction('get_mini_app_ark', async () => {
|
||||
@@ -560,23 +734,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean } from '../api-handler';
|
||||
import { asNumber, asBoolean, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { WebHonorType } from '@/bridge/web/group-honor';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_group_list', async (params) => {
|
||||
@@ -54,11 +55,27 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
|
||||
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: [],
|
||||
});
|
||||
const typeStr = asString(params.type) || 'all';
|
||||
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
|
||||
if (!ctx.getGroupHonorInfo) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
}
|
||||
|
||||
const typeValues = Object.values(WebHonorType) as string[];
|
||||
if (!typeValues.includes(typeStr)) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const honorInfo = await ctx.getGroupHonorInfo(groupId, typeStr as WebHonorType);
|
||||
return okResponse(honorInfo);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_system_msg', async () => {
|
||||
|
||||
@@ -10,12 +10,25 @@ import { register as registerGroupFile } from './actions/group-file';
|
||||
import { register as registerRequest } from './actions/request';
|
||||
import { register as registerExtended } from './actions/extended';
|
||||
|
||||
import { WebHonorType } from '@/bridge/web/group-honor';
|
||||
// import {ClientKeyInfo} from "@/bridge/bridge";
|
||||
|
||||
export interface MessageSendResult {
|
||||
messageId: number;
|
||||
meta?: MessageMeta;
|
||||
echoEvent?: JsonObject;
|
||||
}
|
||||
|
||||
export interface GroupEssenceMsgRet {
|
||||
retcode: number;
|
||||
data: {
|
||||
is_end: boolean;
|
||||
msg_list: any[];
|
||||
[key: string]: any;
|
||||
};
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface ApiActionContext {
|
||||
getLoginInfo: () => { userId: number; nickname: string };
|
||||
isOnline: () => boolean;
|
||||
@@ -62,6 +75,9 @@ export interface ApiActionContext {
|
||||
sendGroupPoke?: (groupId: number, userId: number) => Promise<void>;
|
||||
setEssenceMsg?: (messageId: number) => Promise<void>;
|
||||
deleteEssenceMsg?: (messageId: number) => Promise<void>;
|
||||
forceFetchClientKey? : () => Promise<{clientKey: string, keyIndex: string, expireTime: string}>;
|
||||
setOnlineStatus?: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
|
||||
setProfile?: (nickname?: string, personalNote?: string) => Promise<void>;
|
||||
// New context methods
|
||||
setGroupReaction?: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
|
||||
handleDeleteFriend?: (userId: number, block?: boolean) => Promise<void>;
|
||||
@@ -78,6 +94,20 @@ export interface ApiActionContext {
|
||||
setFriendRemark?: (userId: number, remark: string) => Promise<void>;
|
||||
getGroupFileCount?: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
|
||||
setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
|
||||
markGroupMsgAsRead?: (groupId: number, sequence: number) => Promise<void>;
|
||||
markPrivateMsgAsRead?: (userId: number, sequence: number) => Promise<void>;
|
||||
// Web
|
||||
getGroupHonorInfo?: (groupId: number, type: WebHonorType | string) => Promise<any>;
|
||||
getGroupEssence?: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
|
||||
getGroupEssenceAll?: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
|
||||
sendGroupNotice?: (groupId: number, content: string, options?: any) => Promise<any>;
|
||||
getGroupNotice?: (groupId: number) => Promise<any[]>;
|
||||
getCookiesStr?: (domain: string) => Promise<string>;
|
||||
getCsrfToken?: () => Promise<number>;
|
||||
getCredentials?: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
|
||||
// Media lookup (populated from previously dispatched message segments)
|
||||
getImageInfo?: (file: string) => Promise<JsonObject | null>;
|
||||
getRecordInfo?: (file: string) => Promise<JsonObject | null>;
|
||||
}
|
||||
|
||||
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
|
||||
|
||||
@@ -2,112 +2,75 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import type {
|
||||
HttpPostEndpoint,
|
||||
HttpServerEndpoint,
|
||||
HttpClientNetwork,
|
||||
HttpServerNetwork,
|
||||
JsonObject,
|
||||
MessageFormat,
|
||||
OneBotConfig,
|
||||
WsClientEndpoint,
|
||||
OneBotNetworks,
|
||||
WsClientNetwork,
|
||||
WsRole,
|
||||
WsServerEndpoint,
|
||||
WsServerNetwork,
|
||||
} from './types';
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
|
||||
|
||||
export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||
return {
|
||||
httpServers: [{ host: '0.0.0.0', port: 3000, path: '/' }],
|
||||
httpPostEndpoints: [],
|
||||
wsServers: [{ host: '0.0.0.0', port: 3001 }],
|
||||
wsClients: [],
|
||||
networks: {
|
||||
httpServers: [{
|
||||
name: 'http-default',
|
||||
host: '0.0.0.0',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
accessToken: generateAccessToken(),
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
}],
|
||||
httpClients: [],
|
||||
wsServers: [{
|
||||
name: 'ws-default',
|
||||
host: '0.0.0.0',
|
||||
port: 3001,
|
||||
path: '/',
|
||||
role: 'Universal',
|
||||
accessToken: generateAccessToken(),
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
}],
|
||||
wsClients: [],
|
||||
},
|
||||
musicSignUrl: '',
|
||||
};
|
||||
}
|
||||
|
||||
function generateAccessToken(): string {
|
||||
return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url');
|
||||
}
|
||||
|
||||
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 globalRaw = tryLoadJson(DEFAULT_CONFIG_PATH);
|
||||
const perUinRaw = tryLoadJson(perUinPath);
|
||||
|
||||
const config = fromJson(merged);
|
||||
let shouldSave = !perUinConfig;
|
||||
// Detect legacy on-disk format (top-level per-type arrays). We auto-migrate
|
||||
// these entries into `networks.*` and rewrite the file on the next save.
|
||||
const legacy = !!perUinRaw && hasLegacyTopLevel(perUinRaw);
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
const sources: JsonObject[] = [];
|
||||
if (globalRaw) sources.push(globalRaw);
|
||||
if (perUinRaw) sources.push(perUinRaw);
|
||||
|
||||
// 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 ?? '';
|
||||
const config = fromJson(sources);
|
||||
|
||||
if (shouldSave) {
|
||||
saveJson(perUinPath, merged);
|
||||
}
|
||||
// Persist normalized form whenever the file is missing OR was in legacy
|
||||
// format, so downstream code can rely on the unified shape on disk.
|
||||
const shouldSave = !perUinRaw || legacy;
|
||||
if (shouldSave) saveOneBotConfig(uin, config);
|
||||
|
||||
return config;
|
||||
}
|
||||
@@ -115,8 +78,7 @@ export function loadOneBotConfig(uin: string): OneBotConfig {
|
||||
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);
|
||||
saveJson(perUinPath, toJsonObject(config));
|
||||
}
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
@@ -124,141 +86,251 @@ function ensureConfigDir(): void {
|
||||
}
|
||||
|
||||
function toJsonObject(config: OneBotConfig): JsonObject {
|
||||
const nets = config.networks;
|
||||
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;
|
||||
}),
|
||||
networks: {
|
||||
httpServers: nets.httpServers.map(httpServerToJson),
|
||||
httpClients: nets.httpClients.map(httpClientToJson),
|
||||
wsServers: nets.wsServers.map(wsServerToJson),
|
||||
wsClients: nets.wsClients.map(wsClientToJson),
|
||||
},
|
||||
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);
|
||||
function applyBase(
|
||||
out: JsonObject,
|
||||
n: { name: string; enabled?: boolean; accessToken?: string; messageFormat: MessageFormat; reportSelfMessage: boolean },
|
||||
): void {
|
||||
out.name = n.name;
|
||||
if (n.enabled === false) out.enabled = false;
|
||||
if (n.accessToken) out.accessToken = n.accessToken;
|
||||
out.messageFormat = n.messageFormat;
|
||||
out.reportSelfMessage = n.reportSelfMessage;
|
||||
}
|
||||
|
||||
function httpServerToJson(n: HttpServerNetwork): JsonObject {
|
||||
const out: JsonObject = {};
|
||||
applyBase(out, n);
|
||||
out.host = n.host ?? '0.0.0.0';
|
||||
out.port = n.port;
|
||||
out.path = n.path ?? '/';
|
||||
return out;
|
||||
}
|
||||
|
||||
function httpClientToJson(n: HttpClientNetwork): JsonObject {
|
||||
const out: JsonObject = {};
|
||||
applyBase(out, n);
|
||||
out.url = n.url;
|
||||
if (typeof n.timeoutMs === 'number' && n.timeoutMs > 0) out.timeoutMs = n.timeoutMs;
|
||||
return out;
|
||||
}
|
||||
|
||||
function wsServerToJson(n: WsServerNetwork): JsonObject {
|
||||
const out: JsonObject = {};
|
||||
applyBase(out, n);
|
||||
out.host = n.host ?? '0.0.0.0';
|
||||
out.port = n.port;
|
||||
out.path = n.path ?? '/';
|
||||
out.role = n.role ?? 'Universal';
|
||||
return out;
|
||||
}
|
||||
|
||||
function wsClientToJson(n: WsClientNetwork): JsonObject {
|
||||
const out: JsonObject = {};
|
||||
applyBase(out, n);
|
||||
out.url = n.url;
|
||||
out.role = n.role ?? 'Universal';
|
||||
out.reconnectIntervalMs =
|
||||
typeof n.reconnectIntervalMs === 'number' && Number.isFinite(n.reconnectIntervalMs)
|
||||
? Math.max(1000, Math.trunc(n.reconnectIntervalMs))
|
||||
: 5000;
|
||||
return out;
|
||||
}
|
||||
|
||||
function fromJson(sources: JsonObject[]): OneBotConfig {
|
||||
// Legacy top-level scalars are pulled DOWN into each adapter on the first
|
||||
// load: the on-disk schema has no globals anymore, every adapter is
|
||||
// self-describing. We compute the legacy fallbacks here so that adapters
|
||||
// missing `messageFormat`/`reportSelfMessage` inherit them once and the
|
||||
// file is rewritten in normalized form.
|
||||
let legacyFormat: MessageFormat | undefined;
|
||||
let legacyReport: boolean | undefined;
|
||||
let musicSignUrl = '';
|
||||
for (const src of sources) {
|
||||
const mf = parseMessageFormat(src.messageFormat);
|
||||
if (mf) legacyFormat = mf;
|
||||
if (typeof src.reportSelfMessage === 'boolean') legacyReport = src.reportSelfMessage;
|
||||
if (typeof src.musicSignUrl === 'string') musicSignUrl = src.musicSignUrl;
|
||||
}
|
||||
const inheritedFormat: MessageFormat = legacyFormat ?? 'array';
|
||||
const inheritedReport: boolean = legacyReport ?? false;
|
||||
|
||||
// Pluck per-type arrays from each source: prefer `networks.<kind>` over
|
||||
// legacy top-level arrays, but accept both. Later sources override earlier
|
||||
// ones at the network level (last write wins per `(kind, name)` pair).
|
||||
const adapterDefaults = { messageFormat: inheritedFormat, reportSelfMessage: inheritedReport };
|
||||
const httpServers = collectByName<HttpServerNetwork>(sources, 'httpServers', (raw) => parseHttpServer(raw, adapterDefaults));
|
||||
const httpClients = collectByName<HttpClientNetwork>(sources, 'httpClients', (raw) => parseHttpClient(raw, adapterDefaults), 'httpPostEndpoints');
|
||||
const wsServers = collectByName<WsServerNetwork>(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults));
|
||||
const wsClients = collectByName<WsClientNetwork>(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults));
|
||||
|
||||
// Seed defaults if all four arrays are empty (brand-new install).
|
||||
if (
|
||||
httpServers.length === 0 &&
|
||||
httpClients.length === 0 &&
|
||||
wsServers.length === 0 &&
|
||||
wsClients.length === 0
|
||||
) {
|
||||
const defaults = makeDefaultOneBotConfig().networks;
|
||||
httpServers.push(...defaults.httpServers);
|
||||
wsServers.push(...defaults.wsServers);
|
||||
}
|
||||
|
||||
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
|
||||
return { networks, musicSignUrl };
|
||||
}
|
||||
|
||||
function collectByName<T extends { name: string }>(
|
||||
sources: JsonObject[],
|
||||
kind: keyof OneBotNetworks,
|
||||
parse: (raw: JsonObject) => T | null,
|
||||
legacyKey?: string,
|
||||
): T[] {
|
||||
const byName = new Map<string, T>();
|
||||
const order: string[] = [];
|
||||
|
||||
let counter = 0;
|
||||
const ingest = (rawArr: unknown): void => {
|
||||
if (!Array.isArray(rawArr)) return;
|
||||
for (const raw of rawArr) {
|
||||
if (!isObject(raw)) continue;
|
||||
const parsed = parse(raw);
|
||||
if (!parsed) continue;
|
||||
const name = parsed.name && parsed.name.trim() ? parsed.name.trim() : pickAutoName(kind, byName, ++counter);
|
||||
parsed.name = name;
|
||||
if (!byName.has(name)) order.push(name);
|
||||
byName.set(name, parsed);
|
||||
}
|
||||
};
|
||||
|
||||
for (const src of sources) {
|
||||
const nested = isObject(src.networks) ? (src.networks as JsonObject)[kind] : undefined;
|
||||
ingest(nested);
|
||||
if (legacyKey) ingest(src[legacyKey]);
|
||||
ingest(src[kind]);
|
||||
}
|
||||
|
||||
return order.map((n) => byName.get(n)!);
|
||||
}
|
||||
|
||||
function pickAutoName(kind: keyof OneBotNetworks, used: Map<string, unknown>, counter: number): string {
|
||||
const prefix =
|
||||
kind === 'httpServers' ? 'http' :
|
||||
kind === 'httpClients' ? 'httppost' :
|
||||
kind === 'wsServers' ? 'ws' :
|
||||
'wsclient';
|
||||
let candidate = `${prefix}-${counter}`;
|
||||
while (used.has(candidate)) {
|
||||
counter += 1;
|
||||
candidate = `${prefix}-${counter}`;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
interface AdapterDefaults {
|
||||
messageFormat: MessageFormat;
|
||||
reportSelfMessage: boolean;
|
||||
}
|
||||
|
||||
function parseBase(value: JsonObject, defaults: AdapterDefaults) {
|
||||
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 : '',
|
||||
name: asString(value.name),
|
||||
enabled: typeof value.enabled === 'boolean' ? value.enabled : undefined,
|
||||
accessToken: asString(value.accessToken) || undefined,
|
||||
messageFormat: parseMessageFormat(value.messageFormat) ?? defaults.messageFormat,
|
||||
reportSelfMessage:
|
||||
typeof value.reportSelfMessage === 'boolean' ? value.reportSelfMessage : defaults.reportSelfMessage,
|
||||
};
|
||||
}
|
||||
|
||||
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 parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServerNetwork | null {
|
||||
const port = asNumber(value.port, 0);
|
||||
if (port <= 0) return null;
|
||||
return clean({
|
||||
...parseBase(value, defaults),
|
||||
host: asString(value.host, '0.0.0.0'),
|
||||
port,
|
||||
path: asString(value.path, '/'),
|
||||
});
|
||||
}
|
||||
|
||||
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 parseHttpClient(value: JsonObject, defaults: AdapterDefaults): HttpClientNetwork | null {
|
||||
const url = asString(value.url);
|
||||
if (!url) return null;
|
||||
const timeout = asNumber(value.timeoutMs, 0);
|
||||
return clean({
|
||||
...parseBase(value, defaults),
|
||||
url,
|
||||
timeoutMs: timeout > 0 ? timeout : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
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 parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNetwork | null {
|
||||
const port = asNumber(value.port, 0);
|
||||
if (port <= 0) return null;
|
||||
return clean({
|
||||
...parseBase(value, defaults),
|
||||
host: asString(value.host, '0.0.0.0'),
|
||||
port,
|
||||
path: asString(value.path, '/'),
|
||||
role: asRole(value.role, 'Universal'),
|
||||
});
|
||||
}
|
||||
|
||||
function toWsClients(value: unknown): WsClientEndpoint[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const result: WsClientEndpoint[] = [];
|
||||
function parseWsClient(value: JsonObject, defaults: AdapterDefaults): WsClientNetwork | null {
|
||||
const url = asString(value.url);
|
||||
if (!url) return null;
|
||||
const reconnectIntervalMs = asNumber(value.reconnectIntervalMs, 5000);
|
||||
return clean({
|
||||
...parseBase(value, defaults),
|
||||
url,
|
||||
role: asRole(value.role, 'Universal'),
|
||||
reconnectIntervalMs: Math.max(1000, reconnectIntervalMs),
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
function hasLegacyTopLevel(raw: JsonObject): boolean {
|
||||
return (
|
||||
Array.isArray(raw.httpServers) ||
|
||||
Array.isArray(raw.httpPostEndpoints) ||
|
||||
Array.isArray(raw.wsServers) ||
|
||||
Array.isArray(raw.wsClients) ||
|
||||
typeof raw.messageFormat === 'string' ||
|
||||
typeof raw.reportSelfMessage === 'boolean'
|
||||
);
|
||||
}
|
||||
|
||||
function parseMessageFormat(value: unknown): MessageFormat | undefined {
|
||||
if (value === 'array' || value === 'string') return value;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function clean<T extends Record<string, unknown>>(obj: T): T {
|
||||
for (const key of Object.keys(obj) as (keyof T)[]) {
|
||||
if (obj[key] === undefined) delete obj[key];
|
||||
}
|
||||
|
||||
return result;
|
||||
return obj;
|
||||
}
|
||||
|
||||
function asRole(value: unknown, fallback: WsRole): WsRole {
|
||||
const text = asString(value, fallback);
|
||||
return text === 'api' || text === 'event' || text === 'universal' ? text : fallback;
|
||||
// Accept both uppercase (canonical) and lowercase (legacy on-disk) forms.
|
||||
// Lowercase values are auto-migrated to uppercase on the next save.
|
||||
const text = asString(value, fallback).toLowerCase();
|
||||
if (text === 'api') return 'Api';
|
||||
if (text === 'event') return 'Event';
|
||||
if (text === 'universal') return 'Universal';
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function asString(value: unknown, fallback = ''): string {
|
||||
@@ -276,10 +348,6 @@ function asNumber(value: unknown, fallback = 0): number {
|
||||
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 {
|
||||
|
||||
@@ -5,11 +5,24 @@ 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;
|
||||
/**
|
||||
* Side-channel callback invoked every time an image/record segment is
|
||||
* produced, so that callers can keep a lookup index (e.g. for `get_image` /
|
||||
* `get_record`) without having to re-scan the persisted message store.
|
||||
*/
|
||||
export type MediaSegmentSink = (
|
||||
mediaType: 'image' | 'record',
|
||||
element: MessageElement,
|
||||
data: JsonObject,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
) => void;
|
||||
|
||||
export class EventConverter {
|
||||
private imageUrlResolver_: ImageUrlResolver | null = null;
|
||||
private mediaUrlResolver_: MediaUrlResolver | null = null;
|
||||
private messageIdResolver_: MessageIdResolver | null = null;
|
||||
private mediaSegmentSink_: MediaSegmentSink | null = null;
|
||||
|
||||
setImageUrlResolver(resolver: ImageUrlResolver): void {
|
||||
this.imageUrlResolver_ = resolver;
|
||||
@@ -23,18 +36,24 @@ export class EventConverter {
|
||||
this.messageIdResolver_ = resolver;
|
||||
}
|
||||
|
||||
setMediaSegmentSink(sink: MediaSegmentSink): void {
|
||||
this.mediaSegmentSink_ = sink;
|
||||
}
|
||||
|
||||
async convert(instanceUin: string, event: QQEventVariant): Promise<JsonObject | null> {
|
||||
const selfId = parseSelfId(instanceUin);
|
||||
|
||||
switch (event.kind) {
|
||||
case 'friend_message':
|
||||
{
|
||||
const isSelf = event.senderUin === selfId;
|
||||
const postType = isSelf ? 'message_sent' : '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_);
|
||||
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_, this.mediaSegmentSink_);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'message',
|
||||
post_type: postType,
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: messageId,
|
||||
@@ -54,12 +73,14 @@ export class EventConverter {
|
||||
|
||||
case 'group_message':
|
||||
{
|
||||
const isSelf = event.senderUin === selfId;
|
||||
const postType = isSelf ? 'message_sent' : '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_);
|
||||
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_, this.mediaSegmentSink_);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'message',
|
||||
post_type: postType,
|
||||
message_type: 'group',
|
||||
sub_type: 'normal',
|
||||
message_id: messageId,
|
||||
@@ -83,12 +104,14 @@ export class EventConverter {
|
||||
|
||||
case 'temp_message':
|
||||
{
|
||||
const isSelf = event.senderUin === selfId;
|
||||
const postType = isSelf ? 'message_sent' : '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_);
|
||||
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_, this.mediaSegmentSink_);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'message',
|
||||
post_type: postType,
|
||||
message_type: 'private',
|
||||
sub_type: 'group',
|
||||
message_id: messageId,
|
||||
@@ -314,10 +337,11 @@ async function elementsToJson(
|
||||
resolver?: ImageUrlResolver | null,
|
||||
mediaResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
mediaSink?: MediaSegmentSink | null,
|
||||
): Promise<JsonArray> {
|
||||
const result: JsonArray = [];
|
||||
for (const element of elements) {
|
||||
result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver));
|
||||
result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver, mediaSink));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -329,8 +353,9 @@ export async function elementsToOneBotSegments(
|
||||
resolver?: ImageUrlResolver | null,
|
||||
mediaResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
mediaSink?: MediaSegmentSink | null,
|
||||
): Promise<JsonArray> {
|
||||
return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver);
|
||||
return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver, mediaSink);
|
||||
}
|
||||
|
||||
async function elementToSegment(
|
||||
@@ -340,6 +365,7 @@ async function elementToSegment(
|
||||
resolver?: ImageUrlResolver | null,
|
||||
mediaResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
mediaSink?: MediaSegmentSink | null,
|
||||
): Promise<JsonObject> {
|
||||
if (element.type === 'text') {
|
||||
return { type: 'text', data: { text: element.text ?? '' } };
|
||||
@@ -351,13 +377,12 @@ async function elementToSegment(
|
||||
|
||||
if (element.type === 'image') {
|
||||
const url = resolver ? resolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
return {
|
||||
type: 'image',
|
||||
data: {
|
||||
url,
|
||||
file: element.fileId ?? '',
|
||||
},
|
||||
const data: JsonObject = {
|
||||
url,
|
||||
file: element.fileId ?? '',
|
||||
};
|
||||
if (mediaSink) mediaSink('image', element, data, isGroup, sessionId);
|
||||
return { type: 'image', data };
|
||||
}
|
||||
|
||||
if (element.type === 'at') {
|
||||
@@ -374,13 +399,12 @@ async function elementToSegment(
|
||||
|
||||
if (element.type === 'record') {
|
||||
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
return {
|
||||
type: 'record',
|
||||
data: {
|
||||
file: element.fileName ?? element.fileId ?? '',
|
||||
url,
|
||||
},
|
||||
const data: JsonObject = {
|
||||
file: element.fileName ?? element.fileId ?? '',
|
||||
url,
|
||||
};
|
||||
if (mediaSink) mediaSink('record', element, data, isGroup, sessionId);
|
||||
return { type: 'record', data };
|
||||
}
|
||||
|
||||
if (element.type === 'video') {
|
||||
|
||||
106
packages/core/src/onebot/event-filter.ts
Normal file
106
packages/core/src/onebot/event-filter.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import type { JsonObject, JsonValue, MessageFormat } from './types';
|
||||
|
||||
/**
|
||||
* Per-adapter view of how an event should be reported.
|
||||
*
|
||||
* Built once from each adapter's own configuration at (re)load time so the
|
||||
* per-publish dispatch loop is just a couple of object lookups.
|
||||
*/
|
||||
export interface EventReportOptions {
|
||||
/** Effective `messageFormat` for this adapter. */
|
||||
messageFormat: MessageFormat;
|
||||
/** Whether self-sent messages should be forwarded to this adapter. */
|
||||
reportSelfMessage: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the dispatch options from an adapter. Each adapter is fully
|
||||
* self-describing — there is no global fallback. Defaults are applied here
|
||||
* only as a safety net for partially-deserialized legacy configs.
|
||||
*/
|
||||
export function resolveReportOptions(
|
||||
network: { messageFormat?: MessageFormat; reportSelfMessage?: boolean },
|
||||
): EventReportOptions {
|
||||
return {
|
||||
messageFormat: network.messageFormat ?? 'array',
|
||||
reportSelfMessage: network.reportSelfMessage ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-built payload covering every adapter variant of a single canonical event.
|
||||
*
|
||||
* The bridge produces one OneBot-shaped event per upstream packet. Because
|
||||
* adapters only differ in (a) whether they receive `message_sent` self-events
|
||||
* and (b) whether the `message` field is the segment array or its CQ-string
|
||||
* form, we serialize the event at most twice up-front and let every adapter
|
||||
* pick the slot it needs in O(1).
|
||||
*/
|
||||
export interface DispatchPayload {
|
||||
/** True when the canonical event is a self-sent message (`post_type='message_sent'`). */
|
||||
isSelfMessage: boolean;
|
||||
/** JSON for adapters using `messageFormat: 'array'` (the canonical event). */
|
||||
arrayJson: string;
|
||||
/**
|
||||
* JSON for adapters using `messageFormat: 'string'`. For non-message events
|
||||
* this points at the same string as `arrayJson` (no transformation needed).
|
||||
*/
|
||||
stringJson: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the dispatch payload for one canonical OneBot event. Performs at most
|
||||
* two `JSON.stringify` calls (one per format variant) regardless of how many
|
||||
* adapters the payload will fan out to.
|
||||
*/
|
||||
export function buildDispatchPayload(event: JsonObject): DispatchPayload {
|
||||
const isSelfMessage = event.post_type === 'message_sent';
|
||||
const arrayJson = JSON.stringify(event);
|
||||
|
||||
let stringJson = arrayJson;
|
||||
const hasMessage = event.post_type === 'message' || event.post_type === 'message_sent';
|
||||
if (hasMessage && Array.isArray(event.message)) {
|
||||
const raw = typeof event.raw_message === 'string' ? event.raw_message : '';
|
||||
stringJson = JSON.stringify({ ...event, message: raw as JsonValue });
|
||||
}
|
||||
|
||||
return { isSelfMessage, arrayJson, stringJson };
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the pre-serialized payload variant an adapter should send, or `null`
|
||||
* when the adapter chose not to receive this event. Hot-path helper: one
|
||||
* branch + one map lookup per connection, no allocation.
|
||||
*/
|
||||
export function pickDispatchJson(
|
||||
payload: DispatchPayload,
|
||||
options: EventReportOptions,
|
||||
): string | null {
|
||||
if (payload.isSelfMessage && !options.reportSelfMessage) return null;
|
||||
return options.messageFormat === 'string' ? payload.stringJson : payload.arrayJson;
|
||||
}
|
||||
|
||||
/**
|
||||
* One-shot variant of {@link buildDispatchPayload} + {@link pickDispatchJson}
|
||||
* for ad-hoc events (e.g. WS connection bootstrap meta events) that aren't
|
||||
* worth pre-building a full payload for.
|
||||
*
|
||||
* Returns `null` when the adapter shouldn't see this event. Otherwise returns
|
||||
* the original event untouched, or a shallow clone with `message` rewritten.
|
||||
*/
|
||||
export function shapeEventForAdapter(
|
||||
event: JsonObject,
|
||||
options: EventReportOptions,
|
||||
): JsonObject | null {
|
||||
if (event.post_type === 'message_sent' && !options.reportSelfMessage) return null;
|
||||
|
||||
if (options.messageFormat === 'string'
|
||||
&& (event.post_type === 'message' || event.post_type === 'message_sent')
|
||||
&& Array.isArray(event.message)
|
||||
) {
|
||||
const raw = typeof event.raw_message === 'string' ? event.raw_message : '';
|
||||
return { ...event, message: raw as JsonValue };
|
||||
}
|
||||
|
||||
return event;
|
||||
}
|
||||
113
packages/core/src/onebot/event-pipeline.ts
Normal file
113
packages/core/src/onebot/event-pipeline.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
// Per-kind bridge → OneBot event handlers.
|
||||
//
|
||||
// Replaces the legacy single-firehose `OneBotInstance.onBridgeEvent` switch.
|
||||
// Every bridge event kind gets a small async handler bound to a shared
|
||||
// `OneBotInstanceContext`; subscribers register on `ctx.bridge.events` so
|
||||
// multiple unrelated downstream concerns (meta caching, OB11 conversion,
|
||||
// dispatch) compose cleanly without one giant switch statement.
|
||||
|
||||
import type { OneBotInstanceContext } from './instance-context';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { QQEventVariant } from '../bridge/events';
|
||||
|
||||
/**
|
||||
* Subscribe every `OneBotInstanceContext`-aware handler onto the bridge
|
||||
* event bus. Returns a disposer that removes every subscription registered
|
||||
* here in one shot — useful for tests and for tearing down a session.
|
||||
*/
|
||||
export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
|
||||
const disposers: Array<() => void> = [];
|
||||
|
||||
// Every kind that maps onto an OB11 message event also seeds the
|
||||
// message-meta cache; we do that synchronously before async conversion so
|
||||
// reply / quote lookups for that message id work even if the converter
|
||||
// takes a beat to finish (e.g. while resolving image URLs).
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('group_message', async (event) => {
|
||||
cacheGroupMessageMeta(ctx, event);
|
||||
await convertAndDispatch(ctx, event);
|
||||
}),
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('friend_message', async (event) => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, event.msgId);
|
||||
await convertAndDispatch(ctx, event);
|
||||
}),
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('temp_message', async (event) => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
|
||||
await convertAndDispatch(ctx, event);
|
||||
}),
|
||||
);
|
||||
|
||||
// Notice / request / non-message events: no meta caching needed, just
|
||||
// convert and dispatch.
|
||||
for (const kind of NOTICE_KINDS) {
|
||||
disposers.push(
|
||||
ctx.bridge.events.on(kind, async (event) => {
|
||||
await convertAndDispatch(ctx, event);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const dispose of disposers) {
|
||||
try { dispose(); } catch { /* ignore */ }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const NOTICE_KINDS = [
|
||||
'group_member_join',
|
||||
'group_member_leave',
|
||||
'group_mute',
|
||||
'group_admin',
|
||||
'friend_recall',
|
||||
'group_recall',
|
||||
'friend_request',
|
||||
'group_invite',
|
||||
'friend_poke',
|
||||
'group_poke',
|
||||
'group_essence',
|
||||
'group_file_upload',
|
||||
'friend_add',
|
||||
] as const satisfies readonly QQEventVariant['kind'][];
|
||||
|
||||
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
|
||||
const converted = await ctx.eventConverter.convert(ctx.uin, event);
|
||||
if (!converted) return;
|
||||
ctx.dispatchEvent(converted);
|
||||
}
|
||||
|
||||
function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEventVariant, { kind: 'group_message' }>): void {
|
||||
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
|
||||
ctx.cacheMessageMeta(messageId, {
|
||||
isGroup: true,
|
||||
targetId: event.groupId,
|
||||
sequence: event.msgSeq,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: event.msgId,
|
||||
timestamp: event.time,
|
||||
});
|
||||
}
|
||||
|
||||
function cachePrivateMessageMeta(
|
||||
ctx: OneBotInstanceContext,
|
||||
senderUin: number,
|
||||
msgSeq: number,
|
||||
timestamp: number,
|
||||
random: number,
|
||||
): void {
|
||||
const messageId = hashMessageIdInt32(msgSeq, senderUin, PRIVATE_MESSAGE_EVENT);
|
||||
ctx.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: senderUin,
|
||||
sequence: msgSeq,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random,
|
||||
timestamp,
|
||||
});
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
import type { JsonObject, OneBotConfig, HttpPostEndpoint } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
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 context: HttpPostTransportContext;
|
||||
private endpoints: HttpPostEndpoint[] = [];
|
||||
private stopped = false;
|
||||
|
||||
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
|
||||
this.endpoints = [...config.httpPostEndpoints];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.stopped = false;
|
||||
const count = this.endpoints.length;
|
||||
if (count > 0) {
|
||||
log.info('configured %d HTTP POST endpoint(s)', count);
|
||||
}
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
this.endpoints = [...config.httpPostEndpoints];
|
||||
log.info('reloaded %d HTTP POST endpoint(s)', this.endpoints.length);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
publishEvent(event: JsonObject): void {
|
||||
const endpoints = this.endpoints;
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from 'http';
|
||||
import type { ApiHandler } from './api-handler';
|
||||
import type { HttpServerEndpoint, OneBotConfig } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
export interface HttpTransportContext {
|
||||
api: ApiHandler;
|
||||
}
|
||||
|
||||
const log = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpTransport {
|
||||
private readonly context: HttpTransportContext;
|
||||
private readonly servers = new Map<string, Server>();
|
||||
private endpoints: HttpServerEndpoint[] = [];
|
||||
|
||||
constructor(config: OneBotConfig, context: HttpTransportContext) {
|
||||
this.endpoints = [...config.httpServers];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
for (const endpoint of this.endpoints) this.startEndpoint(endpoint);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
const nextEndpoints = [...config.httpServers];
|
||||
const nextKeys = new Set(nextEndpoints.map(httpServerKey));
|
||||
|
||||
for (const [key, server] of this.servers) {
|
||||
if (!nextKeys.has(key)) {
|
||||
server.close();
|
||||
this.servers.delete(key);
|
||||
log.info('stopped %s', key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextEndpoints) {
|
||||
if (!this.servers.has(httpServerKey(endpoint))) {
|
||||
this.startEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
this.endpoints = nextEndpoints;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
for (const server of this.servers.values()) {
|
||||
server.close();
|
||||
}
|
||||
this.servers.clear();
|
||||
}
|
||||
|
||||
private startEndpoint(endpoint: HttpServerEndpoint): void {
|
||||
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.set(httpServerKey(endpoint), server);
|
||||
}
|
||||
|
||||
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 httpServerKey(endpoint: HttpServerEndpoint): string {
|
||||
return `${endpoint.host}:${endpoint.port}${normalizePath(endpoint.path ?? '/')}#${endpoint.accessToken ?? ''}`;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
@@ -1,24 +1,57 @@
|
||||
import type { Bridge } from '../bridge/bridge';
|
||||
import type { ForwardNodePayload } from '../bridge/events';
|
||||
import type { ForwardNodePayload, MessageElement } from '../bridge/events';
|
||||
import type { QQInfo } from '../bridge/qq-info';
|
||||
import type { ApiActionContext, MessageSendResult } from './api-handler';
|
||||
import type { EventConverter } from './event-converter';
|
||||
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';
|
||||
import type { MediaStore } from './media-store';
|
||||
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import {WebHonorType} from "@/bridge/web/group-honor";
|
||||
|
||||
export interface InstanceRef {
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
/**
|
||||
* Single shared context bag that flows through every OneBot instance-internal
|
||||
* subsystem: API builder and the per-kind event pipeline.
|
||||
*
|
||||
* Only fields that are actually read through this bag live here — the api
|
||||
* handler and network manager are owned by `OneBotInstance` directly because
|
||||
* nothing reads them via ctx, and including them here would force a
|
||||
* chicken-and-egg `late-bound` field dance during construction.
|
||||
*
|
||||
* `dispatchEvent` is the indirection used by the event pipeline to hand a
|
||||
* converted OneBot event back to the instance for caching + adapter fan-out;
|
||||
* it lets the pipeline stay decoupled from the network manager.
|
||||
*/
|
||||
export interface OneBotInstanceContext {
|
||||
/** Self UIN as string (matches what's on disk and on the wire). */
|
||||
uin: string;
|
||||
/** Self UIN parsed once, used in event payloads. */
|
||||
selfId: number;
|
||||
|
||||
qqInfo: QQInfo;
|
||||
bridge: Bridge;
|
||||
|
||||
messageStore: MessageStore;
|
||||
mediaStore: MediaStore;
|
||||
|
||||
eventConverter: EventConverter;
|
||||
|
||||
config: OneBotConfig;
|
||||
musicSignUrl?: string;
|
||||
|
||||
/** Persist meta about a message id; safe to call any number of times. */
|
||||
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
|
||||
/** Hand a fully-converted OneBot event to the network manager + caches. */
|
||||
dispatchEvent(event: JsonObject): void;
|
||||
}
|
||||
|
||||
export function buildApiContext(ref: InstanceRef): ApiActionContext {
|
||||
const { bridge, qqInfo, messageStore } = ref;
|
||||
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
const { bridge, qqInfo, messageStore, mediaStore } = ref;
|
||||
|
||||
return {
|
||||
getLoginInfo: () => getLoginInfo(ref),
|
||||
@@ -26,7 +59,7 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
|
||||
getMessage: (messageId) => messageStore.findEvent(messageId),
|
||||
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => false,
|
||||
canSendRecord: () => true,
|
||||
sendPrivateMessage: (userId, message, autoEscape) => handleSendPrivate(ref, userId, message, autoEscape),
|
||||
sendGroupMessage: (groupId, message, autoEscape) => handleSendGroup(ref, groupId, message, autoEscape),
|
||||
deleteMessage: (messageId, meta) => handleDeleteMessage(bridge, meta),
|
||||
@@ -108,6 +141,8 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
|
||||
getForwardMsg: async (resId) => {
|
||||
return handleGetForward(ref, resId);
|
||||
},
|
||||
forceFetchClientKey: async () => bridge.forceFetchClientKey(),
|
||||
|
||||
// Extended NapCat-compatible
|
||||
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
|
||||
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
|
||||
@@ -116,28 +151,101 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
|
||||
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
|
||||
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
|
||||
},
|
||||
markGroupMsgAsRead: (groupId: number, sequence: number) => bridge.markGroupMsgAsRead(groupId, sequence),
|
||||
markPrivateMsgAsRead: (userId: number, sequence: number) => bridge.markPrivateMsgAsRead(userId, sequence),
|
||||
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.setOnlineStatus(status, extStatus, batteryStatus),
|
||||
setProfile: (nickname?: string, personalNote?: string) => bridge.setProfile(nickname, personalNote),
|
||||
// web
|
||||
getGroupHonorInfo: (groupId: number, type: WebHonorType | string)=> bridge.getGroupHonorInfo(groupId, type),
|
||||
getGroupEssence: (groupId: number, pageStart: number = 0, pageLimit: number = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit),
|
||||
getGroupEssenceAll: (groupId: number) => bridge.getGroupEssenceAll(groupId),
|
||||
sendGroupNotice: (groupId: number, content: string, options?: any) => bridge.sendGroupNotice(groupId, content, options),
|
||||
getGroupNotice: (groupId: number) => bridge.getGroupNotice(groupId),
|
||||
getCookiesStr: (domain: string) => bridge.getCookiesStr(domain),
|
||||
getCsrfToken: () => bridge.getCsrfToken(),
|
||||
getCredentials: (domain: string) => bridge.getCredentials(domain),
|
||||
// Media lookup
|
||||
getImageInfo: (file) => handleGetImageInfo(mediaStore, file),
|
||||
getRecordInfo: (file) => handleGetRecordInfo(bridge, mediaStore, file),
|
||||
};
|
||||
}
|
||||
|
||||
// --- Media lookup ---
|
||||
|
||||
async function handleGetImageInfo(
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findImage(file);
|
||||
if (!cached) return null;
|
||||
const url = cached.url || cached.imageUrl || '';
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url,
|
||||
file_size: String(cached.fileSize ?? 0),
|
||||
file_name: cached.fileName || cached.file,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleGetRecordInfo(
|
||||
bridge: Bridge,
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findRecord(file);
|
||||
if (!cached) return null;
|
||||
|
||||
// Re-resolve via OIDB if the cached URL is missing or empty.
|
||||
// Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid.
|
||||
let url = cached.url;
|
||||
if (!url && cached.mediaNode) {
|
||||
try {
|
||||
url = cached.isGroup
|
||||
? await bridge.fetchGroupPttUrlByNode(cached.sessionId, cached.mediaNode)
|
||||
: await bridge.fetchPrivatePttUrlByNode(cached.mediaNode);
|
||||
if (url) {
|
||||
mediaStore.updateRecordUrl(file, url);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url: url || '',
|
||||
file_size: String(cached.fileSize ?? 0),
|
||||
file_name: cached.fileName || cached.file,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Login info ---
|
||||
|
||||
function getLoginInfo(ref: InstanceRef): { userId: number; nickname: string } {
|
||||
function getLoginInfo(ref: OneBotInstanceContext): { 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 */ }
|
||||
// NOTE: do NOT iterate all groups here. Calling fetchGroupMemberList for
|
||||
// every group on demand causes a fan-out (1 incoming request -> N OIDB
|
||||
// 0xfe7_3 calls where N = group count). When a busy OneBot client (e.g.
|
||||
// MaiBot) issues `get_group_member_info(no_cache=true)` per inbound
|
||||
// message, this amplifier produced ~hundreds of OIDB calls per chat
|
||||
// message and triggered Tencent risk-control / 7-day account ban.
|
||||
// Each handler below now refreshes only the resource it actually needs.
|
||||
|
||||
for (const g of groups) {
|
||||
try {
|
||||
await bridge.fetchGroupMemberList(g.groupId);
|
||||
} catch { /* best effort */ }
|
||||
}
|
||||
async function refreshGroupListOnly(bridge: Bridge, qqInfo: QQInfo): Promise<void> {
|
||||
try {
|
||||
await bridge.fetchGroupList();
|
||||
} catch { /* use cached */ }
|
||||
void qqInfo;
|
||||
}
|
||||
|
||||
async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promise<void> {
|
||||
try {
|
||||
await bridge.fetchGroupMemberList(groupId);
|
||||
} catch { /* use cached */ }
|
||||
}
|
||||
|
||||
function normalizeHistoryCount(count?: number): number {
|
||||
@@ -177,9 +285,7 @@ async function handleGetFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<Json
|
||||
|
||||
async function handleGetGroupList(bridge: Bridge, qqInfo: QQInfo, noCache?: boolean): Promise<JsonObject[]> {
|
||||
try {
|
||||
if (noCache) {
|
||||
await refreshAllGroupMembersCache(bridge, qqInfo);
|
||||
} else if (qqInfo.groups.length === 0) {
|
||||
if (noCache || qqInfo.groups.length === 0) {
|
||||
await bridge.fetchGroupList();
|
||||
}
|
||||
} catch { /* use cached */ }
|
||||
@@ -192,9 +298,7 @@ async function handleGetGroupList(bridge: Bridge, qqInfo: QQInfo, noCache?: bool
|
||||
}
|
||||
|
||||
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)) {
|
||||
if (noCache || !qqInfo.findGroup(groupId)) {
|
||||
try { await bridge.fetchGroupList(); } catch { /* use cached */ }
|
||||
}
|
||||
const g = qqInfo.findGroup(groupId);
|
||||
@@ -209,7 +313,7 @@ async function handleGetGroupInfo(bridge: Bridge, qqInfo: QQInfo, groupId: numbe
|
||||
|
||||
async function handleGetGroupMemberList(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise<JsonObject[]> {
|
||||
if (noCache) {
|
||||
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
|
||||
await refreshSingleGroupMembers(bridge, groupId);
|
||||
|
||||
const g = qqInfo.findGroup(groupId);
|
||||
if (!g) return [];
|
||||
@@ -259,10 +363,8 @@ async function handleGetGroupMemberList(bridge: Bridge, qqInfo: QQInfo, groupId:
|
||||
}
|
||||
|
||||
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 */ }
|
||||
if (noCache || !qqInfo.findGroupMember(groupId, userId)) {
|
||||
await refreshSingleGroupMembers(bridge, groupId);
|
||||
}
|
||||
const m = qqInfo.findGroupMember(groupId, userId);
|
||||
if (!m) return null;
|
||||
@@ -410,17 +512,92 @@ async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, mess
|
||||
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
|
||||
}
|
||||
|
||||
// --- Send message logging ---
|
||||
|
||||
function logSentMessage(isGroup: boolean, targetId: number, elements: MessageElement[]): void {
|
||||
const type = isGroup ? '群聊' : '私聊';
|
||||
const parts: string[] = [];
|
||||
|
||||
// Check for reply element
|
||||
const replyElem = elements.find(e => e.type === 'reply');
|
||||
if (replyElem && replyElem.replyMessageId) {
|
||||
parts.push(`[回复:${replyElem.replyMessageId}]`);
|
||||
}
|
||||
|
||||
// Build message content preview
|
||||
for (const elem of elements) {
|
||||
if (elem.type === 'reply') continue; // Already handled
|
||||
|
||||
switch (elem.type) {
|
||||
case 'text':
|
||||
if (elem.text) {
|
||||
const preview = elem.text.length > 50 ? elem.text.substring(0, 50) + '...' : elem.text;
|
||||
parts.push(preview);
|
||||
}
|
||||
break;
|
||||
case 'image':
|
||||
parts.push('[图片]');
|
||||
break;
|
||||
case 'face':
|
||||
parts.push('[表情]');
|
||||
break;
|
||||
case 'at':
|
||||
if (elem.text) parts.push(elem.text.trim());
|
||||
break;
|
||||
case 'record':
|
||||
parts.push('[语音]');
|
||||
break;
|
||||
case 'video':
|
||||
parts.push('[视频]');
|
||||
break;
|
||||
case 'json':
|
||||
parts.push('[JSON消息]');
|
||||
break;
|
||||
case 'xml':
|
||||
parts.push('[XML消息]');
|
||||
break;
|
||||
case 'markdown':
|
||||
parts.push('[Markdown]');
|
||||
break;
|
||||
case 'forward':
|
||||
parts.push('[转发消息]');
|
||||
break;
|
||||
case 'poke':
|
||||
parts.push('[戳一戳]');
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const content = parts.join(' ').trim() || '[空消息]';
|
||||
log.info(`${type} ${targetId} | 发送:${content}`);
|
||||
}
|
||||
|
||||
// --- Send message ---
|
||||
|
||||
async function handleSendPrivate(
|
||||
ref: InstanceRef,
|
||||
ref: OneBotInstanceContext,
|
||||
userId: number,
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
): Promise<MessageSendResult> {
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) =>
|
||||
ref.messageStore.resolveReplySequence(false, userId, replyMessageId),
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
if (meta) {
|
||||
return {
|
||||
senderUin: meta.targetId, // For received messages, targetId is the sender
|
||||
time: meta.timestamp,
|
||||
random: meta.random,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin),
|
||||
musicSignUrl: ref.musicSignUrl,
|
||||
});
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
@@ -428,6 +605,9 @@ async function handleSendPrivate(
|
||||
const receipt = await ref.bridge.sendPrivateMessage(userId, elements);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||
|
||||
// Log sent message
|
||||
logSentMessage(false, userId, elements);
|
||||
|
||||
// Cache the sent message meta
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
@@ -443,14 +623,27 @@ async function handleSendPrivate(
|
||||
}
|
||||
|
||||
async function handleSendGroup(
|
||||
ref: InstanceRef,
|
||||
ref: OneBotInstanceContext,
|
||||
groupId: number,
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
): Promise<MessageSendResult> {
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) =>
|
||||
ref.messageStore.resolveReplySequence(true, groupId, replyMessageId),
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
const event = ref.messageStore.findEvent(replyMessageId);
|
||||
if (event) {
|
||||
return {
|
||||
senderUin: typeof event.user_id === 'number' ? event.user_id : parseInt(String(event.user_id || '0'), 10),
|
||||
time: typeof event.time === 'number' ? event.time : parseInt(String(event.time || '0'), 10),
|
||||
random: 0, // Group messages might not have random field in event
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin, groupId),
|
||||
musicSignUrl: ref.musicSignUrl,
|
||||
});
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
@@ -458,6 +651,9 @@ async function handleSendGroup(
|
||||
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||
|
||||
// Log sent message
|
||||
logSentMessage(true, groupId, elements);
|
||||
|
||||
// Cache the sent message meta
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
isGroup: true,
|
||||
@@ -473,7 +669,7 @@ async function handleSendGroup(
|
||||
}
|
||||
|
||||
async function handleSendGroupForward(
|
||||
ref: InstanceRef,
|
||||
ref: OneBotInstanceContext,
|
||||
groupId: number,
|
||||
messages: JsonValue,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
@@ -496,7 +692,7 @@ async function handleSendGroupForward(
|
||||
}
|
||||
|
||||
async function handleSendPrivateForward(
|
||||
ref: InstanceRef,
|
||||
ref: OneBotInstanceContext,
|
||||
userId: number,
|
||||
messages: JsonValue,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
@@ -519,7 +715,7 @@ async function handleSendPrivateForward(
|
||||
}
|
||||
|
||||
async function handleUploadForward(
|
||||
ref: InstanceRef,
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
): Promise<{ forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages);
|
||||
@@ -528,7 +724,7 @@ async function handleUploadForward(
|
||||
}
|
||||
|
||||
async function handleGetForward(
|
||||
ref: InstanceRef,
|
||||
ref: OneBotInstanceContext,
|
||||
resId: string,
|
||||
): Promise<JsonObject[]> {
|
||||
const nodes = await ref.bridge.fetchForwardNodes(resId);
|
||||
@@ -548,7 +744,7 @@ async function handleGetForward(
|
||||
return results;
|
||||
}
|
||||
|
||||
async function parseForwardNodes(ref: InstanceRef, messages: JsonValue): Promise<ForwardNodePayload[]> {
|
||||
async function parseForwardNodes(ref: OneBotInstanceContext, messages: JsonValue): Promise<ForwardNodePayload[]> {
|
||||
if (!Array.isArray(messages)) {
|
||||
throw new Error('forward messages must be an array');
|
||||
}
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
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 { MediaStore } from './media-store';
|
||||
import { RKeyCache } from './instance-rkey';
|
||||
import { buildApiContext } from './instance-context';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
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';
|
||||
import type { JsonObject, MessageMeta, OneBotConfig, NetworkBase } from './types';
|
||||
import {
|
||||
OneBotNetworkManager,
|
||||
WsServerAdapter,
|
||||
WsClientAdapter,
|
||||
HttpServerAdapter,
|
||||
HttpPostAdapter,
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('Event');
|
||||
|
||||
export class OneBotInstance {
|
||||
readonly uin: string;
|
||||
@@ -21,10 +30,11 @@ export class OneBotInstance {
|
||||
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 mediaStore: MediaStore;
|
||||
private readonly networkManager: OneBotNetworkManager;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
private readonly ctx: OneBotInstanceContext;
|
||||
private disposeEventPipeline: (() => void) | null = null;
|
||||
|
||||
private readonly pids = new Set<number>();
|
||||
private online = true;
|
||||
@@ -38,6 +48,7 @@ export class OneBotInstance {
|
||||
|
||||
this.eventConverter = new EventConverter();
|
||||
this.rkeyCache = new RKeyCache();
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
|
||||
this.eventConverter.setImageUrlResolver((element, isGroup) =>
|
||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup));
|
||||
this.eventConverter.setMediaUrlResolver(async (element, isGroup, sessionId) => {
|
||||
@@ -66,69 +77,83 @@ export class OneBotInstance {
|
||||
// Then apply RKey if needed
|
||||
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
|
||||
});
|
||||
this.eventConverter.setMediaSegmentSink((mediaType, element, data, isGroup, sessionId) => {
|
||||
const url = typeof data.url === 'string' ? data.url : '';
|
||||
const file = typeof data.file === 'string' ? data.file : '';
|
||||
if (mediaType === 'image') {
|
||||
this.mediaStore.rememberImage({
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileId ?? '',
|
||||
subType: element.subType ?? 0,
|
||||
summary: element.summary ?? '',
|
||||
imageUrl: element.imageUrl ?? '',
|
||||
isGroup,
|
||||
sessionId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.mediaStore.rememberRecord({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileName ?? '',
|
||||
duration: element.duration ?? 0,
|
||||
fileHash: element.fileHash ?? '',
|
||||
mediaNode: element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
});
|
||||
});
|
||||
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({
|
||||
// Shared instance context. Only carries fields that are actually read
|
||||
// through it — api handler and network manager stay as direct fields on
|
||||
// the instance because nothing reads them via ctx.
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: this.uin,
|
||||
selfId: parseInt(this.uin, 10) || 0,
|
||||
qqInfo: this.qqInfo,
|
||||
bridge: this.bridge,
|
||||
messageStore: this.messageStore,
|
||||
mediaStore: this.mediaStore,
|
||||
eventConverter: this.eventConverter,
|
||||
config,
|
||||
musicSignUrl: config.musicSignUrl,
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
});
|
||||
this.apiHandler = new ApiHandler(context);
|
||||
dispatchEvent: (event) => this.dispatchEvent(event),
|
||||
};
|
||||
this.ctx = ctx;
|
||||
|
||||
this.httpTransport = new HttpTransport(config, {
|
||||
api: this.apiHandler,
|
||||
});
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx));
|
||||
this.networkManager = new OneBotNetworkManager();
|
||||
this.installAdaptersFromConfig(config);
|
||||
void this.networkManager.openAll();
|
||||
|
||||
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);
|
||||
|
||||
// Per-kind subscription on the typed event bus. Each bridge event kind
|
||||
// gets its own focused handler in `event-pipeline`; the firehose is gone.
|
||||
this.disposeEventPipeline = registerEventPipeline(ctx);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
this.httpTransport.reloadConfig(config);
|
||||
this.httpPostTransport.reloadConfig(config);
|
||||
this.wsTransport.reloadConfig(config);
|
||||
void this.applyConfigDiff(config);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.online = false;
|
||||
this.stopHeartbeat();
|
||||
this.httpTransport.stop();
|
||||
this.httpPostTransport.stop();
|
||||
this.wsTransport.stop();
|
||||
this.disposeEventPipeline?.();
|
||||
this.disposeEventPipeline = null;
|
||||
void this.networkManager.closeAll();
|
||||
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);
|
||||
this.mediaStore.close();
|
||||
}
|
||||
|
||||
addPid(pid: number): void {
|
||||
@@ -153,12 +178,151 @@ export class OneBotInstance {
|
||||
|
||||
private dispatchEvent(event: JsonObject): void {
|
||||
this.cacheMessageEvent(event);
|
||||
this.wsTransport.publishEvent(event);
|
||||
this.httpPostTransport.publishEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// NetworkManager builds the dispatch payload once and fans out to every
|
||||
// active adapter in parallel via Promise.allSettled.
|
||||
void this.networkManager.emitEvent(event);
|
||||
}
|
||||
|
||||
private buildNetworkContext(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: this.uin,
|
||||
api: this.apiHandler,
|
||||
buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType),
|
||||
buildHeartbeatEvent: () => this.makeHeartbeatEvent(),
|
||||
};
|
||||
}
|
||||
|
||||
private installAdaptersFromConfig(config: OneBotConfig): void {
|
||||
const ctx = this.buildNetworkContext();
|
||||
for (const net of config.networks.httpServers) {
|
||||
if (net.enabled === false) continue;
|
||||
this.networkManager.register(new HttpServerAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.httpClients) {
|
||||
if (net.enabled === false || !net.url) continue;
|
||||
this.networkManager.register(new HttpPostAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.wsServers) {
|
||||
if (net.enabled === false) continue;
|
||||
this.networkManager.register(new WsServerAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.wsClients) {
|
||||
if (net.enabled === false || !net.url) continue;
|
||||
this.networkManager.register(new WsClientAdapter(net.name, net, ctx));
|
||||
}
|
||||
}
|
||||
|
||||
private async applyConfigDiff(next: OneBotConfig): Promise<void> {
|
||||
const ctx = this.buildNetworkContext();
|
||||
const desired = new Map<string, NetworkBase>();
|
||||
const factories = new Map<string, () => void>();
|
||||
|
||||
for (const net of next.networks.httpServers) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new HttpServerAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.httpClients) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new HttpPostAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.wsServers) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new WsServerAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.wsClients) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new WsClientAdapter(net.name, net, ctx)));
|
||||
}
|
||||
|
||||
// Close adapters whose entry has been removed entirely.
|
||||
for (const adapter of this.networkManager.list()) {
|
||||
if (!desired.has(adapter.name)) {
|
||||
await this.networkManager.closeOne(adapter.name);
|
||||
}
|
||||
}
|
||||
|
||||
// Reload existing adapters in place; spin up new ones the manager hasn't
|
||||
// seen before.
|
||||
for (const [name, net] of desired) {
|
||||
const existing = this.networkManager.get(name);
|
||||
if (existing) {
|
||||
try {
|
||||
await existing.reload(net as never);
|
||||
} catch (err) {
|
||||
log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else if (net.enabled !== false) {
|
||||
const factory = factories.get(name);
|
||||
if (factory) {
|
||||
factory();
|
||||
await this.networkManager.get(name)?.open();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private logReceivedMessage(event: JsonObject): void {
|
||||
const isSelf = event.post_type === 'message_sent';
|
||||
if (event.post_type !== 'message' && !isSelf) return;
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
const isGroup = event.message_type === 'group';
|
||||
|
||||
// Build message preview
|
||||
const parts: string[] = [];
|
||||
const message = event.message;
|
||||
|
||||
if (Array.isArray(message)) {
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const type = String(seg.type ?? '');
|
||||
const data: Record<string, unknown> = (
|
||||
typeof seg.data === 'object' && seg.data !== null && !Array.isArray(seg.data)
|
||||
) ? seg.data : {};
|
||||
|
||||
if (type === 'text' && data.text) {
|
||||
const text = String(data.text);
|
||||
const preview = text.length > 50 ? text.substring(0, 50) + '...' : text;
|
||||
parts.push(preview);
|
||||
} else if (type === 'image') {
|
||||
parts.push('[图片]');
|
||||
} else if (type === 'face') {
|
||||
parts.push('[表情]');
|
||||
} else if (type === 'at') {
|
||||
parts.push(`@${data.qq || ''}`);
|
||||
} else if (type === 'reply') {
|
||||
parts.push(`[回复:${data.id || ''}]`);
|
||||
} else if (type === 'record') {
|
||||
parts.push('[语音]');
|
||||
} else if (type === 'video') {
|
||||
parts.push('[视频]');
|
||||
} else {
|
||||
parts.push(`[${type}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const content = parts.join(' ').trim() || '[空消息]';
|
||||
const idStr = `ID:${messageId}`;
|
||||
const selfTag = isSelf ? '[自身] ' : '';
|
||||
|
||||
if (isGroup) {
|
||||
const groupId = toInt(event.group_id);
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = event.sender as any;
|
||||
const nickname = sender?.card || sender?.nickname || String(userId);
|
||||
log.success(`${selfTag}群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`);
|
||||
} else {
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = event.sender as any;
|
||||
const nickname = sender?.nickname || String(userId);
|
||||
log.success(`${selfTag}私聊 ${nickname}(${userId}): ${idStr} ${content}`);
|
||||
}
|
||||
}
|
||||
|
||||
private cacheMessageEvent(event: JsonObject): void {
|
||||
if (event.post_type !== 'message') return;
|
||||
if (event.post_type !== 'message' && event.post_type !== 'message_sent') return;
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
if (messageId === 0) return;
|
||||
@@ -172,49 +336,6 @@ export class OneBotInstance {
|
||||
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);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
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';
|
||||
@@ -21,9 +20,8 @@ export class OneBotManager {
|
||||
this.onSessionClosed(uin);
|
||||
});
|
||||
|
||||
bridgeManager.setEventCallback((uin, event) => {
|
||||
this.onBridgeEvent(uin, event);
|
||||
});
|
||||
// Per-kind subscriptions to `bridge.events` happen inside
|
||||
// `OneBotInstance` itself; no global firehose to wire here.
|
||||
}
|
||||
|
||||
getInstance(uin: string): OneBotInstance | null {
|
||||
@@ -80,12 +78,6 @@ export class OneBotManager {
|
||||
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> {
|
||||
|
||||
267
packages/core/src/onebot/media-store.ts
Normal file
267
packages/core/src/onebot/media-store.ts
Normal file
@@ -0,0 +1,267 @@
|
||||
// Persistent media metadata store.
|
||||
//
|
||||
// The `get_image` / `get_record` actions need to map a `data.file` (or related
|
||||
// identifier) we previously emitted in a message segment back to the URL,
|
||||
// size, name, and any OIDB media-node info needed to re-resolve a stale URL.
|
||||
//
|
||||
// Earlier this lived in an in-memory `MediaCache`, which meant the lookup
|
||||
// table was lost on every restart. This implementation persists everything
|
||||
// alongside the message store so OneBot consumers can always resolve the
|
||||
// media that produced any segment ever stored, even after the bot restarts.
|
||||
//
|
||||
// Schema overview (single SQLite file per UIN, e.g. `data/<uin>/media.db`):
|
||||
// media_entries(type, primary_key, data JSON, last_seen) -- one row per logical media item
|
||||
// media_keys(type, key, primary_key) -- secondary index for every alias
|
||||
//
|
||||
// `rememberImage` / `rememberRecord` upsert exactly one entry row plus one
|
||||
// alias row per identifier (file / fileName / fileId / url). The alias rows
|
||||
// always point to the canonical entry so URL refreshes propagate to every
|
||||
// alias automatically.
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
|
||||
import type { MessageElement } from '../bridge/events';
|
||||
|
||||
export interface CachedImage {
|
||||
/** Primary `data.file` value as exposed in the OneBot segment. */
|
||||
file: string;
|
||||
/** Last known resolved URL (may be empty if resolution failed). */
|
||||
url: string;
|
||||
fileSize: number;
|
||||
fileName: string;
|
||||
subType: number;
|
||||
summary: string;
|
||||
/** Conversation the media originated from. */
|
||||
isGroup: boolean;
|
||||
sessionId: number;
|
||||
/** Original imageUrl from the MessageElement, used for RKey re-appending. */
|
||||
imageUrl: string;
|
||||
}
|
||||
|
||||
export interface CachedRecord {
|
||||
/** Primary `data.file` value as exposed in the OneBot segment. */
|
||||
file: string;
|
||||
/** Raw fileId from the MessageElement (typically the fileUuid). */
|
||||
fileId: string;
|
||||
/** Last known resolved URL (may be empty if resolution failed). */
|
||||
url: string;
|
||||
fileSize: number;
|
||||
fileName: string;
|
||||
duration: number;
|
||||
fileHash: string;
|
||||
/** OIDB media node used to re-fetch the URL via getPtt*UrlByNode. */
|
||||
mediaNode?: MessageElement['mediaNode'];
|
||||
/** Conversation the media originated from (group vs private path). */
|
||||
isGroup: boolean;
|
||||
sessionId: number;
|
||||
}
|
||||
|
||||
const TYPE_IMAGE = 'image';
|
||||
const TYPE_RECORD = 'record';
|
||||
const DEFAULT_KEEP_ENTRIES = 4096;
|
||||
|
||||
export class MediaStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly maxEntriesPerType: number;
|
||||
|
||||
// Prepared statements (pay the parsing cost once at startup).
|
||||
private readonly upsertEntry: StatementSync;
|
||||
private readonly upsertKey: StatementSync;
|
||||
private readonly findEntryByKey: StatementSync;
|
||||
private readonly findEntryByPrimary: StatementSync;
|
||||
private readonly evictByType: StatementSync;
|
||||
private readonly purgeOrphanKeys: StatementSync;
|
||||
private readonly countByType: StatementSync;
|
||||
|
||||
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
|
||||
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
|
||||
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
this.upsertEntry = this.db.prepare(
|
||||
`INSERT INTO media_entries (type, primary_key, data, last_seen)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(type, primary_key) DO UPDATE SET
|
||||
data = excluded.data,
|
||||
last_seen = excluded.last_seen`,
|
||||
);
|
||||
this.upsertKey = this.db.prepare(
|
||||
`INSERT INTO media_keys (type, key, primary_key)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key`,
|
||||
);
|
||||
this.findEntryByKey = this.db.prepare(
|
||||
`SELECT e.data FROM media_entries e
|
||||
JOIN media_keys k ON k.type = e.type AND k.primary_key = e.primary_key
|
||||
WHERE k.type = ? AND k.key = ?
|
||||
LIMIT 1`,
|
||||
);
|
||||
this.findEntryByPrimary = this.db.prepare(
|
||||
`SELECT data FROM media_entries WHERE type = ? AND primary_key = ?`,
|
||||
);
|
||||
this.evictByType = this.db.prepare(
|
||||
// `rowid DESC` makes the tiebreaker match insertion order (newest first)
|
||||
// so reproducible inserts within the same `last_seen` second still get
|
||||
// the most recent rows retained, regardless of how the lexicographic
|
||||
// sort would have ordered the synthetic primary_key.
|
||||
`DELETE FROM media_entries WHERE type = ? AND rowid IN (
|
||||
SELECT rowid FROM media_entries
|
||||
WHERE type = ?
|
||||
ORDER BY last_seen DESC, rowid DESC
|
||||
LIMIT -1 OFFSET ?
|
||||
)`,
|
||||
);
|
||||
this.purgeOrphanKeys = this.db.prepare(
|
||||
`DELETE FROM media_keys WHERE type = ? AND primary_key NOT IN (
|
||||
SELECT primary_key FROM media_entries WHERE type = ?
|
||||
)`,
|
||||
);
|
||||
this.countByType = this.db.prepare(
|
||||
`SELECT COUNT(*) AS n FROM media_entries WHERE type = ?`,
|
||||
);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
|
||||
rememberImage(info: CachedImage): void {
|
||||
const primaryKey = pickPrimary([info.file, info.fileName]);
|
||||
if (!primaryKey) return;
|
||||
this.upsertWithAliases(TYPE_IMAGE, primaryKey, info, [info.file, info.fileName, info.url]);
|
||||
}
|
||||
|
||||
rememberRecord(info: CachedRecord): void {
|
||||
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
|
||||
if (!primaryKey) return;
|
||||
this.upsertWithAliases(TYPE_RECORD, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
}
|
||||
|
||||
findImage(key: string): CachedImage | null {
|
||||
return this.findByAnyKey<CachedImage>(TYPE_IMAGE, key);
|
||||
}
|
||||
|
||||
findRecord(key: string): CachedRecord | null {
|
||||
return this.findByAnyKey<CachedRecord>(TYPE_RECORD, key);
|
||||
}
|
||||
|
||||
updateImageUrl(key: string, url: string): void {
|
||||
if (!url) return;
|
||||
const cached = this.findImage(key);
|
||||
if (!cached || cached.url === url) return;
|
||||
this.rememberImage({ ...cached, url });
|
||||
}
|
||||
|
||||
updateRecordUrl(key: string, url: string): void {
|
||||
if (!url) return;
|
||||
const cached = this.findRecord(key);
|
||||
if (!cached || cached.url === url) return;
|
||||
this.rememberRecord({ ...cached, url });
|
||||
}
|
||||
|
||||
/** Snapshot count of distinct entries per type; mostly used by tests. */
|
||||
size(): { images: number; records: number } {
|
||||
const img = this.countByType.get(TYPE_IMAGE) as { n: number } | undefined;
|
||||
const rec = this.countByType.get(TYPE_RECORD) as { n: number } | undefined;
|
||||
return { images: img?.n ?? 0, records: rec?.n ?? 0 };
|
||||
}
|
||||
|
||||
// --- internals ---
|
||||
|
||||
private initSchema(): void {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS media_entries (
|
||||
type TEXT NOT NULL,
|
||||
primary_key TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
last_seen INTEGER NOT NULL,
|
||||
PRIMARY KEY (type, primary_key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_media_entries_lastseen
|
||||
ON media_entries(type, last_seen DESC);
|
||||
CREATE TABLE IF NOT EXISTS media_keys (
|
||||
type TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
primary_key TEXT NOT NULL,
|
||||
PRIMARY KEY (type, key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_media_keys_primary
|
||||
ON media_keys(type, primary_key);
|
||||
`);
|
||||
}
|
||||
|
||||
private upsertWithAliases<T>(
|
||||
type: string,
|
||||
primaryKey: string,
|
||||
info: T,
|
||||
aliases: (string | undefined)[],
|
||||
): void {
|
||||
const data = JSON.stringify(info);
|
||||
const lastSeen = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Run the writes in a transaction so concurrent readers always see a
|
||||
// consistent (entry, keys) pair.
|
||||
this.db.exec('BEGIN');
|
||||
try {
|
||||
this.upsertEntry.run(type, primaryKey, data, lastSeen);
|
||||
const seen = new Set<string>();
|
||||
for (const raw of aliases) {
|
||||
if (!raw) continue;
|
||||
if (seen.has(raw)) continue;
|
||||
seen.add(raw);
|
||||
this.upsertKey.run(type, raw, primaryKey);
|
||||
}
|
||||
this.db.exec('COMMIT');
|
||||
} catch (err) {
|
||||
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Eager eviction. The DELETE is a no-op when row count <= cap so
|
||||
// there is no measurable cost while we are below the limit.
|
||||
this.evictOldEntries(type);
|
||||
}
|
||||
|
||||
private findByAnyKey<T>(type: string, key: string): T | null {
|
||||
if (!key) return null;
|
||||
const row = this.findEntryByKey.get(type, key) as { data: string } | undefined;
|
||||
if (row?.data) return safeParse<T>(row.data);
|
||||
// Fall back to looking up by primary_key directly so callers that pass
|
||||
// the canonical identifier still hit (e.g. when the alias index is yet
|
||||
// to be built for that key in this session).
|
||||
const fallback = this.findEntryByPrimary.get(type, key) as { data: string } | undefined;
|
||||
return fallback?.data ? safeParse<T>(fallback.data) : null;
|
||||
}
|
||||
|
||||
private evictOldEntries(type: string): void {
|
||||
try {
|
||||
this.evictByType.run(type, type, this.maxEntriesPerType);
|
||||
this.purgeOrphanKeys.run(type, type);
|
||||
} catch {
|
||||
// Best-effort eviction; don't propagate.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function pickPrimary(candidates: (string | undefined)[]): string {
|
||||
for (const c of candidates) {
|
||||
if (c && c.length > 0) return c;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function safeParse<T>(json: string): T | null {
|
||||
try {
|
||||
return JSON.parse(json) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import type { JsonValue, JsonObject } from './types';
|
||||
|
||||
export interface ParseMessageOptions {
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||
resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null;
|
||||
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
|
||||
musicSignUrl?: string;
|
||||
}
|
||||
|
||||
@@ -88,12 +90,25 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
return { type: 'face', faceId: id };
|
||||
}
|
||||
case 'at': {
|
||||
const qq = String(data.qq ?? '');
|
||||
const qq = String(data.qq ?? '').trim();
|
||||
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;
|
||||
if (uin <= 0) return null;
|
||||
|
||||
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
|
||||
let uid = String(data.uid ?? '').trim();
|
||||
if (!uid && options?.resolveMentionUid) {
|
||||
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'at',
|
||||
targetUin: uin,
|
||||
uid: uid || undefined,
|
||||
text: name ? `@${name} ` : `@${uin} `,
|
||||
};
|
||||
}
|
||||
case 'reply': {
|
||||
const id = parseInt(String(data.id ?? '0'), 10);
|
||||
@@ -102,7 +117,23 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
if (options?.resolveReplySequence) {
|
||||
const resolved = options.resolveReplySequence(id);
|
||||
if (typeof resolved === 'number' && resolved > 0) {
|
||||
return { type: 'reply', replySeq: resolved };
|
||||
const element: MessageElement = {
|
||||
type: 'reply',
|
||||
replySeq: resolved,
|
||||
replyMessageId: id // Keep the original messageId for logging
|
||||
};
|
||||
|
||||
// Try to get additional meta info for better reply display
|
||||
if (options?.resolveReplyMeta) {
|
||||
const meta = options.resolveReplyMeta(id);
|
||||
if (meta) {
|
||||
element.replySenderUin = meta.senderUin;
|
||||
element.replyTime = meta.time;
|
||||
element.replyRandom = meta.random;
|
||||
}
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,9 +150,11 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
};
|
||||
}
|
||||
case 'record': {
|
||||
const source = String(data.file ?? data.url ?? data.path ?? '');
|
||||
if (!source) return null;
|
||||
return {
|
||||
type: 'record',
|
||||
url: String(data.file ?? data.url ?? ''),
|
||||
url: source,
|
||||
};
|
||||
}
|
||||
case 'video': {
|
||||
|
||||
@@ -120,15 +120,31 @@ export class MessageStore {
|
||||
}
|
||||
|
||||
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 (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null;
|
||||
// For private messages, we cannot rely on session_id matching because:
|
||||
// - When receiving: session_id is the sender's UIN
|
||||
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
|
||||
// So for private messages, we only match by message_hash and is_group flag.
|
||||
const row = isGroup
|
||||
? this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(sessionId, messageId) as { sequence: number } | undefined
|
||||
: this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 0 AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(messageId) as { sequence: number } | undefined;
|
||||
|
||||
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
|
||||
return null;
|
||||
}
|
||||
return row.sequence;
|
||||
}
|
||||
|
||||
|
||||
65
packages/core/src/onebot/network/adapter.ts
Normal file
65
packages/core/src/onebot/network/adapter.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
// Base abstractions for OneBot network adapters.
|
||||
//
|
||||
// Modeled on NapCat's `IOB11NetworkAdapter` so each entry under
|
||||
// `config.networks.{httpServers,httpClients,wsServers,wsClients}` becomes
|
||||
// exactly one adapter instance, identified by `name`. The previous design
|
||||
// rolled multiple servers/clients into a single transport class; the
|
||||
// per-entry split makes hot-reload, lifecycle, and event isolation much
|
||||
// simpler to reason about.
|
||||
|
||||
import type { ApiHandler } from '../api-handler';
|
||||
import type { JsonObject, NetworkBase } from '../types';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
|
||||
export interface NetworkAdapterContext {
|
||||
/** Self UIN as string — written into outbound headers. */
|
||||
uin: string;
|
||||
/** Shared API dispatcher used by request/response style adapters. */
|
||||
api: ApiHandler;
|
||||
/** Build a lifecycle event payload (connect/enable/disable). */
|
||||
buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject;
|
||||
/** Build a heartbeat event payload. */
|
||||
buildHeartbeatEvent(): JsonObject;
|
||||
}
|
||||
|
||||
export enum NetworkReloadType {
|
||||
/** Configuration unchanged or only soft fields updated. */
|
||||
Normal = 0,
|
||||
/** Underlying socket/listener restarted in place. */
|
||||
Reopened = 1,
|
||||
/** Was running, now closed. */
|
||||
Closed = 2,
|
||||
/** Was idle, now opened. */
|
||||
Opened = 3,
|
||||
}
|
||||
|
||||
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
readonly name: string;
|
||||
protected config: C;
|
||||
protected readonly ctx: NetworkAdapterContext;
|
||||
protected isEnabled = false;
|
||||
|
||||
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
|
||||
this.name = name;
|
||||
// Defensive copy so reload diffs never mutate the caller's object.
|
||||
this.config = structuredClone(config);
|
||||
this.ctx = ctx;
|
||||
}
|
||||
|
||||
/** Whether the adapter is currently accepting/relaying events. */
|
||||
get isActive(): boolean { return this.isEnabled; }
|
||||
|
||||
/** Snapshot of the active config (read-only). */
|
||||
get currentConfig(): Readonly<C> { return this.config; }
|
||||
|
||||
abstract open(): void | Promise<void>;
|
||||
abstract close(): void | Promise<void>;
|
||||
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
|
||||
|
||||
/**
|
||||
* Receive one fully-shaped OneBot event for forwarding. Adapters that
|
||||
* don't push events (e.g. HTTP request-response servers) override with a
|
||||
* no-op.
|
||||
*/
|
||||
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
|
||||
}
|
||||
136
packages/core/src/onebot/network/http-post-adapter.ts
Normal file
136
packages/core/src/onebot/network/http-post-adapter.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
// Outbound HTTP webhook adapter — one instance per `httpClients[]` entry.
|
||||
//
|
||||
// Forwards every event to the configured URL via HTTP POST and interprets
|
||||
// any JSON response body as a OneBot v11 quick-operation.
|
||||
|
||||
import type { HttpClientNetwork, JsonObject } from '../types';
|
||||
import {
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { executeQuickOperation } from './quick-operation';
|
||||
|
||||
const log = createLogger('OneBot.POST');
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private signature_: string;
|
||||
|
||||
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.signature_ = bindingSignature(config);
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
return this.isEnabled;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.config.enabled === false) return;
|
||||
if (!this.config.url) return;
|
||||
this.isEnabled = true;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.isEnabled = false;
|
||||
}
|
||||
|
||||
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false && !!next.url;
|
||||
|
||||
this.config = structuredClone(next);
|
||||
this.options = resolveReportOptions(next);
|
||||
const newSig = bindingSignature(next);
|
||||
const sigChanged = newSig !== this.signature_;
|
||||
this.signature_ = newSig;
|
||||
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
onEvent(event: JsonObject, payload: DispatchPayload): void {
|
||||
if (!this.isEnabled) return;
|
||||
const json = pickDispatchJson(payload, this.options);
|
||||
if (json === null) return;
|
||||
void this.postEvent(json, event);
|
||||
}
|
||||
|
||||
private async postEvent(payload: string, event: JsonObject): Promise<void> {
|
||||
if (!this.isEnabled) return;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'OneBot',
|
||||
'X-Self-ID': this.ctx.uin,
|
||||
};
|
||||
if (this.config.accessToken) {
|
||||
headers['X-Signature'] = await computeHmacSha1(this.config.accessToken, payload);
|
||||
}
|
||||
|
||||
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
try {
|
||||
const response = await fetch(this.config.url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: payload,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
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('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.isEnabled) {
|
||||
log.warn('[%s] POST %s failed: %s', this.name, this.config.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.ctx.api);
|
||||
} catch (error) {
|
||||
log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bindingSignature(net: HttpClientNetwork): string {
|
||||
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
|
||||
}
|
||||
|
||||
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
|
||||
const { createHmac } = await import('crypto');
|
||||
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
|
||||
}
|
||||
203
packages/core/src/onebot/network/http-server-adapter.ts
Normal file
203
packages/core/src/onebot/network/http-server-adapter.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
// Inbound HTTP API server — one instance per `httpServers[]` entry.
|
||||
//
|
||||
// Pure request/response: incoming POST/GET maps to `ApiHandler.handle`,
|
||||
// the response body is JSON-serialized back. `onEvent` is a deliberate
|
||||
// no-op since this transport never pushes events.
|
||||
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from 'http';
|
||||
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
|
||||
override get isActive(): boolean {
|
||||
// HTTP server never receives events — `isActive` purely tracks the
|
||||
// bound listener so the network manager can skip dispatch cleanly.
|
||||
return this.isEnabled;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
if (this.config.enabled === false) return;
|
||||
this.startServer();
|
||||
this.isEnabled = true;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (!this.isEnabled && !this.server) return;
|
||||
this.isEnabled = false;
|
||||
this.server?.close();
|
||||
this.server = null;
|
||||
}
|
||||
|
||||
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false;
|
||||
|
||||
this.config = structuredClone(next);
|
||||
|
||||
const sigChanged = prevSig !== bindingSignature(next);
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
// HTTP server only acts on inbound requests; it doesn't push events.
|
||||
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
|
||||
|
||||
private startServer(): void {
|
||||
const expectedPath = normalizePath(this.config.path ?? '/');
|
||||
const accessToken = this.config.accessToken ?? '';
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
void this.handleRequest(expectedPath, accessToken, req, res);
|
||||
});
|
||||
this.server = server;
|
||||
|
||||
server.on('listening', () => {
|
||||
log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
this.config.port,
|
||||
expectedPath,
|
||||
);
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
server.listen(this.config.port, this.config.host ?? '0.0.0.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;
|
||||
|
||||
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
|
||||
let action = '';
|
||||
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
|
||||
action = '';
|
||||
} else if (incomingPath.startsWith(ep)) {
|
||||
action = incomingPath.substring(ep.length);
|
||||
} 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)) {
|
||||
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;
|
||||
}
|
||||
|
||||
const response = await this.ctx.api.handle(action, params as JsonObject);
|
||||
if (echo !== undefined) {
|
||||
response.echo = echo as 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 bindingSignature(net: HttpServerNetwork): string {
|
||||
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}#${net.accessToken ?? ''}`;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
9
packages/core/src/onebot/network/index.ts
Normal file
9
packages/core/src/onebot/network/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
// Public surface for the OneBot network package.
|
||||
|
||||
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
export { OneBotNetworkManager } from './network-manager';
|
||||
export { WsServerAdapter } from './ws-server-adapter';
|
||||
export { WsClientAdapter } from './ws-client-adapter';
|
||||
export { HttpServerAdapter } from './http-server-adapter';
|
||||
export { HttpPostAdapter } from './http-post-adapter';
|
||||
export { executeQuickOperation } from './quick-operation';
|
||||
105
packages/core/src/onebot/network/network-manager.ts
Normal file
105
packages/core/src/onebot/network/network-manager.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
// OneBot network manager.
|
||||
//
|
||||
// Mirrors NapCat's `OB11NetworkManager`: holds a `Map<name, adapter>`, fans
|
||||
// events out to every active adapter in parallel, and provides primitives
|
||||
// the OneBot instance uses to register, hot-reload, and tear adapters down.
|
||||
|
||||
import type { JsonObject, NetworkBase } from '../types';
|
||||
import { buildDispatchPayload } from '../event-filter';
|
||||
import { IOneBotNetworkAdapter } from './adapter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('OneBot.Network');
|
||||
|
||||
type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
|
||||
|
||||
export class OneBotNetworkManager {
|
||||
private readonly adapters = new Map<string, AnyAdapter>();
|
||||
|
||||
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
|
||||
const existing = this.adapters.get(adapter.name);
|
||||
if (existing) {
|
||||
// Replacing an adapter under the same name — close the previous one
|
||||
// before storing the new instance to keep ports/sockets clean.
|
||||
log.info('replacing adapter [%s]', adapter.name);
|
||||
void Promise.resolve(existing.close()).catch(() => { /* best-effort */ });
|
||||
}
|
||||
this.adapters.set(adapter.name, adapter as AnyAdapter);
|
||||
}
|
||||
|
||||
has(name: string): boolean { return this.adapters.has(name); }
|
||||
|
||||
get(name: string): AnyAdapter | null {
|
||||
return this.adapters.get(name) ?? null;
|
||||
}
|
||||
|
||||
list(): AnyAdapter[] { return [...this.adapters.values()]; }
|
||||
|
||||
hasActiveAdapters(): boolean {
|
||||
for (const a of this.adapters.values()) if (a.isActive) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
async openAll(): Promise<void> {
|
||||
const tasks = this.list().map(async (a) => {
|
||||
try {
|
||||
await a.open();
|
||||
} catch (err) {
|
||||
log.error('adapter [%s] open failed: %s', a.name, errMessage(err));
|
||||
}
|
||||
});
|
||||
await Promise.all(tasks);
|
||||
}
|
||||
|
||||
async closeAll(): Promise<void> {
|
||||
const tasks = this.list().map(async (a) => {
|
||||
try {
|
||||
await a.close();
|
||||
} catch (err) {
|
||||
log.warn('adapter [%s] close failed: %s', a.name, errMessage(err));
|
||||
}
|
||||
});
|
||||
await Promise.all(tasks);
|
||||
this.adapters.clear();
|
||||
}
|
||||
|
||||
async closeOne(name: string): Promise<void> {
|
||||
const adapter = this.adapters.get(name);
|
||||
if (!adapter) return;
|
||||
this.adapters.delete(name);
|
||||
try {
|
||||
await adapter.close();
|
||||
} catch (err) {
|
||||
log.warn('adapter [%s] close failed: %s', adapter.name, errMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch one canonical OneBot event to every active adapter in parallel.
|
||||
* The dispatch payload is built once so each adapter pays only the cost
|
||||
* of picking the right pre-serialized variant.
|
||||
*
|
||||
* Errors thrown inside an adapter are isolated — one bad adapter never
|
||||
* blocks the others.
|
||||
*/
|
||||
async emitEvent(event: JsonObject): Promise<void> {
|
||||
if (!this.hasActiveAdapters()) return;
|
||||
const payload = buildDispatchPayload(event);
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
for (const adapter of this.adapters.values()) {
|
||||
if (!adapter.isActive) continue;
|
||||
tasks.push(
|
||||
Promise.resolve()
|
||||
.then(() => adapter.onEvent(event, payload))
|
||||
.catch((err) => {
|
||||
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(err));
|
||||
}),
|
||||
);
|
||||
}
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
}
|
||||
|
||||
function errMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
89
packages/core/src/onebot/network/quick-operation.ts
Normal file
89
packages/core/src/onebot/network/quick-operation.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
// OneBot v11 hidden API: `.handle_quick_operation`.
|
||||
//
|
||||
// When an HTTP POST event report receives a JSON body in response, that body
|
||||
// is interpreted as a "quick operation" — short-cuts to common follow-up
|
||||
// API calls (reply, recall, ban, kick, approve/reject). Spec:
|
||||
// https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md
|
||||
|
||||
import type { ApiHandler } from '../api-handler';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
|
||||
export async function executeQuickOperation(
|
||||
event: JsonObject,
|
||||
operation: Record<string, unknown>,
|
||||
api: ApiHandler,
|
||||
): Promise<void> {
|
||||
const postType = event.post_type as string;
|
||||
|
||||
if (postType === 'message') {
|
||||
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 JsonValue,
|
||||
auto_escape: autoEscape,
|
||||
};
|
||||
if (operation.at_sender !== false && event.user_id) {
|
||||
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 JsonValue;
|
||||
params.auto_escape = false;
|
||||
} else if (Array.isArray(operation.reply)) {
|
||||
params.message = [atSegment, ...(operation.reply as unknown[])] as 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 JsonValue,
|
||||
auto_escape: autoEscape,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (operation.delete) {
|
||||
await api.handle('delete_msg', { message_id: event.message_id as number });
|
||||
}
|
||||
|
||||
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 JsonValue,
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 JsonValue,
|
||||
remark: (operation.remark ?? '') as 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 JsonValue,
|
||||
reason: (operation.reason ?? '') as JsonValue,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
59
packages/core/src/onebot/network/utils.ts
Normal file
59
packages/core/src/onebot/network/utils.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
// Helpers shared between OneBot network adapters.
|
||||
|
||||
import type { IncomingMessage } from 'http';
|
||||
import type { WebSocket } from '@snowluma/websocket';
|
||||
|
||||
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
|
||||
export function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) return true;
|
||||
const rawAuth = request.headers.authorization;
|
||||
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
|
||||
if (auth === `Bearer ${token}`) return true;
|
||||
try {
|
||||
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
|
||||
if (url.searchParams.get('access_token') === token) return true;
|
||||
} catch { /* ignore malformed URLs */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Convert anything ws can hand us into a UTF-8 string. */
|
||||
export function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
|
||||
if (typeof raw === 'string') return raw;
|
||||
if (Buffer.isBuffer(raw)) 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 '';
|
||||
}
|
||||
|
||||
/** Best-effort send: drops payload if the socket isn't OPEN, reports send errors. */
|
||||
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
|
||||
if (socket.readyState !== 1 /* WebSocket.OPEN */) return;
|
||||
socket.send(payload, (error?: Error | null) => {
|
||||
if (error && onError) onError(error);
|
||||
});
|
||||
}
|
||||
|
||||
/** Best-effort close, treats already-closed sockets as a no-op. */
|
||||
export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
|
||||
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return;
|
||||
socket.close(code, reason);
|
||||
}
|
||||
|
||||
/** Normalize an HTTP/WS path to a comparable form (strip trailing slash, default to "/"). */
|
||||
export function normalizePath(pathValue: string | undefined): string {
|
||||
const path = (pathValue ?? '/').trim() || '/';
|
||||
if (path === '/') return '/';
|
||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
}
|
||||
|
||||
/** Parse the `pathname` from a (potentially relative) WebSocket request URL. */
|
||||
export function parseRequestPath(urlValue: string): string {
|
||||
try {
|
||||
return new URL(urlValue, 'ws://127.0.0.1').pathname;
|
||||
} catch {
|
||||
return '/';
|
||||
}
|
||||
}
|
||||
177
packages/core/src/onebot/network/ws-client-adapter.ts
Normal file
177
packages/core/src/onebot/network/ws-client-adapter.ts
Normal file
@@ -0,0 +1,177 @@
|
||||
// Reverse (client) WebSocket adapter — one instance per `wsClients[]` entry.
|
||||
//
|
||||
// Connects out to a remote OneBot endpoint, manages reconnects, forwards
|
||||
// pushed events on `onEvent`, and dispatches incoming API messages to the
|
||||
// shared ApiHandler.
|
||||
|
||||
import { WebSocket } from '@snowluma/websocket';
|
||||
import type { WsClientNetwork, WsRole, JsonObject } from '../types';
|
||||
import {
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
shapeEventForAdapter,
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.WS-Client');
|
||||
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
|
||||
|
||||
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private socket: WebSocket | null = null;
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
private explicitlyClosed = false;
|
||||
|
||||
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.role = config.role ?? 'Universal';
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
return this.isEnabled;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
if (this.config.enabled === false) return;
|
||||
if (!this.config.url) return;
|
||||
this.explicitlyClosed = false;
|
||||
this.isEnabled = true;
|
||||
this.connect();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.explicitlyClosed = true;
|
||||
this.isEnabled = false;
|
||||
this.cancelReconnect();
|
||||
if (this.socket) {
|
||||
safeClose(this.socket);
|
||||
this.socket = null;
|
||||
}
|
||||
}
|
||||
|
||||
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false && !!next.url;
|
||||
|
||||
this.config = structuredClone(next);
|
||||
this.options = resolveReportOptions(next);
|
||||
this.role = next.role ?? 'Universal';
|
||||
|
||||
const sigChanged = prevSig !== bindingSignature(next);
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, payload: DispatchPayload): void {
|
||||
if (!this.isEnabled || !this.socket) return;
|
||||
if (this.role !== 'Event' && this.role !== 'Universal') return;
|
||||
const json = pickDispatchJson(payload, this.options);
|
||||
if (json === null) return;
|
||||
safeSend(this.socket, json);
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
if (this.explicitlyClosed) return;
|
||||
if (!this.config.url) return;
|
||||
if (this.socket) return;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'User-Agent': 'OneBot/11',
|
||||
'X-Self-ID': this.ctx.uin,
|
||||
'X-Client-Role': this.role,
|
||||
};
|
||||
if (this.config.accessToken) {
|
||||
headers.Authorization = `Bearer ${this.config.accessToken}`;
|
||||
}
|
||||
|
||||
const socket = new WebSocket(this.config.url, { headers });
|
||||
this.socket = socket;
|
||||
|
||||
socket.on('open', () => {
|
||||
log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
});
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, raw);
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
this.socket = null;
|
||||
if (this.explicitlyClosed || !this.isEnabled) return;
|
||||
this.scheduleReconnect();
|
||||
});
|
||||
|
||||
socket.on('error', (err: Error) => {
|
||||
log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectTimer) return;
|
||||
if (this.explicitlyClosed) return;
|
||||
const interval = Math.max(1000, this.config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS);
|
||||
const timer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
if (this.explicitlyClosed || !this.isEnabled) return;
|
||||
this.connect();
|
||||
}, interval);
|
||||
timer.unref?.();
|
||||
this.reconnectTimer = timer;
|
||||
}
|
||||
|
||||
private cancelReconnect(): void {
|
||||
if (!this.reconnectTimer) return;
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, raw: Buffer | string): Promise<void> {
|
||||
if (this.role !== 'Api' && this.role !== 'Universal') return;
|
||||
const text = rawDataToString(raw);
|
||||
if (!text) return;
|
||||
const response = await this.ctx.api.processRequest(text);
|
||||
safeSend(socket, response);
|
||||
}
|
||||
|
||||
private sendBootstrapMetaEvents(socket: WebSocket): void {
|
||||
if (this.role !== 'Event' && this.role !== 'Universal') return;
|
||||
const events = [
|
||||
this.ctx.buildLifecycleEvent('connect'),
|
||||
this.ctx.buildLifecycleEvent('enable'),
|
||||
this.ctx.buildHeartbeatEvent(),
|
||||
];
|
||||
for (const event of events) {
|
||||
const shaped = shapeEventForAdapter(event, this.options);
|
||||
if (!shaped) continue;
|
||||
safeSend(socket, JSON.stringify(shaped));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bindingSignature(net: WsClientNetwork): string {
|
||||
return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`;
|
||||
}
|
||||
187
packages/core/src/onebot/network/ws-server-adapter.ts
Normal file
187
packages/core/src/onebot/network/ws-server-adapter.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
// Forward (server) WebSocket adapter — one instance per `wsServers[]` entry.
|
||||
//
|
||||
// Each adapter owns its own `WebSocketServer`, accepts inbound forward
|
||||
// connections (api / event / universal roles), and pushes events to all live
|
||||
// event-receiving sockets when `onEvent` fires.
|
||||
|
||||
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'http';
|
||||
import type { WsRole, WsServerNetwork, JsonObject } from '../types';
|
||||
import {
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
shapeEventForAdapter,
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, parseRequestPath, rawDataToString, safeClose, safeSend, normalizePath } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.WS-Server');
|
||||
|
||||
interface ForwardConn {
|
||||
socket: WebSocket;
|
||||
role: WsRole;
|
||||
options: EventReportOptions;
|
||||
}
|
||||
|
||||
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
|
||||
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
return this.isEnabled;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
if (this.config.enabled === false) return;
|
||||
this.startServer();
|
||||
this.isEnabled = true;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (!this.isEnabled && this.connections.size === 0 && !this.wss) return;
|
||||
// Final lifecycle broadcast before tearing down so attached event clients
|
||||
// see the disable transition.
|
||||
const lifecycle = this.ctx.buildLifecycleEvent('disable');
|
||||
for (const conn of this.connections.values()) {
|
||||
if (conn.role === 'Api') continue;
|
||||
const shaped = shapeEventForAdapter(lifecycle, conn.options);
|
||||
if (!shaped) continue;
|
||||
safeSend(conn.socket, JSON.stringify(shaped));
|
||||
}
|
||||
|
||||
this.isEnabled = false;
|
||||
for (const ws of [...this.connections.keys()]) safeClose(ws);
|
||||
this.connections.clear();
|
||||
this.wss?.close();
|
||||
this.wss = null;
|
||||
}
|
||||
|
||||
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false;
|
||||
|
||||
this.config = structuredClone(next);
|
||||
this.options = resolveReportOptions(next);
|
||||
for (const conn of this.connections.values()) conn.options = this.options;
|
||||
|
||||
const sigChanged = prevSig !== bindingSignature(next);
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, payload: DispatchPayload): void {
|
||||
if (!this.isEnabled || this.connections.size === 0) return;
|
||||
for (const conn of this.connections.values()) {
|
||||
if (conn.role !== 'Event' && conn.role !== 'Universal') continue;
|
||||
const json = pickDispatchJson(payload, conn.options);
|
||||
if (json === null) continue;
|
||||
safeSend(conn.socket, json);
|
||||
}
|
||||
}
|
||||
|
||||
private startServer(): void {
|
||||
const wss = new WebSocketServer({
|
||||
host: this.config.host ?? '0.0.0.0',
|
||||
port: this.config.port,
|
||||
path: this.config.path ?? '/',
|
||||
});
|
||||
this.wss = wss;
|
||||
|
||||
wss.on('listening', () => {
|
||||
log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
this.config.port,
|
||||
this.config.path ?? '/',
|
||||
);
|
||||
});
|
||||
|
||||
wss.on('error', (err: Error) => {
|
||||
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
|
||||
}
|
||||
|
||||
private onConnection(socket: WebSocket, request: IncomingMessage): void {
|
||||
if (!isAuthorized(request, this.config.accessToken ?? '')) {
|
||||
safeClose(socket, 1008, 'invalid access token');
|
||||
return;
|
||||
}
|
||||
|
||||
const role = this.config.role ?? classifyForwardRole(request);
|
||||
const conn: ForwardConn = { socket, role, options: this.options };
|
||||
this.connections.set(socket, conn);
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, role, raw);
|
||||
});
|
||||
socket.on('close', () => this.connections.delete(socket));
|
||||
socket.on('error', (err: Error) => {
|
||||
log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
if (role === 'Event' || role === 'Universal') {
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
|
||||
if (role !== 'Api' && role !== 'Universal') return;
|
||||
const text = rawDataToString(raw);
|
||||
if (!text) return;
|
||||
const response = await this.ctx.api.processRequest(text);
|
||||
safeSend(socket, response);
|
||||
}
|
||||
|
||||
private sendBootstrapMetaEvents(socket: WebSocket): void {
|
||||
const events = [
|
||||
this.ctx.buildLifecycleEvent('connect'),
|
||||
this.ctx.buildLifecycleEvent('enable'),
|
||||
this.ctx.buildHeartbeatEvent(),
|
||||
];
|
||||
for (const event of events) {
|
||||
const shaped = shapeEventForAdapter(event, this.options);
|
||||
if (!shaped) continue;
|
||||
safeSend(socket, JSON.stringify(shaped));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 bindingSignature(net: WsServerNetwork): string {
|
||||
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path)}#${net.role ?? 'auto'}#${net.accessToken ?? ''}`;
|
||||
}
|
||||
@@ -19,47 +19,72 @@ export interface OneBotRequest {
|
||||
echo?: JsonValue;
|
||||
}
|
||||
|
||||
export interface WsServerEndpoint {
|
||||
name?: string;
|
||||
host: string;
|
||||
export type WsRole = 'Api' | 'Event' | 'Universal';
|
||||
|
||||
export type MessageFormat = 'array' | 'string';
|
||||
|
||||
export type NetworkKind = 'httpServers' | 'httpClients' | 'wsServers' | 'wsClients';
|
||||
|
||||
/**
|
||||
* Fields shared by every network adapter. `messageFormat` and
|
||||
* `reportSelfMessage` live on the adapter itself — there is no global default
|
||||
* fallback; each adapter is fully self-describing.
|
||||
*
|
||||
* The `name` is a free-form identifier scoped to the adapter's array; it is
|
||||
* used for hot-reload bookkeeping and as a label in logs / WebUI.
|
||||
*/
|
||||
export interface NetworkBase {
|
||||
name: string;
|
||||
/** When `false`, the adapter is configured but inactive. Defaults to `true`. */
|
||||
enabled?: boolean;
|
||||
accessToken?: string;
|
||||
/** Output format for this adapter. */
|
||||
messageFormat: MessageFormat;
|
||||
/** When `true`, this adapter receives `post_type='message_sent'` self events. */
|
||||
reportSelfMessage: boolean;
|
||||
}
|
||||
|
||||
export interface HttpServerNetwork extends NetworkBase {
|
||||
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;
|
||||
export interface HttpClientNetwork extends NetworkBase {
|
||||
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 interface WsServerNetwork extends NetworkBase {
|
||||
host?: string;
|
||||
port: number;
|
||||
path?: string;
|
||||
role?: WsRole;
|
||||
}
|
||||
|
||||
export type WsRole = 'api' | 'event' | 'universal';
|
||||
export interface WsClientNetwork extends NetworkBase {
|
||||
url: string;
|
||||
role?: WsRole;
|
||||
reconnectIntervalMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Network adapters grouped by type. Each adapter is identified by `name`
|
||||
* within its own array; hot-reload works on a per-(kind, name) basis.
|
||||
*/
|
||||
export interface OneBotNetworks {
|
||||
httpServers: HttpServerNetwork[];
|
||||
httpClients: HttpClientNetwork[];
|
||||
wsServers: WsServerNetwork[];
|
||||
wsClients: WsClientNetwork[];
|
||||
}
|
||||
|
||||
/** Per-UIN OneBot configuration. */
|
||||
export interface OneBotConfig {
|
||||
networks: OneBotNetworks;
|
||||
/** Music card signing service URL (optional). */
|
||||
musicSignUrl?: string;
|
||||
}
|
||||
|
||||
export interface MessageMeta {
|
||||
isGroup: boolean;
|
||||
|
||||
@@ -1,335 +0,0 @@
|
||||
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'http';
|
||||
import type { ApiHandler } from './api-handler';
|
||||
import type { JsonObject, OneBotConfig, WsClientEndpoint, WsRole, WsServerEndpoint } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
interface ForwardConnection {
|
||||
socket: WebSocket;
|
||||
role: WsRole;
|
||||
}
|
||||
|
||||
interface ReverseConnection {
|
||||
socket: WebSocket;
|
||||
role: WsRole;
|
||||
endpointUrl: string;
|
||||
reconnectIntervalMs: number;
|
||||
key: string;
|
||||
}
|
||||
|
||||
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 context: WsTransportContext;
|
||||
|
||||
private readonly servers = new Map<string, WebSocketServer>();
|
||||
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
|
||||
private readonly reverseConnections = new Set<ReverseConnection>();
|
||||
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
||||
private serverEndpoints: WsServerEndpoint[] = [];
|
||||
private clientEndpoints: WsClientEndpoint[] = [];
|
||||
private stopped = false;
|
||||
|
||||
constructor(config: OneBotConfig, context: WsTransportContext) {
|
||||
this.serverEndpoints = [...config.wsServers];
|
||||
this.clientEndpoints = [...config.wsClients];
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.stopped = false;
|
||||
this.startServers();
|
||||
this.startReverseClients();
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
const nextServers = [...config.wsServers];
|
||||
const nextClients = [...config.wsClients];
|
||||
const nextServerKeys = new Set(nextServers.map(wsServerKey));
|
||||
const nextClientKeys = new Set(nextClients.map(wsClientKey));
|
||||
|
||||
for (const [key, server] of this.servers) {
|
||||
if (!nextServerKeys.has(key)) {
|
||||
server.close();
|
||||
this.servers.delete(key);
|
||||
log.info('stopped forward server %s', key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextServers) {
|
||||
if (!this.servers.has(wsServerKey(endpoint))) {
|
||||
this.startServerEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
for (const conn of [...this.reverseConnections]) {
|
||||
if (!nextClientKeys.has(conn.key)) {
|
||||
safeClose(conn.socket);
|
||||
this.reverseConnections.delete(conn);
|
||||
log.info('stopped reverse client %s', conn.endpointUrl);
|
||||
}
|
||||
}
|
||||
|
||||
for (const endpoint of nextClients) {
|
||||
const key = wsClientKey(endpoint);
|
||||
if (![...this.reverseConnections].some(conn => conn.key === key)) {
|
||||
this.startClientEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
this.serverEndpoints = nextServers;
|
||||
this.clientEndpoints = nextClients;
|
||||
}
|
||||
|
||||
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.values()) {
|
||||
server.close();
|
||||
}
|
||||
this.servers.clear();
|
||||
}
|
||||
|
||||
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.serverEndpoints) {
|
||||
this.startServerEndpoint(endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private startServerEndpoint(endpoint: WsServerEndpoint): void {
|
||||
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: Buffer) => {
|
||||
void this.handleApiMessage(socket, role, raw);
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
this.forwardConnections.delete(socket);
|
||||
});
|
||||
|
||||
socket.on('error', (error: Error) => {
|
||||
log.warn('forward socket error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
this.sendBootstrapMetaEvents(socket, role);
|
||||
});
|
||||
|
||||
wss.on('error', (error: Error) => {
|
||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
this.servers.set(wsServerKey(endpoint), wss);
|
||||
}
|
||||
|
||||
private startReverseClients(): void {
|
||||
for (const endpoint of this.clientEndpoints) this.startClientEndpoint(endpoint);
|
||||
}
|
||||
|
||||
private startClientEndpoint(endpoint: WsClientEndpoint): void {
|
||||
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, key: wsClientPartsKey(endpointUrl, role, reconnectIntervalMs, accessToken) };
|
||||
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: Buffer) => {
|
||||
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: Error) => {
|
||||
log.warn('reverse error %s: %s', endpointUrl, error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): 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 normalizeWsPath(pathValue: string | undefined): string {
|
||||
const path = (pathValue ?? '/').trim() || '/';
|
||||
if (path === '/') return '/';
|
||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
}
|
||||
|
||||
function wsServerKey(endpoint: WsServerEndpoint): string {
|
||||
return `${endpoint.host}:${endpoint.port}${normalizeWsPath(endpoint.path)}#${endpoint.role ?? 'auto'}#${endpoint.accessToken ?? ''}`;
|
||||
}
|
||||
|
||||
function wsClientPartsKey(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string): string {
|
||||
return `${endpointUrl}#${role}#${reconnectIntervalMs}#${accessToken}`;
|
||||
}
|
||||
|
||||
function wsClientKey(endpoint: WsClientEndpoint): string {
|
||||
const role = endpoint.role ?? 'universal';
|
||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
||||
return wsClientPartsKey(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '');
|
||||
}
|
||||
|
||||
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: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
|
||||
if (typeof raw === 'string') return raw;
|
||||
if (Buffer.isBuffer(raw)) 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?: Error | null) => {
|
||||
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);
|
||||
}
|
||||
200
packages/core/src/webui/auth.ts
Normal file
200
packages/core/src/webui/auth.ts
Normal file
@@ -0,0 +1,200 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const WEBUI_CONFIG_PATH = path.join(CONFIG_DIR, 'webui.json');
|
||||
|
||||
const SCRYPT_KEYLEN = 64;
|
||||
const SCRYPT_N = 16384; // cost
|
||||
const SCRYPT_R = 8;
|
||||
const SCRYPT_P = 1;
|
||||
|
||||
/**
|
||||
* Fixed credentials used when SNOWLUMA_DEV_MODE=1 is set. The state is kept
|
||||
* entirely in memory and never written to `config/webui.json`, so toggling
|
||||
* dev mode on/off never disturbs the real persisted password.
|
||||
*/
|
||||
const DEV_PASSWORD = 'snowluma-dev';
|
||||
|
||||
export function isDevAuthMode(): boolean {
|
||||
return process.env.SNOWLUMA_DEV_MODE === '1';
|
||||
}
|
||||
|
||||
export interface WebuiAuthState {
|
||||
passwordHash: string; // hex
|
||||
passwordSalt: string; // hex
|
||||
mustChangePassword: boolean;
|
||||
generatedAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface PasswordRule {
|
||||
id: string;
|
||||
label: string;
|
||||
test: (pwd: string) => boolean;
|
||||
}
|
||||
|
||||
export const PASSWORD_RULES: PasswordRule[] = [
|
||||
{ id: 'length', label: '长度不少于 10 位', test: (p) => p.length >= 10 },
|
||||
{ id: 'lower', label: '包含小写字母', test: (p) => /[a-z]/.test(p) },
|
||||
{ id: 'upper', label: '包含大写字母', test: (p) => /[A-Z]/.test(p) },
|
||||
{ id: 'special', label: '包含特殊符号 (!@#$%…)', test: (p) => /[^A-Za-z0-9\s]/.test(p) },
|
||||
{ id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 },
|
||||
];
|
||||
|
||||
export function evaluatePasswordRules(password: string): { id: string; label: string; ok: boolean }[] {
|
||||
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) }));
|
||||
}
|
||||
|
||||
export function isStrongPassword(password: string): boolean {
|
||||
return PASSWORD_RULES.every((r) => r.test(password));
|
||||
}
|
||||
|
||||
function hashPassword(password: string, salt: Buffer): Buffer {
|
||||
return scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
|
||||
}
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function isValidState(value: unknown): value is WebuiAuthState {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof v.passwordHash === 'string' &&
|
||||
typeof v.passwordSalt === 'string' &&
|
||||
typeof v.mustChangePassword === 'boolean' &&
|
||||
/^[0-9a-f]+$/i.test(v.passwordHash) &&
|
||||
/^[0-9a-f]+$/i.test(v.passwordSalt)
|
||||
);
|
||||
}
|
||||
|
||||
function generateInitialState(initialPassword: string): WebuiAuthState {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(initialPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: true,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
function atomicWrite(state: WebuiAuthState): void {
|
||||
ensureConfigDir();
|
||||
const tmp = WEBUI_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
|
||||
// chmod again in case the file already existed with looser perms
|
||||
try {
|
||||
fs.chmodSync(tmp, 0o600);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
fs.renameSync(tmp, WEBUI_CONFIG_PATH);
|
||||
}
|
||||
|
||||
export class WebuiAuth {
|
||||
private state: WebuiAuthState;
|
||||
private initialPlain: string | null;
|
||||
private readonly devMode: boolean;
|
||||
|
||||
private constructor(state: WebuiAuthState, initialPlain: string | null, devMode: boolean) {
|
||||
this.state = state;
|
||||
this.initialPlain = initialPlain;
|
||||
this.devMode = devMode;
|
||||
}
|
||||
|
||||
static load(): WebuiAuth {
|
||||
if (isDevAuthMode()) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(DEV_PASSWORD, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
return new WebuiAuth(state, null, true);
|
||||
}
|
||||
ensureConfigDir();
|
||||
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
|
||||
try {
|
||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (isValidState(parsed)) {
|
||||
return new WebuiAuth(parsed, null, false);
|
||||
}
|
||||
} catch {
|
||||
/* fallthrough — regenerate */
|
||||
}
|
||||
}
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
|
||||
/** True when SNOWLUMA_DEV_MODE was active at load time. */
|
||||
isDevMode(): boolean {
|
||||
return this.devMode;
|
||||
}
|
||||
|
||||
/** Fixed dev password (only meaningful when {@link isDevMode} is true). */
|
||||
static get devPassword(): string {
|
||||
return DEV_PASSWORD;
|
||||
}
|
||||
|
||||
/** Returns the auto-generated initial password if this is a fresh install, else null. */
|
||||
takeInitialPassword(): string | null {
|
||||
const p = this.initialPlain;
|
||||
this.initialPlain = null;
|
||||
return p;
|
||||
}
|
||||
|
||||
mustChangePassword(): boolean {
|
||||
return this.state.mustChangePassword;
|
||||
}
|
||||
|
||||
verify(password: string): boolean {
|
||||
if (typeof password !== 'string' || password.length === 0) return false;
|
||||
try {
|
||||
const salt = Buffer.from(this.state.passwordSalt, 'hex');
|
||||
const expected = Buffer.from(this.state.passwordHash, 'hex');
|
||||
const got = hashPassword(password, salt);
|
||||
if (got.length !== expected.length) return false;
|
||||
return timingSafeEqual(got, expected);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update password atomically. Throws if the new password fails strength rules.
|
||||
* After success, mustChangePassword=false and the file is rewritten on disk.
|
||||
*/
|
||||
setPassword(newPassword: string): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
|
||||
}
|
||||
if (!isStrongPassword(newPassword)) {
|
||||
throw new Error('密码不符合强度要求');
|
||||
}
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(newPassword, salt);
|
||||
const next: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: this.state.generatedAt,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
}
|
||||
42
packages/core/src/webui/port.ts
Normal file
42
packages/core/src/webui/port.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import net from 'net';
|
||||
|
||||
/**
|
||||
* Probe whether a TCP port is bindable on the given host.
|
||||
* Resolves to true when bind+listen succeed.
|
||||
*/
|
||||
function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
let settled = false;
|
||||
const finalize = (ok: boolean) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
try {
|
||||
server.close(() => resolve(ok));
|
||||
} catch {
|
||||
resolve(ok);
|
||||
}
|
||||
};
|
||||
server.once('error', () => finalize(false));
|
||||
server.once('listening', () => finalize(true));
|
||||
try {
|
||||
server.listen(port, host);
|
||||
} catch {
|
||||
finalize(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an available TCP port starting from `start`, advancing by 1 up to `maxTries` attempts.
|
||||
* Skips reserved/invalid port numbers.
|
||||
*/
|
||||
export async function findAvailablePort(start: number, maxTries = 50): Promise<number> {
|
||||
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
if (port > 65535) break;
|
||||
if (await isPortAvailable(port)) return port;
|
||||
port += 1;
|
||||
}
|
||||
throw new Error(`No available TCP port found near ${start}`);
|
||||
}
|
||||
@@ -8,29 +8,48 @@ import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
||||
import type { OneBotConfig } from '../onebot/types';
|
||||
import type { HookManager } from '../hook/hook-manager';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import os from 'os';
|
||||
import { WebuiAuth, evaluatePasswordRules, isStrongPassword } from './auth';
|
||||
import { findAvailablePort } from './port';
|
||||
|
||||
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>();
|
||||
interface SessionInfo {
|
||||
expiresAt: number;
|
||||
mustChangePassword: boolean;
|
||||
}
|
||||
|
||||
// Login attempt tracker: ip -> { count, resetAt }
|
||||
const sessionTokens = new Map<string, SessionInfo>();
|
||||
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
|
||||
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000;
|
||||
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
// Endpoints that an auth-required-but-must-change-password session can still hit.
|
||||
const MUST_CHANGE_ALLOWLIST = new Set([
|
||||
'/api/status',
|
||||
'/api/auth/state',
|
||||
'/api/auth/check-strength',
|
||||
'/api/auth/change-password',
|
||||
'/api/logout',
|
||||
]);
|
||||
|
||||
// uin = QQ number; 5–12 digits. Used to construct config file paths,
|
||||
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
|
||||
const UIN_REGEX = /^\d{5,12}$/;
|
||||
|
||||
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
|
||||
|
||||
function purgeExpiredTokens() {
|
||||
const now = Date.now();
|
||||
for (const [token, expiry] of sessionTokens) {
|
||||
if (now > expiry) sessionTokens.delete(token);
|
||||
for (const [token, info] of sessionTokens) {
|
||||
if (now > info.expiresAt) sessionTokens.delete(token);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,90 +61,161 @@ async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentTy
|
||||
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
|
||||
headers: {
|
||||
'User-Agent': 'SnowLuma WebUI',
|
||||
'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
|
||||
Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`avatar upstream responded with ${response.status}`);
|
||||
}
|
||||
|
||||
if (!response.ok) throw new Error(`avatar upstream responded with ${response.status}`);
|
||||
const contentType = response.headers.get('content-type') || 'image/jpeg';
|
||||
const body = new Uint8Array(await response.arrayBuffer());
|
||||
return { body, contentType };
|
||||
}
|
||||
|
||||
export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hookManager?: HookManager) {
|
||||
export async function initWebUI(
|
||||
desiredPort: number = 5099,
|
||||
oneBotManager: OneBotManager,
|
||||
hookManager?: HookManager,
|
||||
): Promise<{ port: number }> {
|
||||
const auth = WebuiAuth.load();
|
||||
const initialPassword = auth.takeInitialPassword();
|
||||
if (auth.isDevMode()) {
|
||||
log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword);
|
||||
log.warn('dev mode skips config/webui.json and password rotation');
|
||||
} else if (initialPassword) {
|
||||
log.info('initial credentials: user=admin password=%s', initialPassword);
|
||||
log.info('password change required after first login');
|
||||
} else if (auth.mustChangePassword()) {
|
||||
log.warn('password change is still required');
|
||||
}
|
||||
|
||||
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
|
||||
// ─── Auth middleware ─────────────────────────────────────────────────────
|
||||
app.use('/api/*', async (c, next) => {
|
||||
if (c.req.path === '/api/login') {
|
||||
return next();
|
||||
}
|
||||
const reqPath = c.req.path;
|
||||
if (reqPath === '/api/login') return next();
|
||||
|
||||
const authHeader = c.req.header('Authorization');
|
||||
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
|
||||
const queryToken = c.req.query('token') ?? '';
|
||||
const token = bearerToken || queryToken;
|
||||
if (!token) {
|
||||
return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
|
||||
}
|
||||
if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
|
||||
|
||||
purgeExpiredTokens();
|
||||
const expiry = sessionTokens.get(token);
|
||||
if (!expiry || Date.now() > expiry) {
|
||||
const info = sessionTokens.get(token);
|
||||
if (!info || Date.now() > info.expiresAt) {
|
||||
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
|
||||
}
|
||||
|
||||
if (info.mustChangePassword && !MUST_CHANGE_ALLOWLIST.has(reqPath)) {
|
||||
return c.json({ status: 'failed', message: '请先修改密码', mustChangePassword: true }, 403);
|
||||
}
|
||||
|
||||
c.set('sessionToken' as never, token);
|
||||
await next();
|
||||
});
|
||||
|
||||
// Login Endpoint with rate limiting
|
||||
// ─── Login ───────────────────────────────────────────────────────────────
|
||||
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);
|
||||
}
|
||||
|
||||
let body: { password?: unknown };
|
||||
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 });
|
||||
}
|
||||
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const password = typeof body.password === 'string' ? body.password : '';
|
||||
if (!auth.verify(password)) {
|
||||
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);
|
||||
}
|
||||
|
||||
loginAttempts.delete(ip);
|
||||
purgeExpiredTokens();
|
||||
const token = randomBytes(32).toString('hex');
|
||||
const mustChange = auth.mustChangePassword();
|
||||
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
|
||||
return c.json({ success: true, token, mustChangePassword: mustChange });
|
||||
});
|
||||
|
||||
app.post('/api/logout', (c) => {
|
||||
const token = c.get('sessionToken' as never) as string | undefined;
|
||||
if (token) sessionTokens.delete(token);
|
||||
return c.json({ success: true });
|
||||
});
|
||||
|
||||
app.get('/api/auth/state', (c) => {
|
||||
const token = c.get('sessionToken' as never) as string | undefined;
|
||||
const info = token ? sessionTokens.get(token) : undefined;
|
||||
return c.json({
|
||||
mustChangePassword: info?.mustChangePassword ?? auth.mustChangePassword(),
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/auth/check-strength', async (c) => {
|
||||
let body: { password?: unknown };
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ rules: evaluatePasswordRules(''), valid: false });
|
||||
}
|
||||
const pwd = typeof body.password === 'string' ? body.password : '';
|
||||
return c.json({ rules: evaluatePasswordRules(pwd), valid: isStrongPassword(pwd) });
|
||||
});
|
||||
|
||||
app.post('/api/auth/change-password', async (c) => {
|
||||
let body: { oldPassword?: unknown; newPassword?: unknown };
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const oldPassword = typeof body.oldPassword === 'string' ? body.oldPassword : '';
|
||||
const newPassword = typeof body.newPassword === 'string' ? body.newPassword : '';
|
||||
if (!auth.verify(oldPassword)) {
|
||||
return c.json({ success: false, message: '当前密码不正确' }, 401);
|
||||
}
|
||||
if (!isStrongPassword(newPassword)) {
|
||||
return c.json(
|
||||
{ success: false, message: '新密码不符合强度要求', rules: evaluatePasswordRules(newPassword) },
|
||||
400,
|
||||
);
|
||||
}
|
||||
if (oldPassword === newPassword) {
|
||||
return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400);
|
||||
}
|
||||
try {
|
||||
auth.setPassword(newPassword);
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 400);
|
||||
}
|
||||
// Invalidate all other sessions; current keeps but loses must-change flag.
|
||||
const currentToken = c.get('sessionToken' as never) as string | undefined;
|
||||
for (const [tok, info] of sessionTokens) {
|
||||
if (tok === currentToken) {
|
||||
info.mustChangePassword = false;
|
||||
sessionTokens.set(tok, info);
|
||||
} else {
|
||||
sessionTokens.delete(tok);
|
||||
}
|
||||
}
|
||||
log.info('password updated');
|
||||
return c.json({ success: true });
|
||||
});
|
||||
|
||||
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
|
||||
app.get('/avatar/:uin', async (c) => {
|
||||
const uin = c.req.param('uin');
|
||||
if (!/^\d{5,12}$/.test(uin)) {
|
||||
return c.text('invalid uin', 400);
|
||||
}
|
||||
if (!UIN_REGEX.test(uin)) return c.text('invalid uin', 400);
|
||||
|
||||
const now = Date.now();
|
||||
let cached = avatarCache.get(uin);
|
||||
@@ -139,7 +229,6 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
if (!cached) return c.text('avatar unavailable', 502);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(cached.body, {
|
||||
headers: {
|
||||
'Content-Type': cached.contentType,
|
||||
@@ -148,17 +237,76 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
});
|
||||
});
|
||||
|
||||
// API Routes
|
||||
app.get('/api/status', (c) => {
|
||||
return c.json({ status: 'running' });
|
||||
// ─── Read-only API ───────────────────────────────────────────────────────
|
||||
app.get('/api/status', (c) => c.json({ status: 'running' }));
|
||||
|
||||
// Host system info
|
||||
let lastCpuTimes: { idle: number; total: number }[] | null = null;
|
||||
function sampleCpuLoad(): number[] {
|
||||
const cpus = os.cpus();
|
||||
const current = cpus.map((cpu) => {
|
||||
const t = cpu.times;
|
||||
const total = t.user + t.nice + t.sys + t.idle + t.irq;
|
||||
return { idle: t.idle, total };
|
||||
});
|
||||
if (!lastCpuTimes || lastCpuTimes.length !== current.length) {
|
||||
lastCpuTimes = current;
|
||||
return current.map(() => 0);
|
||||
}
|
||||
const usage = current.map((cur, i) => {
|
||||
const prev = lastCpuTimes![i];
|
||||
const totalDiff = cur.total - prev.total;
|
||||
const idleDiff = cur.idle - prev.idle;
|
||||
if (totalDiff <= 0) return 0;
|
||||
return Math.max(0, Math.min(100, ((totalDiff - idleDiff) / totalDiff) * 100));
|
||||
});
|
||||
lastCpuTimes = current;
|
||||
return usage;
|
||||
}
|
||||
|
||||
app.get('/api/system', (c) => {
|
||||
const cpus = os.cpus();
|
||||
const usage = sampleCpuLoad();
|
||||
const totalMem = os.totalmem();
|
||||
const freeMem = os.freemem();
|
||||
const usedMem = totalMem - freeMem;
|
||||
const runtimeMemory = process.memoryUsage();
|
||||
return c.json({
|
||||
hostname: os.hostname(),
|
||||
platform: os.platform(),
|
||||
arch: os.arch(),
|
||||
release: os.release(),
|
||||
uptime: os.uptime(),
|
||||
processUptime: process.uptime(),
|
||||
nodeVersion: process.version,
|
||||
cpu: {
|
||||
model: cpus[0]?.model ?? 'unknown',
|
||||
cores: cpus.length,
|
||||
speedMHz: cpus[0]?.speed ?? 0,
|
||||
loadAvg: os.loadavg(),
|
||||
perCore: usage,
|
||||
average: usage.length ? usage.reduce((s, v) => s + v, 0) / usage.length : 0,
|
||||
},
|
||||
memory: {
|
||||
total: totalMem,
|
||||
free: freeMem,
|
||||
used: usedMem,
|
||||
usagePercent: totalMem ? (usedMem / totalMem) * 100 : 0,
|
||||
},
|
||||
runtime: {
|
||||
pid: process.pid,
|
||||
rss: runtimeMemory.rss,
|
||||
heapTotal: runtimeMemory.heapTotal,
|
||||
heapUsed: runtimeMemory.heapUsed,
|
||||
external: runtimeMemory.external,
|
||||
arrayBuffers: runtimeMemory.arrayBuffers,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/qq-list', (c) => {
|
||||
const instances = oneBotManager.getInstances();
|
||||
const list = instances.map(inst => ({
|
||||
uin: inst.uin,
|
||||
nickname: inst.qqInfo.nickname
|
||||
}));
|
||||
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.qqInfo.nickname }));
|
||||
return c.json({ list });
|
||||
});
|
||||
|
||||
@@ -185,16 +333,16 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
Connection: 'keep-alive',
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -211,7 +359,7 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
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) {
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
@@ -225,7 +373,7 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
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) {
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
@@ -236,16 +384,35 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/processes/:pid/refresh', 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 || pid > 4_194_304) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
const processInfo = await hookManager.refreshProcess(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');
|
||||
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
|
||||
const config = loadOneBotConfig(uin);
|
||||
return c.json({ config });
|
||||
return c.json({
|
||||
...config,
|
||||
config,
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/config/:uin', async (c) => {
|
||||
try {
|
||||
const uin = c.req.param('uin');
|
||||
const body = await c.req.json() as OneBotConfig;
|
||||
if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400);
|
||||
const body = (await c.req.json()) as OneBotConfig;
|
||||
saveOneBotConfig(uin, body);
|
||||
const reloaded = oneBotManager.reloadConfig(uin);
|
||||
log.info('Updated OneBot config for UIN: %s%s', uin, reloaded ? ' and reloaded' : '');
|
||||
@@ -259,14 +426,38 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
|
||||
}
|
||||
});
|
||||
|
||||
// Serve static files generated by the React frontend
|
||||
const staticRoot = path.join(__dirname, 'client');
|
||||
// ─── Static frontend ─────────────────────────────────────────────────────
|
||||
// Build path is relative to the bundled / dev __dirname. SPA fallback to
|
||||
// index.html so client-side routes (if any) keep working.
|
||||
const staticRoot = path.resolve(__dirname, 'client');
|
||||
app.use('/*', serveStatic({ root: staticRoot }));
|
||||
|
||||
serve({
|
||||
fetch: app.fetch,
|
||||
port
|
||||
}, (info) => {
|
||||
log.info(`WebUI server is listening on http://localhost:${info.port}`);
|
||||
const indexHtmlPath = path.join(staticRoot, 'index.html');
|
||||
app.get('*', (c) => {
|
||||
// SPA fallback: only for navigations that didn't hit a static asset.
|
||||
if (c.req.path.startsWith('/api/') || c.req.path.startsWith('/avatar/')) {
|
||||
return c.text('not found', 404);
|
||||
}
|
||||
if (existsSync(indexHtmlPath)) {
|
||||
const html = readFileSync(indexHtmlPath, 'utf8');
|
||||
return c.html(html);
|
||||
}
|
||||
return c.text(
|
||||
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
|
||||
404,
|
||||
);
|
||||
});
|
||||
|
||||
const finalPort = await findAvailablePort(desiredPort);
|
||||
if (finalPort !== desiredPort) {
|
||||
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
serve({ fetch: app.fetch, port: finalPort }, (info) => {
|
||||
log.info(`listening http://localhost:${info.port}`);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
return { port: finalPort };
|
||||
}
|
||||
|
||||
135
packages/core/tests/bridge-event-bus.test.ts
Normal file
135
packages/core/tests/bridge-event-bus.test.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { BridgeEventBus } from '../src/bridge/event-bus';
|
||||
import type { FriendMessage, GroupMessage } from '../src/bridge/events';
|
||||
|
||||
function makeFriendMessage(): FriendMessage {
|
||||
return {
|
||||
kind: 'friend_message',
|
||||
time: 1700000000,
|
||||
selfUin: 10001,
|
||||
senderUin: 22222,
|
||||
senderNick: 'peer',
|
||||
msgSeq: 1,
|
||||
msgId: 1,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupMessage(): GroupMessage {
|
||||
return {
|
||||
kind: 'group_message',
|
||||
time: 1700000000,
|
||||
selfUin: 10001,
|
||||
groupId: 99999,
|
||||
senderUin: 22222,
|
||||
senderNick: 'peer',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
msgSeq: 2,
|
||||
msgId: 2,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
describe('BridgeEventBus', () => {
|
||||
it('routes events only to subscribers of the matching kind', async () => {
|
||||
const bus = new BridgeEventBus();
|
||||
const friend = vi.fn();
|
||||
const group = vi.fn();
|
||||
bus.on('friend_message', friend);
|
||||
bus.on('group_message', group);
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
await bus.emit(makeGroupMessage());
|
||||
|
||||
expect(friend).toHaveBeenCalledTimes(1);
|
||||
expect(group).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('runs every subscriber in parallel for one kind', async () => {
|
||||
const bus = new BridgeEventBus();
|
||||
const order: string[] = [];
|
||||
bus.on('friend_message', async () => {
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
order.push('slow');
|
||||
});
|
||||
bus.on('friend_message', () => {
|
||||
order.push('fast');
|
||||
});
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
// The synchronous handler must finish before the async one — proves we
|
||||
// don't serialize handlers across the kind.
|
||||
expect(order).toEqual(['fast', 'slow']);
|
||||
});
|
||||
|
||||
it('isolates handler errors and reports them via onError', async () => {
|
||||
const seen: Array<{ kind: string; err: unknown }> = [];
|
||||
const bus = new BridgeEventBus({ onError: (kind, err) => seen.push({ kind, err }) });
|
||||
const ok = vi.fn();
|
||||
bus.on('friend_message', () => {
|
||||
throw new Error('boom');
|
||||
});
|
||||
bus.on('friend_message', ok);
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
|
||||
expect(ok).toHaveBeenCalledTimes(1);
|
||||
expect(seen).toHaveLength(1);
|
||||
expect(seen[0].kind).toBe('friend_message');
|
||||
expect((seen[0].err as Error).message).toBe('boom');
|
||||
});
|
||||
|
||||
it('supports unsubscribe via the returned disposer', async () => {
|
||||
const bus = new BridgeEventBus();
|
||||
const handler = vi.fn();
|
||||
const off = bus.on('friend_message', handler);
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
|
||||
off();
|
||||
await bus.emit(makeFriendMessage());
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('supports onAny and isolates its errors separately', async () => {
|
||||
const seen: Array<{ kind: string; err: unknown }> = [];
|
||||
const bus = new BridgeEventBus({ onError: (kind, err) => seen.push({ kind, err }) });
|
||||
const tap = vi.fn();
|
||||
bus.onAny(tap);
|
||||
bus.onAny(() => { throw new Error('any-fail'); });
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
await bus.emit(makeGroupMessage());
|
||||
|
||||
expect(tap).toHaveBeenCalledTimes(2);
|
||||
expect(seen).toHaveLength(2);
|
||||
expect(seen.every((s) => s.kind === '*')).toBe(true);
|
||||
});
|
||||
|
||||
it('reports has() based on per-kind + onAny subscriptions', () => {
|
||||
const bus = new BridgeEventBus();
|
||||
expect(bus.has('friend_message')).toBe(false);
|
||||
|
||||
const off = bus.on('friend_message', () => {});
|
||||
expect(bus.has('friend_message')).toBe(true);
|
||||
off();
|
||||
expect(bus.has('friend_message')).toBe(false);
|
||||
|
||||
bus.onAny(() => {});
|
||||
expect(bus.has('friend_message')).toBe(true);
|
||||
});
|
||||
|
||||
it('clear() drops every subscriber', async () => {
|
||||
const bus = new BridgeEventBus();
|
||||
const handler = vi.fn();
|
||||
bus.on('friend_message', handler);
|
||||
bus.onAny(handler);
|
||||
|
||||
bus.clear();
|
||||
await bus.emit(makeFriendMessage());
|
||||
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,175 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { loadOneBotConfig, makeDefaultOneBotConfig } from '../src/onebot/config';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { loadOneBotConfig, makeDefaultOneBotConfig, saveOneBotConfig } from '../src/onebot/config';
|
||||
|
||||
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
||||
|
||||
describe('makeDefaultOneBotConfig', () => {
|
||||
it('returns default config structure', () => {
|
||||
it('returns default unified networks 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.networks.httpServers).toHaveLength(1);
|
||||
expect(config.networks.httpServers[0].name).toBe('http-default');
|
||||
expect(config.networks.httpServers[0].host).toBe('0.0.0.0');
|
||||
expect(config.networks.httpServers[0].port).toBe(3000);
|
||||
expect(config.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||
expect(config.networks.httpServers[0].messageFormat).toBe('array');
|
||||
expect(config.networks.httpServers[0].reportSelfMessage).toBe(false);
|
||||
expect(config.networks.httpClients).toEqual([]);
|
||||
expect(config.networks.wsServers).toHaveLength(1);
|
||||
expect(config.networks.wsServers[0].port).toBe(3001);
|
||||
expect(config.networks.wsServers[0].role).toBe('Universal');
|
||||
expect(config.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||
expect(config.networks.wsServers[0].messageFormat).toBe('array');
|
||||
expect(config.networks.wsServers[0].reportSelfMessage).toBe(false);
|
||||
expect(config.networks.wsClients).toEqual([]);
|
||||
expect(config.musicSignUrl).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadOneBotConfig', () => {
|
||||
let tempDir: string;
|
||||
let prevCwd: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-config-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(tempDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(prevCwd);
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('creates and persists default config when none exists', () => {
|
||||
const uin = '10001';
|
||||
const config = loadOneBotConfig(uin);
|
||||
expect(config.networks.httpServers).toHaveLength(1);
|
||||
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'));
|
||||
expect(onDisk.networks).toBeDefined();
|
||||
expect(Array.isArray(onDisk.networks.httpServers)).toBe(true);
|
||||
expect(onDisk.networks.httpServers[0].name).toBe('http-default');
|
||||
expect(onDisk.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||
expect(onDisk.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||
// Legacy keys must not appear in the persisted file.
|
||||
expect(onDisk.httpServers).toBeUndefined();
|
||||
expect(onDisk.wsServers).toBeUndefined();
|
||||
});
|
||||
|
||||
it('migrates legacy per-type arrays into networks groups', () => {
|
||||
const uin = '10002';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const legacy = {
|
||||
httpServers: [{ host: '0.0.0.0', port: 3100, path: '/', accessToken: 'tok' }],
|
||||
httpPostEndpoints: [{ name: 'main-bot', url: 'http://127.0.0.1:5700' }],
|
||||
wsServers: [{ host: '0.0.0.0', port: 3101 }],
|
||||
wsClients: [{ url: 'ws://127.0.0.1:8080' }],
|
||||
musicSignUrl: 'https://example.com/sign',
|
||||
messageFormat: 'string',
|
||||
reportSelfMessage: true,
|
||||
};
|
||||
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify(legacy), 'utf8');
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
expect(config.networks.httpServers).toHaveLength(1);
|
||||
expect(config.networks.httpServers[0].port).toBe(3100);
|
||||
expect(config.networks.httpServers[0].accessToken).toBe('tok');
|
||||
expect(config.networks.httpServers[0].messageFormat).toBe('string');
|
||||
expect(config.networks.httpServers[0].reportSelfMessage).toBe(true);
|
||||
|
||||
expect(config.networks.httpClients).toHaveLength(1);
|
||||
expect(config.networks.httpClients[0].name).toBe('main-bot');
|
||||
expect(config.networks.httpClients[0].url).toBe('http://127.0.0.1:5700');
|
||||
expect(config.networks.httpClients[0].messageFormat).toBe('string');
|
||||
expect(config.networks.httpClients[0].reportSelfMessage).toBe(true);
|
||||
|
||||
expect(config.networks.wsServers).toHaveLength(1);
|
||||
expect(config.networks.wsServers[0].port).toBe(3101);
|
||||
expect(config.networks.wsServers[0].messageFormat).toBe('string');
|
||||
expect(config.networks.wsServers[0].reportSelfMessage).toBe(true);
|
||||
|
||||
expect(config.networks.wsClients).toHaveLength(1);
|
||||
expect(config.networks.wsClients[0].url).toBe('ws://127.0.0.1:8080');
|
||||
expect(config.networks.wsClients[0].messageFormat).toBe('string');
|
||||
expect(config.networks.wsClients[0].reportSelfMessage).toBe(true);
|
||||
|
||||
expect(config.musicSignUrl).toBe('https://example.com/sign');
|
||||
|
||||
// File should now be in unified format on disk.
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join(dir, `onebot_${uin}.json`), 'utf8'));
|
||||
expect(onDisk.networks).toBeDefined();
|
||||
expect(onDisk.httpServers).toBeUndefined();
|
||||
expect(onDisk.httpPostEndpoints).toBeUndefined();
|
||||
expect(onDisk.messageFormat).toBeUndefined();
|
||||
expect(onDisk.reportSelfMessage).toBeUndefined();
|
||||
expect(onDisk.networks.httpServers[0].messageFormat).toBe('string');
|
||||
expect(onDisk.networks.httpServers[0].reportSelfMessage).toBe(true);
|
||||
});
|
||||
|
||||
it('round-trips per-adapter overrides through save/load', () => {
|
||||
const uin = '10003';
|
||||
const config = makeDefaultOneBotConfig();
|
||||
config.networks.httpClients.push({
|
||||
name: 'self-mirror',
|
||||
url: 'http://127.0.0.1:9000',
|
||||
messageFormat: 'string',
|
||||
reportSelfMessage: true,
|
||||
});
|
||||
saveOneBotConfig(uin, config);
|
||||
|
||||
const reloaded = loadOneBotConfig(uin);
|
||||
expect(reloaded.networks.httpClients).toHaveLength(1);
|
||||
expect(reloaded.networks.httpClients[0].name).toBe('self-mirror');
|
||||
expect(reloaded.networks.httpClients[0].messageFormat).toBe('string');
|
||||
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
|
||||
});
|
||||
|
||||
it('migrates legacy lowercase WsRole values into canonical uppercase form', () => {
|
||||
const uin = '10005';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
|
||||
networks: {
|
||||
httpServers: [],
|
||||
httpClients: [],
|
||||
wsServers: [
|
||||
{ name: 'ws-legacy', host: '0.0.0.0', port: 3201, path: '/', role: 'universal', messageFormat: 'array', reportSelfMessage: false },
|
||||
],
|
||||
wsClients: [
|
||||
{ name: 'wsc-legacy', url: 'ws://127.0.0.1:8080', role: 'event', messageFormat: 'array', reportSelfMessage: false },
|
||||
],
|
||||
},
|
||||
}), 'utf8');
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
expect(config.networks.wsServers).toHaveLength(1);
|
||||
expect(config.networks.wsServers[0].role).toBe('Universal');
|
||||
expect(config.networks.wsClients).toHaveLength(1);
|
||||
expect(config.networks.wsClients[0].role).toBe('Event');
|
||||
});
|
||||
|
||||
it('auto-generates names for legacy entries that lack one', () => {
|
||||
const uin = '10004';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
|
||||
httpServers: [
|
||||
{ port: 3000 },
|
||||
{ port: 3001 },
|
||||
],
|
||||
}), 'utf8');
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
const names = config.networks.httpServers.map((n) => n.name);
|
||||
expect(names).toHaveLength(2);
|
||||
expect(new Set(names).size).toBe(2); // unique
|
||||
expect(names.every((n) => n.length > 0)).toBe(true);
|
||||
expect(config.networks.httpServers.every((n) => n.messageFormat === 'array')).toBe(true);
|
||||
expect(config.networks.httpServers.every((n) => n.reportSelfMessage === false)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
244
packages/core/tests/event-converter.test.ts
Normal file
244
packages/core/tests/event-converter.test.ts
Normal file
@@ -0,0 +1,244 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { EventConverter } from '../src/onebot/event-converter';
|
||||
import {
|
||||
buildDispatchPayload,
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
shapeEventForAdapter,
|
||||
} from '../src/onebot/event-filter';
|
||||
import type { FriendMessage, GroupMessage, TempMessage } from '../src/bridge/events';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const SELF_ID = 10001;
|
||||
const PEER_UIN = 22222;
|
||||
|
||||
function makeFriendMessage(senderUin: number): FriendMessage {
|
||||
return {
|
||||
kind: 'friend_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin,
|
||||
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
|
||||
msgSeq: 1,
|
||||
msgId: 1,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupMessage(senderUin: number): GroupMessage {
|
||||
return {
|
||||
kind: 'group_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
groupId: 99999,
|
||||
senderUin,
|
||||
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
msgSeq: 1,
|
||||
msgId: 1,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeTempMessage(senderUin: number): TempMessage {
|
||||
return {
|
||||
kind: 'temp_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin,
|
||||
groupId: 99999,
|
||||
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
|
||||
msgSeq: 1,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
describe('EventConverter post_type tagging', () => {
|
||||
it('tags self friend_message as message_sent', async () => {
|
||||
const conv = new EventConverter();
|
||||
const result = await conv.convert(SELF_UIN, makeFriendMessage(SELF_ID));
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.post_type).toBe('message_sent');
|
||||
expect(result!.message_type).toBe('private');
|
||||
expect(result!.user_id).toBe(SELF_ID);
|
||||
expect(result!.self_id).toBe(SELF_ID);
|
||||
});
|
||||
|
||||
it('tags self group_message as message_sent', async () => {
|
||||
const conv = new EventConverter();
|
||||
const result = await conv.convert(SELF_UIN, makeGroupMessage(SELF_ID));
|
||||
expect(result!.post_type).toBe('message_sent');
|
||||
expect(result!.message_type).toBe('group');
|
||||
});
|
||||
|
||||
it('tags self temp_message as message_sent', async () => {
|
||||
const conv = new EventConverter();
|
||||
const result = await conv.convert(SELF_UIN, makeTempMessage(SELF_ID));
|
||||
expect(result!.post_type).toBe('message_sent');
|
||||
expect(result!.sub_type).toBe('group');
|
||||
});
|
||||
|
||||
it('keeps incoming peer messages tagged as plain message', async () => {
|
||||
const conv = new EventConverter();
|
||||
const friend = await conv.convert(SELF_UIN, makeFriendMessage(PEER_UIN));
|
||||
expect(friend!.post_type).toBe('message');
|
||||
expect(friend!.user_id).toBe(PEER_UIN);
|
||||
|
||||
const group = await conv.convert(SELF_UIN, makeGroupMessage(PEER_UIN));
|
||||
expect(group!.post_type).toBe('message');
|
||||
});
|
||||
});
|
||||
|
||||
describe('shapeEventForAdapter', () => {
|
||||
const baseEvent = {
|
||||
time: 1,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'message_sent' as const,
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: 7,
|
||||
user_id: SELF_ID,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||
raw_message: 'hello',
|
||||
font: 0,
|
||||
sender: { user_id: SELF_ID, nickname: 'me', sex: 'unknown', age: 0 },
|
||||
};
|
||||
|
||||
it('drops self message_sent when adapter has reportSelfMessage=false', () => {
|
||||
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
|
||||
expect(shapeEventForAdapter(baseEvent, opts)).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps self message_sent when adapter has reportSelfMessage=true', () => {
|
||||
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
|
||||
const shaped = shapeEventForAdapter(baseEvent, opts);
|
||||
expect(shaped).not.toBeNull();
|
||||
expect(shaped!.post_type).toBe('message_sent');
|
||||
});
|
||||
|
||||
it('rewrites message to CQ string when format=string', () => {
|
||||
const opts = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: true });
|
||||
const shaped = shapeEventForAdapter(baseEvent, opts);
|
||||
expect(shaped).not.toBeNull();
|
||||
expect(shaped!.message).toBe('hello');
|
||||
// raw_message is preserved untouched.
|
||||
expect(shaped!.raw_message).toBe('hello');
|
||||
});
|
||||
|
||||
it('keeps message as array when format=array (default)', () => {
|
||||
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
|
||||
const shaped = shapeEventForAdapter(baseEvent, opts);
|
||||
expect(Array.isArray(shaped!.message)).toBe(true);
|
||||
});
|
||||
|
||||
it('defaults partially-deserialized adapters to array format and no self report', () => {
|
||||
const opts = resolveReportOptions({});
|
||||
expect(opts.messageFormat).toBe('array');
|
||||
expect(opts.reportSelfMessage).toBe(false);
|
||||
});
|
||||
|
||||
it('passes through non-message events unchanged', () => {
|
||||
const noticeEvent = {
|
||||
time: 1,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_increase',
|
||||
group_id: 1,
|
||||
user_id: 2,
|
||||
};
|
||||
const opts = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: false });
|
||||
expect(shapeEventForAdapter(noticeEvent, opts)).toBe(noticeEvent);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildDispatchPayload + pickDispatchJson', () => {
|
||||
const messageEvent = {
|
||||
time: 1,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'message',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: 7,
|
||||
user_id: PEER_UIN,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||
raw_message: 'hello',
|
||||
font: 0,
|
||||
sender: { user_id: PEER_UIN, nickname: 'peer', sex: 'unknown', age: 0 },
|
||||
};
|
||||
|
||||
const selfMessageEvent = { ...messageEvent, post_type: 'message_sent', user_id: SELF_ID };
|
||||
|
||||
const noticeEvent = {
|
||||
time: 1,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_increase',
|
||||
group_id: 1,
|
||||
user_id: 2,
|
||||
};
|
||||
|
||||
it('builds at most two distinct JSON variants for a message event', () => {
|
||||
const payload = buildDispatchPayload(messageEvent);
|
||||
expect(payload.isSelfMessage).toBe(false);
|
||||
|
||||
const arr = JSON.parse(payload.arrayJson);
|
||||
const str = JSON.parse(payload.stringJson);
|
||||
expect(Array.isArray(arr.message)).toBe(true);
|
||||
expect(typeof str.message).toBe('string');
|
||||
expect(str.message).toBe('hello');
|
||||
expect(str.raw_message).toBe('hello');
|
||||
// every other field should be byte-identical
|
||||
const { message: _arrMsg, ...arrRest } = arr;
|
||||
const { message: _strMsg, ...strRest } = str;
|
||||
expect(arrRest).toEqual(strRest);
|
||||
});
|
||||
|
||||
it('flags self messages and uses identical JSON for non-message events', () => {
|
||||
const selfPayload = buildDispatchPayload(selfMessageEvent);
|
||||
expect(selfPayload.isSelfMessage).toBe(true);
|
||||
|
||||
const noticePayload = buildDispatchPayload(noticeEvent);
|
||||
expect(noticePayload.isSelfMessage).toBe(false);
|
||||
// Non-message events do not need a separate string variant.
|
||||
expect(noticePayload.arrayJson).toBe(noticePayload.stringJson);
|
||||
});
|
||||
|
||||
it('routes connections to the right pre-serialized variant in O(1)', () => {
|
||||
const payload = buildDispatchPayload(messageEvent);
|
||||
const arrayOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
|
||||
const stringOpt = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: false });
|
||||
|
||||
expect(pickDispatchJson(payload, arrayOpt)).toBe(payload.arrayJson);
|
||||
expect(pickDispatchJson(payload, stringOpt)).toBe(payload.stringJson);
|
||||
});
|
||||
|
||||
it('drops self-message dispatches for adapters that opt out', () => {
|
||||
const payload = buildDispatchPayload(selfMessageEvent);
|
||||
const offOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
|
||||
expect(pickDispatchJson(payload, offOpt)).toBeNull();
|
||||
|
||||
const onOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
|
||||
const json = pickDispatchJson(payload, onOpt);
|
||||
expect(json).not.toBeNull();
|
||||
expect(JSON.parse(json!).post_type).toBe('message_sent');
|
||||
});
|
||||
|
||||
it('serializes only twice regardless of fan-out size', () => {
|
||||
const payload = buildDispatchPayload(messageEvent);
|
||||
// Mixed fleet of adapters with different formats / self-report options.
|
||||
const adapters = Array.from({ length: 50 }, (_, i) => i % 2 === 0
|
||||
? { messageFormat: 'array' as const, reportSelfMessage: false }
|
||||
: { messageFormat: 'string' as const, reportSelfMessage: true },
|
||||
);
|
||||
const seen = new Set(
|
||||
adapters
|
||||
.map((opts) => pickDispatchJson(payload, opts))
|
||||
.filter((j): j is string => j !== null),
|
||||
);
|
||||
// No matter the fan-out, only at most the two prebuilt strings appear.
|
||||
expect(seen.size).toBeLessThanOrEqual(2);
|
||||
expect(seen.has(payload.arrayJson)).toBe(true);
|
||||
expect(seen.has(payload.stringJson)).toBe(true);
|
||||
});
|
||||
});
|
||||
193
packages/core/tests/event-pipeline.test.ts
Normal file
193
packages/core/tests/event-pipeline.test.ts
Normal file
@@ -0,0 +1,193 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { BridgeEventBus } from '../src/bridge/event-bus';
|
||||
import { EventConverter } from '../src/onebot/event-converter';
|
||||
import { registerEventPipeline } from '../src/onebot/event-pipeline';
|
||||
import type { OneBotInstanceContext } from '../src/onebot/instance-context';
|
||||
import type {
|
||||
FriendMessage,
|
||||
GroupMessage,
|
||||
GroupMemberJoin,
|
||||
TempMessage,
|
||||
QQEventVariant,
|
||||
} from '../src/bridge/events';
|
||||
import type { JsonObject, MessageMeta } from '../src/onebot/types';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const SELF_ID = 10001;
|
||||
const PEER_UIN = 22222;
|
||||
const GROUP_ID = 99999;
|
||||
|
||||
interface FakeBridge {
|
||||
events: BridgeEventBus;
|
||||
}
|
||||
|
||||
function makeFriendMessage(): FriendMessage {
|
||||
return {
|
||||
kind: 'friend_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin: PEER_UIN,
|
||||
senderNick: 'peer',
|
||||
msgSeq: 11,
|
||||
msgId: 555,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupMessage(): GroupMessage {
|
||||
return {
|
||||
kind: 'group_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
groupId: GROUP_ID,
|
||||
senderUin: PEER_UIN,
|
||||
senderNick: 'peer',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
msgSeq: 22,
|
||||
msgId: 777,
|
||||
elements: [{ type: 'text', text: 'group' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeTempMessage(): TempMessage {
|
||||
return {
|
||||
kind: 'temp_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin: PEER_UIN,
|
||||
groupId: GROUP_ID,
|
||||
senderNick: 'peer',
|
||||
msgSeq: 33,
|
||||
elements: [{ type: 'text', text: 'temp' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeMemberJoin(): GroupMemberJoin {
|
||||
return {
|
||||
kind: 'group_member_join',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
groupId: GROUP_ID,
|
||||
userUin: PEER_UIN,
|
||||
operatorUin: PEER_UIN,
|
||||
};
|
||||
}
|
||||
|
||||
function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
|
||||
ctx: OneBotInstanceContext;
|
||||
bus: BridgeEventBus;
|
||||
metaCalls: Array<{ id: number; meta: MessageMeta }>;
|
||||
dispatchCalls: JsonObject[];
|
||||
} {
|
||||
const bus = new BridgeEventBus();
|
||||
const fakeBridge: FakeBridge = { events: bus };
|
||||
const eventConverter = new EventConverter();
|
||||
const metaCalls: Array<{ id: number; meta: MessageMeta }> = [];
|
||||
const dispatchCalls: JsonObject[] = [];
|
||||
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: SELF_UIN,
|
||||
selfId: SELF_ID,
|
||||
qqInfo: {} as never,
|
||||
bridge: fakeBridge as never,
|
||||
messageStore: {} as never,
|
||||
mediaStore: {} as never,
|
||||
eventConverter,
|
||||
config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never,
|
||||
cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); },
|
||||
dispatchEvent: (event) => { dispatchCalls.push(event); },
|
||||
...extra,
|
||||
};
|
||||
|
||||
return { ctx, bus, metaCalls, dispatchCalls };
|
||||
}
|
||||
|
||||
describe('registerEventPipeline', () => {
|
||||
it('caches meta and dispatches a converted event for friend_message', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
|
||||
expect(metaCalls).toHaveLength(1);
|
||||
expect(metaCalls[0].meta.isGroup).toBe(false);
|
||||
expect(metaCalls[0].meta.targetId).toBe(PEER_UIN);
|
||||
expect(metaCalls[0].meta.sequence).toBe(11);
|
||||
expect(metaCalls[0].meta.random).toBe(555);
|
||||
|
||||
expect(dispatchCalls).toHaveLength(1);
|
||||
expect(dispatchCalls[0].post_type).toBe('message');
|
||||
expect(dispatchCalls[0].message_type).toBe('private');
|
||||
});
|
||||
|
||||
it('caches meta and dispatches for group_message', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeGroupMessage());
|
||||
|
||||
expect(metaCalls[0].meta.isGroup).toBe(true);
|
||||
expect(metaCalls[0].meta.targetId).toBe(GROUP_ID);
|
||||
expect(dispatchCalls[0].message_type).toBe('group');
|
||||
});
|
||||
|
||||
it('caches meta with random=0 for temp_message and dispatches as private+sub_type=group', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeTempMessage());
|
||||
|
||||
expect(metaCalls[0].meta.isGroup).toBe(false);
|
||||
expect(metaCalls[0].meta.random).toBe(0);
|
||||
expect(dispatchCalls[0].message_type).toBe('private');
|
||||
expect(dispatchCalls[0].sub_type).toBe('group');
|
||||
});
|
||||
|
||||
it('dispatches notice events without seeding meta', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeMemberJoin());
|
||||
|
||||
expect(metaCalls).toHaveLength(0);
|
||||
expect(dispatchCalls).toHaveLength(1);
|
||||
expect(dispatchCalls[0].notice_type).toBe('group_increase');
|
||||
});
|
||||
|
||||
it('returns a disposer that fully unsubscribes', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
const dispose = registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
expect(dispatchCalls).toHaveLength(1);
|
||||
|
||||
dispose();
|
||||
await bus.emit(makeFriendMessage());
|
||||
// No new calls after dispose.
|
||||
expect(dispatchCalls).toHaveLength(1);
|
||||
expect(metaCalls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('dispatches a separate event for every kind in parallel', async () => {
|
||||
const { ctx, bus, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
const events: QQEventVariant[] = [makeFriendMessage(), makeGroupMessage(), makeMemberJoin(), makeTempMessage()];
|
||||
await Promise.all(events.map((e) => bus.emit(e)));
|
||||
|
||||
expect(dispatchCalls).toHaveLength(events.length);
|
||||
});
|
||||
|
||||
it('skips dispatch for kinds without a converter mapping (no crash)', async () => {
|
||||
// Stub `convert` on a real EventConverter instance so the type stays
|
||||
// honest -- no structural casts.
|
||||
const stubbed = new EventConverter();
|
||||
stubbed.convert = vi.fn().mockResolvedValue(null);
|
||||
const { ctx, bus, dispatchCalls } = makeContext({ eventConverter: stubbed });
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
expect(dispatchCalls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
306
packages/core/tests/media-store.test.ts
Normal file
306
packages/core/tests/media-store.test.ts
Normal file
@@ -0,0 +1,306 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { MediaStore } from '../src/onebot/media-store';
|
||||
import { EventConverter } from '../src/onebot/event-converter';
|
||||
import type { GroupMessage, FriendMessage, MessageElement } from '../src/bridge/events';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const SELF_ID = 10001;
|
||||
const PEER_UIN = 22222;
|
||||
const GROUP_ID = 99999;
|
||||
|
||||
function imageElement(overrides: Partial<MessageElement> = {}): MessageElement {
|
||||
return {
|
||||
type: 'image',
|
||||
fileId: 'abc.png',
|
||||
fileSize: 4242,
|
||||
imageUrl: 'https://example.com/abc.png',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function recordElement(overrides: Partial<MessageElement> = {}): MessageElement {
|
||||
return {
|
||||
type: 'record',
|
||||
fileId: 'uuid-base64-fake',
|
||||
fileName: 'silk_test.amr',
|
||||
fileSize: 1024,
|
||||
duration: 3,
|
||||
fileHash: 'deadbeef',
|
||||
mediaNode: { fileUuid: 'uuid-base64-fake', storeId: 1 },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupMessage(elements: MessageElement[]): GroupMessage {
|
||||
return {
|
||||
kind: 'group_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
groupId: GROUP_ID,
|
||||
senderUin: PEER_UIN,
|
||||
senderNick: 'peer',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
msgSeq: 1,
|
||||
msgId: 1,
|
||||
elements,
|
||||
};
|
||||
}
|
||||
|
||||
function makeFriendMessage(elements: MessageElement[]): FriendMessage {
|
||||
return {
|
||||
kind: 'friend_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin: PEER_UIN,
|
||||
senderNick: 'peer',
|
||||
msgSeq: 1,
|
||||
msgId: 1,
|
||||
elements,
|
||||
};
|
||||
}
|
||||
|
||||
function tempDbPath(label: string): string {
|
||||
return path.join('data', 'test', `media-${label}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
}
|
||||
|
||||
describe('MediaStore basic semantics', () => {
|
||||
const dbs: string[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
dbs.length = 0;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const dbPath of dbs) {
|
||||
for (const ext of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function open(label: string, max?: number): MediaStore {
|
||||
const dbPath = tempDbPath(label);
|
||||
dbs.push(dbPath);
|
||||
return max !== undefined ? new MediaStore(dbPath, max) : new MediaStore(dbPath);
|
||||
}
|
||||
|
||||
it('indexes images by file, fileName, and url', () => {
|
||||
const store = open('img-keys');
|
||||
store.rememberImage({
|
||||
file: 'abc.png',
|
||||
url: 'https://example.com/abc.png',
|
||||
fileSize: 4242,
|
||||
fileName: 'abc.png',
|
||||
subType: 0,
|
||||
summary: '',
|
||||
imageUrl: 'https://example.com/abc.png',
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
|
||||
expect(store.findImage('abc.png')?.fileSize).toBe(4242);
|
||||
expect(store.findImage('https://example.com/abc.png')?.url).toBe('https://example.com/abc.png');
|
||||
expect(store.findImage('missing.png')).toBeNull();
|
||||
expect(store.findImage('')).toBeNull();
|
||||
store.close();
|
||||
});
|
||||
|
||||
it('indexes records by file, fileName, fileId, and url', () => {
|
||||
const store = open('rec-keys');
|
||||
store.rememberRecord({
|
||||
file: 'silk_test.amr',
|
||||
fileId: 'uuid-base64-fake',
|
||||
url: 'https://example.com/voice.amr',
|
||||
fileSize: 1024,
|
||||
fileName: 'silk_test.amr',
|
||||
duration: 3,
|
||||
fileHash: 'deadbeef',
|
||||
mediaNode: { fileUuid: 'uuid-base64-fake' },
|
||||
isGroup: false,
|
||||
sessionId: PEER_UIN,
|
||||
});
|
||||
|
||||
expect(store.findRecord('silk_test.amr')?.duration).toBe(3);
|
||||
expect(store.findRecord('uuid-base64-fake')?.fileId).toBe('uuid-base64-fake');
|
||||
expect(store.findRecord('https://example.com/voice.amr')?.url).toBe('https://example.com/voice.amr');
|
||||
expect(store.findRecord('nope')).toBeNull();
|
||||
store.close();
|
||||
});
|
||||
|
||||
it('updates URLs in place across all alias keys', () => {
|
||||
const store = open('url-update');
|
||||
store.rememberRecord({
|
||||
file: 'silk_test.amr',
|
||||
fileId: 'uuid-base64-fake',
|
||||
url: '',
|
||||
fileSize: 1024,
|
||||
fileName: 'silk_test.amr',
|
||||
duration: 3,
|
||||
fileHash: '',
|
||||
mediaNode: { fileUuid: 'uuid-base64-fake' },
|
||||
isGroup: false,
|
||||
sessionId: PEER_UIN,
|
||||
});
|
||||
store.updateRecordUrl('silk_test.amr', 'https://refreshed.example.com/voice.amr');
|
||||
|
||||
expect(store.findRecord('silk_test.amr')?.url).toBe('https://refreshed.example.com/voice.amr');
|
||||
expect(store.findRecord('uuid-base64-fake')?.url).toBe('https://refreshed.example.com/voice.amr');
|
||||
store.close();
|
||||
});
|
||||
|
||||
it('survives close+reopen against the same db path', () => {
|
||||
const dbPath = tempDbPath('persist');
|
||||
dbs.push(dbPath);
|
||||
|
||||
{
|
||||
const store = new MediaStore(dbPath);
|
||||
store.rememberImage({
|
||||
file: 'abc.png',
|
||||
url: 'https://example.com/abc.png',
|
||||
fileSize: 99,
|
||||
fileName: 'abc.png',
|
||||
subType: 0,
|
||||
summary: '',
|
||||
imageUrl: 'https://example.com/abc.png',
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
store.close();
|
||||
}
|
||||
|
||||
{
|
||||
const store = new MediaStore(dbPath);
|
||||
const found = store.findImage('abc.png');
|
||||
expect(found).not.toBeNull();
|
||||
expect(found!.fileSize).toBe(99);
|
||||
// Alias index must also persist.
|
||||
expect(store.findImage('https://example.com/abc.png')?.fileSize).toBe(99);
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('evicts old entries beyond the configured cap', () => {
|
||||
// EVICT_EVERY_N_REMEMBERS = 64 inside the store; we exercise the eviction
|
||||
// path by writing well past the cap so it triggers at least once.
|
||||
const cap = 80;
|
||||
const store = open('evict', cap);
|
||||
for (let i = 0; i < 200; i++) {
|
||||
store.rememberImage({
|
||||
file: `file-${i}.png`,
|
||||
url: `https://example.com/${i}.png`,
|
||||
fileSize: i,
|
||||
fileName: `file-${i}.png`,
|
||||
subType: 0,
|
||||
summary: '',
|
||||
imageUrl: '',
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
}
|
||||
const { images } = store.size();
|
||||
expect(images).toBeLessThanOrEqual(cap);
|
||||
// Most recent entries should still be present.
|
||||
expect(store.findImage('file-199.png')?.fileSize).toBe(199);
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('EventConverter media segment sink → MediaStore wiring', () => {
|
||||
const dbs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dbPath of dbs) {
|
||||
for (const ext of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
dbs.length = 0;
|
||||
});
|
||||
|
||||
it('emits sink invocations for image segments with the right context', async () => {
|
||||
const conv = new EventConverter();
|
||||
const sinkCalls: Array<{ type: string; isGroup: boolean; sessionId: number; file: string }> = [];
|
||||
conv.setMediaSegmentSink((type, _element, data, isGroup, sessionId) => {
|
||||
sinkCalls.push({ type, isGroup, sessionId, file: String(data.file ?? '') });
|
||||
});
|
||||
|
||||
await conv.convert(SELF_UIN, makeGroupMessage([imageElement()]));
|
||||
await conv.convert(SELF_UIN, makeFriendMessage([recordElement()]));
|
||||
|
||||
expect(sinkCalls).toEqual([
|
||||
{ type: 'image', isGroup: true, sessionId: GROUP_ID, file: 'abc.png' },
|
||||
{ type: 'record', isGroup: false, sessionId: PEER_UIN, file: 'silk_test.amr' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('lets the sink populate a MediaStore that get_image-style lookups can use', async () => {
|
||||
const dbPath = tempDbPath('sink');
|
||||
dbs.push(dbPath);
|
||||
|
||||
const store = new MediaStore(dbPath);
|
||||
const conv = new EventConverter();
|
||||
conv.setImageUrlResolver((element) => element.imageUrl ?? '');
|
||||
conv.setMediaUrlResolver(async (element) => element.url ?? '');
|
||||
conv.setMediaSegmentSink((type, element, data, isGroup, sessionId) => {
|
||||
const url = typeof data.url === 'string' ? data.url : '';
|
||||
const file = typeof data.file === 'string' ? data.file : '';
|
||||
if (type === 'image') {
|
||||
store.rememberImage({
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileId ?? '',
|
||||
subType: element.subType ?? 0,
|
||||
summary: element.summary ?? '',
|
||||
imageUrl: element.imageUrl ?? '',
|
||||
isGroup,
|
||||
sessionId,
|
||||
});
|
||||
} else {
|
||||
store.rememberRecord({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileName ?? '',
|
||||
duration: element.duration ?? 0,
|
||||
fileHash: element.fileHash ?? '',
|
||||
mediaNode: element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await conv.convert(SELF_UIN, makeGroupMessage([imageElement()]));
|
||||
await conv.convert(SELF_UIN, makeFriendMessage([recordElement()]));
|
||||
|
||||
const img = store.findImage('abc.png');
|
||||
expect(img).not.toBeNull();
|
||||
expect(img!.url).toBe('https://example.com/abc.png');
|
||||
expect(img!.fileSize).toBe(4242);
|
||||
expect(img!.isGroup).toBe(true);
|
||||
expect(img!.sessionId).toBe(GROUP_ID);
|
||||
|
||||
const rec = store.findRecord('silk_test.amr');
|
||||
expect(rec).not.toBeNull();
|
||||
expect(rec!.fileId).toBe('uuid-base64-fake');
|
||||
expect(rec!.duration).toBe(3);
|
||||
expect(rec!.isGroup).toBe(false);
|
||||
expect(rec!.sessionId).toBe(PEER_UIN);
|
||||
// Alias lookup by fileUuid still works.
|
||||
expect(store.findRecord('uuid-base64-fake')?.fileName).toBe('silk_test.amr');
|
||||
store.close();
|
||||
});
|
||||
|
||||
it('does not invoke the sink when no media segments are present', async () => {
|
||||
const conv = new EventConverter();
|
||||
let calls = 0;
|
||||
conv.setMediaSegmentSink(() => { calls++; });
|
||||
await conv.convert(SELF_UIN, makeGroupMessage([{ type: 'text', text: 'hello' }]));
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseMessage } from '../src/onebot/message-parser';
|
||||
import { buildSendElems } from '../src/bridge/builders/element-builder';
|
||||
import { MentionExtraSendSchema } from '../src/bridge/proto/action';
|
||||
import { protoDecode } from '../src/protobuf/decode';
|
||||
|
||||
describe('parseMessage', () => {
|
||||
describe('plain text', () => {
|
||||
@@ -84,6 +87,30 @@ describe('parseMessage', () => {
|
||||
expect(result[0].url).toBe('https://example.com/img.png');
|
||||
});
|
||||
|
||||
it('parses record segment from data.file', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'record', data: { file: 'file:///tmp/voice.amr' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'record', url: 'file:///tmp/voice.amr' }]);
|
||||
});
|
||||
|
||||
it('parses record segment from data.path (NapCat parity)', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'record', data: { path: 'C:\\voices\\hi.silk' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'record', url: 'C:\\voices\\hi.silk' }]);
|
||||
});
|
||||
|
||||
it('drops record segment with empty source', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'record', data: {} }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('parses at segment', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'at', data: { qq: 12345 } }] as any,
|
||||
@@ -94,6 +121,71 @@ describe('parseMessage', () => {
|
||||
expect(result[0].targetUin).toBe(12345);
|
||||
});
|
||||
|
||||
it('uses at segment name for display text and preserves uid', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'at', data: { qq: '123456', name: 'User', uid: 'u_test_uid' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
type: 'at',
|
||||
targetUin: 123456,
|
||||
uid: 'u_test_uid',
|
||||
text: '@User ',
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves missing at uid through parse options', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'at', data: { qq: '123456', name: 'User' } }] as any,
|
||||
false,
|
||||
{ resolveMentionUid: async (targetUin) => targetUin === 123456 ? 'u_resolved_uid' : null },
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
type: 'at',
|
||||
targetUin: 123456,
|
||||
uid: 'u_resolved_uid',
|
||||
text: '@User ',
|
||||
});
|
||||
});
|
||||
|
||||
it('encodes mention extra with resolved uid for QQ notification', async () => {
|
||||
const elements = await parseMessage(
|
||||
[{ type: 'at', data: { qq: '123456', name: 'User' } }] as any,
|
||||
false,
|
||||
{ resolveMentionUid: () => 'u_resolved_uid' },
|
||||
);
|
||||
const protoElems = await buildSendElems(elements);
|
||||
const reserve = protoElems[0].text?.pbReserve;
|
||||
expect(reserve).toBeInstanceOf(Uint8Array);
|
||||
const extra = protoDecode(reserve as Uint8Array, MentionExtraSendSchema);
|
||||
expect(extra).toMatchObject({
|
||||
type: 2,
|
||||
uin: 123456,
|
||||
uid: 'u_resolved_uid',
|
||||
});
|
||||
expect(protoElems[0].text?.str).toBe('@User ');
|
||||
});
|
||||
|
||||
it('skips record send when SendContext is absent (graceful no-bridge path)', async () => {
|
||||
// Without a SendContext, buildSendElems can't run highway upload —
|
||||
// it should warn and drop the element instead of throwing into the
|
||||
// ffmpegAddon (which would explode for callers that don't actually
|
||||
// need to send).
|
||||
const elements = await parseMessage(
|
||||
[
|
||||
{ type: 'text', data: { text: 'hi ' } },
|
||||
{ type: 'record', data: { file: '/tmp/x.silk' } },
|
||||
] as any,
|
||||
false,
|
||||
);
|
||||
const protoElems = await buildSendElems(elements);
|
||||
// Only the leading text should make it through.
|
||||
expect(protoElems).toHaveLength(1);
|
||||
expect(protoElems[0].text?.str).toBe('hi ');
|
||||
});
|
||||
|
||||
it('parses multiple segments', async () => {
|
||||
const result = await parseMessage(
|
||||
[
|
||||
|
||||
190
packages/core/tests/message-store.test.ts
Normal file
190
packages/core/tests/message-store.test.ts
Normal file
@@ -0,0 +1,190 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { MessageStore } from '../src/onebot/message-store';
|
||||
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
describe('MessageStore', () => {
|
||||
const testDbPath = path.join('data', 'test', 'messages-test.db');
|
||||
let store: MessageStore;
|
||||
|
||||
beforeEach(() => {
|
||||
// Clean up any existing test database
|
||||
try {
|
||||
fs.unlinkSync(testDbPath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
store = new MessageStore(testDbPath);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
store.close();
|
||||
// Clean up test database
|
||||
try {
|
||||
fs.unlinkSync(testDbPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
});
|
||||
|
||||
describe('resolveReplySequence', () => {
|
||||
it('resolves group message reply sequence', () => {
|
||||
const groupId = 123456;
|
||||
const sequence = 100;
|
||||
const messageId = hashMessageIdInt32(sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||
|
||||
// Store a group message
|
||||
store.storeMeta(messageId, {
|
||||
isGroup: true,
|
||||
targetId: groupId,
|
||||
sequence,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// Resolve the reply sequence
|
||||
const resolved = store.resolveReplySequence(true, groupId, messageId);
|
||||
expect(resolved).toBe(sequence);
|
||||
});
|
||||
|
||||
it('resolves private message reply sequence without session_id matching', () => {
|
||||
// Simulate receiving a private message from user 111111
|
||||
const senderUin = 111111;
|
||||
const sequence = 200;
|
||||
const messageId = hashMessageIdInt32(sequence, senderUin, PRIVATE_MESSAGE_EVENT);
|
||||
|
||||
// Store the received message (session_id is sender's UIN)
|
||||
store.storeMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: senderUin,
|
||||
sequence,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// When replying to this message, we send to the sender (who becomes the recipient)
|
||||
// The key fix: resolveReplySequence should work even when sessionId doesn't match
|
||||
const resolved = store.resolveReplySequence(false, senderUin, messageId);
|
||||
expect(resolved).toBe(sequence);
|
||||
|
||||
// More importantly: it should also work when we pass a different sessionId
|
||||
// (which was the bug - we were passing recipient UIN instead of sender UIN)
|
||||
const differentUin = 999999;
|
||||
const resolvedWithDifferentSession = store.resolveReplySequence(false, differentUin, messageId);
|
||||
expect(resolvedWithDifferentSession).toBe(sequence);
|
||||
});
|
||||
|
||||
it('returns null for non-existent message', () => {
|
||||
const resolved = store.resolveReplySequence(true, 123456, 999999);
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for invalid messageId', () => {
|
||||
const resolved = store.resolveReplySequence(true, 123456, 0);
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for invalid sessionId', () => {
|
||||
const messageId = hashMessageIdInt32(100, 123456, GROUP_MESSAGE_EVENT);
|
||||
const resolved = store.resolveReplySequence(true, 0, messageId);
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it('distinguishes between group and private messages', () => {
|
||||
const sessionId = 123456;
|
||||
const sequence = 300;
|
||||
|
||||
// Store a group message
|
||||
const groupMessageId = hashMessageIdInt32(sequence, sessionId, GROUP_MESSAGE_EVENT);
|
||||
store.storeMeta(groupMessageId, {
|
||||
isGroup: true,
|
||||
targetId: sessionId,
|
||||
sequence,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// Store a private message with same sequence but different hash
|
||||
const privateMessageId = hashMessageIdInt32(sequence, sessionId, PRIVATE_MESSAGE_EVENT);
|
||||
store.storeMeta(privateMessageId, {
|
||||
isGroup: false,
|
||||
targetId: sessionId,
|
||||
sequence,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// Should resolve correctly based on isGroup flag
|
||||
const groupResolved = store.resolveReplySequence(true, sessionId, groupMessageId);
|
||||
expect(groupResolved).toBe(sequence);
|
||||
|
||||
const privateResolved = store.resolveReplySequence(false, sessionId, privateMessageId);
|
||||
expect(privateResolved).toBe(sequence);
|
||||
|
||||
// Should not cross-resolve
|
||||
const wrongGroupResolve = store.resolveReplySequence(true, sessionId, privateMessageId);
|
||||
expect(wrongGroupResolve).toBeNull();
|
||||
|
||||
const wrongPrivateResolve = store.resolveReplySequence(false, sessionId, groupMessageId);
|
||||
expect(wrongPrivateResolve).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('storeEvent and findEvent', () => {
|
||||
it('stores and retrieves event data', () => {
|
||||
const messageId = 12345;
|
||||
const event = {
|
||||
post_type: 'message',
|
||||
message_type: 'group',
|
||||
message_id: messageId,
|
||||
group_id: 123456,
|
||||
message: 'test message',
|
||||
time: Date.now(),
|
||||
};
|
||||
|
||||
store.storeEvent(messageId, true, 123456, 100, GROUP_MESSAGE_EVENT, event);
|
||||
|
||||
const retrieved = store.findEvent(messageId);
|
||||
expect(retrieved).toEqual(event);
|
||||
});
|
||||
|
||||
it('returns null for non-existent event', () => {
|
||||
const retrieved = store.findEvent(999999);
|
||||
expect(retrieved).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('storeMeta and findMeta', () => {
|
||||
it('stores and retrieves message meta', () => {
|
||||
const messageId = 54321;
|
||||
const meta = {
|
||||
isGroup: true,
|
||||
targetId: 123456,
|
||||
sequence: 100,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: 1,
|
||||
random: 12345,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
store.storeMeta(messageId, meta);
|
||||
|
||||
const retrieved = store.findMeta(messageId);
|
||||
expect(retrieved).toEqual(meta);
|
||||
});
|
||||
|
||||
it('returns null for non-existent meta', () => {
|
||||
const retrieved = store.findMeta(999999);
|
||||
expect(retrieved).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
180
packages/core/tests/network-manager.test.ts
Normal file
180
packages/core/tests/network-manager.test.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, OneBotNetworkManager } from '../src/onebot/network';
|
||||
import type { NetworkAdapterContext } from '../src/onebot/network';
|
||||
import type { JsonObject, NetworkBase } from '../src/onebot/types';
|
||||
import type { DispatchPayload } from '../src/onebot/event-filter';
|
||||
|
||||
interface FakeNetworkConfig extends NetworkBase {
|
||||
// Allows tests to influence behavior via config:
|
||||
failOnEvent?: boolean;
|
||||
}
|
||||
|
||||
class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
|
||||
events: JsonObject[] = [];
|
||||
opens = 0;
|
||||
closes = 0;
|
||||
reloads = 0;
|
||||
// Last dispatch payload object identity, to assert it was reused per emit.
|
||||
lastPayloads: DispatchPayload[] = [];
|
||||
|
||||
open(): void {
|
||||
this.opens++;
|
||||
if (this.config.enabled !== false) this.isEnabled = true;
|
||||
}
|
||||
close(): void {
|
||||
this.closes++;
|
||||
this.isEnabled = false;
|
||||
}
|
||||
reload(next: FakeNetworkConfig): NetworkReloadType {
|
||||
this.reloads++;
|
||||
this.config = structuredClone(next);
|
||||
if (next.enabled === false && this.isEnabled) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (next.enabled !== false && !this.isEnabled) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
onEvent(event: JsonObject, payload: DispatchPayload): void {
|
||||
this.events.push(event);
|
||||
this.lastPayloads.push(payload);
|
||||
if (this.config.failOnEvent) throw new Error('boom');
|
||||
}
|
||||
}
|
||||
|
||||
const NULL_CTX: NetworkAdapterContext = {
|
||||
uin: '10001',
|
||||
api: { handle: async () => ({ status: 'failed', retcode: 0, data: null }), processRequest: async () => '' } as never,
|
||||
buildLifecycleEvent: () => ({}),
|
||||
buildHeartbeatEvent: () => ({}),
|
||||
};
|
||||
|
||||
function makeAdapter(name: string, partial: Partial<FakeNetworkConfig> = {}): FakeAdapter {
|
||||
const config: FakeNetworkConfig = {
|
||||
name,
|
||||
enabled: true,
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
...partial,
|
||||
};
|
||||
return new FakeAdapter(name, config, NULL_CTX);
|
||||
}
|
||||
|
||||
const SAMPLE_EVENT: JsonObject = {
|
||||
time: 1,
|
||||
self_id: 10001,
|
||||
post_type: 'message',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: 1,
|
||||
user_id: 22222,
|
||||
message: [{ type: 'text', data: { text: 'hi' } }],
|
||||
raw_message: 'hi',
|
||||
font: 0,
|
||||
sender: { user_id: 22222, nickname: 'peer', sex: 'unknown', age: 0 },
|
||||
};
|
||||
|
||||
describe('OneBotNetworkManager', () => {
|
||||
it('opens and emits to every active adapter in parallel', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const a = makeAdapter('a');
|
||||
const b = makeAdapter('b');
|
||||
mgr.register(a);
|
||||
mgr.register(b);
|
||||
await mgr.openAll();
|
||||
|
||||
expect(a.opens).toBe(1);
|
||||
expect(b.opens).toBe(1);
|
||||
|
||||
await mgr.emitEvent(SAMPLE_EVENT);
|
||||
expect(a.events).toEqual([SAMPLE_EVENT]);
|
||||
expect(b.events).toEqual([SAMPLE_EVENT]);
|
||||
// Both adapters should receive the same payload reference (built once).
|
||||
expect(a.lastPayloads[0]).toBe(b.lastPayloads[0]);
|
||||
});
|
||||
|
||||
it('skips inactive adapters during emit', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const active = makeAdapter('active');
|
||||
const idle = makeAdapter('idle', { enabled: false });
|
||||
mgr.register(active);
|
||||
mgr.register(idle);
|
||||
await mgr.openAll();
|
||||
|
||||
await mgr.emitEvent(SAMPLE_EVENT);
|
||||
expect(active.events).toHaveLength(1);
|
||||
expect(idle.events).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('isolates adapter errors so one bad adapter does not block others', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const ok = makeAdapter('ok');
|
||||
const bad = makeAdapter('bad', { failOnEvent: true });
|
||||
mgr.register(ok);
|
||||
mgr.register(bad);
|
||||
await mgr.openAll();
|
||||
|
||||
await mgr.emitEvent(SAMPLE_EVENT);
|
||||
// The good adapter still saw the event.
|
||||
expect(ok.events).toHaveLength(1);
|
||||
// The bad adapter logged the throw but didn't crash the manager.
|
||||
expect(bad.events).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('replaces an existing adapter under the same name and closes the old one', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const first = makeAdapter('dup');
|
||||
mgr.register(first);
|
||||
await mgr.openAll();
|
||||
|
||||
const second = makeAdapter('dup');
|
||||
mgr.register(second);
|
||||
|
||||
expect(mgr.get('dup')).toBe(second);
|
||||
expect(first.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('closeOne shuts down a single adapter and removes it', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const a = makeAdapter('a');
|
||||
const b = makeAdapter('b');
|
||||
mgr.register(a);
|
||||
mgr.register(b);
|
||||
await mgr.openAll();
|
||||
|
||||
await mgr.closeOne('a');
|
||||
expect(mgr.has('a')).toBe(false);
|
||||
expect(a.closes).toBe(1);
|
||||
expect(b.closes).toBe(0);
|
||||
expect(mgr.hasActiveAdapters()).toBe(true);
|
||||
});
|
||||
|
||||
it('closeAll clears every adapter', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const a = makeAdapter('a');
|
||||
const b = makeAdapter('b');
|
||||
mgr.register(a);
|
||||
mgr.register(b);
|
||||
await mgr.openAll();
|
||||
|
||||
await mgr.closeAll();
|
||||
expect(mgr.list()).toHaveLength(0);
|
||||
expect(a.closes).toBe(1);
|
||||
expect(b.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('hasActiveAdapters reflects current state', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
expect(mgr.hasActiveAdapters()).toBe(false);
|
||||
const a = makeAdapter('a');
|
||||
mgr.register(a);
|
||||
expect(mgr.hasActiveAdapters()).toBe(false);
|
||||
await mgr.openAll();
|
||||
expect(mgr.hasActiveAdapters()).toBe(true);
|
||||
await mgr.closeAll();
|
||||
expect(mgr.hasActiveAdapters()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defineConfig, PluginOption, UserConfig } from 'vite';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { builtinModules } from 'module';
|
||||
import cp from 'vite-plugin-cp';
|
||||
@@ -22,19 +23,53 @@ const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`
|
||||
const runtimeSrc = toPosix(runtimeDir);
|
||||
const nativeSrc = toPosix(nativeDir);
|
||||
|
||||
// Only the runtime distribution assets land in dist/.
|
||||
// (.gitignore and other dev artifacts must NOT be shipped.)
|
||||
const runtimeDistFiles = ['launcher.bat', 'package.json'];
|
||||
|
||||
// Only ship native binaries matching the current build host's platform/arch.
|
||||
// Override via SNOWLUMA_TARGET=<platform>-<arch> for cross-target packaging.
|
||||
// Target selection: `SNOWLUMA_TARGET=<platform>-<arch>` overrides the host
|
||||
// detection, enabling cross-target packaging on CI.
|
||||
const targetTriple = process.env.SNOWLUMA_TARGET ?? `${process.platform}-${process.arch}`;
|
||||
const nativeGlobs = [
|
||||
`snowluma-${targetTriple}.dll`,
|
||||
`snowluma-${targetTriple}.node`,
|
||||
`websocket-${targetTriple}.node`,
|
||||
const [targetPlatform, targetArch] = targetTriple.split('-');
|
||||
|
||||
// Runtime scaffolding files copied into dist/. The NTQQ hook is Windows-only,
|
||||
// so its launcher/shell script differ per target.
|
||||
const runtimeDistFiles = ['package.json',
|
||||
targetPlatform === 'win32' ? 'launcher.bat' : 'launcher.sh',
|
||||
];
|
||||
|
||||
// Native binaries shipped for the selected target:
|
||||
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
|
||||
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
|
||||
const nativeFiles = [
|
||||
`websocket-${targetTriple}.node`,
|
||||
...(targetPlatform === 'win32'
|
||||
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
|
||||
: []),
|
||||
...(targetPlatform === 'linux'
|
||||
? [`snowluma-${targetTriple}.node`, `snowluma-${targetTriple}.so`]
|
||||
: []),
|
||||
];
|
||||
|
||||
// FFmpeg native addon ported from NapCat. Uses NapCat's
|
||||
// `<platform>.<arch>` naming so the prebuilt binaries can be vendored
|
||||
// as-is without renaming. Lives under `native/ffmpeg/` to keep it
|
||||
// separate from the SnowLuma flat-naming addons above.
|
||||
const ffmpegAddonFile = `ffmpegAddon.${targetPlatform}.${targetArch}.node`;
|
||||
const ffmpegSrcDir = path.resolve(nativeDir, 'ffmpeg');
|
||||
|
||||
// Fail fast if any expected native binary is missing from packages/runtime/native/.
|
||||
// vite-plugin-cp only emits a warning on missing source files; we want a hard
|
||||
// error so CI can't accidentally ship an incomplete archive.
|
||||
const missingNatives = nativeFiles.filter(
|
||||
(f) => !fs.existsSync(path.join(nativeDir, f)),
|
||||
);
|
||||
if (!fs.existsSync(path.join(ffmpegSrcDir, ffmpegAddonFile))) {
|
||||
missingNatives.push(`ffmpeg/${ffmpegAddonFile}`);
|
||||
}
|
||||
if (missingNatives.length > 0) {
|
||||
throw new Error(
|
||||
`Missing native binaries for target ${targetTriple}:\n` +
|
||||
missingNatives.map((f) => ` - ${path.join(nativeDir, f)}`).join('\n'),
|
||||
);
|
||||
}
|
||||
|
||||
const BaseConfigPlugin: PluginOption[] = [
|
||||
cp({
|
||||
targets: [
|
||||
@@ -43,11 +78,16 @@ const BaseConfigPlugin: PluginOption[] = [
|
||||
dest: distDir,
|
||||
flatten: true,
|
||||
})),
|
||||
...nativeGlobs.map((g) => ({
|
||||
src: `${nativeSrc}/${g}`,
|
||||
...nativeFiles.map((f) => ({
|
||||
src: `${nativeSrc}/${f}`,
|
||||
dest: path.join(distDir, 'native'),
|
||||
flatten: true,
|
||||
})),
|
||||
{
|
||||
src: `${toPosix(ffmpegSrcDir)}/${ffmpegAddonFile}`,
|
||||
dest: path.join(distDir, 'native', 'ffmpeg'),
|
||||
flatten: true,
|
||||
},
|
||||
]
|
||||
})
|
||||
];
|
||||
|
||||
16
packages/runtime/launcher.sh
Normal file
16
packages/runtime/launcher.sh
Normal file
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
# Prefer bundled node when present; fall back to $PATH.
|
||||
if [[ -x "./node" ]]; then
|
||||
NODE_BIN="./node"
|
||||
else
|
||||
NODE_BIN="$(command -v node || true)"
|
||||
if [[ -z "$NODE_BIN" ]]; then
|
||||
echo "error: 'node' not found on PATH and no bundled ./node; install Node.js >= 22." >&2
|
||||
exit 127
|
||||
fi
|
||||
fi
|
||||
|
||||
exec "$NODE_BIN" ./index.mjs "$@"
|
||||
BIN
packages/runtime/native/ffmpeg/ffmpegAddon.darwin.arm64.node
Normal file
BIN
packages/runtime/native/ffmpeg/ffmpegAddon.darwin.arm64.node
Normal file
Binary file not shown.
BIN
packages/runtime/native/ffmpeg/ffmpegAddon.linux.arm64.node
Normal file
BIN
packages/runtime/native/ffmpeg/ffmpegAddon.linux.arm64.node
Normal file
Binary file not shown.
BIN
packages/runtime/native/ffmpeg/ffmpegAddon.linux.x64.node
Normal file
BIN
packages/runtime/native/ffmpeg/ffmpegAddon.linux.x64.node
Normal file
Binary file not shown.
BIN
packages/runtime/native/ffmpeg/ffmpegAddon.win32.x64.node
Normal file
BIN
packages/runtime/native/ffmpeg/ffmpegAddon.win32.x64.node
Normal file
Binary file not shown.
BIN
packages/runtime/native/snowluma-linux-arm64.node
Executable file
BIN
packages/runtime/native/snowluma-linux-arm64.node
Executable file
Binary file not shown.
BIN
packages/runtime/native/snowluma-linux-arm64.so
Executable file
BIN
packages/runtime/native/snowluma-linux-arm64.so
Executable file
Binary file not shown.
BIN
packages/runtime/native/snowluma-linux-x64.node
Normal file
BIN
packages/runtime/native/snowluma-linux-x64.node
Normal file
Binary file not shown.
BIN
packages/runtime/native/snowluma-linux-x64.so
Normal file
BIN
packages/runtime/native/snowluma-linux-x64.so
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -12,6 +12,9 @@
|
||||
}
|
||||
},
|
||||
"description": "SnowLuma in-tree WebSocket implementation. Loads packages/runtime/native/websocket-<platform>-<arch>.node via process.dlopen().",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
|
||||
@@ -84,5 +84,46 @@ function loadAddon(): NativeAddon {
|
||||
return mod.exports as unknown as NativeAddon;
|
||||
}
|
||||
|
||||
const addon: NativeAddon = loadAddon();
|
||||
// Local-only escape hatch: when SNOWLUMA_DEV_NO_NATIVE=1 is set, we return a
|
||||
// stub addon that lets the process boot (so the WebUI / HTTP API can run on
|
||||
// platforms without a prebuilt binary, e.g. darwin-arm64 dev machines). Any
|
||||
// actual WebSocket parsing/serialization call will throw at use-time. This
|
||||
// branch never triggers for normal users because the env var is opt-in.
|
||||
function createStubAddon(reason: string): NativeAddon {
|
||||
const fail = (): never => {
|
||||
throw new Error(
|
||||
`[snowluma/websocket] native addon is stubbed (${reason}). ` +
|
||||
`Set SNOWLUMA_DEV_NO_NATIVE=0 (or unset) and provide the prebuilt binary to enable WebSocket I/O.`,
|
||||
);
|
||||
};
|
||||
class StubParser {
|
||||
constructor(_options: ParserOptions) {}
|
||||
push(_chunk: Buffer): ParseResult {
|
||||
return fail();
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(
|
||||
`[snowluma/websocket] WARNING: using stub addon (${reason}). WebSocket features are disabled.`,
|
||||
);
|
||||
return {
|
||||
Parser: StubParser as unknown as NativeAddon['Parser'],
|
||||
buildFrame: fail as unknown as NativeAddon['buildFrame'],
|
||||
computeAcceptKey: fail as unknown as NativeAddon['computeAcceptKey'],
|
||||
};
|
||||
}
|
||||
|
||||
function tryLoad(): NativeAddon {
|
||||
const devSkip = process.env.SNOWLUMA_DEV_NO_NATIVE === '1';
|
||||
try {
|
||||
return loadAddon();
|
||||
} catch (err) {
|
||||
if (devSkip) {
|
||||
return createStubAddon((err as Error).message);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const addon: NativeAddon = tryLoad();
|
||||
export default addon;
|
||||
|
||||
21
packages/webui/components.json
Normal file
21
packages/webui/components.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -2,9 +2,10 @@
|
||||
<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="icon" type="image/png" href="/logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#0ea5e9" />
|
||||
<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" />
|
||||
|
||||
@@ -11,14 +11,21 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@heroui/react": "^3.0.2",
|
||||
"@heroui/styles": "^3.0.2",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.7",
|
||||
"@radix-ui/react-dialog": "^1.1.7",
|
||||
"@radix-ui/react-label": "^2.1.3",
|
||||
"@radix-ui/react-scroll-area": "^1.2.4",
|
||||
"@radix-ui/react-separator": "^1.1.3",
|
||||
"@radix-ui/react-slot": "^1.1.3",
|
||||
"@radix-ui/react-tooltip": "^1.1.9",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"framer-motion": "^12.38.0",
|
||||
"lucide-react": "^1.8.0",
|
||||
"lucide-react": "^0.469.0",
|
||||
"motion": "^12.0.0",
|
||||
"react": "^19.2.5",
|
||||
"react-dom": "^19.2.5",
|
||||
"tailwind-merge": "^3.5.0"
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tw-animate-css": "^1.2.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
@@ -31,7 +38,6 @@
|
||||
"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",
|
||||
|
||||
@@ -1,469 +0,0 @@
|
||||
.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;
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
// Token layer only — component styles live in Tailwind classes inside TSX
|
||||
@use './styles/variables';
|
||||
@@ -1,231 +1,421 @@
|
||||
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 { LogsPage } from './components/pages/LogsPage';
|
||||
import type { QQInfo, OneBotConfig, HookProcessInfo } from './types';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||
import { ThemeProvider, useTheme } from '@/contexts/ThemeContext';
|
||||
import { LoginPage } from '@/components/pages/login-page';
|
||||
import { MainLayout } from '@/components/layout/main-layout';
|
||||
import { OverviewPage } from '@/components/pages/overview-page';
|
||||
import { ConfigPage } from '@/components/pages/config-page';
|
||||
import { LogsPage } from '@/components/pages/logs-page';
|
||||
import { SettingsPage } from '@/components/pages/settings-page';
|
||||
import { ChangePasswordPage, type PasswordRule } from '@/components/pages/change-password-page';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import type { Page } from '@/components/layout/sidebar';
|
||||
import type { HookProcessInfo, OneBotConfig, QQInfo, SystemInfo } 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 });
|
||||
};
|
||||
const TOKEN_KEY = 'snowluma_token';
|
||||
|
||||
function App() {
|
||||
const [status, setStatus] = useState('连接中');
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(
|
||||
import.meta.env.VITE_SKIP_AUTH === 'true' ? true : null
|
||||
function readToken() {
|
||||
return localStorage.getItem(TOKEN_KEY) || '';
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<AppInner />
|
||||
</ThemeProvider>
|
||||
);
|
||||
const [activePage, setActivePage] = useState<'总览' | '配置' | '日志'>('总览');
|
||||
}
|
||||
|
||||
function AppInner() {
|
||||
const { pollInterval } = useTheme();
|
||||
const [authChecked, setAuthChecked] = useState(false);
|
||||
const [authed, setAuthed] = useState(false);
|
||||
const [mustChange, setMustChange] = useState(false);
|
||||
const [status, setStatus] = useState('未连接');
|
||||
const [active, setActive] = useState<Page>('overview');
|
||||
|
||||
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
||||
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
|
||||
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
|
||||
|
||||
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
|
||||
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
|
||||
const [processRefreshingPid, setProcessRefreshingPid] = useState<number | null>(null);
|
||||
const [processActionStatus, setProcessActionStatus] = useState('');
|
||||
const [unloadFailedAlert, setUnloadFailedAlert] = useState<{ pid: number; error: string } | null>(null);
|
||||
// Tracks PIDs with an in-flight load/unload/refresh request so the UI can
|
||||
// collapse spam-clicks instead of firing a second concurrent request.
|
||||
const inflightProcessOps = useRef(new Set<number>());
|
||||
|
||||
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); });
|
||||
}
|
||||
const tokenRef = useRef(readToken());
|
||||
|
||||
useEffect(() => {
|
||||
if (import.meta.env.VITE_SKIP_AUTH !== 'true') checkStatus();
|
||||
// ---------- API helpers ----------
|
||||
const fetchApi = useCallback(async (url: string, options: RequestInit = {}) => {
|
||||
const headers: Record<string, string> = {
|
||||
...(options.headers as Record<string, string> | undefined),
|
||||
};
|
||||
if (tokenRef.current) headers['Authorization'] = `Bearer ${tokenRef.current}`;
|
||||
if (options.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
|
||||
const res = await fetch(url, { ...options, headers });
|
||||
if (res.status === 401) {
|
||||
tokenRef.current = '';
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setAuthed(false);
|
||||
setStatus('未授权');
|
||||
}
|
||||
return res;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated !== true) return;
|
||||
fetchQqList();
|
||||
fetchProcesses();
|
||||
const timer = window.setInterval(() => {
|
||||
fetchQqList();
|
||||
fetchProcesses();
|
||||
}, 3000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [isAuthenticated]);
|
||||
// ---------- Polling ----------
|
||||
const refreshQqList = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchApi('/api/qq-list');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setQqList(data.list || []);
|
||||
} catch (e) {
|
||||
console.error('qq-list', e);
|
||||
}
|
||||
}, [fetchApi]);
|
||||
|
||||
const handleLogin = async (password: string) => {
|
||||
const refreshProcesses = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchApi('/api/processes');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setProcessList(data.list || []);
|
||||
} catch (e) {
|
||||
console.error('processes', e);
|
||||
}
|
||||
}, [fetchApi]);
|
||||
|
||||
const refreshSystem = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchApi('/api/system');
|
||||
if (!res.ok) return;
|
||||
const data = (await res.json()) as SystemInfo;
|
||||
setSystemInfo(data);
|
||||
} catch (e) {
|
||||
console.error('system', e);
|
||||
}
|
||||
}, [fetchApi]);
|
||||
|
||||
const checkStatus = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchApi('/api/status');
|
||||
if (res.ok) {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
return true;
|
||||
}
|
||||
setStatus('未连接');
|
||||
return false;
|
||||
} catch {
|
||||
setStatus('未连接');
|
||||
return false;
|
||||
}
|
||||
}, [fetchApi]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (tokenRef.current) {
|
||||
const ok = await checkStatus();
|
||||
if (ok) {
|
||||
// Existing session may still need to change password.
|
||||
try {
|
||||
const r = await fetchApi('/api/auth/state');
|
||||
if (r.ok) {
|
||||
const d = await r.json();
|
||||
setMustChange(!!d.mustChangePassword);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
setAuthChecked(true);
|
||||
})();
|
||||
}, [checkStatus, fetchApi]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authed || mustChange) return;
|
||||
if (pollInterval <= 0) return;
|
||||
let cancelled = false;
|
||||
const tick = async () => {
|
||||
if (cancelled) return;
|
||||
await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]);
|
||||
};
|
||||
tick();
|
||||
const interval = setInterval(tick, pollInterval);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, [authed, mustChange, pollInterval, refreshQqList, refreshProcesses, refreshSystem]);
|
||||
|
||||
// Auto-select first uin when navigating to config
|
||||
useEffect(() => {
|
||||
if (active !== 'config') return;
|
||||
if (!selectedUin && qqList.length > 0) setSelectedUin(qqList[0].uin);
|
||||
}, [active, qqList, selectedUin]);
|
||||
|
||||
// Load config when selectedUin changes
|
||||
useEffect(() => {
|
||||
if (!selectedUin) {
|
||||
setConfig(null);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`);
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const loaded = data?.config ?? data;
|
||||
if (cancelled) return;
|
||||
const nets = loaded?.networks ?? {};
|
||||
const legacyFormat = loaded?.messageFormat === 'string' ? 'string' : 'array';
|
||||
const legacyReport = !!loaded?.reportSelfMessage;
|
||||
const normalizeNetwork = <T extends Record<string, unknown>>(item: T) => ({
|
||||
...item,
|
||||
messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
|
||||
reportSelfMessage:
|
||||
typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
|
||||
});
|
||||
setConfig({
|
||||
networks: {
|
||||
httpServers: Array.isArray(nets.httpServers) ? nets.httpServers.map(normalizeNetwork) : [],
|
||||
httpClients: Array.isArray(nets.httpClients) ? nets.httpClients.map(normalizeNetwork) : [],
|
||||
wsServers: Array.isArray(nets.wsServers) ? nets.wsServers.map(normalizeNetwork) : [],
|
||||
wsClients: Array.isArray(nets.wsClients) ? nets.wsClients.map(normalizeNetwork) : [],
|
||||
},
|
||||
musicSignUrl: loaded?.musicSignUrl,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('load-config', e);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedUin, fetchApi]);
|
||||
|
||||
// ---------- Actions ----------
|
||||
const handleLogin = useCallback(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 };
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { success: false, error: data.message || data.error || '令牌错误' };
|
||||
}
|
||||
return { success: false, error: '认证失败,请检查控制台日志' };
|
||||
} catch {
|
||||
return { success: false, error: '内部错误,请检查后端运行状态' };
|
||||
const data = await res.json();
|
||||
const token = data.token as string;
|
||||
localStorage.setItem(TOKEN_KEY, token);
|
||||
tokenRef.current = token;
|
||||
setMustChange(!!data.mustChangePassword);
|
||||
const ok = await checkStatus();
|
||||
return ok ? { success: true } : { success: false, error: '校验失败' };
|
||||
} catch (e) {
|
||||
return { success: false, error: (e as Error).message || '网络错误' };
|
||||
}
|
||||
};
|
||||
}, [checkStatus]);
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('snowluma_token');
|
||||
setIsAuthenticated(false);
|
||||
setStatus('需要认证');
|
||||
const handleLogout = useCallback(async () => {
|
||||
try { await fetchApi('/api/logout', { method: 'POST' }); } catch { /* ignore */ }
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
tokenRef.current = '';
|
||||
setAuthed(false);
|
||||
setMustChange(false);
|
||||
setStatus('未连接');
|
||||
setQqList([]);
|
||||
setProcessList([]);
|
||||
setSystemInfo(null);
|
||||
setSelectedUin(null);
|
||||
setConfig(null);
|
||||
};
|
||||
}, [fetchApi]);
|
||||
|
||||
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) => {
|
||||
const handleLoadProcess = useCallback(async (pid: number) => {
|
||||
if (inflightProcessOps.current.has(pid)) return;
|
||||
inflightProcessOps.current.add(pid);
|
||||
setProcessLoadingPid(pid);
|
||||
setProcessActionStatus('正在手动映射加载 SnowLuma...');
|
||||
setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`);
|
||||
try {
|
||||
const res = await fetchApi(`/api/processes/${pid}/load`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const res = await fetchApi(`/api/processes/${pid}/load`, { method: 'POST' });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setProcessActionStatus(res.ok && data.success ? '已开始监听登录状态' : data.message || '加载失败');
|
||||
await fetchProcesses();
|
||||
await fetchQqList();
|
||||
} catch {
|
||||
setProcessActionStatus('网络错误,加载失败');
|
||||
if (!res.ok) throw new Error(data.message || data.error || '加载失败');
|
||||
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma,等待管道连接…`);
|
||||
await refreshProcesses();
|
||||
} catch (e) {
|
||||
setProcessActionStatus(`加载失败:${(e as Error).message}`);
|
||||
} finally {
|
||||
inflightProcessOps.current.delete(pid);
|
||||
setProcessLoadingPid(null);
|
||||
setTimeout(() => setProcessActionStatus(''), 3000);
|
||||
setTimeout(() => setProcessActionStatus(''), 4000);
|
||||
}
|
||||
};
|
||||
}, [fetchApi, refreshProcesses]);
|
||||
|
||||
const unloadProcess = async (pid: number) => {
|
||||
const handleUnloadProcess = useCallback(async (pid: number) => {
|
||||
if (inflightProcessOps.current.has(pid)) return;
|
||||
inflightProcessOps.current.add(pid);
|
||||
setProcessUnloadingPid(pid);
|
||||
setProcessActionStatus('正在卸载 SnowLuma...');
|
||||
setProcessActionStatus(`正在从进程 ${pid} 卸载…`);
|
||||
try {
|
||||
const res = await fetchApi(`/api/processes/${pid}/unload`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setProcessActionStatus(res.ok && data.success ? '已卸载 SnowLuma' : data.message || '卸载失败');
|
||||
await fetchProcesses();
|
||||
await fetchQqList();
|
||||
} catch {
|
||||
setProcessActionStatus('网络错误,卸载失败');
|
||||
if (!res.ok) throw new Error(data.message || data.error || '卸载失败');
|
||||
|
||||
// Check if unload actually failed (pipe still exists)
|
||||
if (data.process?.status === 'connecting' && data.process?.error) {
|
||||
setUnloadFailedAlert({ pid, error: data.process.error });
|
||||
setProcessActionStatus(`进程 ${pid} 卸载失败`);
|
||||
} else {
|
||||
setProcessActionStatus(`已从进程 ${pid} 卸载`);
|
||||
}
|
||||
|
||||
await refreshProcesses();
|
||||
} catch (e) {
|
||||
setProcessActionStatus(`卸载失败:${(e as Error).message}`);
|
||||
} finally {
|
||||
inflightProcessOps.current.delete(pid);
|
||||
setProcessUnloadingPid(null);
|
||||
setTimeout(() => setProcessActionStatus(''), 3000);
|
||||
setTimeout(() => setProcessActionStatus(''), 4000);
|
||||
}
|
||||
};
|
||||
}, [fetchApi, refreshProcesses]);
|
||||
|
||||
const loadConfig = async (uin: string) => {
|
||||
setSelectedUin(uin);
|
||||
setSaveStatus('');
|
||||
setConfig(null);
|
||||
const handleRefreshProcess = useCallback(async (pid: number) => {
|
||||
if (inflightProcessOps.current.has(pid)) return;
|
||||
inflightProcessOps.current.add(pid);
|
||||
setProcessRefreshingPid(pid);
|
||||
setProcessActionStatus(`正在刷新进程 ${pid} 的管道状态…`);
|
||||
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 res = await fetchApi(`/api/processes/${pid}/refresh`, { method: 'POST' });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.message || data.error || '刷新失败');
|
||||
setProcessActionStatus(`已刷新进程 ${pid} 的管道状态`);
|
||||
await refreshProcesses();
|
||||
} catch (e) {
|
||||
setProcessActionStatus(`刷新失败:${(e as Error).message}`);
|
||||
} finally {
|
||||
inflightProcessOps.current.delete(pid);
|
||||
setProcessRefreshingPid(null);
|
||||
setTimeout(() => setProcessActionStatus(''), 4000);
|
||||
}
|
||||
}, [fetchApi, refreshProcesses]);
|
||||
|
||||
const saveConfig = async () => {
|
||||
const handleSaveConfig = useCallback(async () => {
|
||||
if (!selectedUin || !config) return;
|
||||
setSaveStatus('保存中...');
|
||||
try {
|
||||
const res = await fetchApi(`/api/config/${selectedUin}`, {
|
||||
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config),
|
||||
});
|
||||
setSaveStatus(res.ok ? '保存成功' : '保存出错');
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || '保存失败');
|
||||
setSaveStatus('保存成功');
|
||||
} catch (e) {
|
||||
setSaveStatus(`保存失败:${(e as Error).message}`);
|
||||
} finally {
|
||||
setTimeout(() => setSaveStatus(''), 3000);
|
||||
} catch {
|
||||
setSaveStatus('网络错误');
|
||||
}
|
||||
};
|
||||
}, [selectedUin, config, fetchApi]);
|
||||
|
||||
// Loading state
|
||||
if (isAuthenticated === null) {
|
||||
// ---------- Render ----------
|
||||
if (!authChecked) {
|
||||
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 className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
|
||||
初始化中…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Login
|
||||
if (isAuthenticated === false) {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<LoginPage onLogin={handleLogin} />
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
const checkStrength = async (password: string) => {
|
||||
const res = await fetchApi('/api/auth/check-strength', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
|
||||
return { rules: data.rules ?? [], valid: !!data.valid };
|
||||
};
|
||||
const submitPwd = async (oldPassword: string, newPassword: string) => {
|
||||
const res = await fetchApi('/api/auth/change-password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ oldPassword, newPassword }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
|
||||
return { success: !!data.success, message: data.message };
|
||||
};
|
||||
|
||||
// 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}
|
||||
/>
|
||||
)}
|
||||
{activePage === '日志' && (
|
||||
<LogsPage fetchApi={fetchApi} />
|
||||
)}
|
||||
</MainLayout>
|
||||
</ThemeProvider>
|
||||
<TooltipProvider delayDuration={150}>
|
||||
{!authed ? (
|
||||
<LoginPage onLogin={handleLogin} />
|
||||
) : mustChange ? (
|
||||
<ChangePasswordPage
|
||||
forced
|
||||
checkStrength={checkStrength}
|
||||
submit={submitPwd}
|
||||
onSuccess={() => setMustChange(false)}
|
||||
/>
|
||||
) : (
|
||||
<MainLayout active={active} onNavigate={setActive} status={status} onLogout={handleLogout}>
|
||||
{active === 'overview' && (
|
||||
<OverviewPage
|
||||
qqList={qqList}
|
||||
status={status}
|
||||
processList={processList}
|
||||
processLoadingPid={processLoadingPid}
|
||||
processUnloadingPid={processUnloadingPid}
|
||||
processRefreshingPid={processRefreshingPid}
|
||||
processActionStatus={processActionStatus}
|
||||
systemInfo={systemInfo}
|
||||
onRefreshProcesses={refreshProcesses}
|
||||
onRefreshSystem={refreshSystem}
|
||||
onLoadProcess={handleLoadProcess}
|
||||
onUnloadProcess={handleUnloadProcess}
|
||||
onRefreshProcess={handleRefreshProcess}
|
||||
/>
|
||||
)}
|
||||
{active === 'config' && (
|
||||
<ConfigPage
|
||||
qqList={qqList}
|
||||
selectedUin={selectedUin}
|
||||
config={config}
|
||||
saveStatus={saveStatus}
|
||||
onSelectAccount={setSelectedUin}
|
||||
onSave={handleSaveConfig}
|
||||
onConfigChange={setConfig}
|
||||
/>
|
||||
)}
|
||||
{active === 'logs' && <LogsPage fetchApi={fetchApi} />}
|
||||
{active === 'settings' && <SettingsPage fetchApi={fetchApi} onLogout={handleLogout} />}
|
||||
</MainLayout>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!unloadFailedAlert}
|
||||
onOpenChange={(open) => !open && setUnloadFailedAlert(null)}
|
||||
title="卸载失败"
|
||||
description={
|
||||
unloadFailedAlert ? (
|
||||
<>
|
||||
<p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p>
|
||||
<p className="mt-2 text-sm">{unloadFailedAlert.error}</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。
|
||||
</p>
|
||||
</>
|
||||
) : null
|
||||
}
|
||||
confirmText="知道了"
|
||||
onConfirm={() => setUnloadFailedAlert(null)}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
69
packages/webui/src/components/confirm-dialog.tsx
Normal file
69
packages/webui/src/components/confirm-dialog.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { buttonVariants } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ConfirmDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
description?: ReactNode;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
destructive?: boolean;
|
||||
onConfirm: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function ConfirmDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
confirmText = '确认',
|
||||
cancelText = '取消',
|
||||
destructive = false,
|
||||
onConfirm,
|
||||
}: ConfirmDialogProps) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const handleConfirm = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await onConfirm();
|
||||
onOpenChange(false);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||
{description && <AlertDialogDescription>{description}</AlertDialogDescription>}
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={busy}>{cancelText}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
void handleConfirm();
|
||||
}}
|
||||
className={cn(destructive && buttonVariants({ variant: 'destructive' }))}
|
||||
disabled={busy}
|
||||
>
|
||||
{busy ? '处理中…' : confirmText}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -1,251 +0,0 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { Activity, LayoutDashboard, Settings, Sparkles, Terminal } 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 },
|
||||
'日志': { title: '日志', subtitle: '查看后端运行日志与实时事件流', badge: 'SSE 实时流', icon: Terminal },
|
||||
};
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
import { LayoutDashboard, Settings, LogOut, Sun, Moon, Monitor, Terminal } 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 },
|
||||
{ page: '日志', label: '日志', icon: Terminal },
|
||||
];
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
88
packages/webui/src/components/layout/main-layout.tsx
Normal file
88
packages/webui/src/components/layout/main-layout.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { Sheet, SheetContent } from '@/components/ui/sheet';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Sidebar, type Page } from '@/components/layout/sidebar';
|
||||
import { TopBar } from '@/components/layout/top-bar';
|
||||
import { useMediaQuery } from '@/hooks/use-media-query';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface MainLayoutProps {
|
||||
active: Page;
|
||||
onNavigate: (page: Page) => void;
|
||||
status: string;
|
||||
onLogout: () => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function MainLayout({ active, onNavigate, status, onLogout, children }: MainLayoutProps) {
|
||||
const isMobile = !useMediaQuery('(min-width: 768px)');
|
||||
const [collapsed, setCollapsed] = useState(() => {
|
||||
return localStorage.getItem('snowluma_sidebar_collapsed') === '1';
|
||||
});
|
||||
const [mobileOpen, setMobileOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem('snowluma_sidebar_collapsed', collapsed ? '1' : '0');
|
||||
}, [collapsed]);
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-screen overflow-hidden bg-background text-foreground">
|
||||
{/* Desktop sidebar */}
|
||||
{!isMobile && (
|
||||
<motion.aside
|
||||
initial={false}
|
||||
animate={{ width: collapsed ? 64 : 248 }}
|
||||
transition={{ type: 'spring', stiffness: 280, damping: 32 }}
|
||||
className="relative h-full shrink-0 border-r overflow-hidden"
|
||||
>
|
||||
<Sidebar active={active} onNavigate={onNavigate} collapsed={collapsed} />
|
||||
</motion.aside>
|
||||
)}
|
||||
|
||||
{/* Mobile sidebar in sheet */}
|
||||
{isMobile && (
|
||||
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
|
||||
<SheetContent side="left" className="w-64 max-w-[80vw] p-0">
|
||||
<Sidebar
|
||||
active={active}
|
||||
onNavigate={onNavigate}
|
||||
onItemClick={() => setMobileOpen(false)}
|
||||
/>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)}
|
||||
|
||||
{/* Main column */}
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<TopBar
|
||||
active={active}
|
||||
status={status}
|
||||
collapsed={collapsed}
|
||||
onToggleCollapse={() => setCollapsed((v) => !v)}
|
||||
onOpenMobile={() => setMobileOpen(true)}
|
||||
onLogout={onLogout}
|
||||
isMobile={isMobile}
|
||||
/>
|
||||
|
||||
<main className={cn('flex min-h-0 flex-1 flex-col')}>
|
||||
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
|
||||
<div className="mx-auto w-full max-w-7xl px-4 py-5 sm:px-6 sm:py-6 lg:px-8">
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={active}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -8 }}
|
||||
transition={{ duration: 0.22, ease: [0.16, 1, 0.3, 1] }}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
91
packages/webui/src/components/layout/sidebar.tsx
Normal file
91
packages/webui/src/components/layout/sidebar.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import { LayoutDashboard, Settings, SlidersHorizontal, Terminal } from 'lucide-react';
|
||||
import { motion } from 'motion/react';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { APP_NAME, APP_VERSION } from '@/types';
|
||||
|
||||
export type Page = 'overview' | 'config' | 'logs' | 'settings';
|
||||
|
||||
export const NAV_ITEMS: { page: Page; label: string; icon: typeof LayoutDashboard; description: string }[] = [
|
||||
{ page: 'overview', label: '总览', icon: LayoutDashboard, description: '主机与服务状态' },
|
||||
{ page: 'config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' },
|
||||
{ page: 'logs', label: '日志', icon: Terminal, description: '实时事件流' },
|
||||
{ page: 'settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
|
||||
];
|
||||
|
||||
interface SidebarProps {
|
||||
active: Page;
|
||||
onNavigate: (page: Page) => void;
|
||||
collapsed?: boolean;
|
||||
onItemClick?: () => void;
|
||||
}
|
||||
|
||||
export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }: SidebarProps) {
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col bg-sidebar text-sidebar-foreground">
|
||||
{/* Brand */}
|
||||
<div className={cn('flex h-16 items-center gap-3 border-b px-4', collapsed && 'justify-center px-2')}>
|
||||
<div className="relative flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-xl bg-primary/10 ring-1 ring-primary/20">
|
||||
<img src="/logo.png" alt="SnowLuma" className="size-7 object-contain" />
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-baseline gap-1.5">
|
||||
<span className="text-sm font-bold tracking-tight">{APP_NAME}</span>
|
||||
<span className="text-[10px] font-medium text-muted-foreground tabular-nums">v{APP_VERSION}</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground">OneBot v11 控制台</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Nav */}
|
||||
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
|
||||
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
|
||||
{NAV_ITEMS.map(({ page, label, icon: Icon, description }) => {
|
||||
const isActive = active === page;
|
||||
return (
|
||||
<button
|
||||
key={page}
|
||||
type="button"
|
||||
title={collapsed ? label : undefined}
|
||||
onClick={() => {
|
||||
onNavigate(page);
|
||||
onItemClick?.();
|
||||
}}
|
||||
className={cn(
|
||||
'group relative flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
|
||||
collapsed && 'w-10 justify-center px-0',
|
||||
isActive
|
||||
? 'text-sidebar-accent-foreground'
|
||||
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
{isActive && (
|
||||
<motion.span
|
||||
layoutId="sidebar-active-pill"
|
||||
className="absolute inset-0 rounded-lg bg-sidebar-accent ring-1 ring-primary/20"
|
||||
transition={{ type: 'spring', stiffness: 380, damping: 32 }}
|
||||
/>
|
||||
)}
|
||||
<Icon className={cn('relative z-10 size-4 shrink-0', isActive && 'text-primary')} />
|
||||
{!collapsed && (
|
||||
<span className="relative z-10 flex min-w-0 flex-1 flex-col items-start">
|
||||
<span className="truncate leading-tight">{label}</span>
|
||||
<span className="text-[10px] font-normal text-muted-foreground truncate">{description}</span>
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</ScrollArea>
|
||||
|
||||
<Separator />
|
||||
<div className={cn('px-4 py-3 text-[10px] text-muted-foreground', collapsed && 'text-center px-2')}>
|
||||
{collapsed ? '©' : `© ${new Date().getFullYear()} SnowLuma`}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
108
packages/webui/src/components/layout/top-bar.tsx
Normal file
108
packages/webui/src/components/layout/top-bar.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
import { useState } from 'react';
|
||||
import { LogOut, Menu, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ThemeToggle } from '@/components/theme-toggle';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import type { Page } from '@/components/layout/sidebar';
|
||||
import { NAV_ITEMS } from '@/components/layout/sidebar';
|
||||
|
||||
interface TopBarProps {
|
||||
active: Page;
|
||||
status: string;
|
||||
collapsed: boolean;
|
||||
onToggleCollapse: () => void;
|
||||
onOpenMobile: () => void;
|
||||
onLogout: () => void;
|
||||
isMobile: boolean;
|
||||
}
|
||||
|
||||
export function TopBar({
|
||||
active,
|
||||
status,
|
||||
collapsed,
|
||||
onToggleCollapse,
|
||||
onOpenMobile,
|
||||
onLogout,
|
||||
isMobile,
|
||||
}: TopBarProps) {
|
||||
const [confirmLogout, setConfirmLogout] = useState(false);
|
||||
const meta = NAV_ITEMS.find((n) => n.page === active);
|
||||
const PageIcon = meta?.icon;
|
||||
const online = status === '已连接';
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-30 flex h-16 shrink-0 items-center gap-2 border-b bg-background/55 px-3 backdrop-blur-xl backdrop-saturate-150 supports-[backdrop-filter]:bg-background/45 sm:px-4">
|
||||
{/* Collapse toggle (desktop) / menu (mobile) */}
|
||||
{isMobile ? (
|
||||
<Button variant="ghost" size="icon-sm" onClick={onOpenMobile} aria-label="打开菜单">
|
||||
<Menu className="size-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onToggleCollapse}
|
||||
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
title={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
>
|
||||
{collapsed ? <PanelLeftOpen className="size-4" /> : <PanelLeftClose className="size-4" />}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="mx-1 h-6 w-px bg-border" />
|
||||
|
||||
{/* Page title */}
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={active}
|
||||
initial={{ opacity: 0, x: -8 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: 8 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className="flex min-w-0 items-center gap-2"
|
||||
>
|
||||
{PageIcon && <PageIcon className="size-4 text-primary" />}
|
||||
<h1 className="truncate text-sm font-semibold tracking-tight">{meta?.label}</h1>
|
||||
<span className="hidden sm:inline truncate text-xs text-muted-foreground">{meta?.description}</span>
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<Badge
|
||||
variant={online ? 'success' : 'destructive'}
|
||||
className="hidden sm:inline-flex gap-1.5"
|
||||
>
|
||||
<span
|
||||
className={`size-1.5 rounded-full ${online ? 'bg-success' : 'bg-destructive'} ${online ? 'animate-pulse' : ''}`}
|
||||
/>
|
||||
{status}
|
||||
</Badge>
|
||||
|
||||
<ThemeToggle />
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setConfirmLogout(true)}
|
||||
aria-label="登出"
|
||||
title="登出"
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<LogOut className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmLogout}
|
||||
onOpenChange={setConfirmLogout}
|
||||
title="确认登出?"
|
||||
description="登出后将清除当前会话令牌,您需要重新输入访问密码才能进入控制台。"
|
||||
confirmText="登出"
|
||||
destructive
|
||||
onConfirm={onLogout}
|
||||
/>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
function qqAvatarUrl(uin: string): string {
|
||||
return `/avatar/${encodeURIComponent(uin)}`;
|
||||
}
|
||||
|
||||
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 overflow-hidden"
|
||||
style={{
|
||||
background: isActive
|
||||
? 'linear-gradient(135deg, var(--accent), #818cf8)'
|
||||
: 'var(--bg-input)',
|
||||
color: isActive ? '#fff' : 'var(--text-secondary)',
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={qqAvatarUrl(q.uin)}
|
||||
alt={q.nickname || q.uin}
|
||||
className="size-full object-cover"
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -1,473 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { RefreshCw, Terminal } from 'lucide-react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useTheme } from '../../contexts/ThemeContext';
|
||||
|
||||
interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
scope: string;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogsPageProps {
|
||||
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
|
||||
}
|
||||
|
||||
const levelColor: Record<LogEntry['level'], string> = {
|
||||
debug: 'var(--text-tertiary)',
|
||||
info: 'var(--accent)',
|
||||
success: 'var(--color-success)',
|
||||
warn: '#f59e0b',
|
||||
error: 'var(--color-danger)',
|
||||
};
|
||||
|
||||
export function LogsPage({ fetchApi }: LogsPageProps) {
|
||||
const { resolved } = useTheme();
|
||||
const dark = resolved === 'dark';
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
const [streamStatus, setStreamStatus] = useState('连接中');
|
||||
const endRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
|
||||
|
||||
async function loadLogs() {
|
||||
const res = await fetchApi('/api/logs?limit=500');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setLogs(data.list || []);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadLogs().catch(console.error);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
|
||||
const source = new EventSource(url);
|
||||
source.onopen = () => setStreamStatus('实时连接');
|
||||
source.onerror = () => setStreamStatus('重连中');
|
||||
source.onmessage = event => {
|
||||
try {
|
||||
const entry = JSON.parse(event.data) as LogEntry | { type: string };
|
||||
if ('type' in entry) return;
|
||||
setLogs(prev => [...prev.filter(item => item.id !== entry.id), entry].slice(-500));
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
return () => source.close();
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => {
|
||||
endRef.current?.scrollIntoView({ block: 'end' });
|
||||
}, [logs]);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
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)',
|
||||
}}
|
||||
>
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="flex size-9 items-center justify-center rounded-lg"
|
||||
style={{ background: 'var(--accent-subtle)', color: 'var(--accent)' }}
|
||||
>
|
||||
<Terminal size={17} strokeWidth={2} />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold" style={{ color: 'var(--text-primary)' }}>运行日志</h2>
|
||||
<p className="mt-0.5 text-xs" style={{ color: 'var(--text-secondary)' }}>{streamStatus} · 最近 {logs.length} 条</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => loadLogs().catch(console.error)}
|
||||
className="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-3 text-xs font-medium"
|
||||
style={{
|
||||
color: 'var(--text-secondary)',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
background: 'transparent',
|
||||
}}
|
||||
>
|
||||
<RefreshCw size={13} />
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="h-[58vh] overflow-auto rounded-xl p-3 text-xs"
|
||||
style={{
|
||||
background: dark ? 'rgba(0,0,0,0.22)' : 'rgba(255,255,255,0.42)',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
fontFamily: 'var(--font-mono)',
|
||||
}}
|
||||
>
|
||||
{logs.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center" style={{ color: 'var(--text-tertiary)' }}>暂无日志</div>
|
||||
) : logs.map(log => (
|
||||
<div key={log.id} className="flex gap-2 whitespace-pre-wrap py-0.5 leading-5">
|
||||
<span className="shrink-0" style={{ color: 'var(--text-tertiary)' }}>{new Date(log.time).toLocaleTimeString()}</span>
|
||||
<span className="w-14 shrink-0 font-semibold" style={{ color: levelColor[log.level] }}>{log.level.toUpperCase()}</span>
|
||||
<span className="w-24 shrink-0 truncate" style={{ color: 'var(--text-secondary)' }}>[{log.scope}]</span>
|
||||
<span style={{ color: 'var(--text-primary)' }}>{log.message}</span>
|
||||
</div>
|
||||
))}
|
||||
<div ref={endRef} />
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
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)';
|
||||
}
|
||||
|
||||
function qqAvatarUrl(uin: string): string {
|
||||
return `/avatar/${encodeURIComponent(uin)}`;
|
||||
}
|
||||
|
||||
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 overflow-hidden"
|
||||
style={{
|
||||
background: 'linear-gradient(135deg, var(--accent), #818cf8)',
|
||||
boxShadow: '0 0 12px var(--accent-glow)',
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={qqAvatarUrl(q.uin)}
|
||||
alt={q.nickname || q.uin}
|
||||
className="size-full object-cover"
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
303
packages/webui/src/components/pages/change-password-page.tsx
Normal file
303
packages/webui/src/components/pages/change-password-page.tsx
Normal file
@@ -0,0 +1,303 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { Check, Eye, EyeOff, KeyRound, Loader2, ShieldAlert } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ThemeToggle } from '@/components/theme-toggle';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface PasswordRule {
|
||||
id: string;
|
||||
label: string;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
interface ChangePasswordPageProps {
|
||||
/** When true, this is the forced first-time change flow. */
|
||||
forced?: boolean;
|
||||
/** Heading shown above the form. */
|
||||
title?: string;
|
||||
/** Subheading. */
|
||||
description?: string;
|
||||
/** Sends `{ password }` and returns the rule list + valid flag. */
|
||||
checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
/** Sends `{ oldPassword, newPassword }`. Returns success or error message. */
|
||||
submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>;
|
||||
/** Called after a successful submit. */
|
||||
onSuccess: () => void;
|
||||
/** Called when user cancels (only available when not forced). */
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
export function ChangePasswordPage({
|
||||
forced = false,
|
||||
title,
|
||||
description,
|
||||
checkStrength,
|
||||
submit,
|
||||
onSuccess,
|
||||
onCancel,
|
||||
}: ChangePasswordPageProps) {
|
||||
const [oldPassword, setOldPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [showOld, setShowOld] = useState(false);
|
||||
const [showNew, setShowNew] = useState(false);
|
||||
const [rules, setRules] = useState<PasswordRule[]>([]);
|
||||
const [valid, setValid] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword;
|
||||
const canSubmit =
|
||||
!submitting && oldPassword.length > 0 && valid && confirmMatches && oldPassword !== newPassword;
|
||||
|
||||
// Debounce the strength check so we don't slam the API on every keystroke.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const handle = window.setTimeout(async () => {
|
||||
try {
|
||||
const res = await checkStrength(newPassword);
|
||||
if (cancelled) return;
|
||||
setRules(res.rules);
|
||||
setValid(res.valid);
|
||||
} catch {
|
||||
/* ignore – the form will just stay disabled */
|
||||
}
|
||||
}, 180);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearTimeout(handle);
|
||||
};
|
||||
}, [newPassword, checkStrength]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!canSubmit) return;
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const res = await submit(oldPassword, newPassword);
|
||||
if (res.success) {
|
||||
onSuccess();
|
||||
} else {
|
||||
setError(res.message || '修改失败');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : '网络错误');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const computedTitle = title ?? (forced ? '请先设置新的访问密码' : '修改访问密码');
|
||||
const computedDescription =
|
||||
description ??
|
||||
(forced
|
||||
? '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。'
|
||||
: '设置一个全新的强密码后,其他会话将被立即下线,需要重新登录。');
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
|
||||
<div
|
||||
className="pointer-events-none absolute inset-0"
|
||||
style={{
|
||||
background:
|
||||
'radial-gradient(80% 60% at 50% 0%, color-mix(in oklab, var(--primary) 18%, transparent) 0%, transparent 70%)',
|
||||
}}
|
||||
/>
|
||||
<motion.div
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute -left-24 top-24 size-72 rounded-full bg-primary/15 blur-3xl"
|
||||
animate={{ scale: [1, 1.08, 1] }}
|
||||
transition={{ duration: 8, repeat: Infinity, ease: 'easeInOut' }}
|
||||
/>
|
||||
<div className="absolute right-4 top-4">
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
|
||||
className="relative z-10 w-full max-w-lg"
|
||||
>
|
||||
<Card className="border-primary/15 shadow-xl">
|
||||
<CardContent className="p-7 sm:p-9">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20">
|
||||
{forced ? (
|
||||
<ShieldAlert className="size-6 text-primary" />
|
||||
) : (
|
||||
<KeyRound className="size-6 text-primary" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-lg font-semibold tracking-tight">{computedTitle}</h1>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">{computedDescription}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="old">当前密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="old"
|
||||
type={showOld ? 'text' : 'password'}
|
||||
autoComplete="current-password"
|
||||
value={oldPassword}
|
||||
onChange={(e) => setOldPassword(e.target.value)}
|
||||
placeholder="输入当前访问密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowOld((v) => !v)}
|
||||
aria-label={showOld ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showOld ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="new">新密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="new"
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
placeholder="设置新的强密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowNew((v) => !v)}
|
||||
aria-label={showNew ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showNew ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="confirm">确认新密码</Label>
|
||||
<Input
|
||||
id="confirm"
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="再次输入新密码"
|
||||
className="h-10 text-sm"
|
||||
/>
|
||||
{confirmPassword.length > 0 && !confirmMatches && (
|
||||
<span className="text-[11px] text-destructive">两次输入的密码不一致</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<RuleList rules={rules} />
|
||||
|
||||
<AnimatePresence>
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="rounded-md bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{!forced && onCancel && (
|
||||
<Button type="button" variant="ghost" onClick={onCancel} className="h-10">
|
||||
取消
|
||||
</Button>
|
||||
)}
|
||||
<Button type="submit" disabled={!canSubmit} className="ml-auto h-10">
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="size-4 animate-spin" /> 提交中…
|
||||
</>
|
||||
) : (
|
||||
'保存新密码'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RuleList({ rules }: { rules: PasswordRule[] }) {
|
||||
// Initial empty state: show a placeholder set so the user knows the rules
|
||||
// exist even before any input.
|
||||
const display = useMemo<PasswordRule[]>(() => {
|
||||
if (rules.length > 0) return rules;
|
||||
return [
|
||||
{ id: 'length', label: '长度不少于 10 位', ok: false },
|
||||
{ id: 'lower', label: '至少包含一个小写字母', ok: false },
|
||||
{ id: 'upper', label: '至少包含一个大写字母', ok: false },
|
||||
{ id: 'special', label: '至少包含一个特殊字符', ok: false },
|
||||
{ id: 'no-space', label: '不得包含空格', ok: false },
|
||||
];
|
||||
}, [rules]);
|
||||
|
||||
return (
|
||||
<ul className="grid gap-1.5 rounded-lg border bg-muted/30 p-3">
|
||||
{display.map((rule) => (
|
||||
<li key={rule.id} className="flex items-center gap-2">
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{
|
||||
backgroundColor: rule.ok ? 'color-mix(in oklab, var(--primary) 20%, transparent)' : 'transparent',
|
||||
borderColor: rule.ok ? 'var(--primary)' : 'var(--border)',
|
||||
scale: rule.ok ? [1, 1.18, 1] : 1,
|
||||
}}
|
||||
transition={{ duration: 0.25 }}
|
||||
className={cn(
|
||||
'flex size-4 items-center justify-center rounded-full border',
|
||||
)}
|
||||
>
|
||||
<AnimatePresence>
|
||||
{rule.ok && (
|
||||
<motion.span
|
||||
key="check"
|
||||
initial={{ opacity: 0, scale: 0.4 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.4 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
>
|
||||
<Check className="size-3 text-primary" strokeWidth={3} />
|
||||
</motion.span>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.span>
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{ color: rule.ok ? 'var(--foreground)' : 'var(--muted-foreground)' }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="text-xs"
|
||||
>
|
||||
{rule.label}
|
||||
</motion.span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
727
packages/webui/src/components/pages/config-page.tsx
Normal file
727
packages/webui/src/components/pages/config-page.tsx
Normal file
@@ -0,0 +1,727 @@
|
||||
import { useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { MousePointerClick, Plus, Save, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type {
|
||||
MessageFormat,
|
||||
NetworkKind,
|
||||
OneBotConfig,
|
||||
OneBotNetworks,
|
||||
QQInfo,
|
||||
WsRole,
|
||||
} from '@/types';
|
||||
|
||||
interface ConfigPageProps {
|
||||
qqList: QQInfo[];
|
||||
selectedUin: string | null;
|
||||
config: OneBotConfig | null;
|
||||
saveStatus: string;
|
||||
onSelectAccount: (uin: string) => void;
|
||||
onSave: () => Promise<void> | void;
|
||||
onConfigChange: (config: OneBotConfig) => void;
|
||||
}
|
||||
|
||||
function qqAvatarUrl(uin: string) {
|
||||
return `/avatar/${encodeURIComponent(uin)}`;
|
||||
}
|
||||
|
||||
function generateAccessToken(): string {
|
||||
const bytes = new Uint8Array(32);
|
||||
globalThis.crypto.getRandomValues(bytes);
|
||||
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
function Field({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
type = 'text',
|
||||
className,
|
||||
}: {
|
||||
label: string;
|
||||
value: string | number | undefined;
|
||||
onChange: (v: string) => void;
|
||||
placeholder?: string;
|
||||
type?: 'text' | 'number' | 'url';
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('flex flex-col gap-1.5', className)}>
|
||||
<Label>{label}</Label>
|
||||
<Input
|
||||
type={type}
|
||||
value={value ?? ''}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SectionProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
onAdd?: () => void;
|
||||
children: React.ReactNode;
|
||||
count?: number;
|
||||
}
|
||||
|
||||
function Section({ title, description, onAdd, children, count }: SectionProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<CardTitle className="text-sm">{title}</CardTitle>
|
||||
{typeof count === 'number' && <Badge variant="secondary">{count}</Badge>}
|
||||
</div>
|
||||
{description && <p className="mt-0.5 text-xs text-muted-foreground">{description}</p>}
|
||||
</div>
|
||||
{onAdd && (
|
||||
<Button size="sm" variant="outline" onClick={onAdd}>
|
||||
<Plus className="size-3.5" /> 添加
|
||||
</Button>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3 pt-0">{children}</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConfigPage({
|
||||
qqList,
|
||||
selectedUin,
|
||||
config,
|
||||
saveStatus,
|
||||
onSelectAccount,
|
||||
onSave,
|
||||
onConfigChange,
|
||||
}: ConfigPageProps) {
|
||||
const [confirmSave, setConfirmSave] = useState(false);
|
||||
|
||||
const update = (next: OneBotConfig) => onConfigChange(next);
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[260px_minmax(0,1fr)]">
|
||||
{/* Account list */}
|
||||
<Card className="lg:sticky lg:top-2 lg:self-start">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm">在线连接</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
{qqList.length === 0 ? (
|
||||
<p className="py-6 text-center text-xs text-muted-foreground">暂无在线会话</p>
|
||||
) : (
|
||||
<ScrollArea className="max-h-[60vh]" viewportClassName="[&>div]:!block">
|
||||
<div className="grid grid-cols-2 gap-1.5 lg:grid-cols-1">
|
||||
{qqList.map((q) => {
|
||||
const isActive = selectedUin === q.uin;
|
||||
return (
|
||||
<motion.button
|
||||
key={q.uin}
|
||||
type="button"
|
||||
whileHover={{ scale: 1.01 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
onClick={() => onSelectAccount(q.uin)}
|
||||
className={cn(
|
||||
'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer',
|
||||
isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40'
|
||||
)}
|
||||
>
|
||||
<Avatar size={28}>
|
||||
<AvatarImage src={qqAvatarUrl(q.uin)} alt={q.nickname || q.uin} />
|
||||
<AvatarFallback>{(q.nickname || q.uin).slice(0, 2)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div
|
||||
className={cn('truncate text-sm font-medium', isActive ? 'text-primary' : 'text-foreground')}
|
||||
>
|
||||
{q.nickname}
|
||||
</div>
|
||||
<div className="truncate font-mono text-[10px] text-muted-foreground tabular-nums">{q.uin}</div>
|
||||
</div>
|
||||
</motion.button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Editor */}
|
||||
<div className="min-w-0">
|
||||
{!selectedUin ? (
|
||||
<div className="flex h-64 flex-col items-center justify-center gap-2 rounded-lg border border-dashed text-muted-foreground">
|
||||
<MousePointerClick className="size-7" strokeWidth={1.5} />
|
||||
<p className="text-sm">请在左栏选择会话以配置通信节点</p>
|
||||
</div>
|
||||
) : !config ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-9 w-48" />
|
||||
<Skeleton className="h-32" />
|
||||
<Skeleton className="h-32" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h2 className="text-base font-semibold tracking-tight">OneBot 协议端点</h2>
|
||||
<code className="mt-0.5 block font-mono text-xs text-muted-foreground tabular-nums">UIN {selectedUin}</code>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{saveStatus && (
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-full border px-2.5 py-1 text-[11px] font-medium',
|
||||
saveStatus === '保存成功' && 'border-success/30 bg-success/10 text-success',
|
||||
saveStatus === '保存中...' && 'border-border bg-muted text-muted-foreground',
|
||||
saveStatus !== '保存成功' && saveStatus !== '保存中...' && 'border-destructive/30 bg-destructive/10 text-destructive'
|
||||
)}
|
||||
>
|
||||
{saveStatus}
|
||||
</span>
|
||||
)}
|
||||
<Button onClick={() => setConfirmSave(true)} size="sm">
|
||||
<Save className="size-3.5" /> 保存设定
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Section
|
||||
title="通用设置"
|
||||
description="OneBot 共享功能配置"
|
||||
>
|
||||
<Field
|
||||
label="音乐签名服务 URL"
|
||||
type="url"
|
||||
placeholder="留空则不启用"
|
||||
value={config.musicSignUrl}
|
||||
onChange={(v) => update({ ...config, musicSignUrl: v || undefined })}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
{/* HTTP Servers */}
|
||||
<NetworkSection
|
||||
title="HTTP API 服务"
|
||||
description="本地监听 HTTP 端口,OneBot 客户端发起请求"
|
||||
kind="httpServers"
|
||||
networks={config.networks.httpServers}
|
||||
onChange={(arr) => updateNetworks(config, update, 'httpServers', arr)}
|
||||
renderFields={(item, patch) => (
|
||||
<>
|
||||
<Field
|
||||
label="主机"
|
||||
placeholder="0.0.0.0"
|
||||
value={item.host}
|
||||
onChange={(v) => patch({ host: v || undefined })}
|
||||
className="sm:w-40"
|
||||
/>
|
||||
<Field
|
||||
label="端口"
|
||||
type="number"
|
||||
value={item.port}
|
||||
onChange={(v) => patch({ port: Number(v) || 0 })}
|
||||
className="sm:w-28"
|
||||
/>
|
||||
<Field
|
||||
label="路径"
|
||||
placeholder="/"
|
||||
value={item.path}
|
||||
onChange={(v) => patch({ path: v || undefined })}
|
||||
className="sm:w-32"
|
||||
/>
|
||||
<Field
|
||||
label="授权 Token"
|
||||
placeholder="不填则无密码"
|
||||
value={item.accessToken}
|
||||
onChange={(v) => patch({ accessToken: v || undefined })}
|
||||
className="flex-1"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
defaultEntry={(suffix) => ({
|
||||
name: `http-${suffix}`,
|
||||
host: '0.0.0.0',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
accessToken: generateAccessToken(),
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
})}
|
||||
/>
|
||||
|
||||
{/* HTTP Clients (POST push) */}
|
||||
<NetworkSection
|
||||
title="HTTP 推送客户端"
|
||||
description="主动向远端 URL POST 推送事件"
|
||||
kind="httpClients"
|
||||
networks={config.networks.httpClients}
|
||||
onChange={(arr) => updateNetworks(config, update, 'httpClients', arr)}
|
||||
renderFields={(item, patch) => (
|
||||
<>
|
||||
<Field
|
||||
label="目标 URL"
|
||||
type="url"
|
||||
placeholder="http://..."
|
||||
value={item.url}
|
||||
onChange={(v) => patch({ url: v })}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Field
|
||||
label="授权 Token"
|
||||
placeholder="可选"
|
||||
value={item.accessToken}
|
||||
onChange={(v) => patch({ accessToken: v || undefined })}
|
||||
className="sm:w-56"
|
||||
/>
|
||||
<Field
|
||||
label="超时 (ms)"
|
||||
type="number"
|
||||
placeholder="5000"
|
||||
value={item.timeoutMs}
|
||||
onChange={(v) => patch({ timeoutMs: Number(v) || undefined })}
|
||||
className="sm:w-32"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
defaultEntry={(suffix) => ({
|
||||
name: `httppost-${suffix}`,
|
||||
url: 'http://127.0.0.1:5700',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
})}
|
||||
/>
|
||||
|
||||
{/* WebSocket Servers */}
|
||||
<NetworkSection
|
||||
title="WebSocket 服务"
|
||||
description="本地监听 WebSocket 端口,客户端建立持久连接"
|
||||
kind="wsServers"
|
||||
networks={config.networks.wsServers}
|
||||
onChange={(arr) => updateNetworks(config, update, 'wsServers', arr)}
|
||||
renderFields={(item, patch) => (
|
||||
<>
|
||||
<Field
|
||||
label="主机"
|
||||
placeholder="0.0.0.0"
|
||||
value={item.host}
|
||||
onChange={(v) => patch({ host: v || undefined })}
|
||||
className="sm:w-40"
|
||||
/>
|
||||
<Field
|
||||
label="端口"
|
||||
type="number"
|
||||
value={item.port}
|
||||
onChange={(v) => patch({ port: Number(v) || 0 })}
|
||||
className="sm:w-28"
|
||||
/>
|
||||
<Field
|
||||
label="路径"
|
||||
placeholder="/"
|
||||
value={item.path}
|
||||
onChange={(v) => patch({ path: v || undefined })}
|
||||
className="sm:w-32"
|
||||
/>
|
||||
<SelectField
|
||||
label="角色"
|
||||
value={item.role ?? 'Universal'}
|
||||
options={WS_ROLE_OPTIONS}
|
||||
onChange={(v) => patch({ role: v })}
|
||||
className="sm:w-32"
|
||||
/>
|
||||
<Field
|
||||
label="授权 Token"
|
||||
placeholder="不填则无密码"
|
||||
value={item.accessToken}
|
||||
onChange={(v) => patch({ accessToken: v || undefined })}
|
||||
className="flex-1"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
defaultEntry={(suffix) => ({
|
||||
name: `ws-${suffix}`,
|
||||
host: '0.0.0.0',
|
||||
port: 3001,
|
||||
path: '/',
|
||||
role: 'Universal' as WsRole,
|
||||
accessToken: generateAccessToken(),
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
})}
|
||||
/>
|
||||
|
||||
{/* WebSocket Clients (reverse) */}
|
||||
<NetworkSection
|
||||
title="WebSocket 反向客户端"
|
||||
description="主动连接到外部 WebSocket 服务器(reverse-ws)"
|
||||
kind="wsClients"
|
||||
networks={config.networks.wsClients}
|
||||
onChange={(arr) => updateNetworks(config, update, 'wsClients', arr)}
|
||||
renderFields={(item, patch) => (
|
||||
<>
|
||||
<Field
|
||||
label="目标 URL"
|
||||
type="url"
|
||||
placeholder="ws://..."
|
||||
value={item.url}
|
||||
onChange={(v) => patch({ url: v })}
|
||||
className="flex-1"
|
||||
/>
|
||||
<SelectField
|
||||
label="角色"
|
||||
value={item.role ?? 'Universal'}
|
||||
options={WS_ROLE_OPTIONS}
|
||||
onChange={(v) => patch({ role: v })}
|
||||
className="sm:w-32"
|
||||
/>
|
||||
<Field
|
||||
label="重连间隔 (ms)"
|
||||
type="number"
|
||||
value={item.reconnectIntervalMs}
|
||||
onChange={(v) => patch({ reconnectIntervalMs: Number(v) || undefined })}
|
||||
className="sm:w-36"
|
||||
/>
|
||||
<Field
|
||||
label="授权 Token"
|
||||
placeholder="可选"
|
||||
value={item.accessToken}
|
||||
onChange={(v) => patch({ accessToken: v || undefined })}
|
||||
className="sm:w-56"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
defaultEntry={(suffix) => ({
|
||||
name: `wsclient-${suffix}`,
|
||||
url: 'ws://127.0.0.1:8080/ws',
|
||||
role: 'Universal' as WsRole,
|
||||
reconnectIntervalMs: 5000,
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmSave}
|
||||
onOpenChange={setConfirmSave}
|
||||
title="保存配置变更?"
|
||||
description={`即将把当前修改保存到 UIN ${selectedUin ?? ''} 的配置文件,并尝试热重载该会话。`}
|
||||
confirmText="保存"
|
||||
onConfirm={onSave}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyHint({ label }: { label: string }) {
|
||||
return (
|
||||
<div className="rounded-md border border-dashed py-6 text-center text-xs text-muted-foreground">{label}</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ToggleFieldProps {
|
||||
label: string;
|
||||
description?: string;
|
||||
value: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
}
|
||||
|
||||
function ToggleField({ label, description, value, onChange }: ToggleFieldProps) {
|
||||
return (
|
||||
<div className="flex items-start justify-between gap-3 rounded-lg border bg-card/40 p-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<Label className="text-sm">{label}</Label>
|
||||
{description && (
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={value}
|
||||
aria-label={label}
|
||||
onClick={() => onChange(!value)}
|
||||
className={cn(
|
||||
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border transition-colors',
|
||||
value
|
||||
? 'border-primary bg-primary'
|
||||
: 'border-input bg-muted',
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
className="inline-block size-4 rounded-full bg-background shadow-sm"
|
||||
animate={{ x: value ? 22 : 4 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SegmentedOption<T extends string> {
|
||||
value: T;
|
||||
label: string;
|
||||
}
|
||||
|
||||
function SegmentedField<T extends string>({
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
className,
|
||||
}: {
|
||||
label: string;
|
||||
value: T;
|
||||
options: ReadonlyArray<SegmentedOption<T>>;
|
||||
onChange: (v: T) => void;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('flex flex-col gap-1.5', className)}>
|
||||
<Label>{label}</Label>
|
||||
<div className="flex flex-wrap gap-1 rounded-md border bg-muted/30 p-1">
|
||||
{options.map((opt) => {
|
||||
const active = value === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => onChange(opt.value)}
|
||||
className={cn(
|
||||
'flex-1 rounded px-2.5 py-1 text-xs transition-colors cursor-pointer',
|
||||
active
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'text-muted-foreground hover:bg-accent/50',
|
||||
)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectField<T extends string>({
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
className,
|
||||
}: {
|
||||
label: string;
|
||||
value: T;
|
||||
options: ReadonlyArray<SegmentedOption<T>>;
|
||||
onChange: (v: T) => void;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('flex flex-col gap-1.5', className)}>
|
||||
<Label>{label}</Label>
|
||||
<select
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value as T)}
|
||||
className="h-9 rounded-md border bg-background px-2 text-sm shadow-xs"
|
||||
>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ADAPTER_FORMAT_OPTIONS: ReadonlyArray<SegmentedOption<MessageFormat>> = [
|
||||
{ value: 'array', label: '数组' },
|
||||
{ value: 'string', label: 'CQ 码' },
|
||||
];
|
||||
|
||||
const ADAPTER_REPORT_OPTIONS: ReadonlyArray<SegmentedOption<'on' | 'off'>> = [
|
||||
{ value: 'on', label: '开启' },
|
||||
{ value: 'off', label: '关闭' },
|
||||
];
|
||||
|
||||
const WS_ROLE_OPTIONS: ReadonlyArray<SegmentedOption<WsRole>> = [
|
||||
{ value: 'Universal', label: 'Universal' },
|
||||
{ value: 'Event', label: 'Event' },
|
||||
{ value: 'Api', label: 'Api' },
|
||||
];
|
||||
|
||||
interface BaseAdapter {
|
||||
name: string;
|
||||
enabled?: boolean;
|
||||
accessToken?: string;
|
||||
messageFormat: MessageFormat;
|
||||
reportSelfMessage: boolean;
|
||||
}
|
||||
|
||||
interface NetworkSectionProps<T extends BaseAdapter> {
|
||||
title: string;
|
||||
description?: string;
|
||||
kind: NetworkKind;
|
||||
networks: T[];
|
||||
onChange: (next: T[]) => void;
|
||||
renderFields: (item: T, patch: (changes: Partial<T>) => void) => React.ReactNode;
|
||||
defaultEntry: (suffix: number) => T;
|
||||
}
|
||||
|
||||
function NetworkSection<T extends BaseAdapter>({
|
||||
title,
|
||||
description,
|
||||
networks,
|
||||
onChange,
|
||||
renderFields,
|
||||
defaultEntry,
|
||||
}: NetworkSectionProps<T>) {
|
||||
const handleAdd = () => {
|
||||
const used = new Set(networks.map((n) => n.name));
|
||||
let suffix = networks.length + 1;
|
||||
let entry = defaultEntry(suffix);
|
||||
while (used.has(entry.name)) {
|
||||
suffix += 1;
|
||||
entry = defaultEntry(suffix);
|
||||
}
|
||||
onChange([...networks, entry]);
|
||||
};
|
||||
|
||||
const patchAt = (idx: number, changes: Partial<T>) => {
|
||||
onChange(networks.map((it, i) => (i === idx ? { ...it, ...changes } : it)));
|
||||
};
|
||||
|
||||
const removeAt = (idx: number) => {
|
||||
onChange(networks.filter((_, i) => i !== idx));
|
||||
};
|
||||
|
||||
return (
|
||||
<Section title={title} description={description} count={networks.length} onAdd={handleAdd}>
|
||||
{networks.length === 0 ? (
|
||||
<EmptyHint label="暂无适配器,点击右上角『添加』新建" />
|
||||
) : (
|
||||
networks.map((item, idx) => (
|
||||
<AdapterRow
|
||||
key={`${item.name}-${idx}`}
|
||||
item={item}
|
||||
otherNames={networks.filter((_, i) => i !== idx).map((n) => n.name)}
|
||||
onPatch={(changes) => patchAt(idx, changes)}
|
||||
onRemove={() => removeAt(idx)}
|
||||
renderFields={renderFields}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
interface AdapterRowProps<T extends BaseAdapter> {
|
||||
item: T;
|
||||
otherNames: string[];
|
||||
onPatch: (changes: Partial<T>) => void;
|
||||
onRemove: () => void;
|
||||
renderFields: (item: T, patch: (changes: Partial<T>) => void) => React.ReactNode;
|
||||
}
|
||||
|
||||
function AdapterRow<T extends BaseAdapter>({
|
||||
item,
|
||||
otherNames,
|
||||
onPatch,
|
||||
onRemove,
|
||||
renderFields,
|
||||
}: AdapterRowProps<T>) {
|
||||
const enabled = item.enabled !== false;
|
||||
const duplicateName = !!item.name && otherNames.includes(item.name);
|
||||
const blankName = !item.name?.trim();
|
||||
|
||||
const formatValue: MessageFormat = item.messageFormat ?? 'array';
|
||||
const reportValue: 'on' | 'off' = item.reportSelfMessage ? 'on' : 'off';
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className={cn(
|
||||
'flex flex-col gap-3 rounded-lg border bg-card/40 p-3',
|
||||
!enabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<Field
|
||||
label="名称"
|
||||
placeholder="自定义"
|
||||
value={item.name}
|
||||
onChange={(v) => onPatch({ name: v } as Partial<T>)}
|
||||
className="sm:w-44"
|
||||
/>
|
||||
<ToggleField
|
||||
label="启用"
|
||||
value={enabled}
|
||||
onChange={(v) => onPatch({ enabled: v ? undefined : false } as Partial<T>)}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onRemove}
|
||||
aria-label="删除"
|
||||
className="ml-auto self-center text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{(blankName || duplicateName) && (
|
||||
<p className="text-[11px] text-destructive">
|
||||
{blankName ? '请填写名称' : '名称与其它适配器重复'}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-end gap-3">{renderFields(item, onPatch)}</div>
|
||||
|
||||
<div className="grid gap-3 border-t pt-3 sm:grid-cols-2">
|
||||
<SegmentedField
|
||||
label="消息格式"
|
||||
value={formatValue}
|
||||
options={ADAPTER_FORMAT_OPTIONS}
|
||||
onChange={(v) => onPatch({ messageFormat: v } as Partial<T>)}
|
||||
/>
|
||||
<SegmentedField
|
||||
label="上报自身消息"
|
||||
value={reportValue}
|
||||
options={ADAPTER_REPORT_OPTIONS}
|
||||
onChange={(v) =>
|
||||
onPatch({
|
||||
reportSelfMessage: v === 'on',
|
||||
} as Partial<T>)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
function updateNetworks<K extends NetworkKind>(
|
||||
config: OneBotConfig,
|
||||
update: (next: OneBotConfig) => void,
|
||||
kind: K,
|
||||
next: OneBotNetworks[K],
|
||||
): void {
|
||||
update({
|
||||
...config,
|
||||
networks: { ...config.networks, [kind]: next },
|
||||
});
|
||||
}
|
||||
135
packages/webui/src/components/pages/login-page.tsx
Normal file
135
packages/webui/src/components/pages/login-page.tsx
Normal file
@@ -0,0 +1,135 @@
|
||||
import { useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { ArrowRight, Eye, EyeOff, KeyRound } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ThemeToggle } from '@/components/theme-toggle';
|
||||
import { APP_NAME, APP_VERSION } from '@/types';
|
||||
|
||||
interface LoginPageProps {
|
||||
onLogin: (password: string) => Promise<{ success: boolean; error?: string }>;
|
||||
}
|
||||
|
||||
export function LoginPage({ onLogin }: LoginPageProps) {
|
||||
const [password, setPassword] = useState('');
|
||||
const [showPwd, setShowPwd] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [shake, setShake] = useState(0);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
const result = await onLogin(password);
|
||||
setLoading(false);
|
||||
if (!result.success) {
|
||||
setError(result.error || '登录失败');
|
||||
setShake((k) => k + 1);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
|
||||
{/* Sky gradient backdrop */}
|
||||
<div
|
||||
className="pointer-events-none absolute inset-0"
|
||||
style={{
|
||||
background:
|
||||
'radial-gradient(80% 60% at 50% 0%, color-mix(in oklab, var(--primary) 18%, transparent) 0%, transparent 70%)',
|
||||
}}
|
||||
/>
|
||||
<motion.div
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute -left-24 top-24 size-72 rounded-full bg-primary/15 blur-3xl"
|
||||
animate={{ scale: [1, 1.08, 1] }}
|
||||
transition={{ duration: 8, repeat: Infinity, ease: 'easeInOut' }}
|
||||
/>
|
||||
<motion.div
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute -right-16 bottom-10 size-80 rounded-full bg-primary/10 blur-3xl"
|
||||
animate={{ scale: [1, 1.12, 1] }}
|
||||
transition={{ duration: 10, repeat: Infinity, ease: 'easeInOut', delay: 0.6 }}
|
||||
/>
|
||||
|
||||
<div className="absolute right-4 top-4">
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
|
||||
className="relative z-10 w-full max-w-md"
|
||||
>
|
||||
<Card className="border-primary/15 shadow-xl">
|
||||
<CardContent className="p-7 sm:p-9">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-12 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20">
|
||||
<img src="/logo.png" alt="SnowLuma" className="size-9 object-contain" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-xl font-bold tracking-tight">{APP_NAME}</span>
|
||||
<span className="text-[11px] text-muted-foreground tabular-nums">v{APP_VERSION}</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">OneBot v11 协议网关 · 安全登录</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-7 flex flex-col gap-4">
|
||||
<motion.div
|
||||
key={shake}
|
||||
animate={shake > 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}}
|
||||
transition={{ duration: 0.4 }}
|
||||
className="relative"
|
||||
>
|
||||
<KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type={showPwd ? 'text' : 'password'}
|
||||
placeholder="输入访问令牌"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoFocus
|
||||
className="h-11 pl-9 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPwd((v) => !v)}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
|
||||
tabIndex={-1}
|
||||
aria-label={showPwd ? '隐藏密码' : '显示密码'}
|
||||
>
|
||||
{showPwd ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</motion.div>
|
||||
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="rounded-md bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
|
||||
<Button type="submit" disabled={loading || !password} className="h-11">
|
||||
{loading ? '验证中…' : (
|
||||
<>
|
||||
进入控制台 <ArrowRight className="size-4" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<p className="mt-6 text-center text-[11px] text-muted-foreground">
|
||||
© {new Date().getFullYear()} SnowLuma. All rights reserved.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user