- Updated `getAiProxy` function to return a JSON response for missing objects when the user is the owner. - Removed the `upload.ts`, `event.ts`, and related middleware files to streamline the codebase. - Cleaned up `handle-request.ts` and `index.ts` by removing unused imports and routes. - Deleted chunk upload handling and related utility functions to simplify resource management. - Enhanced app manager list functionality to support app creation if not found.
81 lines
2.0 KiB
TypeScript
81 lines
2.0 KiB
TypeScript
import { router } from '@/app.ts';
|
||
import http from 'http';
|
||
import { useContextKey } from '@kevisual/context';
|
||
export { router, };
|
||
|
||
/**
|
||
* 事件客户端
|
||
*/
|
||
const eventClientsInit = () => {
|
||
const clients = new Map<string, { client?: http.ServerResponse; createTime?: number;[key: string]: any }>();
|
||
return clients;
|
||
};
|
||
export const clients = useContextKey('event-clients', () => eventClientsInit());
|
||
/**
|
||
* 获取 task-id
|
||
* @param req
|
||
* @returns
|
||
*/
|
||
export const getTaskId = (req: http.IncomingMessage) => {
|
||
const url = new URL(req.url || '', 'http://localhost');
|
||
const taskId = url.searchParams.get('taskId');
|
||
if (taskId) {
|
||
return taskId;
|
||
}
|
||
return req.headers['task-id'] as string;
|
||
};
|
||
type EventData = {
|
||
progress: number | string;
|
||
message: string;
|
||
};
|
||
|
||
/**
|
||
* 写入事件
|
||
* @param req
|
||
* @param data
|
||
*/
|
||
export const writeEvents = (req: http.IncomingMessage, data: EventData) => {
|
||
const taskId = getTaskId(req);
|
||
if (taskId) {
|
||
const client = clients.get(taskId)?.client;
|
||
if (client) {
|
||
client.write(`data: ${JSON.stringify(data)}\n\n`);
|
||
}
|
||
if (Number(data.progress) === 100) {
|
||
clients.delete(taskId);
|
||
}
|
||
} else {
|
||
console.log('taskId is remove.', taskId);
|
||
}
|
||
};
|
||
/**
|
||
* 查找超出2个小时的clients,都删除了
|
||
*/
|
||
export const deleteOldClients = () => {
|
||
const now = Date.now();
|
||
for (const [taskId, client] of clients) {
|
||
// 如果创建时间超过2个小时,则删除
|
||
if (now - client.createTime > 1000 * 60 * 60 * 2) {
|
||
clients.delete(taskId);
|
||
}
|
||
}
|
||
};
|
||
/**
|
||
* 解析表单数据, 如果表单数据是数组, 则取第一个,appKey, version, username 等
|
||
* @param fields 表单数据
|
||
* @param parseKeys 需要解析的键
|
||
* @returns 解析后的数据
|
||
*/
|
||
export const getKey = (fields: Record<string, any>, parseKeys: string[]) => {
|
||
let value: Record<string, any> = {};
|
||
for (const key of parseKeys) {
|
||
const v = fields[key];
|
||
if (Array.isArray(v)) {
|
||
value[key] = v[0];
|
||
} else {
|
||
value[key] = v;
|
||
}
|
||
}
|
||
return value;
|
||
};
|