Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
279b3ea4eb | ||
|
|
33cc11ba84 | ||
|
|
b058604077 | ||
|
|
1c703a60ed | ||
|
|
285ba9cf2d | ||
|
|
b253fd82c4 | ||
|
|
8996b35dd1 | ||
|
|
25db6f0835 | ||
|
|
2c8f9743da | ||
|
|
fc26077283 | ||
|
|
e9bbc82f37 | ||
|
|
600f2a4518 | ||
|
|
abf57e688c | ||
|
|
d92a4cff8d | ||
|
|
e195aee5d2 | ||
|
|
014a32533d | ||
|
|
fa97d15c66 | ||
|
|
285632f463 | ||
|
|
6d63da4fa0 | ||
|
|
d849188ef2 | ||
|
|
45966f072e | ||
|
|
c235c92ce9 | ||
|
|
a62c9298ac | ||
|
|
c5bc48da1f | ||
|
|
4edb3385e4 | ||
|
|
10f961c552 | ||
|
|
0baf800d21 | ||
|
|
5c0fac7de6 | ||
|
|
c7109e20ad | ||
|
|
d61433f2a4 | ||
|
|
0ae05ccb8d | ||
|
|
973ccaebed | ||
|
|
59bd457a97 | ||
|
|
d70e06a4f5 | ||
|
|
e6f6468377 | ||
|
|
9d5f0ee604 | ||
|
|
07d4d80ab7 | ||
|
|
7a974d38d4 | ||
|
|
e9b74138d1 | ||
|
|
df0795f2c5 | ||
|
|
85b56e52ac | ||
|
|
77c89d0923 | ||
|
|
58b36cd331 | ||
|
|
deae7fd467 | ||
|
|
8b2207e109 | ||
|
|
f3b76e8b3a | ||
|
|
466d9a3c4f | ||
|
|
4af49c5761 | ||
|
|
442ad4f9a3 | ||
|
|
7ee2f1c40d | ||
|
|
7380665cc2 | ||
|
|
2c57faf117 | ||
|
|
8b0d186625 | ||
|
|
3ba1bd9565 | ||
|
|
8aec6aec1b | ||
|
|
36ae7bf923 | ||
|
|
4ed4dfd450 | ||
|
|
b15d02535e | ||
|
|
974528fe7e | ||
|
|
d2d0b258bc | ||
|
|
2dcba633ba | ||
|
|
53ceb85801 | ||
|
|
dbba6b3ffe | ||
|
|
03dd89add0 | ||
|
|
7fc70bc5ce | ||
|
|
6758825895 | ||
|
|
ae53d27313 | ||
|
|
86884b6ba2 | ||
|
|
776cc8cefd | ||
|
|
66542eda26 | ||
|
|
34a699c568 | ||
|
|
2a06688479 | ||
|
|
976331af94 | ||
|
|
46b0532f84 | ||
|
|
819f76afbf | ||
|
|
938074c654 | ||
|
|
d16f493136 | ||
|
|
4c8419d5ab | ||
|
|
fbba3d5ade | ||
|
|
cf80c787c3 | ||
|
|
7b58681b2b | ||
|
|
7c2eacf0dc | ||
|
|
e09c3c1146 | ||
|
|
cec011bdfa | ||
|
|
9cbaafe806 | ||
|
|
0ddf21a2f5 | ||
|
|
b9dcedacf5 | ||
|
|
b42b6c3cf0 | ||
|
|
740d2118f1 | ||
|
|
77bdcfd249 | ||
|
|
896e1c209a | ||
|
|
cff07c7ce5 | ||
|
|
5c04b799a6 | ||
|
|
1fc4655ae1 | ||
|
|
eb07cdb715 | ||
|
|
964fd98914 | ||
|
|
f9764c9559 | ||
|
|
b71a4913eb | ||
|
|
f961830836 | ||
|
|
dd8b5f84a6 | ||
|
|
48ffd5597a | ||
|
|
1b73d68cbf | ||
|
|
5fec649425 | ||
|
|
052e7fa2b3 | ||
|
|
04e425d17a | ||
|
|
cbe0506577 | ||
|
|
32ec097f51 | ||
|
|
53f27ea9e2 | ||
|
|
41d94cd5e2 | ||
|
|
285d352bc8 | ||
|
|
a3b3836b8a | ||
|
|
b9f61cc0ee | ||
|
|
9998207346 | ||
|
|
4f47af233f | ||
|
|
6aadc2402d | ||
|
|
eb937b29e4 | ||
|
|
f44aca9a2f | ||
|
|
c34812bc9c | ||
|
|
d93b430034 | ||
|
|
c91e1378cf |
No files matched your search
@@ -1,16 +1,6 @@
|
||||
# {VERSION}
|
||||
[使用文档](https://napneko.github.io/)
|
||||
|
||||
## Windows 一键包
|
||||
我们提供了轻量化的一键部署方案
|
||||
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
|
||||
|
||||
你可以下载
|
||||
|
||||
NapCat.Shell.Windows.OneKey.zip (无头)
|
||||
|
||||
启动后可自动化部署一键包,教程参考使用文档安装部分
|
||||
|
||||
## 警告
|
||||
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
|
||||
**默认WebUi密钥为随机密码 控制台查看**
|
||||
|
||||
@@ -3,6 +3,16 @@
|
||||
*/
|
||||
|
||||
export const COMMENT_MARKER = '<!-- napcat-pr-build -->';
|
||||
export const DOCKER_COMMENT_MARKER = '<!-- napcat-pr-docker -->';
|
||||
|
||||
// 默认代理前缀(加速中国大陆访问 GitHub Release)
|
||||
// 格式:https://ghfast.top/{full-github-url}
|
||||
export const PROXY_BASE = 'https://gh.llkk.cc';
|
||||
|
||||
/** 将 GitHub 直链转换为 ghfast.top 加速链接 */
|
||||
export function toProxyUrl (directUrl: string): string {
|
||||
return `${PROXY_BASE}/${directUrl}`;
|
||||
}
|
||||
|
||||
export type BuildStatus = 'success' | 'failure' | 'cancelled' | 'pending' | 'unknown';
|
||||
|
||||
@@ -84,8 +94,8 @@ export function generateBuildingComment (prSha: string, targets: string[]): stri
|
||||
'',
|
||||
'## 📋 构建信息',
|
||||
'',
|
||||
`| 项目 | 值 |`,
|
||||
`| :--- | :--- |`,
|
||||
'| 项目 | 值 |',
|
||||
'| :--- | :--- |',
|
||||
`| 📝 提交 | \`${shortSha}\` |`,
|
||||
`| 🕐 开始时间 | ${time} |`,
|
||||
'',
|
||||
@@ -105,12 +115,19 @@ export function generateBuildingComment (prSha: string, targets: string[]): stri
|
||||
|
||||
// ============== 构建结果评论 ==============
|
||||
|
||||
export interface InstallInfo {
|
||||
installUrl: string;
|
||||
releaseUrl: string;
|
||||
}
|
||||
|
||||
export function generateResultComment (
|
||||
targets: BuildTarget[],
|
||||
prSha: string,
|
||||
runId: string,
|
||||
repository: string,
|
||||
version?: string
|
||||
version?: string,
|
||||
installInfo?: InstallInfo,
|
||||
publishFailed?: boolean
|
||||
): string {
|
||||
const runUrl = `https://github.com/${repository}/actions/runs/${runId}`;
|
||||
const shortSha = formatSha(prSha);
|
||||
@@ -165,21 +182,56 @@ export function generateResultComment (
|
||||
'',
|
||||
'## 📋 构建信息',
|
||||
'',
|
||||
`| 项目 | 值 |`,
|
||||
`| :--- | :--- |`,
|
||||
'| 项目 | 值 |',
|
||||
'| :--- | :--- |',
|
||||
...(version ? [`| 🏷️ 版本号 | \`${version}\` |`] : []),
|
||||
`| 📝 提交 | \`${shortSha}\` |`,
|
||||
`| 🔗 构建日志 | [查看详情](${runUrl}) |`,
|
||||
`| 🕐 完成时间 | ${time} |`,
|
||||
];
|
||||
|
||||
// 添加快速安装命令
|
||||
if (installInfo) {
|
||||
const directUrl = installInfo.installUrl;
|
||||
const proxyInstallUrl = toProxyUrl(directUrl);
|
||||
lines.push(
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## 🚀 快速安装 (Linux)',
|
||||
'',
|
||||
'**直连(需要能访问 GitHub)**',
|
||||
'```bash',
|
||||
`curl -sSL ${directUrl} | bash`,
|
||||
'```',
|
||||
'',
|
||||
'**加速(国内推荐,ghfast.top)**',
|
||||
'```bash',
|
||||
`curl -sSL ${proxyInstallUrl} | bash`,
|
||||
'```',
|
||||
'',
|
||||
`> 📦 [查看 Release 页面](${installInfo.releaseUrl})`,
|
||||
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。'
|
||||
);
|
||||
} else if (publishFailed) {
|
||||
lines.push(
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## ⚠️ Release 发布失败',
|
||||
'',
|
||||
'> ❌ PR Release 发布过程中出现错误,无法提供快速安装命令。',
|
||||
`> 🔗 [查看构建日志](${runUrl}) 了解详情。`
|
||||
);
|
||||
}
|
||||
|
||||
// 添加错误详情
|
||||
const failedTargets = targets.filter(t => t.status === 'failure' && t.error);
|
||||
if (failedTargets.length > 0) {
|
||||
lines.push('', '---', '', '## ⚠️ 错误详情', '');
|
||||
for (const target of failedTargets) {
|
||||
lines.push(
|
||||
`<details>`,
|
||||
'<details>',
|
||||
`<summary>🔴 <b>${target.name}</b> 构建错误</summary>`,
|
||||
'',
|
||||
'```',
|
||||
@@ -229,3 +281,137 @@ export function generateResultComment (
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
// ============== Docker 构建评论 ==============
|
||||
|
||||
export function generateDockerBuildingComment (prNumber: string, prSha: string): string {
|
||||
const time = getTimeString();
|
||||
const shortSha = formatSha(prSha);
|
||||
|
||||
const lines: string[] = [
|
||||
DOCKER_COMMENT_MARKER,
|
||||
'',
|
||||
'<div align="center">',
|
||||
'',
|
||||
'# 🐳 Docker 测试镜像构建中',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'</div>',
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## 📋 构建信息',
|
||||
'',
|
||||
'| 项目 | 值 |',
|
||||
'| :--- | :--- |',
|
||||
`| 📝 提交 | \`${shortSha}\` |`,
|
||||
`| 🔗 PR | #${prNumber} |`,
|
||||
`| 🕐 触发时间 | ${time} |`,
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'<div align="center">',
|
||||
'',
|
||||
'> ⏳ **Docker 镜像正在构建中,请稍候...**',
|
||||
'>',
|
||||
'> 构建完成后将自动更新此评论',
|
||||
'',
|
||||
'</div>',
|
||||
];
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export function generateDockerResultComment (
|
||||
prNumber: string,
|
||||
prSha: string,
|
||||
success: boolean,
|
||||
dockerImage?: string,
|
||||
error?: string
|
||||
): string {
|
||||
const time = getTimeString();
|
||||
const shortSha = formatSha(prSha);
|
||||
|
||||
const statusBadge = success
|
||||
? ''
|
||||
: '';
|
||||
const headerTitle = success ? '# ✅ Docker 测试镜像就绪' : '# ❌ Docker 测试镜像构建失败';
|
||||
|
||||
const lines: string[] = [
|
||||
DOCKER_COMMENT_MARKER,
|
||||
'',
|
||||
'<div align="center">',
|
||||
'',
|
||||
headerTitle,
|
||||
'',
|
||||
statusBadge,
|
||||
'',
|
||||
'</div>',
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## 📋 构建信息',
|
||||
'',
|
||||
'| 项目 | 值 |',
|
||||
'| :--- | :--- |',
|
||||
`| 📝 提交 | \`${shortSha}\` |`,
|
||||
`| 🔗 PR | #${prNumber} |`,
|
||||
`| 🕐 完成时间 | ${time} |`,
|
||||
];
|
||||
|
||||
if (success && dockerImage) {
|
||||
lines.push(
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## 🚀 快速使用',
|
||||
'',
|
||||
'```bash',
|
||||
`docker pull ${dockerImage}`,
|
||||
'```',
|
||||
'',
|
||||
'> ⚠️ 此为 PR 测试镜像,保留 5 天后自动清理。'
|
||||
);
|
||||
}
|
||||
|
||||
if (!success && error) {
|
||||
lines.push(
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'<details>',
|
||||
'<summary>🔴 <b>错误详情</b></summary>',
|
||||
'',
|
||||
'```',
|
||||
escapeCodeBlock(error),
|
||||
'```',
|
||||
'',
|
||||
'</details>'
|
||||
);
|
||||
}
|
||||
|
||||
lines.push('', '---', '');
|
||||
if (success) {
|
||||
lines.push(
|
||||
'<div align="center">',
|
||||
'',
|
||||
'> 🎉 **Docker 测试镜像已就绪!**',
|
||||
'>',
|
||||
'> 使用上方命令拉取镜像进行测试',
|
||||
'',
|
||||
'</div>'
|
||||
);
|
||||
} else {
|
||||
lines.push(
|
||||
'<div align="center">',
|
||||
'',
|
||||
'> ⚠️ **Docker 镜像构建失败**',
|
||||
'>',
|
||||
'> 请检查错误详情',
|
||||
'',
|
||||
'</div>'
|
||||
);
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -31,6 +31,21 @@ export interface Artifact {
|
||||
archive_download_url: string;
|
||||
}
|
||||
|
||||
export interface Release {
|
||||
id: number;
|
||||
tag_name: string;
|
||||
name: string;
|
||||
upload_url: string;
|
||||
html_url: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ReleaseAsset {
|
||||
id: number;
|
||||
name: string;
|
||||
browser_download_url: string;
|
||||
}
|
||||
|
||||
// ============== GitHub API Client ==========================
|
||||
|
||||
export class GitHubAPI {
|
||||
@@ -56,6 +71,11 @@ export class GitHubAPI {
|
||||
throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
// 204 No Content(DELETE 等)不解析 body
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
@@ -150,6 +170,119 @@ export class GitHubAPI {
|
||||
console.log('✓ Created new comment');
|
||||
}
|
||||
}
|
||||
|
||||
// ============== Release API ==============
|
||||
|
||||
async getReleaseByTag (owner: string, repo: string, tag: string): Promise<Release | null> {
|
||||
try {
|
||||
return await this.request<Release>(`/repos/${owner}/${repo}/releases/tags/${tag}`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteRelease (owner: string, repo: string, releaseId: number): Promise<void> {
|
||||
await this.request(`/repos/${owner}/${repo}/releases/${releaseId}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
async deleteRef (owner: string, repo: string, ref: string): Promise<void> {
|
||||
try {
|
||||
await this.request(`/repos/${owner}/${repo}/git/refs/${ref}`, { method: 'DELETE' });
|
||||
} catch {
|
||||
// ref may not exist, ignore
|
||||
}
|
||||
}
|
||||
|
||||
async createRelease (
|
||||
owner: string,
|
||||
repo: string,
|
||||
tag: string,
|
||||
name: string,
|
||||
body: string,
|
||||
prerelease = true
|
||||
): Promise<Release> {
|
||||
return this.request<Release>(`/repos/${owner}/${repo}/releases`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ tag_name: tag, name, body, prerelease }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
async uploadReleaseAsset (
|
||||
uploadUrl: string,
|
||||
fileName: string,
|
||||
data: Buffer,
|
||||
contentType = 'application/octet-stream'
|
||||
): Promise<ReleaseAsset> {
|
||||
const url = uploadUrl.replace(/\{[^}]*\}/g, '') + `?name=${encodeURIComponent(fileName)}`;
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
Accept: 'application/vnd.github+json',
|
||||
'Content-Type': contentType,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
body: data,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Upload ${fileName} failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
return response.json() as Promise<ReleaseAsset>;
|
||||
}
|
||||
|
||||
// ============== Dispatch API ==============
|
||||
|
||||
async repositoryDispatch (
|
||||
owner: string,
|
||||
repo: string,
|
||||
eventType: string,
|
||||
clientPayload: Record<string, string>
|
||||
): Promise<void> {
|
||||
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/dispatches`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
Accept: 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ event_type: eventType, client_payload: clientPayload }),
|
||||
});
|
||||
if (!response.ok && response.status !== 204) {
|
||||
throw new Error(`Dispatch failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
async createWorkflowDispatch (
|
||||
owner: string,
|
||||
repo: string,
|
||||
workflowFile: string,
|
||||
ref: string,
|
||||
inputs: Record<string, string>
|
||||
): Promise<void> {
|
||||
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/actions/workflows/${workflowFile}/dispatches`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
Accept: 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ ref, inputs }),
|
||||
});
|
||||
if (!response.ok && response.status !== 204) {
|
||||
throw new Error(`Workflow dispatch failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ============== Release Cleanup API ==============
|
||||
|
||||
async listReleases (owner: string, repo: string, perPage = 100, page = 1): Promise<Release[]> {
|
||||
return this.request<Release[]>(
|
||||
`/repos/${owner}/${repo}/releases?per_page=${perPage}&page=${page}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ============== Output 工具 ==============
|
||||
@@ -172,8 +305,7 @@ export function setMultilineOutput (name: string, value: string): void {
|
||||
|
||||
// ============== 环境变量工具 ==============
|
||||
|
||||
export function getEnv (name: string, required: true): string;
|
||||
export function getEnv (name: string, required?: false): string | undefined;
|
||||
// Note: 不使用函数重载——Node.js --experimental-strip-types 不支持 TS overload signatures
|
||||
export function getEnv (name: string, required = false): string | undefined {
|
||||
const value = process.env[name];
|
||||
if (required && !value) {
|
||||
@@ -183,7 +315,7 @@ export function getEnv (name: string, required = false): string | undefined {
|
||||
}
|
||||
|
||||
export function getRepository (): { owner: string, repo: string; } {
|
||||
const repository = getEnv('GITHUB_REPOSITORY', true);
|
||||
const repository = getEnv('GITHUB_REPOSITORY', true)!;
|
||||
const [owner, repo] = repository.split('/');
|
||||
return { owner, repo };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* PR Build - Dispatch untrusted build workflow
|
||||
*
|
||||
* 环境变量:
|
||||
* - GITHUB_TOKEN: GitHub API Token
|
||||
* - PR_NUMBER: PR 编号
|
||||
* - PR_SHA: PR HEAD SHA
|
||||
* - PR_HEAD_REPO: PR 源仓库
|
||||
* - PR_HEAD_REF: PR 源分支
|
||||
* - WORKFLOW_FILE: 工作流文件名,默认 build-pr.yml
|
||||
* - DISPATCH_REF: 触发分支,默认当前分支
|
||||
*/
|
||||
|
||||
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
|
||||
|
||||
declare const process: { exit(code?: number): never; };
|
||||
|
||||
async function main (): Promise<void> {
|
||||
console.log('🚀 Dispatching PR build workflow\n');
|
||||
|
||||
const token = getEnv('GITHUB_TOKEN', true)!;
|
||||
const prNumber = getEnv('PR_NUMBER', true)!;
|
||||
const prSha = getEnv('PR_SHA', true)!;
|
||||
const prHeadRepo = getEnv('PR_HEAD_REPO', true)!;
|
||||
const prHeadRef = getEnv('PR_HEAD_REF') || '';
|
||||
const workflowFile = getEnv('WORKFLOW_FILE') || 'build-pr.yml';
|
||||
const dispatchRef = getEnv('DISPATCH_REF') || getEnv('GITHUB_REF_NAME') || 'main';
|
||||
const { owner, repo } = getRepository();
|
||||
|
||||
console.log(`PR: #${prNumber}`);
|
||||
console.log(`SHA: ${prSha}`);
|
||||
console.log(`Head repo: ${prHeadRepo}`);
|
||||
console.log(`Workflow: ${workflowFile}`);
|
||||
console.log(`Ref: ${dispatchRef}\n`);
|
||||
|
||||
const github = new GitHubAPI(token);
|
||||
await github.createWorkflowDispatch(owner, repo, workflowFile, dispatchRef, {
|
||||
pr_number: prNumber,
|
||||
pr_sha: prSha,
|
||||
pr_head_repo: prHeadRepo,
|
||||
pr_head_ref: prHeadRef,
|
||||
});
|
||||
|
||||
console.log('✅ Dispatch created');
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('❌ Error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -11,11 +11,13 @@
|
||||
* - FRAMEWORK_ERROR: Framework 构建错误信息
|
||||
* - SHELL_STATUS: Shell 构建状态
|
||||
* - SHELL_ERROR: Shell 构建错误信息
|
||||
* - INSTALL_URL: PR Release 安装脚本 URL (可选)
|
||||
* - RELEASE_URL: PR Release 页面 URL (可选)
|
||||
*/
|
||||
|
||||
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
|
||||
import { generateResultComment, COMMENT_MARKER } from './lib/comment.ts';
|
||||
import type { BuildTarget, BuildStatus } from './lib/comment.ts';
|
||||
import type { BuildTarget, BuildStatus, InstallInfo } from './lib/comment.ts';
|
||||
|
||||
function parseStatus (value: string | undefined): BuildStatus {
|
||||
if (value === 'success' || value === 'failure' || value === 'cancelled') {
|
||||
@@ -46,6 +48,21 @@ async function main (): Promise<void> {
|
||||
console.log(`Framework: ${frameworkStatus}${frameworkError ? ` (${frameworkError})` : ''}`);
|
||||
console.log(`Shell: ${shellStatus}${shellError ? ` (${shellError})` : ''}\n`);
|
||||
|
||||
// PR Release 信息(由 publish-pr-release job 传入)
|
||||
const installUrl = getEnv('INSTALL_URL');
|
||||
const releaseUrl = getEnv('RELEASE_URL');
|
||||
const publishStatus = getEnv('PUBLISH_STATUS'); // 'success' | 'failure' | 'skipped' | ''
|
||||
const installInfo: InstallInfo | undefined =
|
||||
installUrl && releaseUrl ? { installUrl, releaseUrl } : undefined;
|
||||
const publishFailed = publishStatus === 'failure';
|
||||
|
||||
if (installInfo) {
|
||||
console.log(`Install URL: ${installUrl}`);
|
||||
console.log(`Release URL: ${releaseUrl}\n`);
|
||||
} else if (publishFailed) {
|
||||
console.log('Publish status: FAILED\n');
|
||||
}
|
||||
|
||||
const github = new GitHubAPI(token);
|
||||
const repository = `${owner}/${repo}`;
|
||||
|
||||
@@ -79,7 +96,7 @@ async function main (): Promise<void> {
|
||||
},
|
||||
];
|
||||
|
||||
const comment = generateResultComment(targets, prSha, runId, repository, version);
|
||||
const comment = generateResultComment(targets, prSha, runId, repository, version, installInfo, publishFailed);
|
||||
|
||||
await github.createOrUpdateComment(owner, repo, prNumber, comment, COMMENT_MARKER);
|
||||
}
|
||||
|
||||
@@ -22,11 +22,7 @@ interface BuildStep {
|
||||
|
||||
function getCommonSteps (): BuildStep[] {
|
||||
return [
|
||||
{
|
||||
name: 'Install pnpm',
|
||||
command: 'npm i -g pnpm',
|
||||
errorMessage: 'Failed to install pnpm',
|
||||
},
|
||||
// pnpm 已通过 GitHub Action (pnpm/action-setup) 预安装并固定 v9, 此处无需再次安装
|
||||
{
|
||||
name: 'Install dependencies',
|
||||
command: 'pnpm i',
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* PR Build - 触发 NapCat-Docker 仓库构建 PR 测试镜像
|
||||
*
|
||||
* 功能:
|
||||
* 1. 在 PR 中创建 Docker 构建中评论
|
||||
* 2. 触发 NapCat-Docker 仓库的 repository_dispatch 事件
|
||||
*
|
||||
* 环境变量:
|
||||
* DISPATCH_PAT - 具备目标仓库 dispatch 权限的 PAT
|
||||
* GITHUB_TOKEN - GitHub API Token (用于写 PR 评论)
|
||||
* PR_NUMBER - PR 编号
|
||||
* PR_SHA - PR HEAD 提交 SHA
|
||||
* PR_HEAD_REPO - PR 源仓库 (owner/repo)
|
||||
* SOURCE_REPO - 当前仓库 (默认 NapNeko/NapCatQQ)
|
||||
* RELEASE_REPO - PR release 仓库 (默认 NapNeko/napcat-pr-release)
|
||||
* TARGET_REPO - Docker 仓库 (默认 NapNeko/NapCat-Docker)
|
||||
*/
|
||||
|
||||
import { GitHubAPI, getEnv } from './lib/github.ts';
|
||||
import { generateDockerBuildingComment, DOCKER_COMMENT_MARKER } from './lib/comment.ts';
|
||||
|
||||
async function main (): Promise<void> {
|
||||
console.log('🐳 Dispatching Docker build\n');
|
||||
|
||||
const token = getEnv('DISPATCH_PAT', true);
|
||||
const githubToken = getEnv('GITHUB_TOKEN', true);
|
||||
const prNumber = getEnv('PR_NUMBER', true);
|
||||
const prSha = getEnv('PR_SHA', true);
|
||||
const prHeadRepo = getEnv('PR_HEAD_REPO') || '';
|
||||
const sourceRepo = getEnv('SOURCE_REPO') || 'NapNeko/NapCatQQ';
|
||||
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
|
||||
const targetRepo = getEnv('TARGET_REPO') || 'NapNeko/NapCat-Docker';
|
||||
|
||||
const [targetOwner, targetRepoName] = targetRepo.split('/');
|
||||
const [sourceOwner, sourceRepoName] = sourceRepo.split('/');
|
||||
const shortSha = prSha.substring(0, 7);
|
||||
|
||||
console.log(` PR: #${prNumber}`);
|
||||
console.log(` SHA: ${shortSha}`);
|
||||
console.log(` Target: ${targetRepo}`);
|
||||
console.log(` Release: ${releaseRepo}\n`);
|
||||
|
||||
// 在 PR 中创建 Docker 构建中评论
|
||||
console.log('💬 Creating Docker building comment...');
|
||||
const prGithub = new GitHubAPI(githubToken);
|
||||
const dockerComment = generateDockerBuildingComment(prNumber, prSha);
|
||||
await prGithub.createOrUpdateComment(
|
||||
sourceOwner, sourceRepoName, parseInt(prNumber, 10), dockerComment, DOCKER_COMMENT_MARKER
|
||||
);
|
||||
|
||||
// 触发 Docker 仓库构建
|
||||
const github = new GitHubAPI(token);
|
||||
|
||||
await github.repositoryDispatch(targetOwner, targetRepoName, 'napcatqq-pr-build', {
|
||||
pr_number: prNumber,
|
||||
pr_sha: prSha,
|
||||
pr_short_sha: shortSha,
|
||||
pr_head_repo: prHeadRepo,
|
||||
source_repo: sourceRepo,
|
||||
release_repo: releaseRepo,
|
||||
});
|
||||
|
||||
console.log('✅ Dispatch succeeded');
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('❌ Error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* PR Build - 发布构建产物到 napcat-pr-release 仓库
|
||||
*
|
||||
* 功能:
|
||||
* 1. 将 CI 构建产物(Framework / Shell)打包为 zip
|
||||
* 2. 从 NapCat-Installer 仓库拉取 install.sh 并替换下载链接
|
||||
* 3. 发布到 napcat-pr-release 仓库的 GitHub Release
|
||||
*
|
||||
* 环境变量:
|
||||
* RELEASE_PAT - 具备目标仓库 release 写权限的 PAT
|
||||
* PR_NUMBER - PR 编号
|
||||
* PR_SHA - PR HEAD 提交 SHA
|
||||
* NAPCAT_VERSION - 构建版本号
|
||||
* ARTIFACTS_DIR - 构建产物目录 (默认 ./artifacts)
|
||||
* RELEASE_REPO - 发布仓库 (默认 NapNeko/napcat-pr-release)
|
||||
* INSTALLER_REPO - 安装脚本仓库 (默认 NapNeko/NapCat-Installer)
|
||||
* INSTALLER_BRANCH - 安装脚本分支 (默认 main)
|
||||
*/
|
||||
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
|
||||
import { join, basename, resolve } from 'node:path';
|
||||
import { GitHubAPI, getEnv, setOutput } from './lib/github.ts';
|
||||
import { toProxyUrl } from './lib/comment.ts';
|
||||
|
||||
interface AssetEntry {
|
||||
name: string;
|
||||
path: string;
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
async function main (): Promise<void> {
|
||||
console.log('📦 PR Release Publisher\n');
|
||||
|
||||
const token = getEnv('RELEASE_PAT', true);
|
||||
const prNumber = getEnv('PR_NUMBER', true);
|
||||
const prSha = getEnv('PR_SHA', true);
|
||||
const version = getEnv('NAPCAT_VERSION') || 'unknown';
|
||||
const artifactsDir = getEnv('ARTIFACTS_DIR') || './artifacts';
|
||||
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
|
||||
const installerRepo = getEnv('INSTALLER_REPO') || 'NapNeko/NapCat-Installer';
|
||||
const installerBranch = getEnv('INSTALLER_BRANCH') || 'main';
|
||||
|
||||
const [releaseOwner, releaseRepoName] = releaseRepo.split('/');
|
||||
const shortSha = prSha.substring(0, 7);
|
||||
const tag = `pr-${prNumber}-${shortSha}`;
|
||||
const releaseName = `PR #${prNumber} (${shortSha})`;
|
||||
const downloadBase = `https://github.com/${releaseRepo}/releases/download/${tag}`;
|
||||
|
||||
console.log(` Tag: ${tag}`);
|
||||
console.log(` Repo: ${releaseRepo}`);
|
||||
console.log(` Version: ${version}`);
|
||||
console.log(` SHA: ${shortSha}\n`);
|
||||
|
||||
const github = new GitHubAPI(token);
|
||||
const releaseDir = resolve('./release-assets'); // 使用绝对路径,避免 zip cwd 切换后相对路径解析错误
|
||||
mkdirSync(releaseDir, { recursive: true });
|
||||
|
||||
// ---- 打包构建产物 ----
|
||||
const artifacts = ['NapCat.Framework', 'NapCat.Shell'];
|
||||
for (const name of artifacts) {
|
||||
const dir = join(artifactsDir, name);
|
||||
if (existsSync(dir)) {
|
||||
const zipPath = join(releaseDir, `${name}.zip`);
|
||||
console.log(`📦 Packing ${name}...`);
|
||||
execSync(`zip -qr "${zipPath}" .`, { cwd: dir, stdio: 'inherit' });
|
||||
console.log(` ✓ ${name}.zip\n`);
|
||||
} else {
|
||||
console.log(` ⚠ ${name} 目录不存在,跳过\n`);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 拉取并修改安装脚本 ----
|
||||
console.log('📜 Fetching install.sh...');
|
||||
const scriptUrl = `https://raw.githubusercontent.com/${installerRepo}/${installerBranch}/script/install.sh`;
|
||||
try {
|
||||
const response = await fetch(scriptUrl);
|
||||
if (response.ok) {
|
||||
let script = await response.text();
|
||||
// 替换下载链接(保留代理前缀 ${target_proxy:+${target_proxy}/})
|
||||
const shellUrl = `${downloadBase}/NapCat.Shell.zip`;
|
||||
const originalScript = script;
|
||||
script = script.replace(
|
||||
/napcat_download_url="\$\{target_proxy:\+\$\{target_proxy\}\/\}https:\/\/github\.com\/NapNeko\/NapCatQQ\/releases\/latest\/download\/NapCat\.Shell\.zip"/g,
|
||||
`napcat_download_url="\${target_proxy:+\${target_proxy}/}${shellUrl}"`
|
||||
);
|
||||
if (script === originalScript) {
|
||||
console.log(' ⚠ Warning: URL replacement did not match - install.sh format may have changed');
|
||||
}
|
||||
const scriptPath = join(releaseDir, 'install.sh');
|
||||
writeFileSync(scriptPath, script, { mode: 0o755 });
|
||||
console.log(` ✓ Patched download URL -> ${shellUrl}\n`);
|
||||
} else {
|
||||
console.log(` ⚠ Failed to fetch install.sh: ${response.status}\n`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(` ⚠ Failed to fetch install.sh: ${(e as Error).message}\n`);
|
||||
}
|
||||
|
||||
// ---- 收集所有要上传的文件 ----
|
||||
const assets: AssetEntry[] = [];
|
||||
for (const file of readdirSync(releaseDir)) {
|
||||
const ext = file.split('.').pop()?.toLowerCase();
|
||||
const contentType = ext === 'zip' ? 'application/zip' : ext === 'sh' ? 'application/x-sh' : 'application/octet-stream';
|
||||
assets.push({ name: file, path: join(releaseDir, file), contentType });
|
||||
}
|
||||
console.log(`📋 Assets to upload: ${assets.map(a => a.name).join(', ')}\n`);
|
||||
|
||||
// ---- 删除旧 release ----
|
||||
console.log('🗑️ Checking for existing release...');
|
||||
const existing = await github.getReleaseByTag(releaseOwner, releaseRepoName, tag);
|
||||
if (existing) {
|
||||
console.log(` Deleting existing release (id=${existing.id})...`);
|
||||
await github.deleteRelease(releaseOwner, releaseRepoName, existing.id);
|
||||
await github.deleteRef(releaseOwner, releaseRepoName, `tags/${tag}`);
|
||||
console.log(' ✓ Deleted\n');
|
||||
} else {
|
||||
console.log(' No existing release\n');
|
||||
}
|
||||
|
||||
// ---- 创建 Release ----
|
||||
const directInstallUrl = `${downloadBase}/install.sh`;
|
||||
const proxyInstallUrl = toProxyUrl(directInstallUrl);
|
||||
const releaseBody = [
|
||||
`## NapCat PR #${prNumber} 测试版本`,
|
||||
'',
|
||||
`- **版本**: \`${version}\``,
|
||||
`- **提交**: \`${prSha}\``,
|
||||
`- **来源**: [NapCatQQ PR #${prNumber}](https://github.com/NapNeko/NapCatQQ/pull/${prNumber})`,
|
||||
'',
|
||||
'### 快速安装 (Linux)',
|
||||
'',
|
||||
'**直连(需要能访问 GitHub)**',
|
||||
'```bash',
|
||||
`curl -sSL ${directInstallUrl} | bash`,
|
||||
'```',
|
||||
'',
|
||||
'**加速(国内推荐,ghfast.top)**',
|
||||
'```bash',
|
||||
`curl -sSL ${proxyInstallUrl} | bash`,
|
||||
'```',
|
||||
'',
|
||||
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。',
|
||||
].join('\n');
|
||||
|
||||
console.log('🚀 Creating release...');
|
||||
const release = await github.createRelease(
|
||||
releaseOwner, releaseRepoName, tag, releaseName, releaseBody, true
|
||||
);
|
||||
console.log(` ✓ Release created: ${release.html_url}\n`);
|
||||
|
||||
// ---- 上传资产 ----
|
||||
console.log('📤 Uploading assets...');
|
||||
for (const asset of assets) {
|
||||
const data = readFileSync(asset.path);
|
||||
const uploaded = await github.uploadReleaseAsset(
|
||||
release.upload_url, asset.name, data, asset.contentType
|
||||
);
|
||||
console.log(` ✓ ${asset.name} -> ${uploaded.browser_download_url}`);
|
||||
}
|
||||
|
||||
console.log(`\n✅ Release published: ${release.html_url}`);
|
||||
|
||||
// 输出供后续 job 使用
|
||||
setOutput('release_url', release.html_url);
|
||||
setOutput('release_tag', tag);
|
||||
setOutput('install_url', `${downloadBase}/install.sh`);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('❌ Error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* publish-release-hash.mjs
|
||||
*
|
||||
* 读取 release.json(不存在则创建),追加新版本的 Shell/Framework napcat.mjs SHA512,
|
||||
* 保留最近 100 条后写回文件。
|
||||
*
|
||||
* 用法:
|
||||
* node .github/scripts/publish-release-hash.mjs \
|
||||
* --version v4.9.0 \
|
||||
* --shell ./artifacts/NapCat.Shell/napcat.mjs \
|
||||
* --framework ./artifacts/NapCat.Framework/napcat.mjs \
|
||||
* --file ./hash-repo/release.json
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
|
||||
// ─── CLI 参数解析 ────────────────────────────────────────────────────────────
|
||||
|
||||
function parseArgs () {
|
||||
const args = process.argv.slice(2);
|
||||
const result = {};
|
||||
for (let i = 0; i < args.length; i += 2) {
|
||||
result[args[i].replace(/^--/, '')] = args[i + 1];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const { version, shell: shellPath, framework: frameworkPath, file: outputFile } = parseArgs();
|
||||
|
||||
if (!version || !shellPath || !frameworkPath || !outputFile) {
|
||||
console.error('Usage: node publish-release-hash.mjs --version <v> --shell <path> --framework <path> --file <path>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// ─── 工具函数 ────────────────────────────────────────────────────────────────
|
||||
|
||||
function sha512File (filePath) {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error(`File not found: ${filePath}`);
|
||||
}
|
||||
const buf = fs.readFileSync(filePath);
|
||||
return crypto.createHash('sha512').update(buf).digest('hex');
|
||||
}
|
||||
|
||||
// ─── 主逻辑 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const MAX_ENTRIES = 100;
|
||||
|
||||
// 1. 计算哈希
|
||||
console.log(`Computing SHA512 for Shell: ${shellPath}`);
|
||||
const shellHash = sha512File(shellPath);
|
||||
console.log(`Computing SHA512 for Framework: ${frameworkPath}`);
|
||||
const frameworkHash = sha512File(frameworkPath);
|
||||
|
||||
// 2. 读取现有 release.json,不存在则创建空数组
|
||||
let entries = [];
|
||||
if (fs.existsSync(outputFile)) {
|
||||
entries = JSON.parse(fs.readFileSync(outputFile, 'utf-8'));
|
||||
console.log(`Loaded existing ${outputFile} with ${entries.length} entries.`);
|
||||
} else {
|
||||
console.log(`${outputFile} not found, will create it.`);
|
||||
}
|
||||
|
||||
// 3. 追加新条目,去除同版本旧条目,滚动保留最近 MAX_ENTRIES 条
|
||||
const newEntry = {
|
||||
version,
|
||||
shell: { sha512: shellHash },
|
||||
framework: { sha512: frameworkHash },
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const updated = [
|
||||
...entries.filter(e => e.version !== version),
|
||||
newEntry,
|
||||
].slice(-MAX_ENTRIES);
|
||||
|
||||
// 4. 写回文件
|
||||
fs.writeFileSync(outputFile, JSON.stringify(updated, null, 2) + '\n', 'utf-8');
|
||||
console.log(`✅ Written ${updated.length} entries to ${outputFile}`);
|
||||
@@ -1,153 +0,0 @@
|
||||
name: Auto Release Docker
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
publish-schema:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Get Version
|
||||
id: get_version
|
||||
run: |
|
||||
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
|
||||
version=${latest_tag#v}
|
||||
echo "version=${version}" >> $GITHUB_ENV
|
||||
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
|
||||
echo "Debug: Version is ${version}"
|
||||
|
||||
- name: Install Dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build napcat-schema
|
||||
run: |
|
||||
cd packages/napcat-schema
|
||||
pnpm run build:openapi
|
||||
|
||||
- name: Checkout NapCatDocs
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: NapNeko/NapCatDocs
|
||||
token: ${{ secrets.NAPCAT_BUILD }}
|
||||
path: napcat-docs
|
||||
|
||||
- name: Copy OpenAPI Schema
|
||||
run: |
|
||||
mkdir -p napcat-docs/src/api/${{ env.version }}
|
||||
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${{ env.version }}/openapi.json
|
||||
echo "OpenAPI schema copied to napcat-docs/src/api/${{ env.version }}/openapi.json"
|
||||
|
||||
- name: Commit and Push
|
||||
run: |
|
||||
cd napcat-docs
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add src/api/${{ env.version }}/openapi.json
|
||||
git commit -m "chore: update OpenAPI schema for version ${{ env.version }}" || echo "No changes to commit"
|
||||
git push
|
||||
|
||||
shell-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat-Docker docker-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
framework-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat-Framework-Docker docker-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCat.Docker.Framework/actions/workflows/docker-image.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
appimage-shell-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Get Latest NapCat Version
|
||||
id: get_version
|
||||
run: |
|
||||
# 获取当前仓库的最新 tag
|
||||
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
|
||||
# 输出调试信息
|
||||
echo "Debug: Latest NapCat Version is ${latest_tag}"
|
||||
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
|
||||
- name: Trigger Release NapCat AppImage Workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ env.latest_tag }}
|
||||
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
|
||||
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
|
||||
run: |
|
||||
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_version_x86_64=${QQ_VERSION_X86_64}, qq_version_arm64=${QQ_VERSION_ARM64}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatAppImageBuild/actions/workflows/release.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_version_x86_64\":\"${QQ_VERSION_X86_64}\",\"qq_version_arm64\":\"${QQ_VERSION_ARM64}\"}}"
|
||||
node-shell-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Get Latest NapCat Version
|
||||
id: get_version
|
||||
run: |
|
||||
# 获取当前仓库的最新 tag
|
||||
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
|
||||
# 输出调试信息
|
||||
echo "Debug: Latest NapCat Version is ${latest_tag}"
|
||||
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
|
||||
- name: Trigger Release NapCat AppImage Workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ env.latest_tag }}
|
||||
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
|
||||
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
|
||||
run: |
|
||||
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_url_amd64=${QQ_VERSION_X86_64}, qq_url_arm64=${QQ_VERSION_ARM64}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/release.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"
|
||||
- name: Trigger Release NapCat AppImage Workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ env.latest_tag }}
|
||||
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
|
||||
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
|
||||
run: |
|
||||
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_url_amd64=${QQ_VERSION_X86_64}, qq_url_arm64=${QQ_VERSION_ARM64}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/docker-publish.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"
|
||||
@@ -0,0 +1,91 @@
|
||||
name: Build NapCat Artifacts
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions: write-all
|
||||
|
||||
jobs:
|
||||
typecheck-and-test:
|
||||
name: Type Check & Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Install Dependencies
|
||||
run: pnpm i
|
||||
- name: Type Check
|
||||
run: pnpm run typecheck
|
||||
- name: Run Tests
|
||||
run: pnpm test
|
||||
|
||||
build:
|
||||
name: Build NapCat.${{ matrix.target.name }}
|
||||
needs: typecheck-and-test
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target:
|
||||
- name: Framework
|
||||
build_cmd: build:framework
|
||||
src_dir: packages/napcat-framework/dist
|
||||
dist_dir: framework-dist
|
||||
- name: Shell
|
||||
build_cmd: build:shell
|
||||
src_dir: packages/napcat-shell/dist
|
||||
dist_dir: shell-dist
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Generate Version
|
||||
run: |
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${GITHUB_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
- name: Build NapCat.${{ matrix.target.name }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: |
|
||||
pnpm i
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run ${{ matrix.target.build_cmd }}
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
|
||||
cd ${{ matrix.target.dist_dir }}
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.${{ matrix.target.name }}
|
||||
path: ${{ matrix.target.dist_dir }}
|
||||
@@ -0,0 +1,424 @@
|
||||
# =============================================================================
|
||||
# PR 构建工作流
|
||||
# =============================================================================
|
||||
# 安全模型:
|
||||
# 1. pull_request_target / issue_comment 入口只读取元数据、检查权限、更新评论并触发构建。
|
||||
# 2. 真正执行 PR 代码的构建流程只在 workflow_dispatch 中运行。
|
||||
# 3. 构建流程不具备写仓库/写评论/读 secrets 权限,显式清空 GITHUB_TOKEN,不持久化 checkout 凭据。
|
||||
# 4. 版本号在 Action 中提前生成,通过 NAPCAT_VERSION 传给 Vite 插件,插件无需 GitHub token。
|
||||
# 5. 发布 Release、触发 Docker 等可信操作只消费构建 artifact,不执行 PR artifact 中的代码。
|
||||
# =============================================================================
|
||||
|
||||
name: Build PR
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr_number:
|
||||
description: PR 编号
|
||||
required: true
|
||||
type: string
|
||||
pr_sha:
|
||||
description: PR HEAD SHA
|
||||
required: true
|
||||
type: string
|
||||
pr_head_repo:
|
||||
description: PR 源仓库
|
||||
required: true
|
||||
type: string
|
||||
pr_head_ref:
|
||||
description: PR 源分支
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: pr-build-${{ github.event_name == 'workflow_dispatch' && inputs.pr_number || github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# 特权入口:只检查条件、写入“构建中”评论、触发无权限构建
|
||||
# ---------------------------------------------------------------------------
|
||||
check-build:
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: write
|
||||
outputs:
|
||||
should_build: ${{ steps.check.outputs.should_build }}
|
||||
pr_number: ${{ steps.check.outputs.pr_number }}
|
||||
pr_sha: ${{ steps.check.outputs.pr_sha }}
|
||||
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }}
|
||||
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }}
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Check trigger condition
|
||||
id: check
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-check.ts
|
||||
|
||||
update-comment-building:
|
||||
needs: check-build
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Update building comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-building.ts
|
||||
|
||||
dispatch-build:
|
||||
needs: [check-build, update-comment-building]
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Dispatch untrusted build
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
PR_HEAD_REPO: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
PR_HEAD_REF: ${{ needs.check-build.outputs.pr_head_ref }}
|
||||
WORKFLOW_FILE: build-pr.yml
|
||||
DISPATCH_REF: ${{ github.event.repository.default_branch }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-dispatch.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 无权限构建:只由 workflow_dispatch 执行 PR 代码
|
||||
# ---------------------------------------------------------------------------
|
||||
build-framework:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }}
|
||||
error: ${{ steps.build.outputs.error }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
persist-credentials: false
|
||||
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
repository: ${{ inputs.pr_head_repo }}
|
||||
ref: ${{ inputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ inputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ''
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: workspace/framework-dist
|
||||
retention-days: 5
|
||||
|
||||
build-shell:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }}
|
||||
error: ${{ steps.build.outputs.error }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
persist-credentials: false
|
||||
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
repository: ${{ inputs.pr_head_repo }}
|
||||
ref: ${{ inputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ inputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ''
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts shell
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: workspace/shell-dist
|
||||
retention-days: 5
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 可信后处理:只下载/打包/发布 artifact,不执行 artifact 中的代码
|
||||
# ---------------------------------------------------------------------------
|
||||
publish-pr-release:
|
||||
needs: [build-framework, build-shell]
|
||||
if: always() && github.event_name == 'workflow_dispatch' && (needs.build-framework.outputs.status == 'success' || needs.build-shell.outputs.status == 'success')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
outputs:
|
||||
release_url: ${{ steps.publish.outputs.release_url }}
|
||||
release_tag: ${{ steps.publish.outputs.release_tag }}
|
||||
install_url: ${{ steps.publish.outputs.install_url }}
|
||||
publish_status: ${{ steps.publish.outcome }}
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Download Framework artifact
|
||||
if: needs.build-framework.outputs.status == 'success'
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: ./artifacts/NapCat.Framework
|
||||
|
||||
- name: Download Shell artifact
|
||||
if: needs.build-shell.outputs.status == 'success'
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: ./artifacts/NapCat.Shell
|
||||
|
||||
- name: Publish release
|
||||
id: publish
|
||||
continue-on-error: true
|
||||
env:
|
||||
RELEASE_PAT: ${{ secrets.PR_RELEASE_PAT }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
PR_SHA: ${{ inputs.pr_sha }}
|
||||
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
|
||||
ARTIFACTS_DIR: ./artifacts
|
||||
run: |
|
||||
if [ -z "${RELEASE_PAT}" ]; then
|
||||
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 PR Release 发布"
|
||||
exit 0
|
||||
fi
|
||||
node --experimental-strip-types .github/scripts/pr-publish-release.ts
|
||||
|
||||
- name: Upload install script as artifact
|
||||
if: steps.publish.outcome == 'success'
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: install-script
|
||||
path: ./release-assets/install.sh
|
||||
retention-days: 5
|
||||
if-no-files-found: ignore
|
||||
|
||||
update-comment-result:
|
||||
needs: [build-framework, build-shell, publish-pr-release]
|
||||
if: always() && github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Update result comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
PR_SHA: ${{ inputs.pr_sha }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
|
||||
FRAMEWORK_STATUS: ${{ needs.build-framework.outputs.status || 'cancelled' }}
|
||||
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
|
||||
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
|
||||
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
|
||||
INSTALL_URL: ${{ needs.publish-pr-release.outputs.install_url || '' }}
|
||||
RELEASE_URL: ${{ needs.publish-pr-release.outputs.release_url || '' }}
|
||||
PUBLISH_STATUS: ${{ needs.publish-pr-release.outputs.publish_status || '' }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
|
||||
|
||||
trigger-docker:
|
||||
needs: [build-shell, publish-pr-release]
|
||||
if: github.event_name == 'workflow_dispatch' && needs.build-shell.outputs.status == 'success' && needs.publish-pr-release.outputs.release_tag != ''
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Dispatch docker build
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISPATCH_PAT: ${{ secrets.PR_RELEASE_PAT }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
PR_SHA: ${{ inputs.pr_sha }}
|
||||
PR_HEAD_REPO: ${{ inputs.pr_head_repo }}
|
||||
SOURCE_REPO: ${{ github.repository }}
|
||||
RELEASE_REPO: NapNeko/napcat-pr-release
|
||||
run: |
|
||||
if [ -z "${DISPATCH_PAT}" ]; then
|
||||
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 Docker 测试镜像构建"
|
||||
exit 0
|
||||
fi
|
||||
node --experimental-strip-types .github/scripts/pr-docker-dispatch.ts
|
||||
@@ -1,96 +0,0 @@
|
||||
name: Build NapCat Artifacts
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions: write-all
|
||||
|
||||
jobs:
|
||||
Build-Framework:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
- name: Use Node.js 20.X
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Generate Version
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${GITHUB_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
- name: Build NapCat.Framework
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm run typecheck || exit 1
|
||||
pnpm test || exit 1
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run build:framework
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv packages/napcat-framework/dist framework-dist
|
||||
cd framework-dist
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: framework-dist
|
||||
Build-Shell:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
- name: Use Node.js 20.X
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Generate Version
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${GITHUB_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
- name: Build NapCat.Shell
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm run typecheck || exit 1
|
||||
pnpm test || exit 1
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run build:shell
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv packages/napcat-shell/dist shell-dist
|
||||
cd shell-dist
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: shell-dist
|
||||
@@ -1,303 +0,0 @@
|
||||
# =============================================================================
|
||||
# PR 构建工作流
|
||||
# =============================================================================
|
||||
# 功能:
|
||||
# 1. 在 PR 提交时自动构建 Framework 和 Shell 包
|
||||
# 2. 支持通过 /build 命令手动触发构建(仅协作者/组织成员)
|
||||
# 3. 在 PR 中发布构建状态评论,并持续更新(不会重复创建)
|
||||
# 4. 支持 Fork PR 的构建(使用 pull_request_target 获取写权限)
|
||||
#
|
||||
# 安全说明:
|
||||
# - 使用 pull_request_target 事件,在 base 分支上下文运行
|
||||
# - 构建脚本始终从 base 分支 checkout,避免恶意 PR 篡改脚本
|
||||
# - PR 代码单独 checkout 到 workspace 目录
|
||||
# =============================================================================
|
||||
|
||||
name: PR Build
|
||||
|
||||
# =============================================================================
|
||||
# 触发条件
|
||||
# =============================================================================
|
||||
on:
|
||||
# PR 事件:打开、同步(新推送)、重新打开时触发
|
||||
# 注意:使用 pull_request_target 而非 pull_request,以便对 Fork PR 有写权限
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
# Issue 评论事件:用于响应 /build 命令
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
# =============================================================================
|
||||
# 权限配置
|
||||
# =============================================================================
|
||||
permissions:
|
||||
contents: read # 读取仓库内容
|
||||
pull-requests: write # 写入 PR 评论
|
||||
issues: write # 写入 Issue 评论(/build 命令响应)
|
||||
actions: read # 读取 Actions 信息(获取构建日志链接)
|
||||
|
||||
# =============================================================================
|
||||
# 并发控制
|
||||
# =============================================================================
|
||||
# 同一 PR 的多次构建会取消之前未完成的构建,避免资源浪费
|
||||
# 注意:只有在 should_build=true 时才会进入实际构建流程,
|
||||
# issue_comment 事件如果不是 /build 命令,会在 check-build 阶段快速退出,
|
||||
# 不会取消正在进行的构建(因为 cancel-in-progress 只影响同 group 的后续任务)
|
||||
concurrency:
|
||||
# 使用不同的 group 策略:
|
||||
# - pull_request_target: 使用 PR 号
|
||||
# - issue_comment: 只有确认是 /build 命令时才使用 PR 号,否则使用 run_id(不冲突)
|
||||
group: pr-build-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# =============================================================================
|
||||
# 任务定义
|
||||
# =============================================================================
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 1: 检查构建条件
|
||||
# ---------------------------------------------------------------------------
|
||||
# 判断是否应该触发构建:
|
||||
# - pull_request_target 事件:总是触发
|
||||
# - issue_comment 事件:检查是否为 /build 命令,且用户有权限
|
||||
# ---------------------------------------------------------------------------
|
||||
check-build:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
should_build: ${{ steps.check.outputs.should_build }} # 是否应该构建
|
||||
pr_number: ${{ steps.check.outputs.pr_number }} # PR 编号
|
||||
pr_sha: ${{ steps.check.outputs.pr_sha }} # PR 最新提交 SHA
|
||||
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }} # PR 源仓库(用于 Fork)
|
||||
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }} # PR 源分支
|
||||
steps:
|
||||
# 仅 checkout 脚本目录,加快速度
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
# 使用 Node.js 24 以支持原生 TypeScript 执行
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 执行检查脚本,判断是否触发构建
|
||||
- name: Check trigger condition
|
||||
id: check
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-check.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 2: 更新评论为"构建中"状态
|
||||
# ---------------------------------------------------------------------------
|
||||
# 在 PR 中创建或更新评论,显示构建正在进行中
|
||||
# ---------------------------------------------------------------------------
|
||||
update-comment-building:
|
||||
needs: check-build
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 更新 PR 评论,显示构建中状态
|
||||
- name: Update building comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-building.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 3: 构建 Framework 包
|
||||
# ---------------------------------------------------------------------------
|
||||
# 执行 napcat-framework 的构建流程
|
||||
# ---------------------------------------------------------------------------
|
||||
build-framework:
|
||||
needs: [check-build, update-comment-building]
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }} # 构建结果:success/failure
|
||||
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
|
||||
version: ${{ steps.version.outputs.version }} # 构建版本号
|
||||
steps:
|
||||
# 【安全】先从 base 分支 checkout 构建脚本
|
||||
# 这样即使 PR 中修改了脚本,也不会被执行
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
|
||||
# 将 PR 代码 checkout 到单独的 workspace 目录
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
ref: ${{ needs.check-build.outputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 获取最新 release tag 并生成版本号
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
# 执行构建,使用 base 分支的脚本处理 workspace 中的代码
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
|
||||
continue-on-error: true # 允许失败,后续更新评论时处理
|
||||
|
||||
# 构建成功时上传产物
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: workspace/framework-dist
|
||||
retention-days: 7 # 保留 7 天
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 4: 构建 Shell 包
|
||||
# ---------------------------------------------------------------------------
|
||||
# 执行 napcat-shell 的构建流程(与 Framework 并行执行)
|
||||
# ---------------------------------------------------------------------------
|
||||
build-shell:
|
||||
needs: [check-build, update-comment-building]
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }} # 构建结果:success/failure
|
||||
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
|
||||
version: ${{ steps.version.outputs.version }} # 构建版本号
|
||||
steps:
|
||||
# 【安全】先从 base 分支 checkout 构建脚本
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
|
||||
# 将 PR 代码 checkout 到单独的 workspace 目录
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
ref: ${{ needs.check-build.outputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 获取最新 release tag 并生成版本号
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
# 执行构建
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts shell
|
||||
continue-on-error: true
|
||||
|
||||
# 构建成功时上传产物
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: workspace/shell-dist
|
||||
retention-days: 7 # 保留 7 天
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 5: 更新评论为构建结果
|
||||
# ---------------------------------------------------------------------------
|
||||
# 汇总所有构建结果,更新 PR 评论显示最终状态
|
||||
# 使用 always() 确保即使构建失败/取消也会执行
|
||||
# ---------------------------------------------------------------------------
|
||||
update-comment-result:
|
||||
needs: [check-build, update-comment-building, build-framework, build-shell]
|
||||
if: always() && needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 更新评论,显示构建结果和下载链接
|
||||
- name: Update result comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
# 构建版本号
|
||||
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
|
||||
# 获取构建状态,如果 job 被跳过则标记为 cancelled
|
||||
FRAMEWORK_STATUS: ${{ needs.build-framework.outputs.status || 'cancelled' }}
|
||||
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
|
||||
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
|
||||
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
|
||||
@@ -0,0 +1,153 @@
|
||||
name: Release Downstream
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag_name:
|
||||
description: 'Release tag name (e.g., v4.10.7)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
env:
|
||||
QQ_URL_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage'
|
||||
QQ_URL_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage'
|
||||
|
||||
jobs:
|
||||
get-version:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
latest_tag: ${{ steps.get_version.outputs.latest_tag }}
|
||||
version: ${{ steps.get_version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v5
|
||||
- name: Get Latest NapCat Version
|
||||
id: get_version
|
||||
run: |
|
||||
if [ -n "${{ inputs.tag_name }}" ]; then
|
||||
latest_tag="${{ inputs.tag_name }}"
|
||||
else
|
||||
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
|
||||
fi
|
||||
version=${latest_tag#v}
|
||||
echo "Debug: Latest NapCat Version is ${latest_tag}, version is ${version}"
|
||||
echo "latest_tag=${latest_tag}" >> $GITHUB_OUTPUT
|
||||
echo "version=${version}" >> $GITHUB_OUTPUT
|
||||
|
||||
publish-schema:
|
||||
needs: get-version
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Install Dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build napcat-schema
|
||||
run: |
|
||||
cd packages/napcat-schema
|
||||
pnpm run build:openapi
|
||||
|
||||
- name: Checkout NapCatDocs
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
repository: NapNeko/NapCatDocs
|
||||
token: ${{ secrets.NAPCAT_BUILD }}
|
||||
path: napcat-docs
|
||||
|
||||
- name: Copy OpenAPI Schema
|
||||
run: |
|
||||
VERSION="${{ needs.get-version.outputs.version }}"
|
||||
mkdir -p napcat-docs/src/api/${VERSION}
|
||||
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${VERSION}/openapi.json
|
||||
echo "OpenAPI schema copied to napcat-docs/src/api/${VERSION}/openapi.json"
|
||||
|
||||
- name: Commit and Push
|
||||
run: |
|
||||
VERSION="${{ needs.get-version.outputs.version }}"
|
||||
cd napcat-docs
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add src/api/${VERSION}/openapi.json
|
||||
git commit -m "chore: update OpenAPI schema for version ${VERSION}" || echo "No changes to commit"
|
||||
git push
|
||||
|
||||
shell-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat-Docker docker-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
|
||||
framework-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat-Framework-Docker docker-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCat.Docker.Framework/actions/workflows/docker-image.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
|
||||
appimage:
|
||||
needs: get-version
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat AppImage build workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
|
||||
run: |
|
||||
echo "Debug: Triggering NapCat AppImage with napcat_version=${NAPCAT_VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatAppImageBuild/actions/workflows/release.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_version_x86_64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_version_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
|
||||
|
||||
node-shell:
|
||||
needs: get-version
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
|
||||
steps:
|
||||
- name: Trigger NapCat NodeLoader release workflow
|
||||
run: |
|
||||
echo "Debug: Triggering NapCat NodeLoader release with napcat_version=${NAPCAT_VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/release.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_url_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
|
||||
|
||||
- name: Trigger NapCat NodeLoader docker workflow
|
||||
run: |
|
||||
echo "Debug: Triggering NapCat NodeLoader docker with napcat_version=${NAPCAT_VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/docker-publish.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_url_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
|
||||
@@ -1,115 +1,73 @@
|
||||
name: Release NapCat
|
||||
name: Release Publish
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
inputs:
|
||||
version:
|
||||
description: 'Release version tag (e.g., v4.10.7)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: write-all
|
||||
|
||||
env:
|
||||
OPENROUTER_API_URL: https://91vip.futureppo.top/v1/chat/completions
|
||||
OPENROUTER_MODEL: "glm-4.7"
|
||||
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
|
||||
OPENAI_MODEL: "z-ai/glm-4.5-air:free"
|
||||
RELEASE_NAME: "NapCat"
|
||||
|
||||
jobs:
|
||||
# 验证版本号格式
|
||||
validate-version:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
valid: ${{ steps.check.outputs.valid }}
|
||||
version: ${{ steps.check.outputs.version }}
|
||||
steps:
|
||||
- name: Validate semantic version
|
||||
id: check
|
||||
run: |
|
||||
TAG="${GITHUB_REF#refs/tags/}"
|
||||
echo "Checking tag: $TAG"
|
||||
|
||||
# 语义化版本正则表达式
|
||||
# 支持: v1.0.0, v1.0.0-beta, v1.0.0-rc.1, v1.0.0-alpha.1+build.123
|
||||
SEMVER_REGEX="^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?$"
|
||||
|
||||
if [[ "$TAG" =~ $SEMVER_REGEX ]]; then
|
||||
echo "✅ Valid semantic version: $TAG"
|
||||
echo "valid=true" >> $GITHUB_OUTPUT
|
||||
echo "version=$TAG" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "❌ Invalid version format: $TAG"
|
||||
echo "Expected format: vX.Y.Z or vX.Y.Z-prerelease"
|
||||
echo "Examples: v1.0.0, v1.2.3-beta, v2.0.0-rc.1"
|
||||
echo "valid=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
|
||||
Build-Framework:
|
||||
needs: validate-version
|
||||
if: needs.validate-version.outputs.valid == 'true'
|
||||
build:
|
||||
name: Build NapCat.${{ matrix.target.name }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target:
|
||||
- name: Framework
|
||||
build_cmd: build:framework
|
||||
src_dir: packages/napcat-framework/dist
|
||||
dist_dir: framework-dist
|
||||
- name: Shell
|
||||
build_cmd: build:shell
|
||||
src_dir: packages/napcat-shell/dist
|
||||
dist_dir: shell-dist
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Use Node.js 20.X
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ inputs.version }}
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Build NapCat.Framework
|
||||
- name: Build NapCat.${{ matrix.target.name }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run build:framework
|
||||
pnpm run ${{ matrix.target.build_cmd }}
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv packages/napcat-framework/dist framework-dist
|
||||
cd framework-dist
|
||||
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
|
||||
cd ${{ matrix.target.dist_dir }}
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: framework-dist
|
||||
name: NapCat.${{ matrix.target.name }}
|
||||
path: ${{ matrix.target.dist_dir }}
|
||||
|
||||
Build-Shell:
|
||||
needs: validate-version
|
||||
if: needs.validate-version.outputs.valid == 'true'
|
||||
assemble-windows-node:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Use Node.js 20.X
|
||||
uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Build NapCat.Shell
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run build:shell
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv packages/napcat-shell/dist shell-dist
|
||||
cd shell-dist
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: shell-dist
|
||||
Download-QNX64:
|
||||
needs: Build-Shell
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
ref: ${{ inputs.version }}
|
||||
|
||||
- name: Download Artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
path: ./artifacts
|
||||
|
||||
@@ -118,35 +76,48 @@ jobs:
|
||||
sudo apt update
|
||||
sudo apt install -y aria2 unzip zip p7zip-full curl jq
|
||||
|
||||
- name: Download and Assemble NapCat.Shell.Windows.Node.zip
|
||||
- name: Cache QQ and Node.js downloads
|
||||
id: cache-downloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: /tmp/napcat-downloads
|
||||
key: napcat-downloads-qq9.9.27.45627-node22.11.0
|
||||
|
||||
- name: Download QQ and Node.js
|
||||
if: steps.cache-downloads.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p /tmp/napcat-downloads
|
||||
cd /tmp/napcat-downloads
|
||||
|
||||
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
|
||||
echo "Downloading QQ installer..."
|
||||
aria2c -x16 -s16 -k1M -o "QQ_x64.exe" "$NT_URL"
|
||||
|
||||
NODE_VER="22.11.0"
|
||||
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
|
||||
echo "Downloading Node.js $NODE_VER..."
|
||||
aria2c -x1 -s1 -k1M -o "node-win-x64.zip" "$NODE_URL"
|
||||
|
||||
- name: Assemble NapCat.Shell.Windows.Node.zip
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TMPDIR=$(mktemp -d)
|
||||
cd "$TMPDIR"
|
||||
CACHE_DIR="/tmp/napcat-downloads"
|
||||
|
||||
# -----------------------------
|
||||
# 1) 下载 QQ x64
|
||||
# 1) 解压 QQ x64
|
||||
# -----------------------------
|
||||
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
|
||||
QQ_ZIP="$(basename "$NT_URL")"
|
||||
echo "Downloading QQ installer: $QQ_ZIP"
|
||||
aria2c -x16 -s16 -k1M -o "$QQ_ZIP" "$NT_URL"
|
||||
|
||||
QQ_EXTRACT="$TMPDIR/qq_extracted"
|
||||
mkdir -p "$QQ_EXTRACT"
|
||||
7z x -y -o"$QQ_EXTRACT" "$QQ_ZIP" >/dev/null
|
||||
7z x -y -o"$QQ_EXTRACT" "$CACHE_DIR/QQ_x64.exe" >/dev/null
|
||||
|
||||
# -----------------------------
|
||||
# 2) 下载 Node.js Windows x64 zip 22.11.0
|
||||
# 2) 解压 Node.js Windows x64
|
||||
# -----------------------------
|
||||
NODE_VER="22.11.0"
|
||||
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
|
||||
NODE_ZIP="node-v$NODE_VER-win-x64.zip"
|
||||
aria2c -x1 -s1 -k1M -o "$NODE_ZIP" "$NODE_URL"
|
||||
|
||||
NODE_EXTRACT="$TMPDIR/node_extracted"
|
||||
mkdir -p "$NODE_EXTRACT"
|
||||
unzip -q "$NODE_ZIP" -d "$NODE_EXTRACT"
|
||||
unzip -q "$CACHE_DIR/node-win-x64.zip" -d "$NODE_EXTRACT"
|
||||
|
||||
# -----------------------------
|
||||
# 3) 创建输出目录
|
||||
@@ -180,6 +151,7 @@ jobs:
|
||||
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/napcat.bat" "$OUT_DIR/" || true
|
||||
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/index.js" "$OUT_DIR/" || true
|
||||
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/QQNT.dll" "$OUT_DIR/" || true
|
||||
|
||||
# -----------------------------
|
||||
# 7) 拷贝 Node.exe 到 NapCat.Shell.Windows.Node
|
||||
# -----------------------------
|
||||
@@ -187,22 +159,22 @@ jobs:
|
||||
cp -a "$NODE_EXTRACT/node-v$NODE_VER-win-x64/node.exe" "$OUT_DIR/" || true
|
||||
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Shell.Windows.Node
|
||||
path: NapCat.Shell.Windows.Node
|
||||
|
||||
release-napcat:
|
||||
needs: [Build-Framework, Build-Shell, Download-QNX64]
|
||||
needs: [build, assemble-windows-node]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download Artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
path: ./artifacts
|
||||
|
||||
@@ -218,18 +190,18 @@ jobs:
|
||||
[ -d NapCat.Shell.Windows.Node ] && (cd NapCat.Shell.Windows.Node && zip -qr ../../NapCat.Shell.Windows.Node.zip .)
|
||||
cd ..
|
||||
|
||||
- name: Generate release note via OpenRouter
|
||||
- name: Generate release note
|
||||
env:
|
||||
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
|
||||
OPENROUTER_API_URL: ${{ env.OPENROUTER_API_URL }}
|
||||
OPENROUTER_MODEL: ${{ env.OPENROUTER_MODEL }}
|
||||
GITHUB_OWNER: "NapNeko" # 替换成你的 repo owner
|
||||
GITHUB_REPO: "NapCatQQ" # 替换成你的 repo 名
|
||||
OPENAI_API_URL: ${{ env.OPENAI_API_URL }}
|
||||
OPENAI_MODEL: ${{ env.OPENAI_MODEL }}
|
||||
GITHUB_OWNER: "NapNeko"
|
||||
GITHUB_REPO: "NapCatQQ"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# 当前 tag
|
||||
CURRENT_TAG="${GITHUB_REF#refs/tags/}"
|
||||
CURRENT_TAG="${{ inputs.version }}"
|
||||
echo "Current tag: $CURRENT_TAG"
|
||||
|
||||
# 从 GitHub API 获取 tag 列表
|
||||
@@ -248,7 +220,7 @@ jobs:
|
||||
done
|
||||
|
||||
if [ -z "$PREV_TAG" ]; then
|
||||
echo "⚠️ Could not find previous tag for $CURRENT_TAG, using first commit"
|
||||
echo "Could not find previous tag for $CURRENT_TAG, using first commit"
|
||||
PREV_TAG=$(git rev-list --max-parents=0 HEAD | head -1)
|
||||
fi
|
||||
|
||||
@@ -259,7 +231,6 @@ jobs:
|
||||
git fetch origin "refs/tags/$CURRENT_TAG:refs/tags/$CURRENT_TAG" --force || true
|
||||
|
||||
# 获取 commit,使用更清晰的格式
|
||||
# 格式: <type>: <subject> (<hash>)
|
||||
COMMITS=$(git log --pretty=format:'- %s (%h)' "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || git log --pretty=format:'- %s (%h)' -20)
|
||||
|
||||
echo "Commit list from $PREV_TAG to $CURRENT_TAG:"
|
||||
@@ -268,15 +239,15 @@ jobs:
|
||||
# 获取文件变化统计
|
||||
echo "Getting file change statistics..."
|
||||
FILE_STATS=$(git diff --stat "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || echo "")
|
||||
|
||||
|
||||
# 获取总体统计(最后一行)
|
||||
SUMMARY_LINE=$(echo "$FILE_STATS" | tail -1)
|
||||
echo "Summary: $SUMMARY_LINE"
|
||||
|
||||
|
||||
# 获取每个文件的变化(去掉最后一行汇总)
|
||||
# 截断过长的输出(最多50个文件,每行最多80字符)
|
||||
FILE_CHANGES=$(echo "$FILE_STATS" | head -n -1 | head -50 | cut -c1-80)
|
||||
|
||||
|
||||
# 如果文件变化太多,进一步精简:只保留主要目录的变化
|
||||
FILE_COUNT=$(echo "$FILE_STATS" | head -n -1 | wc -l)
|
||||
if [ "$FILE_COUNT" -gt 50 ]; then
|
||||
@@ -289,28 +260,27 @@ jobs:
|
||||
FILE_CHANGES="[按目录分组统计 - 共 $FILE_COUNT 个文件变更]
|
||||
$DIR_STATS"
|
||||
fi
|
||||
|
||||
|
||||
echo "File changes:"
|
||||
echo "$FILE_CHANGES"
|
||||
|
||||
# 获取具体代码变化(关键文件的diff)
|
||||
echo "Getting code diff for key files..."
|
||||
|
||||
|
||||
# 定义关键目录(优先展示这些目录的变化)
|
||||
KEY_DIRS="packages/napcat-core packages/napcat-onebot packages/napcat-webui-backend"
|
||||
|
||||
|
||||
# 获取变更的关键文件列表(排除测试、配置等)
|
||||
# 使用 || true 防止 grep 无匹配时返回非零退出码
|
||||
KEY_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
|
||||
grep -E "^packages/napcat-(core|onebot|webui-backend|shell)/" || true | \
|
||||
grep -E "\.(ts|js)$" || true | \
|
||||
grep -v -E "(test|spec|\.d\.ts|config)" || true | \
|
||||
head -15) || true
|
||||
|
||||
|
||||
CODE_DIFF=""
|
||||
DIFF_CHAR_LIMIT=6000 # 总diff字符限制
|
||||
DIFF_CHAR_LIMIT=6000
|
||||
CURRENT_CHARS=0
|
||||
|
||||
|
||||
if [ -n "$KEY_FILES" ]; then
|
||||
for file in $KEY_FILES; do
|
||||
if [ "$CURRENT_CHARS" -ge "$DIFF_CHAR_LIMIT" ]; then
|
||||
@@ -318,21 +288,19 @@ jobs:
|
||||
[... 更多文件变化已截断 ...]"
|
||||
break
|
||||
fi
|
||||
|
||||
# 获取单个文件的diff,限制每个文件最多50行
|
||||
|
||||
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -50) || true
|
||||
FILE_DIFF_LEN=${#FILE_DIFF}
|
||||
|
||||
# 如果单个文件diff超过1500字符,截断
|
||||
|
||||
if [ "$FILE_DIFF_LEN" -gt 1500 ]; then
|
||||
FILE_DIFF=$(echo "$FILE_DIFF" | head -c 1500)
|
||||
FILE_DIFF="$FILE_DIFF
|
||||
[... 文件 $file 变化已截断 ...]"
|
||||
fi
|
||||
|
||||
|
||||
if [ -n "$FILE_DIFF" ]; then
|
||||
CODE_DIFF="$CODE_DIFF
|
||||
|
||||
|
||||
### $file
|
||||
\`\`\`diff
|
||||
$FILE_DIFF
|
||||
@@ -341,19 +309,19 @@ jobs:
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# 如果没有关键文件变化,获取前5个变更文件的diff
|
||||
if [ -z "$CODE_DIFF" ]; then
|
||||
echo "No key files changed, getting top changed files..."
|
||||
TOP_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
|
||||
grep -E "\.(ts|js|yml|md)$" | head -5) || true
|
||||
|
||||
|
||||
if [ -n "$TOP_FILES" ]; then
|
||||
for file in $TOP_FILES; do
|
||||
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -30) || true
|
||||
if [ -n "$FILE_DIFF" ] && [ ${#FILE_DIFF} -lt 1000 ]; then
|
||||
CODE_DIFF="$CODE_DIFF
|
||||
|
||||
|
||||
### $file
|
||||
\`\`\`diff
|
||||
$FILE_DIFF
|
||||
@@ -362,12 +330,12 @@ jobs:
|
||||
done
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
# 如果仍然没有代码变化,添加说明
|
||||
if [ -z "$CODE_DIFF" ]; then
|
||||
CODE_DIFF="[本次更新主要涉及配置文件和文档变更,无核心代码变化]"
|
||||
fi
|
||||
|
||||
|
||||
echo "Code diff preview:"
|
||||
echo "$CODE_DIFF" | head -50
|
||||
|
||||
@@ -378,16 +346,16 @@ jobs:
|
||||
# 构建用户内容,传递更多上下文(包含文件变化和代码diff)
|
||||
USER_CONTENT="当前版本: $CURRENT_TAG
|
||||
上一版本: $PREV_TAG
|
||||
|
||||
|
||||
## 提交列表
|
||||
$COMMITS
|
||||
|
||||
|
||||
## 文件变化统计
|
||||
$SUMMARY_LINE
|
||||
|
||||
|
||||
## 变更文件列表
|
||||
$FILE_CHANGES
|
||||
|
||||
|
||||
## 关键代码变化
|
||||
$CODE_DIFF"
|
||||
|
||||
@@ -395,20 +363,19 @@ jobs:
|
||||
BODY=$(jq -n \
|
||||
--arg system "$SYSTEM_PROMPT" \
|
||||
--arg user "$USER_CONTENT" \
|
||||
--arg model "$OPENROUTER_MODEL" \
|
||||
'{model: $model, messages:[{role:"system", content:$system},{role:"user", content:$user}], temperature:0.2, max_tokens:1500}')
|
||||
--arg model "$OPENAI_MODEL" \
|
||||
'{model: $model, messages:[{role:"system", content:$system},{role:"user", content:$user}], temperature:0.2, max_tokens:5000}')
|
||||
|
||||
echo "=== OpenRouter request body ==="
|
||||
echo "=== request body ==="
|
||||
echo "$BODY" | jq .
|
||||
|
||||
# 调用 OpenRouter
|
||||
if RESPONSE=$(curl -s -X POST "$OPENROUTER_API_URL" \
|
||||
if RESPONSE=$(curl -s -X POST "$OPENAI_API_URL" \
|
||||
-H "Authorization: Bearer $OPENAI_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$BODY"); then
|
||||
echo "=== raw response ==="
|
||||
echo "$RESPONSE"
|
||||
echo "=== OpenRouter raw response ==="
|
||||
echo "$RESPONSE"
|
||||
echo "=== parsed response ==="
|
||||
if echo "$RESPONSE" | jq . >/dev/null 2>&1; then
|
||||
echo "$RESPONSE" | jq .
|
||||
else
|
||||
@@ -419,37 +386,34 @@ jobs:
|
||||
RELEASE_BODY=$(echo "$RESPONSE" | jq -r '.choices[0].message.content // .choices[0].text // ""' 2>/dev/null || echo "")
|
||||
|
||||
if [ -z "$RELEASE_BODY" ]; then
|
||||
echo "❌ OpenRouter failed to generate release note, using default.md"
|
||||
# 替换默认模板中的版本占位符
|
||||
echo "LLM failed to generate release note, using default.md"
|
||||
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
|
||||
else
|
||||
# 后处理:确保版本号正确,并添加比较链接
|
||||
echo -e "$RELEASE_BODY" > CHANGELOG.md
|
||||
# 替换可能的占位符
|
||||
sed -i "s/{VERSION}/$CURRENT_TAG/g" CHANGELOG.md
|
||||
sed -i "s/{PREV_VERSION}/$PREV_TAG/g" CHANGELOG.md
|
||||
fi
|
||||
else
|
||||
echo "❌ Curl failed, using default.md"
|
||||
echo "Curl failed, using default.md"
|
||||
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
|
||||
fi
|
||||
echo "=== generated release note ==="
|
||||
cat CHANGELOG.md
|
||||
|
||||
- name: Create Release Draft and Upload Artifacts
|
||||
uses: softprops/action-gh-release@v1
|
||||
- name: Create Release and Upload Artifacts
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
name: NapCat ${{ github.ref_name }}
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag_name: ${{ inputs.version }}
|
||||
name: NapCat ${{ inputs.version }}
|
||||
body_path: CHANGELOG.md
|
||||
files: |
|
||||
NapCat.Shell.Windows.Node.zip
|
||||
NapCat.Framework.zip
|
||||
NapCat.Shell.zip
|
||||
NapCat.Shell.Windows.OneKey.zip
|
||||
draft: true
|
||||
draft: false
|
||||
|
||||
|
||||
- name: Update apifox
|
||||
env:
|
||||
APIFOX_TOKEN: ${{ secrets.APIFOX_TOKEN }}
|
||||
@@ -458,7 +422,6 @@ jobs:
|
||||
pnpm i
|
||||
pnpm run build:openapi
|
||||
|
||||
# 使用 jq 安全地构建大型 JSON 数据并保存到文件
|
||||
jq -n --rawfile input packages/napcat-schema/dist/openapi.json \
|
||||
'{
|
||||
input: $input,
|
||||
@@ -471,10 +434,48 @@ jobs:
|
||||
}
|
||||
}' > apifox_payload.json
|
||||
|
||||
# 通过文件形式发送数据,避免命令行长度限制
|
||||
curl --location -g --request POST 'https://api.apifox.com/v1/projects/5348325/import-openapi?locale=zh-CN' \
|
||||
--header 'X-Apifox-Api-Version: 2024-03-28' \
|
||||
--header "Authorization: Bearer $APIFOX_TOKEN" \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data-binary @apifox_payload.json
|
||||
|
||||
- name: Publish release hash
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION="${{ inputs.version }}"
|
||||
HASH_REPO="NapNeko/napcat-release-hash"
|
||||
|
||||
gh auth setup-git
|
||||
gh repo clone "$HASH_REPO" hash-repo
|
||||
|
||||
node .github/scripts/publish-release-hash.mjs \
|
||||
--version "$VERSION" \
|
||||
--shell "./artifacts/NapCat.Shell/napcat.mjs" \
|
||||
--framework "./artifacts/NapCat.Framework/napcat.mjs" \
|
||||
--file "./hash-repo/release.json"
|
||||
|
||||
cd hash-repo
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add release.json
|
||||
if git diff --cached --quiet; then
|
||||
echo "No changes to commit"
|
||||
else
|
||||
git commit -m "chore: update release hash for ${VERSION}"
|
||||
git push origin HEAD:main || git push origin HEAD:master
|
||||
fi
|
||||
|
||||
- name: Trigger downstream release workflows
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
echo "Triggering release-downstream workflow with tag_name=${VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/${{ github.repository }}/actions/workflows/release-downstream.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"tag_name\":\"${VERSION}\"}}"
|
||||
@@ -0,0 +1,53 @@
|
||||
name: Release Tag
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions: write-all
|
||||
|
||||
jobs:
|
||||
validate-version:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
valid: ${{ steps.check.outputs.valid }}
|
||||
version: ${{ steps.check.outputs.version }}
|
||||
steps:
|
||||
- name: Validate semantic version
|
||||
id: check
|
||||
run: |
|
||||
TAG="${GITHUB_REF#refs/tags/}"
|
||||
echo "Checking tag: $TAG"
|
||||
|
||||
SEMVER_REGEX="^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?$"
|
||||
|
||||
if [[ "$TAG" =~ $SEMVER_REGEX ]]; then
|
||||
echo "Valid semantic version: $TAG"
|
||||
echo "valid=true" >> $GITHUB_OUTPUT
|
||||
echo "version=$TAG" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "Invalid version format: $TAG"
|
||||
echo "Expected format: vX.Y.Z or vX.Y.Z-prerelease"
|
||||
echo "Examples: v1.0.0, v1.2.3-beta, v2.0.0-rc.1"
|
||||
echo "valid=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
|
||||
trigger-release:
|
||||
needs: [validate-version]
|
||||
if: needs.validate-version.outputs.valid == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger release-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
VERSION: ${{ needs.validate-version.outputs.version }}
|
||||
run: |
|
||||
echo "Triggering release-publish workflow with version=${VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/${{ github.repository }}/actions/workflows/release-publish.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"version\":\"${VERSION}\"}}"
|
||||
Vendored
+1
-1
@@ -6,7 +6,7 @@
|
||||
"vite.config.ts": "vite*.ts",
|
||||
"README.md": "CODE_OF_CONDUCT.md, RELEASES.md, CONTRIBUTING.md, CHANGELOG.md, SECURITY.md",
|
||||
"tsconfig.json": "tsconfig.*.json, env.d.ts",
|
||||
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, manifest.json, logo.png, .gitignore, LICENSE"
|
||||
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, logo.png, .gitignore, LICENSE"
|
||||
},
|
||||
"css.customData": [
|
||||
".vscode/tailwindcss.json"
|
||||
|
||||
@@ -53,7 +53,7 @@ _Modern protocol-side framework implemented based on NTQQ._
|
||||
| Docs | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| QQ Group | [](https://qm.qq.com/q/CMmPbGw0jA) | [](https://qm.qq.com/q/8zJMLjqy2Y) | [](https://qm.qq.com/q/CMmPbGw0jA) | [](https://qm.qq.com/q/I6LU87a0Yq) |
|
||||
| QQ Group | [](https://qm.qq.com/q/E4nfkGD6oK) | [](https://qm.qq.com/q/XyiyGPqa42) | [](https://qm.qq.com/q/gq18RH7o7S) | [](https://qm.qq.com/q/VwpnklcXqo) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
| Telegram | [](https://t.me/napcatqq) |
|
||||
@@ -62,7 +62,11 @@ _Modern protocol-side framework implemented based on NTQQ._
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
> 请不要在其余社区提及本项目(包括其余协议端/相关应用端项目)引发争论,如有建议到达官方交流群讨论或PR。
|
||||
> QQ群因为特殊原因需要入群密钥,请在webui关于页面获取,仅最新的100个版本以内有效。
|
||||
|
||||
下面的QQ Group 无需密钥,随时清理不活跃人员和Bot,仅500人容量。
|
||||
|
||||
[困困猫猫的高中](https://qm.qq.com/q/14aUVclRUA)
|
||||
|
||||
## Thanks
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"ajv": "^8.13.0",
|
||||
"file-type": "^21.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -12,11 +12,12 @@ export interface HttpDownloadOptions {
|
||||
proxy?: string;
|
||||
}
|
||||
|
||||
type Uri2LocalRes = {
|
||||
export type Uri2LocalRes = {
|
||||
success: boolean,
|
||||
errMsg: string,
|
||||
fileName: string,
|
||||
path: string;
|
||||
isLocal: boolean; // true=用户本地文件(不可删除),false=临时下载/解码文件(需清理)
|
||||
};
|
||||
|
||||
// 定义一个异步函数来检查文件是否存在
|
||||
@@ -151,7 +152,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
|
||||
const isTargetHttps = targetUrl.protocol === 'https:';
|
||||
const proxyPort = parseInt(proxyUrl.port) || (proxyUrl.protocol === 'https:' ? 443 : 80);
|
||||
|
||||
|
||||
// 代理认证头
|
||||
const proxyAuthHeader = proxyUrl.username && proxyUrl.password
|
||||
? { 'Proxy-Authorization': 'Basic ' + Buffer.from(`${decodeURIComponent(proxyUrl.username)}:${decodeURIComponent(proxyUrl.password)}`).toString('base64') }
|
||||
@@ -165,7 +166,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
method: 'CONNECT',
|
||||
path: `${targetUrl.hostname}:${targetUrl.port || 443}`,
|
||||
headers: {
|
||||
'Host': `${targetUrl.hostname}:${targetUrl.port || 443}`,
|
||||
Host: `${targetUrl.hostname}:${targetUrl.port || 443}`,
|
||||
...proxyAuthHeader,
|
||||
},
|
||||
});
|
||||
@@ -179,7 +180,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
|
||||
// 在隧道上建立 TLS 连接
|
||||
const tlsSocket = tls.connect({
|
||||
socket: socket,
|
||||
socket,
|
||||
servername: targetUrl.hostname,
|
||||
rejectUnauthorized: true,
|
||||
}, () => {
|
||||
@@ -187,14 +188,14 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
const requestPath = targetUrl.pathname + targetUrl.search;
|
||||
const requestHeaders = {
|
||||
...headers,
|
||||
'Host': targetUrl.hostname,
|
||||
'Connection': 'close',
|
||||
Host: targetUrl.hostname,
|
||||
Connection: 'close',
|
||||
};
|
||||
|
||||
|
||||
const headerLines = Object.entries(requestHeaders)
|
||||
.map(([key, value]) => `${key}: ${value}`)
|
||||
.join('\r\n');
|
||||
|
||||
|
||||
const httpRequest = `GET ${requestPath} HTTP/1.1\r\n${headerLines}\r\n\r\n`;
|
||||
tlsSocket.write(httpRequest);
|
||||
});
|
||||
@@ -209,19 +210,19 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
|
||||
tlsSocket.on('data', (chunk: Buffer) => {
|
||||
responseData = Buffer.concat([responseData, chunk]);
|
||||
|
||||
|
||||
if (!headersParsed) {
|
||||
const headerEndIndex = responseData.indexOf('\r\n\r\n');
|
||||
if (headerEndIndex !== -1) {
|
||||
headersParsed = true;
|
||||
const headerStr = responseData.subarray(0, headerEndIndex).toString();
|
||||
const headerLines = headerStr.split('\r\n');
|
||||
|
||||
|
||||
// 解析状态码
|
||||
const statusLine = headerLines[0];
|
||||
const statusMatch = statusLine?.match(/HTTP\/\d\.\d\s+(\d+)/);
|
||||
statusCode = statusMatch ? parseInt(statusMatch[1]!) : 0;
|
||||
|
||||
|
||||
// 解析响应头
|
||||
for (const line of headerLines.slice(1)) {
|
||||
const [key, ...valueParts] = line.split(':');
|
||||
@@ -232,7 +233,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
redirectLocation = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bodyData = responseData.subarray(headerEndIndex + 4);
|
||||
}
|
||||
} else {
|
||||
@@ -243,18 +244,18 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
tlsSocket.on('end', () => {
|
||||
// 处理重定向
|
||||
if (statusCode >= 300 && statusCode < 400 && redirectLocation) {
|
||||
const redirectUrl = redirectLocation.startsWith('http')
|
||||
? redirectLocation
|
||||
const redirectUrl = redirectLocation.startsWith('http')
|
||||
? redirectLocation
|
||||
: `${targetUrl.protocol}//${targetUrl.host}${redirectLocation}`;
|
||||
httpDownloadWithProxy(redirectUrl, headers, proxy).then(resolve).catch(reject);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (statusCode !== 200) {
|
||||
reject(new Error(`下载失败: ${statusCode}`));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// 处理 chunked 编码
|
||||
if (isChunked) {
|
||||
resolve(parseChunkedBody(bodyData));
|
||||
@@ -282,7 +283,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
path: url, // 完整 URL
|
||||
headers: {
|
||||
...headers,
|
||||
'Host': targetUrl.hostname,
|
||||
Host: targetUrl.hostname,
|
||||
...proxyAuthHeader,
|
||||
},
|
||||
}, (response) => {
|
||||
@@ -304,26 +305,26 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
function parseChunkedBody (data: Buffer): Buffer {
|
||||
const chunks: Buffer[] = [];
|
||||
let offset = 0;
|
||||
|
||||
|
||||
while (offset < data.length) {
|
||||
// 查找 chunk 大小行的结束
|
||||
const lineEnd = data.indexOf('\r\n', offset);
|
||||
if (lineEnd === -1) break;
|
||||
|
||||
|
||||
const sizeStr = data.subarray(offset, lineEnd).toString().split(';')[0]; // 忽略 chunk 扩展
|
||||
const chunkSize = parseInt(sizeStr!, 16);
|
||||
|
||||
|
||||
if (chunkSize === 0) break; // 最后一个 chunk
|
||||
|
||||
|
||||
const chunkStart = lineEnd + 2;
|
||||
const chunkEnd = chunkStart + chunkSize;
|
||||
|
||||
|
||||
if (chunkEnd > data.length) break;
|
||||
|
||||
|
||||
chunks.push(data.subarray(chunkStart, chunkEnd));
|
||||
offset = chunkEnd + 2; // 跳过 chunk 数据后的 \r\n
|
||||
}
|
||||
|
||||
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
@@ -416,25 +417,24 @@ export async function uriToLocalFile (dir: string, uri: string, filename: string
|
||||
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 };
|
||||
// 直接返回原始路径,不复制,避免不必要的 IO
|
||||
return { success: true, errMsg: '', fileName: localFileName, path: HandledUri, isLocal: true };
|
||||
}
|
||||
|
||||
case FileUriType.Remote: {
|
||||
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {}, proxy });
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath };
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
|
||||
}
|
||||
|
||||
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 };
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
|
||||
}
|
||||
|
||||
default:
|
||||
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' };
|
||||
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '', isLocal: false };
|
||||
}
|
||||
}
|
||||
@@ -253,7 +253,6 @@ export async function getAllTags (mirror?: string): Promise<{ tags: string[], mi
|
||||
return getAllTagsFromMirror('NapNeko', 'NapCatQQ', mirror);
|
||||
}
|
||||
|
||||
|
||||
export async function getLatestTag (mirror?: string): Promise<string> {
|
||||
const { tags } = await getAllTags(mirror);
|
||||
|
||||
|
||||
@@ -21,4 +21,4 @@ export interface ILogWrapper {
|
||||
logWarn (...args: any[]): void;
|
||||
logFatal (...args: any[]): void;
|
||||
logMessage (msg: unknown, selfInfo: unknown): void;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* GitHub 镜像配置模块
|
||||
* 提供统一的镜像源管理,支持复杂网络环境
|
||||
*
|
||||
*
|
||||
* 镜像源测试时间: 2026-01-03
|
||||
* 测试通过: 55/61 完全可用
|
||||
*/
|
||||
@@ -17,7 +17,7 @@ import { PromiseTimer } from './helper';
|
||||
* GitHub 文件加速镜像
|
||||
* 用于加速 release assets 下载
|
||||
* 按延迟排序,优先使用快速镜像
|
||||
*
|
||||
*
|
||||
* 测试时间: 2026-01-03
|
||||
* 镜像支持 301/302 重定向
|
||||
* 懒加载测速:首次使用时自动测速,缓存 30 分钟
|
||||
@@ -74,7 +74,7 @@ export const GITHUB_FILE_MIRRORS = [
|
||||
* GitHub API 镜像
|
||||
* 用于访问 GitHub API(作为备选方案)
|
||||
* 注:优先使用非 API 方法,减少对 API 的依赖
|
||||
*
|
||||
*
|
||||
* 经测试,大部分代理镜像不支持 API 转发
|
||||
* 建议使用 getLatestReleaseTag 等方法避免 API 调用
|
||||
*/
|
||||
@@ -271,8 +271,6 @@ async function performMirrorTest (): Promise<string[]> {
|
||||
.sort((a, b) => a.latency - b.latency)
|
||||
.map(r => r.mirror);
|
||||
|
||||
|
||||
|
||||
// 至少返回原始 URL
|
||||
if (successfulMirrors.length === 0) {
|
||||
return [''];
|
||||
@@ -287,7 +285,6 @@ async function performMirrorTest (): Promise<string[]> {
|
||||
export function clearMirrorCache (): void {
|
||||
cachedFastMirrors = null;
|
||||
cacheTimestamp = 0;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -664,7 +661,7 @@ export function buildReleaseDownloadUrl (
|
||||
|
||||
/**
|
||||
* 获取 GitHub release 信息(优先使用非 API 方法)
|
||||
*
|
||||
*
|
||||
* 策略:
|
||||
* 1. 先通过 git refs 获取 tags
|
||||
* 2. 直接构建下载 URL,不依赖 API
|
||||
@@ -725,7 +722,7 @@ export async function getGitHubRelease (
|
||||
const response = await PromiseTimer(
|
||||
RequestUtil.HttpGetJson<any>(url, 'GET', undefined, {
|
||||
'User-Agent': 'NapCat',
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
Accept: 'application/vnd.github.v3+json',
|
||||
}),
|
||||
currentConfig.timeout
|
||||
);
|
||||
@@ -958,7 +955,7 @@ async function getWorkflowRunsFromHtml (
|
||||
allRuns.push({
|
||||
id,
|
||||
created_at: timeMatch[1],
|
||||
title: title.trim()
|
||||
title: title.trim(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -994,7 +991,7 @@ async function getWorkflowRunsFromHtml (
|
||||
/**
|
||||
* 通过 API 获取最新的 workflow runs,然后直接拼接 nightly.link 下载链接
|
||||
* 无需解析 HTML,直接使用固定的 URL 格式
|
||||
*
|
||||
*
|
||||
* 策略:
|
||||
* 1. 优先使用 GitHub API
|
||||
* 2. API 失败时,从 GitHub Actions HTML 页面解析
|
||||
@@ -1042,7 +1039,6 @@ async function getArtifactsFromNightlyLink (
|
||||
}
|
||||
}
|
||||
return { artifacts, mirror: runsMirror };
|
||||
|
||||
} catch {
|
||||
return { artifacts: [], mirror: '' };
|
||||
}
|
||||
@@ -1051,7 +1047,7 @@ async function getArtifactsFromNightlyLink (
|
||||
/**
|
||||
* 获取 GitHub Action 最新运行的 artifacts
|
||||
* 用于下载 nightly/dev 版本
|
||||
*
|
||||
*
|
||||
* 策略:
|
||||
* 1. 检查缓存(10分钟有效)
|
||||
* 2. 优先尝试从 nightly.link 获取(无需认证,更稳定)
|
||||
|
||||
@@ -3,4 +3,4 @@ export interface ISubscription {
|
||||
subscribe (listener: LogListener): void;
|
||||
unsubscribe (listener: LogListener): void;
|
||||
notify (msg: string): void;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": [
|
||||
"ES2021"
|
||||
],
|
||||
@@ -34,10 +34,15 @@
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"resolveJsonModule": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"napcat-common/src/*": [
|
||||
"../../packages/napcat-common/src/*"
|
||||
],
|
||||
"napcat-image-size/src/*": [
|
||||
"../../packages/napcat-image-size/src/*"
|
||||
],
|
||||
"@/*": [
|
||||
"../*"
|
||||
"../../packages/*"
|
||||
]
|
||||
},
|
||||
"skipLibCheck": true,
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import path from 'node:path';
|
||||
import { InstanceContext, NapCatCore } from '@/napcat-core/index';
|
||||
import {
|
||||
checkSqliteAvailable,
|
||||
DatabaseHandle,
|
||||
openDatabase,
|
||||
decryptAndOpen,
|
||||
readSingleDatabase,
|
||||
scanAllDatabases,
|
||||
formatScanResults,
|
||||
decryptDatabaseFile,
|
||||
type DatabaseScanResult,
|
||||
type DatabaseReadOptions,
|
||||
type TableInfo,
|
||||
} from 'napcat-database';
|
||||
|
||||
type SQLInputValue = import('node:sqlite').SQLInputValue;
|
||||
|
||||
export class NTQQDatabaseApi {
|
||||
context: InstanceContext;
|
||||
core: NapCatCore;
|
||||
|
||||
constructor (context: InstanceContext, core: NapCatCore) {
|
||||
this.context = context;
|
||||
this.core = core;
|
||||
}
|
||||
|
||||
/** node:sqlite 是否可用 */
|
||||
async isSqliteAvailable (): Promise<boolean> {
|
||||
return checkSqliteAvailable();
|
||||
}
|
||||
|
||||
/** 获取当前账号的 nt_db 目录 */
|
||||
getNtDbDir (): string {
|
||||
return path.resolve(this.core.dataPath, this.core.selfInfo.uin, 'nt_qq', 'nt_db');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取解密缓存目录
|
||||
* 默认: <NapCatDataPath>/db_<uin>/
|
||||
* 可通过 customDir 完全自定义
|
||||
*/
|
||||
getDefaultCacheDir (customDir?: string): string {
|
||||
if (customDir) return customDir;
|
||||
return path.resolve(this.core.NapCatDataPath, `db_${this.core.selfInfo.uin}`);
|
||||
}
|
||||
|
||||
/** 当前是否已获取到数据库 passphrase */
|
||||
hasPassphrase (): boolean {
|
||||
return !!this.core.dbPassphrase;
|
||||
}
|
||||
|
||||
/** 获取 passphrase Buffer,未获取时返回 null */
|
||||
getPassphraseBuffer (): Buffer | null {
|
||||
return this.core.dbPassphrase ? Buffer.from(this.core.dbPassphrase) : null;
|
||||
}
|
||||
|
||||
// ======================== SQLite 数据库操作 ========================
|
||||
|
||||
/**
|
||||
* 打开一个已解密的 SQLite 数据库文件
|
||||
* @param filePath 解密后 .db 文件路径
|
||||
* @param readOnly 是否只读 (默认 true)
|
||||
* @returns DatabaseHandle 实例,使用完毕后需调用 .close()
|
||||
*/
|
||||
openDecryptedDb (filePath: string, readOnly = true): DatabaseHandle {
|
||||
return openDatabase(filePath, readOnly);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密并打开一个 NTQQ 加密数据库
|
||||
* @param dbName 数据库文件名 (如 'nt_msg.db') 或完整路径
|
||||
* @param readOnly 是否只读 (默认 true)
|
||||
* @param cacheDir 自定义缓存目录,默认 db_<uin>
|
||||
* @returns DatabaseHandle 实例,使用完毕后需调用 .close()
|
||||
*/
|
||||
openDatabase (dbName: string, readOnly = true, cacheDir?: string): DatabaseHandle | null {
|
||||
const passphrase = this.getPassphraseBuffer();
|
||||
if (!passphrase) return null;
|
||||
|
||||
const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName);
|
||||
const resolvedCacheDir = this.getDefaultCacheDir(cacheDir);
|
||||
|
||||
return decryptAndOpen(dbPath, passphrase, resolvedCacheDir, readOnly);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对加密数据库执行查询并自动关闭连接
|
||||
* @param dbName 数据库文件名或完整路径
|
||||
* @param sql SQL 查询语句
|
||||
* @param params 绑定参数
|
||||
* @returns 查询结果行数组,passphrase 不可用时返回 null
|
||||
*/
|
||||
query<T = Record<string, unknown>> (
|
||||
dbName: string,
|
||||
sql: string,
|
||||
params?: SQLInputValue[] | Record<string, SQLInputValue>
|
||||
): T[] | null {
|
||||
const db = this.openDatabase(dbName);
|
||||
if (!db) return null;
|
||||
try {
|
||||
return db.query<T>(sql, params);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 对加密数据库执行查询,仅返回第一行
|
||||
* @param dbName 数据库文件名或完整路径
|
||||
* @param sql SQL 查询语句
|
||||
* @param params 绑定参数
|
||||
*/
|
||||
queryOne<T = Record<string, unknown>> (
|
||||
dbName: string,
|
||||
sql: string,
|
||||
params?: SQLInputValue[] | Record<string, SQLInputValue>
|
||||
): T | undefined | null {
|
||||
const db = this.openDatabase(dbName);
|
||||
if (!db) return null;
|
||||
try {
|
||||
return db.queryOne<T>(sql, params);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 对加密数据库执行非查询 SQL (INSERT/UPDATE/DELETE 等) 并自动关闭
|
||||
* @param dbName 数据库文件名或完整路径
|
||||
* @param sql SQL 语句
|
||||
* @param params 绑定参数
|
||||
*/
|
||||
execute (
|
||||
dbName: string,
|
||||
sql: string,
|
||||
params?: SQLInputValue[] | Record<string, SQLInputValue>
|
||||
): { changes: number | bigint; lastInsertRowid: number | bigint; } | null {
|
||||
const db = this.openDatabase(dbName, false);
|
||||
if (!db) return null;
|
||||
try {
|
||||
return db.execute(sql, params);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
// ======================== 批量扫描 ========================
|
||||
|
||||
/**
|
||||
* 读取单个加密数据库的表信息
|
||||
* @param dbName 数据库文件名 (如 'nt_msg.db'),或完整路径
|
||||
* @param cacheDir 自定义缓存目录,默认 db_<uin>
|
||||
* @param options 其他选项
|
||||
*/
|
||||
readDatabase (dbName: string, cacheDir?: string, options?: Omit<DatabaseReadOptions, 'cacheDir'>): DatabaseScanResult | null {
|
||||
const passphrase = this.getPassphraseBuffer();
|
||||
if (!passphrase) return null;
|
||||
|
||||
const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName);
|
||||
const resolvedCacheDir = this.getDefaultCacheDir(cacheDir);
|
||||
|
||||
return readSingleDatabase(dbPath, passphrase, { cacheDir: resolvedCacheDir, ...options });
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描所有加密数据库
|
||||
* @param cacheDir 自定义缓存目录,默认 db_<uin>
|
||||
* @param options 其他选项
|
||||
*/
|
||||
scanDatabases (cacheDir?: string, options?: Omit<DatabaseReadOptions, 'cacheDir'>): DatabaseScanResult[] {
|
||||
const passphrase = this.getPassphraseBuffer();
|
||||
if (!passphrase) return [];
|
||||
|
||||
const resolvedCacheDir = this.getDefaultCacheDir(cacheDir);
|
||||
return scanAllDatabases(this.getNtDbDir(), passphrase, { cacheDir: resolvedCacheDir, ...options });
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅解密数据库文件(不读取表信息,不需要 node:sqlite)
|
||||
* @param dbName 数据库文件名或完整路径
|
||||
* @param outputPath 输出路径,默认保存到 db_<uin>/<dbName>
|
||||
*/
|
||||
decryptDatabase (dbName: string, outputPath?: string): string | null {
|
||||
const passphrase = this.getPassphraseBuffer();
|
||||
if (!passphrase) return null;
|
||||
|
||||
const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName);
|
||||
const outPath = outputPath ?? path.resolve(this.getDefaultCacheDir(), path.basename(dbName));
|
||||
|
||||
return decryptDatabaseFile(dbPath, passphrase, outPath);
|
||||
}
|
||||
|
||||
/** 格式化扫描结果为可读字符串 */
|
||||
formatResults (results: DatabaseScanResult[]): string {
|
||||
return formatScanResults(results);
|
||||
}
|
||||
}
|
||||
|
||||
export { DatabaseHandle };
|
||||
export type { DatabaseScanResult, DatabaseReadOptions, TableInfo };
|
||||
@@ -33,7 +33,7 @@ export class NTQQFileApi {
|
||||
'http://ss.xingzhige.com/music_card/rkey',
|
||||
'https://secret-service.bietiaop.com/rkeys',
|
||||
],
|
||||
this.context.logger
|
||||
this.context.logger
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -24,12 +24,28 @@ export class NTQQGroupApi {
|
||||
core: NapCatCore;
|
||||
groupMemberCache: Map<string, Map<string, GroupMember>> = new Map<string, Map<string, GroupMember>>();
|
||||
essenceLRU = new LimitedHashTable<number, string>(1000);
|
||||
// psKey 滑动缓存,TTL 60 秒,惰性删除(不主动清理,等下次访问检测到过期再刷新)
|
||||
private _qunPskeyCache: { value: string; expireAt: number; } | null = null;
|
||||
|
||||
constructor (context: InstanceContext, core: NapCatCore) {
|
||||
this.context = context;
|
||||
this.core = core;
|
||||
}
|
||||
|
||||
/** 获取 qun.qq.com 域名的 psKey,滑动 TTL 60 秒(每次访问顺延) */
|
||||
private async getQunPskey (): Promise<string> {
|
||||
const now = Date.now();
|
||||
if (this._qunPskeyCache && this._qunPskeyCache.expireAt > now) {
|
||||
// 滑动 TTL:每次访问都顺延过期时间
|
||||
this._qunPskeyCache.expireAt = now + 60 * 1000;
|
||||
return this._qunPskeyCache.value;
|
||||
}
|
||||
// 过期或为空,惰性删除旧值(直接覆盖)并重新获取
|
||||
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
this._qunPskeyCache = { value: psKey, expireAt: now + 60 * 1000 };
|
||||
return psKey;
|
||||
}
|
||||
|
||||
async setGroupRemark (groupCode: string, remark: string) {
|
||||
return this.context.session.getGroupService().modifyGroupRemark(groupCode, remark);
|
||||
}
|
||||
@@ -75,7 +91,7 @@ export class NTQQGroupApi {
|
||||
}
|
||||
|
||||
async fetchGroupEssenceList (groupCode: string) {
|
||||
const pskey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
const pskey = await this.getQunPskey();
|
||||
return this.context.session.getGroupService().fetchGroupEssenceList({
|
||||
groupCode,
|
||||
pageStart: 0,
|
||||
@@ -319,7 +335,7 @@ export class NTQQGroupApi {
|
||||
}
|
||||
|
||||
async deleteGroupBulletin (groupCode: string, noticeId: string) {
|
||||
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
const psKey = await this.getQunPskey();
|
||||
return this.context.session.getGroupService().deleteGroupBulletin(groupCode, psKey, noticeId);
|
||||
}
|
||||
|
||||
@@ -423,7 +439,7 @@ export class NTQQGroupApi {
|
||||
}
|
||||
|
||||
async uploadGroupBulletinPic (groupCode: string, imageurl: string) {
|
||||
const _Pskey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
const _Pskey = await this.getQunPskey();
|
||||
return this.context.session.getGroupService().uploadGroupBulletinPic(groupCode, _Pskey, imageurl);
|
||||
}
|
||||
|
||||
@@ -466,8 +482,8 @@ export class NTQQGroupApi {
|
||||
return this.context.session.getGroupService().modifyMemberRole(groupCode, memberUid, role);
|
||||
}
|
||||
|
||||
async setGroupName (groupCode: string, groupName: string) {
|
||||
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, false);
|
||||
async setGroupName (groupCode: string, groupName: string, isNormalMember: boolean = false) {
|
||||
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, isNormalMember);
|
||||
}
|
||||
|
||||
async publishGroupBulletin (groupCode: string, content: string, picInfo: {
|
||||
@@ -475,7 +491,7 @@ export class NTQQGroupApi {
|
||||
width: number,
|
||||
height: number;
|
||||
} | undefined = undefined, pinned: number = 0, confirmRequired: number = 0) {
|
||||
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com');
|
||||
const psKey = await this.getQunPskey();
|
||||
// text是content内容url编码
|
||||
const data = {
|
||||
text: encodeURI(content),
|
||||
|
||||
@@ -9,3 +9,4 @@ export * from './packet';
|
||||
export * from './file';
|
||||
export * from './online';
|
||||
export * from './flash';
|
||||
export * from './database';
|
||||
@@ -114,7 +114,7 @@ export class NTQQOnlineApi {
|
||||
fileElement: {
|
||||
fileName: actualFolderName,
|
||||
filePath: folderPath,
|
||||
fileSize: "",
|
||||
fileSize: '',
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ export class NTQQPacketApi {
|
||||
this.pkt = new PacketClientSession(this.core);
|
||||
await this.pkt.init(process.pid, table.recv, table.send);
|
||||
try {
|
||||
await this.pkt.operation.FetchRkey(1500);
|
||||
await this.pkt.operation.FetchRkey(3000);
|
||||
} catch (error) {
|
||||
this.logger.logError('测试Packet状态异常', error);
|
||||
return false;
|
||||
|
||||
@@ -164,8 +164,6 @@ export class NTQQWebApi {
|
||||
imgWidth: number = 540,
|
||||
imgHeight: number = 300
|
||||
) {
|
||||
|
||||
|
||||
const cookieObject = await this.core.apis.UserApi.getCookies('qun.qq.com');
|
||||
|
||||
try {
|
||||
@@ -330,10 +328,14 @@ export class NTQQWebApi {
|
||||
return (hash & 0x7FFFFFFF).toString();
|
||||
}
|
||||
|
||||
async getAlbumListByNTQQ (gc: string) {
|
||||
public getBknFromPSKey (psKey: string) {
|
||||
return this.getBknFromSKey(psKey);
|
||||
}
|
||||
|
||||
async getAlbumListByNTQQ (gc: string, attach_info: string = '') {
|
||||
return await this.context.session.getAlbumService().getAlbumList({
|
||||
qun_id: gc,
|
||||
attach_info: '',
|
||||
attach_info,
|
||||
seq: 3331,
|
||||
request_time_line: {
|
||||
request_invoke_time: '0',
|
||||
@@ -477,10 +479,10 @@ export class NTQQWebApi {
|
||||
const client_key = Date.now() * 1000;
|
||||
return await this.context.session.getAlbumService().doQunComment(
|
||||
random_seq, {
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
},
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
},
|
||||
qunId,
|
||||
2,
|
||||
createAlbumMediaFeed(uin, albumId, lloc),
|
||||
@@ -505,20 +507,36 @@ export class NTQQWebApi {
|
||||
async doAlbumMediaLikeByNTQQ (
|
||||
qunId: string,
|
||||
albumId: string,
|
||||
lloc: string,
|
||||
id: string) {
|
||||
batchId: string,
|
||||
lloc: string | undefined,
|
||||
isLike: boolean
|
||||
) {
|
||||
const random_seq = Math.floor(Math.random() * 9000) + 1000;
|
||||
const uin = this.core.selfInfo.uin || '10001';
|
||||
|
||||
const type = isLike ? 2 : 1;
|
||||
const status = isLike ? 0 : 1;
|
||||
|
||||
let id = '';
|
||||
if (lloc) {
|
||||
id = `421_1_0_${qunId}|${albumId}|${batchId}^||^421_1_0_${qunId}|${albumId}|${lloc}^||^0`;
|
||||
} else {
|
||||
id = `421_1_0_${qunId}|${albumId}|${batchId}`;
|
||||
}
|
||||
|
||||
return await this.context.session.getAlbumService().doQunLike(
|
||||
random_seq, {
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
}, {
|
||||
id,
|
||||
status: 1,
|
||||
},
|
||||
createAlbumFeedPublish(qunId, uin, albumId, lloc)
|
||||
random_seq,
|
||||
{
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
},
|
||||
type,
|
||||
{
|
||||
id,
|
||||
status,
|
||||
},
|
||||
createAlbumFeedPublish(qunId, uin, albumId, batchId)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -163,14 +163,14 @@ export interface AlbumFeedLikePublish {
|
||||
};
|
||||
cell_media: {
|
||||
album_id: string;
|
||||
batch_id: number;
|
||||
media_items: Array<{
|
||||
batch_id: string | number;
|
||||
media_items?: {
|
||||
type: number;
|
||||
image: {
|
||||
lloc: string;
|
||||
sloc: string;
|
||||
};
|
||||
}>;
|
||||
}[];
|
||||
};
|
||||
cell_qun_info: {
|
||||
qun_id: string;
|
||||
@@ -182,21 +182,19 @@ export interface AlbumFeedLikePublish {
|
||||
* @param qunId 群号
|
||||
* @param uin 用户QQ号
|
||||
* @param albumId 相册ID
|
||||
* @param lloc 信息
|
||||
* @param sloc 信息(可选,默认与lloc相同)
|
||||
* @param batchId 批次ID
|
||||
* @returns 动态发布请求参数对象
|
||||
*/
|
||||
export function createAlbumFeedPublish (
|
||||
qunId: string,
|
||||
uin: string,
|
||||
albumId: string,
|
||||
lloc: string,
|
||||
sloc?: string
|
||||
): AlbumFeedLikePublish {
|
||||
batchId: string
|
||||
) {
|
||||
return {
|
||||
cell_common: {
|
||||
time: Date.now(),
|
||||
feed_id: '',
|
||||
feed_id: `422_0_${batchId}`, // 需要补全feed_id
|
||||
},
|
||||
cell_user_info: {
|
||||
user: {
|
||||
@@ -205,14 +203,7 @@ export function createAlbumFeedPublish (
|
||||
},
|
||||
cell_media: {
|
||||
album_id: albumId,
|
||||
batch_id: 0,
|
||||
media_items: [{
|
||||
type: 0,
|
||||
image: {
|
||||
lloc,
|
||||
sloc: sloc || lloc,
|
||||
},
|
||||
}],
|
||||
batch_id: batchId,
|
||||
},
|
||||
cell_qun_info: {
|
||||
qun_id: qunId,
|
||||
|
||||
@@ -212,7 +212,7 @@ export enum UploadSceneType {
|
||||
KUPLOADSCENEH5LAUNCHCLIENTSHORTCUTKEYCTRLCV,
|
||||
KUPLOADSCENEAIODRAG,
|
||||
KUPLOADSCENEAIOFILESELECTOR,
|
||||
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV
|
||||
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV,
|
||||
}
|
||||
export interface StartFlashTaskRequests {
|
||||
screen: number; // 1 PC-QQ
|
||||
@@ -237,7 +237,7 @@ export interface StartFlashTaskRequests {
|
||||
}
|
||||
export enum BusiScene {
|
||||
KBUSISCENEINVALID,
|
||||
KBUSISCENEFLASHSCENE
|
||||
KBUSISCENEFLASHSCENE,
|
||||
}
|
||||
export interface FileListInfoRequests {
|
||||
seq: number, // 0
|
||||
@@ -274,7 +274,7 @@ export enum DownloadSceneType {
|
||||
KDOWNLOADSCENELINKOTHERINQQ,
|
||||
KDOWNLOADSCENESCANQRCODE,
|
||||
KDWONLOADSCENEFLASHTRANSFERCENTERCLIENT,
|
||||
KDWONLOADSCENEFLASHTRANSFERCENTERSCHEMA
|
||||
KDWONLOADSCENEFLASHTRANSFERCENTERSCHEMA,
|
||||
}
|
||||
export interface FlashFileSetInfo {
|
||||
fileSetId: string,
|
||||
|
||||
+48
@@ -534,5 +534,53 @@
|
||||
"9.9.27-45758": {
|
||||
"appid": 537340213,
|
||||
"qua": "V1_WIN_NQ_9.9.27_45758_GW_B"
|
||||
},
|
||||
"3.2.26-46494": {
|
||||
"appid": 537345891,
|
||||
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
|
||||
},
|
||||
"9.9.28-46494": {
|
||||
"appid": 537345855,
|
||||
"qua": "V1_WIN_NQ_9.9.28_46494_GW_B"
|
||||
},
|
||||
"6.9.90-46494": {
|
||||
"appid": 537345879,
|
||||
"qua": "V1_MAC_NQ_6.9.90_46494_GW_B"
|
||||
},
|
||||
"3.2.26-46928": {
|
||||
"appid": 537345994,
|
||||
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
|
||||
},
|
||||
"9.9.28-46928": {
|
||||
"appid": 537345957,
|
||||
"qua": "V1_WIN_NQ_9.9.28_46928_GW_B"
|
||||
},
|
||||
"3.2.27-47354": {
|
||||
"appid": 537346908,
|
||||
"qua": "V1_LNX_NQ_3.2.27_47354_GW_B"
|
||||
},
|
||||
"9.9.29-47354": {
|
||||
"appid": 537346872,
|
||||
"qua": "V1_WIN_NQ_9.9.29_47354_GW_B"
|
||||
},
|
||||
"6.9.93-47354": {
|
||||
"appid": 537346896,
|
||||
"qua": "V1_MAC_NQ_6.9.93_47354_GW_B"
|
||||
},
|
||||
"9.9.30-48517": {
|
||||
"appid": 537352474,
|
||||
"qua": "V1_WIN_NQ_9.9.30_48517_GW_B"
|
||||
},
|
||||
"3.2.28-48517": {
|
||||
"appid": 537352510,
|
||||
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
|
||||
},
|
||||
"9.9.30-48762": {
|
||||
"appid": 537352525,
|
||||
"qua": "V1_WIN_NQ_9.9.30_48762_GW_B"
|
||||
},
|
||||
"9.9.31-49599": {
|
||||
"appid": 537355779,
|
||||
"qua": "V1_WIN_NQ_9.9.31_49599_GW_B"
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -5,5 +5,13 @@
|
||||
"consoleLogLevel": "info",
|
||||
"packetBackend": "auto",
|
||||
"packetServer": "",
|
||||
"o3HookMode": 0
|
||||
"o3HookMode": 1,
|
||||
"bypass": {
|
||||
"hook": false,
|
||||
"window": false,
|
||||
"module": false,
|
||||
"process": false,
|
||||
"container": false,
|
||||
"js": false
|
||||
}
|
||||
}
|
||||
+64
@@ -178,5 +178,69 @@
|
||||
"9.9.27-45758-x64": {
|
||||
"send": "0A6A6BC",
|
||||
"recv": "1E87EC1"
|
||||
},
|
||||
"9.9.28-46494-x64": {
|
||||
"send": "0A6D66C",
|
||||
"recv": "1E9890D"
|
||||
},
|
||||
"3.2.26-46494-x64": {
|
||||
"send": "5D30910",
|
||||
"recv": "31814B0"
|
||||
},
|
||||
"3.2.26-46494-arm64": {
|
||||
"send": "3EDC654",
|
||||
"recv": "14A3124"
|
||||
},
|
||||
"3.2.26-46928-x64": {
|
||||
"send": "5D30910",
|
||||
"recv": "31814B0"
|
||||
},
|
||||
"3.2.26-46928-arm64": {
|
||||
"send": "3EDC654",
|
||||
"recv": "14A3124"
|
||||
},
|
||||
"9.9.28-46928-x64": {
|
||||
"send": "0A6D66C",
|
||||
"recv": "1E9890D"
|
||||
},
|
||||
"3.2.27-47354-x64": {
|
||||
"send": "5D38930",
|
||||
"recv": "318D090"
|
||||
},
|
||||
"3.2.27-47354-arm64": {
|
||||
"send": "3EE8B24",
|
||||
"recv": "14D422C"
|
||||
},
|
||||
"9.9.29-47354-x64": {
|
||||
"send": "0A70B3C",
|
||||
"recv": "1EAFD51"
|
||||
},
|
||||
"6.9.93-47354-arm64": {
|
||||
"send": "244066C",
|
||||
"recv": "09BCCF8"
|
||||
},
|
||||
"6.9.93-47354-x64": {
|
||||
"send": "28ADE46",
|
||||
"recv": "0A8FD5A"
|
||||
},
|
||||
"9.9.30-48517-x64": {
|
||||
"send": "0A9B1BC",
|
||||
"recv": "1F0324D"
|
||||
},
|
||||
"3.2.28-48517-x64": {
|
||||
"send": "5E41890",
|
||||
"recv": "3216D10"
|
||||
},
|
||||
"3.2.28-48517-arm64": {
|
||||
"send": "3F9C7E4",
|
||||
"recv": "14E1AA8"
|
||||
},
|
||||
"9.9.30-48762-x64": {
|
||||
"send": "0A9B1BC",
|
||||
"recv": "1F0324D"
|
||||
},
|
||||
"9.9.31-49599-x64": {
|
||||
"send": "0AF885C",
|
||||
"recv": "20058E1"
|
||||
}
|
||||
}
|
||||
+64
@@ -686,5 +686,69 @@
|
||||
"3.2.25-45758-arm64": {
|
||||
"send": "6D6F9A0",
|
||||
"recv": "6D73350"
|
||||
},
|
||||
"3.2.26-46494-x64": {
|
||||
"send": "AB341C0",
|
||||
"recv": "AB37C60"
|
||||
},
|
||||
"9.9.28-46494-x64": {
|
||||
"send": "2E77C20",
|
||||
"recv": "2E7B1A0"
|
||||
},
|
||||
"3.2.26-46494-arm64": {
|
||||
"send": "6DBBBB0",
|
||||
"recv": "6DBF560"
|
||||
},
|
||||
"3.2.26-46928-arm64": {
|
||||
"send": "6DBBBB0",
|
||||
"recv": "6DBF560"
|
||||
},
|
||||
"3.2.26-46928-x64": {
|
||||
"send": "AB341C0",
|
||||
"recv": "AB37C60"
|
||||
},
|
||||
"9.9.28-46928-x64": {
|
||||
"send": "2E77C20",
|
||||
"recv": "2E7B1A0"
|
||||
},
|
||||
"3.2.27-47354-x64": {
|
||||
"send": "AB6A6C0",
|
||||
"recv": "AB6E160"
|
||||
},
|
||||
"3.2.27-47354-arm64": {
|
||||
"send": "6DE1438",
|
||||
"recv": "6DE4DE8"
|
||||
},
|
||||
"9.9.29-47354-x64": {
|
||||
"send": "2E84920",
|
||||
"recv": "2E87EA0"
|
||||
},
|
||||
"6.9.93-47354-arm64": {
|
||||
"send": "3FD1E98",
|
||||
"recv": "3FD47A8"
|
||||
},
|
||||
"6.9.93-47354-x64": {
|
||||
"send": "47CD940",
|
||||
"recv": "47D04F0"
|
||||
},
|
||||
"3.2.28-48517-x64": {
|
||||
"send": "AD7C280",
|
||||
"recv": "AD7FD20"
|
||||
},
|
||||
"9.9.30-48517-x64": {
|
||||
"send": "2F3B960",
|
||||
"recv": "2F3EEE0"
|
||||
},
|
||||
"3.2.28-48517-arm64": {
|
||||
"send": "6F48B70",
|
||||
"recv": "6F4C520"
|
||||
},
|
||||
"9.9.30-48762-x64": {
|
||||
"send": "2F3B960",
|
||||
"recv": "2F3EEE0"
|
||||
},
|
||||
"9.9.31-49599-x64": {
|
||||
"send": "3082C40",
|
||||
"recv": "30861C8"
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ export async function encodeSilk (filePath: string, TEMP_DIR: string, logger: Lo
|
||||
return {
|
||||
converted: true,
|
||||
path: pttPath,
|
||||
duration: duration,
|
||||
duration,
|
||||
};
|
||||
} else {
|
||||
let duration = 0;
|
||||
|
||||
@@ -2,22 +2,24 @@ import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import type { NapCatCore } from '@/napcat-core';
|
||||
import json5 from 'json5';
|
||||
import Ajv, { AnySchema, ValidateFunction } from 'ajv';
|
||||
import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { TSchema } from '@sinclair/typebox';
|
||||
|
||||
export abstract class ConfigBase<T> {
|
||||
name: string;
|
||||
core: NapCatCore;
|
||||
configPath: string;
|
||||
configData: T = {} as T;
|
||||
ajv: Ajv;
|
||||
validate: ValidateFunction<T>;
|
||||
configSchema: TSchema;
|
||||
validate: TypeCheck<TSchema>;
|
||||
|
||||
protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: AnySchema) {
|
||||
protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: TSchema) {
|
||||
this.name = name;
|
||||
this.core = core;
|
||||
this.configPath = configPath;
|
||||
this.ajv = new Ajv({ useDefaults: true, coerceTypes: true });
|
||||
this.validate = this.ajv.compile<T>(ConfigSchema);
|
||||
this.configSchema = ConfigSchema;
|
||||
this.validate = TypeCompiler.Compile(ConfigSchema);
|
||||
fs.mkdirSync(this.configPath, { recursive: true });
|
||||
this.read();
|
||||
}
|
||||
@@ -43,8 +45,12 @@ export abstract class ConfigBase<T> {
|
||||
private loadConfig (configPath: string): T {
|
||||
try {
|
||||
const newConfigData = json5.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
this.validate(newConfigData);
|
||||
this.configData = newConfigData;
|
||||
let data: unknown = newConfigData;
|
||||
data = Value.Parse(this.configSchema, data);
|
||||
if (!this.validate.Check(data)) {
|
||||
throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', '));
|
||||
}
|
||||
this.configData = data as T;
|
||||
this.core.context.logger.logDebug(`[Core] [Config] 配置文件${configPath}加载`, this.configData);
|
||||
return this.configData;
|
||||
} catch (e: unknown) {
|
||||
@@ -55,8 +61,12 @@ export abstract class ConfigBase<T> {
|
||||
|
||||
save (newConfigData: T = this.configData): void {
|
||||
const configPath = this.getConfigPath(this.core.selfInfo.uin);
|
||||
this.validate(newConfigData);
|
||||
this.configData = newConfigData;
|
||||
let data: unknown = newConfigData;
|
||||
data = Value.Parse(this.configSchema, data);
|
||||
if (!this.validate.Check(data)) {
|
||||
throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', '));
|
||||
}
|
||||
this.configData = data as T;
|
||||
try {
|
||||
fs.writeFileSync(configPath, JSON.stringify(this.configData, null, 2));
|
||||
} catch (e: unknown) {
|
||||
|
||||
@@ -1,7 +1,21 @@
|
||||
import { ConfigBase } from '@/napcat-core/helper/config-base';
|
||||
import { NapCatCore } from '@/napcat-core/index';
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
import { AnySchema } from 'ajv';
|
||||
import { Type, Static, TSchema } from '@sinclair/typebox';
|
||||
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import json5 from 'json5';
|
||||
|
||||
export const BypassOptionsSchema = Type.Object({
|
||||
hook: Type.Boolean({ default: true }),
|
||||
window: Type.Boolean({ default: true }),
|
||||
module: Type.Boolean({ default: true }),
|
||||
process: Type.Boolean({ default: true }),
|
||||
container: Type.Boolean({ default: true }),
|
||||
js: Type.Boolean({ default: true }),
|
||||
});
|
||||
|
||||
export const NapcatConfigSchema = Type.Object({
|
||||
fileLog: Type.Boolean({ default: false }),
|
||||
@@ -11,12 +25,32 @@ export const NapcatConfigSchema = Type.Object({
|
||||
packetBackend: Type.String({ default: 'auto' }),
|
||||
packetServer: Type.String({ default: '' }),
|
||||
o3HookMode: Type.Number({ default: 0 }),
|
||||
autoTimeSync: Type.Boolean({ default: true }),
|
||||
bypass: Type.Optional(BypassOptionsSchema),
|
||||
});
|
||||
|
||||
export type NapcatConfig = Static<typeof NapcatConfigSchema>;
|
||||
|
||||
/**
|
||||
* 从指定配置目录读取 napcat.json,按 NapcatConfigSchema 校验并填充默认值
|
||||
* 用于登录前(无 NapCatCore 实例时)的早期配置读取
|
||||
*/
|
||||
export function loadNapcatConfig (configPath: string): NapcatConfig {
|
||||
let data: Record<string, unknown> = {};
|
||||
try {
|
||||
const configFile = path.join(configPath, 'napcat.json');
|
||||
if (fs.existsSync(configFile)) {
|
||||
data = json5.parse(fs.readFileSync(configFile, 'utf-8'));
|
||||
}
|
||||
} catch {
|
||||
// 读取失败时使用 schema 默认值
|
||||
}
|
||||
data = Value.Parse(NapcatConfigSchema, data) as Record<string, unknown>;
|
||||
return data as NapcatConfig;
|
||||
}
|
||||
|
||||
export class NapCatConfigLoader extends ConfigBase<NapcatConfig> {
|
||||
constructor (core: NapCatCore, configPath: string, schema: AnySchema) {
|
||||
constructor (core: NapCatCore, configPath: string, schema: TSchema) {
|
||||
super('napcat', core, configPath, schema);
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,7 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
// 获取文件大小和类型
|
||||
const [fileType, duration] = await Promise.all([
|
||||
fileTypeFromFile(videoPath).catch(() => null),
|
||||
this.getDuration(videoPath),
|
||||
this.getDuration(videoPath).catch(() => 60),
|
||||
]);
|
||||
|
||||
// 创建临时缩略图路径
|
||||
@@ -136,22 +136,24 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取时长
|
||||
*/
|
||||
async getDuration (filePath: string): Promise<number> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(this.ffprobePath, [
|
||||
'-v', 'error',
|
||||
'-show_entries', 'format=duration',
|
||||
'-of', 'default=noprint_wrappers=1:nokey=1',
|
||||
filePath,
|
||||
]);
|
||||
* 获取时长
|
||||
*/
|
||||
async getDuration(filePath: string): Promise<number> {
|
||||
const { stdout } = await execFileAsync(this.ffprobePath, [
|
||||
"-v",
|
||||
"error",
|
||||
"-show_entries",
|
||||
"format=duration",
|
||||
"-of",
|
||||
"default=noprint_wrappers=1:nokey=1",
|
||||
filePath,
|
||||
]);
|
||||
|
||||
const duration = parseFloat(stdout.trim());
|
||||
return isNaN(duration) ? 60 : duration;
|
||||
} catch {
|
||||
return 60; // 默认时长
|
||||
const duration = parseFloat(stdout.trim());
|
||||
if (isNaN(duration)) {
|
||||
throw new Error(`ffprobe 返回了无效的时长值: "${stdout.trim()}"`);
|
||||
}
|
||||
return duration;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -64,10 +64,12 @@ export class FFmpegService {
|
||||
}
|
||||
return this.adapter;
|
||||
}
|
||||
|
||||
public static async convertToNTSilkTct (inputFile: string, outputFile: string): Promise<void> {
|
||||
const adapter = await this.getAdapter();
|
||||
await adapter.convertToNTSilkTct(inputFile, outputFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 FFmpeg 路径并更新适配器
|
||||
* @deprecated 建议使用 init() 方法初始化
|
||||
|
||||
@@ -112,11 +112,11 @@ export class ForwardMsgBuilder {
|
||||
preview: m.valid ? m.toPreview() : '[该消息类型暂不支持查看]',
|
||||
})),
|
||||
})),
|
||||
source,
|
||||
news,
|
||||
summary,
|
||||
prompt,
|
||||
uuid,
|
||||
source,
|
||||
news,
|
||||
summary,
|
||||
prompt,
|
||||
uuid
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -59,13 +59,17 @@ class Subscription {
|
||||
export const logSubscription = new Subscription();
|
||||
|
||||
export class LogWrapper implements ILogWrapper {
|
||||
fileLogEnabled = true;
|
||||
fileLogEnabled = false;
|
||||
consoleLogEnabled = true;
|
||||
logger: winston.Logger;
|
||||
|
||||
private logPath: string;
|
||||
private fileTransportAdded = false;
|
||||
private fileLogLevel: string = LogLevel.DEBUG;
|
||||
|
||||
constructor (logDir: string) {
|
||||
const filename = `${getFormattedTimestamp()}.log`;
|
||||
const logPath = path.join(logDir, filename);
|
||||
this.logPath = path.join(logDir, filename);
|
||||
|
||||
this.logger = winston.createLogger({
|
||||
level: 'debug',
|
||||
@@ -77,12 +81,6 @@ export class LogWrapper implements ILogWrapper {
|
||||
})
|
||||
),
|
||||
transports: [
|
||||
new transports.File({
|
||||
filename: logPath,
|
||||
level: 'debug',
|
||||
maxsize: 5 * 1024 * 1024, // 5MB
|
||||
maxFiles: 5,
|
||||
}),
|
||||
new transports.Console({
|
||||
format: format.combine(
|
||||
format.colorize(),
|
||||
@@ -107,7 +105,7 @@ export class LogWrapper implements ILogWrapper {
|
||||
this.deleteOldLogFile(filePath, oneWeekAgo);
|
||||
});
|
||||
}).catch((err) => {
|
||||
this.logger.error('Failed to read log directory', err);
|
||||
this.logError('Failed to read log directory', err);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -117,21 +115,22 @@ export class LogWrapper implements ILogWrapper {
|
||||
fs.unlink(filePath).catch((err) => {
|
||||
if (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
this.logger.warn(`File already deleted: ${filePath}`);
|
||||
this.logWarn(`File already deleted: ${filePath}`);
|
||||
} else {
|
||||
this.logger.error('Failed to delete old log file', err);
|
||||
this.logError('Failed to delete old log file', err);
|
||||
}
|
||||
} else {
|
||||
this.logger.info(`Deleted old log file: ${filePath}`);
|
||||
this.log(`Deleted old log file: ${filePath}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}).catch((err) => {
|
||||
this.logger.error('Failed to get file stats', err);
|
||||
this.logError('Failed to get file stats', err);
|
||||
});
|
||||
}
|
||||
|
||||
setFileAndConsoleLogLevel (fileLogLevel: LogLevel, consoleLogLevel: LogLevel) {
|
||||
this.fileLogLevel = fileLogLevel;
|
||||
this.logger.transports.forEach((transport) => {
|
||||
if (transport instanceof transports.File) {
|
||||
transport.level = fileLogLevel;
|
||||
@@ -148,6 +147,15 @@ export class LogWrapper implements ILogWrapper {
|
||||
|
||||
setFileLogEnabled (isEnabled: boolean) {
|
||||
this.fileLogEnabled = isEnabled;
|
||||
if (isEnabled && !this.fileTransportAdded) {
|
||||
this.fileTransportAdded = true;
|
||||
this.logger.add(new transports.File({
|
||||
filename: this.logPath,
|
||||
level: this.fileLogLevel,
|
||||
maxsize: 5 * 1024 * 1024, // 5MB
|
||||
maxFiles: 5,
|
||||
}));
|
||||
}
|
||||
this.logger.transports.forEach((transport) => {
|
||||
if (transport instanceof transports.File) {
|
||||
transport.silent = !isEnabled;
|
||||
@@ -178,16 +186,18 @@ export class LogWrapper implements ILogWrapper {
|
||||
}
|
||||
|
||||
_log (level: LogLevel, ...args: any[]) {
|
||||
const message = this.formatMsg(args);
|
||||
if (this.consoleLogEnabled && this.fileLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.consoleLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.fileLogEnabled) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
|
||||
if (this.consoleLogEnabled || this.fileLogEnabled) {
|
||||
const message = this.formatMsg(args);
|
||||
if (this.consoleLogEnabled && this.fileLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.consoleLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.fileLogEnabled) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
|
||||
}
|
||||
logSubscription.notify(JSON.stringify({ level, message }));
|
||||
}
|
||||
logSubscription.notify(JSON.stringify({ level, message }));
|
||||
}
|
||||
|
||||
log (...args: any[]) {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 服务器时间矫正 - 全局 Hook
|
||||
*
|
||||
* 保留 Date.now 原始引用,启动后通过 getServerTime 计算偏移量,
|
||||
* 直接覆盖 Date.now(),使全局所有调用自动获得矫正后的时间戳。
|
||||
*/
|
||||
|
||||
/** 原始 Date.now 引用,不受 hook 影响 */
|
||||
export const OriginalDateNow: () => number = Date.now.bind(Date);
|
||||
|
||||
/**
|
||||
* 初始化全局时间矫正,覆盖 Date.now()
|
||||
* @param getServerTimeFn 获取服务器时间的函数,返回毫秒级时间戳字符串
|
||||
* @returns 偏移量(毫秒)
|
||||
*/
|
||||
export function hookGlobalDateNow (getServerTimeFn: () => string): number {
|
||||
const start = OriginalDateNow();
|
||||
const serverTimeStr = getServerTimeFn();
|
||||
const end = OriginalDateNow();
|
||||
const serverTimeMs = parseInt(serverTimeStr, 10);
|
||||
|
||||
if (isNaN(serverTimeMs) || serverTimeMs <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 补偿网络延迟:假定往返时间对称,服务器时间对应本地时间的中点 (start + end) / 2
|
||||
const offsetMs = Math.round(serverTimeMs - (start + end) / 2);
|
||||
|
||||
if (Math.abs(offsetMs) > 5000) {
|
||||
Date.now = () => OriginalDateNow() + offsetMs;
|
||||
}
|
||||
|
||||
return offsetMs;
|
||||
}
|
||||
@@ -6,13 +6,13 @@ import { NTEventWrapper } from './event';
|
||||
* 创建 Service 方法的代理
|
||||
* 拦截所有方法调用,通过 EventWrapper 进行调用
|
||||
*/
|
||||
function createServiceMethodProxy<S extends keyof ServiceNamingMapping>(
|
||||
function createServiceMethodProxy<S extends keyof ServiceNamingMapping> (
|
||||
serviceName: S,
|
||||
originalService: ServiceNamingMapping[S],
|
||||
eventWrapper: NTEventWrapper
|
||||
): ServiceNamingMapping[S] {
|
||||
return new Proxy(originalService as object, {
|
||||
get(target, prop, receiver) {
|
||||
get (target, prop, receiver) {
|
||||
const originalValue = Reflect.get(target, prop, receiver);
|
||||
|
||||
// 如果不是函数,直接返回原始值
|
||||
@@ -50,7 +50,7 @@ function createServiceMethodProxy<S extends keyof ServiceNamingMapping>(
|
||||
* 第一层:拦截 getXXXService 方法
|
||||
* 第二层:拦截 Service 上的具体方法调用
|
||||
*/
|
||||
export function createSessionProxy(
|
||||
export function createSessionProxy (
|
||||
session: NodeIQQNTWrapperSession,
|
||||
eventWrapper: NTEventWrapper
|
||||
): NodeIQQNTWrapperSession {
|
||||
@@ -58,7 +58,7 @@ export function createSessionProxy(
|
||||
const serviceProxyCache = new Map<string, unknown>();
|
||||
|
||||
return new Proxy(session, {
|
||||
get(target, prop, receiver) {
|
||||
get (target, prop, receiver) {
|
||||
const propName = prop as string;
|
||||
|
||||
// 检查是否是 getXXXService 方法
|
||||
@@ -105,7 +105,7 @@ export function createSessionProxy(
|
||||
/**
|
||||
* 检查 Service 名称是否在已知的映射中
|
||||
*/
|
||||
function isKnownService(serviceName: string): serviceName is keyof ServiceNamingMapping {
|
||||
function isKnownService (serviceName: string): serviceName is keyof ServiceNamingMapping {
|
||||
const knownServices: string[] = [
|
||||
'NodeIKernelAvatarService',
|
||||
'NodeIKernelBuddyService',
|
||||
@@ -132,7 +132,7 @@ function isKnownService(serviceName: string): serviceName is keyof ServiceNaming
|
||||
* 创建带有 EventWrapper 集成的 InstanceContext
|
||||
* 这是推荐的使用方式,在创建 context 时自动代理 session
|
||||
*/
|
||||
export function createProxiedSession(
|
||||
export function createProxiedSession (
|
||||
session: NodeIQQNTWrapperSession,
|
||||
eventWrapper: NTEventWrapper
|
||||
): NodeIQQNTWrapperSession {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
NTQQWebApi,
|
||||
NTQQFlashApi,
|
||||
NTQQOnlineApi,
|
||||
NTQQDatabaseApi,
|
||||
} from '@/napcat-core/apis';
|
||||
import { NTQQCollectionApi } from '@/napcat-core/apis/collection';
|
||||
import {
|
||||
@@ -37,6 +38,7 @@ import { Napi2NativeLoader } from './packet/handler/napi2nativeLoader';
|
||||
import { container, ReceiverServiceRegistry } from './packet/handler/serviceRegister';
|
||||
import { appEvent } from './packet/handler/eventList';
|
||||
import { TypedEventEmitter } from './packet/handler/typeEvent';
|
||||
import { hookGlobalDateNow } from './helper/server-time';
|
||||
export * from './wrapper';
|
||||
export * from './types/index';
|
||||
export * from './services/index';
|
||||
@@ -49,6 +51,7 @@ export * from './helper/config';
|
||||
export * from './helper/config-base';
|
||||
export * from './helper/proxy-handler';
|
||||
export * from './helper/session-proxy';
|
||||
export * from './helper/server-time';
|
||||
|
||||
export enum NapCatCoreWorkingEnv {
|
||||
Unknown = 0,
|
||||
@@ -118,6 +121,8 @@ export class NapCatCore {
|
||||
selfInfo: SelfInfo;
|
||||
util: NodeQQNTWrapperUtil;
|
||||
configLoader: NapCatConfigLoader;
|
||||
/** 数据库 passphrase,由 OidbSvcTrpcTcp.0xcde_2 包获取 */
|
||||
dbPassphrase: string | undefined;
|
||||
|
||||
// 通过构造器递过去的 runtime info 应该尽量少
|
||||
constructor (context: InstanceContext, selfInfo: SelfInfo) {
|
||||
@@ -148,6 +153,7 @@ export class NapCatCore {
|
||||
GroupApi: new NTQQGroupApi(this.context, this),
|
||||
FlashApi: new NTQQFlashApi(this.context, this),
|
||||
OnlineApi: new NTQQOnlineApi(this.context, this),
|
||||
DatabaseApi: new NTQQDatabaseApi(this.context, this),
|
||||
};
|
||||
container.bind(NapCatCore).toConstantValue(this);
|
||||
container.bind(TypedEventEmitter).toConstantValue(this.event);
|
||||
@@ -169,6 +175,28 @@ export class NapCatCore {
|
||||
if (!fs.existsSync(this.NapCatTempPath)) {
|
||||
fs.mkdirSync(this.NapCatTempPath, { recursive: true });
|
||||
}
|
||||
// 通过 getServerTime 全局 hook Date.now() 矫正本地时间偏差
|
||||
// 可通过环境变量 NAPCAT_DISABLE_TIME_SYNC=1 或配置 autoTimeSync: false 禁用
|
||||
if (process.env['NAPCAT_DISABLE_TIME_SYNC'] === '1' || !this.configLoader.configData.autoTimeSync) {
|
||||
this.context.logger.log('[ServerTime] 自动对时已禁用');
|
||||
} else {
|
||||
const doTimeSync = () => {
|
||||
try {
|
||||
const offsetMs = hookGlobalDateNow(() => this.context.session.getMSFService().getServerTime());
|
||||
if (Math.abs(offsetMs) > 5000) {
|
||||
this.context.logger.logWarn(`[ServerTime] 本地时间与服务器时间偏差 ${(offsetMs / 1000).toFixed(1)}s,已自动矫正`);
|
||||
} else {
|
||||
this.context.logger.log(`[ServerTime] 时间同步完成,偏差 ${offsetMs}ms`);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('[ServerTime] 时间矫正失败', e);
|
||||
}
|
||||
};
|
||||
doTimeSync();
|
||||
// 每小时定期重同步,防止长时间运行后本地时钟漂移触发风控
|
||||
const syncTimer = setInterval(doTimeSync, 3600000);
|
||||
syncTimer.unref();
|
||||
}
|
||||
// 遍历this.apis[i].initApi 如果存在该函数进行async 调用
|
||||
for (const apiKey in this.apis) {
|
||||
const api = this.apis[apiKey as keyof StableNTApiWrapper];
|
||||
@@ -330,4 +358,5 @@ export interface StableNTApiWrapper {
|
||||
GroupApi: NTQQGroupApi;
|
||||
FlashApi: NTQQFlashApi,
|
||||
OnlineApi: NTQQOnlineApi,
|
||||
DatabaseApi: NTQQDatabaseApi,
|
||||
}
|
||||
@@ -53,6 +53,7 @@ export class NodeIKernelLoginListener {
|
||||
|
||||
onLoginState (..._args: any[]): any {
|
||||
}
|
||||
|
||||
onLoginRecordUpdate (..._args: any[]): any {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
{
|
||||
"name": "napcat-core",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
|
||||
"name": "napcat-core",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./index.ts"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./index.ts"
|
||||
},
|
||||
"./*": {
|
||||
"import": "./*"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"winston": "^3.17.0",
|
||||
"json5": "^2.2.3",
|
||||
"inversify": "^7.10.4",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"@protobuf-ts/runtime": "^2.11.1",
|
||||
"ajv": "^8.13.0",
|
||||
"@sinclair/typebox": "^0.34.38",
|
||||
"file-type": "^21.0.0",
|
||||
"compressing": "^1.10.1",
|
||||
"napcat-image-size": "workspace:*",
|
||||
"napcat-common": "workspace:*",
|
||||
"napcat-protobuf": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
"./*": {
|
||||
"import": "./*"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@protobuf-ts/runtime": "^2.11.1",
|
||||
"@sinclair/typebox": "^0.34.38",
|
||||
"compressing": "^1.10.1",
|
||||
"file-type": "^21.0.0",
|
||||
"inversify": "^7.10.4",
|
||||
"json5": "^2.2.3",
|
||||
"napcat-common": "workspace:*",
|
||||
"napcat-database": "workspace:*",
|
||||
"napcat-image-size": "workspace:*",
|
||||
"napcat-protobuf": "workspace:*",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"winston": "^3.17.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,16 @@ export class PacketOperationContext {
|
||||
await this.context.client.sendOidbPacket(req, true);
|
||||
}
|
||||
|
||||
async CompleteGroupTodo (groupUin: number, msgSeq: string) {
|
||||
const req = trans.CompleteGroupTodo.build(groupUin, msgSeq);
|
||||
await this.context.client.sendOidbPacket(req, true);
|
||||
}
|
||||
|
||||
async CancelGroupTodo (groupUin: number, msgSeq: string) {
|
||||
const req = trans.CancelGroupTodo.build(groupUin, msgSeq);
|
||||
await this.context.client.sendOidbPacket(req, true);
|
||||
}
|
||||
|
||||
async FetchRkey (timeout: number = 10000) {
|
||||
const req = trans.FetchRkey.build();
|
||||
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
|
||||
@@ -228,15 +238,17 @@ export class PacketOperationContext {
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
return res.result.resId;
|
||||
}
|
||||
|
||||
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
|
||||
//await this.SendPreprocess(msg, groupUin);
|
||||
// 遍历上传资源
|
||||
await Promise.allSettled(msg.map(async (item) => { return await this.SendPreprocess(item.actionMsg, groupUin); }));
|
||||
// await this.SendPreprocess(msg, groupUin);
|
||||
// 遍历上传资源(跳过已有原始数据的项)
|
||||
await Promise.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return await this.SendPreprocess(item.actionMsg!, groupUin); }));
|
||||
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
return res.result.resId;
|
||||
}
|
||||
|
||||
async MoveGroupFile (
|
||||
groupUin: number,
|
||||
fileUUID: string,
|
||||
@@ -312,6 +324,15 @@ export class PacketOperationContext {
|
||||
}
|
||||
}
|
||||
|
||||
async FetchForwardMsgRaw (resId: string) {
|
||||
const req = trans.DownloadForwardMsg.build(this.context.napcore.basicInfo.uid, resId);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadForwardMsg.parse(resp);
|
||||
const inflate = gunzipSync(res.result.payload);
|
||||
const result = new NapProtoMsg(LongMsgResult).decode(inflate);
|
||||
return result.action;
|
||||
}
|
||||
|
||||
async FetchForwardMsg (res_id: string): Promise<RawMessage[]> {
|
||||
const req = trans.DownloadForwardMsg.build(this.context.napcore.basicInfo.uid, res_id);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
|
||||
@@ -194,7 +194,7 @@ export class NativePacketHandler {
|
||||
}
|
||||
}
|
||||
|
||||
async init (version: string): Promise<boolean> {
|
||||
async init (version: string, o3HookMode: boolean = false): Promise<boolean> {
|
||||
const version_arch = version + '-' + process.arch;
|
||||
try {
|
||||
if (!this.loaded) {
|
||||
@@ -215,7 +215,7 @@ export class NativePacketHandler {
|
||||
|
||||
this.MoeHooExport.exports.initHook?.(send, recv, (type: PacketType, uin: string, cmd: string, seq: number, hex_data: string) => {
|
||||
this.emitPacket(type, uin, cmd, seq, hex_data);
|
||||
}, true);
|
||||
}, o3HookMode);
|
||||
this.logger.log('[PacketHandler] 初始化成功');
|
||||
return true;
|
||||
} catch (error) {
|
||||
|
||||
@@ -4,10 +4,19 @@ import fs from 'fs';
|
||||
import { constants } from 'node:os';
|
||||
import { LogWrapper } from '../../helper/log';
|
||||
|
||||
export interface BypassOptions {
|
||||
hook?: boolean;
|
||||
window?: boolean;
|
||||
module?: boolean;
|
||||
process?: boolean;
|
||||
container?: boolean;
|
||||
js?: boolean;
|
||||
}
|
||||
|
||||
export interface Napi2NativeExportType {
|
||||
initHook?: (send: string, recv: string) => boolean;
|
||||
setVerbose?: (verbose: boolean) => void; // 默认关闭日志
|
||||
enableAllBypasses?: () => void;
|
||||
enableAllBypasses?: (options?: BypassOptions) => boolean;
|
||||
}
|
||||
|
||||
export class Napi2NativeLoader {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as crypto from 'node:crypto';
|
||||
import * as zlib from 'node:zlib';
|
||||
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
|
||||
import {
|
||||
@@ -510,14 +511,14 @@ export class PacketMsgPttElement extends IPacketMsgElement<SendPttElement> {
|
||||
}
|
||||
|
||||
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
|
||||
//return [];
|
||||
// return [];
|
||||
if (!this.msgInfo) return [];
|
||||
return [{
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
|
||||
businessType: 22,
|
||||
}
|
||||
},
|
||||
}];
|
||||
}
|
||||
|
||||
@@ -665,11 +666,13 @@ export class PacketMsgMarkDownElement extends IPacketMsgElement<SendMarkdownElem
|
||||
export class PacketMultiMsgElement extends IPacketMsgElement<SendMultiForwardMsgElement> {
|
||||
resid: string;
|
||||
message: PacketMsg[];
|
||||
uuid: string;
|
||||
|
||||
constructor (rawElement: SendMultiForwardMsgElement, message?: PacketMsg[]) {
|
||||
super(rawElement);
|
||||
this.resid = rawElement.multiForwardMsgElement.resId;
|
||||
this.message = message ?? [];
|
||||
this.uuid = rawElement.multiForwardMsgElement.fileName || crypto.randomUUID();
|
||||
}
|
||||
|
||||
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
|
||||
@@ -677,7 +680,7 @@ export class PacketMultiMsgElement extends IPacketMsgElement<SendMultiForwardMsg
|
||||
lightAppElem: {
|
||||
data: Buffer.concat([
|
||||
Buffer.from([0x01]),
|
||||
zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message)), 'utf-8')),
|
||||
zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message, undefined, undefined, undefined, undefined, this.uuid)), 'utf-8')),
|
||||
]),
|
||||
},
|
||||
}];
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as proto from '@/napcat-core/packet/transformer/proto';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
|
||||
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
|
||||
|
||||
class CancelGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
|
||||
build (peer: number, msgSeq: string): OidbPacket {
|
||||
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
|
||||
groupUin: peer,
|
||||
msgSeq: BigInt(msgSeq),
|
||||
});
|
||||
return OidbBase.build(0xF90, 3, data);
|
||||
}
|
||||
|
||||
parse (data: Buffer) {
|
||||
return OidbBase.parse(data);
|
||||
}
|
||||
}
|
||||
|
||||
export default new CancelGroupTodo();
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as proto from '@/napcat-core/packet/transformer/proto';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
|
||||
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
|
||||
|
||||
class CompleteGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
|
||||
build (peer: number, msgSeq: string): OidbPacket {
|
||||
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
|
||||
groupUin: peer,
|
||||
msgSeq: BigInt(msgSeq),
|
||||
});
|
||||
return OidbBase.build(0xF90, 2, data);
|
||||
}
|
||||
|
||||
parse (data: Buffer) {
|
||||
return OidbBase.parse(data);
|
||||
}
|
||||
}
|
||||
|
||||
export default new CompleteGroupTodo();
|
||||
@@ -5,7 +5,7 @@ import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
|
||||
|
||||
class SetGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
|
||||
build (peer: number, msgSeq: string): OidbPacket {
|
||||
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90_1).encode({
|
||||
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
|
||||
groupUin: peer,
|
||||
msgSeq: BigInt(msgSeq),
|
||||
});
|
||||
|
||||
@@ -8,4 +8,6 @@ export { default as SetSpecialTitle } from './SetSpecialTitle';
|
||||
export { default as ImageOCR } from './ImageOCR';
|
||||
export { default as MoveGroupFile } from './MoveGroupFile';
|
||||
export { default as RenameGroupFile } from './RenameGroupFile';
|
||||
export { default as CompleteGroupTodo } from './CompleteGroupTodo';
|
||||
export { default as CancelGroupTodo } from './CancelGroupTodo';
|
||||
export { default as SetGroupTodo } from './SetGroupTodo';
|
||||
@@ -1,20 +1,21 @@
|
||||
import zlib from 'node:zlib';
|
||||
import * as proto from '@/napcat-core/packet/transformer/proto';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
|
||||
import { PacketMsg } from '@/napcat-core/packet/message/message';
|
||||
|
||||
export interface UploadForwardMsgParams {
|
||||
actionCommand: string;
|
||||
actionMsg: PacketMsg[];
|
||||
actionMsg?: PacketMsg[];
|
||||
actionMsgBody?: NapProtoEncodeStructType<typeof proto.PushMsgBody>[];
|
||||
}
|
||||
class UploadForwardMsgV2 extends PacketTransformer<typeof proto.SendLongMsgResp> {
|
||||
build (selfUid: string, msg: UploadForwardMsgParams[], groupUin: number = 0): OidbPacket {
|
||||
const reqdata = msg.map((item) => ({
|
||||
actionCommand: item.actionCommand,
|
||||
actionData: {
|
||||
msgBody: this.msgBuilder.buildFakeMsg(selfUid, item.actionMsg),
|
||||
}
|
||||
msgBody: item.actionMsgBody ?? this.msgBuilder.buildFakeMsg(selfUid, item.actionMsg ?? []),
|
||||
},
|
||||
}));
|
||||
const longMsgResultData = new NapProtoMsg(proto.LongMsgResult).encode(
|
||||
{
|
||||
|
||||
@@ -2,4 +2,4 @@ export { default as UploadForwardMsg } from './UploadForwardMsg';
|
||||
export { default as FetchGroupMessage } from './FetchGroupMessage';
|
||||
export { default as FetchC2CMessage } from './FetchC2CMessage';
|
||||
export { default as DownloadForwardMsg } from './DownloadForwardMsg';
|
||||
export { default as UploadForwardMsgV2 } from './UploadForwardMsgV2';
|
||||
export { default as UploadForwardMsgV2 } from './UploadForwardMsgV2';
|
||||
@@ -25,9 +25,10 @@ export * from './oidb/Oidb.0x929';
|
||||
export * from './oidb/Oidb.0xE37_1200';
|
||||
export * from './oidb/Oidb.0xE37_1700';
|
||||
export * from './oidb/Oidb.0XE37_800';
|
||||
export * from './oidb/Oidb.0xCDE_2';
|
||||
export * from './oidb/Oidb.0xEB7';
|
||||
export * from './oidb/Oidb.0xED3_1';
|
||||
export * from './oidb/Oidb.0XFE1_2';
|
||||
export * from './oidb/OidbBase';
|
||||
export * from './oidb/Oidb.0xE07';
|
||||
export * from './oidb/Oidb.0xf90_1';
|
||||
export * from './oidb/Oidb.0xf90';
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ProtoField, ScalarType } from 'napcat-protobuf';
|
||||
|
||||
// OidbSvcTrpcTcp.0xcde_2 响应体
|
||||
// body.field2.field1 为目标字符串值
|
||||
export const OidbSvcTrpcTcp0XCDE_2RespBodyInner = {
|
||||
value: ProtoField(1, ScalarType.STRING),
|
||||
};
|
||||
|
||||
export const OidbSvcTrpcTcp0XCDE_2RespBody = {
|
||||
inner: ProtoField(2, () => OidbSvcTrpcTcp0XCDE_2RespBodyInner),
|
||||
};
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { ProtoField, ScalarType } from 'napcat-protobuf';
|
||||
|
||||
export const OidbSvcTrpcTcp0XF90_1 = {
|
||||
export const OidbSvcTrpcTcp0XF90 = {
|
||||
groupUin: ProtoField(1, ScalarType.UINT32),
|
||||
msgSeq: ProtoField(2, ScalarType.UINT64),
|
||||
};
|
||||
@@ -88,6 +88,7 @@ export interface NodeIKernelAlbumService {
|
||||
map_bytes_info: unknown[],
|
||||
map_user_account: unknown[];
|
||||
},
|
||||
type: number, // type : number 1 取消 2 点赞
|
||||
param: {
|
||||
// {"id":"421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3e*KqaLVYdic!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560336594^||^1","status":1}
|
||||
id: string,
|
||||
|
||||
@@ -32,7 +32,7 @@ export interface NodeIKernelGroupService {
|
||||
getAllGroupPrivilegeFlag (troopUinList: string[], serviceType: number): Promise<unknown>;
|
||||
// <---
|
||||
getGroupExt0xEF0Info (enableGroupCodes: string[], bannedGroupCodes: string[], filter: GroupExt0xEF0InfoFilter, forceFetch: boolean):
|
||||
Promise<GeneralCallResult & { result: { groupExtInfos: Map<string, unknown>; }; }>;
|
||||
Promise<GeneralCallResult & { result: { groupExtInfos: Map<string, unknown>; }; }>;
|
||||
|
||||
kickMemberV2 (param: KickMemberV2Req): Promise<GeneralCallResult>;
|
||||
|
||||
|
||||
@@ -29,10 +29,11 @@ export interface PasswordLoginArgType {
|
||||
uin: string;
|
||||
passwordMd5: string;// passwMD5
|
||||
step: number;// 猜测是需要二次认证 参数 一次为0
|
||||
newDeviceLoginSig: string;
|
||||
proofWaterSig: string;
|
||||
proofWaterRand: string;
|
||||
proofWaterSid: string;
|
||||
newDeviceLoginSig: Uint8Array;
|
||||
proofWaterSig: Uint8Array;
|
||||
proofWaterRand: Uint8Array;
|
||||
proofWaterSid: Uint8Array;
|
||||
unusualDeviceCheckSig: Uint8Array;
|
||||
}
|
||||
|
||||
export interface LoginListItem {
|
||||
|
||||
@@ -341,7 +341,7 @@ export interface NodeIKernelMsgService {
|
||||
|
||||
getFileThumbSavePath (arg1: string, arg2: number, arg3: boolean): unknown;
|
||||
|
||||
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): unknown;
|
||||
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): Promise<GeneralCallResult>;
|
||||
|
||||
setPttPlayedState (arg1: string, arg2: Peer, arg3: string): unknown;
|
||||
|
||||
@@ -688,14 +688,14 @@ export interface NodeIKernelMsgService {
|
||||
msgSeq: string;
|
||||
msgRandom: string;
|
||||
}>, DataMigrationResourceInfo: {
|
||||
extraData: string;
|
||||
filePath: string;
|
||||
fileSize: string;
|
||||
msgRandom: string;
|
||||
msgSeq: string;
|
||||
msgSubType: number;
|
||||
msgType: number;
|
||||
}): unknown;
|
||||
extraData: string;
|
||||
filePath: string;
|
||||
fileSize: string;
|
||||
msgRandom: string;
|
||||
msgSeq: string;
|
||||
msgSubType: number;
|
||||
msgType: number;
|
||||
}): unknown;
|
||||
|
||||
dataMigrationGetResourceLocalDestinyPath (arg: unknown): unknown;
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export interface NodeIKernelStorageCleanService {
|
||||
// "C:\\Users\\nanaeo\\AppData\\Roaming\\QQ\\Partitions\\qqnt_9212"
|
||||
// ]
|
||||
// ]
|
||||
addCacheScanedPaths (paths: Map<`tmp` | `SilentCacheappSessionPartation9212` | `hotUpdate`, unknown>): unknown;
|
||||
addCacheScanedPaths (paths: Map<'tmp' | 'SilentCacheappSessionPartation9212' | 'hotUpdate', unknown>): unknown;
|
||||
|
||||
addFilesScanedPaths (arg: unknown): unknown;
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "napcat-database",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./src/index.ts"
|
||||
},
|
||||
"./src/*": {
|
||||
"import": "./src/*"
|
||||
}
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/** 文件头部扩展区大小 */
|
||||
export const EXT_HEADER_SIZE = 1024;
|
||||
|
||||
/** SQLCipher 页大小 */
|
||||
export const PAGE_SIZE = 4096;
|
||||
|
||||
/** PBKDF2 salt 长度 */
|
||||
export const SALT_SIZE = 16;
|
||||
|
||||
/** AES-256 密钥长度 */
|
||||
export const KEY_SIZE = 32;
|
||||
|
||||
/** AES-CBC IV 长度 */
|
||||
export const IV_SIZE = 16;
|
||||
|
||||
/** HMAC-SHA1 长度 */
|
||||
export const HMAC_SIZE = 20;
|
||||
|
||||
/** 每页保留区大小: IV(16) + HMAC_SHA1(20) + pad(12) = 48 */
|
||||
export const RESERVE_SIZE = 48;
|
||||
|
||||
/** PBKDF2 主密钥迭代次数 */
|
||||
export const KDF_ITERATIONS = 4000;
|
||||
|
||||
/** PBKDF2 HMAC 密钥迭代次数 */
|
||||
export const FAST_ITERATIONS = 2;
|
||||
|
||||
/** HMAC salt XOR 掩码 */
|
||||
export const HMAC_MASK = 0x3a;
|
||||
|
||||
/** SQLite 加密文件头 */
|
||||
export const SQLITE_HEADER = Buffer.from('SQLite header 3\0');
|
||||
|
||||
/** SQLite 明文文件头 */
|
||||
export const SQLITE_FORMAT = Buffer.from('SQLite format 3\0');
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* 密钥派生
|
||||
* enc_key = PBKDF2_HMAC_SHA512(passphrase, salt, 4000, 32)
|
||||
* hmac_key = PBKDF2_HMAC_SHA512(enc_key, salt ^ 0x3a, 2, 32)
|
||||
*/
|
||||
|
||||
import { pbkdf2Sync } from 'node:crypto';
|
||||
import {
|
||||
KEY_SIZE,
|
||||
KDF_ITERATIONS,
|
||||
FAST_ITERATIONS,
|
||||
HMAC_MASK,
|
||||
} from './constants';
|
||||
|
||||
export interface DerivedKeys {
|
||||
encKey: Buffer;
|
||||
hmacKey: Buffer;
|
||||
}
|
||||
export function deriveKeys (passphrase: Buffer, salt: Buffer): DerivedKeys {
|
||||
const encKey = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, KEY_SIZE, 'sha512');
|
||||
|
||||
const hmacSalt = Buffer.alloc(salt.length);
|
||||
for (let i = 0; i < salt.length; i++) {
|
||||
hmacSalt[i] = salt[i]! ^ HMAC_MASK;
|
||||
}
|
||||
const hmacKey = pbkdf2Sync(encKey, hmacSalt, FAST_ITERATIONS, KEY_SIZE, 'sha512');
|
||||
|
||||
return { encKey, hmacKey };
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { createDecipheriv } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import {
|
||||
EXT_HEADER_SIZE,
|
||||
PAGE_SIZE,
|
||||
SALT_SIZE,
|
||||
IV_SIZE,
|
||||
RESERVE_SIZE,
|
||||
SQLITE_HEADER,
|
||||
SQLITE_FORMAT,
|
||||
} from './constants';
|
||||
import { deriveKeys } from './crypto';
|
||||
|
||||
/**
|
||||
* 解密单个 SQLCipher 页面
|
||||
* @param pageData 原始页数据 (4096 字节)
|
||||
* @param encKey AES-256 密钥
|
||||
* @param skipSalt 页 1 需跳过前 16 字节 salt
|
||||
*/
|
||||
function decryptPage (pageData: Buffer, encKey: Buffer, skipSalt: number = 0): Buffer {
|
||||
const data = pageData.subarray(skipSalt);
|
||||
const contentLen = data.length - RESERVE_SIZE;
|
||||
const encrypted = data.subarray(0, contentLen);
|
||||
const iv = data.subarray(contentLen, contentLen + IV_SIZE);
|
||||
|
||||
const decipher = createDecipheriv('aes-256-cbc', encKey, iv);
|
||||
decipher.setAutoPadding(false);
|
||||
return Buffer.concat([decipher.update(encrypted), decipher.final()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件是否为 NTQQ 加密数据库
|
||||
*/
|
||||
export function isEncryptedNTDB (fileData: Buffer): boolean {
|
||||
if (fileData.length < EXT_HEADER_SIZE + PAGE_SIZE) return false;
|
||||
return fileData.subarray(0, 16).equals(SQLITE_HEADER);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将加密的 NTQQ 数据库解密为标准 SQLite 数据库
|
||||
* @param fileData 完整的加密数据库文件内容
|
||||
* @param passphrase 服务端返回的密钥口令
|
||||
* @returns 解密后的 SQLite 数据库 Buffer,失败返回 null
|
||||
*/
|
||||
export function decryptDatabase (fileData: Buffer, passphrase: Buffer): Buffer | null {
|
||||
if (!isEncryptedNTDB(fileData)) return null;
|
||||
|
||||
const scData = fileData.subarray(EXT_HEADER_SIZE);
|
||||
const totalPages = Math.floor(scData.length / PAGE_SIZE);
|
||||
if (totalPages === 0) return null;
|
||||
|
||||
const salt = scData.subarray(0, SALT_SIZE);
|
||||
const { encKey } = deriveKeys(passphrase, salt);
|
||||
|
||||
const output = Buffer.alloc(totalPages * PAGE_SIZE);
|
||||
let offset = 0;
|
||||
|
||||
for (let pgno = 1; pgno <= totalPages; pgno++) {
|
||||
const pageOffset = (pgno - 1) * PAGE_SIZE;
|
||||
const rawPage = scData.subarray(pageOffset, pageOffset + PAGE_SIZE);
|
||||
const skip = pgno === 1 ? SALT_SIZE : 0;
|
||||
const decrypted = decryptPage(rawPage, encKey, skip);
|
||||
|
||||
if (pgno === 1) {
|
||||
// 重建 Page 1: SQLite 标准文件头 + 解密内容
|
||||
SQLITE_FORMAT.copy(output, 0);
|
||||
decrypted.copy(output, 16);
|
||||
// 修正 page_size 字段 (offset 16-17, big-endian)
|
||||
output.writeUInt16BE(PAGE_SIZE, 16);
|
||||
// 保留原始 reserved-bytes-per-page 值 (byte 20)
|
||||
// NTQQ SQLCipher 使用 reserved=80 用于 B-tree 布局 (usable=4016)
|
||||
// 即使加密保留区 (IV+HMAC) 实际只有 48 字节
|
||||
// 清零会导致 SQLite 误判溢出指针,报 "database disk image is malformed"
|
||||
offset = PAGE_SIZE;
|
||||
} else {
|
||||
decrypted.copy(output, offset);
|
||||
offset += PAGE_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密数据库文件并写入输出路径
|
||||
* @param inputPath 加密数据库路径
|
||||
* @param passphrase 密钥口令
|
||||
* @param outputPath 输出路径 (默认: 原路径加 _decrypted 后缀)
|
||||
* @returns 输出路径,失败返回 null
|
||||
*/
|
||||
export function decryptDatabaseFile (
|
||||
inputPath: string,
|
||||
passphrase: Buffer,
|
||||
outputPath?: string
|
||||
): string | null {
|
||||
const fileData = fs.readFileSync(inputPath);
|
||||
const result = decryptDatabase(fileData, passphrase);
|
||||
if (!result) return null;
|
||||
|
||||
if (!outputPath) {
|
||||
const dotIdx = inputPath.lastIndexOf('.');
|
||||
outputPath = dotIdx > 0
|
||||
? inputPath.substring(0, dotIdx) + '_decrypted' + inputPath.substring(dotIdx)
|
||||
: inputPath + '_decrypted';
|
||||
}
|
||||
|
||||
fs.writeFileSync(outputPath, result);
|
||||
return outputPath;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
export { deriveKeys, type DerivedKeys } from './crypto';
|
||||
export { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt';
|
||||
export {
|
||||
checkSqliteAvailable,
|
||||
DatabaseHandle,
|
||||
openDatabase,
|
||||
decryptAndOpen,
|
||||
listTablesFromBuffer,
|
||||
listTablesFromFile,
|
||||
readSingleDatabase,
|
||||
scanAllDatabases,
|
||||
formatScanResults,
|
||||
type TableInfo,
|
||||
type ColumnInfo,
|
||||
type DatabaseScanResult,
|
||||
type DatabaseReadOptions,
|
||||
} from './reader';
|
||||
export {
|
||||
EXT_HEADER_SIZE,
|
||||
PAGE_SIZE,
|
||||
SALT_SIZE,
|
||||
KEY_SIZE,
|
||||
IV_SIZE,
|
||||
HMAC_SIZE,
|
||||
RESERVE_SIZE,
|
||||
KDF_ITERATIONS,
|
||||
FAST_ITERATIONS,
|
||||
HMAC_MASK,
|
||||
} from './constants';
|
||||
@@ -0,0 +1,425 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt';
|
||||
|
||||
type DatabaseSyncType = import('node:sqlite').DatabaseSync;
|
||||
type DatabaseSyncCtor = new (path: string, options?: { readOnly?: boolean; }) => DatabaseSyncType;
|
||||
type SQLInputValue = import('node:sqlite').SQLInputValue;
|
||||
|
||||
let _DatabaseSync: DatabaseSyncCtor | null = null;
|
||||
let _sqliteChecked = false;
|
||||
|
||||
async function loadSqlite (): Promise<DatabaseSyncCtor | null> {
|
||||
if (_sqliteChecked) return _DatabaseSync;
|
||||
_sqliteChecked = true;
|
||||
try {
|
||||
const mod = await import('node:sqlite');
|
||||
_DatabaseSync = mod.DatabaseSync as unknown as DatabaseSyncCtor;
|
||||
return _DatabaseSync;
|
||||
} catch {
|
||||
_DatabaseSync = null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getDatabaseSync (): DatabaseSyncCtor {
|
||||
if (!_DatabaseSync) {
|
||||
throw new Error(
|
||||
'node:sqlite 不可用。请使用 Node.js 22+ 并添加 --experimental-sqlite 标志,' +
|
||||
'或调用 checkSqliteAvailable() 检查可用性。'
|
||||
);
|
||||
}
|
||||
return _DatabaseSync;
|
||||
}
|
||||
|
||||
export async function checkSqliteAvailable (): Promise<boolean> {
|
||||
const ctor = await loadSqlite();
|
||||
return ctor !== null;
|
||||
}
|
||||
|
||||
// ======================== 数据库连接管理 ========================
|
||||
|
||||
/** 数据库连接句柄,封装 DatabaseSync 实例 */
|
||||
export class DatabaseHandle {
|
||||
private db: DatabaseSyncType;
|
||||
private _closed = false;
|
||||
readonly filePath: string;
|
||||
readonly readOnly: boolean;
|
||||
|
||||
constructor (filePath: string, readOnly = false) {
|
||||
const DB = getDatabaseSync();
|
||||
this.db = new DB(filePath, { readOnly });
|
||||
this.filePath = filePath;
|
||||
this.readOnly = readOnly;
|
||||
}
|
||||
|
||||
/** 数据库是否已关闭 */
|
||||
get closed (): boolean {
|
||||
return this._closed;
|
||||
}
|
||||
|
||||
private ensureOpen (): void {
|
||||
if (this._closed) throw new Error('数据库已关闭');
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 SELECT 查询,返回所有结果行
|
||||
* @param sql SQL 语句
|
||||
* @param params 绑定参数 (位置参数数组 或 命名参数对象)
|
||||
*/
|
||||
query<T = Record<string, unknown>> (sql: string, params?: SQLInputValue[] | Record<string, SQLInputValue>): T[] {
|
||||
this.ensureOpen();
|
||||
const stmt = this.db.prepare(sql);
|
||||
if (params) {
|
||||
if (Array.isArray(params)) {
|
||||
return stmt.all(...params) as T[];
|
||||
}
|
||||
return stmt.all(params) as T[];
|
||||
}
|
||||
return stmt.all() as T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 SELECT 查询,仅返回第一行
|
||||
* @param sql SQL 语句
|
||||
* @param params 绑定参数
|
||||
*/
|
||||
queryOne<T = Record<string, unknown>> (sql: string, params?: SQLInputValue[] | Record<string, SQLInputValue>): T | undefined {
|
||||
this.ensureOpen();
|
||||
const stmt = this.db.prepare(sql);
|
||||
if (params) {
|
||||
if (Array.isArray(params)) {
|
||||
return stmt.get(...params) as T | undefined;
|
||||
}
|
||||
return stmt.get(params) as T | undefined;
|
||||
}
|
||||
return stmt.get() as T | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行非查询 SQL (INSERT/UPDATE/DELETE/CREATE 等)
|
||||
* @param sql SQL 语句
|
||||
* @param params 绑定参数
|
||||
* @returns 受影响的行数信息
|
||||
*/
|
||||
execute (sql: string, params?: SQLInputValue[] | Record<string, SQLInputValue>): { changes: number | bigint; lastInsertRowid: number | bigint; } {
|
||||
this.ensureOpen();
|
||||
const stmt = this.db.prepare(sql);
|
||||
if (params) {
|
||||
if (Array.isArray(params)) {
|
||||
return stmt.run(...params);
|
||||
}
|
||||
return stmt.run(params);
|
||||
}
|
||||
return stmt.run();
|
||||
}
|
||||
|
||||
/** 列出所有表的信息 */
|
||||
listTables (): TableInfo[] {
|
||||
this.ensureOpen();
|
||||
return extractTablesInfo(this.db);
|
||||
}
|
||||
|
||||
/** 获取指定表的列信息 */
|
||||
getTableColumns (tableName: string): ColumnInfo[] {
|
||||
this.ensureOpen();
|
||||
const cols = this.db.prepare(`PRAGMA table_info([${tableName}])`).all() as {
|
||||
cid: number; name: string; type: string; notnull: number; pk: number;
|
||||
}[];
|
||||
return cols.map(col => ({
|
||||
cid: col.cid,
|
||||
name: col.name,
|
||||
type: col.type,
|
||||
notnull: col.notnull === 1,
|
||||
pk: col.pk === 1,
|
||||
}));
|
||||
}
|
||||
|
||||
/** 获取表的行数 */
|
||||
getRowCount (tableName: string): number {
|
||||
this.ensureOpen();
|
||||
const cnt = this.db.prepare(`SELECT count(*) as cnt FROM [${tableName}]`).get() as { cnt: number; } | undefined;
|
||||
return cnt?.cnt ?? 0;
|
||||
}
|
||||
|
||||
/** 关闭数据库连接 */
|
||||
close (): void {
|
||||
if (!this._closed) {
|
||||
this.db.close();
|
||||
this._closed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个已解密的 SQLite 数据库文件
|
||||
* @param filePath 解密后的 .db 文件路径
|
||||
* @param readOnly 是否以只读模式打开 (默认 true)
|
||||
*/
|
||||
export function openDatabase (filePath: string, readOnly = true): DatabaseHandle {
|
||||
return new DatabaseHandle(filePath, readOnly);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密并打开一个加密的 NTQQ 数据库
|
||||
* @param dbPath 加密数据库路径
|
||||
* @param passphrase 密钥口令
|
||||
* @param cacheDir 解密缓存目录 (可选)
|
||||
* @param readOnly 是否只读 (默认 true)
|
||||
*/
|
||||
export function decryptAndOpen (
|
||||
dbPath: string,
|
||||
passphrase: Buffer,
|
||||
cacheDir?: string,
|
||||
readOnly = true
|
||||
): DatabaseHandle {
|
||||
const filename = path.basename(dbPath);
|
||||
|
||||
if (cacheDir) {
|
||||
const cachedPath = path.join(cacheDir, filename);
|
||||
// 已存在缓存直接打开
|
||||
if (fs.existsSync(cachedPath)) {
|
||||
return new DatabaseHandle(cachedPath, readOnly);
|
||||
}
|
||||
fs.mkdirSync(cacheDir, { recursive: true });
|
||||
const outPath = decryptDatabaseFile(dbPath, passphrase, cachedPath);
|
||||
if (!outPath) throw new Error(`解密失败: ${dbPath}`);
|
||||
return new DatabaseHandle(outPath, readOnly);
|
||||
}
|
||||
|
||||
// 无缓存目录: 解密到临时文件
|
||||
const tmpPath = path.join(os.tmpdir(), `napcat_db_${Date.now()}_${Math.random().toString(36).slice(2)}.db`);
|
||||
const fileData = fs.readFileSync(dbPath);
|
||||
const decryptedBuf = decryptDatabase(fileData, passphrase);
|
||||
if (!decryptedBuf) throw new Error(`解密失败: ${dbPath}`);
|
||||
fs.writeFileSync(tmpPath, decryptedBuf);
|
||||
return new DatabaseHandle(tmpPath, readOnly);
|
||||
}
|
||||
|
||||
/** 单个数据库表信息 */
|
||||
export interface TableInfo {
|
||||
name: string;
|
||||
type: string; // 'table' | 'view' | ...
|
||||
rowCount: number;
|
||||
columns: ColumnInfo[];
|
||||
}
|
||||
|
||||
/** 列信息 */
|
||||
export interface ColumnInfo {
|
||||
cid: number;
|
||||
name: string;
|
||||
type: string;
|
||||
notnull: boolean;
|
||||
pk: boolean;
|
||||
}
|
||||
|
||||
/** 单个数据库扫描结果 */
|
||||
export interface DatabaseScanResult {
|
||||
/** 数据库文件名 */
|
||||
filename: string;
|
||||
/** 原始加密文件路径 */
|
||||
sourcePath: string;
|
||||
/** 解密后缓存文件路径 (仅当指定了 cacheDir 时) */
|
||||
cachePath?: string;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
tables: TableInfo[];
|
||||
}
|
||||
|
||||
/** 扫描/读取选项 */
|
||||
export interface DatabaseReadOptions {
|
||||
/** 解密后数据库缓存目录,不设置则使用临时文件 */
|
||||
cacheDir?: string;
|
||||
/** 是否跳过已存在的缓存文件 (默认 true) */
|
||||
skipExistingCache?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 DatabaseSync 对象提取表信息
|
||||
*/
|
||||
function extractTablesInfo (db: DatabaseSyncType): TableInfo[] {
|
||||
const tables: TableInfo[] = [];
|
||||
|
||||
const masterRows = db.prepare(
|
||||
"SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY name"
|
||||
).all() as { name: string; type: string; }[];
|
||||
|
||||
for (const { name: tableName, type: tableType } of masterRows) {
|
||||
// 获取列信息
|
||||
const columns: ColumnInfo[] = [];
|
||||
try {
|
||||
const cols = db.prepare(`PRAGMA table_info([${tableName}])`).all() as {
|
||||
cid: number; name: string; type: string; notnull: number; pk: number;
|
||||
}[];
|
||||
for (const col of cols) {
|
||||
columns.push({
|
||||
cid: col.cid,
|
||||
name: col.name,
|
||||
type: col.type,
|
||||
notnull: col.notnull === 1,
|
||||
pk: col.pk === 1,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// PRAGMA 可能对某些表失败
|
||||
}
|
||||
|
||||
// 获取行数
|
||||
let rowCount = 0;
|
||||
try {
|
||||
const cnt = db.prepare(`SELECT count(*) as cnt FROM [${tableName}]`).get() as { cnt: number; } | undefined;
|
||||
rowCount = cnt?.cnt ?? 0;
|
||||
} catch {
|
||||
rowCount = -1;
|
||||
}
|
||||
|
||||
tables.push({
|
||||
name: tableName,
|
||||
type: tableType,
|
||||
rowCount,
|
||||
columns,
|
||||
});
|
||||
}
|
||||
|
||||
return tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个解密后的 SQLite 文件,列出所有表和列信息
|
||||
*/
|
||||
export function listTablesFromFile (filePath: string): TableInfo[] {
|
||||
const DB = getDatabaseSync();
|
||||
const db = new DB(filePath, { readOnly: true });
|
||||
try {
|
||||
return extractTablesInfo(db);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function listTablesFromBuffer (data: Buffer): TableInfo[] {
|
||||
const tmpPath = path.join(os.tmpdir(), `napcat_db_${Date.now()}_${Math.random().toString(36).slice(2)}.db`);
|
||||
try {
|
||||
fs.writeFileSync(tmpPath, data);
|
||||
return listTablesFromFile(tmpPath);
|
||||
} finally {
|
||||
try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密并读取单个数据库文件
|
||||
*
|
||||
* @param dbPath 加密数据库文件路径
|
||||
* @param passphrase 密钥口令
|
||||
* @param options 可选配置 (缓存目录等)
|
||||
* @returns 数据库扫描结果
|
||||
*/
|
||||
export function readSingleDatabase (
|
||||
dbPath: string,
|
||||
passphrase: Buffer,
|
||||
options?: DatabaseReadOptions
|
||||
): DatabaseScanResult {
|
||||
const filename = path.basename(dbPath);
|
||||
const result: DatabaseScanResult = {
|
||||
filename,
|
||||
sourcePath: dbPath,
|
||||
success: false,
|
||||
tables: [],
|
||||
};
|
||||
|
||||
try {
|
||||
// 如果指定了缓存目录,且缓存文件已存在,直接读取
|
||||
if (options?.cacheDir) {
|
||||
const cachedPath = path.join(options.cacheDir, filename);
|
||||
result.cachePath = cachedPath;
|
||||
|
||||
if (options?.skipExistingCache !== false && fs.existsSync(cachedPath)) {
|
||||
result.tables = listTablesFromFile(cachedPath);
|
||||
result.success = true;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
const fileData = fs.readFileSync(dbPath);
|
||||
if (!isEncryptedNTDB(fileData)) {
|
||||
result.error = 'Not an encrypted NTQQ database';
|
||||
return result;
|
||||
}
|
||||
|
||||
// 有缓存目录: 解密写入文件再读取
|
||||
if (options?.cacheDir) {
|
||||
fs.mkdirSync(options.cacheDir, { recursive: true });
|
||||
const outPath = decryptDatabaseFile(dbPath, passphrase, result.cachePath);
|
||||
if (!outPath) {
|
||||
result.error = 'Decryption failed';
|
||||
return result;
|
||||
}
|
||||
result.cachePath = outPath;
|
||||
result.tables = listTablesFromFile(outPath);
|
||||
} else {
|
||||
// 无缓存目录: 解密到内存再用临时文件读取
|
||||
const decryptedBuf = decryptDatabase(fileData, passphrase);
|
||||
if (!decryptedBuf) {
|
||||
result.error = 'Decryption returned null';
|
||||
return result;
|
||||
}
|
||||
result.tables = listTablesFromBuffer(decryptedBuf);
|
||||
}
|
||||
|
||||
result.success = true;
|
||||
} catch (e) {
|
||||
result.error = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function scanAllDatabases (
|
||||
dbDir: string,
|
||||
passphrase: Buffer,
|
||||
options?: DatabaseReadOptions
|
||||
): DatabaseScanResult[] {
|
||||
const results: DatabaseScanResult[] = [];
|
||||
|
||||
if (!fs.existsSync(dbDir)) return results;
|
||||
|
||||
const files = fs.readdirSync(dbDir).filter(f => f.endsWith('.db')).sort();
|
||||
|
||||
for (const filename of files) {
|
||||
const filePath = path.join(dbDir, filename);
|
||||
const result = readSingleDatabase(filePath, passphrase, options);
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化扫描结果为可读字符串
|
||||
*/
|
||||
export function formatScanResults (results: DatabaseScanResult[]): string {
|
||||
const lines: string[] = [];
|
||||
let totalTables = 0;
|
||||
let successCount = 0;
|
||||
|
||||
for (const db of results) {
|
||||
if (db.success) {
|
||||
successCount++;
|
||||
const cacheNote = db.cachePath ? ` → ${db.cachePath}` : '';
|
||||
lines.push(`=== ${db.filename} (${db.tables.length} tables)${cacheNote} ===`);
|
||||
for (const table of db.tables) {
|
||||
totalTables++;
|
||||
const colList = table.columns.map(c => `${c.name}:${c.type || '?'}`).join(', ');
|
||||
lines.push(` ${table.name}: ${table.rowCount} rows [${colList}]`);
|
||||
}
|
||||
} else {
|
||||
lines.push(`=== ${db.filename}: SKIP (${db.error}) ===`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
lines.push(`Summary: ${successCount}/${results.length} databases decrypted, ${totalTables} total tables`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -47,12 +47,12 @@ const itemsToCopy = [
|
||||
'package.json',
|
||||
'QBar.dll',
|
||||
'wrapper.node',
|
||||
'LightQuic.dll'
|
||||
'LightQuic.dll',
|
||||
];
|
||||
|
||||
const win64ItemsToCopy = [
|
||||
'SSOShareInfoHelper64.dll',
|
||||
'parent-ipc-core-x64.dll'
|
||||
'parent-ipc-core-x64.dll',
|
||||
];
|
||||
|
||||
async function copyAll () {
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
// LiteLoader需要提供部分IPC接口,以便于其他插件调用
|
||||
const { ipcMain, BrowserWindow } = require('electron');
|
||||
const napcat = require('./napcat.cjs');
|
||||
const { shell } = require('electron');
|
||||
ipcMain.handle('napcat_get_webui', async () => {
|
||||
return napcat.NCgetWebUiUrl();
|
||||
});
|
||||
ipcMain.on('open_external_url', (event, url) => {
|
||||
shell.openExternal(url);
|
||||
});
|
||||
ipcMain.on('napcat_open_inner_url', (event, url) => {
|
||||
const win = new BrowserWindow({
|
||||
autoHideMenuBar: true,
|
||||
});
|
||||
win.loadURL(url);
|
||||
win.webContents.setWindowOpenHandler(details => {
|
||||
win.loadURL(details.url);
|
||||
});
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"manifest_version": 4,
|
||||
"type": "extension",
|
||||
"name": "NapCatQQ",
|
||||
"slug": "NapCat.Framework",
|
||||
"description": "高性能的 OneBot 11 协议实现",
|
||||
"version": "0.0.1",
|
||||
"icon": "./logo.png",
|
||||
"authors": [
|
||||
{
|
||||
"name": "NapNeko",
|
||||
"link": "https://github.com/NapNeko"
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
"repo": "NapNeko/NapCatQQ",
|
||||
"branch": "main"
|
||||
},
|
||||
"platform": [
|
||||
"win32",
|
||||
"linux",
|
||||
"darwin"
|
||||
],
|
||||
"injects": {
|
||||
"renderer": "./renderer.js",
|
||||
"main": "./liteloader.cjs",
|
||||
"preload": "./preload.cjs"
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { InitWebUi, WebUiConfig, webUiRuntimePort } from 'napcat-webui-backend/i
|
||||
import { NapCatAdapterManager } from 'napcat-adapter';
|
||||
import { NativePacketHandler } from 'napcat-core/packet/handler/client';
|
||||
import { Napi2NativeLoader } from 'napcat-core/packet/handler/napi2nativeLoader';
|
||||
import { loadNapcatConfig } from '@/napcat-core/helper/config';
|
||||
import { FFmpegService } from 'napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import { logSubscription, LogWrapper } from 'napcat-core/helper/log';
|
||||
import { QQBasicInfoWrapper } from '@/napcat-core/helper/qq-basic-info';
|
||||
@@ -11,6 +12,8 @@ import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
|
||||
import { statusHelperSubscription } from '@/napcat-core/helper/status';
|
||||
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
|
||||
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OidbSvcTrpcTcpBase, OidbSvcTrpcTcp0XCDE_2RespBody } from '@/napcat-core/packet/transformer/proto';
|
||||
|
||||
// Framework ES入口文件
|
||||
export async function getWebUiUrl () {
|
||||
@@ -42,33 +45,66 @@ export async function NCoreInitFramework (
|
||||
const wrapper = loadQQWrapper(basicInfoWrapper.QQMainPath, basicInfoWrapper.getFullQQVersion());
|
||||
const nativePacketHandler = new NativePacketHandler({ logger }); // 初始化 NativePacketHandler 用于后续使用
|
||||
const napi2nativeLoader = new Napi2NativeLoader({ logger }); // 初始化 Napi2NativeLoader 用于后续使用
|
||||
//console.log('[NapCat] [Napi2NativeLoader]', napi2nativeLoader.nativeExports.enableAllBypasses?.());
|
||||
const napcatConfig = loadNapcatConfig(pathWrapper.configPath);
|
||||
// console.log('[NapCat] [Napi2NativeLoader]', napi2nativeLoader.nativeExports.enableAllBypasses?.());
|
||||
if (process.env['NAPCAT_DISABLE_BYPASS'] !== '1') {
|
||||
const bypassEnabled = napi2nativeLoader.nativeExports.enableAllBypasses?.();
|
||||
const bypassOptions = napcatConfig.bypass ?? {};
|
||||
const bypassEnabled = napi2nativeLoader.nativeExports.enableAllBypasses?.(bypassOptions);
|
||||
if (bypassEnabled) {
|
||||
logger.log('[NapCat] Napi2NativeLoader: 已启用Bypass');
|
||||
}
|
||||
logger.log('[NapCat] Napi2NativeLoader: Framework模式Bypass配置:', bypassOptions);
|
||||
} else {
|
||||
logger.log('[NapCat] Napi2NativeLoader: Bypass已通过环境变量禁用');
|
||||
}
|
||||
// nativePacketHandler.onAll((packet) => {
|
||||
// console.log('[Packet]', packet.uin, packet.cmd, packet.hex_data);
|
||||
// });
|
||||
await nativePacketHandler.init(basicInfoWrapper.getFullQQVersion());
|
||||
await nativePacketHandler.init(basicInfoWrapper.getFullQQVersion(), napcatConfig.o3HookMode === 1);
|
||||
// 在 init 之后注册监听器
|
||||
|
||||
// 登录前监听 OidbSvcTrpcTcp.0xcde_2 数据包,获取数据库 passphrase
|
||||
let dbPassphrase: string | undefined;
|
||||
nativePacketHandler.onCmd('OidbSvcTrpcTcp.0xcde_2', ({ type, hex_data }) => {
|
||||
if (type !== 1) return; // 仅处理接收方向
|
||||
try {
|
||||
const raw = Buffer.from(hex_data, 'hex');
|
||||
const base = new NapProtoMsg(OidbSvcTrpcTcpBase).decode(raw);
|
||||
if (base.body && base.body.length > 0) {
|
||||
const body = new NapProtoMsg(OidbSvcTrpcTcp0XCDE_2RespBody).decode(base.body);
|
||||
if (body.inner?.value) {
|
||||
dbPassphrase = body.inner.value;
|
||||
logger.log('[NapCat] 已启用数据库辅助支持能力');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.logError('[NapCat] [0xCDE_2] 解析失败:', e);
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化 FFmpeg 服务
|
||||
await FFmpegService.init(pathWrapper.binaryPath, logger);
|
||||
|
||||
// 提前启动 WebUI,使其在登录前可用,支持通过 WebUI 操控登录过程
|
||||
WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework);
|
||||
InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e));
|
||||
|
||||
// 直到登录成功后,执行下一步
|
||||
// const selfInfo = {
|
||||
// uid: 'u_FUSS0_x06S_9Tf4na_WpUg',
|
||||
// uin: '3684714082',
|
||||
// nick: '',
|
||||
// online: true
|
||||
// }
|
||||
const selfInfo = await new Promise<SelfInfo>((resolve) => {
|
||||
const loginContext = { isLogined: false };
|
||||
|
||||
const loginListener = new NodeIKernelLoginListener();
|
||||
|
||||
loginListener.onUserLoggedIn = (userid: string) => {
|
||||
const tips = `当前账号(${userid})已登录,无法重复登录`;
|
||||
logger.logError(tips);
|
||||
WebUiDataRuntime.setQQLoginError(tips);
|
||||
};
|
||||
|
||||
loginListener.onQRCodeLoginSucceed = async (loginResult) => {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
await new Promise<void>(resolve => {
|
||||
registerInitCallback(() => resolve());
|
||||
});
|
||||
@@ -79,18 +115,78 @@ export async function NCoreInitFramework (
|
||||
online: true,
|
||||
});
|
||||
};
|
||||
|
||||
loginListener.onQRCodeGetPicture = ({ qrcodeUrl }) => {
|
||||
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
|
||||
logger.log('[NapCat] [Framework] 二维码已更新, URL:', qrcodeUrl);
|
||||
};
|
||||
|
||||
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number) => {
|
||||
if (!loginContext.isLogined) {
|
||||
logger.logError('[NapCat] [Framework] [Login] QRCode Session Failed, ErrType:', errType, 'ErrCode:', errCode);
|
||||
if (errType === 1 && errCode === 3) {
|
||||
WebUiDataRuntime.setQQLoginError('二维码已过期,请刷新');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loginListener.onLoginFailed = (...args) => {
|
||||
const errInfo = JSON.stringify(args);
|
||||
logger.logError('[NapCat] [Framework] [Login] Login Failed, ErrInfo:', errInfo);
|
||||
WebUiDataRuntime.setQQLoginError(`登录失败: ${errInfo}`);
|
||||
};
|
||||
|
||||
loginListener.onLoginConnected = () => {
|
||||
logger.log('[NapCat] [Framework] 登录服务已连接');
|
||||
// 注册 WebUI 登录操作回调
|
||||
registerWebUiLoginCallbacks(loginService, loginContext, logger);
|
||||
// 获取历史登录列表供 WebUI 使用
|
||||
loginService.getLoginList().then((res) => {
|
||||
const list = res.LocalLoginInfoList.filter((item) => item.isQuickLogin);
|
||||
WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
|
||||
WebUiDataRuntime.setQQNewLoginList(list);
|
||||
}).catch(e => logger.logError('[NapCat] [Framework] 获取登录列表失败:', e));
|
||||
};
|
||||
|
||||
loginListener.onQRCodeSessionUserScaned = () => {
|
||||
logger.log('[NapCat] [Framework] 二维码已被扫描,等待确认...');
|
||||
};
|
||||
|
||||
loginListener.onPasswordLoginFailed = (...args) => {
|
||||
logger.logError('[NapCat] [Framework] 密码登录失败:', ...args);
|
||||
};
|
||||
|
||||
loginService.addKernelLoginListener(proxiedListenerOf(loginListener, logger));
|
||||
});
|
||||
// 过早进入会导致addKernelMsgListener等Listener添加失败
|
||||
// await sleep(2500);
|
||||
// 初始化 NapCatFramework
|
||||
const loaderObject = new NapCatFramework(wrapper, session, logger, selfInfo, basicInfoWrapper, pathWrapper, nativePacketHandler, napi2nativeLoader);
|
||||
// 将捕获的 passphrase 设置到 core 上,供 DatabaseApi 使用
|
||||
if (dbPassphrase) {
|
||||
loaderObject.core.dbPassphrase = dbPassphrase;
|
||||
}
|
||||
await loaderObject.core.initCore();
|
||||
|
||||
// 启动WebUi
|
||||
WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework);
|
||||
// 登录成功后设置数据路径
|
||||
WebUiDataRuntime.setQQDataPath(loaderObject.core.dataPath);
|
||||
InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e));
|
||||
|
||||
// // 测试 DatabaseApi
|
||||
// if (dbPassphrase) {
|
||||
// const dbApi = loaderObject.core.apis.DatabaseApi;
|
||||
// const sqliteOk = await dbApi.isSqliteAvailable();
|
||||
// if (sqliteOk) {
|
||||
// try {
|
||||
// const result = dbApi.readDatabase('nt_msg.db');
|
||||
// if (result) {
|
||||
// logger.log('[NapCat] [Database] nt_msg.db:\n' + dbApi.formatResults([result]));
|
||||
// }
|
||||
// } catch (e) {
|
||||
// logger.logError('[NapCat] [Database] 读取失败:', e);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// 使用 NapCatAdapterManager 统一管理协议适配器
|
||||
const adapterManager = new NapCatAdapterManager(loaderObject.core, loaderObject.context, pathWrapper);
|
||||
await adapterManager.initAdapters();
|
||||
@@ -101,6 +197,164 @@ export async function NCoreInitFramework (
|
||||
}
|
||||
}
|
||||
|
||||
function registerWebUiLoginCallbacks (
|
||||
loginService: NodeIKernelLoginService,
|
||||
loginContext: { isLogined: boolean; },
|
||||
logger: LogWrapper
|
||||
) {
|
||||
// 刷新二维码
|
||||
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
|
||||
loginService.getQRCodePicture();
|
||||
});
|
||||
|
||||
// 快速登录
|
||||
WebUiDataRuntime.setQuickLoginCall(async (uin: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin) {
|
||||
return resolve({ result: false, message: '快速登录失败' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在快速登录', uin);
|
||||
loginService.quickLoginWithUin(uin).then(res => {
|
||||
const success = res.result === '0' && !res.loginErrorInfo?.errMsg;
|
||||
if (!success) {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || `快速登录失败,错误码: ${res.result}`;
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 快速登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('快速登录发生错误');
|
||||
resolve({ result: false, message: '快速登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 密码登录
|
||||
WebUiDataRuntime.setPasswordLoginCall(async (uin: string, passwordMd5: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin || !passwordMd5) {
|
||||
return resolve({ result: false, message: '密码登录失败:参数不完整' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在密码登录', uin);
|
||||
loginService.passwordLogin({
|
||||
uin,
|
||||
passwordMd5,
|
||||
step: 0,
|
||||
newDeviceLoginSig: new Uint8Array(),
|
||||
proofWaterSig: new Uint8Array(),
|
||||
proofWaterRand: new Uint8Array(),
|
||||
proofWaterSid: new Uint8Array(),
|
||||
unusualDeviceCheckSig: new Uint8Array(),
|
||||
}).then(res => {
|
||||
if (res.result === '140022008') {
|
||||
const proofWaterUrl = res.loginErrorInfo?.proofWaterUrl || '';
|
||||
resolve({ result: false, message: '需要验证码', needCaptcha: true, proofWaterUrl });
|
||||
} else if (res.result === '140022010' || res.result === '140022011') {
|
||||
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
|
||||
const newDevicePullQrCodeSig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
|
||||
resolve({ result: false, message: '新设备需要扫码验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig });
|
||||
} else if (res.result !== '0') {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || '密码登录失败';
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 密码登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('密码登录发生错误');
|
||||
resolve({ result: false, message: '密码登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 验证码登录(密码登录需要验证码时的第二步)
|
||||
WebUiDataRuntime.setCaptchaLoginCall(async (uin: string, passwordMd5: string, ticket: string, randstr: string, sid: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin || !passwordMd5 || !ticket) {
|
||||
return resolve({ result: false, message: '验证码登录失败:参数不完整' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在验证码登录', uin);
|
||||
loginService.passwordLogin({
|
||||
uin,
|
||||
passwordMd5,
|
||||
step: 1,
|
||||
newDeviceLoginSig: new Uint8Array(),
|
||||
proofWaterSig: new TextEncoder().encode(ticket),
|
||||
proofWaterRand: new TextEncoder().encode(randstr),
|
||||
proofWaterSid: new TextEncoder().encode(sid),
|
||||
unusualDeviceCheckSig: new Uint8Array(),
|
||||
}).then(res => {
|
||||
if (res.result === '140022010' || res.result === '140022011') {
|
||||
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
|
||||
const newDevicePullQrCodeSig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
|
||||
resolve({ result: false, message: '新设备需要扫码验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig });
|
||||
} else if (res.result !== '0') {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || '验证码登录失败';
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 验证码登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('验证码登录发生错误');
|
||||
resolve({ result: false, message: '验证码登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 新设备验证登录(密码登录需要新设备验证时的第二步)
|
||||
WebUiDataRuntime.setNewDeviceLoginCall(async (uin: string, passwordMd5: string, newDevicePullQrCodeSig: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin || !passwordMd5 || !newDevicePullQrCodeSig) {
|
||||
return resolve({ result: false, message: '新设备验证登录失败:参数不完整' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在新设备验证登录', uin);
|
||||
loginService.passwordLogin({
|
||||
uin,
|
||||
passwordMd5,
|
||||
step: 2,
|
||||
newDeviceLoginSig: new TextEncoder().encode(newDevicePullQrCodeSig),
|
||||
proofWaterSig: new Uint8Array(),
|
||||
proofWaterRand: new Uint8Array(),
|
||||
proofWaterSid: new Uint8Array(),
|
||||
unusualDeviceCheckSig: new Uint8Array(),
|
||||
}).then(res => {
|
||||
if (res.result === '140022011') {
|
||||
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
|
||||
const sig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
|
||||
resolve({ result: false, message: '异常设备需要验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig: sig });
|
||||
} else if (res.result !== '0') {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || '新设备验证登录失败';
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 新设备验证登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('新设备验证登录发生错误');
|
||||
resolve({ result: false, message: '新设备验证登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export class NapCatFramework {
|
||||
public core: NapCatCore;
|
||||
context: InstanceContext;
|
||||
|
||||
@@ -19,10 +19,13 @@
|
||||
"dependencies": {
|
||||
"napcat-core": "workspace:*",
|
||||
"napcat-common": "workspace:*",
|
||||
"napcat-database": "workspace:*",
|
||||
"napcat-protobuf": "workspace:*",
|
||||
"napcat-adapter": "workspace:*",
|
||||
"napcat-webui-backend": "workspace:*",
|
||||
"napcat-vite": "workspace:*",
|
||||
"napcat-qrcode": "workspace:*"
|
||||
"napcat-qrcode": "workspace:*",
|
||||
"json5": "^2.2.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1"
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
const { contextBridge, ipcRenderer } = require('electron');
|
||||
const napcat = {
|
||||
getWebUiUrl: async () => {
|
||||
return ipcRenderer.invoke('napcat_get_webui');
|
||||
},
|
||||
openExternalUrl: async (url) => {
|
||||
ipcRenderer.send('open_external_url', url);
|
||||
},
|
||||
openInnerUrl: async (url) => {
|
||||
ipcRenderer.send('napcat_open_inner_url', url);
|
||||
},
|
||||
};
|
||||
// 在window对象下导出只读对象
|
||||
contextBridge.exposeInMainWorld('napcat', napcat);
|
||||
@@ -1,41 +0,0 @@
|
||||
export const onSettingWindowCreated = async (view) => {
|
||||
const webui = await window.napcat.getWebUiUrl();
|
||||
view.innerHTML = `
|
||||
<setting-section data-title="">
|
||||
<setting-panel>
|
||||
<setting-list data-direction="column">
|
||||
<setting-item>
|
||||
<setting-button data-type="primary" class="nc_openwebui">在QQ内打开配置页面</setting-button>
|
||||
<setting-button data-type="primary" class="nc_openwebui_ex">在默认浏览器打开配置页面</setting-button>
|
||||
</setting-item>
|
||||
<setting-item>
|
||||
<div>
|
||||
<setting-text>WebUi远程地址可以点击下方复制哦~</setting-text>
|
||||
<setting-text class="nc_webui">WebUi</setting-text>
|
||||
</div>
|
||||
</setting-item>
|
||||
</setting-list>
|
||||
</setting-panel>
|
||||
</setting-section>
|
||||
`;
|
||||
|
||||
view.querySelector('.nc_openwebui').addEventListener('click', () => {
|
||||
window.napcat.openInnerUrl(webui);
|
||||
});
|
||||
view.querySelector('.nc_openwebui_ex').addEventListener('click', () => {
|
||||
window.napcat.openExternalUrl(webui);
|
||||
});
|
||||
|
||||
view.querySelector('.nc_webui').innerText = webui;
|
||||
|
||||
// 添加点击复制功能
|
||||
view.querySelector('.nc_webui').addEventListener('click', async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(webui);
|
||||
// eslint-disable-next-line no-undef
|
||||
alert('WebUi URL 已复制到剪贴板');
|
||||
} catch (err) {
|
||||
console.error('复制到剪贴板失败: ', err);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -11,7 +11,7 @@ const external = [
|
||||
'ws',
|
||||
'express',
|
||||
];
|
||||
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
|
||||
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat();
|
||||
const FrameworkBaseConfigPlugin: PluginOption[] = [
|
||||
autoIncludeTSPlugin({
|
||||
entries: [
|
||||
@@ -24,10 +24,8 @@ const FrameworkBaseConfigPlugin: PluginOption[] = [
|
||||
targets: [
|
||||
{ src: '../napcat-napi-loader/', dest: 'dist', flatten: true },
|
||||
{ src: '../napcat-native/', dest: 'dist/native', flatten: false },
|
||||
{ src: './manifest.json', dest: 'dist' },
|
||||
{ src: '../napcat-core/external/napcat.json', dest: 'dist/config/' },
|
||||
{ src: '../napcat-webui-frontend/dist/', dest: 'dist/static/', flatten: false },
|
||||
{ src: './liteloader.cjs', dest: 'dist' },
|
||||
{ src: './napcat.cjs', dest: 'dist' },
|
||||
{ src: './nativeLoader.cjs', dest: 'dist' },
|
||||
{ src: './preload.cjs', dest: 'dist' },
|
||||
|
||||
@@ -158,7 +158,7 @@ function bufferToReadStream (buffer: Buffer): ReadStream {
|
||||
read () {
|
||||
this.push(buffer);
|
||||
this.push(null);
|
||||
}
|
||||
},
|
||||
});
|
||||
return readable as unknown as ReadStream;
|
||||
}
|
||||
|
||||
@@ -63,7 +63,6 @@ export class JpegParser implements ImageParser {
|
||||
const bufferSize = buffer.length;
|
||||
const MIN_REQUIRED_BYTES = 10; // SOF段最低字节数
|
||||
|
||||
|
||||
// 从JPEG头部后开始扫描
|
||||
while (offset < bufferSize - MIN_REQUIRED_BYTES) {
|
||||
// 寻找FF标记
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,5 +1,6 @@
|
||||
import { ActionName, BaseCheckResult } from './router';
|
||||
import Ajv, { ErrorObject, ValidateFunction } from 'ajv';
|
||||
import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { NapCatCore } from 'napcat-core';
|
||||
import { NapCatOneBot11Adapter, OB11Return } from '@/napcat-onebot/index';
|
||||
import { NetworkAdapterConfig } from '../config/config';
|
||||
@@ -10,9 +11,9 @@ export const ActionExamples = {
|
||||
errors: [
|
||||
{ code: 1400, description: '请求参数错误或业务逻辑执行失败' },
|
||||
{ code: 1401, description: '权限不足' },
|
||||
{ code: 1404, description: '资源不存在' }
|
||||
]
|
||||
}
|
||||
{ code: 1404, description: '资源不存在' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export class OB11Response {
|
||||
@@ -46,7 +47,7 @@ export abstract class OneBotRequestToolkit {
|
||||
export abstract class OneBotAction<PayloadType, ReturnDataType> {
|
||||
actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown;
|
||||
core: NapCatCore;
|
||||
private validate?: ValidateFunction<unknown> = undefined;
|
||||
private validate?: TypeCheck<TSchema> = undefined;
|
||||
payloadSchema?: TSchema = undefined;
|
||||
returnSchema?: TSchema = undefined;
|
||||
payloadExample?: unknown = undefined;
|
||||
@@ -64,15 +65,23 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
|
||||
}
|
||||
|
||||
protected async check (payload: PayloadType): Promise<BaseCheckResult> {
|
||||
if (this.payloadSchema) {
|
||||
this.validate = new Ajv({ allowUnionTypes: true, useDefaults: true, coerceTypes: true }).compile(this.payloadSchema);
|
||||
if (!this.payloadSchema) return { valid: true };
|
||||
try {
|
||||
this.validate = TypeCompiler.Compile(this.payloadSchema);
|
||||
let data = payload;
|
||||
data = Value.Parse(this.payloadSchema, data) as PayloadType;
|
||||
if (typeof payload === 'object' && payload !== null && data !== null) {
|
||||
Object.assign(payload, data);
|
||||
}
|
||||
} catch (e: any) {
|
||||
return { valid: false, message: `Schema compilation error: ${e.message}` };
|
||||
}
|
||||
if (this.validate && !this.validate(payload)) {
|
||||
const errors = this.validate.errors as ErrorObject[];
|
||||
const errorMessages = errors.map(e => `Key: ${e.instancePath.split('/').slice(1).join('.')}, Message: ${e.message}`);
|
||||
if (this.validate && !this.validate.Check(payload)) {
|
||||
const errors = [...this.validate.Errors(payload)];
|
||||
const errorMessages = errors.map(e => `Key: ${e.path.split('/').slice(1).join('.')}, Message: ${e.message}`);
|
||||
return {
|
||||
valid: false,
|
||||
message: errorMessages.join('\n') ?? '未知错误',
|
||||
message: errorMessages.length > 0 ? errorMessages.join('\n') : '未知错误',
|
||||
};
|
||||
}
|
||||
return { valid: true };
|
||||
|
||||
@@ -9,9 +9,9 @@ export const ExtendsActionsExamples = {
|
||||
{
|
||||
type: 'string',
|
||||
characters: [
|
||||
{ character_id: 'id', character_name: 'name', preview_url: 'url' }
|
||||
]
|
||||
}
|
||||
{ character_id: 'id', character_name: 'name', preview_url: 'url' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
GetClientkey: {
|
||||
|
||||
@@ -11,4 +11,12 @@ export const PacketActionsExamples = {
|
||||
payload: { group_id: '123456', message_id: '123456789' },
|
||||
response: {},
|
||||
},
|
||||
CompleteGroupTodo: {
|
||||
payload: { group_id: '123456', message_id: '123456789' },
|
||||
response: {},
|
||||
},
|
||||
CancelGroupTodo: {
|
||||
payload: { group_id: '123456', message_id: '123456789' },
|
||||
response: {},
|
||||
},
|
||||
};
|
||||
@@ -27,10 +27,12 @@ export class ClickInlineKeyboardButton extends OneBotAction<PayloadType, ReturnT
|
||||
bot_appid: '1234567890',
|
||||
button_id: 'btn_1',
|
||||
callback_data: '',
|
||||
msg_seq: '10086'
|
||||
msg_seq: '10086',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
return await this.core.apis.MsgApi.clickInlineKeyboardButton({
|
||||
buttonId: payload.button_id,
|
||||
|
||||
@@ -21,11 +21,12 @@ export class CreateCollection extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionTags = ['扩展接口'];
|
||||
override payloadExample = {
|
||||
rawData: '收藏内容',
|
||||
brief: '收藏标题'
|
||||
brief: '收藏标题',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: 0,
|
||||
errMsg: ''
|
||||
errMsg: '',
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
|
||||
@@ -23,9 +23,11 @@ export class DelGroupAlbumMedia extends OneBotAction<PayloadType, ReturnType> {
|
||||
album_id: 'album_id_1',
|
||||
lloc: 'media_id_1',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: {}
|
||||
result: {},
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -19,11 +19,13 @@ export class DoGroupAlbumComment extends OneBotAction<DoGroupAlbumCommentPayload
|
||||
group_id: '123456',
|
||||
album_id: 'album_id_1',
|
||||
lloc: 'media_id_1',
|
||||
content: '很有意思'
|
||||
content: '很有意思',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: {}
|
||||
result: {},
|
||||
};
|
||||
|
||||
override payloadSchema = DoGroupAlbumCommentPayloadSchema;
|
||||
override returnSchema = Type.Any({ description: '评论结果' });
|
||||
|
||||
|
||||
@@ -19,10 +19,11 @@ export class FetchCustomFace extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionSummary = '获取自定义表情';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
count: 10
|
||||
count: 10,
|
||||
};
|
||||
|
||||
override returnExample = [
|
||||
'http://example.com/face1.png'
|
||||
'http://example.com/face1.png',
|
||||
];
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
@@ -30,4 +31,3 @@ export class FetchCustomFace extends OneBotAction<PayloadType, ReturnType> {
|
||||
return ret.emojiInfoList.map(e => e.url);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ const PayloadSchema = Type.Object({
|
||||
emojiId: Type.Union([Type.Number(), Type.String()], { description: '表情ID' }),
|
||||
emojiType: Type.Union([Type.Number(), Type.String()], { description: '表情类型' }),
|
||||
count: Type.Union([Type.Number(), Type.String()], { default: 20, description: '获取数量' }),
|
||||
cookie: Type.String({ default: '', description: '分页Cookie' })
|
||||
cookie: Type.String({ default: '', description: '分页Cookie' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
@@ -37,22 +37,24 @@ export class FetchEmojiLike extends OneBotAction<PayloadType, ReturnType> {
|
||||
emojiId: '123',
|
||||
emojiType: 1,
|
||||
count: 10,
|
||||
cookie: ''
|
||||
cookie: '',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
emojiLikesList: [
|
||||
{
|
||||
tinyId: '123456',
|
||||
nickName: '测试用户',
|
||||
headUrl: 'http://example.com/avatar.png'
|
||||
}
|
||||
headUrl: 'http://example.com/avatar.png',
|
||||
},
|
||||
],
|
||||
cookie: '',
|
||||
isLastPage: true,
|
||||
isFirstPage: true,
|
||||
result: 0,
|
||||
errMsg: ''
|
||||
errMsg: '',
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -21,32 +21,33 @@ export class GetCollectionList extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
category: '0',
|
||||
count: '50'
|
||||
count: '50',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
errCode: 0,
|
||||
errMsg: "",
|
||||
errMsg: '',
|
||||
collectionSearchList: {
|
||||
collectionItemList: [
|
||||
{
|
||||
cid: "123456",
|
||||
cid: '123456',
|
||||
type: 8,
|
||||
status: 1,
|
||||
author: {
|
||||
type: 2,
|
||||
numId: "123456",
|
||||
strId: "昵称",
|
||||
groupId: "123456",
|
||||
groupName: "群名",
|
||||
uid: "123456"
|
||||
numId: '123456',
|
||||
strId: '昵称',
|
||||
groupId: '123456',
|
||||
groupName: '群名',
|
||||
uid: '123456',
|
||||
},
|
||||
bid: 1,
|
||||
category: 1,
|
||||
createTime: "1769169157000",
|
||||
collectTime: "1769413477691",
|
||||
modifyTime: "1769413477691",
|
||||
sequence: "1769413476735",
|
||||
shareUrl: "",
|
||||
createTime: '1769169157000',
|
||||
collectTime: '1769413477691',
|
||||
modifyTime: '1769413477691',
|
||||
sequence: '1769413476735',
|
||||
shareUrl: '',
|
||||
customGroupId: 0,
|
||||
securityBeat: false,
|
||||
summary: {
|
||||
@@ -58,21 +59,21 @@ export class GetCollectionList extends OneBotAction<PayloadType, ReturnType> {
|
||||
fileSummary: null,
|
||||
locationSummary: null,
|
||||
richMediaSummary: {
|
||||
title: "",
|
||||
subTitle: "",
|
||||
brief: "text",
|
||||
title: '',
|
||||
subTitle: '',
|
||||
brief: 'text',
|
||||
picList: [],
|
||||
contentType: 1,
|
||||
originalUri: "",
|
||||
publisher: "",
|
||||
richMediaVersion: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
originalUri: '',
|
||||
publisher: '',
|
||||
richMediaVersion: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
hasMore: false,
|
||||
bottomTimeStamp: "1769413477691"
|
||||
}
|
||||
bottomTimeStamp: '1769413477691',
|
||||
},
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
|
||||
Loaded 100 of 331 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user