// MIC产品上传 — 路由与 WebSocket 桥接 // // 在 server.js 里这样接入(server 变量是 app.listen(...) 的返回值,必须在它 // 创建之后调用): // // const { registerMicUpload } = require('./mic-upload/micUploadRoutes'); // registerMicUpload(app, server, { // requireAuth, readData, writeData, callDeepSeekWithRetry, loadAiConfig, // encrypt, decrypt, // }); // // (这几个名字要跟 server.js 里已有的函数对上:requireAuth/readData/writeData/ // callDeepSeekWithRetry/loadAiConfig/encrypt/decrypt 都是 server.js 里已经定义 // 好的,直接传引用过来即可,不用改动它们本身。encrypt/decrypt 是给保存的MIC账号 // 密码加密用的,跟 ai-config.json 那套是同一份 AES-256-GCM 实现。) // // 需要 `npm install playwright ws`,并在VPS上跑一次 // `npx playwright install --with-deps chromium`(无头浏览器本体,体积较大, // 装的时候留意磁盘空间)。 const crypto = require('crypto'); const WebSocket = require('ws'); const { MicBrowserSession } = require('./micBrowserSession'); const { buildAttributeList } = require('./micFieldMapping'); const _KW_SYSTEM_PROMPT = `You are a B2B export keyword expert for energy products on Made-in-China.com. Generate exactly 10 unique English search keywords for the given product. Rules: 1. Return ONLY a JSON array of exactly 10 strings. No explanation, no markdown. 2. All 10 keywords must be mutually unique. 3. Each keyword: 2-6 words, phrased as a buyer search query. 4. Cover varied angles: capacity+type, application, technology, buyer intent. Output format: ["keyword one", ..., "keyword ten"]`; function localFallbackKeywords(title) { // 原脚本里AI失败时的本地兜底逻辑,直接搬过来,保底不至于完全没有关键词 const low = (title || '').toLowerCase(); const capMatch = low.match(/(\d+)\s*kva/); const kwhMatch = low.match(/(\d+)\s*kwh/); if (kwhMatch) { return [ `${kwhMatch[1]}kWh LiFePO4 Battery`, 'Rack Mount Lithium Battery', 'Solar Energy Storage Battery', 'LiFePO4 Battery Pack', 'Rack Battery Pack', 'ESS Battery Module', 'Lithium Iron Phosphate Battery', 'Off-grid Storage Battery', 'RS485 CAN Battery Pack', 'Energy Storage Battery Supplier', ]; } const pfx = capMatch ? `${capMatch[1]}KVA ` : ''; return [ `${pfx}Online UPS`, 'Double Conversion UPS', 'UPS for Data Centre', 'Industrial Online UPS', 'High Efficiency UPS', 'Wide Input Voltage UPS', 'Generator Compatible UPS', 'SNMP Managed UPS', 'Uninterruptible Power Supply', 'Online UPS Supplier', ]; } async function generateKeywords(ctx, title, model, log) { let apiKey = ''; try { const cfg = ctx.loadAiConfig(); // 同步函数,跟server.js里的定义一致 apiKey = cfg && cfg.apiKey; } catch (e) { /* 没配置DeepSeek key时走本地兜底 */ } if (!apiKey) { log('未配置DeepSeek Key,使用本地关键词兜底', 'WARNING'); return localFallbackKeywords(title); } const messages = [ { role: 'system', content: _KW_SYSTEM_PROMPT }, { role: 'user', content: `Product: ${title}\nModel: ${model}\nGenerate 10 unique English search keywords.` }, ]; try { const content = await ctx.callDeepSeekWithRetry(apiKey, messages, { temperature: 0.7, maxTokens: 400 }, 2); let raw = String(content).trim(); if (raw.startsWith('```')) { raw = raw.split('```')[1]; if (raw.startsWith('json')) raw = raw.slice(4); } const parsed = JSON.parse(raw.trim()); if (!Array.isArray(parsed)) throw new Error('AI返回的不是数组'); const seen = new Set(); const unique = []; for (const kw of parsed) { const s = String(kw).trim(); if (s && !seen.has(s.toLowerCase())) { seen.add(s.toLowerCase()); unique.push(s); } } if (unique.length < 10) throw new Error(`只生成了${unique.length}个`); log(`AI生成 10 个关键词: ${unique[0]} ...`); return unique.slice(0, 10); } catch (e) { log(`AI关键词生成失败,使用本地兜底: ${e.message}`, 'WARNING'); return localFallbackKeywords(title); } } function registerMicUpload(app, server, ctx) { const { requireAuth, readData, writeData, encrypt, decrypt } = ctx; // sessionId -> { session, token, wsClients: Set, createdAt } const sessions = new Map(); function broadcast(entry, msg) { const payload = JSON.stringify(msg); for (const ws of entry.wsClients) { if (ws.readyState === WebSocket.OPEN) ws.send(payload); } } function getMicTemplates() { const data = readData(); return data['crm:micTemplates'] || {}; } // ---- 品类 -> addSimilar模板URL 配置(存进通用storage的 crm:micTemplates) ---- app.get('/api/mic-upload/templates', requireAuth, (req, res) => { res.json({ value: getMicTemplates() }); }); app.put('/api/mic-upload/templates', requireAuth, (req, res) => { const data = readData(); data['crm:micTemplates'] = req.body && req.body.value ? req.body.value : {}; writeData(data); res.json({ ok: true }); }); // ---- MIC账号/密码(加密存储,跟ai-config.json同一套AES-256-GCM)---- // GET只返回是否已保存,从不回传明文;密码只在 autofill 接口里解密,且直接 // 由后端打进Playwright页面,不经过前端网络请求。 app.get('/api/mic-upload/credentials', requireAuth, (req, res) => { const data = readData(); const cred = data['crm:micCredentials'] || {}; res.json({ hasEmail: !!cred.emailEnc, hasPassword: !!cred.passwordEnc }); }); app.put('/api/mic-upload/credentials', requireAuth, (req, res) => { const { email, password } = req.body || {}; const data = readData(); const cred = data['crm:micCredentials'] || {}; if (typeof email === 'string' && email) cred.emailEnc = encrypt(email); if (typeof password === 'string' && password) cred.passwordEnc = encrypt(password); data['crm:micCredentials'] = cred; writeData(data); res.json({ ok: true, hasEmail: !!cred.emailEnc, hasPassword: !!cred.passwordEnc }); }); app.delete('/api/mic-upload/credentials', requireAuth, (req, res) => { const data = readData(); delete data['crm:micCredentials']; writeData(data); res.json({ ok: true }); }); // ---- 会话生命周期 ---- app.post('/api/mic-upload/sessions', requireAuth, async (req, res) => { const id = crypto.randomBytes(8).toString('hex'); const token = crypto.randomBytes(24).toString('hex'); const entry = { session: null, token, wsClients: new Set(), createdAt: Date.now() }; sessions.set(id, entry); const session = new MicBrowserSession(id, { onFrame: (jpegBase64) => broadcast(entry, { type: 'frame', data: jpegBase64 }), onLog: (logMsg) => broadcast(entry, { type: 'log', ...logMsg }), }); entry.session = session; try { await session.start(); res.json({ sessionId: id, wsToken: token }); } catch (e) { sessions.delete(id); res.status(500).json({ error: `浏览器启动失败: ${e.message}` }); } }); app.post('/api/mic-upload/sessions/:id/login', requireAuth, async (req, res) => { const entry = sessions.get(req.params.id); if (!entry) return res.status(404).json({ error: '会话不存在或已关闭' }); try { await entry.session.gotoLogin(); res.json({ ok: true }); } catch (e) { res.status(500).json({ error: e.message }); } }); // 把已保存的账号/密码填进"当前在远程页面里被点中、处于聚焦状态"的输入框。 // 密码全程只在服务端解密+发送keydown/insertText,不经过前端网络请求。 app.post('/api/mic-upload/sessions/:id/autofill', requireAuth, async (req, res) => { const entry = sessions.get(req.params.id); if (!entry) return res.status(404).json({ error: '会话不存在或已关闭' }); const { field } = req.body || {}; if (field !== 'email' && field !== 'password') { return res.status(400).json({ error: 'field 必须是 email 或 password' }); } const data = readData(); const cred = data['crm:micCredentials'] || {}; const encKey = field === 'email' ? 'emailEnc' : 'passwordEnc'; if (!cred[encKey]) { return res.status(400).json({ error: `还没保存过${field === 'email' ? '账号' : '密码'},先在左侧填好并点保存` }); } try { const value = decrypt(cred[encKey]); await entry.session.typeText(value); entry.session.log(`已填入保存的${field === 'email' ? '账号' : '密码'}`); res.json({ ok: true }); } catch (e) { res.status(500).json({ error: e.message }); } }); // 从产品库读数据 -> 生成参数 -> 进入仿造发布页 -> 自动填表(不提交) app.post('/api/mic-upload/sessions/:id/publish', requireAuth, async (req, res) => { const entry = sessions.get(req.params.id); if (!entry) return res.status(404).json({ error: '会话不存在或已关闭' }); const { productId } = req.body || {}; if (!productId) return res.status(400).json({ error: '缺少 productId' }); const session = entry.session; try { const data = readData(); const products = data['crm:products'] || []; const product = products.find((p) => p.id === productId); if (!product) return res.status(404).json({ error: '产品不存在' }); const templates = getMicTemplates(); const templateUrl = templates[product.type] || templates[product.category]; if (!templateUrl) { return res.status(400).json({ error: `品类 "${product.type || product.category}" 还没配置MIC仿造模板URL,请先在"设置"里补上`, }); } const { title, model, attrList, warnings } = buildAttributeList(product); for (const w of warnings) session.log(w, 'WARNING'); await session.gotoPublishTemplate(templateUrl); await session.fillTitle(title); await session.checkCenterWord(); const keywords = await generateKeywords(ctx, title, model, (m, l) => session.log(m, l)); await session.fillKeywords(keywords); await session.fillModel(model); await session.fillAttributes(attrList); res.json({ ok: true, warnings }); } catch (e) { session.log(`填表流程出错: ${e.message}`, 'ERROR'); res.status(500).json({ error: e.message }); } }); app.post('/api/mic-upload/sessions/:id/submit', requireAuth, async (req, res) => { const entry = sessions.get(req.params.id); if (!entry) return res.status(404).json({ error: '会话不存在或已关闭' }); try { await entry.session.submit(); res.json({ ok: true }); } catch (e) { res.status(500).json({ error: e.message }); } }); app.delete('/api/mic-upload/sessions/:id', requireAuth, async (req, res) => { const entry = sessions.get(req.params.id); if (!entry) return res.json({ ok: true }); await entry.session.close(); for (const ws of entry.wsClients) { try { ws.close(); } catch (e) {} } sessions.delete(req.params.id); res.json({ ok: true }); }); // ---- WebSocket:画面推流 + 登录阶段的鼠标/键盘转发 ---- // 鉴权用启动会话时发的一次性 token(不复用cookie/session,接线更简单) const wss = new WebSocket.Server({ noServer: true }); server.on('upgrade', (req, socket, head) => { let url; try { url = new URL(req.url, 'http://localhost'); } catch (e) { socket.destroy(); return; } if (url.pathname !== '/ws/mic-upload') return; // 交给其他upgrade handler(如果有) const sessionId = url.searchParams.get('sessionId'); const token = url.searchParams.get('token'); const entry = sessions.get(sessionId); if (!entry || entry.token !== token) { socket.destroy(); return; } wss.handleUpgrade(req, socket, head, (ws) => { entry.wsClients.add(ws); ws.on('close', () => entry.wsClients.delete(ws)); ws.on('message', async (raw) => { let msg; try { msg = JSON.parse(raw); } catch (e) { return; } const session = entry.session; if (!session) return; try { switch (msg.type) { case 'mousemove': await session.mouseMove(msg.x, msg.y); break; case 'mousedown': await session.mouseDown(msg.x, msg.y, msg.button || 'left'); break; case 'mouseup': await session.mouseUp(msg.x, msg.y, msg.button || 'left'); break; case 'wheel': await session.wheel(msg.dx || 0, msg.dy || 0); break; case 'keydown': await session.keyDown(msg.key); break; case 'keyup': await session.keyUp(msg.key); break; case 'text': await session.typeText(msg.text); break; default: break; } } catch (e) { /* 单次输入转发失败不致命,忽略 */ } }); }); }); // 空会话超时清理(比如浏览器标签页被直接关掉,没走DELETE接口) setInterval(() => { const now = Date.now(); for (const [id, entry] of sessions.entries()) { if (entry.wsClients.size === 0 && now - entry.createdAt > 30 * 60 * 1000) { entry.session.close(); sessions.delete(id); } } }, 5 * 60 * 1000); } module.exports = { registerMicUpload };