UNPKG

@daiyu-5577/quickbuild

Version:

front-end build service

399 lines (398 loc) 13.6 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import express from 'express'; import axios from 'axios'; import { encrypt } from '../../utils/crypto.js'; import dayjs from 'dayjs'; import fs from 'fs-extra'; import path from 'path'; import controller_io, { commands } from './controller.io.js'; import { baseRoute, catchBuildLogPath, catchImagePath, catchWebDistPath, webDistPath } from '../config.js'; import { catchHttpLogPath } from '../config.js'; import { generateUid, updateDatabaseFile } from '../../database/index.js'; import { formatMsg, IdType } from '../commandBuild/type.js'; import { getFromatTime } from '../../utils/time.js'; const __dirname = new URL('.', import.meta.url).pathname; const router = express.Router(); router.post('/login', (req, res) => __awaiter(void 0, void 0, void 0, function* () { const { username, password } = req.body; const database = req.app.get('database'); const table_user = database.get('user'); if (!table_user) { res.status(500).send({ message: 'table_user not found', success: false }); return; } const curUser = table_user.find(v => v.name === username && v.password === password); if (!curUser) { res.status(500).send({ message: '账号或密码错误', success: false }); return; } const token = yield encrypt(JSON.stringify({ id: curUser.id, name: curUser.name, time: +dayjs(), })); res.send({ data: { id: curUser.id, name: curUser.name, token }, message: 'login success', success: true }); })); router.post('/register', (req, res) => __awaiter(void 0, void 0, void 0, function* () { const { username, password } = req.body; const builder = req.app.get('database'); const table_user = builder.get('user'); if (!table_user) { res.status(500).send({ message: 'table_user not found', success: false }); return; } const curUser = table_user.find(v => v.name === username); if (!!curUser) { res.status(500).send({ message: '当前用户名已存在', success: false }); return; } let uid = generateUid(); while (!!table_user.find(v => v.id === uid)) { uid = generateUid(); } table_user.push({ id: uid, name: username, password, }); updateDatabaseFile('user', table_user); res.send({ message: 'register success', success: true }); })); router.post('/addTask', (req, res) => __awaiter(void 0, void 0, void 0, function* () { const builder = req.app.get('builder'); const port = req.app.get('port'); let { packagePaths = ['.'], branch = '', commit = '', notify = `http://127.0.0.1:${port}/api/notify` } = req.body; packagePaths = typeof packagePaths === 'string' ? [packagePaths] : packagePaths; if (!branch) { res.status(500).send({ message: 'branch is required', success: false }); } for (let i = 0; i < packagePaths.length; i++) { const curPath = packagePaths[i]; yield builder.addTask({ packagePath: curPath, branch, commit, notify, buildSourceType: 'buildServer' }); } res.send({ message: 'add task success', success: true }); })); router.get('/getAllTask', (req, res) => { const builder = req.app.get('builder'); res.send({ curTack: builder.curTask, list: builder.buildTasks, success: true }); }); router.get('/getAllCommand', (req, res) => { const list = commands.map(v => ({ command: v.command, desc: v.desc })); res.send({ list, success: true }); }); router.get('/getAllPackage', (req, res) => { const builder = req.app.get('builder'); res.send({ list: builder.packages, success: true }); }); router.get('/getAllLog', (req, res) => { const httpList = []; const buildList = []; const getDirFiles = (type, logDir, arr) => { if (fs.existsSync(logDir)) { const files = fs.readdirSync(logDir); if (!files.length) return; files.sort((a, b) => { return (fs.statSync(`${logDir}/${a}`).mtime.getTime() - fs.statSync(`${logDir}/${b}`).mtime.getTime()) * -1; }); for (let i = 0; i < files.length; i++) { const curFile = files[i]; if (curFile.endsWith('.log')) { arr.push({ name: curFile, path: `${baseRoute}/api/showLog?type=${type}&name=${curFile}` }); } } } }; getDirFiles('log', catchHttpLogPath, httpList); getDirFiles('buildLog', catchBuildLogPath, buildList); res.send({ tabs: [ { title: 'httpLog', list: httpList }, { title: 'buildLog', list: buildList } ], success: true }); }); router.get('/getAllBackup', (req, res) => { const backupList = []; const getDirFiles = (dir, arr) => { if (fs.existsSync(dir)) { const files = fs.readdirSync(dir); if (!files.length) return; files.sort((a, b) => { return (fs.statSync(`${dir}/${a}`).mtime.getTime() - fs.statSync(`${dir}/${b}`).mtime.getTime()) * -1; }); arr.push(...files); } }; getDirFiles(catchWebDistPath, backupList); res.send({ list: backupList, success: true }); }); router.post('/restore', (req, res) => __awaiter(void 0, void 0, void 0, function* () { var _a; const { fileName } = req.body; if (!fileName) { res.status(500).send({ message: 'fileName is required', success: false }); return; } const absPath = path.join(catchWebDistPath, fileName); if (!fs.existsSync(absPath)) { res.status(500).send({ message: `${absPath} not found`, success: false }); return; } const io = req.app.get('io'); yield fs.copySync(absPath, webDistPath, { overwrite: true }); controller_io.sendMsg('on:msg-chat', { id: generateUid(IdType.M), socketId: '', msg: `${(req === null || req === void 0 ? void 0 : req.userInfo) ? `${(_a = req === null || req === void 0 ? void 0 : req.userInfo) === null || _a === void 0 ? void 0 : _a.name} 操作 ` : ''}${fileName} 版本回退成功`, name: '系统消息', time: getFromatTime(), timestamp: +dayjs(), ctxType: 'ctx:txt', type: 'on:msg-chat' }); res.send({ message: '操作成功', success: true }); })); router.get('/showLog', (req, res, next) => { const { type, name = '' } = req.query; const logDirMap = new Map([ ['log', catchHttpLogPath], ['buildLog', catchBuildLogPath], ['image', catchImagePath], ]); if (!type || !name || !logDirMap.get(type)) { res.status(500).send({ message: `${type} or ${name} 不存在`, success: false }); return; } const absLogPath = path.join(logDirMap.get(type), name); if (!fs.existsSync(absLogPath)) { res.status(500).send({ message: `文件: ${name} 不存在`, success: false }); return; } res.sendFile(absLogPath, { dotfiles: 'allow', maxAge: 14 * 24 * 60 * 60 * 1000 }, next); }); router.post('/cancelTask', (req, res) => { var _a; const builder = req.app.get('builder'); const { taskId } = req.body; const curTask = builder.curTask; if (!builder.curTask || !taskId || taskId !== (curTask === null || curTask === void 0 ? void 0 : curTask.taskId)) { res.status(500).send({ message: `${taskId}任务不存在`, success: false }); return; } curTask === null || curTask === void 0 ? void 0 : curTask.abortController.abort(); const io = req.app.get('io'); controller_io.sendMsg('on:msg-chat', { id: generateUid(IdType.M), socketId: '', msg: `${(req === null || req === void 0 ? void 0 : req.userInfo) ? `${(_a = req === null || req === void 0 ? void 0 : req.userInfo) === null || _a === void 0 ? void 0 : _a.name} ` : ''}已取消 ${taskId} 构建任务`, name: '系统消息', time: getFromatTime(), timestamp: +dayjs(), ctxType: 'ctx:txt', type: 'on:msg-chat', }); res.send({ message: 'cancel task success', success: true }); }); router.post('/notify', (req, res) => { const io = req.app.get('io'); const body = req.body; if (!!body.type) { controller_io.sendMsg(body.type, body); } else { io.emit('on:msg-chat', body); } res.send({ message: 'notify success', success: true }); }); router.post('/github', (req, res) => { var _a, _b; const body = req.body; const noticeJson = req.app.get('noticeJson'); const curNotice = noticeJson.find(item => { var _a; return item.httpsOrigin === ((_a = body === null || body === void 0 ? void 0 : body.repository) === null || _a === void 0 ? void 0 : _a.clone_url) && `refs/heads/${item === null || item === void 0 ? void 0 : item.branch}` === (body === null || body === void 0 ? void 0 : body.ref); }); if (!!curNotice) { axios({ url: curNotice.webhook, method: 'post', data: {}, headers: { 'Content-Type': 'application/json' } }); const commits = (body === null || body === void 0 ? void 0 : body.commits) || []; const commitMsg = commits.map((v) => v.message).join('\n'); controller_io.sendMsg('on:msg-chat', { id: generateUid(IdType.M), socketId: '', msg: `用户:${((_a = body === null || body === void 0 ? void 0 : body.pusher) === null || _a === void 0 ? void 0 : _a.name) || ''}\n分支:${(body === null || body === void 0 ? void 0 : body.ref) || ""}\n仓库:${((_b = body === null || body === void 0 ? void 0 : body.repository) === null || _b === void 0 ? void 0 : _b.clone_url) || ''}\n提交信息:\n${commitMsg}`, name: '系统消息', time: getFromatTime(), timestamp: +dayjs(), ctxType: 'ctx:txt', type: 'on:msg-chat' }); } res.send({ message: 'notify success', success: true }); }); router.get('/getNoticeList', (req, res) => { let noticeJson = req.app.get('noticeJson') || []; noticeJson = noticeJson.map(v => { return { branch: v.branch, httpsOrigin: v.httpsOrigin, basename: path.basename(v.httpsOrigin || ''), }; }); res.send({ list: noticeJson, success: true }); }); router.post('/noticeWebhook', (req, res) => { var _a, _b, _c; let noticeJson = req.app.get('noticeJson') || []; const curNotice = noticeJson.find(item => { var _a, _b; return item.httpsOrigin === ((_a = req.body) === null || _a === void 0 ? void 0 : _a.httpsOrigin) && item.branch === ((_b = req.body) === null || _b === void 0 ? void 0 : _b.branch); }); if (!curNotice) { res.send({ message: 'notice not found', success: false }); return; } const msgData = formatMsg('on:msg-chat', { id: generateUid(IdType.M), socketId: '', msg: `用户:${((_a = req === null || req === void 0 ? void 0 : req.userInfo) === null || _a === void 0 ? void 0 : _a.name) || ''}\n分支:${((_b = req.body) === null || _b === void 0 ? void 0 : _b.branch) || ""}\n仓库:${((_c = req.body) === null || _c === void 0 ? void 0 : _c.httpsOrigin) || ''}\n`, name: '系统消息', time: getFromatTime(), timestamp: +dayjs(), ctxType: 'ctx:txt', }); axios({ url: curNotice.webhook, method: 'post', data: {}, headers: { 'Content-Type': 'application/json' } }) .then(() => { msgData.msg += '通知成功'; controller_io.sendMsg('on:msg-chat', msgData); }) .catch(() => { msgData.msg += '通知失败'; controller_io.sendMsg('on:msg-chat', msgData); }); res.send({ message: 'notify success', success: true }); }); export default router;