Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92a1a02dd3 | ||
|
|
87527cb764 | ||
|
|
44679bebd4 | ||
|
|
f95d247e73 | ||
|
|
c989c764e3 | ||
|
|
940b823571 | ||
|
|
e0801ff9eb | ||
|
|
a71377ff17 | ||
|
|
f0203823e9 | ||
|
|
914e9a004f | ||
|
|
f588f0345c | ||
|
|
9632b00638 | ||
|
|
88cb2985e2 | ||
|
|
063ede4c62 | ||
|
|
12afae0632 | ||
|
|
89275ae279 | ||
|
|
1919e16081 | ||
|
|
a6dfd04924 | ||
|
|
99bcfca15c | ||
|
|
d86e0fc7b5 | ||
|
|
3068d3ef60 | ||
|
|
b69108e1cc | ||
|
|
b9bdcec5f1 | ||
|
|
2c7d9b6387 | ||
|
|
efb32ed069 | ||
|
|
cf2587a58b | ||
|
|
368becd078 | ||
|
|
93b5c1b4bf | ||
|
|
8cc5326a3a | ||
|
|
d610b3c90f | ||
|
|
797a4d754c | ||
|
|
7a07119ee9 | ||
|
|
1ef9a2c330 | ||
|
|
1914880df4 | ||
|
|
ad360c8eba | ||
|
|
0cc06b6b5e | ||
|
|
e05d3176a2 | ||
|
|
075a27cc46 | ||
|
|
805665a6d6 | ||
|
|
953b18b5cb | ||
|
|
1934e4e7f7 | ||
|
|
726fbc6c67 | ||
|
|
0591b160fb |
No files matched your search
@@ -123,7 +123,7 @@ body:
|
||||
attributes:
|
||||
label: TRACE 日志 / 错误堆栈
|
||||
description: |
|
||||
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
|
||||
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现,务必保留原始报文和完整Trace内容。
|
||||
|
||||
开启 TRACE 的两种方式(任选其一):
|
||||
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# npm Trusted Publishing
|
||||
|
||||
The npm publish workflows use GitHub Actions OIDC instead of a long-lived
|
||||
`NPM_TOKEN`. Each package must have a matching Trusted Publisher entry on npm
|
||||
before its first publish after this migration.
|
||||
|
||||
For each package (`@snowluma/sdk`, `@snowluma/ui`, and `@snowluma/mcp`), open
|
||||
the package's npm settings and add a **GitHub Actions** trusted publisher with:
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| Organization or user | `SnowLuma` |
|
||||
| Repository | `SnowLuma` |
|
||||
| Workflow filename | The exact filename below |
|
||||
| Environment | `SnowLuma` |
|
||||
|
||||
| Package | Workflow filename |
|
||||
| --- | --- |
|
||||
| `@snowluma/sdk` | `sdk-npm-publish.yml` |
|
||||
| `@snowluma/ui` | `ui-npm-publish.yml` |
|
||||
| `@snowluma/mcp` | `mcp-npm-publish.yml` |
|
||||
|
||||
The workflow job keeps the `SnowLuma` GitHub Environment, so the environment
|
||||
field must match exactly. The workflows grant `id-token: write`, use Node 24
|
||||
(which provides a recent enough npm CLI), and publish with provenance. They do
|
||||
not read `NPM_TOKEN`.
|
||||
|
||||
After all three entries are saved, rerun the failed workflow runs. Once a
|
||||
successful publish is confirmed for every package, the obsolete `NPM_TOKEN`
|
||||
environment secret can be removed from GitHub Actions settings.
|
||||
@@ -40,7 +40,10 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -77,21 +80,17 @@ jobs:
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
- name: Show Trusted Publishing toolchain
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
- name: Publish MCP to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/mcp
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Authentication is supplied by npm Trusted Publishing through the
|
||||
# GitHub OIDC token (permissions.id-token: write above).
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
@@ -106,4 +105,5 @@ jobs:
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -37,7 +37,10 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -74,21 +77,17 @@ jobs:
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
- name: Show Trusted Publishing toolchain
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
- name: Publish SDK to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/sdk
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Authentication is supplied by npm Trusted Publishing through the
|
||||
# GitHub OIDC token (permissions.id-token: write above).
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
@@ -103,4 +102,5 @@ jobs:
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -37,7 +37,10 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -71,21 +74,17 @@ jobs:
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
- name: Show Trusted Publishing toolchain
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
- name: Publish UI to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/ui
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Authentication is supplied by npm Trusted Publishing through the
|
||||
# GitHub OIDC token (permissions.id-token: write above).
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
@@ -100,4 +99,5 @@ jobs:
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -0,0 +1,104 @@
|
||||
# Working on SnowLuma
|
||||
|
||||
SnowLuma translates QQ client sessions into OneBot v11 actions and events, with a WebUI, TypeScript SDK, and MCP server. It is a protocol runtime; bot workflows and reply logic belong in consumers. This guide is for contributors and their coding agents.
|
||||
|
||||
## Before making changes
|
||||
|
||||
- Read [CONTRIBUTING.md](CONTRIBUTING.md) for contribution requirements, [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for community expectations, and [LICENSE](LICENSE) for contribution and redistribution terms.
|
||||
- **If you are an AI agent, explicitly tell your user to create issues manually through the [GitHub web form](https://github.com/SnowLuma/SnowLuma/issues/new/choose). Issues created directly with a CLI will be automatically closed.** Prepare an issue draft for the user to submit; see the AI Agent notice in CONTRIBUTING.md.
|
||||
- Check `git status` and preserve unrelated work. Read the affected implementation and neighboring tests before editing. Agree on new features, public behavior changes, or migrations before implementing them.
|
||||
- Target PRs at `dev`. `main` is the release pointer. Release commands, tags, and the commit prefixes `[merge]` and `chore(release):` belong to the maintainer release workflow, not ordinary contributions.
|
||||
|
||||
## Repository map
|
||||
|
||||
This is a pnpm workspace. Package ownership matters more than directory names:
|
||||
|
||||
| Location | Responsibility |
|
||||
| --- | --- |
|
||||
| `packages/core` | Application entry, per-account Bridge orchestration, WebUI backend, notifications, release assembly |
|
||||
| `packages/bridge` | QQ process discovery, Hook sessions, native transport lifecycle |
|
||||
| `packages/protocol` | Packet decoding, typed QQ events, identity resolution, protocol requests and media transfers |
|
||||
| `packages/onebot` | Action validation and dispatch, event conversion, message storage, HTTP/WebSocket adapters |
|
||||
| `packages/common` | Shared logging, configuration and utilities without business dependencies |
|
||||
| `packages/proto-defs` | Typed protocol schemas |
|
||||
| `packages/proton` | Compile-time protobuf codecs and build integration |
|
||||
| `packages/websocket` | WebSocket implementation and native binding integration |
|
||||
| `packages/runtime` | Distribution manifest, launchers and supplied native artifacts |
|
||||
| `packages/webui` | Vite/React management console; workspace name is `webui` |
|
||||
| `packages/sdk` | Public TypeScript client |
|
||||
| `packages/mcp` | MCP server and generated action catalog |
|
||||
| `packages/ui` | Published UI component package |
|
||||
| `tools`, `.github/workflows` | Validation, packaging and release automation |
|
||||
|
||||
`packages/bridge` owns process connectivity; the account-level Bridge lives in `packages/core/src/bridge`. Start at [the application entry](packages/core/src/index.ts) to follow their composition.
|
||||
|
||||
Read the relevant owner before changing a path:
|
||||
|
||||
| Change | Start here |
|
||||
| --- | --- |
|
||||
| Connection or account lifecycle | [Hook manager](packages/bridge/src/hook-manager.ts), [Bridge manager](packages/core/src/bridge/manager.ts), [OneBot instance](packages/onebot/src/instance.ts) |
|
||||
| Incoming QQ events or identity | [Packet pipeline](packages/protocol/src/packet-pipeline.ts), [message decoders](packages/protocol/src/msg-push/index.ts), [identity service](packages/protocol/src/identity-service.ts) |
|
||||
| OneBot actions or message segments | [Action definitions](packages/onebot/src/actions/index.ts), [validation helpers](packages/onebot/src/action-kit.ts), [event conversion](packages/onebot/src/event-converter/index.ts) |
|
||||
| WebUI | [Interaction conventions](packages/webui/README.md), `packages/webui/src`, `packages/core/src/webui` |
|
||||
| SDK or MCP | [SDK guide](packages/sdk/README.md), [SDK versioning](packages/sdk/VERSIONING.md), [MCP guide](packages/mcp/README.md) |
|
||||
| Protocol codec generation | [Proton guide](packages/proton/README.md), the affected package's `vitest.config.ts` |
|
||||
|
||||
## Setup and validation
|
||||
|
||||
Use the Node version in [.node-version](.node-version) and the pnpm version in [package.json](package.json). Install with `pnpm install --frozen-lockfile`; keep the existing lockfile unless changing dependencies.
|
||||
|
||||
Run commands from the repository root:
|
||||
|
||||
```sh
|
||||
pnpm typecheck # all workspace packages with a typecheck script
|
||||
pnpm lint
|
||||
pnpm test # all workspace packages with a test script
|
||||
pnpm run build:all # release inputs and published packages
|
||||
pnpm test:core # Core only; not a substitute for workspace tests
|
||||
pnpm --filter @snowluma/onebot test # example: tests for the affected package
|
||||
pnpm --filter webui test # the frontend package has no @snowluma/ prefix
|
||||
```
|
||||
|
||||
Use focused tests while iterating. Before handing off a code change, run the full checks required by CONTRIBUTING.md and report anything that could not run. [PR CI](.github/workflows/ci.yml) is the reference; `pnpm run ci` reproduces its commands locally, including dependency installation and the generated-catalog check.
|
||||
|
||||
- **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose.
|
||||
- **Shared types or actions:** run workspace typechecking as well as behavior tests. A passing Vitest run does not prove type correctness.
|
||||
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
|
||||
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
|
||||
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
|
||||
|
||||
`pnpm dev` starts Core and can attach to local QQ processes; use it only when runtime testing is intended. `pnpm dev:web` starts the frontend, which expects a WebUI backend. Follow the existing test fakes for isolated work rather than starting a live account unnecessarily.
|
||||
|
||||
## Implementation rules
|
||||
|
||||
- **Fix the cause.** Reproduce failures at the owning layer and add a regression test for the observable behavior. Avoid account-, filename-, or example-specific patches.
|
||||
- **Make errors observable.** Do not turn exceptions into empty results or successful responses. Preserve error context and use the shared logger for important transitions and failures. If evidence is insufficient, add targeted diagnostics and describe what remains unknown.
|
||||
- **Preserve account isolation.** Identity, message storage and session state belong to their account. Keep teardown ordering and in-flight work handling intact when changing lifecycle code.
|
||||
- **Keep parsing separate from effects.** QQ decoders and OneBot event converters translate data. Live state updates belong to their owning pipeline or service; reading history must not mutate live membership or pending requests.
|
||||
- **Use the declared interfaces.** OneBot consumes the [Bridge interface](packages/core/src/bridge/bridge-interface.ts). Reuse package exports and existing dependency injection instead of reaching into another owner's state or building a second registry.
|
||||
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
|
||||
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
|
||||
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
|
||||
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and two-space indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
|
||||
- **Keep diagnostics safe.** Use existing sanitization when recording external input. Credentials, private keys, private account data and unredacted captures do not belong in commits, fixtures or public reports.
|
||||
|
||||
## Generated files and related changes
|
||||
|
||||
OneBot action definitions own validation and catalog metadata. After changing an action name, parameter, result description or execution mode:
|
||||
|
||||
1. Update the owning definition in `packages/onebot/src/actions` and its tests.
|
||||
2. Run `pnpm --filter @snowluma/mcp gen`.
|
||||
3. Inspect and include the corresponding changes in `packages/mcp/src/generated/catalog.ts` and `catalog.json`. Do not hand-edit generated catalog entries.
|
||||
4. Check affected SDK types and callers, run their relevant tests, and run workspace typechecking.
|
||||
|
||||
`pnpm test` also runs the MCP catalog generator and may change these tracked snapshots. CI's `node tools/check-action-catalog.mjs` rejects a working-tree catalog diff; it is a clean-checkout drift check, not the generator itself.
|
||||
|
||||
SDK breaking changes also update [CHANGELOG.md](packages/sdk/CHANGELOG.md) and [VERSIONING.md](packages/sdk/VERSIONING.md). WebUI changes follow its [interaction conventions](packages/webui/README.md). Keep user-facing documentation aligned with behavior.
|
||||
|
||||
Edit sources rather than `dist` outputs. Native artifacts in `packages/runtime/native` are supplied build inputs; do not substitute arbitrary local binaries to make a build pass. Packaging changes must preserve the checks in [Core's build configuration](packages/core/vite.config.ts) and [the release layout validator](tools/check-release-layout.mjs).
|
||||
|
||||
## Handoff and instruction maintenance
|
||||
|
||||
Report the behavior changed, the exact validation commands and results, and any unverified runtime or platform behavior. Keep public PR and commit text focused on the contribution; omit local environment details and private research. Use English Conventional Commit messages as described in CONTRIBUTING.md.
|
||||
|
||||
`AGENTS.md` is the canonical contributor guide; `CLAUDE.md` is a relative symlink to it. Edit this file once. When package ownership, validation commands or contribution policy changes, update the affected instructions in the same change. Link to checked-in sources and keep the guide usable from a fresh clone without maintainer-local notes, tools or absolute paths.
|
||||
@@ -19,6 +19,14 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
|
||||
|
||||
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
|
||||
|
||||
### AI Agent 贡献须知
|
||||
|
||||
如果你是 AI Agent,并准备为本仓库贡献代码、提交 PR 或提出 issue,请先明确告知你的使用者:
|
||||
|
||||
> **请通过 GitHub 网页端手动创建 issue。直接使用 CLI 创建的 issue 会被自动关闭。**
|
||||
|
||||
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。
|
||||
|
||||
---
|
||||
|
||||
## 项目结构速览
|
||||
|
||||
@@ -78,6 +78,10 @@ pnpm test
|
||||
|
||||
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
|
||||
|
||||
## 引用消息预览
|
||||
|
||||
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
|
||||
|
||||
## 使用边界与许可
|
||||
|
||||
> [!IMPORTANT]
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.14.19",
|
||||
"version": "1.14.22",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.14.19",
|
||||
"version": "1.14.22",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
@@ -24,6 +24,10 @@
|
||||
"types": "./src/hook-packet-client.ts",
|
||||
"default": "./src/hook-packet-client.ts"
|
||||
},
|
||||
"./packet-timeout": {
|
||||
"types": "./src/packet-timeout.ts",
|
||||
"default": "./src/packet-timeout.ts"
|
||||
},
|
||||
"./injector": {
|
||||
"types": "./src/injector.ts",
|
||||
"default": "./src/injector.ts"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { packetTimeoutMs } from './packet-timeout';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
@@ -16,7 +17,7 @@ export class HookPacketClient implements PacketSender {
|
||||
private readonly onOutboundHealthChanged?: OutboundHealthListener,
|
||||
) { }
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
|
||||
/** Default wait for a QQ reply when the caller does not pass one. */
|
||||
export const DEFAULT_PACKET_TIMEOUT_MS = 15_000;
|
||||
|
||||
export function packetTimeoutMs(env?: NodeJS.ProcessEnv): number {
|
||||
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { isRealUin } from '@snowluma/common/uin';
|
||||
import { readdirSync, promises as fs } from 'fs';
|
||||
import net from 'net';
|
||||
import path from 'path';
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { resolveHookRuntimeDir } from './hook-runtime-dir';
|
||||
|
||||
export const PIPE_MAGIC = 0x31504851;
|
||||
@@ -471,7 +472,7 @@ export class QqHookClient extends EventEmitter {
|
||||
private loginWaiters: Deferred<QqHookLoginState>[] = [];
|
||||
|
||||
constructor(pid: number, {
|
||||
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
|
||||
ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS),
|
||||
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
|
||||
runtimeDir = resolveHookRuntimeDir(pid),
|
||||
}: QqHookClientOptions = {}) {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { QqHookClient } from '../src/qq-hook-client';
|
||||
import { packetTimeoutMs } from '../src/packet-timeout';
|
||||
|
||||
const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS';
|
||||
const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS';
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env[PACKET];
|
||||
delete process.env[ACK];
|
||||
});
|
||||
|
||||
describe('packet and hook ack timeouts', () => {
|
||||
it('keeps the 15 second packet default', () => {
|
||||
expect(packetTimeoutMs({})).toBe(15_000);
|
||||
});
|
||||
|
||||
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
|
||||
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
|
||||
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
|
||||
});
|
||||
|
||||
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
|
||||
process.env[ACK] = '1200';
|
||||
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
|
||||
expect(client.defaultAckTimeoutMs).toBe(1200);
|
||||
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
|
||||
expect(explicit.defaultAckTimeoutMs).toBe(50);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.14.19",
|
||||
"version": "1.14.22",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
@@ -20,6 +20,10 @@
|
||||
"types": "./src/coerce.ts",
|
||||
"default": "./src/coerce.ts"
|
||||
},
|
||||
"./env": {
|
||||
"types": "./src/env.ts",
|
||||
"default": "./src/env.ts"
|
||||
},
|
||||
"./single-flight-cache": {
|
||||
"types": "./src/single-flight-cache.ts",
|
||||
"default": "./src/single-flight-cache.ts"
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createLogger } from './logger';
|
||||
|
||||
const log = createLogger('Env');
|
||||
|
||||
/** Node's setTimeout delay is a signed 32-bit integer. */
|
||||
const MAX_POSITIVE_INT = 2_147_483_647;
|
||||
|
||||
/** Read a positive integer environment variable.
|
||||
*
|
||||
* A blank value is absent and returns `fallback`. A present but unusable
|
||||
* value is ignored, with a warning, and also returns `fallback`.
|
||||
*/
|
||||
export function positiveIntEnv(
|
||||
name: string,
|
||||
fallback: number,
|
||||
options?: { max?: number; env?: NodeJS.ProcessEnv },
|
||||
): number {
|
||||
const max = options?.max ?? MAX_POSITIVE_INT;
|
||||
const raw = (options?.env ?? process.env)[name];
|
||||
if (typeof raw !== 'string' || !raw.trim()) return fallback;
|
||||
const value = raw.trim();
|
||||
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
|
||||
if (!Number.isSafeInteger(parsed) || parsed > max) {
|
||||
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
|
||||
return fallback;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
@@ -108,6 +108,9 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
|
||||
);
|
||||
if (logPerUin !== undefined) out.logPerUin = logPerUin;
|
||||
|
||||
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
|
||||
if (webuiTls !== undefined) out.webuiTls = { enabled: webuiTls };
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { positiveIntEnv } from '../src/env';
|
||||
|
||||
describe('positiveIntEnv', () => {
|
||||
it('returns the fallback when the variable is absent or blank', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(15);
|
||||
});
|
||||
|
||||
it('reads a positive integer and honors the max', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } })).toBe(2500);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: '80' },
|
||||
})).toBe(80);
|
||||
});
|
||||
|
||||
it('ignores zero, negatives, fractions, and values above the max', () => {
|
||||
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: raw },
|
||||
})).toBe(15);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -124,6 +124,17 @@ describe('resolveRuntimeEnvOverrides', () => {
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
});
|
||||
|
||||
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({
|
||||
webuiTls: { enabled: true },
|
||||
});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
|
||||
webuiTls: { enabled: false },
|
||||
});
|
||||
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' }))
|
||||
.toThrow(/SNOWLUMA_WEBUI_TLS/);
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.14.19",
|
||||
"version": "1.14.22",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -272,6 +272,10 @@ export class ContactsApi {
|
||||
// is not in the list (0x88D_0 detail only), so it stays undefined here.
|
||||
createTime: raw.info?.createdTime ?? 0,
|
||||
memo: raw.info?.announcement || raw.info?.description || '',
|
||||
// #490: expose the description alongside `memo`. QQ fills in either
|
||||
// field alone, so folding both into `memo` made the description
|
||||
// unreachable whenever an announcement was also set.
|
||||
description: raw.info?.description ?? '',
|
||||
allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp),
|
||||
});
|
||||
}
|
||||
@@ -299,7 +303,9 @@ export class ContactsApi {
|
||||
memberMax: Number(r.maxMemberCount ?? 0n),
|
||||
members: new Map(),
|
||||
// #197: the detail is the only source of `level`; it also carries
|
||||
// createTime + the notice preview (memo).
|
||||
// createTime + the notice preview (memo). `description` is deliberately
|
||||
// left unset — 0x88D_0 has no description tag, so for a group the bot
|
||||
// hasn't joined there is nothing to report (#490).
|
||||
createTime: Number(r.createTime ?? 0n),
|
||||
level: Number(r.level ?? 0n),
|
||||
memo: r.noticePreview ?? '',
|
||||
|
||||
@@ -233,16 +233,9 @@ function previewFromElements(elements: MessageElement[]): string {
|
||||
|
||||
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
|
||||
return {
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
...node,
|
||||
elements,
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
innerForward: node.innerForward,
|
||||
news: node.news?.map(item => ({ ...item })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -478,23 +471,21 @@ export class ForwardApi {
|
||||
type: 'forward',
|
||||
resId: inner.resId,
|
||||
forwardUuid: inner.uuid,
|
||||
forwardSource: deriveInnerSource(node.innerForward, isGroup),
|
||||
forwardSummary: `查看${node.innerForward.length}条转发消息`,
|
||||
forwardPrompt: '[聊天记录]',
|
||||
forwardNews: previewLinesFromNodes(node.innerForward),
|
||||
forwardSource: node.source && node.source.length > 0
|
||||
? node.source
|
||||
: deriveInnerSource(node.innerForward, isGroup),
|
||||
forwardSummary: node.summary && node.summary.length > 0
|
||||
? node.summary
|
||||
: `查看${node.innerForward.length}条转发消息`,
|
||||
forwardPrompt: node.prompt && node.prompt.length > 0
|
||||
? node.prompt
|
||||
: '[聊天记录]',
|
||||
forwardNews: node.news && node.news.length > 0 ? node.news : previewLinesFromNodes(node.innerForward),
|
||||
forwardTSum: node.innerForward.length,
|
||||
};
|
||||
processedNodes.push({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [previewElement],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
});
|
||||
const processed = cloneNodeWithElements(node, [previewElement]);
|
||||
delete processed.innerForward;
|
||||
processedNodes.push(processed);
|
||||
} else {
|
||||
processedNodes.push(node);
|
||||
}
|
||||
@@ -548,14 +539,8 @@ export class ForwardApi {
|
||||
}
|
||||
|
||||
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: node.elements.map(cacheableForwardElement),
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
|
||||
groupId: node.groupId ?? groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
|
||||
})));
|
||||
|
||||
@@ -579,17 +564,7 @@ export class ForwardApi {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cached = forwardResCache.get(resId);
|
||||
if (cached) {
|
||||
const nodes = cached.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
const nodes = cloneNodes(cached);
|
||||
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
|
||||
// on read (a no-op once names are present) and persist so later hits skip.
|
||||
if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes));
|
||||
@@ -863,15 +838,5 @@ function cacheableForwardElement(element: MessageElement): MessageElement {
|
||||
}
|
||||
|
||||
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
|
||||
return nodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
return nodes.map(node => cloneNodeWithElements(node, [...node.elements]));
|
||||
}
|
||||
@@ -64,11 +64,8 @@ export class FriendApi {
|
||||
if (userId <= 0 && uid) {
|
||||
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
|
||||
}
|
||||
// Current Linux replies often omit the account id even though the
|
||||
// official decoder still reads it as a string. The approval packet
|
||||
// cannot accept a raw number, so fill from the same uin→uid path
|
||||
// used by ordinary friend requests. Cache-only lookup is not
|
||||
// enough: filtered applicants are not friends or group members.
|
||||
// Applicants need not be friends or share a group. Use Identity's
|
||||
// profile lookup when the list only supplies an account number.
|
||||
if (!uid && userId > 0) {
|
||||
try {
|
||||
uid = await this.ctx.resolveUserUid(userId);
|
||||
@@ -86,9 +83,11 @@ export class FriendApi {
|
||||
|
||||
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
|
||||
async approveDoubtRequest(uidOrFlag: string): Promise<void> {
|
||||
return ApproveDoubtBuddyReq.invoke(this.ctx, {
|
||||
uid: await this.resolveDoubtFlag(uidOrFlag),
|
||||
});
|
||||
log.trace('doubt-request approval: resolving applicant');
|
||||
const uid = await this.resolveDoubtFlag(uidOrFlag);
|
||||
log.trace('doubt-request approval: submitting request');
|
||||
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
log.trace('doubt-request approval: completed');
|
||||
}
|
||||
|
||||
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
|
||||
|
||||
@@ -31,6 +31,9 @@ import {
|
||||
type GroupMemberPermission,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-member-permission';
|
||||
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
|
||||
import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags';
|
||||
import { AddGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/add-group-category-tag';
|
||||
import { DeleteGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/delete-group-category-tag';
|
||||
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
|
||||
import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/modify-group-ext-info';
|
||||
import { OidbError } from '@snowluma/protocol/oidb-service';
|
||||
@@ -117,6 +120,18 @@ export class GroupAdminApi {
|
||||
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
|
||||
}
|
||||
|
||||
listCategoryTags(groupClass: number): Promise<{ tags: { id: number; name: string; type: number }[] }> {
|
||||
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
|
||||
}
|
||||
|
||||
addCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
removeCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
|
||||
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
AlbumCreator,
|
||||
@@ -179,7 +180,7 @@ export class GroupAlbumApi {
|
||||
body.length,
|
||||
);
|
||||
|
||||
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000);
|
||||
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs());
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(
|
||||
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
|
||||
@@ -297,7 +298,7 @@ export class GroupAlbumApi {
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
|
||||
body,
|
||||
15000,
|
||||
packetTimeoutMs(),
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
@@ -359,7 +360,7 @@ export class GroupAlbumApi {
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, 15000);
|
||||
const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, packetTimeoutMs());
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to comment on album media');
|
||||
@@ -431,7 +432,7 @@ export class GroupAlbumApi {
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
|
||||
body,
|
||||
15000,
|
||||
packetTimeoutMs(),
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
@@ -470,7 +471,7 @@ export class GroupAlbumApi {
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
|
||||
body,
|
||||
15000,
|
||||
packetTimeoutMs(),
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
@@ -571,7 +572,7 @@ export class GroupAlbumApi {
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, 15000);
|
||||
const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, packetTimeoutMs());
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to fetch album feed');
|
||||
}
|
||||
|
||||
@@ -412,6 +412,14 @@ export class MessageApi {
|
||||
}
|
||||
|
||||
const seq = response.groupSequence ?? 0;
|
||||
if (seq <= 0) {
|
||||
log.warn(
|
||||
'group message delivery unconfirmed: group=%d random=%d result=%s sequence=%s time=%s responseBytes=%d',
|
||||
groupId, random, response.result, response.groupSequence,
|
||||
response.timestamp1, result.responseData.length,
|
||||
);
|
||||
throw new Error('group message delivery was not confirmed: QQ returned no message receipt; check the conversation before retrying');
|
||||
}
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
return { messageId, sequence: seq, clientSequence: 0, random, timestamp };
|
||||
@@ -577,6 +585,7 @@ export class MessageApi {
|
||||
bridge: this.ctx as unknown as Bridge,
|
||||
userUid,
|
||||
scene: 'group-temp',
|
||||
tempGroupId: groupUin,
|
||||
});
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
@@ -180,6 +180,19 @@ export class ProfileApi {
|
||||
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
|
||||
}
|
||||
|
||||
/** Resolve an existing saved sticker by its resource id or content MD5. */
|
||||
async resolveCustomFace(identifier: string): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
|
||||
const wanted = identifier.trim();
|
||||
if (!wanted) throw new Error('custom face identifier is empty');
|
||||
const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
|
||||
const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted);
|
||||
const emojiId = ids.find((id) => byMd5
|
||||
? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase()
|
||||
: id === wanted);
|
||||
if (!emojiId) throw new Error('custom face is not in the saved sticker list');
|
||||
return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) };
|
||||
}
|
||||
|
||||
/** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */
|
||||
deleteCustomFace(emojiId: string): Promise<void> {
|
||||
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
@@ -296,7 +297,7 @@ export class Bridge implements BridgeInterface {
|
||||
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
|
||||
return this.msgRandom_ & 0x7FFFFFFF;
|
||||
}
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
return runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
// Side-effecting collaborators (config load, per-UIN channel ids, webhook POST,
|
||||
// SMTP send, the clock) are injected so the class is fully unit-testable; the
|
||||
// real wiring lives in `createNotificationManager()` at the bottom.
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig } from '@snowluma/onebot/config';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
@@ -262,7 +263,9 @@ export class NotificationManager {
|
||||
|
||||
/** Default outbound POST: a single attempt with a timeout, JSON content-type
|
||||
* (the common case for 钉钉/Discord/飞书). Never throws. */
|
||||
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
|
||||
export function createDefaultPost(
|
||||
timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS),
|
||||
): NotificationManagerDeps['post'] {
|
||||
return async (url, body, headers) => {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
|
||||
@@ -249,6 +249,63 @@ describe('apis/contacts / group roster', () => {
|
||||
expect(rememberGroups).toHaveBeenCalledWith(groups);
|
||||
});
|
||||
|
||||
// #490: `memo` prefers the announcement, so a group with both fields set used
|
||||
// to lose its description entirely. The description must stay readable.
|
||||
it('keeps the group description readable when an announcement is also set (#490)', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupListPacket({
|
||||
groups: [{
|
||||
groupUin: 123456789,
|
||||
info: {
|
||||
groupName: 'Both Set',
|
||||
description: '简介正文',
|
||||
announcement: '公告正文',
|
||||
},
|
||||
}],
|
||||
}));
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { rememberGroups: vi.fn() },
|
||||
} as any);
|
||||
|
||||
const [group] = await api.fetchGroupList();
|
||||
|
||||
expect(group?.memo).toBe('公告正文');
|
||||
expect(group?.description).toBe('简介正文');
|
||||
});
|
||||
|
||||
it('reports the description for a group that has no announcement (#490)', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupListPacket({
|
||||
groups: [{
|
||||
groupUin: 123456789,
|
||||
info: { groupName: 'Description Only', description: '只有简介' },
|
||||
}],
|
||||
}));
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { rememberGroups: vi.fn() },
|
||||
} as any);
|
||||
|
||||
const [group] = await api.fetchGroupList();
|
||||
|
||||
// memo still falls back to the description (unchanged pre-#490 behaviour).
|
||||
expect(group?.memo).toBe('只有简介');
|
||||
expect(group?.description).toBe('只有简介');
|
||||
});
|
||||
|
||||
it('leaves the description unset on a non-member detail lookup (#490)', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupDetailPacket({
|
||||
groupInfo: { uin: 123456789n, results: { name: 'Not Joined', noticePreview: '公告预览' } },
|
||||
}));
|
||||
const api = new ContactsApi({ sendRawPacket, identity: {} } as any);
|
||||
|
||||
const detail = await api.fetchGroupDetail(123456789);
|
||||
|
||||
// 0x88D_0 has no description tag, so there is nothing to expose — the field
|
||||
// must stay absent rather than echo the announcement preview.
|
||||
expect(detail?.memo).toBe('公告预览');
|
||||
expect(detail?.description).toBeUndefined();
|
||||
});
|
||||
|
||||
it('maps the group-wide mute timestamp from a single-group detail', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupDetailPacket({
|
||||
groupInfo: {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn() }));
|
||||
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn() }));
|
||||
vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn() }));
|
||||
|
||||
describe('forward metadata through upload and cached reads', () => {
|
||||
it.each([
|
||||
{ nested: false, enrich: false }, { nested: true, enrich: false },
|
||||
{ nested: false, enrich: true }, { nested: true, enrich: true },
|
||||
])('preserves titles and previews with nesting=$nested and enrichment=$enrich', async ({ nested, enrich }) => {
|
||||
let uploadCount = 0;
|
||||
const sendRawPacket = vi.fn(async () => ({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<SendLongMsgResp>({
|
||||
result: { resId: `metadata-${nested}-${enrich}-${++uploadCount}` },
|
||||
})),
|
||||
}));
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
bridge.apis.contacts.fetchGroupMemberList.mockResolvedValue([
|
||||
{ uin: 111, nickname: 'resolved outer', card: '' },
|
||||
]);
|
||||
const forward = new ForwardApi(bridge as any);
|
||||
const ctx = {
|
||||
selfId: 10001,
|
||||
bridge: { apis: {
|
||||
forward,
|
||||
message: { sendGroup: vi.fn(async () => ({
|
||||
messageId: 1, sequence: 2, clientSequence: 0, random: 3, timestamp: 1700000000,
|
||||
})) },
|
||||
} },
|
||||
messageStore: { findEvent: () => null, findMedia: () => null },
|
||||
cacheMessageMeta: vi.fn(),
|
||||
converterCtx: {
|
||||
selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null,
|
||||
messageIdResolver: null, mediaSegmentSink: null,
|
||||
},
|
||||
} as unknown as OneBotInstanceContext;
|
||||
const api = buildApiContext(ctx);
|
||||
const text = [{ type: 'text', data: { text: 'hello' } }];
|
||||
const preview = {
|
||||
title: 'outer title', source: 'custom source', summary: 'custom summary',
|
||||
prompt: 'custom prompt', news: [{ text: 'custom preview' }],
|
||||
};
|
||||
const { forwardId } = await api.sendGroupForwardMsg(12345, [{
|
||||
type: 'node', data: {
|
||||
user_id: 111, nickname: enrich ? '' : 'outer', ...preview,
|
||||
content: nested
|
||||
? [{ type: 'node', data: { user_id: 222, nickname: 'inner', title: 'inner title', content: text } }]
|
||||
: text,
|
||||
},
|
||||
}]);
|
||||
|
||||
const first = await api.getForwardMsg(forwardId);
|
||||
expect(first[0]!.sender).toMatchObject({ title: 'outer title' });
|
||||
expect(first[0]!.sender).toMatchObject({ nickname: enrich ? 'resolved outer' : 'outer' });
|
||||
expect((await forward.fetch(forwardId!))[0]).toMatchObject(preview);
|
||||
if (nested) {
|
||||
expect((await api.getForwardMsg(`metadata-true-${enrich}-1`))[0]!.sender)
|
||||
.toMatchObject({ title: 'inner title' });
|
||||
}
|
||||
|
||||
const fetched = await forward.fetch(forwardId!);
|
||||
fetched[0]!.title = 'changed title';
|
||||
fetched[0]!.news![0]!.text = 'changed preview';
|
||||
preview.news[0]!.text = 'changed input';
|
||||
const again = await forward.fetch(forwardId!);
|
||||
expect(again[0]!.title).toBe('outer title');
|
||||
expect(again[0]!.news).toEqual([{ text: 'custom preview' }]);
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(nested ? 2 : 1);
|
||||
});
|
||||
});
|
||||
@@ -59,7 +59,7 @@ function decodeOuterLongMsg(rawBytes: Uint8Array): LongMsgResult {
|
||||
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
|
||||
}
|
||||
|
||||
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string } | null {
|
||||
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string; news?: Array<{ text: string }>; source?: string; summary?: string } | null {
|
||||
for (const body of msgBody) {
|
||||
const elems: Elem[] = body.body?.richText?.elems ?? [];
|
||||
for (const elem of elems) {
|
||||
@@ -74,6 +74,9 @@ function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: st
|
||||
app: parsed.app,
|
||||
resid: parsed.meta?.detail?.resid,
|
||||
uniseq: parsed.meta?.detail?.uniseq,
|
||||
news: parsed.meta?.detail?.news,
|
||||
source: parsed.meta?.detail?.source,
|
||||
summary: parsed.meta?.detail?.summary,
|
||||
};
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
@@ -178,4 +181,86 @@ describe('forward / nested upload wire alignment', () => {
|
||||
expect(outermost.action![2]!.actionCommand).not.toBe('MultiMsg');
|
||||
expect(outermost.action![1]!.actionCommand).not.toBe(outermost.action![2]!.actionCommand);
|
||||
});
|
||||
|
||||
it('inner forward bubble prefers caller-supplied node news over auto-generated lines', async () => {
|
||||
const responses = ['inner-res', 'outer-res'];
|
||||
const sendRawPacket = vi.fn(async () =>
|
||||
uploadResponseWithResId(responses.shift()!)) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
const customNews = [{ text: '自定义预览行 1' }, { text: '自定义预览行 2' }];
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 111,
|
||||
nickname: 'outer',
|
||||
elements: [],
|
||||
news: customNews,
|
||||
innerForward: [
|
||||
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: '会被覆盖的正文' }] },
|
||||
],
|
||||
}]);
|
||||
|
||||
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
|
||||
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
|
||||
const preview = findLightAppJson(outerMsgBody);
|
||||
|
||||
expect(preview).not.toBeNull();
|
||||
// Caller-supplied news wins over `inner: 会被覆盖的正文`.
|
||||
expect(preview!.news).toEqual(customNews);
|
||||
});
|
||||
|
||||
it('inner forward bubble falls back to auto-generated lines when node has no news', async () => {
|
||||
const responses = ['inner-res', 'outer-res'];
|
||||
const sendRawPacket = vi.fn(async () =>
|
||||
uploadResponseWithResId(responses.shift()!)) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 111,
|
||||
nickname: 'outer',
|
||||
elements: [],
|
||||
// no `news` field — auto-generate from inner nodes
|
||||
innerForward: [
|
||||
{ userUin: 222, nickname: '内层说话人', elements: [{ type: 'text', text: '第一句台词' }] },
|
||||
],
|
||||
}]);
|
||||
|
||||
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
|
||||
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
|
||||
const preview = findLightAppJson(outerMsgBody);
|
||||
|
||||
expect(preview).not.toBeNull();
|
||||
expect(preview!.news).toEqual([{ text: '内层说话人: 第一句台词' }]);
|
||||
});
|
||||
|
||||
it('inner forward card prefers caller-supplied source/summary/prompt metadata', async () => {
|
||||
const responses = ['inner-res', 'outer-res'];
|
||||
const sendRawPacket = vi.fn(async () =>
|
||||
uploadResponseWithResId(responses.shift()!)) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 111,
|
||||
nickname: 'outer',
|
||||
elements: [],
|
||||
source: '万叶的手记',
|
||||
summary: '共 12 条剧情消息',
|
||||
prompt: '查看剧情',
|
||||
innerForward: [
|
||||
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
|
||||
],
|
||||
}]);
|
||||
|
||||
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
|
||||
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
|
||||
const preview = findLightAppJson(outerMsgBody);
|
||||
|
||||
expect(preview).not.toBeNull();
|
||||
// decodeOuterLongMsg → lightApp meta.detail as built by element-builder
|
||||
expect(preview!.app).toBe('com.tencent.multimsg');
|
||||
// The plaintext preview lines of the wire bubble.
|
||||
// Caller metadata wins: source = 万叶的手记, summary used instead of
|
||||
// the auto-generated `查看N条转发消息`.
|
||||
expect(preview!.source).toBe('万叶的手记');
|
||||
expect(preview!.summary).toBe('共 12 条剧情消息');
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ import type {
|
||||
// against the bridge mock's sendRawPacket directly — no need for
|
||||
// module-level bridge-oidb mocks anymore.
|
||||
import { DATALINE_UIN_PAD } from '@snowluma/protocol/dataline/device-contacts';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { FriendApi } from '../../src/bridge/apis/friend';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
@@ -183,9 +184,9 @@ describe('apis/friend', () => {
|
||||
await new FriendApi(bridge as any).approveDoubtRequest('12345');
|
||||
expect(bridge.resolveUserUid).toHaveBeenCalledWith(12345);
|
||||
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
expect(cmd).toBe('OidbSvcTrpcTcp.0xd69_0');
|
||||
expect(cmd).toBe('OidbSvcTrpcTcp.0xd72_0');
|
||||
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
|
||||
expect(env.body).toMatchObject({ uid: 'resolved-uid', targetUid: 'resolved-uid' });
|
||||
expect(env.body).toMatchObject({ selfUid: 'self-uid', targetUid: 'resolved-uid', field3: 0, field4: '' });
|
||||
});
|
||||
|
||||
it('approveDoubtRequest forwards a uid flag without resolving', async () => {
|
||||
@@ -194,7 +195,37 @@ describe('apis/friend', () => {
|
||||
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
|
||||
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
|
||||
expect(env.body).toMatchObject({ uid: 'u_abc', targetUid: 'u_abc' });
|
||||
expect(env.body).toMatchObject({ selfUid: 'self-uid', targetUid: 'u_abc' });
|
||||
});
|
||||
|
||||
it('approves a filtered stranger through Identity without requiring a shared roster', async () => {
|
||||
const identity = new IdentityService('10001', null);
|
||||
const bridge = mockBridge();
|
||||
const fetchProfile = vi.fn(async (uin: number) => ({
|
||||
uin, uid: uin === 10001 ? 'u_self' : 'u_stranger',
|
||||
}));
|
||||
identity.setFetcher({ fetchProfile: fetchProfile as any });
|
||||
bridge.identity = identity as any;
|
||||
bridge.resolveUserUid = vi.fn((uin: number) => identity.resolveUid(uin));
|
||||
try {
|
||||
await new FriendApi(bridge as any).approveDoubtRequest('12345');
|
||||
expect(fetchProfile.mock.calls.map(([uin]) => uin)).toEqual([12345, 10001]);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
|
||||
expect(env.body).toMatchObject({ selfUid: 'u_self', targetUid: 'u_stranger' });
|
||||
} finally {
|
||||
identity.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not send an approval when the applicant cannot be resolved', async () => {
|
||||
const bridge = mockBridge({
|
||||
resolveUserUid: vi.fn(async () => { throw new Error('applicant lookup failed'); }),
|
||||
});
|
||||
await expect(new FriendApi(bridge as any).approveDoubtRequest('12345'))
|
||||
.rejects.toThrow('applicant lookup failed');
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejectDoubtRequest resolves a digit-only flag before sending', async () => {
|
||||
|
||||
@@ -23,6 +23,11 @@ import type {
|
||||
OidbSetAdmin,
|
||||
OidbSpecialTitle,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type {
|
||||
OidbChangeGroupCategoryTag,
|
||||
OidbGetGroupCategoryTags,
|
||||
OidbGetGroupCategoryTagsResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-category-tag';
|
||||
|
||||
// Post-namespace migration: GroupAdminApi forwards through namespaces
|
||||
// under @snowluma/protocol/oidb-services/group-admin. Tests assert
|
||||
@@ -705,4 +710,54 @@ describe('apis/group-admin', () => {
|
||||
remain_at_all_count_for_uin: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('lists category tags and keeps category 0 on the wire', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({
|
||||
body: { tags: [{ id: 7, name: '学习', type: 1 }, { name: '未编号' }] },
|
||||
}),
|
||||
));
|
||||
|
||||
const out = await new GroupAdminApi(bridge as any).listCategoryTags(0);
|
||||
expect(out).toEqual({
|
||||
tags: [
|
||||
{ id: 7, name: '学习', type: 1 },
|
||||
{ id: 0, name: '未编号', type: 0 },
|
||||
],
|
||||
});
|
||||
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x967c_0');
|
||||
const env = protobuf_decode<OidbBase<OidbGetGroupCategoryTags>>(bridge.sendRawPacket.mock.calls[0]![1]);
|
||||
expect(env.command).toBe(0x967C);
|
||||
expect(env.body?.groupClass).toBe(0);
|
||||
});
|
||||
|
||||
it('returns an empty tag list when the category has none', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({ body: {} }),
|
||||
));
|
||||
await expect(new GroupAdminApi(bridge as any).listCategoryTags(2)).resolves.toEqual({ tags: [] });
|
||||
});
|
||||
|
||||
it('adds and removes a category tag by its name', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new GroupAdminApi(bridge as any).addCategoryTag(3, ' 户外 ');
|
||||
await new GroupAdminApi(bridge as any).removeCategoryTag(3, '户外');
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
|
||||
'OidbSvcTrpcTcp.0x967d_0',
|
||||
'OidbSvcTrpcTcp.0x967e_0',
|
||||
]);
|
||||
const added = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[0]![1]);
|
||||
expect(added.body).toMatchObject({ groupClass: 3, name: ' 户外 ' });
|
||||
const removed = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[1]![1]);
|
||||
expect(removed.body).toMatchObject({ groupClass: 3, name: '户外' });
|
||||
});
|
||||
|
||||
it('refuses an empty tag name instead of sending it', async () => {
|
||||
const bridge = mockBridge();
|
||||
await expect(new GroupAdminApi(bridge as any).addCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
|
||||
await expect(new GroupAdminApi(bridge as any).removeCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeContext } from '../../src/bridge/bridge-context';
|
||||
import { MessageApi } from '../../src/bridge/apis/message';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function sender(responseHex: string) {
|
||||
const ctx = {
|
||||
...mockBridge(),
|
||||
nextMessageRandom: () => 1234,
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(responseHex, 'hex'),
|
||||
})),
|
||||
};
|
||||
return { api: new MessageApi(ctx as unknown as BridgeContext), send: ctx.sendRawPacket };
|
||||
}
|
||||
|
||||
describe('group send receipts (#492)', () => {
|
||||
it('accepts the confirmed response from the issue log', async () => {
|
||||
const { api } = sender('080018abb3e8d506500058844a60abb3e8d506700078df0d');
|
||||
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }])).resolves.toMatchObject({
|
||||
sequence: 9476, messageId: 1234,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['missing', '080018c9b3e8d506500060c9b3e8d5067000'],
|
||||
['zero', '08005800'],
|
||||
])('rejects a %s receipt without automatically resending', async (_name, response) => {
|
||||
const { api, send } = sender(response);
|
||||
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }]))
|
||||
.rejects.toThrow('group message delivery was not confirmed');
|
||||
expect(send).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('preserves an explicit server rejection', async () => {
|
||||
const { api } = sender('0801');
|
||||
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }]))
|
||||
.rejects.toThrow('send group message rejected: result=1');
|
||||
});
|
||||
});
|
||||
@@ -334,6 +334,24 @@ describe('apis/profile', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(['resource', 'md5'])('resolves a saved sticker by %s without fetching every description', async (kind) => {
|
||||
const bridge = mockBridge();
|
||||
const md5 = 'ABCDEF0123456789ABCDEF0123456789';
|
||||
const emojiId = `10001_0_0_0_${md5}_0_0`;
|
||||
bridge.sendRawPacket.mockResolvedValue({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({ item: { faceIds: [emojiId] } })),
|
||||
} as any);
|
||||
const api = new ProfileApi(bridge as any);
|
||||
expect(await api.resolveCustomFace(kind === 'md5' ? md5.toLowerCase() : emojiId)).toEqual({
|
||||
emojiId, md5, url: `https://p.qpic.cn/qq_expression/10001/${emojiId}/0`,
|
||||
});
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
await expect(api.resolveCustomFace('missing')).rejects.toThrow(/not in the saved sticker list/);
|
||||
await expect(api.resolveCustomFace(' ')).rejects.toThrow(/identifier is empty/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('rejects a negative custom-face count before sending', async () => {
|
||||
const bridge = mockBridge();
|
||||
await expect(new ProfileApi(bridge as any).fetchCustomFaceIds(-1)).rejects.toThrow(
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { inflateSync } from 'zlib';
|
||||
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/image-upload', () => ({
|
||||
uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])),
|
||||
@@ -294,6 +295,7 @@ describe('element-builder / all-message validation preflight', () => {
|
||||
true,
|
||||
12345,
|
||||
expect.objectContaining({ imageUrl: 'https://gchat.qpic.cn/received.jpg' }),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -346,26 +348,25 @@ describe('element-builder / file element is no longer carried in elems[]', () =>
|
||||
});
|
||||
});
|
||||
|
||||
describe('element-builder / forward preview (com.tencent.multimsg LightApp)', () => {
|
||||
// The forward preview is the bubble the recipient renders in chat
|
||||
// before tapping to expand. It MUST be the modern LightApp /
|
||||
// `com.tencent.multimsg` JSON (not the older `richMsg serviceID=35`
|
||||
// XML) because nested forwards rely on `meta.detail.uniseq` to link
|
||||
// each inner preview to the matching `actionCommand` piggyback on
|
||||
// the outer's LongMsgResult — without uniseq the QQ-NT client has
|
||||
// no way to walk the tree and has to re-fetch each inner resId.
|
||||
describe('element-builder / forward preview', () => {
|
||||
// Flat outer forwards use the serviceID=35 RichMsg shape accepted by NTQQ.
|
||||
// Nested previews keep the modern LightApp JSON because their
|
||||
// meta.detail.uniseq must match an actionCommand piggyback in the outer
|
||||
// LongMsgResult.
|
||||
function decodeLightApp(elem: any): unknown {
|
||||
return JSON.parse(inflatePrefixedPayload(elem.lightApp.data));
|
||||
}
|
||||
|
||||
it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => {
|
||||
it('emits a serviceID=35 richMsg XML for a flat outer forward', async () => {
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'forward', resId: 'res-XYZ' } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
expect(elem.lightApp).toBeDefined();
|
||||
expect((elem as any).richMsg).toBeUndefined();
|
||||
expect(elem.lightApp!.data![0]).toBe(0x01);
|
||||
expect(elem.richMsg?.serviceId).toBe(35);
|
||||
expect(elem.lightApp).toBeUndefined();
|
||||
const xml = inflatePrefixedPayload(elem.richMsg!.template1!);
|
||||
expect(xml).toContain('action="viewMultiMsg"');
|
||||
expect(xml).toContain('m_resid="res-XYZ"');
|
||||
});
|
||||
|
||||
it('places resid + uniseq inside meta.detail (and uniseq matches extra.filename)', async () => {
|
||||
@@ -373,6 +374,8 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', ()
|
||||
[{ type: 'forward', resId: 'res-XYZ', forwardUuid: 'fixed-uuid-1234' } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
expect(elem.lightApp).toBeDefined();
|
||||
expect(elem.richMsg).toBeUndefined();
|
||||
const json = decodeLightApp(elem) as any;
|
||||
expect(json.app).toBe('com.tencent.multimsg');
|
||||
expect(json.meta.detail.resid).toBe('res-XYZ');
|
||||
@@ -383,17 +386,87 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', ()
|
||||
expect(extra.filename).toBe('fixed-uuid-1234');
|
||||
});
|
||||
|
||||
it('autogenerates a uniseq when the element omits forwardUuid (flat forward — cosmetic)', async () => {
|
||||
it('autogenerates m_fileName for a flat outer forward', async () => {
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'forward', resId: 'res-flat' } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
const json = decodeLightApp(elem) as any;
|
||||
expect(json.meta.detail.resid).toBe('res-flat');
|
||||
// Auto-generated UUID — non-empty, non-trivial.
|
||||
expect(json.meta.detail.uniseq).toMatch(/^[0-9a-f-]{36}$/i);
|
||||
const extra = JSON.parse(json.extra);
|
||||
expect(extra.filename).toBe(json.meta.detail.uniseq);
|
||||
const xml = inflatePrefixedPayload(elem.richMsg!.template1!);
|
||||
expect(xml).toContain('m_resid="res-flat"');
|
||||
expect(xml).toMatch(/m_fileName="[0-9a-f-]{36}"/i);
|
||||
});
|
||||
|
||||
it('escapes dynamic XML fields in a flat outer forward', async () => {
|
||||
const [elem] = await buildSendElems(
|
||||
[{
|
||||
type: 'forward',
|
||||
resId: 'res&<>"\'',
|
||||
forwardSource: 'Alice & <Bob>',
|
||||
forwardSummary: 'summary "quoted" & more',
|
||||
forwardPrompt: '[A & B]',
|
||||
forwardNews: [
|
||||
{ text: 'Alice: <hello>' },
|
||||
{ text: 'Bob: it\'s "ok"' },
|
||||
],
|
||||
forwardTSum: 2,
|
||||
} as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
const xml = inflatePrefixedPayload(elem.richMsg!.template1!);
|
||||
expect(xml).toContain('m_resid="res&<>"'"');
|
||||
expect(xml).toContain('brief="[A & B]"');
|
||||
expect(xml).toContain('Alice & <Bob>');
|
||||
expect(xml).toContain('summary "quoted" & more');
|
||||
expect(xml).toContain('Alice: <hello>');
|
||||
expect(xml).toContain('Bob: it's "ok"');
|
||||
expect(xml).toContain('tSum="2"');
|
||||
});
|
||||
|
||||
it('normalizes only unsupported preview characters and records the affected fields', async () => {
|
||||
const logs: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs(entry => logs.push(entry));
|
||||
const element = {
|
||||
type: 'forward' as const,
|
||||
resId: 'preview-controls',
|
||||
forwardSource: 'source\u0000',
|
||||
forwardSummary: 'summary\uFFFE',
|
||||
forwardPrompt: 'prompt\uFFFF',
|
||||
forwardNews: [{ text: 'a\u0001b\u000Bc\u001Fd\uD800e\uDC00f😀中文\t\n\r' }],
|
||||
};
|
||||
const original = structuredClone(element);
|
||||
try {
|
||||
const [elem] = await buildSendElems([element], { bridge: fakeBridge, groupId: 12345 });
|
||||
const xml = inflatePrefixedPayload(elem.richMsg!.template1!);
|
||||
expect(xml).toContain('brief="prompt�"');
|
||||
expect(xml).toContain('source�</title>');
|
||||
expect(xml).toContain('summary�</summary>');
|
||||
expect(xml).toContain('a�b�c�d�e�f😀中文	

</title>');
|
||||
expect(element).toEqual(original);
|
||||
expect(logs.filter(entry => entry.message.startsWith('forward preview characters normalized:'))
|
||||
.map(entry => entry.message)).toEqual([
|
||||
'forward preview characters normalized: field=source',
|
||||
'forward preview characters normalized: field=news[0]',
|
||||
'forward preview characters normalized: field=prompt',
|
||||
'forward preview characters normalized: field=summary',
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an unrepresentable resource reference instead of rewriting its identity', async () => {
|
||||
await expect(buildSendElems([{ type: 'forward', resId: 'res\u0001id' }], {
|
||||
bridge: fakeBridge, groupId: 12345,
|
||||
})).rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'forward', field: 'resId' });
|
||||
});
|
||||
|
||||
it('preserves valid Unicode boundaries and whitespace in preview text', async () => {
|
||||
const text = '\u0009\u000A\u000D\u0020\uD7FF\uE000\uFFFD\u{10000}\u{10FFFF}';
|
||||
const [elem] = await buildSendElems([{ type: 'forward', resId: 'valid-unicode', forwardNews: [{ text }] }], {
|
||||
bridge: fakeBridge, groupId: 12345,
|
||||
});
|
||||
expect(inflatePrefixedPayload(elem.richMsg!.template1!))
|
||||
.toContain('	

 \uD7FF\uE000\uFFFD\u{10000}\u{10FFFF}</title>');
|
||||
});
|
||||
|
||||
it('threads forwardSource / forwardSummary / forwardPrompt / forwardNews / forwardTSum verbatim', async () => {
|
||||
|
||||
@@ -302,6 +302,27 @@ describe('fetchHighwaySession trace lifecycle', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps a server address encoded as a fixed 32-bit field', async () => {
|
||||
// Address field 2 is four raw bytes. The fixture is not produced by the
|
||||
// schema encoder, so a varint declaration cannot hide itself.
|
||||
const responseData = Buffer.from('8a50150a02aabb1201cc1a0c08011208150102030418903f', 'hex');
|
||||
const bridge = {
|
||||
identity: { uin: '10001' },
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData,
|
||||
})),
|
||||
} as unknown as BridgeContext;
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
|
||||
expect(session.host).toBe('1.2.3.4');
|
||||
expect(session.port).toBe(8080);
|
||||
});
|
||||
|
||||
it('records a thrown control request as one failed terminal', async () => {
|
||||
const bridge = {
|
||||
identity: { uin: '10001' },
|
||||
|
||||
@@ -45,8 +45,8 @@ describe('image-upload', () => {
|
||||
expect(args.businessType).toBe(1);
|
||||
expect(args.compatQmsgSceneType).toBe(2);
|
||||
expect(args.uploads[0]!.cmdId).toBe(GROUP_IMAGE_CMD_ID);
|
||||
expect((args.extBizInfo as any).pic.reserveTroop).toBeDefined();
|
||||
expect((args.extBizInfo as any).pic.reserveC2c).toBeUndefined();
|
||||
expect(args.extBizInfo.pic?.extData).toBeDefined();
|
||||
expect(args.extBizInfo.pic?.bytesPbReserveC2c).toBeUndefined();
|
||||
});
|
||||
|
||||
it('c2c: uses 0x11C5_100 + PRIVATE_IMAGE_CMD_ID and tags scene as c2c', async () => {
|
||||
@@ -56,8 +56,8 @@ describe('image-upload', () => {
|
||||
expect(args.serviceCmd).toBe('OidbSvcTrpcTcp.0x11c5_100');
|
||||
expect(args.compatQmsgSceneType).toBe(1);
|
||||
expect(args.uploads[0]!.cmdId).toBe(PRIVATE_IMAGE_CMD_ID);
|
||||
expect((args.extBizInfo as any).pic.reserveC2c).toBeDefined();
|
||||
expect((args.extBizInfo as any).pic.reserveTroop).toBeUndefined();
|
||||
expect(args.extBizInfo.pic?.bytesPbReserveC2c).toBeDefined();
|
||||
expect(args.extBizInfo.pic?.extData).toBeUndefined();
|
||||
});
|
||||
|
||||
it('uses receive-side imageUrl when url/fileId are absent', async () => {
|
||||
@@ -110,7 +110,7 @@ describe('image-upload', () => {
|
||||
await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x', subType: 0 } as any);
|
||||
expect(pipeline.finalizeMediaMsgInfo).toHaveBeenCalledOnce();
|
||||
const [, defaultPic] = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!;
|
||||
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[图片]' });
|
||||
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[图片]', extData: { subType: 0, textSummary: '[图片]' } });
|
||||
});
|
||||
|
||||
it('caller-supplied summary wins over the Chinese default', async () => {
|
||||
@@ -120,6 +120,6 @@ describe('image-upload', () => {
|
||||
url: 'http://x', subType: 0, summary: '[custom-bubble]',
|
||||
} as any);
|
||||
const [, defaultPic] = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!;
|
||||
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[custom-bubble]' });
|
||||
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[custom-bubble]', extData: { subType: 0, textSummary: '[custom-bubble]' } });
|
||||
});
|
||||
});
|
||||
@@ -2,8 +2,8 @@
|
||||
// regular load path goes through ffmpeg's silk encoder + the OS temp
|
||||
// directory, which we don't want to exercise in a unit test. The
|
||||
// fingerprint path covers most of what makes ptt-upload distinct
|
||||
// (group/c2c requestId difference, command id mapping, NapCat-style
|
||||
// bytesGeneralFlags, voiceFormat honouring).
|
||||
// (group/c2c requestId difference, command id mapping, the group-only
|
||||
// bytesGeneralFlags blob, voiceFormat honouring).
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
@@ -30,6 +30,15 @@ describe('ptt-upload', () => {
|
||||
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
|
||||
});
|
||||
|
||||
it('retains successful upload metadata for self-sent history', async () => {
|
||||
const node = { fileUuid: 'uploaded-resource', storeId: 1, info: { fileSize: 1234 } };
|
||||
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
|
||||
const element = { ...FINGERPRINT };
|
||||
await uploadPttMsgInfo({} as any, true, 12345, element);
|
||||
expect(element).toMatchObject({ fileId: 'uploaded-resource', mediaNode: node, md5Hex: 'aa', sha1Hex: 'bb' });
|
||||
expect(element.fileName).toBeTruthy();
|
||||
});
|
||||
|
||||
it('group: 0x126E_100 + GROUP_PTT_CMD_ID + group-flavored bytesGeneralFlags', async () => {
|
||||
await uploadPttMsgInfo({} as any, true, 12345, FINGERPRINT);
|
||||
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
|
||||
@@ -45,7 +54,7 @@ describe('ptt-upload', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('c2c: 0x126D_100 + PRIVATE_PTT_CMD_ID + requestId=4 + c2c-flavored flags', async () => {
|
||||
it('c2c: 0x126D_100 + PRIVATE_PTT_CMD_ID + requestId=4 + no generalFlags', async () => {
|
||||
await uploadPttMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
|
||||
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
|
||||
expect(args.oidbCmd).toBe(0x126D);
|
||||
@@ -53,10 +62,14 @@ describe('ptt-upload', () => {
|
||||
expect(args.requestId).toBe(4);
|
||||
expect(args.uploads[0]!.cmdId).toBe(PRIVATE_PTT_CMD_ID);
|
||||
|
||||
const c2cFlags = (args.extBizInfo as any).ptt.bytesGeneralFlags;
|
||||
expect(c2cFlags.length).toBe(14);
|
||||
expect(c2cFlags[0]).toBe(0x9a);
|
||||
// Private voice must not carry a generalFlags blob: with the NapCat c2c
|
||||
// one present the receiver drops the progress bar even though the waveform
|
||||
// is in the payload. Group keeps its 10-byte blob (covered above).
|
||||
expect((args.extBizInfo as any).ptt.bytesGeneralFlags).toBeUndefined();
|
||||
expect((args.extBizInfo as any).ptt.waveform).toBeUndefined();
|
||||
|
||||
// Reserve stays the bare legacy 4 bytes, same as group voice.
|
||||
expect([...(args.extBizInfo as any).ptt.bytesReserve]).toEqual([0x08, 0x00, 0x38, 0x00]);
|
||||
});
|
||||
|
||||
it('fingerprint path does not invent a waveform', async () => {
|
||||
|
||||
@@ -49,6 +49,15 @@ describe('video-upload', () => {
|
||||
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
|
||||
});
|
||||
|
||||
it('retains successful upload metadata for self-sent history', async () => {
|
||||
const node = { fileUuid: 'uploaded-resource', storeId: 1, info: { fileSize: 1234 } };
|
||||
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
|
||||
const element = { ...FINGERPRINT };
|
||||
await uploadVideoMsgInfo({} as any, true, 12345, element);
|
||||
expect(element).toMatchObject({ fileId: 'uploaded-resource', mediaNode: node, md5Hex: 'aa', sha1Hex: 'bb' });
|
||||
expect(element.fileName).toBeTruthy();
|
||||
});
|
||||
|
||||
it('group: 0x11EA_100 + GROUP_VIDEO_CMD_ID for main, GROUP_VIDEO_THUMB_CMD_ID for thumb', async () => {
|
||||
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
|
||||
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
NotificationManager,
|
||||
createDefaultPost,
|
||||
selectChannels,
|
||||
type MailPayload,
|
||||
type NotificationManagerDeps,
|
||||
@@ -321,3 +322,28 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
|
||||
expect(events).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createDefaultPost timeout', () => {
|
||||
const name = 'SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS';
|
||||
const saved = process.env[name];
|
||||
|
||||
afterEach(() => {
|
||||
if (saved === undefined) delete process.env[name];
|
||||
else process.env[name] = saved;
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('uses SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', async () => {
|
||||
process.env[name] = '1234';
|
||||
const seen: number[] = [];
|
||||
const timeout = AbortSignal.timeout.bind(AbortSignal);
|
||||
vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms: number) => {
|
||||
seen.push(ms);
|
||||
return timeout(50);
|
||||
});
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200 })));
|
||||
const post = createDefaultPost();
|
||||
await post('http://127.0.0.1/hook', '{}');
|
||||
expect(seen).toEqual([1234]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { RoutingHead, SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { NTV2C2CUserInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
|
||||
const png = 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jFZkAAAAASUVORK5CYII=';
|
||||
|
||||
function fixture(rejectUpload = false) {
|
||||
const requests: Array<{ command: string; body: Uint8Array }> = [];
|
||||
class TestBridge extends Bridge {
|
||||
override async resolveUserUid(): Promise<string> { return 'u_peer'; }
|
||||
|
||||
override async sendRawPacket(command: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
requests.push({ command, body });
|
||||
let response: Uint8Array;
|
||||
if (command === 'OidbSvcTrpcTcp.0x11c5_100') {
|
||||
response = protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
|
||||
command: 0x11c5, subCommand: 100,
|
||||
errorCode: rejectUpload ? 170019003 : 0,
|
||||
errorMsg: rejectUpload ? 'verify identify fail' : '',
|
||||
body: { upload: { msgInfo: { msgInfoBody: [{ index: { fileUuid: 'cached-image' } }] } } },
|
||||
});
|
||||
} else if (command === 'MessageSvc.PbSendMsg') {
|
||||
response = protobuf_encode<SendMessageResponse>({ result: 0, privateSequence: 88 });
|
||||
} else {
|
||||
throw new Error(`unexpected packet: ${command}`);
|
||||
}
|
||||
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.from(response) };
|
||||
}
|
||||
}
|
||||
return { bridge: new TestBridge(IdentityService.memory('10000')), requests };
|
||||
}
|
||||
|
||||
describe('passive temp-session image wire request (#471)', () => {
|
||||
it('uses the same existing-session route for image upload and the final message', async () => {
|
||||
const { bridge, requests } = fixture();
|
||||
await bridge.apis.message.sendGroupTempMessage(1001, 700, [
|
||||
{ type: 'text', text: 'reply' },
|
||||
{ type: 'image', url: png },
|
||||
]);
|
||||
|
||||
expect(requests.map((r) => r.command)).toEqual([
|
||||
'OidbSvcTrpcTcp.0x11c5_100', 'MessageSvc.PbSendMsg',
|
||||
]);
|
||||
const upload = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(requests[0]!.body).body!;
|
||||
expect(upload.reqHead?.scene).toMatchObject({
|
||||
sceneType: 1, businessType: 1, c2c: { accountType: 2, targetUid: 'u_peer' },
|
||||
});
|
||||
expect(upload.reqHead?.scene?.group ?? undefined).toBeUndefined();
|
||||
const route = upload.reqHead!.scene!.c2c!.routingHead!;
|
||||
expect(Array.from(route)).toEqual([
|
||||
0x1a, 0x0b, 0x18, 0xbc, 0x05, 0x22, 0x06, 0x75, 0x5f, 0x70, 0x65, 0x65, 0x72,
|
||||
]);
|
||||
expect(Array.from(protobuf_encode<NTV2C2CUserInfo>(upload.reqHead!.scene!.c2c!))).toEqual([
|
||||
0x08, 0x02, 0x12, 0x06, 0x75, 0x5f, 0x70, 0x65, 0x65, 0x72,
|
||||
0x1a, 0x0d, 0x1a, 0x0b, 0x18, 0xbc, 0x05, 0x22, 0x06, 0x75, 0x5f, 0x70, 0x65, 0x65, 0x72,
|
||||
]);
|
||||
const sent = protobuf_decode<SendMessageRequest>(requests[1]!.body);
|
||||
expect(protobuf_decode<RoutingHead>(route)).toEqual(sent.routingHead);
|
||||
expect(sent.routingHead?.grpTmp).toEqual({ groupUin: 700n, toUid: 'u_peer' });
|
||||
expect(sent.messageBody?.richText?.elems).toEqual([
|
||||
expect.objectContaining({ text: expect.objectContaining({ str: 'reply' }) }),
|
||||
expect.objectContaining({ commonElem: expect.objectContaining({ serviceType: 48, businessType: 10 }) }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps normal private image uploads free of temp-session context', async () => {
|
||||
const { bridge, requests } = fixture();
|
||||
await bridge.apis.message.sendPrivate(1001, [{ type: 'image', url: png }]);
|
||||
const upload = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(requests[0]!.body).body!;
|
||||
expect(upload.reqHead?.scene?.c2c?.routingHead ?? undefined).toBeUndefined();
|
||||
const sent = protobuf_decode<SendMessageRequest>(requests[1]!.body);
|
||||
expect(sent.routingHead?.grpTmp ?? undefined).toBeUndefined();
|
||||
});
|
||||
|
||||
it('propagates upload rejection without sending text or retrying as another conversation', async () => {
|
||||
const { bridge, requests } = fixture(true);
|
||||
await expect(bridge.apis.message.sendGroupTempMessage(1001, 700, [
|
||||
{ type: 'text', text: 'must not be sent separately' },
|
||||
{ type: 'image', url: png },
|
||||
])).rejects.toThrow('verify identify fail');
|
||||
expect(requests.map((r) => r.command)).toEqual(['OidbSvcTrpcTcp.0x11c5_100']);
|
||||
});
|
||||
|
||||
it('rejects missing source context before reading the image or sending any packet', async () => {
|
||||
const { bridge, requests } = fixture();
|
||||
const fetch = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('must not download image'));
|
||||
try {
|
||||
await expect(buildSendElems([{ type: 'image', url: 'https://must-not-fetch.invalid/image.png' }], {
|
||||
bridge, scene: 'group-temp', userUid: 'u_peer',
|
||||
})).rejects.toThrow('temp-session image source group is missing');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(requests).toEqual([]);
|
||||
} finally { fetch.mockRestore(); }
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "1.14.19",
|
||||
"version": "1.14.22",
|
||||
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -440,6 +440,54 @@
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "add_group_tag",
|
||||
"aliases": [],
|
||||
"summary": "向某个群分类添加资料标签",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
"name": "group_class",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_class": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_class",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群管理"
|
||||
},
|
||||
{
|
||||
"name": "bot_exit",
|
||||
"aliases": [],
|
||||
@@ -1422,6 +1470,54 @@
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "delete_group_tag",
|
||||
"aliases": [],
|
||||
"summary": "从某个群分类移除资料标签",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
"name": "group_class",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_class": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_class",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群管理"
|
||||
},
|
||||
{
|
||||
"name": "delete_msg",
|
||||
"aliases": [],
|
||||
@@ -4428,6 +4524,10 @@
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_description": {
|
||||
"type": "string",
|
||||
"description": "群简介(公告不算;未加入的群为空)"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
@@ -5036,6 +5136,10 @@
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_description": {
|
||||
"type": "string",
|
||||
"description": "群简介(公告不算;未加入的群为空)"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
@@ -5138,6 +5242,10 @@
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_description": {
|
||||
"type": "string",
|
||||
"description": "群简介(公告不算;未加入的群为空)"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
@@ -5241,6 +5349,10 @@
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_description": {
|
||||
"type": "string",
|
||||
"description": "群简介(公告不算;未加入的群为空)"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
@@ -5342,6 +5454,14 @@
|
||||
"type": "string",
|
||||
"description": "群等级"
|
||||
},
|
||||
"qq_level": {
|
||||
"type": "integer",
|
||||
"description": "QQ 等级,仅在账号资料可用时返回"
|
||||
},
|
||||
"qage": {
|
||||
"type": "integer",
|
||||
"description": "按注册时间计算的完整周年数(UTC),注册时间不可用时省略"
|
||||
},
|
||||
"role": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
@@ -5513,6 +5633,14 @@
|
||||
"type": "string",
|
||||
"description": "群等级"
|
||||
},
|
||||
"qq_level": {
|
||||
"type": "integer",
|
||||
"description": "QQ 等级,仅在账号资料可用时返回"
|
||||
},
|
||||
"qage": {
|
||||
"type": "integer",
|
||||
"description": "按注册时间计算的完整周年数(UTC),注册时间不可用时省略"
|
||||
},
|
||||
"role": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
@@ -6075,6 +6203,75 @@
|
||||
},
|
||||
"category": "群信息"
|
||||
},
|
||||
{
|
||||
"name": "get_group_tags",
|
||||
"aliases": [],
|
||||
"summary": "读取某个群分类下的资料标签",
|
||||
"returns": "该分类下的资料标签列表。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"description": "资料标签",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer",
|
||||
"description": "标签编号"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "标签名"
|
||||
},
|
||||
"type": {
|
||||
"type": "integer",
|
||||
"description": "标签类型"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"type"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"tags"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "group_class",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_class": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_class"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群管理"
|
||||
},
|
||||
{
|
||||
"name": "get_group_todo_list",
|
||||
"aliases": [],
|
||||
@@ -7548,7 +7745,7 @@
|
||||
{
|
||||
"name": "get_status",
|
||||
"aliases": [],
|
||||
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。",
|
||||
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -7559,11 +7756,16 @@
|
||||
"good": {
|
||||
"type": "boolean",
|
||||
"description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false"
|
||||
},
|
||||
"time": {
|
||||
"type": "integer",
|
||||
"description": "当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"online",
|
||||
"good"
|
||||
"good",
|
||||
"time"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
@@ -7580,7 +7782,7 @@
|
||||
"name": "get_stranger_info",
|
||||
"aliases": [],
|
||||
"summary": "获取陌生人信息",
|
||||
"returns": "用户资料:QQ 号、昵称、好友备注、性别、年龄与个性签名,命中资料时另含等级、企点标志与企业名称。",
|
||||
"returns": "用户资料,含账号标识、等级别名和可用的注册时间、会员信息。注册时间或会员信息未返回时省略对应字段;登录天数暂无可靠来源,不返回占位值。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -7588,6 +7790,14 @@
|
||||
"type": "integer",
|
||||
"description": "QQ 号"
|
||||
},
|
||||
"uid": {
|
||||
"type": "string",
|
||||
"description": "账号唯一标识(仅查到资料时返回)"
|
||||
},
|
||||
"qid": {
|
||||
"type": "string",
|
||||
"description": "自定义账号标识(仅查到资料时返回)"
|
||||
},
|
||||
"nickname": {
|
||||
"type": "string",
|
||||
"description": "昵称"
|
||||
@@ -7612,6 +7822,26 @@
|
||||
"type": "integer",
|
||||
"description": "QQ 等级(仅查到资料时返回)"
|
||||
},
|
||||
"qqLevel": {
|
||||
"type": "integer",
|
||||
"description": "QQ 等级,同 qq_level"
|
||||
},
|
||||
"reg_time": {
|
||||
"type": "integer",
|
||||
"description": "注册时间戳(秒),不可用时省略"
|
||||
},
|
||||
"is_vip": {
|
||||
"type": "boolean",
|
||||
"description": "超级会员状态,兼容 NapCat;不可用时省略"
|
||||
},
|
||||
"is_years_vip": {
|
||||
"type": "boolean",
|
||||
"description": "年费会员状态,不可用时省略"
|
||||
},
|
||||
"vip_level": {
|
||||
"type": "integer",
|
||||
"description": "会员等级,不可用时省略"
|
||||
},
|
||||
"level": {
|
||||
"type": "integer",
|
||||
"description": "QQ 等级,同 qq_level(仅查到资料时返回)"
|
||||
@@ -8798,6 +9028,94 @@
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "send_custom_face",
|
||||
"aliases": [],
|
||||
"summary": "发送账号收藏表情(emoji_id 或 MD5),保留表情显示样式",
|
||||
"returns": "{ message_id: number }",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
"name": "emoji_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"desc": "当前账号收藏表情的完整 ID 或 32 位 MD5"
|
||||
},
|
||||
{
|
||||
"name": "group_id",
|
||||
"type": "uint",
|
||||
"required": false,
|
||||
"role": "group_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"desc": "目标群号;与 user_id 二选一"
|
||||
},
|
||||
{
|
||||
"name": "user_id",
|
||||
"type": "uint",
|
||||
"required": false,
|
||||
"role": "user_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"desc": "目标 QQ 号;与 group_id 二选一"
|
||||
},
|
||||
{
|
||||
"name": "reply_to",
|
||||
"type": "messageId",
|
||||
"required": false,
|
||||
"role": "message_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"not": {
|
||||
"const": 0
|
||||
}
|
||||
},
|
||||
"desc": "可选回复消息 ID"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"emoji_id": {
|
||||
"type": "string",
|
||||
"description": "当前账号收藏表情的完整 ID 或 32 位 MD5"
|
||||
},
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "目标群号;与 user_id 二选一",
|
||||
"x-role": "group_id"
|
||||
},
|
||||
"user_id": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "目标 QQ 号;与 group_id 二选一",
|
||||
"x-role": "user_id"
|
||||
},
|
||||
"reply_to": {
|
||||
"type": "integer",
|
||||
"not": {
|
||||
"const": 0
|
||||
},
|
||||
"description": "可选回复消息 ID",
|
||||
"x-role": "message_id"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"emoji_id"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "消息"
|
||||
},
|
||||
{
|
||||
"name": "send_flash_msg",
|
||||
"aliases": [],
|
||||
@@ -12989,7 +13307,7 @@
|
||||
},
|
||||
{
|
||||
"category": "消息",
|
||||
"count": 5
|
||||
"count": 6
|
||||
},
|
||||
{
|
||||
"category": "好友",
|
||||
@@ -13001,7 +13319,7 @@
|
||||
},
|
||||
{
|
||||
"category": "群管理",
|
||||
"count": 18
|
||||
"count": 21
|
||||
},
|
||||
{
|
||||
"category": "群文件",
|
||||
|
||||
@@ -443,6 +443,54 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "add_group_tag",
|
||||
"aliases": [],
|
||||
"summary": "向某个群分类添加资料标签",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
"name": "group_class",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_class": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_class",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群管理"
|
||||
},
|
||||
{
|
||||
"name": "bot_exit",
|
||||
"aliases": [],
|
||||
@@ -1425,6 +1473,54 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "delete_group_tag",
|
||||
"aliases": [],
|
||||
"summary": "从某个群分类移除资料标签",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
"name": "group_class",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_class": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_class",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群管理"
|
||||
},
|
||||
{
|
||||
"name": "delete_msg",
|
||||
"aliases": [],
|
||||
@@ -4431,6 +4527,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_description": {
|
||||
"type": "string",
|
||||
"description": "群简介(公告不算;未加入的群为空)"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
@@ -5039,6 +5139,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_description": {
|
||||
"type": "string",
|
||||
"description": "群简介(公告不算;未加入的群为空)"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
@@ -5141,6 +5245,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_description": {
|
||||
"type": "string",
|
||||
"description": "群简介(公告不算;未加入的群为空)"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
@@ -5244,6 +5352,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "string",
|
||||
"description": "群简介 / 公告预览"
|
||||
},
|
||||
"group_description": {
|
||||
"type": "string",
|
||||
"description": "群简介(公告不算;未加入的群为空)"
|
||||
},
|
||||
"group_all_shut": {
|
||||
"type": "integer",
|
||||
"enum": [
|
||||
@@ -5345,6 +5457,14 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "string",
|
||||
"description": "群等级"
|
||||
},
|
||||
"qq_level": {
|
||||
"type": "integer",
|
||||
"description": "QQ 等级,仅在账号资料可用时返回"
|
||||
},
|
||||
"qage": {
|
||||
"type": "integer",
|
||||
"description": "按注册时间计算的完整周年数(UTC),注册时间不可用时省略"
|
||||
},
|
||||
"role": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
@@ -5516,6 +5636,14 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "string",
|
||||
"description": "群等级"
|
||||
},
|
||||
"qq_level": {
|
||||
"type": "integer",
|
||||
"description": "QQ 等级,仅在账号资料可用时返回"
|
||||
},
|
||||
"qage": {
|
||||
"type": "integer",
|
||||
"description": "按注册时间计算的完整周年数(UTC),注册时间不可用时省略"
|
||||
},
|
||||
"role": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
@@ -6078,6 +6206,75 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"category": "群信息"
|
||||
},
|
||||
{
|
||||
"name": "get_group_tags",
|
||||
"aliases": [],
|
||||
"summary": "读取某个群分类下的资料标签",
|
||||
"returns": "该分类下的资料标签列表。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"description": "资料标签",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer",
|
||||
"description": "标签编号"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "标签名"
|
||||
},
|
||||
"type": {
|
||||
"type": "integer",
|
||||
"description": "标签类型"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"type"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"tags"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
"params": [
|
||||
{
|
||||
"name": "group_class",
|
||||
"type": "int",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"group_class": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group_class"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "群管理"
|
||||
},
|
||||
{
|
||||
"name": "get_group_todo_list",
|
||||
"aliases": [],
|
||||
@@ -7551,7 +7748,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
{
|
||||
"name": "get_status",
|
||||
"aliases": [],
|
||||
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。",
|
||||
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -7562,11 +7759,16 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"good": {
|
||||
"type": "boolean",
|
||||
"description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false"
|
||||
},
|
||||
"time": {
|
||||
"type": "integer",
|
||||
"description": "当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"online",
|
||||
"good"
|
||||
"good",
|
||||
"time"
|
||||
]
|
||||
},
|
||||
"readOnly": true,
|
||||
@@ -7583,7 +7785,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"name": "get_stranger_info",
|
||||
"aliases": [],
|
||||
"summary": "获取陌生人信息",
|
||||
"returns": "用户资料:QQ 号、昵称、好友备注、性别、年龄与个性签名,命中资料时另含等级、企点标志与企业名称。",
|
||||
"returns": "用户资料,含账号标识、等级别名和可用的注册时间、会员信息。注册时间或会员信息未返回时省略对应字段;登录天数暂无可靠来源,不返回占位值。",
|
||||
"returnsSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -7591,6 +7793,14 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "integer",
|
||||
"description": "QQ 号"
|
||||
},
|
||||
"uid": {
|
||||
"type": "string",
|
||||
"description": "账号唯一标识(仅查到资料时返回)"
|
||||
},
|
||||
"qid": {
|
||||
"type": "string",
|
||||
"description": "自定义账号标识(仅查到资料时返回)"
|
||||
},
|
||||
"nickname": {
|
||||
"type": "string",
|
||||
"description": "昵称"
|
||||
@@ -7615,6 +7825,26 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "integer",
|
||||
"description": "QQ 等级(仅查到资料时返回)"
|
||||
},
|
||||
"qqLevel": {
|
||||
"type": "integer",
|
||||
"description": "QQ 等级,同 qq_level"
|
||||
},
|
||||
"reg_time": {
|
||||
"type": "integer",
|
||||
"description": "注册时间戳(秒),不可用时省略"
|
||||
},
|
||||
"is_vip": {
|
||||
"type": "boolean",
|
||||
"description": "超级会员状态,兼容 NapCat;不可用时省略"
|
||||
},
|
||||
"is_years_vip": {
|
||||
"type": "boolean",
|
||||
"description": "年费会员状态,不可用时省略"
|
||||
},
|
||||
"vip_level": {
|
||||
"type": "integer",
|
||||
"description": "会员等级,不可用时省略"
|
||||
},
|
||||
"level": {
|
||||
"type": "integer",
|
||||
"description": "QQ 等级,同 qq_level(仅查到资料时返回)"
|
||||
@@ -8801,6 +9031,94 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"category": "扩展"
|
||||
},
|
||||
{
|
||||
"name": "send_custom_face",
|
||||
"aliases": [],
|
||||
"summary": "发送账号收藏表情(emoji_id 或 MD5),保留表情显示样式",
|
||||
"returns": "{ message_id: number }",
|
||||
"readOnly": false,
|
||||
"params": [
|
||||
{
|
||||
"name": "emoji_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"desc": "当前账号收藏表情的完整 ID 或 32 位 MD5"
|
||||
},
|
||||
{
|
||||
"name": "group_id",
|
||||
"type": "uint",
|
||||
"required": false,
|
||||
"role": "group_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"desc": "目标群号;与 user_id 二选一"
|
||||
},
|
||||
{
|
||||
"name": "user_id",
|
||||
"type": "uint",
|
||||
"required": false,
|
||||
"role": "user_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"desc": "目标 QQ 号;与 group_id 二选一"
|
||||
},
|
||||
{
|
||||
"name": "reply_to",
|
||||
"type": "messageId",
|
||||
"required": false,
|
||||
"role": "message_id",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"not": {
|
||||
"const": 0
|
||||
}
|
||||
},
|
||||
"desc": "可选回复消息 ID"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"emoji_id": {
|
||||
"type": "string",
|
||||
"description": "当前账号收藏表情的完整 ID 或 32 位 MD5"
|
||||
},
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "目标群号;与 user_id 二选一",
|
||||
"x-role": "group_id"
|
||||
},
|
||||
"user_id": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "目标 QQ 号;与 group_id 二选一",
|
||||
"x-role": "user_id"
|
||||
},
|
||||
"reply_to": {
|
||||
"type": "integer",
|
||||
"not": {
|
||||
"const": 0
|
||||
},
|
||||
"description": "可选回复消息 ID",
|
||||
"x-role": "message_id"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"emoji_id"
|
||||
],
|
||||
"additionalProperties": true
|
||||
},
|
||||
"category": "消息"
|
||||
},
|
||||
{
|
||||
"name": "send_flash_msg",
|
||||
"aliases": [],
|
||||
@@ -12993,7 +13311,7 @@ export const CATEGORIES: CatalogCategory[] = [
|
||||
},
|
||||
{
|
||||
"category": "消息",
|
||||
"count": 5
|
||||
"count": 6
|
||||
},
|
||||
{
|
||||
"category": "好友",
|
||||
@@ -13005,7 +13323,7 @@ export const CATEGORIES: CatalogCategory[] = [
|
||||
},
|
||||
{
|
||||
"category": "群管理",
|
||||
"count": 18
|
||||
"count": 21
|
||||
},
|
||||
{
|
||||
"category": "群文件",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.14.19",
|
||||
"version": "1.14.22",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { FriendDressError } from '@snowluma/protocol/web/friend-dress';
|
||||
import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info';
|
||||
@@ -21,7 +22,11 @@ import { groupInfoReturnsSchema } from './group-info';
|
||||
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
|
||||
|
||||
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
|
||||
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
|
||||
const DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
|
||||
|
||||
function downloadFileTimeoutMs(): number {
|
||||
return positiveIntEnv('SNOWLUMA_DOWNLOAD_FILE_TIMEOUT_MS', DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
const profileLikeUserSchema = {
|
||||
type: 'object',
|
||||
@@ -1902,11 +1907,8 @@ export const actions = [
|
||||
return okResponse(list);
|
||||
},
|
||||
}),
|
||||
// set_doubt_friends_add_request — handle a 可疑好友申请 (0xd69_0). `flag` is
|
||||
// the uid from the get list, or the applicant's account number (resolved
|
||||
// before the packet is built). approve → approvalDoubtBuddyReq; approve:false
|
||||
// → delDoubtBuddyReq (reject/decline). NapCat only ever approves; we add the
|
||||
// reject path since we RE'd delDoubtBuddyReq too.
|
||||
// Accept the list UID or resolve the applicant's account number.
|
||||
// Approval and rejection use their respective friend API operations.
|
||||
defineAction({
|
||||
name: 'set_doubt_friends_add_request',
|
||||
summary: '处理可疑好友申请',
|
||||
@@ -1915,8 +1917,6 @@ export const actions = [
|
||||
approve: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
// approve → approvalDoubtBuddyReq (0xd69_0); reject → delDoubtBuddyReq
|
||||
// (also 0xd69_0, distinct body) — both RE'd from the binary.
|
||||
if (p.approve) {
|
||||
await ctx.bridge.apis.friend.approveDoubtRequest(p.flag);
|
||||
} else {
|
||||
@@ -2597,7 +2597,7 @@ export const actions = [
|
||||
buf = Buffer.from(base64, 'base64');
|
||||
if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
|
||||
} else {
|
||||
buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS);
|
||||
buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, downloadFileTimeoutMs());
|
||||
}
|
||||
try {
|
||||
const safe = await saveDownloadBuffer(buf, name);
|
||||
|
||||
@@ -32,17 +32,24 @@ export const actions = [
|
||||
name: 'get_stranger_info',
|
||||
summary: '获取陌生人信息',
|
||||
readOnly: true,
|
||||
returns: '用户资料:QQ 号、昵称、好友备注、性别、年龄与个性签名,命中资料时另含等级、企点标志与企业名称。',
|
||||
returns: '用户资料,含账号标识、等级别名和可用的注册时间、会员信息。注册时间或会员信息未返回时省略对应字段;登录天数暂无可靠来源,不返回占位值。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
user_id: { type: 'integer', description: 'QQ 号' },
|
||||
uid: { type: 'string', description: '账号唯一标识(仅查到资料时返回)' },
|
||||
qid: { type: 'string', description: '自定义账号标识(仅查到资料时返回)' },
|
||||
nickname: { type: 'string', description: '昵称' },
|
||||
remark: { type: 'string', description: '好友备注;非好友或未设置时为空字符串' },
|
||||
sex: { type: 'string', description: '性别(male/female/unknown)' },
|
||||
age: { type: 'integer', description: '年龄' },
|
||||
long_nick: { type: 'string', description: '个性签名' },
|
||||
qq_level: { type: 'integer', description: 'QQ 等级(仅查到资料时返回)' },
|
||||
qqLevel: { type: 'integer', description: 'QQ 等级,同 qq_level' },
|
||||
reg_time: { type: 'integer', description: '注册时间戳(秒),不可用时省略' },
|
||||
is_vip: { type: 'boolean', description: '超级会员状态,兼容 NapCat;不可用时省略' },
|
||||
is_years_vip: { type: 'boolean', description: '年费会员状态,不可用时省略' },
|
||||
vip_level: { type: 'integer', description: '会员等级,不可用时省略' },
|
||||
level: { type: 'integer', description: 'QQ 等级,同 qq_level(仅查到资料时返回)' },
|
||||
status: { type: 'integer', description: '在线状态码' },
|
||||
extStatus: { type: 'integer', description: '扩展状态码' },
|
||||
|
||||
@@ -166,6 +166,60 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'get_group_tags',
|
||||
summary: '读取某个群分类下的资料标签',
|
||||
readOnly: true,
|
||||
returns: '该分类下的资料标签列表。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
tags: {
|
||||
type: 'array',
|
||||
description: '资料标签',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'integer', description: '标签编号' },
|
||||
name: { type: 'string', description: '标签名' },
|
||||
type: { type: 'integer', description: '标签类型' },
|
||||
},
|
||||
required: ['id', 'name', 'type'],
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['tags'],
|
||||
},
|
||||
params: { group_class: f.int({ min: 0, max: 0xFFFFFFFF }) },
|
||||
run: async (p, ctx) => okResponse(await ctx.bridge.apis.groupAdmin.listCategoryTags(p.group_class)),
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'add_group_tag',
|
||||
summary: '向某个群分类添加资料标签',
|
||||
params: {
|
||||
group_class: f.int({ min: 0, max: 0xFFFFFFFF }),
|
||||
name: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.addCategoryTag(p.group_class, p.name);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'delete_group_tag',
|
||||
summary: '从某个群分类移除资料标签',
|
||||
params: {
|
||||
group_class: f.int({ min: 0, max: 0xFFFFFFFF }),
|
||||
name: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.removeCategoryTag(p.group_class, p.name);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupUserAction({
|
||||
name: 'set_group_admin',
|
||||
summary: '设置/取消管理员',
|
||||
|
||||
@@ -13,6 +13,7 @@ export const groupInfoReturnsSchema = {
|
||||
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
|
||||
group_level: { type: 'integer', description: '群等级' },
|
||||
group_memo: { type: 'string', description: '群简介 / 公告预览' },
|
||||
group_description: { type: 'string', description: '群简介(公告不算;未加入的群为空)' },
|
||||
group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' },
|
||||
},
|
||||
required: [
|
||||
@@ -40,6 +41,7 @@ export const actions = [
|
||||
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
|
||||
group_level: { type: 'integer', description: '群等级(列表批量场景恒 0,详见 get_group_info)' },
|
||||
group_memo: { type: 'string', description: '群简介 / 公告预览' },
|
||||
group_description: { type: 'string', description: '群简介(公告不算;未加入的群为空)' },
|
||||
group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' },
|
||||
},
|
||||
required: [
|
||||
@@ -77,6 +79,7 @@ export const actions = [
|
||||
group_create_time: 0,
|
||||
group_level: 0,
|
||||
group_memo: '',
|
||||
group_description: '',
|
||||
group_all_shut: 0,
|
||||
};
|
||||
if (ctx.getGroupInfo) {
|
||||
@@ -108,6 +111,8 @@ export const actions = [
|
||||
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
|
||||
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
|
||||
level: { type: 'string', description: '群等级' },
|
||||
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
|
||||
qage: { type: 'integer', description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略' },
|
||||
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
|
||||
title: { type: 'string', description: '专属头衔' },
|
||||
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
|
||||
@@ -151,6 +156,8 @@ export const actions = [
|
||||
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
|
||||
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
|
||||
level: { type: 'string', description: '群等级' },
|
||||
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
|
||||
qage: { type: 'integer', description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略' },
|
||||
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
|
||||
title: { type: 'string', description: '专属头衔' },
|
||||
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
|
||||
|
||||
@@ -27,19 +27,20 @@ export const actions = [
|
||||
defineAction({
|
||||
name: 'get_status',
|
||||
readOnly: true,
|
||||
returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。',
|
||||
returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
online: { type: 'boolean', description: '是否在线' },
|
||||
good: { type: 'boolean', description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false' },
|
||||
time: { type: 'integer', description: '当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时' },
|
||||
},
|
||||
required: ['online', 'good'],
|
||||
required: ['online', 'good', 'time'],
|
||||
},
|
||||
params: {},
|
||||
run: (_p, ctx) => {
|
||||
const online = ctx.isOnline();
|
||||
return okResponse({ online, good: online && ctx.bridge.receiveHealthy });
|
||||
return okResponse({ online, good: online && ctx.bridge.receiveHealthy, time: Math.floor(ctx.getUptimeMs() / 1000) });
|
||||
},
|
||||
}),
|
||||
|
||||
|
||||
@@ -48,6 +48,32 @@ async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext):
|
||||
}
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'send_custom_face',
|
||||
summary: '发送账号收藏表情(emoji_id 或 MD5),保留表情显示样式',
|
||||
returns: '{ message_id: number }',
|
||||
params: {
|
||||
emoji_id: f.string().describe('当前账号收藏表情的完整 ID 或 32 位 MD5'),
|
||||
group_id: f.groupId().optional().describe('目标群号;与 user_id 二选一'),
|
||||
user_id: f.userId().optional().describe('目标 QQ 号;与 group_id 二选一'),
|
||||
reply_to: f.messageId().optional().describe('可选回复消息 ID'),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
if ((p.group_id === undefined) === (p.user_id === undefined)) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'exactly one of group_id and user_id is required');
|
||||
}
|
||||
if (!p.emoji_id.trim()) return failedResponse(RETCODE.BAD_REQUEST, 'emoji_id is required');
|
||||
const face = await ctx.bridge.apis.profile.resolveCustomFace(p.emoji_id);
|
||||
const message: JsonObject[] = [];
|
||||
if (p.reply_to !== undefined) message.push({ type: 'reply', data: { id: String(p.reply_to) } });
|
||||
message.push({ type: 'image', data: { file: face.url, sub_type: 1, summary: '[动画表情]' } });
|
||||
const result = p.group_id !== undefined
|
||||
? await ctx.sendGroupMessage(p.group_id, message, false)
|
||||
: await ctx.sendPrivateMessage(p.user_id!, message, false);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
},
|
||||
}),
|
||||
|
||||
// send_msg routes on message_type / group_id presence, so the *required*
|
||||
// id is conditional — that branch stays in run(). The fields themselves
|
||||
// (message required; group_id/user_id valid uints when present) are
|
||||
@@ -144,4 +170,3 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -49,6 +49,7 @@ export interface ApiActionContext {
|
||||
bridge: BridgeInterface;
|
||||
getLoginInfo: () => { userId: number; nickname: string };
|
||||
isOnline: () => boolean;
|
||||
getUptimeMs: () => number;
|
||||
getMessage: (messageId: number) => JsonObject | null;
|
||||
getMessageMeta: (messageId: number) => MessageMeta | null;
|
||||
cacheMessageMetas: (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { randomBytes } from 'crypto';
|
||||
@@ -110,7 +111,69 @@ export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions =
|
||||
saveOneBotConfig(uin, config, { mode: globalRaw ? 'overlay' : 'snapshot' });
|
||||
}
|
||||
|
||||
return config;
|
||||
// Listen-port overrides stay in memory. Persisting them would bake a
|
||||
// machine-specific port into onebot_<uin>.json.
|
||||
return applyOneBotListenPortOverrides(config);
|
||||
}
|
||||
|
||||
const HTTP_DEFAULT_SERVER = 'http-default';
|
||||
const WS_DEFAULT_SERVER = 'ws-default';
|
||||
|
||||
/** Override only the factory listeners. Other adapters keep their saved ports. */
|
||||
export function applyOneBotListenPortOverrides(
|
||||
config: OneBotConfig,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): OneBotConfig {
|
||||
const httpPort = readListenPort('SNOWLUMA_ONEBOT_HTTP_PORT', env);
|
||||
const wsPort = readListenPort('SNOWLUMA_ONEBOT_WS_PORT', env);
|
||||
if (httpPort === undefined && wsPort === undefined) return config;
|
||||
|
||||
const next = structuredClone(config);
|
||||
const httpApplied = httpPort !== undefined && assignFactoryPort(
|
||||
next.networks.httpServers,
|
||||
HTTP_DEFAULT_SERVER,
|
||||
httpPort,
|
||||
'SNOWLUMA_ONEBOT_HTTP_PORT',
|
||||
);
|
||||
const wsApplied = wsPort !== undefined && assignFactoryPort(
|
||||
next.networks.wsServers,
|
||||
WS_DEFAULT_SERVER,
|
||||
wsPort,
|
||||
'SNOWLUMA_ONEBOT_WS_PORT',
|
||||
);
|
||||
if (!httpApplied && !wsApplied) return config;
|
||||
try {
|
||||
assertValidOneBotConfig(next);
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'OneBot listen port override ignored: %s',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return config;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function readListenPort(name: string, env: NodeJS.ProcessEnv): number | undefined {
|
||||
const raw = env[name];
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const port = positiveIntEnv(name, 0, { max: 65535, env });
|
||||
return port > 0 ? port : undefined;
|
||||
}
|
||||
|
||||
function assignFactoryPort(
|
||||
servers: Array<{ name: string; port: number }>,
|
||||
name: string,
|
||||
port: number,
|
||||
envName: string,
|
||||
): boolean {
|
||||
const server = servers.find((entry) => entry.name === name);
|
||||
if (!server) {
|
||||
log.warn('%s is ignored; no %s listener', envName, name);
|
||||
return false;
|
||||
}
|
||||
server.port = port;
|
||||
return true;
|
||||
}
|
||||
|
||||
export interface SaveOneBotConfigOptions {
|
||||
|
||||
@@ -150,12 +150,37 @@ export const ELEMENT_CODECS = {
|
||||
|
||||
face: {
|
||||
async toSegment(element) {
|
||||
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
|
||||
return {
|
||||
type: 'face',
|
||||
data: {
|
||||
id: String(element.faceId ?? 0),
|
||||
...(element.resultId !== undefined ? { resultId: element.resultId } : {}),
|
||||
},
|
||||
};
|
||||
},
|
||||
async fromSegment(data) {
|
||||
const id = intOr(data.id, -1);
|
||||
if (id < 0) return null;
|
||||
return { type: 'face', faceId: id };
|
||||
const element: MessageElementOf<'face'> = { type: 'face', faceId: id };
|
||||
if (data.resultId !== undefined) {
|
||||
if (typeof data.resultId === 'string') {
|
||||
element.resultId = data.resultId;
|
||||
} else if (typeof data.resultId === 'number' && Number.isSafeInteger(data.resultId) && data.resultId >= 0) {
|
||||
element.resultId = String(data.resultId);
|
||||
} else {
|
||||
throw new MessageElementValidationError('INVALID_FIELD', 'face.resultId must be a string or non-negative safe integer', 'face', 'resultId');
|
||||
}
|
||||
}
|
||||
if (data.large !== undefined) {
|
||||
if (data.large === true || data.large === 'true' || data.large === 1 || data.large === '1') {
|
||||
element.large = true;
|
||||
} else if (data.large === false || data.large === 'false' || data.large === 0 || data.large === '0') {
|
||||
element.large = false;
|
||||
} else {
|
||||
throw new MessageElementValidationError('INVALID_FIELD', 'face.large must be a boolean');
|
||||
}
|
||||
}
|
||||
return element;
|
||||
},
|
||||
},
|
||||
|
||||
@@ -203,6 +228,7 @@ export const ELEMENT_CODECS = {
|
||||
element.replyTime && element.replyTime > 0
|
||||
? element.replyTime
|
||||
: Number.MAX_SAFE_INTEGER,
|
||||
element.replyElements,
|
||||
);
|
||||
return { type: 'reply', data: { id: String(id) } };
|
||||
},
|
||||
@@ -236,6 +262,7 @@ export const ELEMENT_CODECS = {
|
||||
element.replySenderUin = meta.senderUin;
|
||||
element.replyTime = meta.time;
|
||||
element.replyRandom = meta.random;
|
||||
element.replyElements = meta.elements;
|
||||
}
|
||||
|
||||
return element;
|
||||
|
||||
@@ -39,6 +39,7 @@ export type MessageIdResolver = (
|
||||
sequence: number,
|
||||
eventName: string,
|
||||
timestamp?: number,
|
||||
replyElements?: readonly MessageElement[],
|
||||
) => number;
|
||||
|
||||
export type MediaSegmentSink = (
|
||||
@@ -120,4 +121,3 @@ export async function convertEvent(
|
||||
return (converter as (ctx: ConverterContext, event: QQEventVariant) => JsonObject | Promise<JsonObject>)(ctx, event);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { ToSegmentContext } from './element-codecs';
|
||||
import { getElementCodec } from './element-codecs';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { ConverterContext } from './index';
|
||||
import { attachMessageMedia } from '../message-media';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
@@ -32,13 +33,24 @@ export async function elementsToOneBotSegments(
|
||||
const segmentCtx = toSegmentContext(ctx, isGroup, sessionId);
|
||||
const result: JsonArray = [];
|
||||
for (const element of elements) {
|
||||
let segment: JsonObject;
|
||||
// One malformed element shouldn't drop the whole message — skip it (with a
|
||||
// breadcrumb) and keep converting the rest.
|
||||
try {
|
||||
result.push(await elementToSegment(element, segmentCtx));
|
||||
segment = await elementToSegment(element, { ...segmentCtx, mediaSegmentSink: null });
|
||||
} catch (err) {
|
||||
log.warn('segment convert skipped type=%s (%s)', element.type,
|
||||
err instanceof Error ? err.message : String(err));
|
||||
continue;
|
||||
}
|
||||
// Persistence failures must propagate, not masquerade as bad wire elements.
|
||||
attachMessageMedia(segment, element);
|
||||
if (element.type === 'image' || element.type === 'record' || element.type === 'video') {
|
||||
ctx.mediaSegmentSink?.(element.type, element, segment.data as JsonObject, isGroup, sessionId);
|
||||
}
|
||||
result.push(segment);
|
||||
if (element.type === 'markdown' && element.text) {
|
||||
result.push({ type: 'text', data: { text: element.text } });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
||||
import type { MessageIdResolver } from './index';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
|
||||
export function parseSelfId(instanceUin: string): number {
|
||||
const parsed = Number.parseInt(instanceUin, 10);
|
||||
@@ -39,12 +40,13 @@ export function resolveReplyId(
|
||||
resolver?: MessageIdResolver | null,
|
||||
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
|
||||
timestamp?: number,
|
||||
replyElements?: readonly MessageElement[],
|
||||
): number {
|
||||
const seq = Math.trunc(sequence);
|
||||
if (seq === 0) return 0;
|
||||
|
||||
if (resolver) {
|
||||
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp);
|
||||
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp, replyElements);
|
||||
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ export function segmentToCQ(seg: JsonObject): string {
|
||||
case 'text':
|
||||
return cqEscape(String(data.text ?? ''));
|
||||
case 'face':
|
||||
return `[CQ:face,id=${data.id ?? 0}]`;
|
||||
return `[CQ:face,id=${data.id ?? 0}${data.resultId !== undefined ? `,resultId=${cqEscape(String(data.resultId))}` : ''}]`;
|
||||
case 'image':
|
||||
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
case 'at':
|
||||
@@ -77,4 +77,3 @@ export async function parseFromCQString(message: string, options?: ParseMessageO
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ export interface OneBotInstanceContext {
|
||||
converterCtx: ConverterContext;
|
||||
config: OneBotConfig;
|
||||
musicSignUrl?: string;
|
||||
getUptimeMs(): number;
|
||||
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
|
||||
dispatchEvent(
|
||||
event: JsonObject,
|
||||
@@ -68,6 +69,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
|
||||
getLoginInfo: () => getLoginInfo(ref),
|
||||
isOnline: () => true,
|
||||
getUptimeMs: () => ref.getUptimeMs(),
|
||||
getMessage: (messageId) => messageStore.findEvent(messageId),
|
||||
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||
cacheMessageMetas: (entries) => messageStore.storeMetas(entries),
|
||||
|
||||
@@ -62,7 +62,7 @@ export class OneBotInstance {
|
||||
private lifecycleTail: Promise<void>;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
private readonly ctx: OneBotInstanceContext;
|
||||
/** Process-uptime baseline for the `#sl` status reply. */
|
||||
/** Account-session uptime shared by the status action and `#sl`. */
|
||||
private readonly startedAt = Date.now();
|
||||
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
|
||||
private readonly statusCommandCooldown = new Map<string, number>();
|
||||
@@ -132,7 +132,7 @@ export class OneBotInstance {
|
||||
: moduleLog;
|
||||
|
||||
this.rkeyCache = new RKeyCache(globalSettings.rkey);
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'messages.db'));
|
||||
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
|
||||
this.reactionStore = new ReactionStore(path.join('data', this.uin, 'reactions.db'));
|
||||
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
|
||||
@@ -143,7 +143,7 @@ export class OneBotInstance {
|
||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
|
||||
mediaUrlResolver: (element, isGroup, sessionId) =>
|
||||
mediaUrlResolver.resolve(element, isGroup, sessionId),
|
||||
messageIdResolver: (isGroup, sessionId, sequence, eventName, timestamp) => {
|
||||
messageIdResolver: (isGroup, sessionId, sequence, eventName, timestamp, replyElements) => {
|
||||
const resolvedEventName = eventName
|
||||
|| (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
|
||||
if (!isGroup
|
||||
@@ -155,6 +155,7 @@ export class OneBotInstance {
|
||||
sequence,
|
||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
|
||||
timestamp,
|
||||
replyElements,
|
||||
);
|
||||
if (storedId !== null) return storedId;
|
||||
}
|
||||
@@ -180,6 +181,7 @@ export class OneBotInstance {
|
||||
converterCtx: this.converterCtx,
|
||||
config,
|
||||
musicSignUrl: globalSettings.musicSignUrl,
|
||||
getUptimeMs: () => Math.max(0, Date.now() - this.startedAt),
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
dispatchEvent: (event, source = 'bridge', startedAt) => this.dispatchEvent(event, source, startedAt),
|
||||
};
|
||||
@@ -271,6 +273,20 @@ export class OneBotInstance {
|
||||
this.ctx.musicSignUrl = globalSettings.musicSignUrl;
|
||||
}
|
||||
|
||||
/** Drop listeners and sockets without waiting for shutdown to finish.
|
||||
* Used when dispose() does not settle and a replacement session must bind. */
|
||||
forceRelease(): void {
|
||||
try {
|
||||
this.quiesce();
|
||||
} catch (error) {
|
||||
this.log.warn(
|
||||
'quiesce during forced release failed: %s',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
this.networkManager.forceRelease();
|
||||
}
|
||||
|
||||
/** Synchronously stop every ingress seam for this instance generation.
|
||||
*
|
||||
* This operation is sticky and idempotent. It is intentionally separate
|
||||
@@ -477,7 +493,7 @@ export class OneBotInstance {
|
||||
version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev',
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
uptimeMs: Date.now() - this.startedAt,
|
||||
uptimeMs: this.ctx.getUptimeMs(),
|
||||
});
|
||||
if (isGroup) await sendGroupMessage(this.ctx, sessionId, text, true);
|
||||
else await sendPrivateMessage(this.ctx, sessionId, text, true);
|
||||
|
||||
+110
-19
@@ -1,7 +1,7 @@
|
||||
import { createLogger, runWithoutRequestContext } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { BridgeManager } from '@snowluma/core/manager';
|
||||
import { loadOneBotConfig } from './config';
|
||||
import { loadOneBotConfig, OneBotConfigValidationError } from './config';
|
||||
import { loadGlobalSettings } from './global-config';
|
||||
import { OneBotInstance } from './instance';
|
||||
import type { MessageStoreMigrationStatus } from './message-store-migration';
|
||||
@@ -43,7 +43,43 @@ export interface DatabaseMigrationTask {
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
/** A peer that never finishes a close handshake must not keep the next
|
||||
* account session offline. Ten seconds covers a normal drain.
|
||||
* SNOWLUMA_SESSION_RELEASE_DEADLINE_MS overrides the configured value. */
|
||||
const DEFAULT_SESSION_RELEASE_DEADLINE_MS = 10_000;
|
||||
const SESSION_RELEASE_DEADLINE_ENV = 'SNOWLUMA_SESSION_RELEASE_DEADLINE_MS';
|
||||
const MAX_SESSION_RELEASE_DEADLINE_MS = 2_147_483_647;
|
||||
|
||||
/** Positive integer milliseconds, or `undefined` when the raw value is absent
|
||||
* or not usable. Callers decide the fallback. */
|
||||
export function parseSessionReleaseDeadlineMs(raw: string | undefined): number | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
const value = raw.trim();
|
||||
if (!/^[1-9]\d*$/.test(value)) return undefined;
|
||||
const parsed = Number(value);
|
||||
if (!Number.isSafeInteger(parsed) || parsed > MAX_SESSION_RELEASE_DEADLINE_MS) return undefined;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** Env wins over an explicit deadline. An unusable env value is ignored. */
|
||||
export function resolveSessionReleaseDeadlineMs(configured?: number, envRaw?: string): number {
|
||||
const fromEnv = parseSessionReleaseDeadlineMs(envRaw);
|
||||
if (fromEnv !== undefined) return fromEnv;
|
||||
if (
|
||||
configured !== undefined
|
||||
&& Number.isSafeInteger(configured)
|
||||
&& configured > 0
|
||||
&& configured <= MAX_SESSION_RELEASE_DEADLINE_MS
|
||||
) {
|
||||
return configured;
|
||||
}
|
||||
return DEFAULT_SESSION_RELEASE_DEADLINE_MS;
|
||||
}
|
||||
|
||||
export interface OneBotManagerOptions {
|
||||
/** How long a retiring instance may block the replacement session.
|
||||
* SNOWLUMA_SESSION_RELEASE_DEADLINE_MS overrides this when it is set. */
|
||||
sessionReleaseDeadlineMs?: number;
|
||||
createDatabaseMigrationTask?: (uin: string) => DatabaseMigrationTask;
|
||||
createInstance?: (
|
||||
uin: string,
|
||||
@@ -91,8 +127,21 @@ export class OneBotManager {
|
||||
private readonly createInstance: NonNullable<OneBotManagerOptions['createInstance']>;
|
||||
private disposePromise: Promise<void> | null = null;
|
||||
private disposed = false;
|
||||
private readonly sessionReleaseDeadlineMs: number;
|
||||
|
||||
constructor(options: OneBotManagerOptions = {}) {
|
||||
const envRaw = process.env[SESSION_RELEASE_DEADLINE_ENV];
|
||||
if (envRaw !== undefined && envRaw.trim() && parseSessionReleaseDeadlineMs(envRaw) === undefined) {
|
||||
log.warn(
|
||||
'%s=%j is ignored; expected a positive integer number of milliseconds',
|
||||
SESSION_RELEASE_DEADLINE_ENV,
|
||||
envRaw,
|
||||
);
|
||||
}
|
||||
this.sessionReleaseDeadlineMs = resolveSessionReleaseDeadlineMs(
|
||||
options.sessionReleaseDeadlineMs,
|
||||
envRaw,
|
||||
);
|
||||
this.createDatabaseMigrationTask = options.createDatabaseMigrationTask
|
||||
?? createMessageStoreMigrationTask;
|
||||
this.createInstance = options.createInstance
|
||||
@@ -269,18 +318,22 @@ export class OneBotManager {
|
||||
};
|
||||
this.databaseMigrations.set(uin, migration);
|
||||
const startTask = (): void => {
|
||||
const handleFailure = (): void => {
|
||||
const handleFailure = (error: unknown, stage = 'database migration'): void => {
|
||||
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
|
||||
const retryable = !(error instanceof OneBotConfigValidationError);
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
const label = stage === 'session startup' ? '账号启动失败' : '数据库迁移失败';
|
||||
migration.state = {
|
||||
...migration.state,
|
||||
phase: 'failed',
|
||||
usable: migration.ready,
|
||||
estimatedRemainingSeconds: null,
|
||||
error: '数据库迁移失败,将自动重试',
|
||||
error: `${label}:${detail}${retryable ? ';将自动重试' : ';请修正配置后重启'}`,
|
||||
};
|
||||
log.error('database migration failed: UIN=%s', uin);
|
||||
log.error('%s failed: UIN=%s retryable=%s error=%s',
|
||||
stage, uin, retryable, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
migration.task.cancel();
|
||||
if (migration.retryTimer) return;
|
||||
if (!retryable || migration.retryTimer) return;
|
||||
migration.retryTimer = setTimeout(() => {
|
||||
migration.retryTimer = null;
|
||||
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
|
||||
@@ -298,8 +351,8 @@ export class OneBotManager {
|
||||
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
|
||||
try {
|
||||
this.startSession(uin, bridge);
|
||||
} catch {
|
||||
handleFailure();
|
||||
} catch (error) {
|
||||
handleFailure(error, 'session startup');
|
||||
return;
|
||||
}
|
||||
migration.ready = true;
|
||||
@@ -311,8 +364,8 @@ export class OneBotManager {
|
||||
};
|
||||
try {
|
||||
migration.task.beginMigration();
|
||||
} catch {
|
||||
handleFailure();
|
||||
} catch (error) {
|
||||
handleFailure(error);
|
||||
}
|
||||
},
|
||||
onProgress: (status, elapsedMs) => {
|
||||
@@ -330,8 +383,8 @@ export class OneBotManager {
|
||||
},
|
||||
onFailed: handleFailure,
|
||||
});
|
||||
} catch {
|
||||
handleFailure();
|
||||
} catch (error) {
|
||||
handleFailure(error);
|
||||
}
|
||||
};
|
||||
startTask();
|
||||
@@ -443,20 +496,58 @@ export class OneBotManager {
|
||||
return result;
|
||||
}
|
||||
|
||||
private async releaseRetiringInstance(
|
||||
uin: string,
|
||||
pending: { bridge: BridgeInterface; cancelled: boolean },
|
||||
instance: OneBotInstance,
|
||||
): Promise<void> {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<'timeout'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('timeout'), this.sessionReleaseDeadlineMs);
|
||||
timer.unref?.();
|
||||
});
|
||||
// Map rejection here so a dispose() that fails after the deadline still
|
||||
// has a handler. The race may already have moved on.
|
||||
const releasing = instance.dispose().then(
|
||||
() => 'released' as const,
|
||||
(error: unknown) => ({ failed: error }),
|
||||
);
|
||||
try {
|
||||
const outcome = await Promise.race([releasing, timeout]);
|
||||
if (outcome === 'timeout') {
|
||||
log.error(
|
||||
'session release timed out; forcing adapters closed and starting the replacement: UIN=%s',
|
||||
uin,
|
||||
);
|
||||
try {
|
||||
instance.forceRelease?.();
|
||||
} catch (error) {
|
||||
log.error(
|
||||
'forced session release failed: UIN=%s: %s',
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (typeof outcome === 'object') {
|
||||
// Do not leave this UIN permanently guarded by a failed handoff. A
|
||||
// later session-start observation may retry the still-visible retire.
|
||||
if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin);
|
||||
throw new InstanceLifecycleError(instance, outcome.failed);
|
||||
}
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
private async finishRetiringBeforeStart(
|
||||
uin: string,
|
||||
pending: { bridge: BridgeInterface; cancelled: boolean },
|
||||
retiring: OneBotInstance[],
|
||||
): Promise<void> {
|
||||
for (const instance of retiring) {
|
||||
try {
|
||||
await instance.dispose();
|
||||
} catch (error) {
|
||||
// Do not leave this UIN permanently guarded by a failed handoff. A
|
||||
// later session-start observation may retry the still-visible retire.
|
||||
if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin);
|
||||
throw new InstanceLifecycleError(instance, error);
|
||||
}
|
||||
await this.releaseRetiringInstance(uin, pending, instance);
|
||||
this.retirementSucceeded(instance);
|
||||
}
|
||||
if (this.pendingStarts.get(uin) !== pending) return;
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
import { foldMediaKey, MediaStore, rollbackMediaTransaction, serializeMediaInfo } from './media-store';
|
||||
|
||||
const log = createLogger('OneBot.MediaMigration');
|
||||
const BATCH_SIZE = 200;
|
||||
|
||||
/** Runs in the existing database worker, before the account is marked ready.
|
||||
* Copy only: leave the old database (including its WAL) intact for recovery.
|
||||
* Each committed batch advances its cursor in the destination transaction.
|
||||
*/
|
||||
export async function migrateLegacyMedia(
|
||||
messageDbPath: string,
|
||||
cancelled: () => boolean = () => false,
|
||||
): Promise<void> {
|
||||
const store = new MediaStore(messageDbPath);
|
||||
store.close();
|
||||
const destination = openSqliteDb(messageDbPath);
|
||||
let source: DatabaseSync | undefined;
|
||||
try {
|
||||
destination.exec(`CREATE TABLE IF NOT EXISTS media_migration_state (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1), phase TEXT NOT NULL, cursor INTEGER NOT NULL
|
||||
); INSERT OR IGNORE INTO media_migration_state VALUES (1, 'entries', 0)`);
|
||||
const state = destination.prepare('SELECT phase, cursor FROM media_migration_state WHERE id = 1')
|
||||
.get() as { phase: string; cursor: number };
|
||||
if (state.phase === 'complete') return;
|
||||
const sourcePath = path.join(path.dirname(messageDbPath), 'media.db');
|
||||
if (!fs.existsSync(sourcePath)) {
|
||||
destination.exec("UPDATE media_migration_state SET phase = 'complete' WHERE id = 1");
|
||||
return;
|
||||
}
|
||||
source = new DatabaseSync(sourcePath, { readOnly: true });
|
||||
log.info('preserving legacy media metadata: migration started');
|
||||
const insertEntry = destination.prepare(`INSERT INTO legacy_media_entries (type, primary_key, data, last_seen)
|
||||
VALUES (?, ?, ?, ?) ON CONFLICT(type, primary_key) DO NOTHING`);
|
||||
const insertKey = destination.prepare(`INSERT INTO legacy_media_keys (type, key, primary_key)
|
||||
VALUES (?, ?, ?) ON CONFLICT(type, key) DO NOTHING`);
|
||||
const saveState = destination.prepare('UPDATE media_migration_state SET phase = ?, cursor = ? WHERE id = 1');
|
||||
while (!cancelled() && state.phase !== 'complete') {
|
||||
const table = state.phase === 'entries' ? 'media_entries' : 'media_keys';
|
||||
const rows = source.prepare(`SELECT rowid AS migration_rowid, * FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT ?`)
|
||||
.all(state.cursor, BATCH_SIZE) as Array<{
|
||||
migration_rowid: number; type: string; primary_key: string; data: string; last_seen: number; key: string;
|
||||
}>;
|
||||
const nextPhase = rows.length === 0 ? (state.phase === 'entries' ? 'keys' : 'complete') : state.phase;
|
||||
const nextCursor = rows.at(-1)?.migration_rowid ?? 0;
|
||||
destination.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
for (const row of rows) {
|
||||
if (!['image', 'record', 'video'].includes(row.type)) {
|
||||
throw new Error(`unsupported legacy media type at row ${row.migration_rowid}`);
|
||||
}
|
||||
if (state.phase === 'entries') {
|
||||
const info: unknown = JSON.parse(row.data);
|
||||
if (!info || typeof info !== 'object' || Array.isArray(info)) {
|
||||
throw new Error(`invalid legacy media metadata at row ${row.migration_rowid}`);
|
||||
}
|
||||
insertEntry.run(row.type, foldMediaKey(row.primary_key), serializeMediaInfo(info), row.last_seen);
|
||||
} else {
|
||||
insertKey.run(row.type, foldMediaKey(row.key), foldMediaKey(row.primary_key));
|
||||
}
|
||||
}
|
||||
saveState.run(nextPhase, nextCursor);
|
||||
destination.exec('COMMIT');
|
||||
} catch (error) {
|
||||
rollbackMediaTransaction(destination, error);
|
||||
}
|
||||
state.phase = nextPhase;
|
||||
state.cursor = nextCursor;
|
||||
log.debug('preserving legacy media metadata: phase=%s cursor=%d', state.phase, state.cursor);
|
||||
// Yield between committed batches so cancellation is handled by the worker.
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
||||
}
|
||||
if (!cancelled()) log.info('preserving legacy media metadata: migration complete; source retained');
|
||||
} finally {
|
||||
source?.close();
|
||||
destination.close();
|
||||
}
|
||||
}
|
||||
+118
-194
@@ -60,239 +60,171 @@ const TYPE_IMAGE = 'image';
|
||||
const TYPE_RECORD = 'record';
|
||||
const TYPE_VIDEO = 'video';
|
||||
const DEFAULT_KEEP_ENTRIES = 4096;
|
||||
export type MediaLookupSource = 'current' | 'legacy';
|
||||
/** SQLite keys / aliases longer than this are folded to a short digest. */
|
||||
export const MEDIA_KEY_MAX_CHARS = 2048;
|
||||
/** Persisted JSON must stay well under a page-overflow storm. */
|
||||
export const MEDIA_DATA_MAX_CHARS = 64 * 1024;
|
||||
const INLINE_MEDIA_SOURCE = /^(base64:\/\/|data:)/i;
|
||||
|
||||
/** Durable media metadata. Production shares messages.db with MessageStore.
|
||||
* Only the in-memory lookup cache is bounded; history dependencies never expire.
|
||||
*/
|
||||
export class MediaStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly maxEntriesPerType: number;
|
||||
|
||||
// Prepared statements (pay the parsing cost once at startup).
|
||||
private readonly cache = new Map<string, string>();
|
||||
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);
|
||||
private readonly findEntry: StatementSync;
|
||||
private readonly findLegacyEntry: StatementSync;
|
||||
|
||||
constructor(dbPath: string, private readonly maxCachedEntries = DEFAULT_KEEP_ENTRIES) {
|
||||
this.db = openSqliteDb(dbPath);
|
||||
this.initSchema();
|
||||
this.purgeOversizedRows();
|
||||
|
||||
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 = ?`,
|
||||
);
|
||||
for (const prefix of ['', 'legacy_']) {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS ${prefix}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 TABLE IF NOT EXISTS ${prefix}media_keys (
|
||||
type TEXT NOT NULL, key TEXT NOT NULL, primary_key TEXT NOT NULL,
|
||||
PRIMARY KEY (type, key)
|
||||
);
|
||||
`);
|
||||
}
|
||||
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.findEntry = this.db.prepare(`
|
||||
SELECT data FROM media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
this.findLegacyEntry = this.db.prepare(`
|
||||
SELECT data FROM legacy_media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM legacy_media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
close(): void { this.cache.clear(); 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]);
|
||||
this.remember(TYPE_IMAGE, 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]);
|
||||
this.remember(TYPE_RECORD, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
}
|
||||
|
||||
rememberVideo(info: CachedVideo): void {
|
||||
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
|
||||
if (!primaryKey) return;
|
||||
this.upsertWithAliases(TYPE_VIDEO, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
this.remember(TYPE_VIDEO, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
}
|
||||
|
||||
findImage(key: string): CachedImage | null {
|
||||
return this.findByAnyKey<CachedImage>(TYPE_IMAGE, key);
|
||||
findImage(key: string, source: MediaLookupSource = 'current'): CachedImage | null {
|
||||
return this.find(TYPE_IMAGE, key, source);
|
||||
}
|
||||
findRecord(key: string, source: MediaLookupSource = 'current'): CachedRecord | null {
|
||||
return this.find(TYPE_RECORD, key, source);
|
||||
}
|
||||
findVideo(key: string, source: MediaLookupSource = 'current'): CachedVideo | null {
|
||||
return this.find(TYPE_VIDEO, key, source);
|
||||
}
|
||||
|
||||
findRecord(key: string): CachedRecord | null {
|
||||
return this.findByAnyKey<CachedRecord>(TYPE_RECORD, key);
|
||||
}
|
||||
updateImageUrl(key: string, url: string): void { this.updateUrl(TYPE_IMAGE, key, url); }
|
||||
updateRecordUrl(key: string, url: string): void { this.updateUrl(TYPE_RECORD, key, url); }
|
||||
updateVideoUrl(key: string, url: string): void { this.updateUrl(TYPE_VIDEO, key, url); }
|
||||
|
||||
findVideo(key: string): CachedVideo | null {
|
||||
return this.findByAnyKey<CachedVideo>(TYPE_VIDEO, key);
|
||||
}
|
||||
|
||||
updateImageUrl(key: string, url: string): void {
|
||||
if (!url || mustFoldMediaKey(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 || mustFoldMediaKey(url)) return;
|
||||
const cached = this.findRecord(key);
|
||||
if (!cached || cached.url === url) return;
|
||||
this.rememberRecord({ ...cached, url });
|
||||
}
|
||||
|
||||
updateVideoUrl(key: string, url: string): void {
|
||||
if (!url || mustFoldMediaKey(url)) return;
|
||||
const cached = this.findVideo(key);
|
||||
if (!cached || cached.url === url) return;
|
||||
this.rememberVideo({ ...cached, url });
|
||||
}
|
||||
|
||||
/** Snapshot count of distinct entries per type; mostly used by tests. */
|
||||
/** Counts durable records, not the bounded lookup cache. */
|
||||
size(): { images: number; records: number; videos: number } {
|
||||
const img = this.countByType.get(TYPE_IMAGE) as { n: number } | undefined;
|
||||
const rec = this.countByType.get(TYPE_RECORD) as { n: number } | undefined;
|
||||
const vid = this.countByType.get(TYPE_VIDEO) as { n: number } | undefined;
|
||||
return { images: img?.n ?? 0, records: rec?.n ?? 0, videos: vid?.n ?? 0 };
|
||||
const counts = this.db.prepare(`SELECT type, COUNT(*) AS n FROM (
|
||||
SELECT type FROM media_entries UNION ALL SELECT type FROM legacy_media_entries
|
||||
) GROUP BY type`)
|
||||
.all() as Array<{ type: string; n: number }>;
|
||||
const count = (type: string) => counts.find(row => row.type === type)?.n ?? 0;
|
||||
return { images: count(TYPE_IMAGE), records: count(TYPE_RECORD), videos: count(TYPE_VIDEO) };
|
||||
}
|
||||
|
||||
// --- 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 purgeOversizedRows(): void {
|
||||
// Older builds could persist a whole inline payload as the key / JSON.
|
||||
// Drop those rows on open so later eviction does not walk overflow pages.
|
||||
this.db.exec(`
|
||||
DELETE FROM media_keys
|
||||
WHERE length(key) > ${MEDIA_KEY_MAX_CHARS}
|
||||
OR length(primary_key) > ${MEDIA_KEY_MAX_CHARS};
|
||||
DELETE FROM media_entries
|
||||
WHERE length(primary_key) > ${MEDIA_KEY_MAX_CHARS}
|
||||
OR length(data) > ${MEDIA_DATA_MAX_CHARS};
|
||||
DELETE FROM media_keys
|
||||
WHERE primary_key NOT IN (SELECT primary_key FROM media_entries);
|
||||
`);
|
||||
}
|
||||
|
||||
private upsertWithAliases<T extends object>(
|
||||
type: string,
|
||||
primaryKey: string,
|
||||
info: T,
|
||||
aliases: (string | undefined)[],
|
||||
): void {
|
||||
const data = JSON.stringify(persistableMediaInfo(info));
|
||||
if (data.length > MEDIA_DATA_MAX_CHARS) return;
|
||||
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');
|
||||
private remember(type: string, info: object, aliases: string[]): void {
|
||||
const primary = pickPrimary(aliases);
|
||||
if (!primary) throw new Error(`cannot store ${type} metadata without an identifier`);
|
||||
const data = serializeMediaInfo(info);
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
this.upsertEntry.run(type, primaryKey, data, lastSeen);
|
||||
const seen = new Set<string>();
|
||||
for (const raw of aliases) {
|
||||
if (!raw) continue;
|
||||
const key = foldMediaKey(raw);
|
||||
if (!key || seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
this.upsertKey.run(type, key, primaryKey);
|
||||
this.upsertEntry.run(type, primary, data, Math.floor(Date.now() / 1000));
|
||||
for (const key of new Set(aliases.filter(Boolean).map(foldMediaKey))) {
|
||||
this.upsertKey.run(type, key, primary);
|
||||
}
|
||||
this.db.exec('COMMIT');
|
||||
} catch (err) {
|
||||
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
|
||||
throw err;
|
||||
} catch (error) {
|
||||
rollbackMediaTransaction(this.db, error);
|
||||
}
|
||||
|
||||
// Eager eviction. Skip the DELETE entirely while we are under the cap.
|
||||
this.evictOldEntries(type);
|
||||
// Alias remapping can invalidate any cached lookup. JSON strings ensure
|
||||
// callers cannot mutate the durable record through a returned object.
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
private findByAnyKey<T>(type: string, key: string): T | null {
|
||||
private find<T>(type: string, key: string, source: MediaLookupSource = 'current'): T | null {
|
||||
const lookup = foldMediaKey(key);
|
||||
if (!lookup) return null;
|
||||
const row = this.findEntryByKey.get(type, lookup) 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, lookup) as { data: string } | undefined;
|
||||
return fallback?.data ? safeParse<T>(fallback.data) : null;
|
||||
const cacheKey = `${source}:${type}:${lookup}`;
|
||||
let data = this.cache.get(cacheKey);
|
||||
if (data === undefined) {
|
||||
// Legacy history has no per-message snapshots. Its frozen migration
|
||||
// index must never resolve through a later, mutable filename alias.
|
||||
const current = source === 'current' ? this.findEntry.get(type, type, lookup, lookup) : undefined;
|
||||
const row = (current ?? this.findLegacyEntry.get(type, type, lookup, lookup)) as { data: string } | undefined;
|
||||
if (!row) return null;
|
||||
data = row.data;
|
||||
}
|
||||
// Parse before caching: malformed persisted metadata is an observable error.
|
||||
const result: unknown = JSON.parse(data);
|
||||
if (!result || typeof result !== 'object' || Array.isArray(result)) {
|
||||
throw new Error(`invalid persisted ${type} metadata`);
|
||||
}
|
||||
this.cache.delete(cacheKey);
|
||||
this.cache.set(cacheKey, data);
|
||||
while (this.cache.size > Math.max(0, this.maxCachedEntries)) {
|
||||
this.cache.delete(this.cache.keys().next().value!);
|
||||
}
|
||||
return result as T;
|
||||
}
|
||||
|
||||
private evictOldEntries(type: string): void {
|
||||
try {
|
||||
const row = this.countByType.get(type) as { n: number } | undefined;
|
||||
if ((row?.n ?? 0) <= this.maxEntriesPerType) return;
|
||||
this.evictByType.run(type, type, this.maxEntriesPerType);
|
||||
this.purgeOrphanKeys.run(type, type);
|
||||
} catch {
|
||||
// Best-effort eviction; don't propagate.
|
||||
}
|
||||
private updateUrl(type: string, key: string, url: string): void {
|
||||
if (!url || mustFoldMediaKey(url)) return;
|
||||
const info = this.find<Record<string, unknown>>(type, key);
|
||||
if (!info || info.url === url) return;
|
||||
this.remember(type, { ...info, url }, [info.file, info.fileName, info.fileId, url]
|
||||
.filter((value): value is string => typeof value === 'string'));
|
||||
}
|
||||
}
|
||||
|
||||
export function serializeMediaInfo(info: object): string {
|
||||
const data = JSON.stringify(persistableMediaInfo(info));
|
||||
if (data.length > MEDIA_DATA_MAX_CHARS) {
|
||||
throw new Error(`media metadata exceeds storage limit (${data.length} characters)`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export function rollbackMediaTransaction(db: DatabaseSync, error: unknown): never {
|
||||
try { db.exec('ROLLBACK'); }
|
||||
catch (rollbackError) {
|
||||
throw new AggregateError([error, rollbackError], 'media write and rollback failed', { cause: error });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
function mustFoldMediaKey(value: string): boolean {
|
||||
return value.length > MEDIA_KEY_MAX_CHARS || INLINE_MEDIA_SOURCE.test(value);
|
||||
}
|
||||
|
||||
function foldMediaKey(value: string): string {
|
||||
export function foldMediaKey(value: string): string {
|
||||
if (!value) return '';
|
||||
if (!mustFoldMediaKey(value)) return value;
|
||||
return `inline:${createHash('sha256').update(value).digest('hex')}`;
|
||||
@@ -317,11 +249,3 @@ function pickPrimary(candidates: (string | undefined)[]): string {
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function safeParse<T>(json: string): T | null {
|
||||
try {
|
||||
return JSON.parse(json) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { serializeMediaInfo } from './media-store';
|
||||
import type { JsonObject } from './types';
|
||||
|
||||
export type MessageMedia = Extract<MessageElement, { type: 'image' | 'record' | 'video' }>;
|
||||
const mediaSnapshot = Symbol('message media snapshot');
|
||||
type MediaSegment = JsonObject & { [mediaSnapshot]?: MessageMedia };
|
||||
|
||||
export function isMessageMedia(element: MessageElement): element is MessageMedia {
|
||||
return element.type === 'image' || element.type === 'record' || element.type === 'video';
|
||||
}
|
||||
|
||||
/** Keep persistence-only metadata beside the converted segment, never on the
|
||||
* public JSON wire. Capture after successful conversion so skipped elements
|
||||
* cannot shift the association between a message and its media snapshots.
|
||||
*/
|
||||
export function attachMessageMedia(segment: JsonObject, element: MessageElement): void {
|
||||
if (!isMessageMedia(element)) return;
|
||||
const { type, fileId, fileName, fileSize, url, imageUrl, md5Hex, sha1Hex,
|
||||
subType, summary, width, height, picFormat, duration, voiceFormat,
|
||||
videoFormat, fileHash, mediaNode, flash } = element;
|
||||
const snapshot = JSON.parse(serializeMediaInfo({
|
||||
type, fileId, fileName, fileSize, url, imageUrl, md5Hex, sha1Hex,
|
||||
subType, summary, width, height, picFormat, duration, voiceFormat,
|
||||
videoFormat, fileHash, mediaNode, flash,
|
||||
})) as MessageMedia;
|
||||
Object.defineProperty(segment, mediaSnapshot, { value: snapshot });
|
||||
}
|
||||
|
||||
export function serializeMessageMedia(event: JsonObject): string | null {
|
||||
if (!Array.isArray(event.message)) return null;
|
||||
const snapshots = event.message.flatMap(segment => {
|
||||
if (!segment || typeof segment !== 'object' || Array.isArray(segment)) return [];
|
||||
const snapshot = (segment as MediaSegment)[mediaSnapshot];
|
||||
return snapshot ? [snapshot] : [];
|
||||
});
|
||||
return snapshots.length > 0 ? JSON.stringify(snapshots) : null;
|
||||
}
|
||||
|
||||
export function parseMessageMedia(data: string): MessageMedia[] {
|
||||
const parsed: unknown = JSON.parse(data);
|
||||
if (!Array.isArray(parsed) || parsed.some(value => !value || typeof value !== 'object'
|
||||
|| !['image', 'record', 'video'].includes(value.type))) {
|
||||
throw new Error('invalid persisted message media metadata');
|
||||
}
|
||||
return parsed as MessageMedia[];
|
||||
}
|
||||
|
||||
/** A repeated server representation may omit fields already learned from an
|
||||
* upload or earlier receive. Preserve those fields only for the same resource;
|
||||
* conflicting fingerprints or uncertain associations must not rewrite history.
|
||||
*/
|
||||
export function mergeMessageMedia(previous: string | null, next: string | null): string | null {
|
||||
if (!previous) return next;
|
||||
if (previous === next) return previous;
|
||||
if (!next) throw new Error('message update is missing previously stored media metadata');
|
||||
const oldMedia = parseMessageMedia(previous);
|
||||
const newMedia = parseMessageMedia(next);
|
||||
if (oldMedia.length !== newMedia.length) throw new Error('message media association changed');
|
||||
const merged = newMedia.map((media, index) => {
|
||||
const old = oldMedia[index]!;
|
||||
if (old.type !== media.type) throw new Error('message media association changed');
|
||||
let matched = false;
|
||||
for (const field of ['md5Hex', 'sha1Hex'] as const) {
|
||||
if (!old[field] || !media[field]) continue;
|
||||
if (old[field].toLowerCase() !== media[field].toLowerCase()) {
|
||||
throw new Error('message update has conflicting media fingerprints');
|
||||
}
|
||||
matched = true;
|
||||
}
|
||||
// Images can expose a filename as fileId, so only their fingerprints can
|
||||
// prove an association. Voice/video fileId is a source resource UUID.
|
||||
matched ||= media.type !== 'image' && !!old.fileId && old.fileId === media.fileId;
|
||||
if (!matched && JSON.stringify(old) !== JSON.stringify(media)) {
|
||||
throw new Error('message update has an unverified media association');
|
||||
}
|
||||
return mergeKnownMediaFields(old, media);
|
||||
});
|
||||
return JSON.stringify(merged);
|
||||
}
|
||||
|
||||
function mergeKnownMediaFields(old: object, next: object): Record<string, unknown> {
|
||||
const merged: Record<string, unknown> = { ...old };
|
||||
for (const [key, value] of Object.entries(next)) {
|
||||
// Zero dimensions, sizes and durations are incomplete observations, not
|
||||
// evidence that known properties of the same resource have changed.
|
||||
if (value === undefined || value === null || value === '' || value === 0) continue;
|
||||
const previous = merged[key];
|
||||
merged[key] = typeof value === 'object' && !Array.isArray(value)
|
||||
&& previous !== null && typeof previous === 'object' && !Array.isArray(previous)
|
||||
? mergeKnownMediaFields(previous, value)
|
||||
: value;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export interface ParseMessageOptions {
|
||||
senderUin: number;
|
||||
time: number;
|
||||
random: number;
|
||||
elements?: MessageElement[];
|
||||
sequenceAuthoritative?: boolean;
|
||||
} | null;
|
||||
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
import { Worker, type WorkerOptions } from 'node:worker_threads';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
DatabaseMigrationCallbacks,
|
||||
DatabaseMigrationTask,
|
||||
@@ -29,6 +30,7 @@ export function createMessageStoreMigrationTask(
|
||||
uin: string,
|
||||
createWorker: CreateMigrationWorker = (filename, options) => new Worker(filename, options),
|
||||
): DatabaseMigrationTask {
|
||||
const log = createLogger('OneBot.MessageMigration').child({ uin: Number(uin) });
|
||||
let worker: MessageStoreMigrationWorkerHandle | null = null;
|
||||
let cancelled = false;
|
||||
let finished = false;
|
||||
@@ -59,6 +61,15 @@ export function createMessageStoreMigrationTask(
|
||||
if (cancelled) return;
|
||||
if (message.kind === 'ready') {
|
||||
callbacks.onReady();
|
||||
} else if (message.kind === 'preparation') {
|
||||
const progress = message.progress;
|
||||
if (progress.stage === 'started') {
|
||||
log.info('preparing message history migration');
|
||||
} else if (progress.stage === 'indexed') {
|
||||
log.info('message history migration preparation finished in %dms', Math.round(progress.elapsedMs));
|
||||
} else {
|
||||
log.info('message history migration: pending=%d checked in %dms', progress.total, Math.round(progress.elapsedMs));
|
||||
}
|
||||
} else if (message.kind === 'progress') {
|
||||
callbacks.onProgress(message.status, message.elapsedMs);
|
||||
if (message.status.phase === 'complete') finished = true;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { parentPort, workerData } from 'node:worker_threads';
|
||||
import { migrateLegacyMedia } from './media-store-migration';
|
||||
import {
|
||||
MessageStoreMigrator,
|
||||
prepareMessageStoreDatabase,
|
||||
type MessageStoreMigrationPreparation,
|
||||
type MessageStoreMigrationStatus,
|
||||
} from './message-store-migration';
|
||||
|
||||
@@ -16,6 +18,7 @@ export interface MessageStoreMigrationWorkerData {
|
||||
|
||||
export type MessageStoreMigrationWorkerMessage =
|
||||
| { kind: 'ready' }
|
||||
| { kind: 'preparation'; progress: MessageStoreMigrationPreparation }
|
||||
| {
|
||||
kind: 'progress';
|
||||
status: MessageStoreMigrationStatus;
|
||||
@@ -49,10 +52,14 @@ export async function runMessageStoreMigrationWorker(
|
||||
|
||||
try {
|
||||
prepareMessageStoreDatabase(data.dbPath);
|
||||
await migrateLegacyMedia(data.dbPath, () => cancelled);
|
||||
if (cancelled) return;
|
||||
port.postMessage({ kind: 'ready' } satisfies MessageStoreMigrationWorkerMessage);
|
||||
await startRequested;
|
||||
if (cancelled) return;
|
||||
migrator = new MessageStoreMigrator(data.dbPath);
|
||||
migrator = new MessageStoreMigrator(data.dbPath, progress => {
|
||||
port.postMessage({ kind: 'preparation', progress } satisfies MessageStoreMigrationWorkerMessage);
|
||||
});
|
||||
let lastProgressAt: number | null = null;
|
||||
|
||||
while (!cancelled) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
|
||||
const CLASSIFICATION_VERSION = 1;
|
||||
const PENDING_INDEX_NAME = `idx_messages_pending_classification_v${CLASSIFICATION_VERSION}`;
|
||||
const MIGRATION_NAME = 'message-classification-v1';
|
||||
const LEGACY_PRIVATE_SEQUENCE_MIGRATION = 'private-nt-sequence-v1';
|
||||
|
||||
@@ -13,6 +14,11 @@ export interface MessageStoreMigrationStatus {
|
||||
total: number;
|
||||
}
|
||||
|
||||
export type MessageStoreMigrationPreparation =
|
||||
| { stage: 'started' }
|
||||
| { stage: 'indexed'; elapsedMs: number }
|
||||
| { stage: 'counted'; total: number; elapsedMs: number };
|
||||
|
||||
interface MigrationStateRow {
|
||||
phase: MessageStoreMigrationPhase;
|
||||
processed: number;
|
||||
@@ -39,42 +45,47 @@ export class MessageStoreMigrator {
|
||||
private readonly updateState: StatementSync;
|
||||
private state: MigrationStateRow;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
constructor(dbPath: string, reportPreparation?: (progress: MessageStoreMigrationPreparation) => void) {
|
||||
this.db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
|
||||
createMigrationStateTable(this.db);
|
||||
this.state = this.loadOrCreateState();
|
||||
this.selectInitialBatch = this.db.prepare(`
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
this.selectNextBatch = this.db.prepare(`
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ? AND message_hash > ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
this.updateRow = this.db.prepare(`
|
||||
UPDATE messages
|
||||
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
|
||||
WHERE message_hash = ?
|
||||
AND classification_version < ?
|
||||
AND is_group = ?
|
||||
AND sequence = ?
|
||||
AND sequence_authoritative = ?
|
||||
AND client_sequence = ?
|
||||
AND private_direction = ?
|
||||
AND random = ?
|
||||
AND data IS ?
|
||||
`);
|
||||
this.updateState = this.db.prepare(`
|
||||
UPDATE message_store_migration_state
|
||||
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
|
||||
WHERE name = ?
|
||||
`);
|
||||
try {
|
||||
createMigrationStateTable(this.db);
|
||||
this.state = this.loadOrCreateState(reportPreparation);
|
||||
this.selectInitialBatch = this.db.prepare(`
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
this.selectNextBatch = this.db.prepare(`
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ? AND message_hash > ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
this.updateRow = this.db.prepare(`
|
||||
UPDATE messages
|
||||
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
|
||||
WHERE message_hash = ?
|
||||
AND classification_version < ?
|
||||
AND is_group = ?
|
||||
AND sequence = ?
|
||||
AND sequence_authoritative = ?
|
||||
AND client_sequence = ?
|
||||
AND private_direction = ?
|
||||
AND random = ?
|
||||
AND data IS ?
|
||||
`);
|
||||
this.updateState = this.db.prepare(`
|
||||
UPDATE message_store_migration_state
|
||||
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
|
||||
WHERE name = ?
|
||||
`);
|
||||
} catch (error) {
|
||||
this.db.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
@@ -153,20 +164,32 @@ export class MessageStoreMigrator {
|
||||
return this.getStatus();
|
||||
}
|
||||
|
||||
private loadOrCreateState(): MigrationStateRow {
|
||||
private loadOrCreateState(reportPreparation?: (progress: MessageStoreMigrationPreparation) => void): MigrationStateRow {
|
||||
const existing = this.db.prepare(`
|
||||
SELECT phase, processed, total, cursor
|
||||
FROM message_store_migration_state
|
||||
WHERE name = ?
|
||||
`).get(MIGRATION_NAME) as MigrationStateRow | undefined;
|
||||
if (existing?.phase === 'complete') return existing;
|
||||
|
||||
reportPreparation?.({ stage: 'started' });
|
||||
const preparationStartedAt = performance.now();
|
||||
this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS ${PENDING_INDEX_NAME}
|
||||
ON messages(message_hash, classification_version)
|
||||
WHERE classification_version < ${CLASSIFICATION_VERSION}
|
||||
`);
|
||||
reportPreparation?.({ stage: 'indexed', elapsedMs: Math.max(0, performance.now() - preparationStartedAt) });
|
||||
if (existing) return existing;
|
||||
|
||||
const countStartedAt = performance.now();
|
||||
const row = this.db.prepare(`
|
||||
SELECT COUNT(*) AS total
|
||||
FROM messages
|
||||
WHERE classification_version < ?
|
||||
`).get(CLASSIFICATION_VERSION) as { total: number };
|
||||
const total = Number(row.total);
|
||||
reportPreparation?.({ stage: 'counted', total, elapsedMs: Math.max(0, performance.now() - countStartedAt) });
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const state: MigrationStateRow = {
|
||||
phase: total === 0 ? 'complete' : 'migrating',
|
||||
@@ -279,6 +302,9 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
|
||||
export function prepareMessageStoreSchema(db: DatabaseSync): void {
|
||||
const before = db.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }>;
|
||||
const existingColumns = new Set(before.map((column) => column.name));
|
||||
if (!existingColumns.has('media_data')) {
|
||||
db.exec('ALTER TABLE messages ADD COLUMN media_data TEXT');
|
||||
}
|
||||
const existingRowsAreCurrent = existingColumns.has('sequence_authoritative')
|
||||
&& existingColumns.has('private_direction')
|
||||
&& hasLegacyPrivateSequenceMigration(db);
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { JsonObject, MessageMeta } from './types';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { cqUnescape } from './helper/cq';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
import { mergeMessageMedia, parseMessageMedia, serializeMessageMedia, type MessageMedia } from './message-media';
|
||||
import {
|
||||
createMessageStoreIndexes,
|
||||
prepareMessageStoreSchema,
|
||||
@@ -32,6 +35,7 @@ export class MessageStore {
|
||||
private readonly stmtStoreEvent: StatementSync;
|
||||
private readonly stmtStoreMeta: StatementSync;
|
||||
private readonly stmtFindEvent: StatementSync;
|
||||
private readonly stmtFindMedia: StatementSync;
|
||||
private readonly stmtFindMeta: StatementSync;
|
||||
private readonly stmtResolveReplyGroup: StatementSync;
|
||||
private readonly stmtResolveReplyPrivate: StatementSync;
|
||||
@@ -59,8 +63,8 @@ export class MessageStore {
|
||||
// Database instance — `close()` finalizes them automatically.
|
||||
this.stmtStoreEvent = this.db.prepare(
|
||||
`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp, data, classification_version)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 0, ?, 0, ?, ?, 1)
|
||||
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp, data, media_data, classification_version)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 0, ?, 0, ?, ?, ?, 1)
|
||||
ON CONFLICT(message_hash) DO UPDATE SET
|
||||
is_group = excluded.is_group,
|
||||
session_id = excluded.session_id,
|
||||
@@ -76,6 +80,7 @@ export class MessageStore {
|
||||
END,
|
||||
timestamp = excluded.timestamp,
|
||||
data = excluded.data,
|
||||
media_data = excluded.media_data,
|
||||
classification_version = CASE
|
||||
WHEN excluded.is_group = 1 THEN excluded.classification_version
|
||||
ELSE messages.classification_version
|
||||
@@ -103,6 +108,8 @@ export class MessageStore {
|
||||
'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL',
|
||||
);
|
||||
|
||||
this.stmtFindMedia = this.db.prepare('SELECT media_data FROM messages WHERE message_hash = ?');
|
||||
|
||||
this.stmtFindMeta = this.db.prepare(
|
||||
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp FROM messages WHERE message_hash = ?',
|
||||
);
|
||||
@@ -191,11 +198,9 @@ export class MessageStore {
|
||||
);
|
||||
|
||||
this.stmtFindPrivateMessageAtTime = this.db.prepare(
|
||||
`SELECT message_hash
|
||||
`SELECT message_hash, data
|
||||
FROM messages
|
||||
WHERE is_group = 0 AND session_id = ? AND private_direction = ? AND timestamp = ?
|
||||
ORDER BY sequence DESC
|
||||
LIMIT 1`,
|
||||
WHERE is_group = 0 AND session_id = ? AND private_direction = ? AND timestamp = ?`,
|
||||
);
|
||||
|
||||
this.stmtFindPrivateMessageBySequence = this.db.prepare(
|
||||
@@ -275,6 +280,8 @@ export class MessageStore {
|
||||
}
|
||||
}
|
||||
|
||||
const previous = this.stmtFindMedia.get(messageId) as { media_data: string | null } | undefined;
|
||||
const media = mergeMessageMedia(previous?.media_data ?? null, serializeMessageMedia(event));
|
||||
this.stmtStoreEvent.run(
|
||||
messageId,
|
||||
isGroup ? 1 : 0,
|
||||
@@ -285,9 +292,16 @@ export class MessageStore {
|
||||
privateDirection,
|
||||
timestamp,
|
||||
json,
|
||||
media,
|
||||
);
|
||||
}
|
||||
|
||||
findMedia(messageId: number): MessageMedia[] | null {
|
||||
if (!isValidMessageId(messageId)) return null;
|
||||
const row = this.stmtFindMedia.get(messageId) as { media_data: string | null } | undefined;
|
||||
return row?.media_data != null ? parseMessageMedia(row.media_data) : null;
|
||||
}
|
||||
|
||||
storeMeta(messageId: number, meta: MessageMeta): void {
|
||||
if (!isValidMessageId(messageId)) return;
|
||||
const privateDirection = encodePrivateDirection(meta.privateDirection);
|
||||
@@ -514,6 +528,7 @@ export class MessageStore {
|
||||
replySequence: number,
|
||||
sentBySelf: boolean,
|
||||
timestamp?: number,
|
||||
replyElements?: readonly MessageElement[],
|
||||
): number | null {
|
||||
if (Number.isSafeInteger(replySequence) && replySequence > 0) {
|
||||
const byClientSequence = this.findPrivateMessageId(
|
||||
@@ -531,7 +546,7 @@ export class MessageStore {
|
||||
if (byConversationSequence !== null) return byConversationSequence;
|
||||
}
|
||||
if (!sentBySelf) return null;
|
||||
const byExactTime = this.findPrivateMessageIdAtTime(sessionId, true, timestamp);
|
||||
const byExactTime = this.findPrivateMessageIdAtTime(sessionId, true, timestamp, replyElements);
|
||||
if (byExactTime !== null) return byExactTime;
|
||||
const byNearbyTime = this.findUniquePrivateOutgoingNearTime(sessionId, timestamp);
|
||||
if (byNearbyTime !== null) return byNearbyTime;
|
||||
@@ -542,15 +557,32 @@ export class MessageStore {
|
||||
sessionId: number,
|
||||
sentBySelf: boolean,
|
||||
timestamp?: number,
|
||||
replyElements?: readonly MessageElement[],
|
||||
): number | null {
|
||||
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) return null;
|
||||
if (!isUsablePrivateQuoteTime(timestamp)) return null;
|
||||
const row = this.stmtFindPrivateMessageAtTime.get(
|
||||
const rows = this.stmtFindPrivateMessageAtTime.all(
|
||||
sessionId,
|
||||
sentBySelf ? 1 : 0,
|
||||
timestamp,
|
||||
) as { message_hash: number } | undefined;
|
||||
if (!row) return null;
|
||||
) as { message_hash: number; data: string | null }[];
|
||||
if (rows.length === 0) return null;
|
||||
let matches = rows;
|
||||
if (rows.length > 1) {
|
||||
const text = replyElements?.length && replyElements.every(e => e.type === 'text')
|
||||
? replyElements.map(e => e.text ?? '').join('')
|
||||
: null;
|
||||
const candidates = text ? rows.map(row => ({ row, preview: cachedQuoteText(row.data) }))
|
||||
.filter(({ preview }) => preview === null || preview.text.startsWith(text)) : [];
|
||||
matches = candidates.length === 1 && candidates[0]!.preview?.plain
|
||||
&& candidates[0]!.preview.text === text ? [candidates[0]!.row] : [];
|
||||
if (matches.length !== 1) {
|
||||
log.debug('private quote time is ambiguous: peer=%d time=%d candidates=%d contentMatches=%d',
|
||||
sessionId, timestamp, rows.length, matches.length);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const row = matches[0]!;
|
||||
if (!isValidMessageId(row.message_hash)) {
|
||||
throw new Error(`private message lookup matched invalid message id ${String(row.message_hash)}`);
|
||||
}
|
||||
@@ -822,6 +854,32 @@ function eventPrivateDirection(isGroup: boolean, event: JsonObject): number {
|
||||
|
||||
const PRIVATE_REPLY_TIME_WINDOWS_SECONDS = [5, 30] as const;
|
||||
|
||||
/** Unknown, truncated, and media previews remain possible competing matches. */
|
||||
function cachedQuoteText(data: string | null): { text: string; plain: boolean } | null {
|
||||
if (!data) return null;
|
||||
const event = JSON.parse(data) as JsonObject;
|
||||
if (typeof event.message === 'string') {
|
||||
return event.message.includes('[CQ:') ? null : { text: cqUnescape(event.message), plain: true };
|
||||
}
|
||||
if (!Array.isArray(event.message) || event.message.length === 0) return null;
|
||||
const segments = event.message as JsonObject[];
|
||||
const labels: Record<string, string> = {
|
||||
image: '[图片]', record: '[语音]', video: '[视频]', file: '[文件]',
|
||||
face: '[表情]', mface: '[表情]', forward: '[聊天记录]', json: '[卡片]', xml: '[卡片]',
|
||||
};
|
||||
const parts: string[] = [];
|
||||
let plain = true;
|
||||
for (const segment of segments) {
|
||||
const body = segment?.data as JsonObject | undefined;
|
||||
if (segment?.type === 'text' && typeof body?.text === 'string') parts.push(body.text);
|
||||
else if (typeof segment?.type === 'string' && labels[segment.type]) {
|
||||
parts.push(typeof body?.summary === 'string' ? body.summary : labels[segment.type]!);
|
||||
plain = false;
|
||||
} else return null;
|
||||
}
|
||||
return { text: parts.join(''), plain };
|
||||
}
|
||||
|
||||
function isUsablePrivateQuoteTime(timestamp: number | undefined): timestamp is number {
|
||||
return timestamp !== undefined
|
||||
&& Number.isSafeInteger(timestamp)
|
||||
|
||||
@@ -101,6 +101,9 @@ export async function getGroupList(
|
||||
group_create_time: g.createTime ?? 0,
|
||||
group_level: g.level ?? 0,
|
||||
group_memo: g.memo ?? '',
|
||||
// #490: the description is its own field; group_memo prefers the
|
||||
// announcement, so it can't be used to recover the description.
|
||||
group_description: g.description ?? '',
|
||||
group_all_shut: g.allMuted ? -1 : 0,
|
||||
}));
|
||||
}
|
||||
@@ -175,6 +178,7 @@ export async function getGroupInfo(
|
||||
group_create_time: g.createTime ?? 0,
|
||||
group_level: await getGroupLevel(bridge, groupId, noCache),
|
||||
group_memo: g.memo ?? '',
|
||||
group_description: g.description ?? '',
|
||||
group_all_shut: g.allMuted ? -1 : 0,
|
||||
};
|
||||
}
|
||||
@@ -198,6 +202,10 @@ export async function getGroupInfo(
|
||||
group_create_time: detail.createTime ?? 0,
|
||||
group_level: detail.level ?? 0,
|
||||
group_memo: detail.memo ?? '',
|
||||
// #490: always '' here — the non-member detail lookup has no
|
||||
// description to read (see QQGroupInfo.description). The key is still
|
||||
// returned so the response shape doesn't change with membership.
|
||||
group_description: detail.description ?? '',
|
||||
group_all_shut: detail.allMuted ? -1 : 0,
|
||||
};
|
||||
nonMemberGroupCache.set(cacheKey, { info, at: Date.now() });
|
||||
@@ -256,11 +264,12 @@ export async function getGroupMemberInfo(
|
||||
// 企点标志(#404 后续 PR):优先读身份缓存,无缓存时再按需拉取一次用户资料。
|
||||
// 均为 best-effort —— 失败时回退为 0,不影响成员信息主流程。
|
||||
let profile = cachedQidianProfile(bridge, userId);
|
||||
if (!profile) {
|
||||
if (noCache || !profile) {
|
||||
try {
|
||||
profile = await bridge.apis.contacts.fetchUserProfile(userId);
|
||||
} catch {
|
||||
// profile enrichment is best-effort; fall back to all-zero flags
|
||||
} catch (error) {
|
||||
log.warn('group member profile unavailable: group=%d member=%d error=%s',
|
||||
groupId, userId, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
return formatGroupMember(groupId, m, profile ?? undefined);
|
||||
@@ -304,13 +313,20 @@ export async function getGroupFiles(
|
||||
function formatStrangerInfo(p: UserProfileInfo, corp?: QidianCorpInfo | null): JsonObject {
|
||||
return {
|
||||
user_id: p.uin,
|
||||
uid: p.uid,
|
||||
qid: p.qid,
|
||||
nickname: p.nickname,
|
||||
remark: p.remark,
|
||||
sex: p.sex,
|
||||
age: p.age,
|
||||
long_nick: p.sign,
|
||||
qq_level: p.level,
|
||||
qqLevel: p.level,
|
||||
level: p.level,
|
||||
...(p.regTime !== undefined ? { reg_time: p.regTime } : {}),
|
||||
...(p.svipFlag !== undefined ? { is_vip: p.svipFlag } : {}),
|
||||
...(p.yearVipFlag !== undefined ? { is_years_vip: p.yearVipFlag } : {}),
|
||||
...(p.vipLevel !== undefined ? { vip_level: p.vipLevel } : {}),
|
||||
status: p.status ?? 0,
|
||||
extStatus: p.extStatus ?? 0,
|
||||
ext_status: p.extStatus ?? 0,
|
||||
@@ -563,6 +579,7 @@ function formatGroupMember(
|
||||
`group member robot classification unavailable: group=${groupId} member=${member.uin}`,
|
||||
);
|
||||
}
|
||||
const qage = accountAge(profile?.regTime);
|
||||
return {
|
||||
group_id: groupId,
|
||||
user_id: member.uin,
|
||||
@@ -575,6 +592,8 @@ function formatGroupMember(
|
||||
last_sent_time: member.lastSentTime,
|
||||
shut_up_timestamp: member.shutUpTime,
|
||||
level: String(member.level),
|
||||
...(profile ? { qq_level: profile.level } : {}),
|
||||
...(qage !== undefined ? { qage } : {}),
|
||||
role: member.role,
|
||||
title: member.title,
|
||||
// OneBot v11 completeness (#197). QQ NT doesn't expose these, so they're
|
||||
@@ -592,6 +611,17 @@ function formatGroupMember(
|
||||
};
|
||||
}
|
||||
|
||||
/** Completed UTC calendar years since registration; unavailable dates stay absent. */
|
||||
function accountAge(regTime: number | undefined): number | undefined {
|
||||
if (regTime === undefined || !Number.isSafeInteger(regTime) || regTime <= 0) return undefined;
|
||||
const now = new Date();
|
||||
const registered = new Date(regTime * 1000);
|
||||
if (!Number.isFinite(registered.getTime()) || registered > now) return undefined;
|
||||
const years = now.getUTCFullYear() - registered.getUTCFullYear();
|
||||
registered.setUTCFullYear(now.getUTCFullYear());
|
||||
return years - (registered > now ? 1 : 0);
|
||||
}
|
||||
|
||||
/** Best-effort read of a cached user profile's qidian flags. Triggers no
|
||||
* network call — only the identity cache (populated by fetchUserProfile /
|
||||
* fetchUserProfileByUid). */
|
||||
|
||||
@@ -42,7 +42,8 @@ export async function fetchPttText(
|
||||
}
|
||||
if (!file) throw new Error('消息中不包含语音');
|
||||
|
||||
const cached = mediaStore.findRecord(file);
|
||||
const snapshot = messageStore.findMedia(messageId)?.find(element => element.type === 'record');
|
||||
const cached = snapshot ? { ...snapshot, isGroup: event.message_type === 'group', sessionId: Number(event.group_id) || selfId } : mediaStore.findRecord(file, 'legacy');
|
||||
if (!cached) throw new Error('语音不在缓存中,无法转写');
|
||||
|
||||
const isGroup = event.message_type === 'group' || cached.isGroup;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isMessageMedia, type MessageMedia } from '../message-media';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-contacts';
|
||||
@@ -26,6 +27,27 @@ import { hasAuthoritativeSequence, type JsonArray, type JsonObject, type JsonVal
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
function replyPreviewElements(message: unknown): MessageElement[] {
|
||||
if (!Array.isArray(message)) return [];
|
||||
const labels: Record<string, string> = {
|
||||
image: '[图片]', record: '[语音]', video: '[视频]', file: '[文件]',
|
||||
face: '[表情]', mface: '[表情]', forward: '[聊天记录]',
|
||||
json: '[卡片]', xml: '[卡片]', markdown: '[Markdown]',
|
||||
};
|
||||
const parts: string[] = [];
|
||||
for (const segment of message) {
|
||||
if (!segment || typeof segment !== 'object') continue;
|
||||
const data = segment.data;
|
||||
if (!data || typeof data !== 'object') continue;
|
||||
if (segment.type === 'text' && typeof data.text === 'string') parts.push(data.text);
|
||||
else if (segment.type === 'at') parts.push(data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`);
|
||||
else if (typeof segment.type === 'string' && labels[segment.type]) parts.push(labels[segment.type]);
|
||||
}
|
||||
const text = parts.join('');
|
||||
return text ? [{ type: 'text', text }] : [];
|
||||
}
|
||||
|
||||
|
||||
// A video larger than QQ's Highway video ceiling can't be sent through the
|
||||
// element pipeline — it must fall back to a regular file upload. The fallback
|
||||
// is decided at the OneBot layer (not element-builder) because building a
|
||||
@@ -840,6 +862,7 @@ export async function sendPrivateMessage(
|
||||
senderUin,
|
||||
time,
|
||||
random: meta?.random ?? 0,
|
||||
elements: replyPreviewElements(event.message),
|
||||
sequenceAuthoritative: meta?.sequenceAuthoritative,
|
||||
};
|
||||
}
|
||||
@@ -1081,6 +1104,7 @@ export async function sendGroupMessage(
|
||||
? event.time
|
||||
: parseInt(String(event.time || '0'), 10),
|
||||
random: meta?.random ?? 0,
|
||||
elements: replyPreviewElements(event.message),
|
||||
sequenceAuthoritative: meta?.sequenceAuthoritative,
|
||||
};
|
||||
}
|
||||
@@ -1264,7 +1288,7 @@ export async function forwardSingleMessage(
|
||||
const parsed = await parseMessage(content, false);
|
||||
if (parsed.length === 0) throw new Error('message has no content');
|
||||
|
||||
const elements = await prepareSingleForwardElements(ref, parsed, target);
|
||||
const elements = await prepareSingleForwardElements(ref, restoreHistoricalMedia(ref, parsed, messageId), target);
|
||||
|
||||
let receipt;
|
||||
let messageIdOut: number;
|
||||
@@ -1296,7 +1320,7 @@ async function prepareSingleForwardElements(
|
||||
const out: MessageElement[] = [];
|
||||
for (const element of elements) {
|
||||
if (element.type !== 'forward') {
|
||||
out.push(enrichForForward(ref, element));
|
||||
out.push(isMessageMedia(element) ? element : enrichForForward(ref, element));
|
||||
continue;
|
||||
}
|
||||
const resId = element.resId.trim();
|
||||
@@ -1372,7 +1396,29 @@ async function expandForwardNodeForTarget(
|
||||
return { ...node, elements };
|
||||
}
|
||||
|
||||
function enrichForForward(ref: OneBotInstanceContext, element: MessageElement): MessageElement {
|
||||
function restoreHistoricalMedia(
|
||||
ref: OneBotInstanceContext,
|
||||
elements: MessageElement[],
|
||||
messageId: number,
|
||||
): MessageElement[] {
|
||||
if (!elements.some(isMessageMedia)) return elements;
|
||||
const snapshots = ref.messageStore.findMedia(messageId);
|
||||
let index = 0;
|
||||
const restored = elements.map(element => {
|
||||
if (!isMessageMedia(element)) return element;
|
||||
const snapshot = snapshots?.[index++];
|
||||
if (snapshots && (!snapshot || snapshot.type !== element.type)) {
|
||||
throw new Error(`historical media metadata does not match message ${messageId}`);
|
||||
}
|
||||
return enrichForForward(ref, element, snapshot);
|
||||
});
|
||||
if (snapshots && index !== snapshots.length) {
|
||||
throw new Error(`historical media metadata does not match message ${messageId}`);
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
|
||||
function enrichForForward(ref: OneBotInstanceContext, element: MessageElement, snapshot?: MessageMedia): MessageElement {
|
||||
if (element.type === 'forward') {
|
||||
throw new Error('merged forward must be regenerated for the target chat');
|
||||
}
|
||||
@@ -1393,14 +1439,14 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement):
|
||||
// the keys MediaStore aliases under. After parseMessage, the segment's
|
||||
// `data.file` lands on `element.url` for all three types.
|
||||
const lookupKey = element.url || element.fileName || element.fileId || '';
|
||||
if (!lookupKey) {
|
||||
if (!lookupKey && !snapshot) {
|
||||
throw new Error(`forward ${element.type} missing cache key`);
|
||||
}
|
||||
|
||||
if (element.type === 'image') {
|
||||
const cached = ref.mediaStore.findImage(lookupKey);
|
||||
const cached = snapshot?.type === 'image' ? snapshot : ref.mediaStore.findImage(lookupKey, 'legacy');
|
||||
if (!cached || !cached.md5Hex || !cached.sha1Hex || !cached.width || !cached.height || !cached.picFormat) {
|
||||
throw new Error('forward image fingerprint not cached (legacy image or expired)');
|
||||
throw new Error('historical image metadata is incomplete; fetch the original message again');
|
||||
}
|
||||
return {
|
||||
...element,
|
||||
@@ -1419,9 +1465,9 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement):
|
||||
}
|
||||
|
||||
if (element.type === 'record') {
|
||||
const cached = ref.mediaStore.findRecord(lookupKey);
|
||||
const cached = snapshot?.type === 'record' ? snapshot : ref.mediaStore.findRecord(lookupKey, 'legacy');
|
||||
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
|
||||
throw new Error('forward record fingerprint not cached');
|
||||
throw new Error('historical voice metadata is incomplete; fetch the original message again');
|
||||
}
|
||||
return {
|
||||
...element,
|
||||
@@ -1438,9 +1484,9 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement):
|
||||
}
|
||||
|
||||
if (element.type === 'video') {
|
||||
const cached = ref.mediaStore.findVideo(lookupKey);
|
||||
const cached = snapshot?.type === 'video' ? snapshot : ref.mediaStore.findVideo(lookupKey, 'legacy');
|
||||
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
|
||||
throw new Error('forward video fingerprint not cached');
|
||||
throw new Error('historical video metadata is incomplete; fetch the original message again');
|
||||
}
|
||||
log.warn('video forward uses a fallback thumbnail (original thumb not cached)');
|
||||
return {
|
||||
@@ -1485,6 +1531,9 @@ export async function getForwardMessage(
|
||||
nickname: node.nickname,
|
||||
};
|
||||
if (isGroup) sender.card = node.senderCard ?? '';
|
||||
if (node.title !== undefined && node.title.length > 0) {
|
||||
sender.title = node.title;
|
||||
}
|
||||
|
||||
const message: JsonObject = {
|
||||
self_id: ref.selfId,
|
||||
@@ -1623,14 +1672,33 @@ function isNestedNodeArray(value: JsonValue): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
function assertForwardNodeMetadataIsScalar(
|
||||
function assertForwardNodeMetadata(
|
||||
nodeData: JsonObject,
|
||||
index: number,
|
||||
): void {
|
||||
for (const [field, value] of Object.entries(nodeData)) {
|
||||
if (field === 'content' || field === 'message') continue;
|
||||
if (value === undefined) continue;
|
||||
if (field === 'news') {
|
||||
if (isForwardNewsArray(value)) continue;
|
||||
throw new MessageElementValidationError(
|
||||
'INVALID_FIELD',
|
||||
`forward messages[${index}].news must be an array of objects with string text`,
|
||||
'node',
|
||||
field,
|
||||
);
|
||||
}
|
||||
if (field === 'title' || field === 'source' || field === 'summary' || field === 'prompt') {
|
||||
if (typeof value === 'string') continue;
|
||||
throw new MessageElementValidationError(
|
||||
'INVALID_FIELD',
|
||||
`forward messages[${index}].${field} must be a string`,
|
||||
'node',
|
||||
field,
|
||||
);
|
||||
}
|
||||
if (
|
||||
value === undefined || value === null || typeof value === 'string'
|
||||
value === null || typeof value === 'string'
|
||||
|| typeof value === 'number' || typeof value === 'boolean'
|
||||
) continue;
|
||||
throw new MessageElementValidationError(
|
||||
@@ -1642,17 +1710,28 @@ function assertForwardNodeMetadataIsScalar(
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a value looks like OneBot preview news: `Array<{ text: string }>`. */
|
||||
function isForwardNewsArray(value: JsonValue): value is Array<{ text: string }> {
|
||||
if (!Array.isArray(value)) return false;
|
||||
for (const item of value) {
|
||||
const obj = asJsonObject(item);
|
||||
if (!obj || typeof obj.text !== 'string') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function assertForwardMessageInputPolicies(
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
depth = 0,
|
||||
): void {
|
||||
if (!Array.isArray(messages) || depth >= MAX_FORWARD_DEPTH) return;
|
||||
for (const item of messages) {
|
||||
for (const [index, item] of messages.entries()) {
|
||||
const segment = asJsonObject(item);
|
||||
if (!segment) continue;
|
||||
const nodeData = segment.type === 'node' ? asJsonObject(segment.data) : segment;
|
||||
if (!nodeData) continue;
|
||||
assertForwardNodeMetadata(nodeData, index);
|
||||
|
||||
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
|
||||
if (messageId !== 0) {
|
||||
@@ -1750,7 +1829,7 @@ async function parseForwardNodes(
|
||||
'data',
|
||||
);
|
||||
}
|
||||
assertForwardNodeMetadataIsScalar(nodeData, index);
|
||||
assertForwardNodeMetadata(nodeData, index);
|
||||
return { segment, nodeData };
|
||||
}
|
||||
|
||||
@@ -1764,7 +1843,7 @@ async function parseForwardNodes(
|
||||
'content',
|
||||
);
|
||||
}
|
||||
assertForwardNodeMetadataIsScalar(segment, index);
|
||||
assertForwardNodeMetadata(segment, index);
|
||||
return { segment, nodeData: segment };
|
||||
});
|
||||
|
||||
@@ -1802,7 +1881,7 @@ async function parseForwardNodes(
|
||||
);
|
||||
}
|
||||
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
||||
const elements = await parseMessage(content, false);
|
||||
const elements = restoreHistoricalMedia(ref, await parseMessage(content, false), messageId);
|
||||
if (elements.length > 0) {
|
||||
const messageType = event.message_type === 'group' ? 'group' : 'private';
|
||||
const groupIdValue = toPositiveInt(event.group_id);
|
||||
@@ -1868,6 +1947,20 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
const node: ForwardNodePayload = { userUin, nickname, elements };
|
||||
// Forward optional preview news lines (OneBot `data.news`) onto the
|
||||
// payload so nested-forward bubble previews can prefer caller-supplied
|
||||
// lines over auto-generated ones. Only accepted when the array shape
|
||||
// is valid (already asserted by assertForwardNodeMetadata).
|
||||
if (isForwardNewsArray(nodeData.news)) {
|
||||
node.news = nodeData.news.map(item => ({ text: item.text }));
|
||||
}
|
||||
// Forward optional OneBot bubble-preview metadata so nested-forward
|
||||
// cards can prefer caller-supplied titles/source/summary/prompt over
|
||||
// auto-derived ones (types already asserted above).
|
||||
if (nodeData.title !== undefined && typeof nodeData.title === 'string') node.title = nodeData.title;
|
||||
if (nodeData.source !== undefined && typeof nodeData.source === 'string') node.source = nodeData.source;
|
||||
if (nodeData.summary !== undefined && typeof nodeData.summary === 'string') node.summary = nodeData.summary;
|
||||
if (nodeData.prompt !== undefined && typeof nodeData.prompt === 'string') node.prompt = nodeData.prompt;
|
||||
// Honour an explicit per-node display time (OneBot `data.time`, unix
|
||||
// seconds) so a custom forward can set/back-date each node's timestamp
|
||||
// (#209). The wire field is uint32, so reject a millisecond value or any
|
||||
|
||||
@@ -61,6 +61,11 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
abstract open(): void | Promise<void>;
|
||||
abstract close(): void | Promise<void>;
|
||||
|
||||
/** Drop sockets and listeners without waiting for a peer handshake.
|
||||
* Graceful `close()` can sit forever on a half-open connection; shutdown
|
||||
* uses this so the next account session can bind the same ports. */
|
||||
forceClose(): void { /* adapters that own a listener override this */ }
|
||||
|
||||
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
|
||||
|
||||
/** Report live connection health for the WebUI dashboard. */
|
||||
|
||||
@@ -25,6 +25,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
private server: Server | null = null;
|
||||
private webSocketServer: WebSocketServer | null = null;
|
||||
private listening = false;
|
||||
private releaseForced = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
@@ -113,6 +114,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
try {
|
||||
await attempt;
|
||||
} catch (error) {
|
||||
if (this.releaseForced) return;
|
||||
if (!httpReleased && server?.listening === true) {
|
||||
// A failed HTTP close callback cannot prove the listener was released.
|
||||
// The upgrade handler is still attached, so the old ingress can accept
|
||||
@@ -128,6 +130,26 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
}
|
||||
}
|
||||
|
||||
override forceClose(): void {
|
||||
this.releaseForced = true;
|
||||
this.acceptingActions = false;
|
||||
this.webSocketConnections.stopAccepting();
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
this.webSocketConnections.terminateAll();
|
||||
const webSocketServer = this.webSocketServer;
|
||||
this.webSocketServer = null;
|
||||
const server = this.server;
|
||||
this.server = null;
|
||||
if (webSocketServer) {
|
||||
try { webSocketServer.destroy(); } catch { /* already dropping */ }
|
||||
}
|
||||
if (server) {
|
||||
try { server.closeAllConnections(); } catch { /* already closed */ }
|
||||
try { server.close(() => undefined); } catch { /* already closed */ }
|
||||
}
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
|
||||
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||||
|
||||
@@ -228,6 +228,20 @@ export class OneBotNetworkManager {
|
||||
return this.shutdown();
|
||||
}
|
||||
|
||||
/** Best-effort immediate release. Does not wait for the operation queue,
|
||||
* in-flight dispatches, or peer close handshakes. */
|
||||
forceRelease(): void {
|
||||
this.acceptingReconciles = false;
|
||||
this.acceptingEvents = false;
|
||||
for (const { adapter } of this.adapters.values()) {
|
||||
try {
|
||||
adapter.forceClose();
|
||||
} catch (error) {
|
||||
log.error('forced adapter release failed: %s', errMessage(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
emitEvent(event: JsonObject): Promise<void> {
|
||||
if (!this.acceptingEvents) {
|
||||
return Promise.reject(new Error('network manager is shutting down; event dispatch rejected'));
|
||||
|
||||
@@ -60,6 +60,21 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
}
|
||||
}
|
||||
|
||||
override forceClose(): void {
|
||||
this.explicitlyClosed = true;
|
||||
this.acceptingActions = false;
|
||||
this.isEnabled = false;
|
||||
this.connected = false;
|
||||
this.cancelReconnect();
|
||||
this.heartbeatStop?.();
|
||||
this.heartbeatStop = null;
|
||||
const socket = this.socket;
|
||||
this.socket = null;
|
||||
if (socket) {
|
||||
try { socket.terminate(); } catch { /* already gone */ }
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.explicitlyClosed = true;
|
||||
this.acceptingActions = false;
|
||||
|
||||
@@ -15,6 +15,7 @@ const moduleLog = createLogger('OneBot.WS-Server');
|
||||
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private listening = false;
|
||||
private releaseForced = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private readonly connections: WsServerConnections;
|
||||
|
||||
@@ -66,6 +67,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
await attempt;
|
||||
if (wss && this.wss === wss) this.wss = null;
|
||||
} catch (error) {
|
||||
if (this.releaseForced) return;
|
||||
// A failed close callback leaves release ambiguous. Retain the server
|
||||
// reference and active binding state so a later shutdown can retry.
|
||||
this.isEnabled = wasEnabled;
|
||||
@@ -77,6 +79,19 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
}
|
||||
|
||||
override forceClose(): void {
|
||||
this.releaseForced = true;
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
this.connections.stopAccepting();
|
||||
this.connections.terminateAll();
|
||||
const wss = this.wss;
|
||||
this.wss = null;
|
||||
if (wss) {
|
||||
try { wss.destroy(); } catch { /* already dropping */ }
|
||||
}
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
|
||||
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||||
|
||||
@@ -212,6 +212,17 @@ export class WsServerConnections {
|
||||
this.connections.clear();
|
||||
}
|
||||
|
||||
/** Destroy sockets immediately. A graceful close frame can leave the
|
||||
* listener waiting on a peer that will never answer. */
|
||||
terminateAll(): void {
|
||||
this.stopAccepting();
|
||||
for (const connection of this.connections.values()) {
|
||||
connection.stopHeartbeat();
|
||||
try { connection.socket.terminate(); } catch { /* already gone */ }
|
||||
}
|
||||
this.connections.clear();
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
|
||||
const text = rawDataToString(raw);
|
||||
if (!text) {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const log = createLogger('OneBot.Stream');
|
||||
|
||||
export interface StreamStorageSnapshot {
|
||||
totalBytes: number;
|
||||
fileCount: number;
|
||||
@@ -273,7 +276,23 @@ function resolveManagedRoot(input: string): string {
|
||||
return path.join(fs.realpathSync(parent), path.basename(absolute));
|
||||
}
|
||||
|
||||
export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'onebot-stream'));
|
||||
export function createStreamStorage(env: NodeJS.ProcessEnv = process.env): StreamStorage {
|
||||
const fallback = path.join(os.tmpdir(), 'onebot-stream');
|
||||
const raw = env.SNOWLUMA_STREAM_DIR?.trim();
|
||||
if (!raw) return new StreamStorage(fallback);
|
||||
try {
|
||||
return new StreamStorage(raw);
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'SNOWLUMA_STREAM_DIR=%j is ignored: %s',
|
||||
raw,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return new StreamStorage(fallback);
|
||||
}
|
||||
}
|
||||
|
||||
export const streamStorage = createStreamStorage();
|
||||
export const STREAM_ROOT = streamStorage.root;
|
||||
export const STREAM_UPLOAD_DIR = streamStorage.uploadDir;
|
||||
export const STREAM_DOWNLOAD_DIR = streamStorage.downloadDir;
|
||||
|
||||
@@ -40,6 +40,9 @@ const setGroupMemberInvitePolicy = requireAction('set_group_member_invite_policy
|
||||
const setGroupNewMemberHistoryVisibility = requireAction('set_group_new_member_history_visibility');
|
||||
const setGroupMemberPermissions = requireAction('set_group_member_permissions');
|
||||
const getGroupAdminSettings = requireAction('get_group_admin_settings');
|
||||
const getGroupTags = requireAction('get_group_tags');
|
||||
const addGroupTag = requireAction('add_group_tag');
|
||||
const deleteGroupTag = requireAction('delete_group_tag');
|
||||
const setGroupAdmin = requireAction('set_group_admin');
|
||||
const setGroupCard = requireAction('set_group_card');
|
||||
const setGroupName = requireAction('set_group_name');
|
||||
@@ -62,6 +65,9 @@ describe('group admin actions catalog', () => {
|
||||
['set_group_new_member_history_visibility'],
|
||||
['set_group_member_permissions'],
|
||||
['get_group_admin_settings'],
|
||||
['get_group_tags'],
|
||||
['add_group_tag'],
|
||||
['delete_group_tag'],
|
||||
['set_group_admin'],
|
||||
['set_group_card'],
|
||||
['set_group_name'],
|
||||
@@ -74,7 +80,7 @@ describe('group admin actions catalog', () => {
|
||||
expect(actions.map((action) => action.kind)).toEqual([
|
||||
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
|
||||
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
|
||||
'normal', 'normal', 'normal', 'normal',
|
||||
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1223,3 +1229,92 @@ describe('set_group_portrait toHandler', () => {
|
||||
expect(setGroupAvatar).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('get_group_tags parse', () => {
|
||||
it('accepts category 0 and a numeric string', () => {
|
||||
expect(getGroupTags.parse({ group_class: 0 })).toEqual({
|
||||
ok: true,
|
||||
value: { group_class: 0 },
|
||||
});
|
||||
expect(getGroupTags.parse({ group_class: '12' })).toEqual({
|
||||
ok: true,
|
||||
value: { group_class: 12 },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a missing, negative, or oversized category', () => {
|
||||
expect(getGroupTags.parse({})).toEqual({
|
||||
ok: false,
|
||||
field: 'group_class',
|
||||
reason: 'is required',
|
||||
});
|
||||
expect(getGroupTags.parse({ group_class: -1 })).toEqual({
|
||||
ok: false,
|
||||
field: 'group_class',
|
||||
reason: 'must be >= 0',
|
||||
});
|
||||
expect(getGroupTags.parse({ group_class: 0x1_0000_0000 })).toEqual({
|
||||
ok: false,
|
||||
field: 'group_class',
|
||||
reason: 'must be <= 4294967295',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('get_group_tags toHandler', () => {
|
||||
it('returns the tag list for the category', async () => {
|
||||
const listCategoryTags = vi.fn(async () => ({
|
||||
tags: [{ id: 7, name: '学习', type: 1 }],
|
||||
}));
|
||||
const { ctx } = adminCtx({ listCategoryTags });
|
||||
|
||||
await expect(getGroupTags.toHandler(ctx)({ group_class: 4 })).resolves.toEqual({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { tags: [{ id: 7, name: '学习', type: 1 }] },
|
||||
});
|
||||
expect(listCategoryTags.mock.calls).toEqual([[4]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('add_group_tag and delete_group_tag', () => {
|
||||
it('rejects an empty name and does not call the bridge', async () => {
|
||||
const addCategoryTag = vi.fn(async () => {});
|
||||
const removeCategoryTag = vi.fn(async () => {});
|
||||
const { ctx } = adminCtx({ addCategoryTag, removeCategoryTag });
|
||||
|
||||
await expect(addGroupTag.toHandler(ctx)({ group_class: 1, name: '' })).resolves.toEqual({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
data: null,
|
||||
wording: 'name: must not be empty',
|
||||
});
|
||||
await expect(deleteGroupTag.toHandler(ctx)({ group_class: 1, name: '' })).resolves.toEqual({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
data: null,
|
||||
wording: 'name: must not be empty',
|
||||
});
|
||||
expect(addCategoryTag).not.toHaveBeenCalled();
|
||||
expect(removeCategoryTag).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('forwards the category and the exact name', async () => {
|
||||
const addCategoryTag = vi.fn(async () => {});
|
||||
const removeCategoryTag = vi.fn(async () => {});
|
||||
const { ctx } = adminCtx({ addCategoryTag, removeCategoryTag });
|
||||
|
||||
await expect(addGroupTag.toHandler(ctx)({ group_class: 0, name: ' 户外 ' })).resolves.toEqual({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: null,
|
||||
});
|
||||
await expect(deleteGroupTag.toHandler(ctx)({ group_class: '2', name: '户外' })).resolves.toEqual({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: null,
|
||||
});
|
||||
expect(addCategoryTag.mock.calls).toEqual([[0, ' 户外 ']]);
|
||||
expect(removeCategoryTag.mock.calls).toEqual([[2, '户外']]);
|
||||
});
|
||||
});
|
||||
@@ -20,8 +20,9 @@ const getMsg = requireAction('get_msg');
|
||||
const deleteMsg = requireAction('delete_msg');
|
||||
|
||||
describe('message actions catalog', () => {
|
||||
it('exports the five public message actions in source order', () => {
|
||||
it('exports the public message actions in source order', () => {
|
||||
expect(actions.map((entry) => entry.names[0])).toEqual([
|
||||
'send_custom_face',
|
||||
'send_msg',
|
||||
'send_private_msg',
|
||||
'send_group_msg',
|
||||
@@ -39,6 +40,47 @@ describe('message actions catalog', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('send_custom_face', () => {
|
||||
const action = requireAction('send_custom_face');
|
||||
const url = 'https://p.qpic.cn/qq_expression/10001/saved-sticker/0';
|
||||
const image = { type: 'image', data: { file: url, sub_type: 1, summary: '[动画表情]' } };
|
||||
|
||||
function context() {
|
||||
const resolveCustomFace = vi.fn(async () => ({ emojiId: 'saved-sticker', url, md5: 'a'.repeat(32) }));
|
||||
const sendGroupMessage = vi.fn(async () => ({ messageId: 7 }));
|
||||
const sendPrivateMessage = vi.fn(async () => ({ messageId: 8 }));
|
||||
const ctx = asCtx({
|
||||
bridge: { apis: { profile: { resolveCustomFace } } } as unknown as ApiActionContext['bridge'],
|
||||
sendGroupMessage, sendPrivateMessage,
|
||||
});
|
||||
return { ctx, resolveCustomFace, sendGroupMessage, sendPrivateMessage };
|
||||
}
|
||||
|
||||
it('resolves the saved id and sends a sticker with an optional reply', async () => {
|
||||
const { ctx, resolveCustomFace, sendGroupMessage } = context();
|
||||
expect(await action.toHandler(ctx)({ emoji_id: 'saved-sticker', group_id: 123, reply_to: -42 }))
|
||||
.toMatchObject({ status: 'ok', data: { message_id: 7 } });
|
||||
expect(resolveCustomFace).toHaveBeenCalledWith('saved-sticker');
|
||||
expect(sendGroupMessage).toHaveBeenCalledWith(123, [{ type: 'reply', data: { id: '-42' } }, image], false);
|
||||
});
|
||||
|
||||
it('supports a private destination and propagates lookup failures', async () => {
|
||||
const { ctx, resolveCustomFace, sendPrivateMessage } = context();
|
||||
expect(await action.toHandler(ctx)({ emoji_id: 'a'.repeat(32), user_id: 456 }))
|
||||
.toMatchObject({ status: 'ok', data: { message_id: 8 } });
|
||||
expect(sendPrivateMessage).toHaveBeenCalledWith(456, [image], false);
|
||||
resolveCustomFace.mockRejectedValueOnce(new Error('sticker missing'));
|
||||
await expect(action.toHandler(ctx)({ emoji_id: 'missing', user_id: 456 })).rejects.toThrow('sticker missing');
|
||||
expect(sendPrivateMessage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([{}, { group_id: 123, user_id: 456 }])('rejects an ambiguous destination before lookup', async (target) => {
|
||||
const { ctx, resolveCustomFace } = context();
|
||||
expect(await action.toHandler(ctx)({ emoji_id: 'saved-sticker', ...target })).toMatchObject({ retcode: 1400 });
|
||||
expect(resolveCustomFace).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('send_msg parse', () => {
|
||||
it('defaults auto_escape to false and leaves optional ids unset', () => {
|
||||
expect(sendMsg.parse({ message: 'hello route' })).toEqual({
|
||||
|
||||
@@ -640,3 +640,61 @@ describe('OneBotConfig login history sync', () => {
|
||||
.toThrow(/historySync\.enabled must be a boolean/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('OneBot listen port environment overrides', () => {
|
||||
let tempDir = '';
|
||||
let previous = '';
|
||||
const saved: Record<string, string | undefined> = {};
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-port-env-'));
|
||||
previous = process.cwd();
|
||||
process.chdir(tempDir);
|
||||
for (const name of ['SNOWLUMA_ONEBOT_HTTP_PORT', 'SNOWLUMA_ONEBOT_WS_PORT']) {
|
||||
saved[name] = process.env[name];
|
||||
delete process.env[name];
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const name of ['SNOWLUMA_ONEBOT_HTTP_PORT', 'SNOWLUMA_ONEBOT_WS_PORT']) {
|
||||
if (saved[name] === undefined) delete process.env[name];
|
||||
else process.env[name] = saved[name];
|
||||
}
|
||||
process.chdir(previous);
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('overrides only the factory listeners and does not write the port back', () => {
|
||||
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = '3800';
|
||||
process.env.SNOWLUMA_ONEBOT_WS_PORT = '3801';
|
||||
const loaded = loadOneBotConfig('10001', { persistDefaults: true });
|
||||
expect(loaded.networks.httpServers[0]?.port).toBe(3800);
|
||||
expect(loaded.networks.wsServers[0]?.port).toBe(3801);
|
||||
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', 'onebot_10001.json'), 'utf8')) as {
|
||||
networks: { httpServers: Array<{ port: number }>; wsServers: Array<{ port: number }> };
|
||||
};
|
||||
expect(onDisk.networks.httpServers[0]?.port).toBe(3000);
|
||||
expect(onDisk.networks.wsServers[0]?.port).toBe(3001);
|
||||
});
|
||||
|
||||
it('leaves a custom listener alone', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
config.networks.httpServers = [{
|
||||
...config.networks.httpServers[0]!,
|
||||
name: 'public-http',
|
||||
port: 4000,
|
||||
}];
|
||||
saveOneBotConfig('10001', config);
|
||||
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = '3800';
|
||||
const loaded = loadOneBotConfig('10001');
|
||||
expect(loaded.networks.httpServers.map((server) => server.port)).toEqual([4000]);
|
||||
});
|
||||
|
||||
it('keeps the saved port when the override is not a port', () => {
|
||||
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = 'nope';
|
||||
const loaded = loadOneBotConfig('10001', { persistDefaults: true });
|
||||
expect(loaded.networks.httpServers[0]?.port).toBe(3000);
|
||||
});
|
||||
});
|
||||
@@ -228,10 +228,44 @@ describe('onebot/contact-actions / getGroupList', () => {
|
||||
group_remark: '工作群',
|
||||
member_count: 0, max_member_count: 500,
|
||||
group_create_time: 0, group_level: 0, group_memo: '',
|
||||
group_description: '',
|
||||
group_all_shut: -1,
|
||||
}]);
|
||||
});
|
||||
|
||||
// #490: group_description must carry the description itself, not a copy of
|
||||
// group_memo (which prefers the announcement).
|
||||
it('exposes the group description separately from the memo (#490)', async () => {
|
||||
const fetched = [{
|
||||
...makeGroup(150, 'Both Set'),
|
||||
memo: '公告正文',
|
||||
description: '简介正文',
|
||||
}];
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => fetched),
|
||||
identity: fakeIdentity({ groups: fetched }),
|
||||
});
|
||||
|
||||
const out = await getGroupList(bridge);
|
||||
|
||||
expect(out[0]).toMatchObject({
|
||||
group_memo: '公告正文',
|
||||
group_description: '简介正文',
|
||||
});
|
||||
});
|
||||
|
||||
it('reports an empty group_description when QQ returns no description (#490)', async () => {
|
||||
const fetched = [makeGroup(160, 'No Description')];
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => fetched),
|
||||
identity: fakeIdentity({ groups: fetched }),
|
||||
});
|
||||
|
||||
const out = await getGroupList(bridge);
|
||||
|
||||
expect(out[0]).toMatchObject({ group_memo: '', group_description: '' });
|
||||
});
|
||||
|
||||
it('skips fetch when cache is populated and noCache is omitted', async () => {
|
||||
const cached = [makeGroup(200, 'Group B')];
|
||||
const bridge = fakeBridge({
|
||||
@@ -467,6 +501,24 @@ describe('onebot/contact-actions / getGroupMemberList', () => {
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getGroupMemberInfo', () => {
|
||||
it('includes account level and completed account years without changing group level', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-10-04T00:00:00Z'));
|
||||
try {
|
||||
const profile = { ...makeProfile(88, 'member'), level: 64, regTime: Date.parse('2016-10-05T00:00:00Z') / 1000 };
|
||||
const fetchUserProfile = vi.fn(async () => profile);
|
||||
const bridge = fakeBridge({
|
||||
fetchUserProfile,
|
||||
identity: fakeIdentity({ findGroupMember: () => makeMember(88, 'member') }),
|
||||
});
|
||||
expect(await getGroupMemberInfo(bridge, 1400, 88)).toMatchObject({ level: '1', qq_level: 64, qage: 9 });
|
||||
vi.setSystemTime(new Date('2026-10-05T00:00:00Z'));
|
||||
expect(await getGroupMemberInfo(bridge, 1400, 88)).toMatchObject({ qage: 10 });
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns the cached member when present and noCache is false', async () => {
|
||||
const member = makeMember(44, 'dave', 'D');
|
||||
const bridge = fakeBridge({
|
||||
@@ -581,6 +633,27 @@ describe('onebot/contact-actions / getGroupMemberInfo', () => {
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getStrangerInfo', () => {
|
||||
it('exposes available compatibility fields without fabricating login days', async () => {
|
||||
const bridge = fakeBridge({ fetchUserProfile: vi.fn(async () => ({
|
||||
...makeProfile(55555, 'member'), qid: 'my_qid', level: 64, regTime: 1_200_000_000,
|
||||
svipFlag: true, yearVipFlag: false, vipLevel: 7,
|
||||
})) });
|
||||
const out = await getStrangerInfo(bridge, 55555);
|
||||
expect(out).toMatchObject({
|
||||
uid: 'u_55555', qid: 'my_qid', qq_level: 64, qqLevel: 64, level: 64,
|
||||
reg_time: 1_200_000_000, is_vip: true, is_years_vip: false, vip_level: 7,
|
||||
});
|
||||
expect(out).not.toHaveProperty('login_days');
|
||||
});
|
||||
|
||||
it('omits unavailable registration and membership values', async () => {
|
||||
const bridge = fakeBridge({ fetchUserProfile: vi.fn(async () => makeProfile(55555, 'member')) });
|
||||
const out = await getStrangerInfo(bridge, 55555);
|
||||
for (const field of ['reg_time', 'is_vip', 'is_years_vip', 'vip_level']) {
|
||||
expect(out).not.toHaveProperty(field);
|
||||
}
|
||||
});
|
||||
|
||||
it('returns a fetched profile', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchUserProfile: vi.fn(async () => makeProfile(
|
||||
|
||||
@@ -530,7 +530,8 @@ describe('convertEvent — message elements', () => {
|
||||
it('reply: self-sent private targets use the outgoing lookup namespace', async () => {
|
||||
const calls: unknown[][] = [];
|
||||
const seg = await segment(
|
||||
{ type: 'reply', replySeq: 5, replySenderUin: SELF_ID, replyTime: 1234 },
|
||||
{ type: 'reply', replySeq: 5, replySenderUin: SELF_ID, replyTime: 1234,
|
||||
replyElements: [{ type: 'text', text: 'quoted text' }] },
|
||||
{
|
||||
messageIdResolver: (...args) => {
|
||||
calls.push(args);
|
||||
@@ -546,6 +547,7 @@ describe('convertEvent — message elements', () => {
|
||||
5,
|
||||
PRIVATE_SENT_MESSAGE_EVENT,
|
||||
1234,
|
||||
[{ type: 'text', text: 'quoted text' }],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -596,6 +598,31 @@ describe('convertEvent — message elements', () => {
|
||||
expect(seg).toEqual({ type: 'markdown', data: { content: '# Bot answer' } });
|
||||
});
|
||||
|
||||
it.each([true, false])('markdown: adds readable text while retaining rich content (group=%s)', async (isGroup) => {
|
||||
const content = '# Bot answer\n**天气**:晴 ☀️';
|
||||
const segments = await elementsToOneBotSegments(bareCtx(), [
|
||||
{ type: 'at', targetUin: PEER_UIN },
|
||||
{ type: 'markdown', text: content },
|
||||
{ type: 'text', text: 'after' },
|
||||
], isGroup, isGroup ? GROUP_ID : PEER_UIN);
|
||||
expect(segments).toEqual([
|
||||
{ type: 'at', data: { qq: String(PEER_UIN) } },
|
||||
{ type: 'markdown', data: { content } },
|
||||
{ type: 'text', data: { text: content } },
|
||||
{ type: 'text', data: { text: 'after' } },
|
||||
]);
|
||||
expect(segments.filter((s) => typeof s === 'object' && s?.type === 'text')
|
||||
.map((s) => (s as { data: { text: string } }).data.text).join('')).toBe(`${content}after`);
|
||||
});
|
||||
|
||||
it('markdown: does not add empty text or text copies of unrelated rich elements', async () => {
|
||||
const segments = await elementsToOneBotSegments(bareCtx(), [
|
||||
{ type: 'markdown', text: '' },
|
||||
{ type: 'json', text: '{"title":"card"}' },
|
||||
], true, GROUP_ID);
|
||||
expect(segments.map((s) => (s as { type: string }).type)).toEqual(['markdown', 'json']);
|
||||
});
|
||||
|
||||
it('inline keyboard: exposes rows and actionable button metadata', async () => {
|
||||
const seg = await segment({
|
||||
type: 'inline_keyboard',
|
||||
|
||||
@@ -2162,6 +2162,16 @@ describe('extended-actions / TierB ③ share + doubt + robot-option', () => {
|
||||
expect(approveDoubtRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('set_doubt_friends_add_request reports an approval error without rejecting the applicant', async () => {
|
||||
const approveDoubtRequest = vi.fn(async () => { throw new Error('approval denied'); });
|
||||
const rejectDoubtRequest = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({ apis: { friend: { approveDoubtRequest, rejectDoubtRequest } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('set_doubt_friends_add_request', { flag: 'u_abc' });
|
||||
expect(res).toMatchObject({ status: 'failed', wording: 'approval denied' });
|
||||
expect(approveDoubtRequest).toHaveBeenCalledOnce();
|
||||
expect(rejectDoubtRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('set_group_robot_add_option forwards group + switch/examine', async () => {
|
||||
const setRobotAddOption = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({ apis: { groupAdmin: { setRobotAddOption } } });
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { decodeRichBody } from '@snowluma/protocol/msg-push/rich-body-decoder';
|
||||
import { convertEvent, type ConverterContext } from '../src/event-converter';
|
||||
import { MessageStore } from '../src/message-store';
|
||||
import { GROUP_MESSAGE_EVENT } from '../src/message-id';
|
||||
import { parseMessage } from '../src/message-parser';
|
||||
import { getGroupMsgHistory } from '../src/modules/message-actions';
|
||||
import { segmentsToRawMessage } from '../src/helper/cq';
|
||||
|
||||
const ctx: ConverterContext = {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
};
|
||||
|
||||
describe('face animation results', () => {
|
||||
it('preserves zero from an incoming message through CQ, persistence and history', async () => {
|
||||
const elements = decodeRichBody({
|
||||
richText: { elems: [{ commonElem: {
|
||||
serviceType: 37,
|
||||
businessType: 2,
|
||||
pbElem: Buffer.from('1872320130', 'hex'),
|
||||
} }] },
|
||||
}, true);
|
||||
expect(elements).toEqual([{ type: 'face', faceId: 114, resultId: '0' }]);
|
||||
|
||||
const event = await convertEvent(ctx, {
|
||||
kind: 'group_message',
|
||||
groupId: 30001,
|
||||
groupName: 'group',
|
||||
senderUin: 20001,
|
||||
senderNick: 'sender',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
selfUin: 10001,
|
||||
time: 1_700_000_000,
|
||||
msgSeq: 42,
|
||||
msgId: 10042,
|
||||
elements,
|
||||
});
|
||||
if (!event) throw new Error('message conversion returned no event');
|
||||
const message = [{ type: 'face', data: { id: '114', resultId: '0' } }];
|
||||
expect(event.message).toEqual(message);
|
||||
expect(event.raw_message).toBe('[CQ:face,id=114,resultId=0]');
|
||||
await expect(parseMessage(String(event.raw_message), false)).resolves.toEqual(elements);
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-face-animation-'));
|
||||
const dbPath = path.join(dir, 'messages.db');
|
||||
let store = new MessageStore(dbPath);
|
||||
try {
|
||||
store.storeEvent(Number(event.message_id), true, 30001, 42, GROUP_MESSAGE_EVENT, event);
|
||||
store.close();
|
||||
store = new MessageStore(dbPath);
|
||||
expect(store.findEvent(Number(event.message_id))?.message).toEqual(message);
|
||||
const history = await getGroupMsgHistory(store, 30001, undefined, 20);
|
||||
expect(history).toHaveLength(1);
|
||||
expect(history[0].message).toEqual(message);
|
||||
expect(history[0].raw_message).toBe(event.raw_message);
|
||||
} finally {
|
||||
store.close();
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('escapes an opaque result identifier without changing its value', async () => {
|
||||
const resultId = 'a,b&[c]';
|
||||
const raw = segmentsToRawMessage([{ type: 'face', data: { id: '114', resultId } }]);
|
||||
await expect(parseMessage(raw, false)).resolves.toEqual([{ type: 'face', faceId: 114, resultId }]);
|
||||
});
|
||||
});
|
||||
@@ -36,7 +36,7 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
|
||||
uin: '10001',
|
||||
selfId: 10001,
|
||||
bridge,
|
||||
messageStore: { findEvent: () => null } as any,
|
||||
messageStore: { findMedia: () => null, findEvent: () => null } as any,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as any,
|
||||
musicSignUrl: '',
|
||||
@@ -263,6 +263,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
|
||||
}),
|
||||
@@ -290,6 +291,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
|
||||
}),
|
||||
@@ -340,6 +342,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
message: [{ type: 'forward', data: { id: 'OUTER' } }],
|
||||
}),
|
||||
@@ -361,6 +364,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
message: [
|
||||
{ type: 'video', data: { file: 'cached-video-id' } },
|
||||
@@ -439,6 +443,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
user_id: 0,
|
||||
message_type: 'group',
|
||||
@@ -478,7 +483,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = { findEvent };
|
||||
(ctx as any).messageStore = { findEvent, findMedia: () => null };
|
||||
|
||||
await sendGroupForwardMessage(ctx, 12345, [
|
||||
{ type: 'node', data: { id: -123 } },
|
||||
@@ -525,7 +530,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = { findEvent };
|
||||
(ctx as any).messageStore = { findEvent, findMedia: () => null };
|
||||
|
||||
await sendGroupForwardMessage(ctx, 12345, [
|
||||
{ type: 'node', data: { id: 7, nickname: 'node-override' } },
|
||||
@@ -610,4 +615,98 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
expect((nodes as any[])[0].nickname).toBe('PixivBot'); // custom nickname preserved
|
||||
expect((nodes as any[])[1].userUin).toBe(10001); // omitted → self_id
|
||||
});
|
||||
|
||||
it('accepts node metadata `news` preview arrays (OneBot ecosystem compat)', async () => {
|
||||
// Upstream frameworks (NapCat / LLOneBot / AstrBot etc.) attach
|
||||
// `news: [{ text }]` preview metadata to forward nodes. Only scalar
|
||||
// metadata was allowed before, so a standard OneBot-style node was
|
||||
// rejected with `forward messages[i].news must be a scalar value`.
|
||||
const uploadForwardNodes = vi.fn(async (_nodes: any[]) => 'RESID');
|
||||
const sendGroupMessage = vi.fn(async () => ({
|
||||
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
|
||||
}));
|
||||
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
const messages = [{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 111,
|
||||
nickname: 'outer',
|
||||
news: [{ text: '预览行 1' }, { text: '预览行 2' }],
|
||||
summary: '共 2 条',
|
||||
content: [{ type: 'node', data: { user_id: 222, nickname: 'inner', content: [{ type: 'text', data: { text: 'hi' } }] } }],
|
||||
},
|
||||
}];
|
||||
|
||||
await sendGroupForwardMessage(ctx, 12345, messages as any);
|
||||
expect(uploadForwardNodes).toHaveBeenCalledOnce();
|
||||
const [nodes] = uploadForwardNodes.mock.calls[0]!;
|
||||
expect((nodes as any[])[0].userUin).toBe(111);
|
||||
expect((nodes as any[])[0].innerForward).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('rejects non-scalar node metadata that is not an accepted preview field', async () => {
|
||||
// The news carve-out must stay narrow: any other non-scalar metadata
|
||||
// (e.g. an accidental nested object) is still rejected up front.
|
||||
const uploadForwardNodes = vi.fn(async (_nodes: any[]) => 'RESID');
|
||||
const sendGroupMessage = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
const messages = [{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 111,
|
||||
nickname: 'bad',
|
||||
arbitrary: { nested: true },
|
||||
content: [{ type: 'text', data: { text: 'hi' } }],
|
||||
},
|
||||
}];
|
||||
|
||||
await expect(sendGroupForwardMessage(ctx, 12345, messages as any)).rejects.toMatchObject({
|
||||
code: 'INVALID_FIELD',
|
||||
elementType: 'node',
|
||||
field: 'arbitrary',
|
||||
});
|
||||
expect(uploadForwardNodes).not.toHaveBeenCalled();
|
||||
expect(sendGroupMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['news', 123], ['news', 'preview'], ['news', null], ['news', [{ text: false }]],
|
||||
['news', [null]], ['title', 123], ['source', false], ['summary', []], ['prompt', null],
|
||||
])('rejects malformed %s preview metadata before upload', async (field, value) => {
|
||||
const upload = vi.fn();
|
||||
const sendGroup = vi.fn();
|
||||
const ctx = makeCtx(fakeBridge({ apis: { message: { sendGroup }, forward: { upload } } } as any));
|
||||
await expect(sendGroupForwardMessage(ctx, 12345, [{
|
||||
type: 'node', data: {
|
||||
user_id: 111, nickname: 'sender', [field as string]: value,
|
||||
content: [{ type: 'text', data: { text: 'hello' } }],
|
||||
},
|
||||
}] as any)).rejects.toMatchObject({ code: 'INVALID_FIELD', field });
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('validates nested preview metadata before parsing an earlier contact card', async () => {
|
||||
const getGroupRecommendArk = vi.fn();
|
||||
const upload = vi.fn();
|
||||
const sendGroup = vi.fn();
|
||||
const ctx = makeCtx(fakeBridge({ apis: {
|
||||
message: { sendGroup }, forward: { upload }, contacts: { getGroupRecommendArk },
|
||||
} } as any));
|
||||
await expect(sendGroupForwardMessage(ctx, 12345, [
|
||||
{ type: 'node', data: { user_id: 111, content: [{ type: 'contact', data: { type: 'group', id: 12345 } }] } },
|
||||
{ type: 'node', data: { user_id: 222, content: [
|
||||
{ type: 'node', data: { user_id: 333, source: false, content: [{ type: 'text', data: { text: 'hello' } }] } },
|
||||
] } },
|
||||
])).rejects.toMatchObject({ code: 'INVALID_FIELD', field: 'source' });
|
||||
expect(getGroupRecommendArk).not.toHaveBeenCalled();
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -117,6 +117,23 @@ describe('group information actions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// #490: group_memo prefers the announcement, so the group description needs
|
||||
// its own documented field.
|
||||
it('documents the group description on both group-info results', async () => {
|
||||
const infoSchema = getGroupInfo.describe().returnsSchema;
|
||||
const listSchema = getGroupList.describe().returnsSchema;
|
||||
|
||||
expect(infoSchema?.properties).toHaveProperty('group_description');
|
||||
expect(listSchema?.items?.properties).toHaveProperty('group_description');
|
||||
// Never required: only the group list carries it, so a non-member lookup
|
||||
// legitimately returns ''.
|
||||
expect(infoSchema?.required ?? []).not.toContain('group_description');
|
||||
|
||||
// The no-provider fallback must still carry the key.
|
||||
const response = await getGroupInfo.toHandler({} as any)({ group_id: 123456 });
|
||||
expect(response).toMatchObject({ status: 'ok', data: { group_description: '' } });
|
||||
});
|
||||
|
||||
it('documents qidian flags on both member-list and single-member results', () => {
|
||||
const listSchema = getGroupMemberList.describe().returnsSchema;
|
||||
const infoSchema = getGroupMemberInfo.describe().returnsSchema;
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../src/event-converter';
|
||||
import { MediaIndexer } from '../src/media-indexer';
|
||||
import { MediaStore, MEDIA_DATA_MAX_CHARS } from '../src/media-store';
|
||||
import { migrateLegacyMedia } from '../src/media-store-migration';
|
||||
import { MessageStore } from '../src/message-store';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import { forwardSingleMessage, sendGroupForwardMessage } from '../src/modules/message-actions';
|
||||
|
||||
const directories: string[] = [];
|
||||
afterEach(() => { for (const dir of directories.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); });
|
||||
function location() {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'historical-media-'));
|
||||
directories.push(directory);
|
||||
return { directory, dbPath: path.join(directory, 'messages.db'), legacyPath: path.join(directory, 'media.db') };
|
||||
}
|
||||
const image = {
|
||||
file: 'same.png', fileName: 'same.png', url: '', imageUrl: '', fileSize: 120,
|
||||
md5Hex: 'aa'.repeat(16), sha1Hex: 'bb'.repeat(20), width: 32, height: 24, picFormat: 1001,
|
||||
subType: 0, summary: '', isGroup: true, sessionId: 123,
|
||||
};
|
||||
function converter(media: MediaStore): ConverterContext {
|
||||
const indexer = new MediaIndexer(media);
|
||||
return { selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null, messageIdResolver: null,
|
||||
mediaSegmentSink: (...args) => indexer.remember(...args) };
|
||||
}
|
||||
function context(messages: MessageStore, media: MediaStore) {
|
||||
const sendGroup = vi.fn(async () => ({ sequence: 234, clientSequence: 0, random: 1, timestamp: 1700000001 }));
|
||||
const upload = vi.fn(async (_nodes: unknown) => 'forward-id');
|
||||
const ref = {
|
||||
selfId: 10001, messageStore: messages, mediaStore: media,
|
||||
converterCtx: converter(media), cacheMessageMeta: vi.fn(),
|
||||
bridge: { identity: { nickname: 'self' }, apis: { message: { sendGroup }, forward: { upload } } },
|
||||
} as unknown as OneBotInstanceContext;
|
||||
return { ref, sendGroup, upload };
|
||||
}
|
||||
|
||||
describe('durable historical media', () => {
|
||||
it.each(['image', 'record', 'video'] as const)('forwards %s after cache churn, alias replacement and reopen', async type => {
|
||||
const { dbPath } = location();
|
||||
let messages = new MessageStore(dbPath);
|
||||
let media = new MediaStore(dbPath, 2);
|
||||
const element = { type, fileId: 'same.png', fileName: 'same.png', fileSize: 120,
|
||||
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: 32, height: 24,
|
||||
picFormat: 1001, duration: 3, voiceFormat: 1, videoFormat: 0 } as MessageElement;
|
||||
const event = await convertEvent(converter(media), {
|
||||
kind: 'group_message', groupName: '', time: 1700000000, selfUin: 10001,
|
||||
groupId: 123, senderUin: 456, senderNick: 'peer', senderCard: '', senderRole: 'member',
|
||||
msgSeq: 10, msgId: 10, elements: [element],
|
||||
});
|
||||
event!.message_id = 42;
|
||||
messages.storeHistoryEvent(42, true, 123, 10, 'GroupMessage', event!);
|
||||
expect(JSON.stringify(event)).not.toContain('md5Hex');
|
||||
expect(JSON.stringify(messages.findEvent(42))).not.toContain('sha1Hex');
|
||||
|
||||
// Repeated names and many new resources must not change the old message.
|
||||
for (let i = 0; i < 80; i++) {
|
||||
await elementsToOneBotSegments(converter(media), [{ ...element, md5Hex: 'cc'.repeat(16) }], true, 123);
|
||||
media.rememberImage({ ...image, file: `other-${i}`, fileName: `other-${i}` });
|
||||
media.findImage(`other-${i}`);
|
||||
}
|
||||
media.close(); messages.close();
|
||||
messages = new MessageStore(dbPath); media = new MediaStore(dbPath, 2);
|
||||
try {
|
||||
const { ref, sendGroup, upload } = context(messages, media);
|
||||
await forwardSingleMessage(ref, 42, { groupId: 999 });
|
||||
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({
|
||||
type, md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, noByteFallback: true,
|
||||
})]);
|
||||
await sendGroupForwardMessage(ref, 999, [{ type: 'node', data: { id: 42 } }]);
|
||||
expect(upload.mock.calls[0]?.[0]).toEqual([expect.objectContaining({
|
||||
elements: [expect.objectContaining({ type, md5Hex: image.md5Hex, noByteFallback: true })],
|
||||
})]);
|
||||
expect(messages.findEvent(42)?.message_id).toBe(42);
|
||||
} finally { media.close(); messages.close(); }
|
||||
});
|
||||
|
||||
it('stores the body and media snapshot atomically and strips inline bytes', async () => {
|
||||
const { dbPath } = location();
|
||||
const messages = new MessageStore(dbPath);
|
||||
const media = new MediaStore(dbPath);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
try {
|
||||
const segments = await elementsToOneBotSegments(converter(media), [{ type: 'image',
|
||||
...image, url: `base64://${'A'.repeat(100000)}`, imageUrl: '', fileId: 'same.png' }], true, 123);
|
||||
const event = { time: 1, message: segments };
|
||||
db.exec("CREATE TRIGGER fail_media BEFORE INSERT ON messages WHEN NEW.media_data IS NOT NULL BEGIN SELECT RAISE(ABORT, 'test media write failure'); END");
|
||||
expect(() => messages.storeEvent(1, true, 123, 1, 'GroupMessage', event)).toThrow('test media write failure');
|
||||
expect(messages.findEvent(1)).toBeNull();
|
||||
db.exec('DROP TRIGGER fail_media');
|
||||
messages.storeEvent(1, true, 123, 1, 'GroupMessage', event);
|
||||
expect(messages.findMedia(1)?.[0].md5Hex).toBe(image.md5Hex);
|
||||
expect(JSON.stringify(messages.findMedia(1))).not.toContain('base64://');
|
||||
} finally { db.close(); media.close(); messages.close(); }
|
||||
});
|
||||
|
||||
it('propagates media persistence failures instead of silently skipping segments', async () => {
|
||||
const { dbPath } = location();
|
||||
const media = new MediaStore(dbPath);
|
||||
media.close();
|
||||
await expect(elementsToOneBotSegments(converter(media), [{ type: 'image', fileId: 'test' }], true, 123))
|
||||
.rejects.toThrow();
|
||||
});
|
||||
|
||||
it('does not substitute another same-named resource for an incomplete snapshot', async () => {
|
||||
const { dbPath } = location();
|
||||
const messages = new MessageStore(dbPath);
|
||||
const media = new MediaStore(dbPath);
|
||||
try {
|
||||
const segments = await elementsToOneBotSegments(converter(media), [{ type: 'image', fileId: image.file }], true, 123);
|
||||
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
|
||||
media.rememberImage(image);
|
||||
const { ref, sendGroup } = context(messages, media);
|
||||
await expect(forwardSingleMessage(ref, 42, { groupId: 999 })).rejects.toThrow('metadata is incomplete');
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
} finally { media.close(); messages.close(); }
|
||||
});
|
||||
|
||||
it('preserves complete metadata across an incomplete repeat and rejects conflicting resources', async () => {
|
||||
const { dbPath } = location();
|
||||
let messages = new MessageStore(dbPath);
|
||||
let media = new MediaStore(dbPath);
|
||||
const complete: MessageElement = { type: 'image', ...image, fileId: image.file };
|
||||
const save = async (element: MessageElement) => {
|
||||
const segments = await elementsToOneBotSegments(converter(media), [element], true, 123);
|
||||
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
|
||||
};
|
||||
await save(complete);
|
||||
await save({ type: 'image', fileId: image.file, md5Hex: image.md5Hex, width: 0, height: 0 });
|
||||
await expect(save({ ...complete, md5Hex: 'cc'.repeat(16) })).rejects.toThrow('conflicting');
|
||||
media.close(); messages.close();
|
||||
messages = new MessageStore(dbPath); media = new MediaStore(dbPath);
|
||||
try {
|
||||
const { ref, sendGroup } = context(messages, media);
|
||||
await forwardSingleMessage(ref, 42, { groupId: 999 });
|
||||
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({
|
||||
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: image.width, height: image.height,
|
||||
})]);
|
||||
} finally { media.close(); messages.close(); }
|
||||
});
|
||||
|
||||
it('does not combine disjoint image fingerprints merely because fileId is the same filename', async () => {
|
||||
const { dbPath } = location();
|
||||
const messages = new MessageStore(dbPath);
|
||||
const media = new MediaStore(dbPath);
|
||||
try {
|
||||
const original = await elementsToOneBotSegments(converter(media), [
|
||||
{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 },
|
||||
], true, 123);
|
||||
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: original });
|
||||
const different = await elementsToOneBotSegments(converter(media), [
|
||||
{ type: 'image', fileId: 'photo.jpg', sha1Hex: image.sha1Hex, width: 64 },
|
||||
], true, 123);
|
||||
expect(() => messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: different }))
|
||||
.toThrow('unverified media association');
|
||||
expect(messages.findMedia(42)).toEqual([{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 }]);
|
||||
} finally { media.close(); messages.close(); }
|
||||
});
|
||||
|
||||
it('rejects corrupt and oversized metadata without deleting history', () => {
|
||||
const { dbPath } = location();
|
||||
const media = new MediaStore(dbPath);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
try {
|
||||
expect(() => media.rememberImage({ ...image, summary: 'x'.repeat(MEDIA_DATA_MAX_CHARS) })).toThrow('storage limit');
|
||||
media.rememberImage(image);
|
||||
db.exec("UPDATE media_entries SET data = '{broken'");
|
||||
expect(() => media.findImage(image.file)).toThrow();
|
||||
db.exec("UPDATE media_entries SET data = 'null'");
|
||||
expect(() => media.findImage(image.file)).toThrow('invalid persisted');
|
||||
expect(media.size().images).toBe(1);
|
||||
} finally { db.close(); media.close(); }
|
||||
});
|
||||
|
||||
it.each(['image', 'record', 'video'] as const)('keeps migrated %s history independent of new same-named resources', async type => {
|
||||
const { dbPath, legacyPath } = location();
|
||||
const old = new MediaStore(legacyPath);
|
||||
const element = { type, fileId: 'same.png', fileName: 'same.png', fileSize: 120,
|
||||
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: 32, height: 24,
|
||||
picFormat: 1001, duration: 3, voiceFormat: 1, videoFormat: 0 } as MessageElement;
|
||||
await elementsToOneBotSegments(converter(old), [element], true, 123);
|
||||
old.close();
|
||||
const source = fs.readFileSync(legacyPath);
|
||||
const messages = new MessageStore(dbPath);
|
||||
messages.storeEvent(42, true, 123, 1, 'GroupMessage', {
|
||||
user_id: 456, message_id: 42, message_type: 'group',
|
||||
message: [{ type, data: { file: image.file } }],
|
||||
});
|
||||
await migrateLegacyMedia(dbPath);
|
||||
expect(fs.readFileSync(legacyPath)).toEqual(source);
|
||||
fs.rmSync(legacyPath);
|
||||
await migrateLegacyMedia(dbPath);
|
||||
const media = new MediaStore(dbPath);
|
||||
try {
|
||||
await elementsToOneBotSegments(converter(media), [{ ...element, md5Hex: 'cc'.repeat(16) }], true, 123);
|
||||
const { ref, sendGroup } = context(messages, media);
|
||||
await forwardSingleMessage(ref, 42, { groupId: 999 });
|
||||
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({ md5Hex: image.md5Hex })]);
|
||||
} finally { media.close(); messages.close(); }
|
||||
});
|
||||
|
||||
it('rolls back a failed legacy batch and resumes after the source is repaired', async () => {
|
||||
const { dbPath, legacyPath } = location();
|
||||
const old = new MediaStore(legacyPath); old.rememberImage(image); old.close();
|
||||
const source = new DatabaseSync(legacyPath);
|
||||
source.prepare("INSERT INTO media_entries VALUES ('image', 'broken', ?, 1)").run('{broken');
|
||||
source.close();
|
||||
await expect(migrateLegacyMedia(dbPath)).rejects.toThrow();
|
||||
const destination = new MediaStore(dbPath);
|
||||
expect(destination.size().images).toBe(0); destination.close();
|
||||
const repaired = new DatabaseSync(legacyPath);
|
||||
repaired.prepare("UPDATE media_entries SET data = ? WHERE primary_key = 'broken'").run(JSON.stringify({ ...image, file: 'broken' }));
|
||||
repaired.close();
|
||||
await migrateLegacyMedia(dbPath);
|
||||
const reopened = new MediaStore(dbPath);
|
||||
expect(reopened.size().images).toBe(2); reopened.close();
|
||||
});
|
||||
|
||||
it('normalizes legacy inline payloads without discarding their metadata', async () => {
|
||||
const { dbPath, legacyPath } = location();
|
||||
const old = new MediaStore(legacyPath); old.close();
|
||||
const inline = `base64://${'Z'.repeat(100000)}`;
|
||||
const source = new DatabaseSync(legacyPath);
|
||||
source.prepare("INSERT INTO media_entries VALUES ('image', ?, ?, 1)")
|
||||
.run(inline, JSON.stringify({ ...image, file: inline, url: inline, imageUrl: inline }));
|
||||
source.prepare("INSERT INTO media_keys VALUES ('image', ?, ?)").run(inline, inline);
|
||||
source.close();
|
||||
await migrateLegacyMedia(dbPath);
|
||||
const media = new MediaStore(dbPath);
|
||||
try {
|
||||
expect(media.findImage(inline)).toMatchObject({ md5Hex: image.md5Hex, url: '', imageUrl: '' });
|
||||
expect(JSON.stringify(media.findImage(inline))).not.toContain('base64://');
|
||||
} finally { media.close(); }
|
||||
});
|
||||
|
||||
it('resumes a cancelled migration from its committed batch cursor', async () => {
|
||||
const { dbPath, legacyPath } = location();
|
||||
const old = new MediaStore(legacyPath);
|
||||
for (let i = 0; i < 205; i++) old.rememberImage({ ...image, file: `entry-${i}` });
|
||||
old.close();
|
||||
let checks = 0;
|
||||
await migrateLegacyMedia(dbPath, () => ++checks > 1);
|
||||
const partial = new MediaStore(dbPath);
|
||||
expect(partial.size().images).toBe(200); partial.close();
|
||||
await migrateLegacyMedia(dbPath);
|
||||
const complete = new MediaStore(dbPath);
|
||||
expect(complete.size().images).toBe(205);
|
||||
expect(complete.findImage('entry-204')?.md5Hex).toBe(image.md5Hex);
|
||||
complete.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { once } from 'node:events';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { NetworkAdapterContext } from '../src/network/adapter';
|
||||
import { HttpServerAdapter } from '../src/network/http-server-adapter';
|
||||
import type { HttpServerNetwork } from '../src/types';
|
||||
|
||||
describe('HttpServerAdapter forced release', () => {
|
||||
it('drops a held connection so the port can be bound again', async () => {
|
||||
const ctx = {
|
||||
uin: '10001',
|
||||
api: { handle: async () => ({ status: 'ok', retcode: 0, data: null }), isStreamAction: () => false },
|
||||
buildLifecycleEvent: () => ({}),
|
||||
buildHeartbeatEvent: () => ({}),
|
||||
} as unknown as NetworkAdapterContext;
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'http-force-close',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
};
|
||||
const adapter = new HttpServerAdapter(config.name, config, ctx);
|
||||
let socket: net.Socket | null = null;
|
||||
try {
|
||||
await adapter.open();
|
||||
const server = (adapter as unknown as { server: http.Server | null }).server;
|
||||
expect(server).not.toBeNull();
|
||||
const port = (server!.address() as AddressInfo).port;
|
||||
socket = net.connect({ host: '127.0.0.1', port });
|
||||
await once(socket, 'connect');
|
||||
|
||||
adapter.forceClose();
|
||||
|
||||
expect(server!.listening).toBe(false);
|
||||
await expect(listenOn(port)).resolves.toBeUndefined();
|
||||
} finally {
|
||||
socket?.destroy();
|
||||
await adapter.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function listenOn(port: number): Promise<void> {
|
||||
const server = net.createServer();
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(port, '127.0.0.1', () => {
|
||||
server.close(() => resolve());
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -112,6 +112,7 @@ function makeRef(overrides: {
|
||||
reactionStore?: Record<string, unknown>;
|
||||
converterCtx?: Record<string, unknown>;
|
||||
extraBridge?: Record<string, unknown>;
|
||||
getUptimeMs?: () => number;
|
||||
} = {}): {
|
||||
ref: OneBotInstanceContext;
|
||||
api: ReturnType<typeof buildApiContext>;
|
||||
@@ -128,6 +129,7 @@ function makeRef(overrides: {
|
||||
});
|
||||
|
||||
const messageStore = {
|
||||
findMedia: () => null,
|
||||
findEvent: (messageId: number) => events.get(messageId) ?? null,
|
||||
findMeta: (messageId: number) => metas.get(messageId) ?? null,
|
||||
storeMetas: (entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>) => {
|
||||
@@ -253,6 +255,7 @@ function makeRef(overrides: {
|
||||
} as OneBotConfig,
|
||||
cacheMessageMeta,
|
||||
dispatchEvent,
|
||||
getUptimeMs: overrides.getUptimeMs ?? (() => 0),
|
||||
} as unknown as OneBotInstanceContext;
|
||||
|
||||
return {
|
||||
@@ -266,6 +269,17 @@ function makeRef(overrides: {
|
||||
}
|
||||
|
||||
describe('buildApiContext capabilities', () => {
|
||||
it('reads current uptime from each account session independently', () => {
|
||||
let firstUptime = 1_999;
|
||||
const first = makeRef({ getUptimeMs: () => firstUptime });
|
||||
const second = makeRef({ getUptimeMs: () => 0 });
|
||||
expect(first.api.getUptimeMs()).toBe(1_999);
|
||||
expect(second.api.getUptimeMs()).toBe(0);
|
||||
firstUptime = 3_001;
|
||||
expect(first.api.getUptimeMs()).toBe(3_001);
|
||||
expect(makeRef({ getUptimeMs: () => 0 }).api.getUptimeMs()).toBe(0);
|
||||
});
|
||||
|
||||
it('reports the account as online and able to send image or record', () => {
|
||||
const { api } = makeRef();
|
||||
expect(api.isOnline()).toBe(true);
|
||||
@@ -716,6 +730,7 @@ describe('buildApiContext contact reads', () => {
|
||||
group_create_time: 100,
|
||||
group_level: 2,
|
||||
group_memo: 'rules',
|
||||
group_description: '',
|
||||
group_all_shut: -1,
|
||||
}]);
|
||||
expect(fetchGroupList).not.toHaveBeenCalled();
|
||||
@@ -744,6 +759,7 @@ describe('buildApiContext contact reads', () => {
|
||||
group_create_time: 0,
|
||||
group_level: 6,
|
||||
group_memo: '',
|
||||
group_description: '',
|
||||
group_all_shut: 0,
|
||||
});
|
||||
});
|
||||
@@ -797,6 +813,7 @@ describe('buildApiContext contact reads', () => {
|
||||
uin: 20002,
|
||||
uid: 'u_20002',
|
||||
nickname: 'stranger',
|
||||
qid: 'qid_20002',
|
||||
remark: 'r',
|
||||
sex: 'female',
|
||||
age: 21,
|
||||
@@ -809,12 +826,15 @@ describe('buildApiContext contact reads', () => {
|
||||
|
||||
await expect(api.getStrangerInfo(20002)).resolves.toEqual({
|
||||
user_id: 20002,
|
||||
uid: 'u_20002',
|
||||
qid: 'qid_20002',
|
||||
nickname: 'stranger',
|
||||
remark: 'r',
|
||||
sex: 'female',
|
||||
age: 21,
|
||||
long_nick: 'hello sign',
|
||||
qq_level: 17,
|
||||
qqLevel: 17,
|
||||
level: 17,
|
||||
status: 0,
|
||||
extStatus: 0,
|
||||
@@ -1111,6 +1131,22 @@ describe('buildApiContext send and forward dispatch', () => {
|
||||
expect(dispatchEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('replies with an image only through the recorded temp session without refreshing it', async () => {
|
||||
const { api, ref } = makeRef();
|
||||
ref.tempSessions.record(PEER_ID, GROUP_ID);
|
||||
const record = vi.spyOn(ref.tempSessions, 'record');
|
||||
const source = 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jFZkAAAAASUVORK5CYII=';
|
||||
await api.sendPrivateMessage(PEER_ID, [
|
||||
{ type: 'image', data: { file: source } },
|
||||
], false, GROUP_ID);
|
||||
|
||||
expect(ref.bridge.apis.message.sendGroupTempMessage).toHaveBeenCalledWith(
|
||||
PEER_ID, GROUP_ID, [expect.objectContaining({ type: 'image', url: source })],
|
||||
);
|
||||
expect(ref.bridge.apis.message.sendPrivate).not.toHaveBeenCalled();
|
||||
expect(record).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends a group message without a self-sent dispatch callback', async () => {
|
||||
const { api, dispatchEvent, ref } = makeRef();
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { currentRequestId, runWithRequestId } from '@snowluma/common/logger';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { currentRequestId, runWithRequestId, subscribeLogs } from '@snowluma/common/logger';
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
@@ -7,9 +7,12 @@ import type { AdapterStatus } from '../src/network';
|
||||
import type { OneBotInstance } from '../src/instance';
|
||||
import {
|
||||
OneBotManager,
|
||||
parseSessionReleaseDeadlineMs,
|
||||
resolveSessionReleaseDeadlineMs,
|
||||
type DatabaseMigrationCallbacks,
|
||||
type DatabaseMigrationTask,
|
||||
} from '../src/manager';
|
||||
import { makeDefaultOneBotConfig } from '../src/config';
|
||||
import { estimateRemainingSeconds } from '../src/message-store-migration-task';
|
||||
|
||||
function fakeBridge(warmup?: Promise<{ friendsLoaded: boolean; groupsLoaded: boolean }>) {
|
||||
@@ -37,6 +40,26 @@ function fakeInstance(
|
||||
} as unknown as OneBotInstance;
|
||||
}
|
||||
|
||||
describe('session release deadline', () => {
|
||||
it('keeps 10 seconds when nothing overrides it', () => {
|
||||
expect(resolveSessionReleaseDeadlineMs(undefined, undefined)).toBe(10_000);
|
||||
expect(resolveSessionReleaseDeadlineMs(undefined, ' ')).toBe(10_000);
|
||||
});
|
||||
|
||||
it('lets SNOWLUMA_SESSION_RELEASE_DEADLINE_MS override a configured deadline', () => {
|
||||
expect(resolveSessionReleaseDeadlineMs(30, '2500')).toBe(2500);
|
||||
expect(parseSessionReleaseDeadlineMs('0')).toBeUndefined();
|
||||
expect(parseSessionReleaseDeadlineMs('-5')).toBeUndefined();
|
||||
expect(parseSessionReleaseDeadlineMs('1.5')).toBeUndefined();
|
||||
expect(parseSessionReleaseDeadlineMs('nope')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores an unusable environment value and keeps the configured deadline', () => {
|
||||
expect(resolveSessionReleaseDeadlineMs(30, 'nope')).toBe(30);
|
||||
expect(resolveSessionReleaseDeadlineMs(undefined, 'nope')).toBe(10_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('database migration estimates', () => {
|
||||
it('waits for measured throughput and reaches zero on completion', () => {
|
||||
expect(estimateRemainingSeconds(
|
||||
@@ -209,7 +232,7 @@ describe('OneBotManager database preparation', () => {
|
||||
expect(manager.getConnectionStatuses()[0].databaseMigration).toMatchObject({
|
||||
phase: 'failed',
|
||||
usable: false,
|
||||
error: '数据库迁移失败,将自动重试',
|
||||
error: '数据库迁移失败:private worker detail;将自动重试',
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(5_000);
|
||||
@@ -260,7 +283,7 @@ describe('OneBotManager database preparation', () => {
|
||||
expect(manager.getConnectionStatuses()[0].databaseMigration).toMatchObject({
|
||||
phase: 'failed',
|
||||
usable: true,
|
||||
error: '数据库迁移失败,将自动重试',
|
||||
error: '数据库迁移失败:private signal detail;将自动重试',
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(5_000);
|
||||
@@ -302,7 +325,7 @@ describe('OneBotManager database preparation', () => {
|
||||
expect(manager.getConnectionStatuses()[0].databaseMigration).toMatchObject({
|
||||
phase: 'failed',
|
||||
usable: false,
|
||||
error: '数据库迁移失败,将自动重试',
|
||||
error: '账号启动失败:private startup detail;将自动重试',
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(5_000);
|
||||
@@ -314,6 +337,51 @@ describe('OneBotManager database preparation', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('reports invalid account configuration and stops retrying after database readiness', async () => {
|
||||
const originalCwd = process.cwd();
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'snowluma-invalid-startup-'));
|
||||
const entries: string[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry.message));
|
||||
let callbacks!: DatabaseMigrationCallbacks;
|
||||
const cancel = vi.fn();
|
||||
const beginMigration = vi.fn();
|
||||
const createTask = vi.fn(() => ({
|
||||
start: (next: DatabaseMigrationCallbacks) => { callbacks = next; },
|
||||
cancel, beginMigration,
|
||||
}));
|
||||
const createInstance = vi.fn();
|
||||
const manager = new OneBotManager({ createDatabaseMigrationTask: createTask, createInstance });
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
process.chdir(root);
|
||||
mkdirSync('config');
|
||||
const config = makeDefaultOneBotConfig();
|
||||
config.networks.wsServers[0].port = config.networks.httpServers[0].port;
|
||||
config.networks.wsServers[0].host = config.networks.httpServers[0].host;
|
||||
writeFileSync('config/onebot_10001.json', JSON.stringify(config));
|
||||
(manager as unknown as { onSessionStarted(uin: string, bridge: never): void })
|
||||
.onSessionStarted('10001', fakeBridge() as never);
|
||||
callbacks.onReady();
|
||||
const state = manager.getConnectionStatuses()[0].databaseMigration!;
|
||||
expect(state).toMatchObject({ phase: 'failed', usable: false });
|
||||
expect(state.error).toContain('账号启动失败');
|
||||
expect(state.error).toContain('conflicts with');
|
||||
expect(entries.some((message) => message.includes('session startup failed')
|
||||
&& message.includes('OneBotConfigValidationError') && message.includes('conflicts with'))).toBe(true);
|
||||
expect(createInstance).not.toHaveBeenCalled();
|
||||
expect(beginMigration).not.toHaveBeenCalled();
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(createTask).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
await manager.dispose();
|
||||
unsubscribe();
|
||||
vi.useRealTimers();
|
||||
process.chdir(originalCwd);
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('retries a failed database task while the session remains present', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
@@ -340,7 +408,7 @@ describe('OneBotManager database preparation', () => {
|
||||
expect(manager.getConnectionStatuses()[0].databaseMigration).toMatchObject({
|
||||
phase: 'failed',
|
||||
usable: false,
|
||||
error: '数据库迁移失败,将自动重试',
|
||||
error: '数据库迁移失败:private detail;将自动重试',
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(5_000);
|
||||
@@ -523,6 +591,108 @@ describe('OneBotManager lifecycle failure accounting', () => {
|
||||
expect((manager as unknown as { pendingStarts: Map<string, unknown> }).pendingStarts.has('10001')).toBe(false);
|
||||
});
|
||||
|
||||
it('starts the replacement account when release never finishes', async () => {
|
||||
const originalCwd = process.cwd();
|
||||
const savedDeadline = process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
|
||||
delete process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'snowluma-manager-release-'));
|
||||
process.chdir(root);
|
||||
const forceRelease = vi.fn();
|
||||
const old = {
|
||||
...fakeInstance('10001', () => new Promise(() => undefined)),
|
||||
forceRelease,
|
||||
} as unknown as OneBotInstance;
|
||||
const replacement = {
|
||||
...fakeInstance('10001', async () => undefined),
|
||||
waitUntilNetworkReady: vi.fn(async () => ({ applied: true, statuses: [], errors: [] })),
|
||||
startLoginHistorySync: vi.fn(),
|
||||
startGroupRequestPolling: vi.fn(),
|
||||
} as unknown as OneBotInstance;
|
||||
let created = false;
|
||||
const manager = new OneBotManager({
|
||||
sessionReleaseDeadlineMs: 30,
|
||||
createDatabaseMigrationTask: () => ({
|
||||
beginMigration: vi.fn(),
|
||||
cancel: vi.fn(),
|
||||
start: (next) => { next.onReady(); },
|
||||
}),
|
||||
createInstance: () => {
|
||||
created = true;
|
||||
return replacement;
|
||||
},
|
||||
});
|
||||
const internals = manager as unknown as {
|
||||
retiringInstances: Set<OneBotInstance>;
|
||||
onSessionStarted(uin: string, bridge: never): void;
|
||||
pendingStarts: Map<string, unknown>;
|
||||
};
|
||||
try {
|
||||
internals.retiringInstances.add(old);
|
||||
internals.onSessionStarted('10001', fakeBridge() as never);
|
||||
await vi.waitFor(() => {
|
||||
expect(created).toBe(true);
|
||||
});
|
||||
expect(forceRelease).toHaveBeenCalledOnce();
|
||||
expect(manager.getInstance('10001')).toBe(replacement);
|
||||
expect(internals.pendingStarts.has('10001')).toBe(false);
|
||||
expect(internals.retiringInstances.has(old)).toBe(false);
|
||||
} finally {
|
||||
if (savedDeadline === undefined) delete process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
|
||||
else process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS = savedDeadline;
|
||||
process.chdir(originalCwd);
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('uses SNOWLUMA_SESSION_RELEASE_DEADLINE_MS instead of a longer configured deadline', async () => {
|
||||
const originalCwd = process.cwd();
|
||||
const savedDeadline = process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
|
||||
process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS = '40';
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'snowluma-manager-release-env-'));
|
||||
process.chdir(root);
|
||||
const forceRelease = vi.fn();
|
||||
const old = {
|
||||
...fakeInstance('10001', () => new Promise(() => undefined)),
|
||||
forceRelease,
|
||||
} as unknown as OneBotInstance;
|
||||
let created = false;
|
||||
const replacement = {
|
||||
...fakeInstance('10001', async () => undefined),
|
||||
waitUntilNetworkReady: vi.fn(async () => ({ applied: true, statuses: [], errors: [] })),
|
||||
startLoginHistorySync: vi.fn(),
|
||||
startGroupRequestPolling: vi.fn(),
|
||||
} as unknown as OneBotInstance;
|
||||
const manager = new OneBotManager({
|
||||
sessionReleaseDeadlineMs: 60_000,
|
||||
createDatabaseMigrationTask: () => ({
|
||||
beginMigration: vi.fn(),
|
||||
cancel: vi.fn(),
|
||||
start: (next) => { next.onReady(); },
|
||||
}),
|
||||
createInstance: () => {
|
||||
created = true;
|
||||
return replacement;
|
||||
},
|
||||
});
|
||||
const internals = manager as unknown as {
|
||||
retiringInstances: Set<OneBotInstance>;
|
||||
onSessionStarted(uin: string, bridge: never): void;
|
||||
};
|
||||
try {
|
||||
internals.retiringInstances.add(old);
|
||||
internals.onSessionStarted('10001', fakeBridge() as never);
|
||||
await vi.waitFor(() => {
|
||||
expect(created).toBe(true);
|
||||
});
|
||||
expect(forceRelease).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
if (savedDeadline === undefined) delete process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS;
|
||||
else process.env.SNOWLUMA_SESSION_RELEASE_DEADLINE_MS = savedDeadline;
|
||||
process.chdir(originalCwd);
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('allows a later same-UIN start observation to retry a failed handoff', async () => {
|
||||
const manager = new OneBotManager();
|
||||
let attempts = 0;
|
||||
|
||||
@@ -36,7 +36,7 @@ function trackPttKey(selfId: number, messageId: number): string {
|
||||
}
|
||||
|
||||
function fakeMessageStore(event: JsonObject | null): MessageStore {
|
||||
return { findEvent: () => event } as unknown as MessageStore;
|
||||
return { findMedia: () => null, findEvent: () => event } as unknown as MessageStore;
|
||||
}
|
||||
|
||||
function fakeImageStore(image: CachedImage | null): MediaStore {
|
||||
@@ -177,7 +177,7 @@ describe('fetchPttText', () => {
|
||||
SELF_ID,
|
||||
40004,
|
||||
)).resolves.toEqual({ text: '跳过垃圾段落后转写' });
|
||||
expect(store.findRecord).toHaveBeenCalledWith('keep.silk');
|
||||
expect(store.findRecord).toHaveBeenCalledWith('keep.silk', 'legacy');
|
||||
});
|
||||
|
||||
it('throws when the record segment has no file and no url', async () => {
|
||||
@@ -248,7 +248,7 @@ describe('fetchPttText', () => {
|
||||
SELF_ID,
|
||||
40009,
|
||||
)).resolves.toEqual({ text: 'url 字段转写' });
|
||||
expect(store.findRecord).toHaveBeenCalledWith('https://ptt.example/by-url.silk');
|
||||
expect(store.findRecord).toHaveBeenCalledWith('https://ptt.example/by-url.silk', 'legacy');
|
||||
});
|
||||
|
||||
it('uses the first record segment even when a later one exists', async () => {
|
||||
@@ -272,8 +272,8 @@ describe('fetchPttText', () => {
|
||||
SELF_ID,
|
||||
40010,
|
||||
)).resolves.toEqual({ text: '第一段' });
|
||||
expect(store.findRecord).toHaveBeenCalledWith('first.silk');
|
||||
expect(store.findRecord).not.toHaveBeenCalledWith('second.silk');
|
||||
expect(store.findRecord).toHaveBeenCalledWith('first.silk', 'legacy');
|
||||
expect(store.findRecord).not.toHaveBeenCalledWith('second.silk', 'legacy');
|
||||
});
|
||||
|
||||
it('stringifies a numeric file id before cache lookup', async () => {
|
||||
@@ -292,7 +292,7 @@ describe('fetchPttText', () => {
|
||||
SELF_ID,
|
||||
40011,
|
||||
)).resolves.toEqual({ text: '数字 file' });
|
||||
expect(store.findRecord).toHaveBeenCalledWith('9001');
|
||||
expect(store.findRecord).toHaveBeenCalledWith('9001', 'legacy');
|
||||
});
|
||||
|
||||
it('throws when the record is not in the media cache', async () => {
|
||||
|
||||
@@ -182,9 +182,8 @@ describe('MediaStore basic semantics', () => {
|
||||
}
|
||||
});
|
||||
|
||||
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.
|
||||
it('retains durable entries beyond the memory cache cap', () => {
|
||||
// Lookups can be evicted from memory, but historical metadata survives.
|
||||
const cap = 80;
|
||||
const store = open('evict', cap);
|
||||
for (let i = 0; i < 200; i++) {
|
||||
@@ -201,7 +200,9 @@ describe('MediaStore basic semantics', () => {
|
||||
});
|
||||
}
|
||||
const { images } = store.size();
|
||||
expect(images).toBeLessThanOrEqual(cap);
|
||||
expect(images).toBe(200);
|
||||
for (let i = 0; i < 200; i++) expect(store.findImage(`file-${i}.png`)?.fileSize).toBe(i);
|
||||
expect(store.findImage('file-0.png')?.fileSize).toBe(0);
|
||||
// Most recent entries should still be present.
|
||||
expect(store.findImage('file-199.png')?.fileSize).toBe(199);
|
||||
store.close();
|
||||
@@ -285,7 +286,7 @@ describe('MediaStore basic semantics', () => {
|
||||
store.close();
|
||||
});
|
||||
|
||||
it('drops oversized rows left by older builds on open', () => {
|
||||
it('does not destructively purge existing metadata on open', () => {
|
||||
const dbPath = tempDbPath('legacy-overflow');
|
||||
dbs.push(dbPath);
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
@@ -316,11 +317,11 @@ describe('MediaStore basic semantics', () => {
|
||||
|
||||
const store = new MediaStore(dbPath);
|
||||
expect(store.findImage(poisonKey)).toBeNull();
|
||||
expect(store.size().images).toBe(0);
|
||||
expect(store.size().images).toBe(1);
|
||||
store.close();
|
||||
const rows = inspectMediaDb(dbPath);
|
||||
expect(rows.entryCount).toBe(0);
|
||||
expect(rows.keyCount).toBe(0);
|
||||
expect(rows.entryCount).toBe(1);
|
||||
expect(rows.keyCount).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -36,6 +36,21 @@ describe('parseMessage', () => {
|
||||
});
|
||||
|
||||
describe('CQ code parsing', () => {
|
||||
it.each(['0', '2', 0, 2])('preserves an animation result %s', async (resultId) => {
|
||||
expect(await parseMessage([{ type: 'face', data: { id: 114, resultId } }], false))
|
||||
.toEqual([{ type: 'face', faceId: 114, resultId: String(resultId) }]);
|
||||
});
|
||||
|
||||
it.each([null, false, {}, [], '', ' ', -1, 1.5, Number.MAX_SAFE_INTEGER + 1])('rejects an invalid animation result %j', async (resultId) => {
|
||||
await expect(parseMessage([{ type: 'face', data: { id: 114, resultId } }], false))
|
||||
.rejects.toMatchObject({ code: 'INVALID_FIELD', field: 'resultId' });
|
||||
});
|
||||
|
||||
it('rejects a selected animation on a small face', async () => {
|
||||
await expect(parseMessage('[CQ:face,id=114,large=false,resultId=0]', false))
|
||||
.rejects.toMatchObject({ code: 'INVALID_FIELD', field: 'resultId' });
|
||||
});
|
||||
|
||||
it('parses face CQ code', async () => {
|
||||
const result = await parseMessage('[CQ:face,id=123]', false);
|
||||
expect(result).toHaveLength(1);
|
||||
@@ -43,6 +58,18 @@ describe('parseMessage', () => {
|
||||
expect(result[0].faceId).toBe(123);
|
||||
});
|
||||
|
||||
it.each([true, false, 'true', 'false', 1, 0, '1', '0'])('preserves face animation choice %s', async (large) => {
|
||||
const result = await parseMessage([{ type: 'face', data: { id: '424', large } }], false);
|
||||
expect(result).toEqual([{ type: 'face', faceId: 424, large: [true, 'true', 1, '1'].includes(large) }]);
|
||||
});
|
||||
|
||||
it('accepts the CQ animation switch and rejects invalid booleans', async () => {
|
||||
expect(await parseMessage('[CQ:face,id=424,large=false]', false))
|
||||
.toEqual([{ type: 'face', faceId: 424, large: false }]);
|
||||
await expect(parseMessage('[CQ:face,id=424,large=maybe]', false))
|
||||
.rejects.toMatchObject({ code: 'INVALID_FIELD' });
|
||||
});
|
||||
|
||||
it('parses at CQ code', async () => {
|
||||
const result = await parseMessage('[CQ:at,qq=12345]', false);
|
||||
expect(result).toHaveLength(1);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { subscribeLogs } from '@snowluma/common/logger';
|
||||
import type { DatabaseMigrationCallbacks } from '../src/manager';
|
||||
import {
|
||||
createMessageStoreMigrationTask,
|
||||
@@ -22,6 +23,32 @@ function callbacks(): DatabaseMigrationCallbacks {
|
||||
}
|
||||
|
||||
describe('message-store migration task lifecycle', () => {
|
||||
it('records worker preparation through the parent logger with account context', () => {
|
||||
const worker = fakeWorker();
|
||||
const handlers = callbacks();
|
||||
const entries: Array<{ scope: string; uin?: number; message: string }> = [];
|
||||
const unsubscribe = subscribeLogs(entry => entries.push(entry));
|
||||
const task = createMessageStoreMigrationTask('10001', () => worker);
|
||||
try {
|
||||
task.start(handlers);
|
||||
worker.emit('message', { kind: 'preparation', progress: { stage: 'started' } });
|
||||
worker.emit('message', { kind: 'preparation', progress: { stage: 'indexed', elapsedMs: 12.5 } });
|
||||
worker.emit('message', { kind: 'preparation', progress: { stage: 'counted', total: 3, elapsedMs: 2.1 } });
|
||||
expect(entries.map(entry => ({ scope: entry.scope, uin: entry.uin, message: entry.message }))).toEqual([
|
||||
{ scope: 'OneBot.MessageMigration', uin: 10001, message: 'preparing message history migration' },
|
||||
{ scope: 'OneBot.MessageMigration', uin: 10001, message: 'message history migration preparation finished in 13ms' },
|
||||
{ scope: 'OneBot.MessageMigration', uin: 10001, message: 'message history migration: pending=3 checked in 2ms' },
|
||||
]);
|
||||
expect(handlers.onProgress).not.toHaveBeenCalled();
|
||||
expect(handlers.onFailed).not.toHaveBeenCalled();
|
||||
task.cancel();
|
||||
worker.emit('message', { kind: 'preparation', progress: { stage: 'started' } });
|
||||
expect(entries).toHaveLength(3);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports an exit before completion even when its code is zero', () => {
|
||||
const worker = fakeWorker();
|
||||
const handlers = callbacks();
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
inspectMessageStoreMigration,
|
||||
MessageStoreMigrator,
|
||||
prepareMessageStoreDatabase,
|
||||
type MessageStoreMigrationPreparation,
|
||||
} from '../src/message-store-migration';
|
||||
import {
|
||||
isMessageStoreMigrationWorkerData,
|
||||
@@ -25,20 +26,24 @@ function workerPayload(dbPath: string): MessageStoreMigrationWorkerData {
|
||||
function createControlPort(): {
|
||||
port: MessagePort;
|
||||
messages: MessageStoreMigrationWorkerMessage[];
|
||||
preparations: MessageStoreMigrationPreparation[];
|
||||
send(message: unknown): void;
|
||||
listenerCount(): number;
|
||||
} {
|
||||
const messages: MessageStoreMigrationWorkerMessage[] = [];
|
||||
const preparations: MessageStoreMigrationPreparation[] = [];
|
||||
const events = new EventEmitter();
|
||||
return {
|
||||
port: {
|
||||
on: events.on.bind(events),
|
||||
off: events.off.bind(events),
|
||||
postMessage(message: MessageStoreMigrationWorkerMessage) {
|
||||
messages.push(message);
|
||||
if (message.kind === 'preparation') preparations.push(message.progress);
|
||||
else messages.push(message);
|
||||
},
|
||||
} as unknown as MessagePort,
|
||||
messages,
|
||||
preparations,
|
||||
send(message: unknown) {
|
||||
events.emit('message', message);
|
||||
},
|
||||
@@ -127,6 +132,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const close = vi.spyOn(MessageStoreMigrator.prototype, 'close');
|
||||
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
expect(control.messages).toEqual([{ kind: 'ready' }]);
|
||||
expect(control.listenerCount()).toBe(1);
|
||||
|
||||
@@ -154,6 +160,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
|
||||
control.send('go');
|
||||
control.send({ kind: 'start' });
|
||||
@@ -172,12 +179,44 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('forwards preparation timings only after start without opening a worker log transport', async () => {
|
||||
const { subscribeLogs } = await import('@snowluma/common/logger');
|
||||
const { getFileTransport } = await import('@snowluma/common/log-file-transport');
|
||||
const fileTransport = getFileTransport();
|
||||
const write = vi.spyOn(fileTransport, 'write').mockImplementation(() => {});
|
||||
const logs: string[] = [];
|
||||
const unsubscribe = subscribeLogs(entry => logs.push(entry.scope));
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE', '1');
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
seedUnclassified(dbPath, 1);
|
||||
const control = createControlPort();
|
||||
try {
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve();
|
||||
expect(control.preparations).toEqual([]);
|
||||
control.send('start');
|
||||
await running;
|
||||
expect(control.preparations).toEqual([
|
||||
{ stage: 'started' },
|
||||
{ stage: 'indexed', elapsedMs: expect.any(Number) },
|
||||
{ stage: 'counted', total: 1, elapsedMs: expect.any(Number) },
|
||||
]);
|
||||
expect(control.preparations.filter(progress => progress.stage !== 'started').every(progress => progress.elapsedMs >= 0)).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
unsubscribe();
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns after cancel without posting progress', async () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
seedUnclassified(dbPath, 1);
|
||||
const control = createControlPort();
|
||||
const runBatch = vi.spyOn(MessageStoreMigrator.prototype, 'runBatch');
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
|
||||
control.send('cancel');
|
||||
await running;
|
||||
@@ -198,6 +237,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const control = createControlPort();
|
||||
const runBatch = vi.spyOn(MessageStoreMigrator.prototype, 'runBatch');
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
|
||||
control.send('start');
|
||||
control.send('cancel');
|
||||
@@ -212,6 +252,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
seedUnclassified(dbPath, 1);
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
|
||||
control.send('start');
|
||||
await running;
|
||||
@@ -236,6 +277,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
seedUnclassified(dbPath, 201);
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
|
||||
control.send('start');
|
||||
await running;
|
||||
@@ -269,6 +311,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
seedUnclassified(dbPath, 201);
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
|
||||
control.send('start');
|
||||
await Promise.resolve();
|
||||
@@ -323,6 +366,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
expect(control.messages).toEqual([{ kind: 'ready' }]);
|
||||
|
||||
const db = new DatabaseSync(dbPath);
|
||||
@@ -334,7 +378,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
|
||||
expect(control.messages).toEqual([
|
||||
{ kind: 'ready' },
|
||||
{ kind: 'failed', message: 'no such table: messages' },
|
||||
{ kind: 'failed', message: 'no such table: main.messages' },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -353,6 +397,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const control = createControlPort();
|
||||
const close = vi.spyOn(MessageStoreMigrator.prototype, 'close');
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
|
||||
control.send('start');
|
||||
await running;
|
||||
@@ -371,6 +416,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
});
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
|
||||
control.send('start');
|
||||
await running;
|
||||
|
||||
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user