Compare commits

...

74 Commits

Author SHA1 Message Date
手瓜一十雪
62b04007bb fix 2025-04-04 13:29:00 +08:00
手瓜一十雪
39d938f603 fix 2025-04-04 13:28:50 +08:00
手瓜一十雪
6f6cffbc67 feat: codec wav 2025-04-04 13:28:28 +08:00
手瓜一十雪
f739c88106 feat 2025-04-04 12:40:25 +08:00
手瓜一十雪
320a23de20 feat: audio 2025-04-04 12:16:56 +08:00
pk5ls20
3cf502fea3 chore: improve log output for protocol fetch with multiple messages 2025-04-04 01:59:31 +08:00
手瓜一十雪
863a953ae1 style: lint 2025-04-03 15:06:34 +08:00
手瓜一十雪
a44104d8f7 Update OneBotAction.ts 2025-04-03 15:03:00 +08:00
手瓜一十雪
f602bbb0cf fix: 启用类型强制转换 2025-04-03 14:52:33 +08:00
手瓜一十雪
2807ff5927 fix: 刷新群头衔缓存 2025-04-03 14:46:56 +08:00
手瓜一十雪
4fb8e6a4da fix: typo 2025-04-03 14:44:59 +08:00
手瓜一十雪
7ec61f089d fix 2025-04-02 21:40:10 +08:00
手瓜一十雪
f7a500a8cf feat: GroupMemberTitle 2025-04-02 21:30:25 +08:00
Mlikiowa
2b319bd694 release: v4.7.13 2025-04-02 04:05:02 +00:00
手瓜一十雪
24cf7c01f8 fix: 清理文件 2025-04-02 12:04:05 +08:00
手瓜一十雪
aa50e73909 Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2025-04-02 11:58:59 +08:00
手瓜一十雪
d9b33b5439 fix: file clean 2025-04-02 11:58:56 +08:00
Mlikiowa
da58c6bec0 release: v4.7.12 2025-04-02 03:54:37 +00:00
手瓜一十雪
c4cbac4331 fix: #918 2025-04-02 11:51:51 +08:00
手瓜一十雪
ac26a99143 fix: type 2025-04-02 10:49:48 +08:00
手瓜一十雪
640252d391 fix: 初始化后清理 2025-04-02 10:05:57 +08:00
Mlikiowa
258a1dda5e release: v4.7.11 2025-04-01 12:44:06 +00:00
手瓜一十雪
53a7ce2e46 feat: 优化webui快速登录&优化代码整体逻辑 2025-04-01 20:43:46 +08:00
手瓜一十雪
291e2fd8fd feat: 33800 2025-04-01 20:33:14 +08:00
手瓜一十雪
f180c7698f feat: 文件清理quene 2025-04-01 20:22:46 +08:00
手瓜一十雪
183d6f3011 feat: no_cache 2025-04-01 19:54:01 +08:00
bietiaop
ba71d7ad03 fix: #908 2025-03-29 21:26:34 +08:00
手瓜一十雪
26cfaac3bd fix: 增强异常处理 2025-03-29 10:50:27 +08:00
手瓜一十雪
556c8b24c0 fix 2025-03-28 16:55:19 +08:00
Mlikiowa
31f0f527b7 release: v4.7.10 2025-03-27 04:36:54 +00:00
手瓜一十雪
b2e0cab702 feat: 好友等级 2025-03-27 12:35:05 +08:00
Mlikiowa
3e3609e0f2 release: v4.7.9 2025-03-27 04:16:25 +00:00
手瓜一十雪
83e73d9842 fix: 修复一些数据问题 2025-03-27 12:15:53 +08:00
手瓜一十雪
673a175ddf fix: 烘焙raw 2025-03-26 21:51:51 +08:00
手瓜一十雪
12eacd3530 feat: 移除ws 2025-03-21 20:54:59 +08:00
手瓜一十雪
030f0551fd feat: 移除部分淘汰代码 2025-03-21 20:47:38 +08:00
Mlikiowa
47f5947410 release: v4.7.8 2025-03-21 12:43:58 +00:00
手瓜一十雪
aaefa2e83c fix: error 2025-03-21 20:43:41 +08:00
Mlikiowa
f8e92f7c8d release: v4.7.7 2025-03-21 11:48:29 +00:00
手瓜一十雪
b6430e6eb6 fix: 优化 2025-03-21 19:44:31 +08:00
手瓜一十雪
e60605c7bb feat: 简化代码逻辑 2025-03-21 19:40:47 +08:00
手瓜一十雪
58d2bd3c81 Revert "fix: #883"
This reverts commit 79aa1dc67f.
2025-03-20 10:57:57 +08:00
手瓜一十雪
6534d05b76 Revert "fix"
This reverts commit 2d7de174c5.
2025-03-20 10:57:54 +08:00
手瓜一十雪
2d7de174c5 fix 2025-03-20 10:32:30 +08:00
手瓜一十雪
79aa1dc67f fix: #883 2025-03-20 10:32:13 +08:00
Mlikiowa
7792ad9ea0 release: v4.7.6 2025-03-19 07:35:12 +00:00
手瓜一十雪
be6671923b feat: 33139 2025-03-19 15:34:33 +08:00
手瓜一十雪
0fa1b3f044 feat: 33139 2025-03-19 15:26:55 +08:00
手瓜一十雪
4ab751696b Revert "fix: image size"
This reverts commit 2759a34d96.
2025-03-19 11:58:19 +08:00
手瓜一十雪
dce4eedf7d Revert "fix: moduleResolution"
This reverts commit 9ab776d53a.
2025-03-19 11:58:16 +08:00
手瓜一十雪
129b67b751 Revert "chore(deps-dev): bump image-size from 1.2.0 to 2.0.1"
This reverts commit e3feb6a73c.
2025-03-19 11:57:55 +08:00
手瓜一十雪
9ab776d53a fix: moduleResolution 2025-03-19 11:54:29 +08:00
手瓜一十雪
2759a34d96 fix: image size 2025-03-19 11:09:57 +08:00
手瓜一十雪
2f9f42750e Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2025-03-19 10:45:59 +08:00
手瓜一十雪
30abd1f904 fix: #884 2025-03-19 10:45:56 +08:00
手瓜一十雪
008075466e Merge pull request #887 from NapNeko/dependabot/npm_and_yarn/eslint-import-resolver-typescript-4.0.0
chore(deps-dev): bump eslint-import-resolver-typescript from 3.9.1 to 4.0.0
2025-03-19 10:39:33 +08:00
手瓜一十雪
5b4035c320 Merge pull request #888 from NapNeko/dependabot/npm_and_yarn/image-size-2.0.1
chore(deps-dev): bump image-size from 1.2.0 to 2.0.1
2025-03-19 10:39:21 +08:00
dependabot[bot]
e3feb6a73c chore(deps-dev): bump image-size from 1.2.0 to 2.0.1
Bumps [image-size](https://github.com/image-size/image-size) from 1.2.0 to 2.0.1.
- [Release notes](https://github.com/image-size/image-size/releases)
- [Commits](https://github.com/image-size/image-size/compare/v1.2.0...v2.0.1)

---
updated-dependencies:
- dependency-name: image-size
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-17 09:23:32 +00:00
dependabot[bot]
40fe73317d chore(deps-dev): bump eslint-import-resolver-typescript
Bumps [eslint-import-resolver-typescript](https://github.com/import-js/eslint-import-resolver-typescript) from 3.9.1 to 4.0.0.
- [Release notes](https://github.com/import-js/eslint-import-resolver-typescript/releases)
- [Changelog](https://github.com/import-js/eslint-import-resolver-typescript/blob/master/CHANGELOG.md)
- [Commits](https://github.com/import-js/eslint-import-resolver-typescript/compare/v3.9.1...v4.0.0)

---
updated-dependencies:
- dependency-name: eslint-import-resolver-typescript
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-17 09:21:48 +00:00
pk5ls20
073745030c fix: #843
- maybe a temporary solution
2025-03-16 20:07:47 +08:00
Mlikiowa
c523437506 release: v4.7.5 2025-03-16 08:08:15 +00:00
手瓜一十雪
9eef570d37 fix: network prepare 2025-03-16 16:07:51 +08:00
Mlikiowa
be37b8cbbd release: v4.7.4 2025-03-16 07:57:45 +00:00
手瓜一十雪
c635496677 fix: msf Status 2025-03-16 15:57:27 +08:00
Mlikiowa
8753ecfd92 release: v4.7.3 2025-03-16 03:57:48 +00:00
手瓜一十雪
5eda1f2870 fix: quick login 2025-03-16 11:57:28 +08:00
Mlikiowa
d5a60074f7 release: v4.7.2 2025-03-16 03:55:17 +00:00
手瓜一十雪
91df57d932 fix: async error 2025-03-16 11:55:00 +08:00
Mlikiowa
e27d4c4302 release: v4.7.1 2025-03-16 03:40:48 +00:00
手瓜一十雪
55847f6e10 fix: quick login 延迟问题 2025-03-16 11:39:38 +08:00
手瓜一十雪
b39d8bae27 fix: login timer / add:不规范的promise 2025-03-16 10:42:15 +08:00
手瓜一十雪
b0cf23f775 doc: security 2025-03-16 09:36:27 +08:00
手瓜一十雪
c641246056 doc: code of conduct 2025-03-16 09:33:06 +08:00
Mlikiowa
1e5bc9bbea release: v4.7.0 2025-03-16 01:13:17 +00:00
52 changed files with 1990 additions and 400 deletions

View File

@@ -6,5 +6,7 @@
"tsconfig.json": "tsconfig.*.json, env.d.ts, vite.config.ts",
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, manifest.json, logo.png, .gitignore, LICENSE"
},
"css.customData": [".vscode/tailwindcss.json"],
"css.customData": [
".vscode/tailwindcss.json"
],
}

128
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
nanaeonn@outlook.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

11
SECURITY.md Normal file
View File

@@ -0,0 +1,11 @@
# Security Policy
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| > 4.0 | :white_check_mark: |
| < 4.0 | :x: |
## Reporting a Vulnerability
you should open an issue

View File

@@ -1,9 +1,9 @@
{
"name": "qq-chat",
"version": "9.9.18-32793",
"verHash": "d43f097e",
"linuxVersion": "3.2.16-32793",
"linuxVerHash": "ee4bd910",
"version": "9.9.18-32869",
"verHash": "e735296c",
"linuxVersion": "3.2.16-32869",
"linuxVerHash": "4c192ba9",
"private": true,
"description": "QQ",
"productName": "QQ",
@@ -34,9 +34,9 @@
"vuex@4.1.0": "patches/vuex@4.1.0.patch"
}
},
"buildVersion": "32793",
"buildVersion": "32869",
"isPureShell": true,
"isByteCodeShell": true,
"platform": "win32",
"eleArch": "x64"
}
}

View File

@@ -4,7 +4,7 @@
"name": "NapCatQQ",
"slug": "NapCat.Framework",
"description": "高性能的 OneBot 11 协议实现",
"version": "4.6.9",
"version": "4.7.13",
"icon": "./logo.png",
"authors": [
{

View File

@@ -79,6 +79,7 @@ export default function WebLoginPage() {
<CardBody className="flex gap-5 py-5 px-5 md:px-10">
<Input
isClearable
type="password"
classNames={{
label: 'text-black/50 dark:text-white/90',
input: [

View File

@@ -2,7 +2,7 @@
"name": "napcat",
"private": true,
"type": "module",
"version": "4.6.9",
"version": "4.7.13",
"scripts": {
"build:universal": "npm run build:webui && vite build --mode universal || exit 1",
"build:framework": "npm run build:webui && vite build --mode framework || exit 1",
@@ -32,6 +32,7 @@
"@types/express": "^5.0.0",
"@types/multer": "^1.4.12",
"@types/node": "^22.0.1",
"@types/node-wav": "^0.0.4",
"@types/on-finished": "^2.3.4",
"@types/qrcode-terminal": "^0.12.2",
"@types/react-color": "^3.0.13",
@@ -42,10 +43,11 @@
"ajv": "^8.13.0",
"async-mutex": "^0.5.0",
"commander": "^13.0.0",
"compressing": "^1.10.1",
"cors": "^2.8.5",
"esbuild": "0.25.0",
"eslint": "^9.14.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-import-resolver-typescript": "^4.0.0",
"eslint-plugin-import": "^2.29.1",
"express-rate-limit": "^7.5.0",
"fast-xml-parser": "^4.3.6",
@@ -54,19 +56,22 @@
"image-size": "^1.1.1",
"json5": "^2.2.3",
"multer": "^1.4.5-lts.1",
"napcat.protobuf": "^1.1.4",
"typescript": "^5.3.3",
"typescript-eslint": "^8.13.0",
"vite": "^6.0.1",
"vite-plugin-cp": "^4.0.8",
"vite-tsconfig-paths": "^5.1.0",
"napcat.protobuf": "^1.1.3",
"winston": "^3.17.0",
"compressing": "^1.10.1"
"winston": "^3.17.0"
},
"dependencies": {
"@breezystack/lamejs": "^1.2.7",
"@ffmpeg.wasm/core-mt": "^0.13.2",
"audio-decode": "^2.2.2",
"express": "^5.0.0",
"node-wav": "^0.0.2",
"silk-wasm": "^3.6.1",
"wavefile": "^11.0.0",
"ws": "^8.18.0"
}
}

View File

@@ -0,0 +1,145 @@
// WAV 文件头结构
interface WavHeader {
riffChunkId: string; // "RIFF"
riffChunkSize: number; // 文件大小 - 8
riffFormat: string; // "WAVE"
fmtChunkId: string; // "fmt "
fmtChunkSize: number; // 16
audioFormat: number; // 1 = PCM
numChannels: number; // 声道数
sampleRate: number; // 采样率
byteRate: number; // 字节率 (SampleRate * NumChannels * BitsPerSample / 8)
blockAlign: number; // 块对齐 (NumChannels * BitsPerSample / 8)
bitsPerSample: number; // 采样位数
dataChunkId: string; // "data"
dataChunkSize: number; // 音频数据大小
}
export class WavEncoder {
private header: WavHeader;
private data: Buffer;
private dataOffset: number;
public bitsPerSample: number;
constructor(sampleRate: number, numChannels: number, bitsPerSample: number) {
if (![8, 16, 24, 32].includes(bitsPerSample)) {
throw new Error("Unsupported bitsPerSample value. Must be 8, 16, 24, or 32.");
}
this.bitsPerSample = bitsPerSample;
this.header = {
riffChunkId: "RIFF",
riffChunkSize: 0, // 待计算
riffFormat: "WAVE",
fmtChunkId: "fmt ",
fmtChunkSize: 16,
audioFormat: 1, // PCM
numChannels: numChannels,
sampleRate: sampleRate,
byteRate: sampleRate * numChannels * bitsPerSample / 8,
blockAlign: numChannels * bitsPerSample / 8,
bitsPerSample: bitsPerSample,
dataChunkId: "data",
dataChunkSize: 0 // 待计算
};
this.data = Buffer.alloc(0);
this.dataOffset = 0;
}
public write(buffer: Buffer): void {
this.data = Buffer.concat([this.data, buffer]);
this.dataOffset += buffer.length;
}
public encode(): Buffer {
this.header.dataChunkSize = this.dataOffset;
this.header.riffChunkSize = 36 + this.dataOffset;
const headerBuffer = Buffer.alloc(44);
headerBuffer.write(this.header.riffChunkId, 0, 4, 'ascii');
headerBuffer.writeUInt32LE(this.header.riffChunkSize, 4);
headerBuffer.write(this.header.riffFormat, 8, 4, 'ascii');
headerBuffer.write(this.header.fmtChunkId, 12, 4, 'ascii');
headerBuffer.writeUInt32LE(this.header.fmtChunkSize, 16);
headerBuffer.writeUInt16LE(this.header.audioFormat, 20);
headerBuffer.writeUInt16LE(this.header.numChannels, 22);
headerBuffer.writeUInt32LE(this.header.sampleRate, 24);
headerBuffer.writeUInt32LE(this.header.byteRate, 28);
headerBuffer.writeUInt16LE(this.header.blockAlign, 32);
headerBuffer.writeUInt16LE(this.header.bitsPerSample, 34);
headerBuffer.write(this.header.dataChunkId, 36, 4, 'ascii');
headerBuffer.writeUInt32LE(this.header.dataChunkSize, 40);
return Buffer.concat([headerBuffer, this.data]);
}
}
export class WavDecoder {
private header: WavHeader;
private data: Buffer;
private dataOffset: number;
public bitsPerSample: number;
constructor(private buffer: Buffer) {
this.header = {
riffChunkId: "",
riffChunkSize: 0,
riffFormat: "",
fmtChunkId: "",
fmtChunkSize: 0,
audioFormat: 0,
numChannels: 0,
sampleRate: 0,
byteRate: 0,
blockAlign: 0,
bitsPerSample: 0,
dataChunkId: "",
dataChunkSize: 0
};
this.data = Buffer.alloc(0);
this.dataOffset = 0;
this.decodeHeader();
this.decodeData();
this.bitsPerSample = this.header.bitsPerSample;
}
private decodeHeader(): void {
this.header.riffChunkId = this.buffer.toString('ascii', 0, 4);
this.header.riffChunkSize = this.buffer.readUInt32LE(4);
this.header.riffFormat = this.buffer.toString('ascii', 8, 4);
this.header.fmtChunkId = this.buffer.toString('ascii', 12, 4);
this.header.fmtChunkSize = this.buffer.readUInt32LE(16);
this.header.audioFormat = this.buffer.readUInt16LE(20);
this.header.numChannels = this.buffer.readUInt16LE(22);
this.header.sampleRate = this.buffer.readUInt32LE(24);
this.header.byteRate = this.buffer.readUInt32LE(28);
this.header.blockAlign = this.buffer.readUInt16LE(32);
this.header.bitsPerSample = this.buffer.readUInt16LE(34);
this.header.dataChunkId = this.buffer.toString('ascii', 36, 4);
this.header.dataChunkSize = this.buffer.readUInt32LE(40);
this.dataOffset = 44;
// 可以在此处添加对 header 值的校验
if (this.header.riffChunkId !== "RIFF" || this.header.riffFormat !== "WAVE") {
throw new Error("Invalid WAV file format.");
}
if (![8, 16, 24, 32].includes(this.header.bitsPerSample)) {
throw new Error(`Unsupported bitsPerSample: ${this.header.bitsPerSample}`);
}
}
private decodeData(): void {
this.data = this.buffer.slice(this.dataOffset, this.dataOffset + this.header.dataChunkSize);
}
public getHeader(): WavHeader {
return this.header;
}
public getData(): Buffer {
return this.data;
}
}

814
src/common/audio-pure.ts Normal file
View File

@@ -0,0 +1,814 @@
/**
* 现代音频格式转换库 - 使用纯JavaScript实现的音频格式转换工具
* 支持格式: MP3, WAV, FLAC, OGG, OPUS, AMR, M4A和PCM等格式间的转换
* PCM格式支持8位、16位和32位采样深度
*
* 特点:
* - 纯JavaScript/TypeScript实现无需外部依赖如FFmpeg
* - 完全支持Web和Node.js环境
* - 强类型定义和现代化错误处理
* - 高性能实现,支持流式处理
*/
import { readFile, writeFile } from 'fs/promises';
import path from 'path';
import audioDecode from 'audio-decode'; // 解码 WAV MP3 OGG FLAC
import { Mp3Encoder } from '@breezystack/lamejs'; // 编码 MP3
import { WavEncoder, WavDecoder } from './audio-enhance/codec/wav'; // 导入 WavEncoder 和 WavDecoder
// import { Encoder as FlacEncoder } from 'libflacjs/lib/encoder'; // 编码 FLAC
// import * as Flac from 'libflacjs'; // 编码 FLAC
// import { Muxer } from 'mp4-muxer'; // 替换demux用于编码 AAC/M4A
/* ============================================================================
类型与接口定义
============================================================================ */
/**
* 音频处理错误类 - 提供丰富的错误上下文
*/
export class AudioError extends Error {
constructor(
message: string,
public readonly step: 'decode' | 'encode' | 'convert' | 'validate',
public readonly format?: string,
public readonly cause?: Error
) {
super(message);
this.name = 'AudioError';
// 捕获原始错误堆栈
if (cause && cause.stack) {
this.stack = `${this.stack}\nCaused by: ${cause.stack}`;
}
}
}
/** 解码后的PCM数据及相关音频信息 */
export interface PCMData {
/** PCM样本数据统一使用Float32Array表示 */
samples: Float32Array;
/** 采样率Hz) */
sampleRate: number;
/** 声道数 */
channels: number;
/** 音频元数据 (可选) */
metadata?: AudioMetadata;
}
/** 音频元数据 */
export interface AudioMetadata {
title?: string;
artist?: string;
album?: string;
year?: number;
genre?: string;
duration?: number; // 秒
[key: string]: any; // 允许其他元数据
}
/** 音频转换选项 */
export interface ConvertOptions {
/** 目标采样率 */
sampleRate?: number;
/** 目标声道数 */
channels?: number;
/** PCM位深度 (8, 16 或 32) */
bitDepth?: 8 | 16 | 32;
/** 编码比特率 (kbps) */
bitrate?: number;
/** 编码质量 (0-1) */
quality?: number;
/** 保留元数据 */
preserveMetadata?: boolean;
/** 使用Web Worker (仅浏览器环境) */
useWorker?: boolean;
}
/**
* 音频编解码器接口
*/
interface Codec {
/** 编解码器名称 */
readonly name: string;
/** 支持的文件扩展名 */
readonly extensions: string[];
/** 检查是否支持指定格式 */
supports(format: string): boolean;
/** 解码音频数据为PCM */
decode(buffer: Buffer, options?: ConvertOptions): Promise<PCMData>;
/** 编码PCM数据为目标格式 */
encode(pcmData: PCMData, options?: ConvertOptions): Promise<Buffer>;
}
/**
* PCM数据处理工具
*/
class AudioProcessor {
/**
* 将Float32Array PCM数据转换为指定位深度的Buffer
*/
static floatToPCM(samples: Float32Array, bitDepth: number): Buffer {
const bytesPerSample = bitDepth / 8;
const buffer = Buffer.alloc(samples.length * bytesPerSample);
if (bitDepth === 8) {
for (let i = 0; i < samples.length; i++) {
// 将[-1,1]映射到[0,255]
const sample = Math.max(-1, Math.min(1, samples[i]!));
buffer[i] = (sample * 0.5 + 0.5) * 255;
}
} else if (bitDepth === 16) {
for (let i = 0; i < samples.length; i++) {
// 将[-1,1]映射到[-32768,32767]
const sample = Math.max(-1, Math.min(1, samples[i]!));
const val = sample < 0 ? sample * 32768 : sample * 32767;
buffer.writeInt16LE(Math.floor(val), i * 2);
}
} else if (bitDepth === 32) {
for (let i = 0; i < samples.length; i++) {
// 将[-1,1]映射到[-2147483648,2147483647]
const sample = Math.max(-1, Math.min(1, samples[i]!));
const val = sample < 0 ? sample * 2147483648 : sample * 2147483647;
buffer.writeInt32LE(Math.floor(val), i * 4);
}
} else {
throw new AudioError(`不支持的PCM位深度: ${bitDepth}`, 'encode', 'pcm');
}
return buffer;
}
/**
* 将指定位深度的PCM Buffer转换为Float32Array
*/
static pcmToFloat(buffer: Buffer, bitDepth: number): Float32Array {
const samples = new Float32Array(buffer.length / (bitDepth / 8));
if (bitDepth === 8) {
for (let i = 0; i < samples.length; i++) {
// 将[0,255]映射回[-1,1]
samples[i] = (buffer[i]! / 255) * 2 - 1;
}
} else if (bitDepth === 16) {
for (let i = 0; i < samples.length; i++) {
const val = buffer.readInt16LE(i * 2);
// 将[-32768,32767]映射回[-1,1]
samples[i] = val < 0 ? val / 32768 : val / 32767;
}
} else if (bitDepth === 32) {
for (let i = 0; i < samples.length; i++) {
const val = buffer.readInt32LE(i * 4);
// 将[-2147483648,2147483647]映射回[-1,1]
samples[i] = val < 0 ? val / 2147483648 : val / 2147483647;
}
} else {
throw new AudioError(`不支持的PCM位深度: ${bitDepth}`, 'decode', 'pcm');
}
return samples;
}
/**
* 重采样PCM数据
*/
static resample(samples: Float32Array, fromRate: number, toRate: number, channels: number): Float32Array {
if (fromRate === toRate) return samples;
const ratio = toRate / fromRate;
const inputLength = samples.length;
const outputLength = Math.ceil(inputLength * ratio);
const result = new Float32Array(outputLength);
// 线性插值重采样
for (let i = 0; i < outputLength; i++) {
const pos = i / ratio;
const leftPos = Math.floor(pos);
const rightPos = Math.min(leftPos + 1, inputLength - 1);
const fraction = pos - leftPos;
// 对每个通道分别进行插值
for (let channel = 0; channel < channels; channel++) {
const leftIdx = leftPos * channels + channel;
const rightIdx = rightPos * channels + channel;
const leftSample = samples[leftIdx] || 0;
const rightSample = samples[rightIdx] || 0;
// 线性插值
result[i * channels + channel] = leftSample + fraction * (rightSample - leftSample);
}
}
return result;
}
/**
* 混合声道 (多声道到单声道或立体声)
*/
static mixChannels(samples: Float32Array, fromChannels: number, toChannels: number): Float32Array {
if (fromChannels === toChannels) return samples;
const frameCount = samples.length / fromChannels;
const result = new Float32Array(frameCount * toChannels);
if (fromChannels === 1 && toChannels === 2) {
// 单声道到立体声 - 复制到两个声道
for (let i = 0; i < frameCount; i++) {
const sample = samples[i]!;
result[i * 2] = sample; // 左声道
result[i * 2 + 1] = sample; // 右声道
}
} else if (fromChannels === 2 && toChannels === 1) {
// 立体声到单声道 - 取平均值
for (let i = 0; i < frameCount; i++) {
const left = samples[i * 2];
const right = samples[i * 2 + 1];
result[i] = (left! + right!) / 2;
}
} else if (fromChannels > toChannels) {
// 多声道到少声道 - 根据需要混合
for (let i = 0; i < frameCount; i++) {
for (let c = 0; c < toChannels; c++) {
// 根据toChannel位置映射到fromChannel
let sum = 0;
let count = 0;
for (let fc = c; fc < fromChannels; fc += toChannels) {
sum += samples[i * fromChannels + fc]!;
count++;
}
result[i * toChannels + c] = sum / count;
}
}
} else {
// 少声道到多声道 - 根据需要复制
for (let i = 0; i < frameCount; i++) {
for (let c = 0; c < toChannels; c++) {
// 循环复制
const fromChannel = c % fromChannels;
result[i * toChannels + c] = samples[i * fromChannels + fromChannel]!;
}
}
}
return result;
}
/**
* 处理PCM数据包括重采样和声道转换
*/
static processPCM(pcmData: PCMData, options?: ConvertOptions): PCMData {
const targetSampleRate = options?.sampleRate ?? pcmData.sampleRate;
const targetChannels = options?.channels ?? pcmData.channels;
let processedSamples = pcmData.samples;
// 如果需要重采样
console.log(`重采样: ${pcmData.sampleRate}Hz → ${targetSampleRate}Hz`);
if (pcmData.sampleRate !== targetSampleRate) {
processedSamples = this.resample(
processedSamples,
pcmData.sampleRate,
targetSampleRate,
pcmData.channels
);
}
// 如果需要改变声道数
if (pcmData.channels !== targetChannels) {
processedSamples = this.mixChannels(
processedSamples,
pcmData.channels,
targetChannels
);
}
return {
samples: processedSamples,
sampleRate: targetSampleRate,
channels: targetChannels,
metadata: options?.preserveMetadata ? pcmData.metadata : undefined
};
}
/**
* 从Buffer中提取音频元数据
*/
static extractMetadata(data: any): AudioMetadata | undefined {
if (!data) return undefined;
return {
title: data.title || data.TITLE,
artist: data.artist || data.ARTIST || data.performer,
album: data.album || data.ALBUM,
year: data.year ? parseInt(data.year) : (data.date ? parseInt(data.date) : undefined),
genre: data.genre || data.GENRE,
duration: data.duration
};
}
/**
* 将交织的PCM数据分离为各声道数据
*/
static deinterleaveChannels(samples: Float32Array | Int16Array, channels: number): Array<Float32Array | Int16Array> {
const frameCount = samples.length / channels;
const result = new Array(channels);
// 创建每个声道的数组
for (let c = 0; c < channels; c++) {
result[c] = new (samples.constructor as any)(frameCount);
}
// 分离声道数据
for (let i = 0; i < frameCount; i++) {
for (let c = 0; c < channels; c++) {
result[c][i] = samples[i * channels + c];
}
}
return result;
}
/**
* 将Float32Array转换为Int16Array
*/
static floatToInt16(samples: Float32Array): Int16Array {
const int16Samples = new Int16Array(samples.length);
for (let i = 0; i < samples.length; i++) {
const sample = Math.max(-1, Math.min(1, samples[i]!));
int16Samples[i] = Math.round(sample < 0 ? sample * 32768 : sample * 32767);
}
return int16Samples;
}
}
/* ============================================================================
编解码器实现
============================================================================ */
/**
* 通用音频解码器 - 使用audio-decode库处理多种格式
*/
class GenericDecoder {
/**
* 使用audio-decode解码多种格式
*/
static async decode(buffer: Buffer, _options?: ConvertOptions): Promise<PCMData> {
try {
// 使用audio-decode解码音频
const audioData = await audioDecode(buffer);
return {
samples: this.interleaveSamples(audioData),
sampleRate: audioData.sampleRate,
channels: audioData.numberOfChannels,
metadata: AudioProcessor.extractMetadata({})
};
} catch (error: any) {
throw new AudioError(
`音频解码错误: ${error.message}`,
'decode',
'audio',
error
);
}
}
/**
* 将多声道音频数据交织成单个Float32Array
*/
private static interleaveSamples(audioData: AudioBuffer): Float32Array {
const channels = audioData.numberOfChannels;
const length = audioData.length;
const result = new Float32Array(length * channels);
for (let c = 0; c < channels; c++) {
const channelData = audioData.getChannelData(c);
for (let i = 0; i < length; i++) {
result[i * channels + c] = channelData[i]!;
}
}
return result;
}
}
/**
* 基础编解码器类 - 提供通用实现
*/
abstract class BaseCodec implements Codec {
abstract readonly name: string;
abstract readonly extensions: string[];
supports(format: string): boolean {
return this.extensions.includes(format.toLowerCase());
}
async decode(buffer: Buffer, options?: ConvertOptions): Promise<PCMData> {
return GenericDecoder.decode(buffer, options);
}
abstract encode(pcmData: PCMData, options?: ConvertOptions): Promise<Buffer>;
}
/**
* MP3编解码器
*/
class MP3Codec extends BaseCodec {
readonly name = 'MP3 Codec';
readonly extensions = ['mp3'];
async encode(pcmData: PCMData, options?: ConvertOptions): Promise<Buffer> {
try {
const processed = AudioProcessor.processPCM(pcmData, options);
const bitrate = options?.bitrate ?? 128;
// 创建MP3编码器
const encoder = new Mp3Encoder(
processed.channels,
processed.sampleRate,
bitrate
);
// 将Float32Array转换为Int16Array (lamejs需要)
const samples = AudioProcessor.floatToPCM(processed.samples, 16);
const int16Samples = new Int16Array(samples.buffer, samples.byteOffset, samples.length / 2);
const mp3Data: Uint8Array[] = [];
const sampleBlockSize = 1152; // MP3编码的标准帧大小
// 分块处理,避免内存占用过大
for (let i = 0; i < int16Samples.length; i += sampleBlockSize) {
const chunk = int16Samples.subarray(i, i + sampleBlockSize);
const mp3buf = encoder.encodeBuffer(chunk);
if (mp3buf.length > 0) {
mp3Data.push(new Uint8Array(mp3buf));
}
}
// 完成编码,获取最后一块数据
const finalChunk = encoder.flush();
if (finalChunk.length > 0) {
mp3Data.push(new Uint8Array(finalChunk));
}
// 合并所有MP3数据块
const totalLength = mp3Data.reduce((sum, arr) => sum + arr.length, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
for (const arr of mp3Data) {
result.set(arr, offset);
offset += arr.length;
}
return Buffer.from(result);
} catch (error: any) {
throw new AudioError(`MP3编码错误: ${error.message}`, 'encode', 'mp3', error);
}
}
}
/**
* WAV编解码器
*/
class WAVCodec extends BaseCodec {
readonly name = 'WAV Codec';
readonly extensions = ['wav'];
override async decode(buffer: Buffer, options?: ConvertOptions): Promise<PCMData> {
try {
const decoder = new WavDecoder(buffer);
const header = decoder.getHeader();
const data = decoder.getData();
const sampleRate = header.sampleRate;
const channels = header.numChannels;
const bitsPerSample = header.bitsPerSample;
// 将Buffer转换为Float32Array
let samples: Float32Array;
if (bitsPerSample === 8 || bitsPerSample === 16 || bitsPerSample === 32) {
samples = AudioProcessor.pcmToFloat(data, bitsPerSample);
} else {
throw new AudioError(`不支持的WAV位深: ${bitsPerSample}`, 'decode', 'wav');
}
return {
samples,
sampleRate,
channels,
metadata: undefined
};
} catch (error: any) {
// WAV解析失败尝试使用通用解码器
return GenericDecoder.decode(buffer, options);
}
}
async encode(pcmData: PCMData, options?: ConvertOptions): Promise<Buffer> {
try {
const processed = AudioProcessor.processPCM(pcmData, options);
const bitDepth = options?.bitDepth ?? 16;
const encoder = new WavEncoder(processed.sampleRate, processed.channels, bitDepth);
// 将Float32Array转换为指定位深度的Buffer
const pcmBuffer = AudioProcessor.floatToPCM(processed.samples, bitDepth);
encoder.write(pcmBuffer);
return encoder.encode();
} catch (error: any) {
throw new AudioError(`WAV编码错误: ${error.message}`, 'encode', 'wav', error);
}
}
}
/**
* OGG Vorbis编解码器
*/
class OGGCodec extends BaseCodec {
readonly name = 'OGG Vorbis Codec';
readonly extensions = ['ogg'];
async encode(pcmData: PCMData, options?: ConvertOptions): Promise<Buffer> {
try {
// 注意这里应该使用专门的OGG Vorbis编码库但为了保持库的纯JavaScript特性
// 我们可以使用一个基于Web Audio API的解决方案或找一个纯JS的OGG编码器
// 由于pure-JS的OGG编码器较为复杂这里提供一个简化的实现
// 在实际应用中应使用专门的库如ogg-vorbis-encoder-js
const processed = AudioProcessor.processPCM(pcmData, options);
// 如果后续需要OGG编码功能请添加合适的库
// 这里返回一个模拟实现
return this.createMockOggFile(processed, options);
} catch (error: any) {
throw new AudioError(`OGG编码错误: ${error.message}`, 'encode', 'ogg', error);
}
}
// 创建模拟的OGG文件仅作示例实际应用中请替换为真实OGG编码
private createMockOggFile(pcmData: PCMData, options?: ConvertOptions): Buffer {
const quality = options?.quality ?? 0.5;
// 创建基本的OGG头部
const header = Buffer.alloc(100);
header.write('OggS', 0);
header.writeUInt8(0, 4); // 版本
header.writeUInt8(pcmData.channels, 5);
header.writeUInt32LE(pcmData.sampleRate, 6);
header.writeUInt8(Math.floor(quality * 10), 10);
// 对音频数据进行简单的处理(仅作示例)
const samplesBuffer = AudioProcessor.floatToPCM(pcmData.samples, 16);
// 组合头部和数据
return Buffer.concat([header, samplesBuffer]);
}
}
/**
* PCM编解码器
*/
class PCMCodec implements Codec {
readonly name = 'PCM Codec';
readonly extensions = ['pcm'];
supports(format: string): boolean {
return this.extensions.includes(format.toLowerCase());
}
async decode(buffer: Buffer, options?: ConvertOptions): Promise<PCMData> {
try {
const bitDepth = options?.bitDepth ?? 16;
// 验证位深度是否受支持
if (![8, 16, 32].includes(bitDepth)) {
throw new AudioError(`不支持的PCM位深: ${bitDepth}`, 'decode', 'pcm');
}
// 获取采样率和声道数 (PCM文件本身不包含这些信息使用默认值或用户提供的值)
const sampleRate = options?.sampleRate ?? 44100;
const channels = options?.channels ?? 2;
// 将PCM数据转换为Float32Array
const samples = AudioProcessor.pcmToFloat(buffer, bitDepth);
return {
samples,
sampleRate,
channels
};
} catch (error: any) {
if (error instanceof AudioError) throw error;
throw new AudioError(`PCM解码错误: ${error.message}`, 'decode', 'pcm', error);
}
}
async encode(pcmData: PCMData, options?: ConvertOptions): Promise<Buffer> {
try {
const processed = AudioProcessor.processPCM(pcmData, options);
const bitDepth = options?.bitDepth ?? 16;
// 验证位深度是否受支持
if (![8, 16, 32].includes(bitDepth)) {
throw new AudioError(`不支持的PCM位深: ${bitDepth}`, 'encode', 'pcm');
}
// 将Float32Array转换为指定位深度的PCM数据
return AudioProcessor.floatToPCM(processed.samples, bitDepth);
} catch (error: any) {
if (error instanceof AudioError) throw error;
throw new AudioError(`PCM编码错误: ${error.message}`, 'encode', 'pcm', error);
}
}
}
/**
* 编解码器注册表
*/
class CodecRegistry {
private static codecs: Map<string, Codec> = new Map();
private static initialized = false;
/**
* 初始化编解码器注册表
*/
static init(): void {
if (this.initialized) return;
// 注册所有支持的编解码器
this.register(new MP3Codec());
this.register(new WAVCodec());
this.register(new OGGCodec());
this.register(new PCMCodec());
this.initialized = true;
}
/**
* 注册编解码器
*/
static register(codec: Codec): void {
codec.extensions.forEach(ext => this.codecs.set(ext.toLowerCase(), codec));
}
/**
* 获取指定格式的编解码器
*/
static getCodec(format: string): Codec {
this.init();
const codec = this.codecs.get(format.toLowerCase());
if (!codec) {
throw new AudioError(`不支持的音频格式: ${format}`, 'validate', format);
}
return codec;
}
/**
* 获取所有支持的格式
*/
static getSupportedFormats(): string[] {
this.init();
return [...new Set(this.codecs.keys())];
}
}
/**
* 转换音频文件格式
*
* @param inputPath 输入文件路径
* @param outputPath 输出文件路径
* @param targetFormat 目标格式
* @param options 转换选项
*/
export async function convertAudio(
inputPath: string,
outputPath: string,
targetFormat: string,
options?: ConvertOptions
): Promise<void> {
// 初始化编解码器注册表
CodecRegistry.init();
// 提取文件扩展名
const inputExt = path.extname(inputPath).slice(1).toLowerCase();
// 验证格式支持
if (!CodecRegistry.getSupportedFormats().includes(inputExt)) {
throw new AudioError(`不支持的输入格式: ${inputExt}`, 'validate', inputExt);
}
if (!CodecRegistry.getSupportedFormats().includes(targetFormat)) {
throw new AudioError(`不支持的目标格式: ${targetFormat}`, 'validate', targetFormat);
}
try {
// 读取输入文件
const inputBuffer = await readFile(inputPath);
// 解码为PCM
const inputCodec = CodecRegistry.getCodec(inputExt);
const decoded = await inputCodec.decode(inputBuffer, options);
// 编码为目标格式
const outputCodec = CodecRegistry.getCodec(targetFormat);
const outputBuffer = await outputCodec.encode(decoded, options);
// 写入输出文件
await writeFile(outputPath, outputBuffer);
console.log(
`转换完成: ${inputExt}${targetFormat}, ` +
`保存到 ${outputPath} ` +
`(${(outputBuffer.length / 1024).toFixed(2)} KB)`
);
} catch (error: any) {
// 统一错误处理
if (error instanceof AudioError) {
throw error;
}
throw new AudioError(
`音频转换失败: ${error.message}`,
'convert',
`${inputExt}->${targetFormat}`,
error
);
}
}
/**
* 从二进制数据转换音频格式
*
* @param inputBuffer 输入音频数据
* @param inputFormat 输入格式
* @param outputFormat 输出格式
* @param options 转换选项
* @returns 转换后的音频数据
*/
export async function convertAudioBuffer(
inputBuffer: Buffer,
inputFormat: string,
outputFormat: string,
options?: ConvertOptions
): Promise<Buffer> {
// 初始化编解码器注册表
CodecRegistry.init();
// 验证格式支持
if (!CodecRegistry.getSupportedFormats().includes(inputFormat)) {
throw new AudioError(`不支持的输入格式: ${inputFormat}`, 'validate', inputFormat);
}
if (!CodecRegistry.getSupportedFormats().includes(outputFormat)) {
throw new AudioError(`不支持的目标格式: ${outputFormat}`, 'validate', outputFormat);
}
try {
// 解码为PCM
const inputCodec = CodecRegistry.getCodec(inputFormat);
const decoded = await inputCodec.decode(inputBuffer, options);
// 编码为目标格式
const outputCodec = CodecRegistry.getCodec(outputFormat);
return await outputCodec.encode(decoded, options);
} catch (error: any) {
// 统一错误处理
if (error instanceof AudioError) {
throw error;
}
throw new AudioError(
`音频转换失败: ${error.message}`,
'convert',
`${inputFormat}->${outputFormat}`,
error
);
}
}
/**
* 创建音频转换函数
*
* @param inputFormat 输入格式
* @param outputFormat 输出格式
* @param options 转换选项
*/
export async function createAudioConverter(
inputFormat: string,
outputFormat: string,
options?: ConvertOptions
): Promise<(inputBuffer: Buffer) => Promise<Buffer>> {
// 初始化编解码器
CodecRegistry.init();
// 验证格式支持
const inputCodec = CodecRegistry.getCodec(inputFormat);
const outputCodec = CodecRegistry.getCodec(outputFormat);
// 返回转换函数
return async (inputBuffer: Buffer): Promise<Buffer> => {
const decoded = await inputCodec.decode(inputBuffer, options);
return outputCodec.encode(decoded, options);
};
}

229
src/common/clean-task.ts Normal file
View File

@@ -0,0 +1,229 @@
import fs from 'fs';
// generate Claude 3.7 Sonet Thinking
interface FileRecord {
filePath: string;
addedTime: number;
retries: number;
}
interface CleanupTask {
fileRecord: FileRecord;
timer: NodeJS.Timeout;
}
class CleanupQueue {
private tasks: Map<string, CleanupTask> = new Map();
private readonly MAX_RETRIES = 3;
private isProcessing: boolean = false;
private pendingOperations: Array<() => void> = [];
/**
* 执行队列中的待处理操作,确保异步安全
*/
private executeNextOperation(): void {
if (this.pendingOperations.length === 0) {
this.isProcessing = false;
return;
}
this.isProcessing = true;
const operation = this.pendingOperations.shift();
operation?.();
// 使用 setImmediate 允许事件循环继续,防止阻塞
setImmediate(() => this.executeNextOperation());
}
/**
* 安全执行操作,防止竞态条件
* @param operation 要执行的操作
*/
private safeExecute(operation: () => void): void {
this.pendingOperations.push(operation);
if (!this.isProcessing) {
this.executeNextOperation();
}
}
/**
* 检查文件是否存在
* @param filePath 文件路径
* @returns 文件是否存在
*/
private fileExists(filePath: string): boolean {
try {
return fs.existsSync(filePath);
} catch (error) {
//console.log(`检查文件存在出错: ${filePath}`, error);
return false;
}
}
/**
* 添加文件到清理队列
* @param filePath 文件路径
* @param cleanupDelay 清理延迟时间(毫秒)
*/
addFile(filePath: string, cleanupDelay: number): void {
this.safeExecute(() => {
// 如果文件已在队列中,取消原来的计时器
if (this.tasks.has(filePath)) {
this.cancelCleanup(filePath);
}
// 创建新的文件记录
const fileRecord: FileRecord = {
filePath,
addedTime: Date.now(),
retries: 0
};
// 设置计时器
const timer = setTimeout(() => {
this.cleanupFile(fileRecord, cleanupDelay);
}, cleanupDelay);
// 添加到任务队列
this.tasks.set(filePath, { fileRecord, timer });
});
}
/**
* 批量添加文件到清理队列
* @param filePaths 文件路径数组
* @param cleanupDelay 清理延迟时间(毫秒)
*/
addFiles(filePaths: string[], cleanupDelay: number): void {
this.safeExecute(() => {
for (const filePath of filePaths) {
// 内部直接处理,不通过 safeExecute 以保证批量操作的原子性
if (this.tasks.has(filePath)) {
// 取消已有的计时器,但不使用 cancelCleanup 方法以避免重复的安全检查
const existingTask = this.tasks.get(filePath);
if (existingTask) {
clearTimeout(existingTask.timer);
}
}
const fileRecord: FileRecord = {
filePath,
addedTime: Date.now(),
retries: 0
};
const timer = setTimeout(() => {
this.cleanupFile(fileRecord, cleanupDelay);
}, cleanupDelay);
this.tasks.set(filePath, { fileRecord, timer });
}
});
}
/**
* 清理文件
* @param record 文件记录
* @param delay 延迟时间,用于重试
*/
private cleanupFile(record: FileRecord, delay: number): void {
this.safeExecute(() => {
// 首先检查文件是否存在,不存在则视为清理成功
if (!this.fileExists(record.filePath)) {
//console.log(`文件已不存在,跳过清理: ${record.filePath}`);
this.tasks.delete(record.filePath);
return;
}
try {
// 尝试删除文件
fs.unlinkSync(record.filePath);
// 删除成功,从队列中移除任务
this.tasks.delete(record.filePath);
} catch (error) {
const err = error as NodeJS.ErrnoException;
// 明确处理文件不存在的情况
if (err.code === 'ENOENT') {
//console.log(`文件在删除时不存在,视为清理成功: ${record.filePath}`);
this.tasks.delete(record.filePath);
return;
}
// 文件没有访问权限等情况
if (err.code === 'EACCES' || err.code === 'EPERM') {
//console.error(`没有权限删除文件: ${record.filePath}`, err);
}
// 其他删除失败情况,考虑重试
if (record.retries < this.MAX_RETRIES - 1) {
// 还有重试机会,增加重试次数
record.retries++;
//console.log(`清理文件失败,将重试(${record.retries}/${this.MAX_RETRIES}): ${record.filePath}`);
// 设置相同的延迟时间再次尝试
const timer = setTimeout(() => {
this.cleanupFile(record, delay);
}, delay);
// 更新任务
this.tasks.set(record.filePath, { fileRecord: record, timer });
} else {
// 已达到最大重试次数,从队列中移除任务
this.tasks.delete(record.filePath);
//console.error(`清理文件失败,已达最大重试次数(${this.MAX_RETRIES}): ${record.filePath}`, error);
}
}
});
}
/**
* 取消文件的清理任务
* @param filePath 文件路径
* @returns 是否成功取消
*/
cancelCleanup(filePath: string): boolean {
let cancelled = false;
this.safeExecute(() => {
const task = this.tasks.get(filePath);
if (task) {
clearTimeout(task.timer);
this.tasks.delete(filePath);
cancelled = true;
}
});
return cancelled;
}
/**
* 获取队列中的文件数量
* @returns 文件数量
*/
getQueueSize(): number {
return this.tasks.size;
}
/**
* 获取所有待清理的文件
* @returns 文件路径数组
*/
getPendingFiles(): string[] {
return Array.from(this.tasks.keys());
}
/**
* 清空所有清理任务
*/
clearAll(): void {
this.safeExecute(() => {
// 取消所有定时器
for (const task of this.tasks.values()) {
clearTimeout(task.timer);
}
this.tasks.clear();
//console.log('已清空所有清理任务');
});
}
}
export const cleanTaskQueue = new CleanupQueue();

View File

@@ -16,6 +16,9 @@ export function recvTask<T>(cb: (taskData: T) => Promise<unknown>) {
}
});
}
export function sendLog(_log: string) {
//parentPort?.postMessage({ log });
}
class FFmpegService {
public static async extractThumbnail(videoPath: string, thumbnailPath: string): Promise<void> {
const ffmpegInstance = await FFmpeg.create({ core: '@ffmpeg.wasm/core-mt' });
@@ -107,35 +110,175 @@ class FFmpegService {
}
}
}
public static async getVideoInfo(videoPath: string, thumbnailPath: string): Promise<VideoInfo> {
await FFmpegService.extractThumbnail(videoPath, thumbnailPath);
const fileType = (await fileTypeFromFile(videoPath))?.ext ?? 'mp4';
const inputFileName = `${randomUUID()}.${fileType}`;
const ffmpegInstance = await FFmpeg.create({ core: '@ffmpeg.wasm/core-mt' });
ffmpegInstance.fs.writeFile(inputFileName, readFileSync(videoPath));
ffmpegInstance.setLogging(true);
let duration = 60;
ffmpegInstance.setLogger((_level, ...msg) => {
const message = msg.join(' ');
const durationMatch = message.match(/Duration: (\d+):(\d+):(\d+\.\d+)/);
if (durationMatch) {
const hours = parseInt(durationMatch[1] ?? '0', 10);
const minutes = parseInt(durationMatch[2] ?? '0', 10);
const seconds = parseFloat(durationMatch[3] ?? '0');
duration = hours * 3600 + minutes * 60 + seconds;
}
});
await ffmpegInstance.run('-i', inputFileName);
const image = imageSize(thumbnailPath);
ffmpegInstance.fs.unlink(inputFileName);
const fileSize = statSync(videoPath).size;
const startTime = Date.now();
sendLog(`开始获取视频信息: ${videoPath}`);
// 创建一个超时包装函数
const withTimeout = <T>(promise: Promise<T>, timeoutMs: number, taskName: string): Promise<T> => {
return Promise.race([
promise,
new Promise<T>((_, reject) => {
setTimeout(() => reject(new Error(`任务超时: ${taskName} (${timeoutMs}ms)`)), timeoutMs);
})
]);
};
// 并行执行多个任务
const [fileInfo, durationInfo] = await Promise.all([
// 任务1: 获取文件信息和提取缩略图
(async () => {
sendLog(`开始任务1: 获取文件信息和提取缩略图`);
// 获取文件信息 (并行)
const fileInfoStartTime = Date.now();
const [fileType, fileSize] = await Promise.all([
withTimeout(fileTypeFromFile(videoPath), 10000, '获取文件类型')
.then(result => {
sendLog(`获取文件类型完成,耗时: ${Date.now() - fileInfoStartTime}ms`);
return result;
}),
(async () => {
const result = statSync(videoPath).size;
sendLog(`获取文件大小完成,耗时: ${Date.now() - fileInfoStartTime}ms`);
return result;
})()
]);
// 直接实现缩略图提取 (不调用extractThumbnail方法)
const thumbStartTime = Date.now();
sendLog(`开始提取缩略图`);
const ffmpegInstance = await withTimeout(
FFmpeg.create({ core: '@ffmpeg.wasm/core-mt' }),
15000,
'创建FFmpeg实例(缩略图)'
);
const videoFileName = `${randomUUID()}.mp4`;
const outputFileName = `${randomUUID()}.jpg`;
try {
// 写入视频文件到FFmpeg
const writeFileStartTime = Date.now();
ffmpegInstance.fs.writeFile(videoFileName, readFileSync(videoPath));
sendLog(`写入视频文件到FFmpeg完成耗时: ${Date.now() - writeFileStartTime}ms`);
// 提取缩略图
const extractStartTime = Date.now();
const code = await withTimeout(
ffmpegInstance.run('-i', videoFileName, '-ss', '00:00:01.000', '-vframes', '1', outputFileName),
30000,
'提取缩略图'
);
sendLog(`FFmpeg提取缩略图命令执行完成耗时: ${Date.now() - extractStartTime}ms`);
if (code !== 0) {
throw new Error('Error extracting thumbnail: FFmpeg process exited with code ' + code);
}
// 读取并保存缩略图
const saveStartTime = Date.now();
const thumbnail = ffmpegInstance.fs.readFile(outputFileName);
writeFileSync(thumbnailPath, thumbnail);
sendLog(`读取并保存缩略图完成,耗时: ${Date.now() - saveStartTime}ms`);
// 获取缩略图尺寸
const imageSizeStartTime = Date.now();
const image = imageSize(thumbnailPath);
sendLog(`获取缩略图尺寸完成,耗时: ${Date.now() - imageSizeStartTime}ms`);
sendLog(`提取缩略图完成,总耗时: ${Date.now() - thumbStartTime}ms`);
return {
format: fileType?.ext ?? 'mp4',
size: fileSize,
width: image.width ?? 100,
height: image.height ?? 100
};
} finally {
// 清理资源
try {
ffmpegInstance.fs.unlink(outputFileName);
} catch (error) {
sendLog(`清理输出文件失败: ${(error as Error).message}`);
}
try {
ffmpegInstance.fs.unlink(videoFileName);
} catch (error) {
sendLog(`清理视频文件失败: ${(error as Error).message}`);
}
}
})(),
// 任务2: 获取视频时长
(async () => {
const task2StartTime = Date.now();
sendLog(`开始任务2: 获取视频时长`);
// 创建FFmpeg实例
const ffmpegCreateStartTime = Date.now();
const ffmpegInstance = await withTimeout(
FFmpeg.create({ core: '@ffmpeg.wasm/core-mt' }),
15000,
'创建FFmpeg实例(时长)'
);
sendLog(`创建FFmpeg实例完成耗时: ${Date.now() - ffmpegCreateStartTime}ms`);
const inputFileName = `${randomUUID()}.mp4`;
try {
// 写入文件
const writeStartTime = Date.now();
ffmpegInstance.fs.writeFile(inputFileName, readFileSync(videoPath));
sendLog(`写入文件到FFmpeg完成耗时: ${Date.now() - writeStartTime}ms`);
ffmpegInstance.setLogging(true);
let duration = 60; // 默认值
ffmpegInstance.setLogger((_level, ...msg) => {
const message = msg.join(' ');
const durationMatch = message.match(/Duration: (\d+):(\d+):(\d+\.\d+)/);
if (durationMatch) {
const hours = parseInt(durationMatch[1] ?? '0', 10);
const minutes = parseInt(durationMatch[2] ?? '0', 10);
const seconds = parseFloat(durationMatch[3] ?? '0');
duration = hours * 3600 + minutes * 60 + seconds;
}
});
// 执行FFmpeg
const runStartTime = Date.now();
await withTimeout(
ffmpegInstance.run('-i', inputFileName),
20000,
'获取视频时长'
);
sendLog(`执行FFmpeg命令完成耗时: ${Date.now() - runStartTime}ms`);
sendLog(`任务2(获取视频时长)完成,总耗时: ${Date.now() - task2StartTime}ms`);
return { time: duration };
} finally {
try {
ffmpegInstance.fs.unlink(inputFileName);
} catch (error) {
sendLog(`清理输入文件失败: ${(error as Error).message}`);
}
}
})()
]);
// 合并结果并返回
const totalDuration = Date.now() - startTime;
sendLog(`获取视频信息完成,总耗时: ${totalDuration}ms`);
return {
width: image.width ?? 100,
height: image.height ?? 100,
time: duration,
format: fileType,
size: fileSize,
width: fileInfo.width,
height: fileInfo.height,
time: durationInfo.time,
format: fileInfo.format,
size: fileInfo.size,
filePath: videoPath
};
}

View File

@@ -30,7 +30,7 @@ export class FFmpegService {
}
public static async getVideoInfo(videoPath: string, thumbnailPath: string): Promise<VideoInfo> {
const result = await await runTask<EncodeArgs, EncodeResult>(getWorkerPath(), { method: 'getVideoInfo', args: [videoPath, thumbnailPath] });
const result = await runTask<EncodeArgs, EncodeResult>(getWorkerPath(), { method: 'getVideoInfo', args: [videoPath, thumbnailPath] });
return result;
}
}

View File

@@ -76,7 +76,7 @@ export function calculateFileMD5(filePath: string): Promise<string> {
const stream = fs.createReadStream(filePath);
const hash = crypto.createHash('md5');
stream.on('data', (data: Buffer) => {
stream.on('data', (data) => {
// 当读取到数据时,更新哈希对象的状态
hash.update(data);
});
@@ -182,28 +182,28 @@ export async function uriToLocalFile(dir: string, uri: string, filename: string
const filePath = path.join(dir, filename);
switch (UriType) {
case FileUriType.Local: {
const fileExt = path.extname(HandledUri);
const localFileName = path.basename(HandledUri, fileExt) + fileExt;
const tempFilePath = path.join(dir, filename + fileExt);
fs.copyFileSync(HandledUri, tempFilePath);
return { success: true, errMsg: '', fileName: localFileName, path: tempFilePath };
}
case FileUriType.Local: {
const fileExt = path.extname(HandledUri);
const localFileName = path.basename(HandledUri, fileExt) + fileExt;
const tempFilePath = path.join(dir, filename + fileExt);
fs.copyFileSync(HandledUri, tempFilePath);
return { success: true, errMsg: '', fileName: localFileName, path: tempFilePath };
}
case FileUriType.Remote: {
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {} });
fs.writeFileSync(filePath, buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath };
}
case FileUriType.Remote: {
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {} });
fs.writeFileSync(filePath, buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath };
}
case FileUriType.Base64: {
const base64 = HandledUri.replace(/^base64:\/\//, '');
const base64Buffer = Buffer.from(base64, 'base64');
fs.writeFileSync(filePath, base64Buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath };
}
case FileUriType.Base64: {
const base64 = HandledUri.replace(/^base64:\/\//, '');
const base64Buffer = Buffer.from(base64, 'base64');
fs.writeFileSync(filePath, base64Buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath };
}
default:
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' };
default:
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' };
}
}

View File

@@ -1 +1 @@
export const napCatVersion = '4.6.9';
export const napCatVersion = '4.7.13';

View File

@@ -5,6 +5,12 @@ export async function runTask<T, R>(workerScript: string, taskData: T): Promise<
try {
return await new Promise<R>((resolve, reject) => {
worker.on('message', (result: R) => {
if ((result as any)?.log) {
console.error('Worker Log--->:', (result as { log: string }).log);
}
if ((result as any)?.error) {
reject(new Error("Worker error: " + (result as { error: string }).error));
}
resolve(result);
});

View File

@@ -44,7 +44,7 @@ export class NTQQFileApi {
'https://ss.xingzhige.com/music_card/rkey', // 国内
'https://secret-service.bietiaop.com/rkeys',//国内
],
this.context.logger
this.context.logger
);
}
@@ -182,23 +182,30 @@ export class NTQQFileApi {
filePath = newFilePath;
const { fileName: _fileName, path, fileSize, md5 } = await this.core.apis.FileApi.uploadFile(filePath, ElementType.VIDEO);
context.deleteAfterSentFiles.push(path);
if (fileSize === 0) {
throw new Error('文件异常大小为0');
}
const thumbDir = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`);
fs.mkdirSync(pathLib.dirname(thumbDir), { recursive: true });
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`);
try {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
} catch {
fs.writeFileSync(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
}
if (_diyThumbPath) {
try {
await this.copyFile(_diyThumbPath, thumbPath);
} catch (e) {
this.context.logger.logError('复制自定义缩略图失败', e);
}
} else {
try {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
if (!fs.existsSync(thumbPath)) {
this.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
throw new Error('获取视频缩略图失败');
}
} catch (e) {
this.context.logger.logError('获取视频信息失败', e);
fs.writeFileSync(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
}
}
context.deleteAfterSentFiles.push(thumbPath);
const thumbSize = (await fsPromises.stat(thumbPath)).size;
@@ -224,7 +231,7 @@ export class NTQQFileApi {
},
};
}
async createValidSendPttElement(pttPath: string): Promise<SendPttElement> {
async createValidSendPttElement(_context: SendMessageContext, pttPath: string): Promise<SendPttElement> {
const { converted, path: silkPath, duration } = await encodeSilk(pttPath, this.core.NapCatTempPath, this.core.context.logger);
if (!silkPath) {
@@ -301,18 +308,18 @@ export class NTQQFileApi {
element.elementType === ElementType.FILE
) {
switch (element.elementType) {
case ElementType.PIC:
case ElementType.PIC:
element.picElement!.sourcePath = elementResults?.[elementIndex] ?? '';
break;
case ElementType.VIDEO:
break;
case ElementType.VIDEO:
element.videoElement!.filePath = elementResults?.[elementIndex] ?? '';
break;
case ElementType.PTT:
break;
case ElementType.PTT:
element.pttElement!.filePath = elementResults?.[elementIndex] ?? '';
break;
case ElementType.FILE:
break;
case ElementType.FILE:
element.fileElement!.filePath = elementResults?.[elementIndex] ?? '';
break;
break;
}
elementIndex++;
}

View File

@@ -90,7 +90,30 @@ export class NTQQUserApi {
() => true,
(profile) => profile.uid === uid,
);
const RetUser: User = {
return profile;
}
async getUserDetailInfo(uid: string, no_cache: boolean = false): Promise<User> {
let profile = await solveAsyncProblem(async (uid) => this.fetchUserDetailInfo(uid, no_cache ? UserDetailSource.KSERVER : UserDetailSource.KDB), uid);
if (profile && profile.uin !== '0' && profile.commonExt) {
return {
...profile.simpleInfo.status,
...profile.simpleInfo.vasInfo,
...profile.commonExt,
...profile.simpleInfo.baseInfo,
...profile.simpleInfo.coreInfo,
qqLevel: profile.commonExt?.qqLevel,
age: profile.simpleInfo.baseInfo.age,
pendantId: '',
nick: profile.simpleInfo.coreInfo.nick || '',
};
}
this.context.logger.logDebug('[NapCat] [Mark] getUserDetailInfo Mode1 Failed.');
profile = await this.fetchUserDetailInfo(uid, UserDetailSource.KSERVER);
if (profile && profile.uin === '0') {
profile.uin = await this.core.apis.UserApi.getUidByUinV2(uid) ?? '0';
}
return {
...profile.simpleInfo.status,
...profile.simpleInfo.vasInfo,
...profile.commonExt,
@@ -101,33 +124,6 @@ export class NTQQUserApi {
pendantId: '',
nick: profile.simpleInfo.coreInfo.nick || '',
};
return RetUser;
}
async getUserDetailInfo(uid: string): Promise<User> {
let retUser = await solveAsyncProblem(async (uid) => this.fetchUserDetailInfo(uid, UserDetailSource.KDB), uid);
if (retUser && retUser.uin !== '0') {
return retUser;
}
this.context.logger.logDebug('[NapCat] [Mark] getUserDetailInfo Mode1 Failed.');
retUser = await this.fetchUserDetailInfo(uid, UserDetailSource.KSERVER);
if (retUser && retUser.uin === '0') {
retUser.uin = await this.core.apis.UserApi.getUidByUinV2(uid) ?? '0';
}
return retUser;
}
async getUserDetailInfoV2(uid: string): Promise<User> {
const fallback = new Fallback<User>((user) => FallbackUtil.boolchecker(user, user !== undefined && user.uin !== '0'))
.add(() => this.fetchUserDetailInfo(uid, UserDetailSource.KDB))
.add(() => this.fetchUserDetailInfo(uid, UserDetailSource.KSERVER));
const retUser = await fallback.run().then(async (user) => {
if (user && user.uin === '0') {
user.uin = await this.core.apis.UserApi.getUidByUinV2(uid) ?? '0';
}
return user;
});
return retUser;
}
async modifySelfProfile(param: ModifyProfileParams) {

View File

@@ -218,5 +218,21 @@
"9.9.18-32869": {
"appid": 537271294,
"qua": "V1_WIN_NQ_9.9.18_32869_GW_B"
},
"3.2.16-33139": {
"appid": 537273909,
"qua": "V1_LNX_NQ_3.2.16_33139_GW_B"
},
"9.9.18-33139": {
"appid": 537273874,
"qua": "V1_WIN_NQ_9.9.18_33139_GW_B"
},
"9.9.18-33800": {
"appid": 537273974,
"qua": "V1_WIN_NQ_9.9.18_33800_GW_B"
},
"3.2.16-33800": {
"appid": 537274009,
"qua": "V1_LNX_NQ_3.2.16_33800_GW_B"
}
}

View File

@@ -290,5 +290,29 @@
"3.2.16-32869-arm64": {
"send": "7226630",
"recv": "7229F60"
},
"9.9.18-33139-x64": {
"send": "39F5870",
"recv": "39FA070"
},
"3.2.16-33139-x64": {
"send": "A634F60",
"recv": "A638980"
},
"3.2.16-33139-arm64": {
"send": "7262BB0",
"recv": "72664E0"
},
"9.9.18-33800-x64": {
"send": "39F5870",
"recv": "39FA070"
},
"3.2.16-33800-x64": {
"send": "A634F60",
"recv": "A638980"
},
"3.2.16-33800-arm64": {
"send": "7262BB0",
"recv": "72664E0"
}
}

View File

@@ -1,5 +1,5 @@
export class NodeIKernelLoginListener {
onLoginConnected(...args: any[]): any {
onLoginConnected(): Promise<void> | void {
}
onLoginDisConnected(...args: any[]): any {

View File

@@ -38,12 +38,12 @@ export class NativePacketClient extends IPacketClient {
return true;
}
async init(pid: number, recv: string, send: string): Promise<void> {
async init(_pid: number, recv: string, send: string): Promise<void> {
const platform = process.platform + '.' + process.arch;
const moehoo_path = path.join(dirname(fileURLToPath(import.meta.url)), './moehoo/MoeHoo.' + platform + '.node');
process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
this.MoeHooExport.exports.InitHook?.(send, recv, (type: number, uin: string, cmd: string, seq: number, hex_data: string) => {
this.MoeHooExport.exports.InitHook?.(send, recv, (type: number, _uin: string, cmd: string, seq: number, hex_data: string) => {
const trace_id = createHash('md5').update(Buffer.from(hex_data, 'hex')).digest('hex');
if (type === 0 && this.cb.get(trace_id + 'recv')) {
//此时为send 提取seq

View File

@@ -1,113 +0,0 @@
import { Data, WebSocket, ErrorEvent } from 'ws';
import { IPacketClient, RecvPacket } from '@/core/packet/client/baseClient';
import { LogStack } from '@/core/packet/context/clientContext';
import { NapCoreContext } from '@/core/packet/context/napCoreContext';
import { PacketLogger } from '@/core/packet/context/loggerContext';
export class WsPacketClient extends IPacketClient {
private websocket: WebSocket | null = null;
private reconnectAttempts: number = 0;
private readonly maxReconnectAttempts: number = 60; // 现在暂时不可配置
private readonly clientUrl: string;
private readonly clientUrlWrap: (url: string) => string = (url: string) => `ws://${url}/ws`;
private isInitialized: boolean = false;
private initPayload: { pid: number, recv: string, send: string } | null = null;
constructor(napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) {
super(napCore, logger, logStack);
this.clientUrl = this.napcore.config.packetServer
? this.clientUrlWrap(this.napcore.config.packetServer)
: this.clientUrlWrap('127.0.0.1:8083');
}
check(): boolean {
if (!this.napcore.config.packetServer) {
this.logStack.pushLogWarn('wsPacketClient 未配置服务器地址');
return false;
}
return true;
}
async init(pid: number, recv: string, send: string): Promise<void> {
this.initPayload = { pid, recv, send };
await this.connectWithRetry();
}
sendCommandImpl(cmd: string, data: string, trace_id: string): void {
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
this.websocket.send(JSON.stringify({
action: 'send',
cmd,
data,
trace_id
}));
} else {
this.logStack.pushLogWarn(`WebSocket 未连接,无法发送命令: ${cmd}`);
}
}
private async connectWithRetry(): Promise<void> {
while (this.reconnectAttempts < this.maxReconnectAttempts) {
try {
await this.connect();
return;
} catch {
this.reconnectAttempts++;
this.logStack.pushLogWarn(`${this.reconnectAttempts}/${this.maxReconnectAttempts} 次尝试重连失败!`);
await this.delay(5000);
}
}
this.logStack.pushLogError(`wsPacketClient 在 ${this.clientUrl} 达到最大重连次数 (${this.maxReconnectAttempts})`);
throw new Error(`无法连接到 WebSocket 服务器:${this.clientUrl}`);
}
private connect(): Promise<void> {
return new Promise((resolve, reject) => {
this.websocket = new WebSocket(this.clientUrl);
this.websocket.onopen = () => {
this.available = true;
this.reconnectAttempts = 0;
this.logger.info(`wsPacketClient 已连接到 ${this.clientUrl}`);
if (!this.isInitialized && this.initPayload) {
this.websocket!.send(JSON.stringify({
action: 'init',
...this.initPayload
}));
this.isInitialized = true;
}
resolve();
};
this.websocket.onclose = () => {
this.available = false;
this.logger.warn('WebSocket 连接关闭,尝试重连...');
reject(new Error('WebSocket 连接关闭'));
};
this.websocket.onmessage = (event) => this.handleMessage(event.data).catch(err => {
this.logger.error(`处理消息时出错: ${err}`);
});
this.websocket.onerror = (event: ErrorEvent) => {
this.available = false;
this.logger.error(`WebSocket 出错: ${event.message}`);
this.websocket?.close();
reject(new Error(`WebSocket 出错: ${event.message}`));
};
});
}
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
private async handleMessage(message: Data): Promise<void> {
try {
const json: RecvPacket = JSON.parse(message.toString());
const trace_id_md5 = json.trace_id_md5;
const action = json?.type ?? 'init';
const event = this.cb.get(`${trace_id_md5}${action}`);
if (event) await event(json.data);
} catch (error) {
this.logger.error(`解析ws消息时出错: ${(error as Error).message}`);
}
}
}

View File

@@ -1,6 +1,5 @@
import { IPacketClient } from '@/core/packet/client/baseClient';
import { NativePacketClient } from '@/core/packet/client/nativeClient';
import { WsPacketClient } from '@/core/packet/client/wsClient';
import { OidbPacket } from '@/core/packet/transformer/base';
import { PacketLogger } from '@/core/packet/context/loggerContext';
import { NapCoreContext } from '@/core/packet/context/napCoreContext';
@@ -10,8 +9,7 @@ type clientPriorityType = {
}
const clientPriority: clientPriorityType = {
10: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new NativePacketClient(napCore, logger, logStack),
1: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new WsPacketClient(napCore, logger, logStack),
10: (napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) => new NativePacketClient(napCore, logger, logStack)
};
export class LogStack {
@@ -88,10 +86,6 @@ export class PacketClientContext {
this.logger.info('使用指定的 NativePacketClient 作为后端');
client = new NativePacketClient(this.napCore, this.logger, this.logStack);
break;
case 'frida':
this.logger.info('[Core] [Packet] 使用指定的 FridaPacketClient 作为后端');
client = new WsPacketClient(this.napCore, this.logger, this.logStack);
break;
case 'auto':
case undefined:
client = this.judgeClient();

View File

@@ -68,8 +68,8 @@ export class PacketOperationContext {
}
}
async SetGroupSpecialTitle(groupUin: number, uid: string, tittle: string) {
const req = trans.SetSpecialTitle.build(groupUin, uid, tittle);
async SetGroupSpecialTitle(groupUin: number, uid: string, title: string) {
const req = trans.SetSpecialTitle.build(groupUin, uid, title);
await this.context.client.sendOidbPacket(req);
}

View File

@@ -8,16 +8,15 @@ class SetSpecialTitle extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase>
super();
}
build(groupCode: number, uid: string, tittle: string): OidbPacket {
const oidb_0x8FC_2_body = new NapProtoMsg(proto.OidbSvcTrpcTcp0X8FC_2_Body).encode({
targetUid: uid,
specialTitle: tittle,
expiredTime: -1,
uinName: tittle
});
build(groupCode: number, uid: string, title: string): OidbPacket {
const oidb_0x8FC_2 = new NapProtoMsg(proto.OidbSvcTrpcTcp0X8FC_2).encode({
groupUin: +groupCode,
body: oidb_0x8FC_2_body
body: {
targetUid: uid,
specialTitle: title,
expiredTime: -1,
uinName: title
}
});
return OidbBase.build(0x8FC, 2, oidb_0x8FC_2, false, false);
}

View File

@@ -4,12 +4,12 @@ import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
//设置群头衔 OidbSvcTrpcTcp.0x8fc_2
export const OidbSvcTrpcTcp0X8FC_2_Body = {
targetUid: ProtoField(1, ScalarType.STRING),
specialTitle: ProtoField(5, ScalarType.STRING),
expiredTime: ProtoField(6, ScalarType.SINT32),
uinName: ProtoField(7, ScalarType.STRING),
specialTitle: ProtoField(5, ScalarType.STRING, true),
expiredTime: ProtoField(6, ScalarType.INT32),
uinName: ProtoField(7, ScalarType.STRING, true),
targetName: ProtoField(8, ScalarType.STRING),
};
export const OidbSvcTrpcTcp0X8FC_2 = {
groupUin: ProtoField(1, ScalarType.UINT32),
body: ProtoField(3, ScalarType.BYTES),
body: ProtoField(3, () => OidbSvcTrpcTcp0X8FC_2_Body),
};

View File

@@ -16,7 +16,7 @@ export interface NodeIKernelBuddyService {
getBuddyListFromCache(reqType: BuddyListReqType): Promise<Array<
{
categoryId: number,//9999应该跳过 那是兜底数据吧
categoryId: number,//9999为特别关心
categorySortId: number,//排序方式
categroyName: string,//分类名
categroyMbCount: number,//不懂

View File

@@ -60,7 +60,10 @@ export interface QuickLoginResult {
}
export interface NodeIKernelLoginService {
getMsfStatus: () => number;
setLoginMiscData(arg0: string, value: string): unknown;
getMachineGuid(): string;
get(): NodeIKernelLoginService;

View File

@@ -207,6 +207,7 @@ interface PhotoWall {
// 简单信息
export interface SimpleInfo {
qqLevel?: QQLevel;//临时添加
uid?: string;
uin?: string;
coreInfo: CoreInfo;

View File

@@ -3,6 +3,7 @@ import Ajv, { ErrorObject, ValidateFunction } from 'ajv';
import { NapCatCore } from '@/core';
import { NapCatOneBot11Adapter, OB11Return } from '@/onebot';
import { NetworkAdapterConfig } from '../config/config';
import { TSchema } from '@sinclair/typebox';
export class OB11Response {
private static createResponse<T>(data: T, status: string, retcode: number, message: string = '', echo: unknown = null): OB11Return<T> {
@@ -33,7 +34,7 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown;
core: NapCatCore;
private validate?: ValidateFunction<unknown> = undefined;
payloadSchema?: unknown = undefined;
payloadSchema?: TSchema = undefined;
obContext: NapCatOneBot11Adapter;
constructor(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
@@ -43,7 +44,7 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
protected async check(payload: PayloadType): Promise<BaseCheckResult> {
if (this.payloadSchema) {
this.validate = new Ajv({ allowUnionTypes: true, useDefaults: true }).compile(this.payloadSchema);
this.validate = new Ajv({ allowUnionTypes: true, useDefaults: true, coerceTypes: true }).compile(this.payloadSchema);
}
if (this.validate && !this.validate(payload)) {
const errors = this.validate.errors as ErrorObject[];

View File

@@ -10,8 +10,8 @@ const SchemaData = Type.Object({
type Payload = Static<typeof SchemaData>;
export class SetSpecialTittle extends GetPacketStatusDepends<Payload, void> {
override actionName = ActionName.SetSpecialTittle;
export class SetSpecialTitle extends GetPacketStatusDepends<Payload, void> {
override actionName = ActionName.SetSpecialTitle;
override payloadSchema = SchemaData;
async _handle(payload: Payload) {

View File

@@ -7,6 +7,7 @@ import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
user_id: Type.Union([Type.Number(), Type.String()]),
no_cache: Type.Union([Type.Boolean(), Type.String()], { default: false }),
});
type Payload = Static<typeof SchemaData>;
@@ -16,10 +17,11 @@ export default class GoCQHTTPGetStrangerInfo extends OneBotAction<Payload, OB11U
override payloadSchema = SchemaData;
async _handle(payload: Payload) {
const user_id = payload.user_id.toString();
const isNocache = typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache;
const extendData = await this.core.apis.UserApi.getUserDetailInfoByUin(user_id);
let uid = (await this.core.apis.UserApi.getUidByUinV2(user_id));
if (!uid) uid = extendData.detail.uid;
const info = (await this.core.apis.UserApi.getUserDetailInfo(uid));
const info = (await this.core.apis.UserApi.getUserDetailInfo(uid, isNocache));
return {
...extendData.detail.simpleInfo.coreInfo,
...extendData.detail.commonExt ?? {},

View File

@@ -20,6 +20,7 @@ class GetGroupInfo extends OneBotAction<Payload, OB11Group> {
const data = await this.core.apis.GroupApi.fetchGroupDetail(payload.group_id.toString());
return {
...data,
group_remark: '',
group_id: +payload.group_id,
group_name: data.groupName,
member_count: data.memberNum,

View File

@@ -32,7 +32,7 @@ class GetGroupMemberInfo extends OneBotAction<Payload, OB11GroupMember> {
const [member, info] = await Promise.all([
this.core.apis.GroupApi.getGroupMemberEx(payload.group_id.toString(), uid, isNocache),
this.core.apis.UserApi.getUserDetailInfo(uid),
this.core.apis.UserApi.getUserDetailInfo(uid, isNocache),
]);
if (!member || !groupMember) throw new Error(`群(${payload.group_id})成员${payload.user_id}不存在`);

View File

@@ -81,7 +81,7 @@ import { GetGroupSystemMsg } from './system/GetSystemMsg';
import { GroupPoke } from './group/GroupPoke';
import { GetUserStatus } from './extends/GetUserStatus';
import { GetRkey } from './extends/GetRkey';
import { SetSpecialTittle } from './extends/SetSpecialTittle';
import { SetSpecialTitle } from './extends/SetSpecialTitle';
import { GetGroupShutList } from './group/GetGroupShutList';
import { GetGroupMemberList } from './group/GetGroupMemberList';
import { GetGroupFileUrl } from '@/onebot/action/file/GetGroupFileUrl';
@@ -215,7 +215,7 @@ export function createActionMap(obContext: NapCatOneBot11Adapter, core: NapCatCo
new FriendPoke(obContext, core),
new GetUserStatus(obContext, core),
new GetRkey(obContext, core),
new SetSpecialTittle(obContext, core),
new SetSpecialTitle(obContext, core),
new SetDiyOnlineStatus(obContext, core),
// new UploadForwardMsg(obContext, core),
new GetGroupShutList(obContext, core),

View File

@@ -31,7 +31,7 @@ export const ActionName = {
SetGroupCard: 'set_group_card',
SetGroupName: 'set_group_name',
SetGroupLeave: 'set_group_leave',
SetSpecialTittle: 'set_group_special_title',
SetSpecialTitle: 'set_group_special_title',
SetFriendAddRequest: 'set_friend_add_request',
SetGroupAddRequest: 'set_group_add_request',
GetLoginInfo: 'get_login_info',

View File

@@ -14,8 +14,22 @@ export default class GetFriendList extends OneBotAction<Payload, OB11User[]> {
override actionName = ActionName.GetFriendList;
override payloadSchema = SchemaData;
async _handle(payload: Payload) {
//全新逻辑
return OB11Construct.friends(await this.core.apis.FriendApi.getBuddy(typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache));
async _handle(_payload: Payload) {
const buddyMap = await this.core.apis.FriendApi.getBuddyV2SimpleInfoMap();
const isNocache = typeof _payload.no_cache === 'string' ? _payload.no_cache === 'true' : !!_payload.no_cache;
await Promise.all(
Array.from(buddyMap.values()).map(async (buddyInfo) => {
try {
const userDetail = await this.core.apis.UserApi.getUserDetailInfo(buddyInfo.coreInfo.uid, isNocache);
const data = buddyMap.get(buddyInfo.coreInfo.uid);
if (data) {
data.qqLevel = userDetail.qqLevel;
}
} catch (error) {
this.core.context.logger.logError('获取好友详细信息失败', error);
}
})
);
return OB11Construct.friends(Array.from(buddyMap.values()));
}
}
}

View File

@@ -151,14 +151,15 @@ export class OneBotGroupApi {
async parseOtherJsonEvent(msg: RawMessage, jsonStr: string, context: InstanceContext) {
const json = JSON.parse(jsonStr);
const type = json.items[json.items.length - 1]?.txt;
await this.core.apis.GroupApi.refreshGroupMemberCachePartial(msg.peerUid, msg.senderUid);
if (type === '头衔') {
const memberUin = json.items[1].param[0];
const title = json.items[3].txt;
context.logger.logDebug('收到群成员新头衔消息', json);
return new OB11GroupTitleEvent(
this.core,
parseInt(msg.peerUid),
parseInt(memberUin),
+msg.peerUid,
+memberUin,
title,
);
} else if (type === '移出') {

View File

@@ -34,7 +34,7 @@ import { EventType } from '@/onebot/event/OneBotEvent';
import { encodeCQCode } from '@/onebot/helper/cqcode';
import { uriToLocalFile } from '@/common/file';
import { RequestUtil } from '@/common/request';
import fsPromise, { constants } from 'node:fs/promises';
import fsPromise from 'node:fs/promises';
import { OB11FriendAddNoticeEvent } from '@/onebot/event/notice/OB11FriendAddNoticeEvent';
import { ForwardMsgBuilder } from '@/common/forward-msg-builder';
import { NapProtoMsg } from '@napneko/nap-proto-core';
@@ -45,6 +45,7 @@ import { OB11GroupAdminNoticeEvent } from '../event/notice/OB11GroupAdminNoticeE
import { GroupChange, GroupChangeInfo, GroupInvite, PushMsgBody } from '@/core/packet/transformer/proto';
import { OB11GroupRequestEvent } from '../event/request/OB11GroupRequest';
import { LRUCache } from '@/common/lru-cache';
import { cleanTaskQueue } from '@/common/clean-task';
type RawToOb11Converters = {
[Key in keyof MessageElement as Key extends `${string}Element` ? Key : never]: (
@@ -372,7 +373,8 @@ export class OneBotMsgApi {
try {
multiMsgs = await this.core.apis.PacketApi.pkt.operation.FetchForwardMsg(element.resId);
} catch (e) {
this.core.context.logger.logError('Protocol FetchForwardMsg fallback failed!', e);
this.core.context.logger.logError(`Protocol FetchForwardMsg fallback failed!
element = ${JSON.stringify(element)} , error=${e})`);
return null;
}
}
@@ -554,7 +556,7 @@ export class OneBotMsgApi {
},
[OB11MessageDataType.voice]: async (sendMsg, context) =>
this.core.apis.FileApi.createValidSendPttElement(
this.core.apis.FileApi.createValidSendPttElement(context,
(await this.handleOb11FileLikeMessage(sendMsg, context)).path),
[OB11MessageDataType.json]: async ({ data: { data } }) => ({
@@ -712,6 +714,56 @@ export class OneBotMsgApi {
this.obContext = obContext;
this.core = core;
}
/**
* 解析带有JSON标记的文本
* @param text 要解析的文本
* @returns 解析后的结果数组,每个元素包含类型(text或json)和内容
*/
parseTextWithJson(text: string) {
// 匹配<{...}>格式的JSON
const regex = /<(\{.*?\})>/g;
const parts: Array<{ type: 'text' | 'json', content: string | object }> = [];
let lastIndex = 0;
let match;
// 查找所有匹配项
while ((match = regex.exec(text)) !== null) {
// 添加匹配前的文本
if (match.index > lastIndex) {
parts.push({
type: 'text',
content: text.substring(lastIndex, match.index)
});
}
// 添加JSON部分
try {
const jsonContent = JSON.parse(match[1] ?? '');
parts.push({
type: 'json',
content: jsonContent
});
} catch (e) {
// 如果JSON解析失败作为普通文本处理
parts.push({
type: 'text',
content: match[0]
});
}
lastIndex = regex.lastIndex;
}
// 添加最后一部分文本
if (lastIndex < text.length) {
parts.push({
type: 'text',
content: text.substring(lastIndex)
});
}
return parts;
}
async parsePrivateMsgEvent(msg: RawMessage, grayTipElement: GrayTipElement) {
if (grayTipElement.subElementType == NTGrayTipElementSubTypeV2.GRAYTIP_ELEMENT_SUBTYPE_JSON) {
@@ -970,7 +1022,6 @@ export class OneBotMsgApi {
});
const timeout = 10000 + (totalSize / 1024 / 256 * 1000);
try {
const returnMsg = await this.core.apis.MsgApi.sendMsg(peer, sendElements, timeout);
if (!returnMsg) throw new Error('发送消息失败');
@@ -983,18 +1034,19 @@ export class OneBotMsgApi {
} catch (error) {
throw new Error((error as Error).message);
} finally {
setTimeout(async () => {
const deletePromises = deleteAfterSentFiles.map(async file => {
try {
if (await fsPromise.access(file, constants.W_OK).then(() => true).catch(() => false)) {
await fsPromise.unlink(file);
}
} catch (e) {
this.core.context.logger.logError('发送消息删除文件失败', e);
}
});
await Promise.all(deletePromises);
}, 60000);
cleanTaskQueue.addFiles(deleteAfterSentFiles, timeout);
// setTimeout(async () => {
// const deletePromises = deleteAfterSentFiles.map(async file => {
// try {
// if (await fsPromise.access(file, constants.W_OK).then(() => true).catch(() => false)) {
// await fsPromise.unlink(file);
// }
// } catch (e) {
// this.core.context.logger.logError('发送消息删除文件失败', e);
// }
// });
// await Promise.all(deletePromises);
// }, 60000);
}
}
@@ -1213,6 +1265,41 @@ export class OneBotMsgApi {
} else if (SysMessage.contentHead.type == 528 && SysMessage.contentHead.subType == 39 && SysMessage.body?.msgContent) {
return await this.obContext.apis.UserApi.parseLikeEvent(SysMessage.body?.msgContent);
}
// else if (SysMessage.contentHead.type == 732 && SysMessage.contentHead.subType == 16 && SysMessage.body?.msgContent) {
// let data_wrap = PBString(2);
// let user_wrap = PBUint64(5);
// let group_wrap = PBUint64(4);
// ProtoBuf(class extends ProtoBufBase {
// group = group_wrap;
// content = ProtoBufIn(5, { data: data_wrap, user: user_wrap });
// }).decode(SysMessage.body?.msgContent.slice(7));
// let xml_data = UnWrap(data_wrap);
// let group = UnWrap(group_wrap).toString();
// //let user = UnWrap(user_wrap).toString();
// const parsedParts = this.parseTextWithJson(xml_data);
// //解析JSON
// if (parsedParts[1] && parsedParts[3]) {
// let set_user_id: string = (parsedParts[1].content as { data: string }).data;
// let uid = await this.core.apis.UserApi.getUidByUinV2(set_user_id);
// let new_title: string = (parsedParts[3].content as { text: string }).text;
// console.log(this.core.apis.GroupApi.groupMemberCache.get(group)?.get(uid)?.memberSpecialTitle, new_title)
// if (this.core.apis.GroupApi.groupMemberCache.get(group)?.get(uid)?.memberSpecialTitle == new_title) {
// return;
// }
// await this.core.apis.GroupApi.refreshGroupMemberCachePartial(group, uid);
// //let json_data_1_url_search = new URL((parsedParts[3].content as { url: string }).url).searchParams;
// //let is_new: boolean = json_data_1_url_search.get('isnew') === '1';
// //console.log(group, set_user_id, is_new, new_title);
// return new GroupMemberTitle(
// this.core,
// +group,
// +set_user_id,
// new_title
// );
// }
// }
return undefined;
}
}

View File

@@ -20,16 +20,36 @@ export class OB11Construct {
static friends(friends: FriendV2[]): OB11User[] {
return friends.map(rawFriend => ({
...rawFriend.baseInfo,
...rawFriend.coreInfo,
birthday_year: rawFriend.baseInfo.birthday_year,
birthday_month: rawFriend.baseInfo.birthday_month,
birthday_day: rawFriend.baseInfo.birthday_day,
user_id: parseInt(rawFriend.coreInfo.uin),
age: rawFriend.baseInfo.age,
phone_num: rawFriend.baseInfo.phoneNum,
email: rawFriend.baseInfo.eMail,
category_id: rawFriend.baseInfo.categoryId,
nickname: rawFriend.coreInfo.nick ?? '',
remark: rawFriend.coreInfo.remark ?? rawFriend.coreInfo.nick,
sex: this.sex(rawFriend.baseInfo.sex),
level: 0,
level: rawFriend.qqLevel && calcQQLevel(rawFriend.qqLevel) || 0,
}));
}
static friend(friends: FriendV2): OB11User {
return {
birthday_year: friends.baseInfo.birthday_year,
birthday_month: friends.baseInfo.birthday_month,
birthday_day: friends.baseInfo.birthday_day,
user_id: parseInt(friends.coreInfo.uin),
age: friends.baseInfo.age,
phone_num: friends.baseInfo.phoneNum,
email: friends.baseInfo.eMail,
category_id: friends.baseInfo.categoryId,
nickname: friends.coreInfo.nick ?? '',
remark: friends.coreInfo.remark ?? friends.coreInfo.nick,
sex: this.sex(friends.baseInfo.sex),
level: 0,
};
}
static groupMemberRole(role: number): OB11GroupMemberRole | undefined {
return {
4: OB11GroupMemberRole.owner,
@@ -73,6 +93,7 @@ export class OB11Construct {
static group(group: Group): OB11Group {
return {
group_remark: group.remarkName,
group_id: +group.groupCode,
group_name: group.groupName,
member_count: group.memberCount,

View File

@@ -100,7 +100,7 @@ export class NapCatOneBot11Adapter {
const selfInfo = this.core.selfInfo;
const ob11Config = this.configLoader.configData;
this.core.apis.UserApi.getUserDetailInfo(selfInfo.uid)
this.core.apis.UserApi.getUserDetailInfo(selfInfo.uid, false)
.then((user) => {
selfInfo.nick = user.nick;
this.context.logger.setLogSelfInfo(selfInfo);

View File

@@ -37,7 +37,13 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
}, this.config.heartInterval);
}
this.isEnable = true;
await this.tryConnect();
try {
await this.tryConnect();
} catch (error) {
this.logger.logError('[OneBot] [WebSocket Client] TryConnect Error , info -> ', error);
}
}
close() {

View File

@@ -1,4 +1,10 @@
export interface OB11User {
birthday_year?: number; // 生日
birthday_month?: number; // 生日
birthday_day?: number; // 生日
phone_num?: string; // 手机号
email?: string; // 邮箱
category_id?: number; // 分组ID
user_id: number; // 用户ID
nickname: string; // 昵称
remark?: string; // 备注
@@ -57,6 +63,7 @@ export interface OB11GroupMember {
}
export interface OB11Group {
group_remark: string; // 群备注
group_id: number; // 群ID
group_name: string; // 群名称
member_count?: number; // 成员数量

View File

@@ -30,6 +30,8 @@ import { InitWebUi } from '@/webui';
import { WebUiDataRuntime } from '@/webui/src/helper/Data';
import { napCatVersion } from '@/common/version';
import { NodeIO3MiscListener } from '@/core/listeners/NodeIO3MiscListener';
import { sleep } from '@/common/helper';
// NapCat Shell App ES 入口文件
async function handleUncaughtExceptions(logger: LogWrapper) {
process.on('uncaughtException', (err) => {
@@ -113,120 +115,126 @@ async function handleLogin(
quickLoginUin: string | undefined,
historyLoginList: LoginListItem[]
): Promise<SelfInfo> {
return new Promise<SelfInfo>((resolve) => {
const loginListener = new NodeIKernelLoginListener();
let isLogined = false;
let context = { isLogined: false };
let inner_resolve: (value: SelfInfo) => void;
let selfInfo: Promise<SelfInfo> = new Promise((resolve) => {
inner_resolve = resolve;
});
// 连接服务
loginListener.onUserLoggedIn = (userid: string) => {
logger.logError(`当前账号(${userid})已登录,无法重复登录`);
};
loginListener.onQRCodeLoginSucceed = async (loginResult) => {
isLogined = true;
resolve({
uid: loginResult.uid,
uin: loginResult.uin,
nick: '',
online: true,
});
};
loginListener.onQRCodeGetPicture = ({ pngBase64QrcodeData, qrcodeUrl }) => {
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
const realBase64 = pngBase64QrcodeData.replace(/^data:image\/\w+;base64,/, '');
const buffer = Buffer.from(realBase64, 'base64');
logger.logWarn('请扫描下面的二维码然后在手Q上授权登录');
const qrcodePath = path.join(pathWrapper.cachePath, 'qrcode.png');
qrcode.generate(qrcodeUrl, { small: true }, (res) => {
logger.logWarn([
'\n',
res,
'二维码解码URL: ' + qrcodeUrl,
'如果控制台二维码无法扫码可以复制解码url到二维码生成网站生成二维码再扫码也可以打开下方的二维码路径图片进行扫码。',
].join('\n'));
fs.writeFile(qrcodePath, buffer, {}, () => {
logger.logWarn('二维码已保存到', qrcodePath);
});
});
};
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number) => {
if (!isLogined) {
logger.logError('[Core] [Login] Login Error,ErrType: ', errType, ' ErrCode:', errCode);
if (errType == 1 && errCode == 3) {
// 二维码过期刷新
}
loginService.getQRCodePicture();
}
};
loginListener.onLoginFailed = (...args) => {
logger.logError('[Core] [Login] Login Error , ErrInfo: ', JSON.stringify(args));
};
loginService.addKernelLoginListener(proxiedListenerOf(loginListener, logger));
const isConnect = loginService.connect();
if (!isConnect) {
logger.logError('核心登录服务连接失败!');
return;
}
logger.log('核心登录服务连接成功!');
loginService.getLoginList().then((res) => {
// 遍历 res.LocalLoginInfoList[x].isQuickLogin是否可以 res.LocalLoginInfoList[x].uin 转为string 加入string[] 最后遍历完成调用WebUiDataRuntime.setQQQuickLoginList
const list = res.LocalLoginInfoList.filter((item) => item.isQuickLogin);
WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
WebUiDataRuntime.setQQNewLoginList(list);
const loginListener = new NodeIKernelLoginListener();
loginListener.onUserLoggedIn = (userid: string) => {
logger.logError(`当前账号(${userid})已登录,无法重复登录`);
};
loginListener.onQRCodeLoginSucceed = async (loginResult) => {
context.isLogined = true;
inner_resolve({
uid: loginResult.uid,
uin: loginResult.uin,
nick: '',
online: true,
});
WebUiDataRuntime.setQuickLoginCall(async (uin: string) => {
return await new Promise((resolve) => {
if (uin) {
logger.log('正在快速登录 ', uin);
loginService.quickLoginWithUin(uin).then(res => {
if (res.loginErrorInfo.errMsg) {
resolve({ result: false, message: res.loginErrorInfo.errMsg });
}
resolve({ result: true, message: '' });
}).catch((e) => {
logger.logError(e);
resolve({ result: false, message: '快速登录发生错误' });
});
} else {
resolve({ result: false, message: '快速登录失败' });
}
};
loginListener.onLoginConnected = () => {
waitForNetworkConnection(loginService, logger).then(() => {
handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList).then().catch(e => logger.logError(e));
loginListener.onLoginConnected = () => { };
});
}
loginListener.onQRCodeGetPicture = ({ pngBase64QrcodeData, qrcodeUrl }) => {
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
const realBase64 = pngBase64QrcodeData.replace(/^data:image\/\w+;base64,/, '');
const buffer = Buffer.from(realBase64, 'base64');
logger.logWarn('请扫描下面的二维码然后在手Q上授权登录');
const qrcodePath = path.join(pathWrapper.cachePath, 'qrcode.png');
qrcode.generate(qrcodeUrl, { small: true }, (res) => {
logger.logWarn([
'\n',
res,
'二维码解码URL: ' + qrcodeUrl,
'如果控制台二维码无法扫码可以复制解码url到二维码生成网站生成二维码再扫码也可以打开下方的二维码路径图片进行扫码。',
].join('\n'));
fs.writeFile(qrcodePath, buffer, {}, () => {
logger.logWarn('二维码已保存到', qrcodePath);
});
});
};
if (quickLoginUin) {
if (historyLoginList.some(u => u.uin === quickLoginUin)) {
logger.log('正在快速登录 ', quickLoginUin);
setTimeout(() => {
loginService.quickLoginWithUin(quickLoginUin)
.then(result => {
if (result.loginErrorInfo.errMsg) {
logger.logError('快速登录错误:', result.loginErrorInfo.errMsg);
if (!isLogined) loginService.getQRCodePicture();
}
})
.catch();
}, 1000);
} else {
logger.logError('快速登录失败,未找到该 QQ 历史登录记录,将使用二维码登录方式');
if (!isLogined) loginService.getQRCodePicture();
}
} else {
logger.log('没有 -q 指令指定快速登录,将使用二维码登录方式');
if (historyLoginList.length > 0) {
logger.log(`可用于快速登录的 QQ\n${historyLoginList
.map((u, index) => `${index + 1}. ${u.uin} ${u.nickName}`)
.join('\n')
}`);
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number) => {
if (!context.isLogined) {
logger.logError('[Core] [Login] Login Error,ErrType: ', errType, ' ErrCode:', errCode);
if (errType == 1 && errCode == 3) {
// 二维码过期刷新
}
loginService.getQRCodePicture();
}
};
loginListener.onLoginFailed = (...args) => {
logger.logError('[Core] [Login] Login Error , ErrInfo: ', JSON.stringify(args));
};
loginService.addKernelLoginListener(proxiedListenerOf(loginListener, logger));
loginService.connect();
return await selfInfo;
}
async function handleLoginInner(context: { isLogined: boolean }, logger: LogWrapper, loginService: NodeIKernelLoginService, quickLoginUin: string | undefined, historyLoginList: LoginListItem[]) {
WebUiDataRuntime.setQuickLoginCall(async (uin: string) => {
return await new Promise((resolve) => {
if (uin) {
logger.log('正在快速登录 ', uin);
loginService.quickLoginWithUin(uin).then(res => {
if (res.loginErrorInfo.errMsg) {
resolve({ result: false, message: res.loginErrorInfo.errMsg });
}
resolve({ result: true, message: '' });
}).catch((e) => {
logger.logError(e);
resolve({ result: false, message: '快速登录发生错误' });
});
} else {
resolve({ result: false, message: '快速登录失败' });
}
});
});
if (quickLoginUin) {
if (historyLoginList.some(u => u.uin === quickLoginUin)) {
logger.log('正在快速登录 ', quickLoginUin);
loginService.quickLoginWithUin(quickLoginUin)
.then(result => {
if (result.loginErrorInfo.errMsg) {
logger.logError('快速登录错误:', result.loginErrorInfo.errMsg);
if (!context.isLogined) loginService.getQRCodePicture();
}
})
.catch();
} else {
logger.logError('快速登录失败,未找到该 QQ 历史登录记录,将使用二维码登录方式');
if (!context.isLogined) loginService.getQRCodePicture();
}
} else {
logger.log('没有 -q 指令指定快速登录,将使用二维码登录方式');
if (historyLoginList.length > 0) {
logger.log(`可用于快速登录的 QQ\n${historyLoginList
.map((u, index) => `${index + 1}. ${u.uin} ${u.nickName}`)
.join('\n')
}`);
}
loginService.getQRCodePicture();
try {
await WebUiDataRuntime.runWebUiConfigQuickFunction();
} catch (error) {
logger.logError('WebUi 快速登录失败 执行失败', error);
}
}
loginService.getLoginList().then((res) => {
// 遍历 res.LocalLoginInfoList[x].isQuickLogin是否可以 res.LocalLoginInfoList[x].uin 转为string 加入string[] 最后遍历完成调用WebUiDataRuntime.setQQQuickLoginList
const list = res.LocalLoginInfoList.filter((item) => item.isQuickLogin);
WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
WebUiDataRuntime.setQQNewLoginList(list);
});
}
@@ -284,6 +292,20 @@ async function handleProxy(session: NodeIQQNTWrapperSession, logger: LogWrapper)
});
}
}
async function waitForNetworkConnection(loginService: NodeIKernelLoginService, logger: LogWrapper) {
let network_ok = false;
let tryCount = 0;
while (!network_ok) {
network_ok = loginService.getMsfStatus() !== 3;// win 11 0连接 1未连接
logger.log('等待网络连接...');
await sleep(500);
tryCount++;
}
logger.log('网络已连接');
return network_ok;
}
export async function NCoreInitShell() {
console.log('NapCat Shell App Loading...');
const pathWrapper = new NapCatPathWrapper();

View File

@@ -1,2 +1,4 @@
import { convertAudio } from '@/common/audio-pure';
import { NCoreInitShell } from './base';
await convertAudio("F:\\BVideo\\陈致逸,HOYO-MiX - 蒲苇如丝 Lovers' Oath.mp3", "F:\\BVideo\\陈致逸,HOYO-MiX - 蒲苇如丝 Lovers' Oath.wav", "wav");
NCoreInitShell();

View File

@@ -50,20 +50,21 @@ export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapp
logger.log('[NapCat] [WebUi] Current WebUi is not run.');
return;
}
setTimeout(async () => {
let autoLoginAccount = process.env['NAPCAT_QUICK_ACCOUNT'] || WebUiConfig.getAutoLoginAccount();
if (autoLoginAccount) {
try {
const { result, message } = await WebUiDataRuntime.requestQuickLogin(autoLoginAccount);
if (!result) {
throw new Error(message);
WebUiDataRuntime.setWebUiConfigQuickFunction(
async () => {
let autoLoginAccount = process.env['NAPCAT_QUICK_ACCOUNT'] || WebUiConfig.getAutoLoginAccount();
if (autoLoginAccount) {
try {
const { result, message } = await WebUiDataRuntime.requestQuickLogin(autoLoginAccount);
if (!result) {
throw new Error(message);
}
console.log(`[NapCat] [WebUi] Auto login account: ${autoLoginAccount}`);
} catch (error) {
console.log(`[NapCat] [WebUi] Auto login account failed.` + error);
}
console.log(`[NapCat] [WebUi] Auto login account: ${autoLoginAccount}`);
} catch (error) {
console.log(`[NapCat] [WebUi] Auto login account failed.` + error);
}
}
}, 30000);
});
// ------------注册中间件------------
// 使用express的json中间件
app.use(express.json());

View File

@@ -25,6 +25,9 @@ const LoginRuntime: LoginRuntimeType = {
NewQQLoginList: [],
},
packageJson: packageJson,
WebUiConfigQuickFunction: async () => {
return;
}
};
export const WebUiDataRuntime = {
@@ -118,4 +121,11 @@ export const WebUiDataRuntime = {
getQQVersion() {
return LoginRuntime.QQVersion;
},
setWebUiConfigQuickFunction(func: LoginRuntimeType['WebUiConfigQuickFunction']): void {
LoginRuntime.WebUiConfigQuickFunction = func;
},
runWebUiConfigQuickFunction: async function () {
await LoginRuntime.WebUiConfigQuickFunction();
}
};

View File

@@ -9,6 +9,7 @@ interface LoginRuntimeType {
QQLoginUin: string;
QQLoginInfo: SelfInfo;
QQVersion: string;
WebUiConfigQuickFunction: () => Promise<void>;
NapCatHelper: {
onQuickLoginRequested: (uin: string) => Promise<{ result: boolean; message: string }>;
onOB11ConfigChanged: (ob11: OneBotConfig) => Promise<void>;

View File

@@ -8,7 +8,10 @@ const external = [
'silk-wasm',
'ws',
'express',
'@ffmpeg.wasm/core-mt'
'@ffmpeg.wasm/core-mt',
'@breezystack/lamejs',
'audio-decode',
'wavefile'
];
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();