Compare commits

..

28 Commits

Author SHA1 Message Date
手瓜一十雪
dd00d4c8a5 fix: 小问题 2025-04-12 11:59:29 +08:00
手瓜一十雪
4d292a75fa fix 2025-04-12 11:36:46 +08:00
pk5ls20
50b6733f57 Merge pull request #938 from Fahaxikiii/patch-2
Update README.md
2025-04-12 00:11:23 +08:00
万里
19479b4b3c Update README.md
换成美国vps
2025-04-12 00:09:19 +08:00
pk5ls20
540f58d8ec Merge pull request #937 from Fahaxikiii/patch-1 2025-04-11 23:18:46 +08:00
万里
749f1dfcf9 Update README.md
服务器到期了呜呜呜
2025-04-11 22:03:28 +08:00
Mlikiowa
176691bb96 release: v4.7.17 2025-04-11 07:12:53 +00:00
手瓜一十雪
b9ec8ac9b1 feat: LL Framework适配 2025-04-11 15:12:32 +08:00
手瓜一十雪
28d973b9cb Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2025-04-11 14:40:31 +08:00
手瓜一十雪
a6be54937c feat: 删掉不必要的启动脚本 2025-04-11 14:40:22 +08:00
Mlikiowa
0664b9af84 release: v4.7.16 2025-04-11 06:21:19 +00:00
手瓜一十雪
407d8d1fd2 feat: 34231 2025-04-11 14:20:27 +08:00
手瓜一十雪
108897f6ad feat: shell 能力 launcher-user-34231 2025-04-11 14:18:12 +08:00
手瓜一十雪
3d2decb0ec feat: 34231 2025-04-11 12:47:25 +08:00
Mlikiowa
386b884f1b release: v4.7.15 2025-04-10 11:00:12 +00:00
手瓜一十雪
ace4da2297 fix: rkey server部署 2025-04-10 18:59:49 +08:00
Mlikiowa
a8fb48fb50 release: v4.7.14 2025-04-10 10:55:24 +00:00
手瓜一十雪
61f065c0c6 feat: rkey标准化&rkey server增强&简化rkey端部署 2025-04-10 18:54:18 +08:00
手瓜一十雪
d6cf6d120a feat: group_all_shut 2025-04-10 09:00:00 +08:00
手瓜一十雪
c20c19d8e0 feat: 更新类型 fetchUserDetailInfo 2025-04-08 10:12:18 +08:00
手瓜一十雪
bd8bbf76ab feat: moveGroupFile 2025-04-08 09:42:28 +08:00
手瓜一十雪
faccff1834 Merge pull request #927 from NapNeko/dependabot/npm_and_yarn/vite-plugin-cp-6.0.0
chore(deps-dev): bump vite-plugin-cp from 4.0.8 to 6.0.0
2025-04-08 09:19:58 +08:00
手瓜一十雪
99d3c5a117 Merge pull request #930 from clansty/feat/gfs
增加更多群文件相关功能
2025-04-08 09:19:41 +08:00
Clansty
31eb09edef feat: 重命名群文件 2025-04-08 05:14:53 +08:00
Clansty
4180c2d754 feat: 群文件转存永久 2025-04-08 04:40:34 +08:00
Clansty
68f5deedff feat: 移动群文件 2025-04-08 02:48:48 +08:00
dependabot[bot]
9f72196414 chore(deps-dev): bump vite-plugin-cp from 4.0.8 to 6.0.0
Bumps [vite-plugin-cp](https://github.com/fengxinming/vite-plugins/tree/HEAD/packages/vite-plugin-cp) from 4.0.8 to 6.0.0.
- [Commits](https://github.com/fengxinming/vite-plugins/commits/HEAD/packages/vite-plugin-cp)

---
updated-dependencies:
- dependency-name: vite-plugin-cp
  dependency-version: 6.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-07 09:33:04 +00:00
手瓜一十雪
b32efa9131 fix: 更新逻辑 2025-04-05 11:45:21 +08:00
33 changed files with 399 additions and 1008 deletions

View File

@@ -37,7 +37,7 @@ _Modern protocol-side framework implemented based on NTQQ._
| Docs | [![Github.IO](https://img.shields.io/badge/docs%20on-Github.IO-orange)](https://napneko.github.io/) | [![Cloudflare.Worker](https://img.shields.io/badge/docs%20on-Cloudflare.Worker-black)](https://doc.napneko.icu/) | [![Cloudflare.HKServer](https://img.shields.io/badge/docs%20on-Cloudflare.HKServer-informational)](https://napcat.napneko.icu/) |
|:-:|:-:|:-:|:-:|
| Docs | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://docs.napcat.cyou/) | [![NapCat.Wiki](https://img.shields.io/badge/docs%20on-NapCat.Wiki-red)](https://www.napcat.wiki) |
| Docs | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.cyou/) | [![NapCat.Wiki](https://img.shields.io/badge/docs%20on-NapCat.Wiki-red)](https://www.napcat.wiki) |
|:-:|:-:|:-:|:-:|
| Contact | [![QQ Group#1](https://img.shields.io/badge/QQ%20Group%231-Join-blue)](https://qm.qq.com/q/I6LU87a0Yq) | [![QQ Group#2](https://img.shields.io/badge/QQ%20Group%232-Join-blue)](https://qm.qq.com/q/HaRcfrHpUk) | [![Telegram](https://img.shields.io/badge/Telegram-MelodicMoonlight-blue)](https://t.me/MelodicMoonlight) |

Binary file not shown.

Binary file not shown.

View File

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

View File

@@ -2,7 +2,7 @@
"name": "napcat",
"private": true,
"type": "module",
"version": "4.7.13",
"version": "4.7.17",
"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,7 +32,6 @@
"@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",
@@ -43,7 +42,6 @@
"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",
@@ -56,22 +54,19 @@
"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-plugin-cp": "^6.0.0",
"vite-tsconfig-paths": "^5.1.0",
"winston": "^3.17.0"
"napcat.protobuf": "^1.1.4",
"winston": "^3.17.0",
"compressing": "^1.10.1"
},
"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

@@ -1,145 +0,0 @@
// 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;
}
}

View File

@@ -1,814 +0,0 @@
/**
* 现代音频格式转换库 - 使用纯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);
};
}

View File

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

View File

@@ -41,8 +41,8 @@ export class NTQQFileApi {
this.context = context;
this.core = core;
this.rkeyManager = new RkeyManager([
'https://ss.xingzhige.com/music_card/rkey', // 国内
'https://secret-service.bietiaop.com/rkeys',//国内
'https://secret-service.bietiaop.com/rkeys',
'http://ss.xingzhige.com/music_card/rkey',
],
this.context.logger
);

View File

@@ -218,6 +218,10 @@ export class NTQQGroupApi {
return this.context.session.getRichMediaService().deleteGroupFolder(groupCode, folderId);
}
async transGroupFile(groupCode: string, fileId: string) {
return this.context.session.getRichMediaService().transGroupFile(groupCode, fileId);
}
async addGroupEssence(groupCode: string, msgId: string) {
const MsgData = await this.context.session.getMsgService().getMsgsIncludeSelf({
chatType: 2,

View File

@@ -12,7 +12,7 @@ export class NTQQMsgApi {
this.context = context;
this.core = core;
}
async clickInlineKeyboardButton(...params: Parameters<NodeIKernelMsgService['clickInlineKeyboardButton']>) {
return this.context.session.getMsgService().clickInlineKeyboardButton(...params);
}

View File

@@ -234,5 +234,13 @@
"3.2.16-33800": {
"appid": 537274009,
"qua": "V1_LNX_NQ_3.2.16_33800_GW_B"
},
"9.9.19-34231": {
"appid": 537279209,
"qua": "V1_WIN_NQ_9.9.19_34231_GW_B"
},
"3.2.17-34231": {
"appid": 537279245,
"qua": "V1_LNX_NQ_3.2.17_34231_GW_B"
}
}

View File

@@ -314,5 +314,17 @@
"3.2.16-33800-arm64": {
"send": "7262BB0",
"recv": "72664E0"
},
"9.9.19-34231-x64": {
"send": "3BD73D0",
"recv": "3BDBBD0"
},
"3.2.17-34231-x64": {
"send": "AD787E0",
"recv": "AD7C200"
},
"3.2.17-34231-arm64": {
"send": "770CDC0",
"recv": "77106F0"
}
}

View File

@@ -6,6 +6,17 @@ interface ServerRkeyData {
private_rkey: string;
expired_time: number;
}
interface OneBotApiRet {
status: string,
retcode: number,
data: ServerRkeyData,
message: string,
wording: string,
}
interface UrlFailureInfo {
count: number;
lastTimestamp: number;
}
export class RkeyManager {
serverUrl: string[] = [];
@@ -15,9 +26,8 @@ export class RkeyManager {
private_rkey: '',
expired_time: 0,
};
private failureCount: number = 0;
private lastFailureTimestamp: number = 0;
private readonly FAILURE_LIMIT: number = 8;
private urlFailures: Map<string, UrlFailureInfo> = new Map();
private readonly FAILURE_LIMIT: number = 4;
private readonly ONE_DAY: number = 24 * 60 * 60 * 1000;
constructor(serverUrl: string[], logger: LogWrapper) {
@@ -26,50 +36,92 @@ export class RkeyManager {
}
async getRkey() {
const now = new Date().getTime();
if (now - this.lastFailureTimestamp > this.ONE_DAY) {
this.failureCount = 0; // 重置失败计数器
}
if (this.failureCount >= this.FAILURE_LIMIT) {
this.logger.logError('[Rkey] 服务存在异常, 图片使用FallBack机制');
throw new Error('获取rkey失败次数过多请稍后再试');
const availableUrls = this.getAvailableUrls();
if (availableUrls.length === 0) {
this.logger.logError('[Rkey] 所有服务均已禁用, 图片使用FallBack机制');
throw new Error('获取rkey失败所有服务URL均已被禁用');
}
if (this.isExpired()) {
try {
await this.refreshRkey();
} catch (e) {
throw new Error(`${e}`);//外抛
throw new Error(`${e}`);
}
}
return this.rkeyData;
}
private getAvailableUrls(): string[] {
return this.serverUrl.filter(url => !this.isUrlDisabled(url));
}
private isUrlDisabled(url: string): boolean {
const failureInfo = this.urlFailures.get(url);
if (!failureInfo) return false;
const now = new Date().getTime();
// 如果已经过了一天,重置失败计数
if (now - failureInfo.lastTimestamp > this.ONE_DAY) {
failureInfo.count = 0;
this.urlFailures.set(url, failureInfo);
return false;
}
return failureInfo.count >= this.FAILURE_LIMIT;
}
private updateUrlFailure(url: string) {
const now = new Date().getTime();
const failureInfo = this.urlFailures.get(url) || { count: 0, lastTimestamp: 0 };
// 如果已经过了一天,重置失败计数
if (now - failureInfo.lastTimestamp > this.ONE_DAY) {
failureInfo.count = 1;
} else {
failureInfo.count++;
}
failureInfo.lastTimestamp = now;
this.urlFailures.set(url, failureInfo);
if (failureInfo.count >= this.FAILURE_LIMIT) {
this.logger.logError(`[Rkey] URL ${url} 已被禁用,失败次数达到 ${this.FAILURE_LIMIT}`);
}
}
isExpired(): boolean {
const now = new Date().getTime() / 1000;
return now > this.rkeyData.expired_time;
}
async refreshRkey() {
//刷新rkey
for (const url of this.serverUrl) {
const availableUrls = this.getAvailableUrls();
if (availableUrls.length === 0) {
this.logger.logError('[Rkey] 所有服务均已禁用');
throw new Error('获取rkey失败所有服务URL均已被禁用');
}
for (const url of availableUrls) {
try {
const temp = await RequestUtil.HttpGetJson<ServerRkeyData>(url, 'GET');
let temp = await RequestUtil.HttpGetJson<ServerRkeyData>(url, 'GET');
if ('retcode' in temp) {
// 支持Onebot Ret风格
temp = (temp as unknown as OneBotApiRet).data;
}
this.rkeyData = {
group_rkey: temp.group_rkey.slice(6),
private_rkey: temp.private_rkey.slice(6),
expired_time: temp.expired_time
};
this.failureCount = 0;
return;
} catch (e) {
this.logger.logError(`[Rkey] 异常服务 ${url} 异常 / `, e);
this.failureCount++;
this.lastFailureTimestamp = new Date().getTime();
//是否为最后一个url
if (url === this.serverUrl[this.serverUrl.length - 1]) {
throw new Error(`获取rkey失败: ${e}`);//外抛
this.updateUrlFailure(url);
if (url === availableUrls[availableUrls.length - 1]) {
throw new Error(`获取rkey失败: ${e}`);
}
}
}

View File

@@ -154,6 +154,20 @@ export class PacketOperationContext {
return res.result.resId;
}
async MoveGroupFile(groupUin: number, fileUUID: string, currentParentDirectory: string, targetParentDirectory: string) {
const req = trans.MoveGroupFile.build(groupUin, fileUUID, currentParentDirectory, targetParentDirectory);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.MoveGroupFile.parse(resp);
return res.move.retCode;
}
async RenameGroupFile(groupUin: number, fileUUID: string, currentParentDirectory: string, newName: string) {
const req = trans.RenameGroupFile.build(groupUin, fileUUID, currentParentDirectory, newName);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.RenameGroupFile.parse(resp);
return res.rename.retCode;
}
async GetGroupFileUrl(groupUin: number, fileUUID: string) {
const req = trans.DownloadGroupFile.build(groupUin, fileUUID);
const resp = await this.context.client.sendOidbPacket(req, true);

View File

@@ -0,0 +1,35 @@
import * as proto from '@/core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/core/packet/transformer/base';
import OidbBase from '@/core/packet/transformer/oidb/oidbBase';
class MoveGroupFile extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0x6D6Response> {
constructor() {
super();
}
build(groupUin: number, fileUUID: string, currentParentDirectory: string, targetParentDirectory: string): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6).encode({
move: {
groupUin: groupUin,
appId: 5,
busId: 102,
fileId: fileUUID,
parentDirectory: currentParentDirectory,
targetDirectory: targetParentDirectory,
}
});
return OidbBase.build(0x6D6, 5, body, true, false);
}
parse(data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
const res = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
if (res.move.retCode !== 0) {
throw new Error(`sendGroupFileMoveReq error: ${res.move.clientWording} (code=${res.move.retCode})`);
}
return res;
}
}
export default new MoveGroupFile();

View File

@@ -0,0 +1,34 @@
import * as proto from '@/core/packet/transformer/proto';
import { NapProtoMsg } from '@napneko/nap-proto-core';
import { OidbPacket, PacketTransformer } from '@/core/packet/transformer/base';
import OidbBase from '@/core/packet/transformer/oidb/oidbBase';
class RenameGroupFile extends PacketTransformer<typeof proto.OidbSvcTrpcTcp0x6D6Response> {
constructor() {
super();
}
build(groupUin: number, fileUUID: string, currentParentDirectory: string, newName: string): OidbPacket {
const body = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6).encode({
rename: {
groupUin: groupUin,
busId: 102,
fileId: fileUUID,
parentFolder: currentParentDirectory,
newFileName: newName,
}
});
return OidbBase.build(0x6D6, 4, body, true, false);
}
parse(data: Buffer) {
const oidbBody = OidbBase.parse(data).body;
const res = new NapProtoMsg(proto.OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
if (res.rename.retCode !== 0) {
throw new Error(`sendGroupFileRenameReq error: ${res.rename.clientWording} (code=${res.rename.retCode})`);
}
return res;
}
}
export default new RenameGroupFile();

View File

@@ -6,3 +6,5 @@ export { default as GetStrangerInfo } from './GetStrangerInfo';
export { default as SendPoke } from './SendPoke';
export { default as SetSpecialTitle } from './SetSpecialTitle';
export { default as ImageOCR } from './ImageOCR';
export { default as MoveGroupFile } from './MoveGroupFile';
export { default as RenameGroupFile } from './RenameGroupFile';

View File

@@ -1,5 +1,5 @@
import { AnyCnameRecord } from 'node:dns';
import { BizKey, ModifyProfileParams, NodeIKernelProfileListener, ProfileBizType, SimpleInfo, UserDetailInfoByUin, UserDetailSource } from '@/core';
import { BizKey, ModifyProfileParams, NodeIKernelProfileListener, ProfileBizType, SimpleInfo, UserDetailInfoByUin, UserDetailInfoListenerArg, UserDetailSource } from '@/core';
import { GeneralCallResult } from '@/core/services/common';
export interface NodeIKernelProfileService {
@@ -15,7 +15,13 @@ export interface NodeIKernelProfileService {
getCoreAndBaseInfo(callfrom: string, uids: string[]): Promise<Map<string, SimpleInfo>>;
fetchUserDetailInfo(trace: string, uids: string[], source: UserDetailSource, bizType: ProfileBizType[]): Promise<GeneralCallResult>;
fetchUserDetailInfo(trace: string, uids: string[], source: UserDetailSource, bizType: ProfileBizType[]): Promise<GeneralCallResult &
{
source: UserDetailSource,
// uid -> detail
detail: Map<string, UserDetailInfoListenerArg>,
}
>;
addKernelProfileListener(listener: NodeIKernelProfileListener): number;

View File

@@ -198,9 +198,29 @@ export interface NodeIKernelRichMediaService {
renameGroupFile(arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown, arg5: unknown): unknown;
moveGroupFile(arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown, arg5: unknown): unknown;
moveGroupFile(groupCode: string, busId: Array<number>, fileList: Array<string>, currentParentDirectory: string, targetParentDirectory: string): Promise<GeneralCallResult & {
moveGroupFileResult: {
result: {
retCode: number,
retMsg: symbol,
clientWording: string
},
successFileIdList: Array<string>,
failFileIdList: Array<string>
}
}>;
transGroupFile(arg1: unknown, arg2: unknown): unknown;
transGroupFile(groupCode: string, fileId: string): Promise<GeneralCallResult & {
transGroupFileResult: {
result: {
retCode: number
retMsg: string
clientWording: string
}
saveBusId: number
saveFilePath: string
}
}>;
searchGroupFile(
keywords: Array<string>,

View File

@@ -0,0 +1,33 @@
import { ActionName } from '@/onebot/action/router';
import { FileNapCatOneBotUUID } from '@/common/file-uuid';
import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
file_id: Type.String(),
current_parent_directory: Type.String(),
target_parent_directory: Type.String(),
});
type Payload = Static<typeof SchemaData>;
interface MoveGroupFileResponse {
ok: boolean;
}
export class MoveGroupFile extends GetPacketStatusDepends<Payload, MoveGroupFileResponse> {
override actionName = ActionName.MoveGroupFile;
override payloadSchema = SchemaData;
async _handle(payload: Payload) {
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (contextMsgFile?.fileUUID) {
await this.core.apis.PacketApi.pkt.operation.MoveGroupFile(+payload.group_id, contextMsgFile.fileUUID, payload.current_parent_directory, payload.target_parent_directory);
return {
ok: true,
};
}
throw new Error('real fileUUID not found!');
}
}

View File

@@ -0,0 +1,33 @@
import { ActionName } from '@/onebot/action/router';
import { FileNapCatOneBotUUID } from '@/common/file-uuid';
import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
file_id: Type.String(),
current_parent_directory: Type.String(),
new_name: Type.String(),
});
type Payload = Static<typeof SchemaData>;
interface RenameGroupFileResponse {
ok: boolean;
}
export class RenameGroupFile extends GetPacketStatusDepends<Payload, RenameGroupFileResponse> {
override actionName = ActionName.RenameGroupFile;
override payloadSchema = SchemaData;
async _handle(payload: Payload) {
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (contextMsgFile?.fileUUID) {
await this.core.apis.PacketApi.pkt.operation.RenameGroupFile(+payload.group_id, contextMsgFile.fileUUID, payload.current_parent_directory, payload.new_name);
return {
ok: true,
};
}
throw new Error('real fileUUID not found!');
}
}

View File

@@ -0,0 +1,34 @@
import { ActionName } from '@/onebot/action/router';
import { FileNapCatOneBotUUID } from '@/common/file-uuid';
import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
file_id: Type.String(),
});
type Payload = Static<typeof SchemaData>;
interface TransGroupFileResponse {
ok: boolean;
}
export class TransGroupFile extends GetPacketStatusDepends<Payload, TransGroupFileResponse> {
override actionName = ActionName.TransGroupFile;
override payloadSchema = SchemaData;
async _handle(payload: Payload) {
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (contextMsgFile?.fileUUID) {
const result = await this.core.apis.GroupApi.transGroupFile(payload.group_id.toString(), contextMsgFile.fileUUID);
if (result.transGroupFileResult.result.retCode === 0) {
return {
ok: true
};
}
throw new Error(result.transGroupFileResult.result.retMsg);
}
throw new Error('real fileUUID not found!');
}
}

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_all_shut: data.shutUpAllTimestamp > 0 ? -1 : 0,
group_remark: '',
group_id: +payload.group_id,
group_name: data.groupName,

View File

@@ -109,10 +109,17 @@ import { ClickInlineKeyboardButton } from './extends/ClickInlineKeyboardButton';
import { GetPrivateFileUrl } from './file/GetPrivateFileUrl';
import { GetUnidirectionalFriendList } from './extends/GetUnidirectionalFriendList';
import SetGroupRemark from './extends/SetGroupRemark';
import { MoveGroupFile } from './extends/MoveGroupFile';
import { TransGroupFile } from './extends/TransGroupFile';
import { RenameGroupFile } from './extends/RenameGroupFile';
import { GetRkeyServer } from './packet/GetRkeyServer';
import { GetRkeyEx } from './packet/GetRkeyEx';
export function createActionMap(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
const actionHandlers = [
new GetRkeyEx(obContext, core),
new GetRkeyServer(obContext, core),
new SetGroupRemark(obContext, core),
new GetGroupInfoEx(obContext, core),
new FetchEmojiLike(obContext, core),
@@ -132,6 +139,9 @@ export function createActionMap(obContext: NapCatOneBot11Adapter, core: NapCatCo
new SetGroupSign(obContext, core),
new SendGroupSign(obContext, core),
new GetClientkey(obContext, core),
new MoveGroupFile(obContext, core),
new RenameGroupFile(obContext, core),
new TransGroupFile(obContext, core),
// onebot11
new SendLike(obContext, core),
new GetMsg(obContext, core),

View File

@@ -0,0 +1,18 @@
import { ActionName } from '@/onebot/action/router';
import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus';
export class GetRkeyEx extends GetPacketStatusDepends<void, unknown> {
override actionName = ActionName.GetRkeyEx;
async _handle() {
let rkeys = await this.core.apis.PacketApi.pkt.operation.FetchRkey();
return rkeys.map(rkey => {
return {
type: rkey.type === 10 ? "private" : "group",
rkey: rkey.rkey,
created_at: rkey.time,
ttl: rkey.ttl,
};
});
}
}

View File

@@ -0,0 +1,38 @@
import { ActionName } from '@/onebot/action/router';
import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus';
export class GetRkeyServer extends GetPacketStatusDepends<void, { private_rkey?: string; group_rkey?: string; expired_time?: number; name: string }> {
override actionName = ActionName.GetRkeyServer;
private rkeyCache: {
private_rkey?: string;
group_rkey?: string;
expired_time?: number;
name: string;
} | null = null;
private expiryTime: number | null = null;
async _handle() {
// 检查缓存是否有效
if (this.expiryTime && this.expiryTime > Math.floor(Date.now() / 1000) && this.rkeyCache) {
return this.rkeyCache;
}
// 获取新的 Rkey
let rkeys = await this.core.apis.PacketApi.pkt.operation.FetchRkey();
let privateRkeyItem = rkeys.filter(rkey => rkey.type === 10)[0];
let groupRkeyItem = rkeys.filter(rkey => rkey.type === 20)[0];
this.expiryTime = Math.floor(Date.now() / 1000) + Math.min(+groupRkeyItem!.ttl.toString(),+privateRkeyItem!.ttl.toString());
// 更新缓存
this.rkeyCache = {
private_rkey: privateRkeyItem ? privateRkeyItem.rkey : undefined,
group_rkey: groupRkeyItem ? groupRkeyItem.rkey : undefined,
expired_time: this.expiryTime,
name: "NapCat 4"
};
return this.rkeyCache;
}
}

View File

@@ -10,6 +10,8 @@ export interface InvalidCheckResult {
}
export const ActionName = {
GetRkeyEx: 'get_rkey',
GetRkeyServer: 'get_rkey_server',
SetGroupRemark: 'set_group_remark',
NapCat_GetPrivateFileUrl: 'get_private_file_url',
ClickInlineKeyboardButton: 'click_inline_keyboard_button',
@@ -130,6 +132,10 @@ export const ActionName = {
GetRkey: 'nc_get_rkey',
GetGroupShutList: 'get_group_shut_list',
MoveGroupFile: 'move_group_file',
TransGroupFile: 'trans_group_file',
RenameGroupFile: 'rename_group_file',
GetGuildList: 'get_guild_list',
GetGuildProfile: 'get_guild_service_profile',

View File

@@ -114,7 +114,6 @@ export class OneBotGroupApi {
async parseCardChangedEvent(msg: RawMessage) {
if (msg.senderUin && msg.senderUin !== '0') {
const member = await this.core.apis.GroupApi.getGroupMember(msg.peerUid, msg.senderUin);
await this.core.apis.GroupApi.refreshGroupMemberCachePartial(msg.peerUid, msg.senderUid);
if (member && member.cardName !== msg.sendMemberName) {
const newCardName = msg.sendMemberName ?? '';
const event = new OB11GroupCardEvent(this.core, parseInt(msg.peerUid), parseInt(msg.senderUin), newCardName, member.cardName);
@@ -130,7 +129,6 @@ export class OneBotGroupApi {
async parsePaiYiPai(msg: RawMessage, jsonStr: string) {
const json = JSON.parse(jsonStr);
//判断业务类型
//Poke事件
const pokedetail: Array<{ uid: string }> = json.items;

View File

@@ -93,6 +93,7 @@ export class OB11Construct {
static group(group: Group): OB11Group {
return {
group_all_shut: (+group.groupShutupExpireTime > 0 )? -1 : 0,
group_remark: group.remarkName,
group_id: +group.groupCode,
group_name: group.groupName,

View File

@@ -63,6 +63,7 @@ export interface OB11GroupMember {
}
export interface OB11Group {
group_all_shut: number; // 群全员禁言
group_remark: string; // 群备注
group_id: number; // 群ID
group_name: string; // 群名称

View File

@@ -1,4 +1,2 @@
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

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