259 lines
7.6 KiB
TypeScript
259 lines
7.6 KiB
TypeScript
import { useFileStore } from '@kevisual/use-config/file-store';
|
|
import http from 'node:http';
|
|
import fs from 'fs';
|
|
import Busboy from 'busboy';
|
|
import { app, minioClient } from '@/app.ts';
|
|
|
|
import { bucketName } from '@/modules/minio.ts';
|
|
import { getContentType } from '@/utils/get-content-type.ts';
|
|
import { User } from '@/models/user.ts';
|
|
import { getContainerById } from '@/routes/container/module/get-container-file.ts';
|
|
import { router, error, checkAuth, writeEvents } from './router.ts';
|
|
import './index.ts';
|
|
import { handleRequest as PageProxy } from './page-proxy.ts';
|
|
import path from 'path';
|
|
import { createWriteStream } from 'fs';
|
|
import { pipeBusboy } from '@/modules/fm-manager/pipe-busboy.ts';
|
|
const cacheFilePath = useFileStore('cache-file', { needExists: true });
|
|
|
|
router.get('/api/app/upload', async (req, res) => {
|
|
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
|
res.end('Upload API is ready');
|
|
});
|
|
|
|
router.post('/api/app/upload', async (req, res) => {
|
|
if (res.headersSent) return; // 如果响应已发送,不再处理
|
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
const { tokenUser, token } = await checkAuth(req, res);
|
|
if (!tokenUser) return;
|
|
|
|
// 使用 busboy 解析 multipart/form-data
|
|
const busboy = Busboy({ headers: req.headers, preservePath: true });
|
|
const fields: any = {};
|
|
const files: any = [];
|
|
const filePromises: Promise<void>[] = [];
|
|
let bytesReceived = 0;
|
|
let bytesExpected = parseInt(req.headers['content-length'] || '0');
|
|
|
|
busboy.on('field', (fieldname, value) => {
|
|
fields[fieldname] = value;
|
|
});
|
|
|
|
busboy.on('file', (fieldname, fileStream, info) => {
|
|
const { filename, encoding, mimeType } = info;
|
|
const tempPath = path.join(cacheFilePath, `${Date.now()}-${Math.random().toString(36).substring(7)}`);
|
|
const writeStream = createWriteStream(tempPath);
|
|
|
|
const filePromise = new Promise<void>((resolve, reject) => {
|
|
fileStream.on('data', (chunk) => {
|
|
bytesReceived += chunk.length;
|
|
if (bytesExpected > 0) {
|
|
const progress = (bytesReceived / bytesExpected) * 100;
|
|
console.log(`Upload progress: ${progress.toFixed(2)}%`);
|
|
const data = {
|
|
progress: progress.toFixed(2),
|
|
message: `Upload progress: ${progress.toFixed(2)}%`,
|
|
};
|
|
writeEvents(req, data);
|
|
}
|
|
});
|
|
|
|
fileStream.pipe(writeStream);
|
|
|
|
writeStream.on('finish', () => {
|
|
files.push({
|
|
filepath: tempPath,
|
|
originalFilename: filename,
|
|
mimetype: mimeType,
|
|
});
|
|
resolve();
|
|
});
|
|
|
|
writeStream.on('error', (err) => {
|
|
reject(err);
|
|
});
|
|
});
|
|
|
|
filePromises.push(filePromise);
|
|
});
|
|
|
|
busboy.on('finish', async () => {
|
|
// 等待所有文件写入完成
|
|
try {
|
|
await Promise.all(filePromises);
|
|
} catch (err) {
|
|
console.error(`File write error: ${err.message}`);
|
|
res.end(error(`File write error: ${err.message}`));
|
|
return;
|
|
}
|
|
const clearFiles = () => {
|
|
files.forEach((file: any) => {
|
|
if (file?.filepath && fs.existsSync(file.filepath)) {
|
|
fs.unlinkSync(file.filepath);
|
|
}
|
|
});
|
|
};
|
|
|
|
// 检查是否有文件上传
|
|
if (files.length === 0) {
|
|
res.end(error('files is required'));
|
|
return;
|
|
}
|
|
|
|
let appKey,
|
|
version,
|
|
username = '';
|
|
const { appKey: _appKey, version: _version, username: _username } = fields;
|
|
if (Array.isArray(_appKey)) {
|
|
appKey = _appKey?.[0];
|
|
} else {
|
|
appKey = _appKey;
|
|
}
|
|
if (Array.isArray(_version)) {
|
|
version = _version?.[0];
|
|
} else {
|
|
version = _version;
|
|
}
|
|
if (Array.isArray(_username)) {
|
|
username = _username?.[0];
|
|
} else if (_username) {
|
|
username = _username;
|
|
}
|
|
if (username) {
|
|
const user = await User.getUserByToken(token);
|
|
const has = await user.hasUser(username, true);
|
|
if (!has) {
|
|
res.end(error('username is not found'));
|
|
clearFiles();
|
|
return;
|
|
}
|
|
}
|
|
if (!appKey) {
|
|
res.end(error('appKey is required'));
|
|
clearFiles();
|
|
return;
|
|
}
|
|
if (!version) {
|
|
res.end(error('version is required'));
|
|
clearFiles();
|
|
return;
|
|
}
|
|
console.log('Appkey', appKey, version);
|
|
|
|
// 逐个处理每个上传的文件
|
|
const uploadResults = [];
|
|
for (let i = 0; i < files.length; i++) {
|
|
const file = files[i];
|
|
const tempPath = file.filepath; // 文件上传时的临时路径
|
|
const relativePath = file.originalFilename; // 保留表单中上传的文件名 (包含文件夹结构)
|
|
// 比如 child2/b.txt
|
|
const minioPath = `${username || tokenUser.username}/${appKey}/${version}/${relativePath}`;
|
|
// 上传到 MinIO 并保留文件夹结构
|
|
const isHTML = relativePath.endsWith('.html');
|
|
await minioClient.fPutObject(bucketName, minioPath, tempPath, {
|
|
'Content-Type': getContentType(relativePath),
|
|
'app-source': 'user-app',
|
|
'Cache-Control': isHTML ? 'no-cache' : 'max-age=31536000, immutable', // 缓存一年
|
|
});
|
|
uploadResults.push({
|
|
name: relativePath,
|
|
path: minioPath,
|
|
});
|
|
fs.unlinkSync(tempPath); // 删除临时文件
|
|
}
|
|
// 受控
|
|
const r = await app.call({
|
|
path: 'app',
|
|
key: 'uploadFiles',
|
|
payload: {
|
|
token: token,
|
|
data: {
|
|
appKey,
|
|
version,
|
|
username,
|
|
files: uploadResults,
|
|
},
|
|
},
|
|
});
|
|
const data: any = {
|
|
code: r.code,
|
|
data: r.body,
|
|
};
|
|
if (r.message) {
|
|
data.message = r.message;
|
|
}
|
|
res.end(JSON.stringify(data));
|
|
});
|
|
|
|
pipeBusboy(req, res, busboy);
|
|
});
|
|
|
|
router.get('/api/container/file/:id', async (req, res) => {
|
|
const id = req.params.id;
|
|
if (!id) {
|
|
res.end(error('id is required'));
|
|
return;
|
|
}
|
|
const container = await getContainerById(id);
|
|
if (container.id) {
|
|
const code = container.code;
|
|
res.writeHead(200, {
|
|
'Content-Type': 'application/javascript; charset=utf-8',
|
|
'container-id': container.id,
|
|
});
|
|
res.end(code);
|
|
} else {
|
|
res.end(error('Container not found'));
|
|
}
|
|
|
|
res.writeHead(200, {
|
|
'Content-Type': 'application/json',
|
|
});
|
|
res.end(JSON.stringify(container));
|
|
});
|
|
|
|
router.all('/api/nocodb-test/router', async (req, res) => {
|
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
|
|
const param = await router.getSearch(req);
|
|
const body = await router.getBody(req);
|
|
|
|
const contentType = req.headers['content-type'] || '';
|
|
console.log('Content-Type:', contentType);
|
|
console.log('NocoDB test router called.', req.method, param, JSON.stringify(body, null));
|
|
res.end(JSON.stringify({ message: 'NocoDB test router is working' }));
|
|
});
|
|
const simpleAppsPrefixs = [
|
|
"/api/app/",
|
|
"/api/micro-app/",
|
|
"/api/events",
|
|
"/api/s1/",
|
|
"/api/container/",
|
|
"/api/resource/",
|
|
"/api/wxmsg",
|
|
"/api/nocodb-test/"
|
|
];
|
|
|
|
|
|
export const handleRequest = async (req: http.IncomingMessage, res: http.ServerResponse) => {
|
|
if (req.url?.startsWith('/api/router')) {
|
|
// router自己管理
|
|
return;
|
|
}
|
|
// if (req.url === '/MP_verify_NGWvli5lGpEkByyt.txt') {
|
|
// res.writeHead(200, { 'Content-Type': 'text/plain' });
|
|
// res.end('NGWvli5lGpEkByyt');
|
|
// return;
|
|
// }
|
|
if (req.url && simpleAppsPrefixs.some(prefix => req.url!.startsWith(prefix))) {
|
|
// 简单应用路由处理
|
|
// 设置跨域
|
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
|
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
return router.parse(req, res);
|
|
}
|
|
// 其他请求交给页面代理处理
|
|
return PageProxy(req, res);
|
|
};
|