/** * 附件:上传、Electron 原生选文件、以及"宿主页拖拽进来的文件"待取队列。 * 图片会以 data URL 形式喂给支持视觉的模型;文本类文件直接内联正文。 */ import fs from 'node:fs'; import path from 'node:path'; import { DATA_DIR } from './config.mjs'; export const UPLOADS_DIR = path.join(DATA_DIR, 'uploads'); fs.mkdirSync(UPLOADS_DIR, { recursive: true }); const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp']); const TEXT_EXT = new Set([ '.txt', '.md', '.markdown', '.json', '.csv', '.tsv', '.log', '.ini', '.toml', '.yml', '.yaml', '.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.html', '.htm', '.css', '.scss', '.xml', '.sql', '.sh', '.bat', '.ps1', '.java', '.c', '.h', '.cpp', '.cs', '.go', '.rs', '.rb', '.php', '.swift', '.kt', '.lua', '.r', '.vue', '.svelte', ]); /** * 单个文件上限。 * * ★ 和请求体上限联动:走 /api/upload 时文件先 base64 再进 JSON,体积涨 1/3 —— * 100MB 的文件对应约 133MB 请求体,所以 index.mjs 那边得给到 150MB, * 否则会先被"请求体过大"挡下来。改一个要改另一个。 */ const COPY_LIMIT = 100 * 1024 * 1024; /** 喂给模型的单张图片上限 */ const VISION_LIMIT = 6 * 1024 * 1024; let pending = []; function rid() { return `f_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`; } function safeName(name) { return String(name || 'file').replace(/[\\/:*?"<>|]/g, '_').slice(-60); } export function isImage(name) { return IMAGE_EXT.has(path.extname(String(name || '')).toLowerCase()); } export function isText(name) { return TEXT_EXT.has(path.extname(String(name || '')).toLowerCase()); } function mimeOf(name) { const ext = path.extname(String(name || '')).toLowerCase(); const map = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.bmp': 'image/bmp', '.pdf': 'application/pdf', '.json': 'application/json', '.md': 'text/markdown', }; return map[ext] || (isText(name) ? 'text/plain' : 'application/octet-stream'); } function meta(filePath, name, { copy = true } = {}) { const stat = fs.statSync(filePath); let storedPath = filePath; let url = ''; if (copy && stat.size <= COPY_LIMIT) { const target = path.join(UPLOADS_DIR, `${Date.now().toString(36)}_${safeName(name)}`); fs.copyFileSync(filePath, target); storedPath = target; url = `/uploads/${path.basename(target)}`; } return { id: rid(), name: String(name), size: stat.size, mime: mimeOf(name), path: storedPath, url, at: new Date().toISOString(), }; } /** 浏览器上传:base64 → 落盘 */ export function saveUpload({ name, base64 }) { if (!name || !base64) throw new Error('缺少 name 或 base64'); const buffer = Buffer.from(String(base64).replace(/^data:[^,]+,/, ''), 'base64'); if (buffer.length > COPY_LIMIT) throw new Error(`文件超过 ${COPY_LIMIT / 1024 / 1024}MB`); const target = path.join(UPLOADS_DIR, `${Date.now().toString(36)}_${safeName(name)}`); fs.writeFileSync(target, buffer); return { id: rid(), name: String(name), size: buffer.length, mime: mimeOf(name), path: target, url: `/uploads/${path.basename(target)}`, at: new Date().toISOString(), }; } /** 桌面版原生选文件:登记(必要时复制) */ export function registerLocalFile(filePath) { if (!fs.existsSync(filePath)) throw new Error(`文件不存在:${filePath}`); return meta(filePath, path.basename(filePath)); } /** 宿主页拖拽进来的文件先放这里,等界面来取 */ export function addPending(items) { pending.push(...items); } export function takePending() { const items = pending; pending = []; return items; } /** * 把附件转成模型能吃的形式。 * @returns {{text: string, images: {url: string}[]}} */ export function attachmentPayload(attachment) { const out = { text: '', images: [] }; if (!attachment || !fs.existsSync(attachment.path)) { out.text = `【附件 ${attachment?.name || '未知'} 已丢失】`; return out; } const size = fs.statSync(attachment.path).size; if (isImage(attachment.name) && size <= VISION_LIMIT) { const b64 = fs.readFileSync(attachment.path).toString('base64'); out.images.push({ url: `data:${attachment.mime};base64,${b64}` }); out.text = `【图片 ${attachment.name}】`; return out; } if (isText(attachment.name) || size < 64 * 1024) { let body = ''; try { body = fs.readFileSync(attachment.path, 'utf8'); } catch { body = ''; } if (body) { const clipped = body.length > 20000 ? `${body.slice(0, 20000)}\n…(已截断,共 ${body.length} 字符)` : body; out.text = `【文件 ${attachment.name}(${size} 字节)】\n\`\`\`\n${clipped}\n\`\`\``; return out; } } out.text = `【附件 ${attachment.name}(${size} 字节,二进制)本地路径:${attachment.path}】`; return out; }