Initial commit: TaskPool React panel

- React frontend with route-level code splitting
- Backend rebranded from Baihu to TaskPool
- DB brand migration script and local compatibility
This commit is contained in:
2026-07-26 08:43:52 +08:00
commit e6956aa001
397 changed files with 73621 additions and 0 deletions
+187
View File
@@ -0,0 +1,187 @@
const http = require('http');
const https = require('https');
const { URL } = require('url');
/**
* 内部 API 请求辅助函数
*/
function request(urlStr, method = 'GET', data = null) {
const token = process.env.BHPKG_OPENAPI_TOKEN || process.env.OPENAPI_TOKEN || process.env.BHPKG_NOTIFY_TOKEN;
if (!token) {
throw new Error(`没有正确配置或缺少 BHPKG_OPENAPI_TOKEN 环境变量以使用 env 函数。请在任务池的任务设置中配置这些 Key。`);
}
const parsedUrl = new URL(urlStr);
const protocol = parsedUrl.protocol === 'https:' ? https : http;
let payload = '';
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
if (data !== null) {
payload = JSON.stringify(data);
headers['Content-Length'] = Buffer.byteLength(payload);
}
const options = {
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.pathname + (parsedUrl.search || ''),
method: method,
headers: headers
};
return new Promise((resolve, reject) => {
const req = protocol.request(options, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
try {
const parsed = body ? JSON.parse(body) : {};
if (parsed && typeof parsed === 'object' && parsed.code !== undefined && parsed.code !== 200) {
reject(new Error(`请求失败 [${parsed.code}]: ${parsed.msg || parsed.message || '未知错误'}`));
} else {
resolve(parsed);
}
} catch (e) {
resolve(body);
}
} else {
let errMsg = body;
try {
const parsed = JSON.parse(body);
errMsg = parsed.msg || parsed.message || body;
} catch(e) {}
reject(new Error(`请求失败 [${res.statusCode}]: ${errMsg}`));
}
});
});
req.on('error', (e) => reject(e));
if (payload) {
req.write(payload);
}
req.end();
});
}
function getEnvsUrl() {
const url = process.env.BHPKG_OPENAPI_URL || process.env.OPENAPI_URL;
if (url) return url;
const notifyUrl = process.env.BHPKG_NOTIFY_URL || 'http://localhost:8052/api/v1/notify/send';
const targets = ['/api/v1/notify/send/', '/api/v1/notify/send', '/api/v1/notify/', '/api/v1/notify'];
for (const target of targets) {
if (notifyUrl.includes(target)) {
return notifyUrl.replace(target, '/open2api/v1/env');
}
}
return 'http://localhost:8052/open2api/v1/env';
}
/**
* 获取所有的环境变量列表
*/
async function getEnvs() {
const url = `${getEnvsUrl()}/all`;
const res = await request(url, 'GET');
return res.data || [];
}
/**
* 根据变量名获取环境变量,不存在则返回 null
*/
async function getEnv(name) {
const envs = await getEnvs();
for (const env of envs) {
if (env.name === name) {
return env;
}
}
return null;
}
/**
* 批量添加环境变量
*/
async function addEnvs(envsList) {
const url = getEnvsUrl();
const addedEnvs = [];
for (const env of envsList) {
if (!env.name || !env.value) {
throw new Error("环境变量必须包含 'name' 和 'value'");
}
const res = await request(url, 'POST', env);
if (res.data) {
addedEnvs.push(res.data);
}
}
return addedEnvs;
}
/**
* 添加单个环境变量
*/
async function addEnv(name, value, remark = "", type = "normal", hidden = true, enabled = true) {
const url = getEnvsUrl();
const payload = {
name,
value,
remark,
type,
hidden,
enabled
};
const res = await request(url, 'POST', payload);
return res.data;
}
/**
* 根据 ID 更新环境变量
*/
async function updateEnv(id, name, value, remark = null, type = null, hidden = null, enabled = null) {
const url = `${getEnvsUrl()}/${id}`;
const payload = {};
if (name !== null) payload.name = name;
if (value !== null) payload.value = value;
if (remark !== null) payload.remark = remark;
if (type !== null) payload.type = type;
if (hidden !== null) payload.hidden = hidden;
if (enabled !== null) payload.enabled = enabled;
const res = await request(url, 'PUT', payload);
return res.data;
}
/**
* 批量删除环境变量
*/
async function deleteEnvs(ids) {
for (const id of ids) {
await deleteEnv(id);
}
return true;
}
/**
* 根据 ID 删除指定环境变量
*/
async function deleteEnv(id) {
const url = `${getEnvsUrl()}/${id}`;
await request(url, 'DELETE');
return true;
}
module.exports = {
getEnvs,
getEnv,
addEnvs,
addEnv,
updateEnv,
deleteEnvs,
deleteEnv
};
+37
View File
@@ -0,0 +1,37 @@
const { notify } = require('./notify');
const {
getEnvs,
getEnv,
addEnvs,
addEnv,
updateEnv,
deleteEnvs,
deleteEnv
} = require('./env');
const {
getTasks,
getTask,
updateTask,
deleteTask,
executeTask,
stopTask,
getLastResults
} = require('./task');
module.exports = {
notify,
getEnvs,
getEnv,
addEnvs,
addEnv,
updateEnv,
deleteEnvs,
deleteEnv,
getTasks,
getTask,
updateTask,
deleteTask,
executeTask,
stopTask,
getLastResults
};
+51
View File
@@ -0,0 +1,51 @@
const http = require('http');
const https = require('https');
const { URL } = require('url');
/**
* 发送通知的辅助函数 (仅使用 Node.js 标准库)
*/
function notify(title, text, channelId) {
const token = process.env.BHPKG_NOTIFY_TOKEN;
const channel = process.env.BHPKG_NOTIFY_CHANNEL;
if (!token || !channel) {
const missing = [];
if (!token) missing.push("BHPKG_NOTIFY_TOKEN");
if (!channel) missing.push("BHPKG_NOTIFY_CHANNEL");
throw new Error(`没有正确配置或缺少 ${missing.join(" 和 ")} 环境变量以使用 notify 函数。请在任务池的任务设置中配置这些 Key。`);
}
const notifyUrl = process.env.BHPKG_NOTIFY_URL || 'http://localhost:8052/api/v1/notify/send';
const cid = channelId || channel;
if (!notifyUrl || !token || !cid) return;
const parsedUrl = new URL(notifyUrl);
const protocol = parsedUrl.protocol === 'https:' ? https : http;
const data = JSON.stringify({
channel_id: cid,
title: title || '系统通知',
text: text
});
const options = {
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.pathname + (parsedUrl.search || ''),
method: 'POST',
headers: {
'Content-Type': 'application/json',
'notify-token': token,
'Content-Length': Buffer.byteLength(data)
}
};
const req = protocol.request(options);
req.on('error', (e) => {});
req.write(data);
req.end();
}
module.exports = { notify };
+7
View File
@@ -0,0 +1,7 @@
{
"name": "taskpool",
"version": "1.0.0",
"description": "TaskPool internal helper for Node.js",
"main": "index.js",
"license": "MIT"
}
+175
View File
@@ -0,0 +1,175 @@
const http = require('http');
const https = require('https');
const { URL } = require('url');
/**
* 内部 API 请求辅助函数
*/
function request(urlStr, method = 'GET', data = null) {
const token = process.env.BHPKG_OPENAPI_TOKEN || process.env.OPENAPI_TOKEN || process.env.BHPKG_NOTIFY_TOKEN;
if (!token) {
throw new Error(`没有正确配置或缺少 BHPKG_OPENAPI_TOKEN 环境变量以使用 task 函数。请在任务池的任务设置中配置这些 Key。`);
}
const parsedUrl = new URL(urlStr);
const protocol = parsedUrl.protocol === 'https:' ? https : http;
let payload = '';
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
if (data !== null) {
payload = JSON.stringify(data);
headers['Content-Length'] = Buffer.byteLength(payload);
}
const options = {
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.pathname + (parsedUrl.search || ''),
method: method,
headers: headers
};
return new Promise((resolve, reject) => {
const req = protocol.request(options, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
try {
const parsed = body ? JSON.parse(body) : {};
if (parsed && typeof parsed === 'object' && parsed.code !== undefined && parsed.code !== 200) {
reject(new Error(`请求失败 [${parsed.code}]: ${parsed.msg || parsed.message || '未知错误'}`));
} else {
resolve(parsed);
}
} catch (e) {
resolve(body);
}
} else {
let errMsg = body;
try {
const parsed = JSON.parse(body);
errMsg = parsed.msg || parsed.message || body;
} catch(e) {}
reject(new Error(`请求失败 [${res.statusCode}]: ${errMsg}`));
}
});
});
req.on('error', (e) => reject(e));
if (payload) {
req.write(payload);
}
req.end();
});
}
function getBaseUrl() {
const url = process.env.BHPKG_OPENAPI_URL || process.env.OPENAPI_URL;
if (url) {
if (url.endsWith('/env')) return url.slice(0, -4);
if (url.endsWith('/env/')) return url.slice(0, -5);
return url;
}
const notifyUrl = process.env.BHPKG_NOTIFY_URL || 'http://localhost:8052/api/v1/notify/send';
const targets = ['/api/v1/notify/send/', '/api/v1/notify/send', '/api/v1/notify/', '/api/v1/notify'];
for (const target of targets) {
if (notifyUrl.includes(target)) {
return notifyUrl.replace(target, '/open2api/v1');
}
}
return 'http://localhost:8052/open2api/v1';
}
/**
* 获取全部任务列表
*/
async function getTasks() {
const url = `${getBaseUrl()}/tasks`;
const res = await request(url, 'GET');
return res.data || [];
}
/**
* 根据 ID 获取单个任务信息
*/
async function getTask(id) {
const url = `${getBaseUrl()}/tasks/${id}`;
const res = await request(url, 'GET');
return res.data;
}
/**
* 根据 ID 更新指定任务
*/
async function updateTask(id, name, command, remark, pin_type, trigger_type, schedule, timeout, work_dir, retry_count, retry_interval, random_range, enabled) {
const url = `${getBaseUrl()}/tasks/${id}`;
const payload = {};
if (name !== undefined) payload.name = name;
if (command !== undefined) payload.command = command;
if (remark !== undefined) payload.remark = remark;
if (pin_type !== undefined) payload.pin_type = pin_type;
if (trigger_type !== undefined) payload.trigger_type = trigger_type;
if (schedule !== undefined) payload.schedule = schedule;
if (timeout !== undefined) payload.timeout = timeout;
if (work_dir !== undefined) payload.work_dir = work_dir;
if (retry_count !== undefined) payload.retry_count = retry_count;
if (retry_interval !== undefined) payload.retry_interval = retry_interval;
if (random_range !== undefined) payload.random_range = random_range;
if (enabled !== undefined) payload.enabled = enabled;
const res = await request(url, 'PUT', payload);
return res.data;
}
/**
* 根据 ID 删除任务
*/
async function deleteTask(id) {
const url = `${getBaseUrl()}/tasks/${id}`;
await request(url, 'DELETE');
return true;
}
/**
* 触发运行指定任务
*/
async function executeTask(id) {
const url = `${getBaseUrl()}/execute/task/${id}`;
const res = await request(url, 'POST');
return res.data;
}
/**
* 根据日志 ID 停止正在运行的任务
*/
async function stopTask(logId) {
const url = `${getBaseUrl()}/tasks/stop/${logId}`;
const res = await request(url, 'POST');
return res.data;
}
/**
* 获取最近的任务执行结果列表
*/
async function getLastResults() {
const url = `${getBaseUrl()}/execute/results`;
const res = await request(url, 'GET');
return res.data || [];
}
module.exports = {
getTasks,
getTask,
updateTask,
deleteTask,
executeTask,
stopTask,
getLastResults
};