|
|
| import { log } from '../config/logger.js';
|
|
|
|
|
| export function sanitizeLog(obj) {
|
| if (!obj) return obj;
|
| const sanitized = JSON.parse(JSON.stringify(obj));
|
|
|
|
|
| if (sanitized.headers && sanitized.headers.authorization) {
|
| sanitized.headers.authorization = '******';
|
| }
|
| if (sanitized.API_KEY) {
|
| sanitized.API_KEY = '******';
|
| }
|
|
|
| return sanitized;
|
| }
|
|
|
|
|
| export function logRequest(req, requestId) {
|
| log('info', '收到新请求', {
|
| requestId,
|
| method: req.method,
|
| url: req.url,
|
| headers: sanitizeLog(req.headers),
|
| body: sanitizeLog(req.body),
|
| query: req.query
|
| });
|
| }
|
|
|
|
|
| export function logResponse(requestId, status, data) {
|
| log('info', '发送响应', {
|
| requestId,
|
| status,
|
| response: sanitizeLog(data)
|
| });
|
| }
|
|
|
|
|
| export function logApiCall(requestId, config, apiPath, duration) {
|
| log('info', 'Dify API调用完成', {
|
| requestId,
|
| apiPath,
|
| botType: config.BOT_TYPE,
|
| durationMs: duration
|
| });
|
| }
|
|
|
|
|
| export function generateId() {
|
| let result = "";
|
| const characters =
|
| "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
| for (let i = 0; i < 29; i++) {
|
| result += characters.charAt(Math.floor(Math.random() * characters.length));
|
| }
|
| return result;
|
| }
|
|
|
|
|
| export function getFileExtension(url) {
|
|
|
| if (url.startsWith('data:')) {
|
| const mimeMatch = url.match(/data:([^;]+)/);
|
| if (mimeMatch && mimeMatch[1]) {
|
| const mime = mimeMatch[1];
|
|
|
| const mimeToExt = {
|
| 'image/jpeg': 'jpg',
|
| 'image/png': 'png',
|
| 'image/gif': 'gif',
|
| 'image/webp': 'webp',
|
| 'image/svg+xml': 'svg',
|
| 'application/pdf': 'pdf',
|
| 'text/plain': 'txt',
|
| 'text/html': 'html',
|
| 'audio/mpeg': 'mp3',
|
| 'video/mp4': 'mp4'
|
| };
|
| return mimeToExt[mime] || 'bin';
|
| }
|
| return 'bin';
|
| }
|
|
|
|
|
| try {
|
|
|
| const cleanUrl = url.split('?')[0];
|
|
|
| const parts = cleanUrl.split('/');
|
| const filename = parts[parts.length - 1];
|
| const ext = filename.split('.').pop().toLowerCase();
|
| return ext || 'bin';
|
| } catch (error) {
|
| log('warn', '无法从 URL 提取文件扩展名', { url: url.substring(0, 30) + '...', error });
|
| return 'bin';
|
| }
|
| }
|
|
|
|
|
| export function getFileType(extension) {
|
|
|
| const documentExts = ['txt', 'md', 'markdown', 'pdf', 'html', 'xlsx', 'xls', 'docx', 'csv', 'eml', 'msg', 'pptx', 'ppt', 'xml', 'epub'];
|
| const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
|
| const audioExts = ['mp3', 'm4a', 'wav', 'webm', 'amr'];
|
| const videoExts = ['mp4', 'mov', 'mpeg', 'mpga'];
|
|
|
|
|
| const ext = extension.toLowerCase();
|
|
|
| if (documentExts.includes(ext)) return 'document';
|
| if (imageExts.includes(ext)) return 'image';
|
| if (audioExts.includes(ext)) return 'audio';
|
| if (videoExts.includes(ext)) return 'video';
|
|
|
|
|
| return 'custom';
|
| }
|
|
|
|
|
| export { log }; |