From f8ade1be39f19408eb1dc2a1946e7efc1fd8dbc2 Mon Sep 17 00:00:00 2001 From: mike Date: Sun, 20 Sep 2026 17:33:00 +0800 Subject: [PATCH] Update micUploadRoutes.js via upload script - 2026-09-20 17:32:52 --- micUploadRoutes.js | 270 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 micUploadRoutes.js diff --git a/micUploadRoutes.js b/micUploadRoutes.js new file mode 100644 index 0000000..e69b5df --- /dev/null +++ b/micUploadRoutes.js @@ -0,0 +1,270 @@ +// MIC产品上传 — 路由与 WebSocket 桥接 +// +// 在 server.js 里这样接入(server 变量是 app.listen(...) 的返回值,必须在它 +// 创建之后调用): +// +// const { registerMicUpload } = require('./mic-upload/micUploadRoutes'); +// registerMicUpload(app, server, { +// requireAuth, readData, writeData, callDeepSeekWithRetry, loadAiConfig, +// }); +// +// (这几个名字要跟 server.js 里已有的函数对上:requireAuth/readData/writeData/ +// callDeepSeekWithRetry/loadAiConfig 都是 server.js 里已经定义好的,直接传引用 +// 过来即可,不用改动它们本身。) +// +// 需要 `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 } = 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 }); + }); + + // ---- 会话生命周期 ---- + + 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 }); + } + }); + + // 从产品库读数据 -> 生成参数 -> 进入仿造发布页 -> 自动填表(不提交) + 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 };