| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241 |
- 'use strict';
- const http = require('http');
- const https = require('https');
- const fs = require('fs');
- const path = require('path');
- const crypto = require('crypto');
- const { execFile } = require('child_process');
- const { URL } = require('url');
- const jpeg = require('jpeg-js');
- const { PNG } = require('pngjs');
- const { getImageSize } = require('./imageMeta.js');
- const naposService = require('./napos-service.js');
- const nlQuery = require('./nl-query.js');
- const reportHtml = require('./report-html.js');
- const CONFIG_PATH = path.join(__dirname, 'config.json');
- const CONFIG_EXAMPLE_PATH = path.join(__dirname, 'config.example.json');
- const CONFIG_DEFAULTS = {
- port: 5177,
- apiKey: '',
- apiBase: 'https://api.lk888.ai',
- model: 'gpt-image-2',
- maxConcurrentJobs: 4,
- pageSize: 50,
- delayMs: 300,
- requestTimeoutMs: 20000,
- chatModel: '',
- chatApiBase: '',
- chatApiKey: '',
- };
- function writeConfigFile(cfg) {
- const temp = CONFIG_PATH + '.tmp';
- fs.writeFileSync(temp, JSON.stringify(cfg, null, 2), 'utf8');
- fs.renameSync(temp, CONFIG_PATH);
- }
- // 缺失/损坏时自动用模板(或内置默认)在本机生成新的 config.json —— 分发包开箱即用
- function loadConfig() {
- try {
- return { ...CONFIG_DEFAULTS, ...JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) };
- } catch (e) {
- if (e.code !== 'ENOENT') {
- console.warn(`config.json 解析失败(${e.message || e}),已改用默认配置;保存设置后会重建该文件。`);
- }
- let seeded = {};
- try { seeded = JSON.parse(fs.readFileSync(CONFIG_EXAMPLE_PATH, 'utf8')); } catch { /* 无模板则用内置默认 */ }
- const cfg = { ...CONFIG_DEFAULTS, ...seeded };
- try {
- writeConfigFile(cfg);
- console.log('已生成本机默认 config.json —— 请在「系统设置」中填写你自己的 API Key。');
- } catch { /* 只读目录等场景忽略 */ }
- return cfg;
- }
- }
- let config = loadConfig();
- function saveConfig() {
- writeConfigFile(config);
- }
- const WORKSPACE_ROOT = path.join(path.dirname(__dirname), 'workspace');
- function getWorkspaceRoot() {
- const configuredRoot = String(config.rootDir || WORKSPACE_ROOT).trim() || WORKSPACE_ROOT;
- return path.resolve(configuredRoot);
- }
- const HOST = process.env.HOST || '127.0.0.1';
- const MAX_BODY_BYTES = 32 * 1024 * 1024;
- function isWorkspaceRoot(candidate) {
- try {
- return !!candidate && path.resolve(String(candidate)) === getWorkspaceRoot();
- } catch {
- return false;
- }
- }
- function isWorkspacePath(candidate) {
- try {
- const resolved = path.resolve(String(candidate));
- const root = getWorkspaceRoot();
- return resolved === root || resolved.startsWith(root + path.sep);
- } catch {
- return false;
- }
- }
- function safeShopDir(root, folderName) {
- if (!isWorkspaceRoot(root) || typeof folderName !== 'string' ||
- !folderName || folderName === '.' || folderName === '..' ||
- folderName.includes('/') || folderName.includes('\\')) return null;
- const rootDir = path.resolve(root);
- const shopDir = path.resolve(rootDir, folderName);
- return shopDir.startsWith(rootDir + path.sep) ? shopDir : null;
- }
- try {
- fs.mkdirSync(getWorkspaceRoot(), { recursive: true });
- } catch (e) {
- // 历史配置的 rootDir 在本机不可创建(权限/目录被移动)时不要崩,允许进设置页修改
- console.warn(`输出根目录不可用:${getWorkspaceRoot()}(${e.code || e.message})。请到「系统设置」修改输出根目录。`);
- }
- const SESSION_PATH = path.join(__dirname, 'session.json');
- const MANUAL_SHOPS_PATH = path.join(__dirname, 'manual-shops.json');
- const MODELS = [
- { id: 'gpt-image-2', label: 'GPT Image 2(默认)' },
- { id: 'gpt-image-2-guan', label: 'GPT Image 2 官转' },
- { id: 'doubao-seedream-5-0-pro-260628', label: '豆包 Seedream 5.0 Pro' },
- { id: 'doubao-seedream-5-0-260128', label: '即梦 5.0(Seedream 5.0)' },
- { id: 'doubao-seedream-4-5-251128', label: '即梦 4.5(Seedream 4.5)' },
- { id: 'wan2.6-image', label: '通义万相 wan2.6-image' },
- ];
- const MODEL_IDS = new Set(MODELS.map((m) => m.id));
- // These seedream variants don't support the '1K' tier the UI's size dropdown offers by
- // default (doubao-seedream-4-5-251128: 2K/4K only; doubao-seedream-5-0-260128: 2K/3K only) -
- // map it up to '2K' rather than sending an invalid enum value.
- const NO_1K_SUPPORT = new Set(['doubao-seedream-4-5-251128', 'doubao-seedream-5-0-260128']);
- const IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
- const MIME_BY_EXT = {
- '.jpg': 'image/jpeg',
- '.jpeg': 'image/jpeg',
- '.png': 'image/png',
- '.webp': 'image/webp',
- '.gif': 'image/gif',
- };
- const POSTER_CANVAS_SPECS = {
- banner: { fileName: '店内海报_1138x292.png', width: 1138, height: 292 },
- signage: { fileName: '招牌头图_750x288.png', width: 750, height: 288 },
- };
- const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
- const SKIP_DIR_NAMES = new Set(['膳绘']);
- // ---------- small utils ----------
- function sendJson(res, statusCode, obj) {
- const data = JSON.stringify(obj);
- res.writeHead(statusCode, { 'Content-Type': 'application/json; charset=utf-8' });
- res.end(data);
- }
- function sleep(ms) {
- return new Promise((resolve) => setTimeout(resolve, ms));
- }
- function sanitizeFileName(name) {
- return String(name).replace(/[\\/:*?"<>|]/g, '_').trim() || 'file';
- }
- function readBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- let size = 0;
- req.on('data', (c) => chunks.push(c));
- req.on('data', (c) => {
- size += c.length;
- if (size > MAX_BODY_BYTES) {
- req.destroy(new Error('请求体过大'));
- reject(new Error('请求体过大'));
- }
- });
- req.on('end', () => {
- if (!chunks.length) return resolve({});
- try {
- resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
- } catch (e) {
- reject(e);
- }
- });
- req.on('error', reject);
- });
- }
- // ============================================================
- // CRAWLER MODULE — 闪购菜品图爬取
- // ============================================================
- let session = { cookie: '' };
- function extractCookieValue(cookie, name) {
- const match = String(cookie || '').match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
- if (!match) return '';
- try { return decodeURIComponent(match[1]); } catch { return match[1]; }
- }
- function getKsid() { return extractCookieValue(session.cookie, 'ksid'); }
- function loadSession() {
- try {
- const saved = JSON.parse(fs.readFileSync(SESSION_PATH, 'utf8'));
- session.cookie = String(saved.cookie || '');
- } catch { /* no saved session */ }
- }
- function saveSession() {
- fs.writeFileSync(SESSION_PATH, JSON.stringify(session, null, 2), 'utf8');
- }
- loadSession();
- function invokeApi(service, method, requestParams, extraMetas) {
- return new Promise((resolve, reject) => {
- const body = {
- id: crypto.randomBytes(16).toString('hex').toUpperCase() + '|' + Date.now(),
- method, service,
- params: { request: requestParams || {} },
- metas: Object.assign({ appName: 'melody', appVersion: '4.4.0', ksid: getKsid() }, extraMetas || {}),
- ncp: '2.0.0', adapter: 'ncp',
- extendConfig: { docMode: 'master,,' },
- };
- const data = JSON.stringify(body);
- const options = {
- hostname: 'app-api.shop.ele.me', port: 443,
- path: `/nevermore.goods/invoke?method=${encodeURIComponent(service + '.' + method)}`,
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json; charset=UTF-8', Accept: 'application/json',
- Origin: 'https://napos-goods-pc.faas.ele.me', Referer: 'https://napos-goods-pc.faas.ele.me/',
- Cookie: session.cookie || '', 'User-Agent': UA,
- 'Content-Length': Buffer.byteLength(data),
- },
- timeout: config.requestTimeoutMs,
- };
- const req = https.request(options, (res) => {
- const chunks = [];
- res.on('data', (c) => chunks.push(c));
- res.on('end', () => {
- const raw = Buffer.concat(chunks).toString('utf8');
- let json = null;
- try { json = JSON.parse(raw); } catch { /* keep raw */ }
- resolve({ statusCode: res.statusCode, json, raw });
- });
- });
- req.on('error', reject);
- req.on('timeout', () => req.destroy(new Error('请求超时')));
- req.write(data);
- req.end();
- });
- }
- function isAuthError(resp) {
- if (resp.statusCode === 401 || resp.statusCode === 403) return true;
- const j = resp.json;
- if (!j) return false;
- if (j.result !== undefined) return false;
- return /未登录|请登录|login|unauthorized|token.*expired|session.*expired/i.test(JSON.stringify(j));
- }
- function downloadImage(urlStr, redirectsLeft) {
- if (redirectsLeft === undefined) redirectsLeft = 5;
- return new Promise((resolve, reject) => {
- let u;
- try { u = new URL(urlStr); } catch (e) { return reject(new Error('无效的图片地址: ' + urlStr)); }
- const mod = u.protocol === 'http:' ? http : https;
- mod.get(u, { headers: { Referer: 'https://melody.shop.ele.me/', 'User-Agent': UA } }, (res) => {
- if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location && redirectsLeft > 0) {
- res.resume();
- return resolve(downloadImage(res.headers.location, redirectsLeft - 1));
- }
- if (res.statusCode !== 200) { res.resume(); return reject(new Error('下载图片失败 HTTP ' + res.statusCode)); }
- const chunks = [];
- res.on('data', (c) => chunks.push(c));
- res.on('end', () => resolve(Buffer.concat(chunks)));
- }).on('error', reject);
- });
- }
- let shopList = [];
- function loadManualShops() {
- try {
- const data = JSON.parse(fs.readFileSync(MANUAL_SHOPS_PATH, 'utf8'));
- if (data.version !== 1 || !Array.isArray(data.shops)) throw new Error('清单格式无效');
- const shopsById = new Map();
- for (const shop of data.shops) {
- if (!shop || !Number.isInteger(shop.shopId) || shop.shopId <= 0) continue;
- shopsById.set(shop.shopId, { shopId: shop.shopId, shopName: String(shop.shopName || shop.shopId), source: 'manual' });
- }
- shopList = Array.from(shopsById.values());
- } catch (e) {
- if (e.code !== 'ENOENT') console.warn(`读取手动店铺清单失败: ${e.message || e}`);
- }
- }
- function saveManualShops(shops) {
- const temp = `${MANUAL_SHOPS_PATH}.${process.pid}.tmp`;
- fs.writeFileSync(temp, JSON.stringify({ version: 1, shops }, null, 2), 'utf8');
- fs.renameSync(temp, MANUAL_SHOPS_PATH);
- }
- function mergeShops(newOnes) {
- const shopsById = new Map(shopList.map((shop) => [shop.shopId, shop]));
- for (const shop of newOnes) shopsById.set(shop.shopId, shop);
- return Array.from(shopsById.values());
- }
- loadManualShops();
- function completionStatePath(root) { return path.join(root, '_膳绘_店铺状态.json'); }
- function readCompletionState(root) {
- try {
- const data = JSON.parse(fs.readFileSync(completionStatePath(root), 'utf8'));
- return data.version === 1 && data.shops && typeof data.shops === 'object' ? data.shops : {};
- } catch { return {}; }
- }
- function writeCompletionState(root, shops) {
- const target = completionStatePath(root);
- const temp = `${target}.${process.pid}.tmp`;
- fs.writeFileSync(temp, JSON.stringify({ version: 1, shops }, null, 2), 'utf8');
- fs.renameSync(temp, target);
- }
- function markShopCompleted(root, shopEntry) {
- const shops = readCompletionState(root);
- shops[String(shopEntry.shopId)] = {
- shopId: shopEntry.shopId, shopName: shopEntry.shopName, folderName: shopEntry.folderName,
- completedAt: new Date().toISOString(), downloaded: shopEntry.downloaded,
- skipped: shopEntry.skipped, total: shopEntry.total,
- };
- writeCompletionState(root, shops);
- }
- function handleShopsManual(body, res) {
- const lines = String((body && body.text) || '').split(/\r?\n/);
- const parsed = [];
- for (const line of lines) {
- const t = line.trim();
- if (!t) continue;
- const parts = t.split(/[\s,,]+/).filter(Boolean);
- const idPart = parts.find((p) => /^\d+$/.test(p));
- if (!idPart) continue;
- const shopId = Number(idPart);
- const shopName = parts.filter((p) => p !== idPart).join(' ') || String(shopId);
- parsed.push({ shopId, shopName, source: 'manual' });
- }
- const previousShops = shopList;
- const mergedShops = mergeShops(parsed);
- try { saveManualShops(mergedShops); shopList = mergedShops; }
- catch (e) { shopList = previousShops; throw e; }
- sendJson(res, 200, { shops: shopList, addedCount: parsed.length });
- }
- function handleShopsList(root, res) {
- if (root && !isWorkspaceRoot(root)) return sendJson(res, 403, { error: '仅允许访问当前输出根目录' });
- const completed = root && fs.existsSync(root) ? readCompletionState(root) : {};
- sendJson(res, 200, {
- shops: shopList.map((shop) => ({ ...shop, completed: completed[String(shop.shopId)] || null })),
- });
- }
- function listRootDirs(root) {
- return fs.readdirSync(root, { withFileTypes: true })
- .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !SKIP_DIR_NAMES.has(e.name))
- .map((e) => e.name);
- }
- function resolveShopDir(root, shopId, shopName) {
- const dirs = listRootDirs(root);
- const suffix = '_' + String(shopId);
- const match = dirs.find((d) => d.endsWith(suffix));
- if (match) return { dir: path.join(root, match), folderName: match, reused: true };
- let maxSeq = 0;
- for (const d of dirs) {
- const mm = /^(\d+)_/.exec(d);
- if (mm) maxSeq = Math.max(maxSeq, parseInt(mm[1], 10));
- }
- const seq = String(maxSeq + 1).padStart(3, '0');
- const folderName = `${seq}_${sanitizeFileName(shopName)}_${shopId}`;
- const dir = path.join(root, folderName);
- fs.mkdirSync(dir, { recursive: true });
- return { dir, folderName, reused: false };
- }
- let crawlState = { status: 'idle', startedAt: null, finishedAt: null, shops: [], log: [] };
- let cancelFlag = false;
- const systemLogs = [];
- let logSeq = 0;
- function detectLogLevel(message) {
- if (/失败|错误|异常|过期|error|鉴权/i.test(message)) return 'error';
- if (/停止|跳过|警告|warn/i.test(message)) return 'warn';
- if (/完成|成功|已保存|已启动|done/i.test(message)) return 'success';
- return 'info';
- }
- function createLogEntry(message, source = 'task', level = 'info') {
- const now = new Date();
- return {
- seq: ++logSeq,
- id: `${source}-${logSeq}`,
- source,
- level,
- time: now.toTimeString().slice(0, 8),
- timestamp: now.getTime(),
- message: String(message),
- };
- }
- function pushLog(msg) {
- const entry = createLogEntry(msg, 'task', detectLogLevel(msg));
- crawlState.log.push(entry);
- if (crawlState.log.length > 500) crawlState.log.shift();
- }
- function pushSystemLog(msg, level = 'info') {
- systemLogs.push(createLogEntry(msg, 'system', level));
- if (systemLogs.length > 500) systemLogs.shift();
- }
- function getMergedLogs() {
- return [...crawlState.log, ...systemLogs]
- .sort((a, b) => b.seq - a.seq)
- .slice(0, 500);
- }
- async function startCrawl(body, res) {
- if (crawlState.status === 'running') return sendJson(res, 409, { error: '已有抓取任务在进行中' });
- if (!session.cookie || !getKsid()) return sendJson(res, 400, { error: '请先填写包含 ksid 的 Cookie' });
- const root = String((body && body.root) || getWorkspaceRoot()).trim();
- if (!isWorkspaceRoot(root)) return sendJson(res, 403, { error: '仅允许采集当前输出根目录' });
- if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
- return sendJson(res, 400, { error: '输出根目录不存在: ' + root });
- }
- const shopIds = Array.isArray(body && body.shopIds) ? body.shopIds.map(Number) : [];
- const selectedShops = shopIds.map((id) => shopList.find((s) => s.shopId === id)).filter(Boolean);
- if (!selectedShops.length) return sendJson(res, 400, { error: '没有可抓取的店铺,请先填写手动店铺清单并勾选' });
- const forceFullCrawl = Boolean(body && body.forceFullCrawl);
- const completed = readCompletionState(root);
- const skippedCompleted = forceFullCrawl ? [] : selectedShops.filter((s) => completed[String(s.shopId)]);
- const shops = forceFullCrawl ? selectedShops : selectedShops.filter((s) => !completed[String(s.shopId)]);
- const pageSize = Number(body && body.pageSize) || config.pageSize;
- const delayMs = Number(body && body.delayMs) || config.delayMs;
- cancelFlag = false;
- crawlState = {
- status: shops.length ? 'running' : 'done', startedAt: Date.now(),
- finishedAt: shops.length ? null : Date.now(), forceFullCrawl,
- shops: [
- ...skippedCompleted.map((s) => ({
- shopId: s.shopId, shopName: s.shopName, folderName: completed[String(s.shopId)].folderName || null,
- state: 'skipped_completed', total: completed[String(s.shopId)].total || 0,
- downloaded: 0, skipped: 0, failed: 0, error: null,
- })),
- ...shops.map((s) => ({
- shopId: s.shopId, shopName: s.shopName, folderName: null, state: 'pending',
- total: 0, downloaded: 0, skipped: 0, failed: 0, error: null,
- })),
- ],
- log: [],
- };
- pushLog(`开始抓取,实际抓取 ${shops.length} 家${skippedCompleted.length ? `,历史完成跳过 ${skippedCompleted.length} 家` : ''},root=${root}`);
- sendJson(res, 200, { ok: true, crawlCount: shops.length, skippedCompletedCount: skippedCompleted.length });
- if (!shops.length) return pushLog('所选店铺均已完成;勾选"强制全量抓取"可重新下载');
- runCrawlLoop(root, pageSize, delayMs, forceFullCrawl).catch((e) => {
- crawlState.status = 'error';
- crawlState.finishedAt = Date.now();
- pushLog('抓取流程异常终止: ' + (e.message || e));
- });
- }
- async function runCrawlLoop(root, pageSize, delayMs, forceFullCrawl) {
- for (const shopEntry of crawlState.shops) {
- if (shopEntry.state === 'skipped_completed') continue;
- if (cancelFlag) {
- crawlState.status = 'stopped';
- crawlState.finishedAt = Date.now();
- pushLog('已停止');
- return;
- }
- shopEntry.state = 'running';
- pushLog(`[${shopEntry.shopName}] 开始`);
- let dirInfo;
- try { dirInfo = resolveShopDir(root, shopEntry.shopId, shopEntry.shopName); }
- catch (e) {
- shopEntry.state = 'failed';
- shopEntry.error = '创建目录失败: ' + (e.message || e);
- pushLog(`[${shopEntry.shopName}] 创建目录失败: ${e.message || e}`);
- continue;
- }
- shopEntry.folderName = dirInfo.folderName;
- pushLog(`[${shopEntry.shopName}] ${dirInfo.reused ? '复用已有目录' : '新建目录'} ${dirInfo.folderName}`);
- const allItems = [];
- const seen = new Set();
- let nextId;
- let page = 0;
- const MAX_PAGES = 200;
- let authFailed = false;
- while (page < MAX_PAGES) {
- if (cancelFlag) break;
- page++;
- const requestParams = {
- shopId: shopEntry.shopId, pageSize, queryType: 'SHOP',
- searchKey: '', searchType: ['ITEM_NAME'],
- };
- if (nextId) requestParams.nextId = nextId;
- let resp;
- try { resp = await invokeApi('ItemPhotoProcessService', 'getItemPhotoGallery', requestParams, { shopId: shopEntry.shopId }); }
- catch (e) {
- shopEntry.error = '请求失败: ' + (e.message || e);
- pushLog(`[${shopEntry.shopName}] 请求失败: ${e.message || e}`);
- break;
- }
- if (isAuthError(resp)) {
- authFailed = true;
- shopEntry.error = '会话可能已过期,请重新登录后更新 Cookie';
- pushLog(`[${shopEntry.shopName}] 鉴权失败(ksid/Cookie 可能已过期)`);
- break;
- }
- const items = (resp.json && resp.json.result && resp.json.result.result) || [];
- nextId = resp.json && resp.json.result && resp.json.result.nextId;
- if (!items.length) {
- pushLog(`[${shopEntry.shopName}] 第${page}页无数据,结束翻页`);
- break;
- }
- let newCount = 0;
- for (const it of items) {
- const gid = it.itemGlobalId;
- if (gid !== undefined && gid !== null && seen.has(gid)) continue;
- if (gid !== undefined && gid !== null) seen.add(gid);
- allItems.push(it);
- newCount++;
- }
- pushLog(`[${shopEntry.shopName}] 第${page}页 新增${newCount}条`);
- if (!nextId) break;
- await sleep(200);
- }
- shopEntry.total = allItems.length;
- if (authFailed && !allItems.length) {
- shopEntry.state = 'failed';
- continue;
- }
- pushLog(`[${shopEntry.shopName}] 共${allItems.length}个菜品,开始下载`);
- const manifest = [];
- const usedNames = new Set();
- for (const it of allItems) {
- if (cancelFlag) break;
- const itemName = String(it.itemName || it.itemGlobalId || 'unnamed').trim();
- const photoUrl = it.photoUrl || it.thumbnailUrl;
- if (!photoUrl) {
- shopEntry.skipped++;
- manifest.push({ itemName, itemGlobalId: it.itemGlobalId, photoUrl: null, savedFile: null, status: 'no_photo' });
- continue;
- }
- let finalBase = sanitizeFileName(itemName);
- let n = 1;
- while (usedNames.has(finalBase)) { finalBase = `${sanitizeFileName(itemName)}_${n++}`; }
- usedNames.add(finalBase);
- try {
- const buf = await downloadImage(photoUrl);
- const ext = guessExtFromUrl(photoUrl);
- const fileName = `${finalBase}.${ext}`;
- fs.writeFileSync(path.join(dirInfo.dir, fileName), buf);
- shopEntry.downloaded++;
- manifest.push({ itemName, itemGlobalId: it.itemGlobalId, photoUrl, savedFile: fileName, status: 'downloaded' });
- } catch (e) {
- shopEntry.failed++;
- manifest.push({ itemName, itemGlobalId: it.itemGlobalId, photoUrl, savedFile: null, status: 'download_failed', error: e.message || String(e) });
- pushLog(`[${shopEntry.shopName}] 下载失败 ${itemName}: ${e.message || e}`);
- }
- await sleep(delayMs);
- }
- try {
- fs.writeFileSync(path.join(dirInfo.dir, '_菜品图爬取记录.json'), JSON.stringify(manifest, null, 2), 'utf8');
- if (!shopEntry.failed && !cancelFlag) markShopCompleted(root, shopEntry);
- } catch (e) {
- shopEntry.failed++;
- shopEntry.error = `保存抓取状态失败: ${e.message || e}`;
- pushLog(`[${shopEntry.shopName}] 保存抓取状态失败: ${e.message || e}`);
- }
- shopEntry.state = shopEntry.failed ? 'failed' : cancelFlag ? 'stopped' : 'done';
- pushLog(`[${shopEntry.shopName}] 完成: 成功${shopEntry.downloaded} 跳过${shopEntry.skipped} 失败${shopEntry.failed}`);
- }
- crawlState.status = cancelFlag ? 'stopped' : 'done';
- crawlState.finishedAt = Date.now();
- pushLog('抓取任务结束');
- }
- function stopCrawl(res) {
- if (crawlState.status !== 'running') return sendJson(res, 200, { ok: true, note: '当前没有正在进行的任务' });
- cancelFlag = true;
- pushLog('收到停止请求,将在当前步骤完成后停止');
- sendJson(res, 200, { ok: true });
- }
- // ============================================================
- // GENERATOR MODULE — 店铺视觉图生成
- // ============================================================
- const OVERLAY_POSITION_LABELS = {
- 'top-left': '左上角',
- 'top-right': '右上角',
- 'bottom-left': '左下角',
- 'bottom-right': '右下角',
- };
- function findExistingAsset(shopDir, baseName) {
- const dir = path.join(shopDir, '_生成图片');
- for (const ext of IMAGE_EXT) {
- const p = path.join(dir, baseName + ext);
- if (fs.existsSync(p)) return p;
- }
- return null;
- }
- const findExistingLogo = (shopDir) => findExistingAsset(shopDir, 'logo');
- const findExistingSticker = (shopDir) => findExistingAsset(shopDir, '贴纸');
- function readAsDataUri(filePath) {
- const buf = fs.readFileSync(filePath);
- let ext = path.extname(filePath).toLowerCase().replace('.', '');
- if (ext === 'jpg') ext = 'jpeg';
- return `data:image/${ext};base64,${buf.toString('base64')}`;
- }
- // Builds the reference-image list and final prompt for a generation request, optionally
- // fusing the shop's already-generated LOGO and/or 贴纸(sticker) into the frame. Each overlay
- // can use either of two modes:
- // - 'ai' (default): the asset is passed as an extra reference image and the model is asked
- // to paint it into the frame itself.
- // - 'composite': the model is only asked to leave the target corner visually clean; the
- // actual pixel fusion is done afterwards by compositeOverlaysOntoImage() with no LLM call.
- function buildImagesAndPrompt(shopDir, basePrompt, refDishFiles, opts) {
- const { addLogo, logoPosition, logoMode, addSticker, stickerPosition, stickerMode } = opts || {};
- const images = [];
- for (const f of (refDishFiles || []).slice(0, 3)) {
- try {
- images.push(readAsDataUri(path.join(shopDir, f)));
- } catch {
- // skip unreadable reference image
- }
- }
- const warnings = [];
- const overlayClauses = [];
- const compositeOverlays = [];
- if (addLogo) {
- const logoPath = findExistingLogo(shopDir);
- if (logoPath) {
- const posLabel = OVERLAY_POSITION_LABELS[logoPosition] || OVERLAY_POSITION_LABELS['bottom-right'];
- if (logoMode === 'composite') {
- compositeOverlays.push({ type: 'logo', path: logoPath, position: logoPosition || 'bottom-right' });
- overlayClauses.push(
- opts.sourceImageFirst
- ? `第一张图是菜品原图,第二张图是店铺指定LOGO。必须彻底移除菜品原图中已有的LOGO、水印、店铺名、徽章和旧品牌标识,并自然修复该区域背景;不要模仿或保留这些旧标识。画面${posLabel}保持干净,留出用于程序叠加店铺指定LOGO的区域。`
- : `画面的${posLabel}请保持背景简洁、不绘制任何LOGO或品牌图案(该区域将在生成后由程序直接叠加店铺LOGO图片)`
- );
- } else {
- try {
- images.push(readAsDataUri(logoPath));
- overlayClauses.push(
- opts.sourceImageFirst
- ? `第一张图是菜品原图,第二张图是店铺指定LOGO。店铺指定LOGO是唯一权威品牌标识;必须彻底移除菜品原图中已有的LOGO、水印、店铺名、徽章和旧品牌标识,并自然修复该区域背景。只在画面${posLabel}使用店铺指定LOGO,严格保持其图形、文字、配色和比例完整清晰,不要复制、模仿或保留原图旧标识。`
- : `参考图中的店铺LOGO图案(简洁品牌标识)请原样添加到画面的${posLabel}`
- );
- } catch {
- warnings.push('读取已生成的LOGO文件失败,本次生成未附加LOGO');
- }
- }
- } else {
- warnings.push('未找到可用LOGO,请先生成');
- }
- }
- if (addSticker) {
- const stickerPath = findExistingSticker(shopDir);
- if (stickerPath) {
- const posLabel = OVERLAY_POSITION_LABELS[stickerPosition] || OVERLAY_POSITION_LABELS['bottom-left'];
- if (stickerMode === 'composite') {
- compositeOverlays.push({ type: 'sticker', path: stickerPath, position: stickerPosition || 'bottom-left' });
- overlayClauses.push(`画面的${posLabel}请保持背景简洁、不绘制任何贴纸/徽章图案(该区域将在生成后由程序直接叠加店铺贴纸图片)`);
- } else {
- try {
- images.push(readAsDataUri(stickerPath));
- overlayClauses.push(`参考图中的店铺贴纸插画(徽章/贴纸风格图案)请原样叠加到画面的${posLabel}`);
- } catch {
- warnings.push('读取已生成的贴纸文件失败,本次生成未附加贴纸');
- }
- }
- } else {
- warnings.push('未找到可用贴纸,请先生成');
- }
- }
- let prompt = basePrompt;
- if (overlayClauses.length) {
- prompt += `\n\n${overlayClauses.join(';')},保持图案本身完整、清晰、不变形、不被裁切,不要遮挡画面主体;其余参考图仅作为风格/内容参考,不必出现在画面里。`;
- }
- return { images, prompt, warning: warnings.length ? warnings.join(';') : null, compositeOverlays };
- }
- // ---------- sticker: chroma-key background removal (pure-JS, no image editor needed) ----------
- // The generation model has no true alpha-channel/transparent-background output, so for the
- // "贴纸" (sticker) asset we ask it to render on a flat key-color background and cut that
- // color out ourselves, producing a real transparent PNG.
- const STICKER_KEY_COLOR = [255, 0, 255]; // pure magenta, rarely present in food photography
- const STICKER_THRESHOLD = 60;
- const STICKER_FEATHER = 40;
- function decodeToRGBA(buf) {
- if (buf.length > 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
- const png = PNG.sync.read(buf);
- return { width: png.width, height: png.height, data: png.data };
- }
- const img = jpeg.decode(buf, { useTArray: true });
- return { width: img.width, height: img.height, data: img.data };
- }
- function chromaKeyToTransparentPng(decoded, keyColor, threshold, feather) {
- const { width, height, data } = decoded;
- const png = new PNG({ width, height });
- const [kr, kg, kb] = keyColor;
- for (let i = 0; i < width * height; i++) {
- const o = i * 4;
- const r = data[o];
- const g = data[o + 1];
- const b = data[o + 2];
- const dist = Math.sqrt((r - kr) ** 2 + (g - kg) ** 2 + (b - kb) ** 2);
- let alpha;
- if (dist <= threshold) alpha = 0;
- else if (dist >= threshold + feather) alpha = 255;
- else alpha = Math.round(((dist - threshold) / feather) * 255);
- png.data[o] = r;
- png.data[o + 1] = g;
- png.data[o + 2] = b;
- png.data[o + 3] = alpha;
- }
- return PNG.sync.write(png);
- }
- // ---------- pure image-processing overlay compositing (no LLM call) ----------
- // Alternative to the AI-fusion overlay path above: pastes an already-generated logo/sticker
- // image directly onto the generated result via alpha blending, entirely in-process.
- function resizeRGBA(src, srcW, srcH, dstW, dstH) {
- if (srcW === dstW && srcH === dstH) return src;
- const dst = Buffer.alloc(dstW * dstH * 4);
- for (let y = 0; y < dstH; y++) {
- const srcYf = Math.min(srcH - 1, Math.max(0, ((y + 0.5) * srcH) / dstH - 0.5));
- const y0 = Math.floor(srcYf);
- const y1 = Math.min(srcH - 1, y0 + 1);
- const wy = srcYf - y0;
- for (let x = 0; x < dstW; x++) {
- const srcXf = Math.min(srcW - 1, Math.max(0, ((x + 0.5) * srcW) / dstW - 0.5));
- const x0 = Math.floor(srcXf);
- const x1 = Math.min(srcW - 1, x0 + 1);
- const wx = srcXf - x0;
- const o = (y * dstW + x) * 4;
- for (let c = 0; c < 4; c++) {
- const p00 = src[(y0 * srcW + x0) * 4 + c];
- const p10 = src[(y0 * srcW + x1) * 4 + c];
- const p01 = src[(y1 * srcW + x0) * 4 + c];
- const p11 = src[(y1 * srcW + x1) * 4 + c];
- const top = p00 + (p10 - p00) * wx;
- const bottom = p01 + (p11 - p01) * wx;
- dst[o + c] = Math.round(top + (bottom - top) * wy);
- }
- }
- }
- return dst;
- }
- const OVERLAY_WIDTH_RATIO = { logo: 0.16, sticker: 0.22 };
- // Alpha-blends `overlay` (resized to a fraction of the base width, keeping its aspect ratio)
- // onto `base` at the given corner and returns a new decoded-RGBA object. Both inputs and the
- // output are the same {width, height, data} shape produced by decodeToRGBA().
- function compositeOverlayOntoBase(base, overlay, position, widthRatio) {
- const targetW = Math.max(1, Math.round(base.width * widthRatio));
- const targetH = Math.max(1, Math.round((overlay.height / overlay.width) * targetW));
- const resized = resizeRGBA(overlay.data, overlay.width, overlay.height, targetW, targetH);
- const margin = Math.round(base.width * 0.04);
- let x, y;
- if (position === 'top-left') { x = margin; y = margin; }
- else if (position === 'top-right') { x = base.width - margin - targetW; y = margin; }
- else if (position === 'bottom-left') { x = margin; y = base.height - margin - targetH; }
- else { x = base.width - margin - targetW; y = base.height - margin - targetH; } // bottom-right (default)
- x = Math.max(0, Math.min(x, base.width - targetW));
- y = Math.max(0, Math.min(y, base.height - targetH));
- const out = Buffer.from(base.data);
- for (let j = 0; j < targetH; j++) {
- const by = y + j;
- if (by < 0 || by >= base.height) continue;
- for (let i = 0; i < targetW; i++) {
- const bx = x + i;
- if (bx < 0 || bx >= base.width) continue;
- const so = (j * targetW + i) * 4;
- const alpha = resized[so + 3] / 255;
- if (alpha <= 0) continue;
- const bo = (by * base.width + bx) * 4;
- out[bo] = Math.round(resized[so] * alpha + out[bo] * (1 - alpha));
- out[bo + 1] = Math.round(resized[so + 1] * alpha + out[bo + 1] * (1 - alpha));
- out[bo + 2] = Math.round(resized[so + 2] * alpha + out[bo + 2] * (1 - alpha));
- }
- }
- return { width: base.width, height: base.height, data: out };
- }
- function encodeRGBAToPng(decoded) {
- const png = new PNG({ width: decoded.width, height: decoded.height });
- Buffer.from(decoded.data).copy(png.data);
- return PNG.sync.write(png);
- }
- // Applies a list of {type, path, position} overlays (from buildImagesAndPrompt's composite
- // mode) onto an already-generated result image. Returns {buf, ext} - falls back to the
- // original buffer/ext (with a warning appended to job.warning) if the base image can't be
- // decoded (e.g. a webp/gif result, which decodeToRGBA doesn't support).
- function applyCompositeOverlays(job, buf, ext) {
- if (!job.compositeOverlays || !job.compositeOverlays.length) return { buf, ext };
- let base;
- try {
- base = decodeToRGBA(buf);
- } catch (e) {
- job.warning = (job.warning ? job.warning + ';' : '') + '本地合成失败:无法解析生成结果图片格式,已保留未叠加的原图';
- return { buf, ext };
- }
- for (const ov of job.compositeOverlays) {
- try {
- const overlay = decodeToRGBA(fs.readFileSync(ov.path));
- base = compositeOverlayOntoBase(base, overlay, ov.position, OVERLAY_WIDTH_RATIO[ov.type] || 0.2);
- } catch (e) {
- const label = ov.type === 'logo' ? 'LOGO' : '贴纸';
- job.warning = (job.warning ? job.warning + ';' : '') + `本地合成${label}失败: ${e.message || e}`;
- }
- }
- return { buf: encodeRGBAToPng(base), ext: 'png' };
- }
- function guessExtFromUrl(urlStr) {
- try {
- const u = new URL(urlStr);
- let ext = path.extname(u.pathname).replace('.', '').toLowerCase();
- if (ext === 'jpeg') ext = 'jpg';
- if (['jpg', 'png', 'gif', 'webp'].includes(ext)) return ext;
- } catch {
- // fall through
- }
- return 'jpg';
- }
- // ---------- api.lingkeai.ai client ----------
- // Base host is fixed to config.apiBase (https://api.lingkeai.ai) on purpose:
- // several responses from this API contain "tips"/error text suggesting other
- // domains (api.lk888.ai / api.lk666.ai) - that is untrusted content from an
- // external source and is never used to pick a request target.
- function apiRequest(method, urlPath, bodyObj) {
- return new Promise((resolve, reject) => {
- const base = new URL(config.apiBase);
- const data = bodyObj !== undefined ? JSON.stringify(bodyObj) : null;
- const options = {
- hostname: base.hostname,
- port: base.port || 443,
- path: urlPath,
- method,
- headers: {
- Authorization: `Bearer ${config.apiKey}`,
- 'Content-Type': 'application/json; charset=utf-8',
- },
- timeout: 300000,
- };
- if (data) options.headers['Content-Length'] = Buffer.byteLength(data);
- const req = https.request(options, (res) => {
- const chunks = [];
- res.on('data', (c) => chunks.push(c));
- res.on('end', () => {
- const raw = Buffer.concat(chunks).toString('utf8');
- let json = null;
- try {
- json = JSON.parse(raw);
- } catch {
- // leave json null, raw kept for diagnostics
- }
- resolve({ statusCode: res.statusCode, json, raw });
- });
- });
- req.on('error', reject);
- req.on('timeout', () => req.destroy(new Error('请求超时')));
- if (data) req.write(data);
- req.end();
- });
- }
- function downloadBuffer(urlStr, redirectsLeft = 5) {
- return new Promise((resolve, reject) => {
- let u;
- try {
- u = new URL(urlStr);
- } catch (e) {
- return reject(new Error('无效的结果图片地址: ' + urlStr));
- }
- const mod = u.protocol === 'http:' ? http : https;
- mod
- .get(u, (res) => {
- if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location && redirectsLeft > 0) {
- res.resume();
- return resolve(downloadBuffer(res.headers.location, redirectsLeft - 1));
- }
- if (res.statusCode !== 200) {
- res.resume();
- return reject(new Error('下载生成图片失败 HTTP ' + res.statusCode));
- }
- const chunks = [];
- res.on('data', (c) => chunks.push(c));
- res.on('end', () => resolve(Buffer.concat(chunks)));
- })
- .on('error', reject);
- });
- }
- // ---------- job queue ----------
- const jobs = new Map();
- const pendingQueue = [];
- let activeCount = 0;
- const persistedTasks = new Map();
- let taskStoreLoaded = false;
- function getTaskStoreFile() {
- return path.join(getWorkspaceRoot(), '.genpic', 'tasks.json');
- }
- function taskSnapshot(job) {
- const { images, ...safeJob } = job;
- return {
- ...safeJob,
- imageCount: Array.isArray(images) ? images.length : 0,
- updatedAt: Date.now(),
- };
- }
- function persistJob(job) {
- if (!job || !job.id) return;
- persistedTasks.set(job.id, taskSnapshot(job));
- const storeFile = getTaskStoreFile();
- fs.mkdirSync(path.dirname(storeFile), { recursive: true });
- const tempPath = `${storeFile}.${process.pid}.tmp`;
- fs.writeFileSync(tempPath, JSON.stringify({
- version: 1,
- updatedAt: new Date().toISOString(),
- tasks: Array.from(persistedTasks.values()),
- }, null, 2));
- fs.renameSync(tempPath, storeFile);
- }
- function loadPersistedJobs() {
- if (taskStoreLoaded) return;
- taskStoreLoaded = true;
- const storeFile = getTaskStoreFile();
- let parsed;
- try {
- parsed = JSON.parse(fs.readFileSync(storeFile, 'utf8'));
- } catch {
- return;
- }
- if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.tasks)) return;
- for (const raw of parsed.tasks) {
- if (!raw || typeof raw.id !== 'string' || !raw.root || typeof raw.state !== 'string') continue;
- const job = {
- ...raw,
- images: [],
- compositeOverlays: Array.isArray(raw.compositeOverlays) ? raw.compositeOverlays : [],
- };
- if (!MODEL_IDS.has(job.model)) job.model = config.model;
- jobs.set(job.id, job);
- persistedTasks.set(job.id, taskSnapshot(job));
- }
- for (const job of jobs.values()) {
- if (job.state === 'queued') {
- job.state = 'failed';
- job.finishedAt = Date.now();
- job.error = '服务重启前任务仍在排队,请重新提交';
- persistJob(job);
- } else if (job.state === 'running' || job.state === 'submitted') {
- if (!job.taskId) {
- job.state = 'failed';
- job.finishedAt = Date.now();
- job.error = '服务重启时任务尚未获得供应商任务 ID,请重新提交';
- persistJob(job);
- } else {
- runJob(job);
- }
- }
- }
- }
- function createJob(opts) {
- const id = crypto.randomUUID();
- const job = {
- id,
- root: opts.root,
- folderName: opts.folderName,
- kind: opts.kind,
- shopName: opts.shopName,
- dishName: opts.dishName || null,
- model: MODEL_IDS.has(opts.model) ? opts.model : config.model,
- prompt: opts.prompt,
- size: opts.size,
- aspectRatio: opts.aspectRatio,
- images: opts.images || [],
- outputDir: opts.outputDir,
- outputBaseName: opts.outputBaseName,
- compositeOverlays: opts.compositeOverlays || [],
- state: 'queued',
- progress: '0%',
- taskId: null,
- cost: null,
- resultUrl: null,
- remoteUrl: null,
- width: null,
- height: null,
- fileSizeBytes: null,
- error: null,
- warning: opts.warning || null,
- createdAt: Date.now(),
- startedAt: null,
- finishedAt: null,
- };
- jobs.set(id, job);
- persistJob(job);
- const jobTitle = job.dishName ? `${job.shopName} / ${job.dishName}` : `${job.shopName} / ${job.kind}`;
- pushSystemLog(`生成任务已提交:${jobTitle}(${job.model})`);
- if (activeCount < config.maxConcurrentJobs) {
- startJob(job);
- } else {
- pendingQueue.push(id);
- }
- return job;
- }
- function startJob(job) {
- runJob(job);
- }
- function runJob(job) {
- activeCount++;
- job.state = 'running';
- job.startedAt = job.startedAt || Date.now();
- persistJob(job);
- processJob(job)
- .catch((e) => {
- job.state = 'failed';
- job.error = job.error || e.message || String(e);
- })
- .finally(() => {
- const jobTitle = job.dishName ? `${job.shopName} / ${job.dishName}` : `${job.shopName} / ${job.kind}`;
- if (job.state === 'success') pushSystemLog(`生成完成:${jobTitle}`, 'success');
- else if (job.state === 'failed') pushSystemLog(`生成失败:${jobTitle},${job.error || '未知错误'}`, 'error');
- job.finishedAt = Date.now();
- persistJob(job);
- activeCount--;
- const nextId = pendingQueue.shift();
- if (nextId) {
- const nextJob = jobs.get(nextId);
- if (nextJob) startJob(nextJob);
- }
- });
- }
- // Builds the model-specific `params` object for the /v1/media/generate request. Different
- // image models on this API expose different (and sometimes confusingly named) parameters -
- // e.g. wan2.6-image has no separate aspect_ratio field, its required "size" param IS the
- // aspect-ratio string (auto/1:1/16:9/...), plus an optional prompt_extend flag.
- function buildParamsForModel(modelId, job) {
- const params = {};
- if (modelId === 'gpt-image-2') {
- params.size = 'auto';
- params.quality = 'auto';
- params.resolution = job.size || '1K';
- params.n = 1;
- params.response_format = 'url';
- if (job.aspectRatio && job.aspectRatio !== 'auto') params.aspect_ratio = job.aspectRatio;
- } else if (modelId === 'gpt-image-2-guan') {
- params.size = 'auto';
- params.quality = 'auto';
- } else if (modelId === 'wan2.6-image') {
- params.size = job.aspectRatio || job.size || 'auto';
- params.prompt_extend = true;
- } else {
- if (job.size) params.size = NO_1K_SUPPORT.has(modelId) && job.size === '1K' ? '2K' : job.size;
- if (job.aspectRatio) params.aspect_ratio = job.aspectRatio;
- }
- let images = job.images;
- if (modelId === 'wan2.6-image' && images.length > 4) {
- job.warning = (job.warning ? job.warning + ';' : '') + 'wan2.6-image 最多支持4张参考图,已自动截取前4张';
- images = images.slice(0, 4);
- }
- if (images.length === 1) params.images = images[0];
- else if (images.length > 1) params.images = images;
- return params;
- }
- async function processJob(job) {
- const resuming = !!job.taskId;
- if (!resuming) {
- const body = {
- model: job.model,
- prompt: job.prompt,
- params: buildParamsForModel(job.model, job),
- };
- const submit = await apiRequest('POST', '/v1/media/generate', body);
- const taskId = submit.json && (submit.json.task_id || (submit.json.data && submit.json.data.task_id));
- if (submit.statusCode !== 200 || !submit.json || !taskId) {
- throw new Error('提交生成任务失败: ' + (submit.json ? JSON.stringify(submit.json) : submit.raw.slice(0, 500)));
- }
- job.taskId = taskId;
- persistJob(job);
- }
- await sleep(resuming ? 1000 : 7000);
- const start = job.startedAt || Date.now();
- const TIMEOUT_MS = 10 * 60 * 1000;
- for (;;) {
- if (Date.now() - start > TIMEOUT_MS) {
- job.state = 'failed';
- job.error = '轮询超时(10分钟未完成)';
- return;
- }
- const statusPath = (job.model === 'gpt-image-2' || job.model === 'gpt-image-2-guan')
- ? `/v1/media/status?task_id=${encodeURIComponent(job.taskId)}`
- : `/v1/skills/task-status?task_id=${encodeURIComponent(job.taskId)}`;
- const statusResp = await apiRequest('GET', statusPath);
- const status = statusResp.json;
- if (!status) {
- await sleep(5000);
- continue;
- }
- job.progress = String(status.progress ?? job.progress);
- if (status.cost !== undefined) job.cost = status.cost;
- persistJob(job);
- if (status.is_final) {
- if (status.state === 'success' && status.result_url) {
- job.remoteUrl = status.result_url;
- const buf = await downloadBuffer(status.result_url);
- let finalBuf, ext;
- finalBuf = buf;
- ext = guessExtFromUrl(status.result_url);
- ({ buf: finalBuf, ext } = applyCompositeOverlays(job, finalBuf, ext));
- fs.mkdirSync(job.outputDir, { recursive: true });
- const savePath = path.join(job.outputDir, `${job.outputBaseName}.${ext}`);
- fs.writeFileSync(savePath, finalBuf);
- const dims = getImageSize(finalBuf) || {};
- job.width = dims.width || null;
- job.height = dims.height || null;
- job.fileSizeBytes = finalBuf.length;
- job.resultPath = savePath;
- job.resultUrl = '/files?path=' + encodeURIComponent(savePath);
- const creationHistoryDir = path.basename(job.outputDir) === '菜品图'
- ? path.dirname(job.outputDir)
- : job.outputDir;
- appendCreationHistory(creationHistoryDir, {
- id: job.id,
- root: job.root,
- folderName: job.folderName,
- shopName: job.shopName,
- kind: job.kind,
- name: job.dishName || job.kind,
- dishName: job.dishName,
- fileName: path.basename(savePath),
- relativePath: path.relative(creationHistoryDir, savePath),
- remoteUrl: job.remoteUrl,
- model: job.model,
- cost: job.cost,
- width: job.width,
- height: job.height,
- fileSizeBytes: job.fileSizeBytes,
- generatedAt: new Date().toISOString(),
- });
- job.state = 'success';
- } else {
- job.state = 'failed';
- job.error = status.error || status.status || '生成失败';
- job.cost = status.cost ?? job.cost;
- }
- return;
- }
- await sleep(5000);
- }
- }
- // ---------- scan helpers ----------
- function fileInfo(p) {
- const buf = fs.readFileSync(p);
- const dims = getImageSize(buf) || {};
- return {
- url: '/files?path=' + encodeURIComponent(p),
- width: dims.width || null,
- height: dims.height || null,
- fileSizeBytes: buf.length,
- };
- }
- function scanGenerated(shopDir) {
- const dir = path.join(shopDir, '_生成图片');
- const result = { logo: null, banner: null, signage: null, sticker: null, dishes: {} };
- if (!fs.existsSync(dir)) return result;
- for (const [kind, base] of [['logo', 'logo'], ['banner', 'banner'], ['signage', '招牌头图'], ['sticker', '贴纸']]) {
- for (const ext of IMAGE_EXT) {
- const p = path.join(dir, base + ext);
- if (fs.existsSync(p)) {
- try {
- result[kind] = fileInfo(p);
- } catch {
- // ignore unreadable file
- }
- break;
- }
- }
- }
- const dishDir = path.join(dir, '菜品图');
- if (fs.existsSync(dishDir)) {
- for (const f of fs.readdirSync(dishDir)) {
- const ext = path.extname(f).toLowerCase();
- if (!IMAGE_EXT.has(ext)) continue;
- const name = f.slice(0, -ext.length);
- try {
- result.dishes[name] = fileInfo(path.join(dishDir, f));
- } catch {
- // ignore unreadable file
- }
- }
- }
- return result;
- }
- function loadCreationHistory(outputDir) {
- const historyPath = path.join(outputDir, 'generation-history.json');
- if (!fs.existsSync(historyPath)) return [];
- try {
- const records = JSON.parse(fs.readFileSync(historyPath, 'utf8'));
- return Array.isArray(records) ? records : [];
- } catch {
- return [];
- }
- }
- function appendCreationHistory(outputDir, record) {
- fs.mkdirSync(outputDir, { recursive: true });
- const historyPath = path.join(outputDir, 'generation-history.json');
- const records = loadCreationHistory(outputDir).filter((item) => item.id !== record.id);
- records.push(record);
- const tempPath = historyPath + '.tmp';
- fs.writeFileSync(tempPath, JSON.stringify(records, null, 2));
- fs.renameSync(tempPath, historyPath);
- }
- function handleScan(query, res) {
- const root = query.root;
- if (!isWorkspaceRoot(root)) return sendJson(res, 403, { error: '仅允许扫描当前输出根目录' });
- if (!root || !fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
- return sendJson(res, 400, { error: '目录不存在: ' + root });
- }
- let selectedFolders = null;
- if (query.folders) {
- try {
- selectedFolders = JSON.parse(query.folders);
- } catch {
- return sendJson(res, 400, { error: '指定店铺参数无效' });
- }
- if (!Array.isArray(selectedFolders) || !selectedFolders.length ||
- selectedFolders.some((name) => typeof name !== 'string' || !name ||
- name === '.' || name === '..' || name.includes('/') || name.includes('\\'))) {
- return sendJson(res, 400, { error: '指定店铺参数无效' });
- }
- selectedFolders = [...new Set(selectedFolders)];
- }
- let entries;
- try {
- entries = fs.readdirSync(root, { withFileTypes: true });
- } catch (e) {
- return sendJson(res, 400, { error: '无法读取目录: ' + e.message });
- }
- const shops = [];
- for (const ent of entries) {
- if (!ent.isDirectory()) continue;
- if (ent.name.startsWith('.') || ent.name === '图片生成工具') continue;
- if (selectedFolders && !selectedFolders.includes(ent.name)) continue;
- const folderName = ent.name;
- const shopDir = path.join(root, folderName);
- let files;
- try {
- files = fs.readdirSync(shopDir, { withFileTypes: true });
- } catch {
- continue;
- }
- const dishes = [];
- for (const f of files) {
- if (!f.isFile()) continue;
- const ext = path.extname(f.name).toLowerCase();
- if (!IMAGE_EXT.has(ext)) continue;
- dishes.push({
- file: f.name,
- name: f.name.slice(0, -ext.length).replace(/^\d+_/, ''),
- url: '/files?path=' + encodeURIComponent(path.join(shopDir, f.name)),
- });
- }
- if (!dishes.length) continue;
- dishes.sort((a, b) => a.file.localeCompare(b.file, 'zh'));
- let overrides = {};
- const cfgPath = path.join(shopDir, '_生成图片', 'prompt-config.json');
- if (fs.existsSync(cfgPath)) {
- try {
- overrides = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
- } catch {
- // ignore malformed override file
- }
- }
- const parsedName = folderName.replace(/^\d+_/, '').replace(/_\d+$/, '');
- shops.push({
- folderName,
- shopName: overrides.shopName || parsedName,
- dishes,
- promptOverrides: overrides.prompts || {},
- generated: scanGenerated(shopDir),
- });
- }
- shops.sort((a, b) => a.folderName.localeCompare(b.folderName, 'zh'));
- sendJson(res, 200, { root, shops });
- }
- const CREATION_KINDS = new Set(['logo', 'banner', 'signage', 'sticker', 'dish']);
- function getCreationKind(directoryName, fileName) {
- if (directoryName === '菜品图') return 'dish';
- if (/^logo\./i.test(fileName)) return 'logo';
- if (/^(banner|店内海报)/i.test(fileName)) return 'banner';
- if (/^招牌头图/i.test(fileName)) return 'signage';
- if (/^贴纸/i.test(fileName)) return 'sticker';
- return 'other';
- }
- function handleCreations(query, res) {
- const root = query.root;
- if (!isWorkspaceRoot(root)) return sendJson(res, 403, { error: '仅允许访问当前输出根目录' });
- const resolvedRoot = path.resolve(String(root));
- if (!fs.existsSync(resolvedRoot) || !fs.statSync(resolvedRoot).isDirectory()) {
- return sendJson(res, 400, { error: '目录不存在: ' + resolvedRoot });
- }
- const limit = Math.min(Math.max(Number(query.limit) || 300, 1), 600);
- const retentionCutoff = Date.now() - 48 * 60 * 60 * 1000;
- const items = [];
- let entries;
- try {
- entries = fs.readdirSync(resolvedRoot, { withFileTypes: true });
- } catch (e) {
- return sendJson(res, 400, { error: '无法读取目录: ' + e.message });
- }
- for (const entry of entries) {
- if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === '图片生成工具' || SKIP_DIR_NAMES.has(entry.name)) continue;
- const shopDir = path.join(resolvedRoot, entry.name);
- const outputDir = path.join(shopDir, '_生成图片');
- if (!fs.existsSync(outputDir) || !fs.statSync(outputDir).isDirectory()) continue;
- let shopName = entry.name.replace(/^\d+_/, '').replace(/_\d+$/, '');
- const cfgPath = path.join(outputDir, 'prompt-config.json');
- if (fs.existsSync(cfgPath)) {
- try {
- const config = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
- shopName = config.shopName || shopName;
- } catch {}
- }
- const nestedHistoryRecords = loadCreationHistory(path.join(outputDir, '菜品图'))
- .map((record) => ({
- ...record,
- relativePath: path.normalize(path.join('菜品图', record.relativePath || record.fileName || '.')),
- }));
- const historyRecords = [...loadCreationHistory(outputDir), ...nestedHistoryRecords];
- const seenHistoryIds = new Set();
- const historyPaths = new Set();
- for (const record of historyRecords) {
- if (record.id && seenHistoryIds.has(record.id)) continue;
- if (record.id) seenHistoryIds.add(record.id);
- if (!record.remoteUrl || !record.fileName) continue;
- const generatedAt = record.generatedAt || record.modifiedAt;
- const generatedTimeMs = generatedAt ? new Date(generatedAt).getTime() : 0;
- if (!Number.isFinite(generatedTimeMs) || generatedTimeMs < retentionCutoff) continue;
- const kind = CREATION_KINDS.has(record.kind) ? record.kind : getCreationKind(record.relativePath || '.', record.fileName);
- if (!kind || kind === 'other') continue;
- const relativePath = path.normalize(record.relativePath || record.fileName);
- historyPaths.add(relativePath);
- items.push({
- folderName: entry.name,
- shopName: record.shopName || shopName,
- kind,
- name: record.name || record.dishName || path.basename(record.fileName, path.extname(record.fileName)),
- fileName: record.fileName,
- url: record.remoteUrl,
- remoteUrl: record.remoteUrl,
- localPath: path.join(outputDir, relativePath),
- source: 'remote',
- model: record.model,
- cost: record.cost,
- modifiedAt: generatedAt,
- modifiedTimeMs: generatedTimeMs,
- width: record.width,
- height: record.height,
- fileSizeBytes: record.fileSizeBytes,
- });
- }
- for (const relativeDir of ['.', '菜品图']) {
- const currentDir = path.join(outputDir, relativeDir);
- if (!fs.existsSync(currentDir) || !fs.statSync(currentDir).isDirectory()) continue;
- let files;
- try {
- files = fs.readdirSync(currentDir, { withFileTypes: true });
- } catch {
- continue;
- }
- for (const file of files) {
- if (!file.isFile()) continue;
- const ext = path.extname(file.name).toLowerCase();
- if (!IMAGE_EXT.has(ext)) continue;
- const kind = getCreationKind(relativeDir, file.name);
- if (kind === 'other') continue;
- const fullPath = path.join(currentDir, file.name);
- const relativePath = path.relative(outputDir, fullPath);
- if (historyPaths.has(path.normalize(relativePath))) continue;
- let stat;
- try {
- stat = fs.statSync(fullPath);
- } catch {
- continue;
- }
- if (stat.mtimeMs < retentionCutoff) continue;
- items.push({
- folderName: entry.name,
- shopName,
- kind,
- name: path.basename(file.name, ext),
- fileName: file.name,
- url: '/files?path=' + encodeURIComponent(fullPath),
- modifiedAt: stat.mtime.toISOString(),
- modifiedTimeMs: stat.mtimeMs,
- fileSizeBytes: stat.size,
- });
- }
- }
- }
- items.sort((a, b) => b.modifiedTimeMs - a.modifiedTimeMs);
- sendJson(res, 200, { root: resolvedRoot, total: items.length, items: items.slice(0, limit) });
- }
- function handleFiles(query, res) {
- const p = query.path;
- if (!p) {
- res.writeHead(400);
- return res.end('missing path');
- }
- const resolved = path.resolve(p);
- if (!isWorkspacePath(resolved)) {
- res.writeHead(403);
- return res.end('forbidden');
- }
- if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
- res.writeHead(404);
- return res.end('not found');
- }
- const ext = path.extname(resolved).toLowerCase();
- if (!IMAGE_EXT.has(ext)) {
- res.writeHead(403);
- return res.end('forbidden');
- }
- res.writeHead(200, { 'Content-Type': MIME_BY_EXT[ext], 'Cache-Control': 'no-cache' });
- fs.createReadStream(resolved).pipe(res);
- }
- async function handleGenerateBrand(body, res) {
- const { root, folderName, shopName, kind, prompt, size, aspectRatio, refDishFiles, addLogo, logoPosition, logoMode, model } = body;
- const outNameMap = { logo: 'logo', banner: 'banner', signage: '招牌头图', sticker: '贴纸' };
- if (!root || !folderName || !kind || !outNameMap[kind] || !prompt) {
- return sendJson(res, 400, { error: '参数不完整' });
- }
- const shopDir = safeShopDir(root, folderName);
- if (!shopDir) return sendJson(res, 403, { error: '店铺目录无效' });
- // logo/sticker are themselves brand-mark assets, adding the shop logo onto them is not applicable
- const shouldAddLogo = !!addLogo && kind !== 'logo';
- const { images, prompt: finalPrompt, warning, compositeOverlays } = buildImagesAndPrompt(shopDir, prompt, refDishFiles, {
- addLogo: shouldAddLogo,
- logoPosition,
- logoMode,
- });
- const job = createJob({
- kind,
- root,
- folderName,
- shopName,
- model,
- prompt: finalPrompt,
- size: size || '1K',
- aspectRatio: aspectRatio || undefined,
- images,
- outputDir: path.join(shopDir, '_生成图片'),
- outputBaseName: outNameMap[kind],
- warning,
- compositeOverlays,
- });
- sendJson(res, 200, { jobId: job.id });
- }
- async function handleGenerateDish(body, res) {
- const { root, folderName, shopName, dishFile, dishName, prompt, size, addLogo, logoPosition, logoMode, addSticker, stickerPosition, stickerMode, model } = body;
- if (!root || !folderName || !dishFile || !prompt) {
- return sendJson(res, 400, { error: '参数不完整' });
- }
- const shopDir = safeShopDir(root, folderName);
- if (!shopDir) return sendJson(res, 403, { error: '店铺目录无效' });
- const dishPath = path.resolve(shopDir, dishFile);
- if (!isWorkspacePath(dishPath) || !dishPath.startsWith(shopDir + path.sep)) {
- return sendJson(res, 403, { error: '菜品文件无效' });
- }
- let dishImage;
- try {
- dishImage = readAsDataUri(dishPath);
- } catch (e) {
- return sendJson(res, 400, { error: '读取菜品原图失败: ' + e.message });
- }
- const { images: overlayImages, prompt: finalPrompt, warning, compositeOverlays } = buildImagesAndPrompt(shopDir, prompt, [], {
- addLogo: !!addLogo,
- logoPosition,
- logoMode,
- addSticker: !!addSticker,
- stickerPosition,
- stickerMode,
- sourceImageFirst: true,
- });
- const job = createJob({
- kind: 'dish',
- root,
- folderName,
- shopName,
- dishName,
- model,
- prompt: finalPrompt,
- size: size || '1K',
- aspectRatio: '1:1',
- images: [dishImage, ...overlayImages],
- outputDir: path.join(shopDir, '_生成图片', '菜品图'),
- outputBaseName: sanitizeFileName(dishName),
- warning,
- compositeOverlays,
- });
- sendJson(res, 200, { jobId: job.id });
- }
- function handleJob(pathname, res) {
- const id = pathname.split('/').pop();
- const job = jobs.get(id);
- if (!job) return sendJson(res, 404, { error: 'job not found' });
- sendJson(res, 200, {
- id: job.id,
- kind: job.kind,
- dishName: job.dishName,
- state: job.state,
- progress: job.progress,
- cost: job.cost,
- resultUrl: job.resultUrl,
- width: job.width,
- height: job.height,
- fileSizeBytes: job.fileSizeBytes,
- error: job.error,
- warning: job.warning,
- });
- }
- function publicTask(job) {
- return {
- id: job.id,
- type: 'generation',
- status: job.state,
- root: job.root,
- folderName: job.folderName,
- shopName: job.shopName,
- dishName: job.dishName,
- name: job.dishName || job.kind,
- kind: job.kind,
- model: job.model,
- providerTaskId: job.taskId,
- progress: job.progress,
- cost: job.cost,
- resultUrl: job.resultUrl,
- remoteUrl: job.remoteUrl,
- width: job.width,
- height: job.height,
- fileSizeBytes: job.fileSizeBytes,
- error: job.error,
- warning: job.warning,
- createdAt: job.createdAt,
- startedAt: job.startedAt,
- finishedAt: job.finishedAt,
- updatedAt: job.updatedAt || job.createdAt,
- };
- }
- function handleTasks(query, res) {
- if (query.root && !isWorkspaceRoot(query.root)) {
- return sendJson(res, 403, { error: '仅允许访问当前输出根目录' });
- }
- const root = getWorkspaceRoot();
- const tasks = Array.from(jobs.values())
- .filter((job) => path.resolve(job.root) === root)
- .sort((a, b) => b.createdAt - a.createdAt)
- .map(publicTask);
- const summary = tasks.reduce((acc, task) => {
- acc[task.status] = (acc[task.status] || 0) + 1;
- return acc;
- }, { all: tasks.length });
- sendJson(res, 200, { root, summary, tasks });
- }
- async function handleSaveConfig(body, res) {
- const { root, folderName, shopName, prompts } = body;
- if (!root || !folderName) return sendJson(res, 400, { error: '参数不完整' });
- const shopDir = safeShopDir(root, folderName);
- if (!shopDir) return sendJson(res, 403, { error: '店铺目录无效' });
- const dir = path.join(shopDir, '_生成图片');
- fs.mkdirSync(dir, { recursive: true });
- const cfgPath = path.join(dir, 'prompt-config.json');
- let existing = {};
- if (fs.existsSync(cfgPath)) {
- try {
- existing = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
- } catch {
- // start fresh if corrupt
- }
- }
- const merged = {
- shopName: shopName !== undefined ? shopName : existing.shopName,
- prompts: { ...(existing.prompts || {}), ...(prompts || {}) },
- };
- fs.writeFileSync(cfgPath, JSON.stringify(merged, null, 2), 'utf8');
- sendJson(res, 200, { ok: true });
- }
- async function handleSavePosterCanvas(body, res) {
- const { root, folderName, kind, imageDataUrl } = body;
- const spec = POSTER_CANVAS_SPECS[kind];
- if (!root || !folderName || !spec || !imageDataUrl) {
- return sendJson(res, 400, { error: '参数不完整' });
- }
- if (typeof folderName !== 'string' || folderName === '.' || folderName === '..' || /[\\/]/.test(folderName)) {
- return sendJson(res, 400, { error: '店铺目录名无效' });
- }
- const dataUrlMatch = typeof imageDataUrl === 'string' && /^data:image\/png;base64,([A-Za-z0-9+/=]+)$/.exec(imageDataUrl);
- if (!dataUrlMatch) {
- return sendJson(res, 400, { error: '画板图必须为 PNG 格式' });
- }
- const base64 = dataUrlMatch[1];
- if (!base64 || base64.length > 10 * 1024 * 1024) {
- return sendJson(res, 400, { error: '画板图数据无效或过大' });
- }
- let imageBuffer;
- try {
- imageBuffer = Buffer.from(base64, 'base64');
- } catch {
- return sendJson(res, 400, { error: '画板图数据无法读取' });
- }
- const pngSignature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
- if (!imageBuffer.length || !imageBuffer.subarray(0, 8).equals(pngSignature)) {
- return sendJson(res, 400, { error: '画板图不是有效的 PNG 文件' });
- }
- const dimensions = getImageSize(imageBuffer);
- if (!dimensions || dimensions.width !== spec.width || dimensions.height !== spec.height) {
- return sendJson(res, 400, { error: `画板图尺寸必须为 ${spec.width}×${spec.height}` });
- }
- const resolvedRoot = path.resolve(root);
- if (!isWorkspaceRoot(resolvedRoot)) return sendJson(res, 403, { error: '仅允许访问当前输出根目录' });
- const shopDir = path.resolve(resolvedRoot, folderName);
- if (shopDir !== path.join(resolvedRoot, folderName) || !shopDir.startsWith(resolvedRoot + path.sep)) {
- return sendJson(res, 400, { error: '店铺目录无效' });
- }
- const dir = path.join(shopDir, '_生成图片');
- const savePath = path.join(dir, spec.fileName);
- try {
- fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(savePath, imageBuffer);
- } catch (e) {
- return sendJson(res, 500, { error: '保存画板图失败: ' + e.message });
- }
- sendJson(res, 200, { ok: true, fileName: spec.fileName, width: dimensions.width, height: dimensions.height, fileSizeBytes: imageBuffer.length });
- }
- function handleOpenFolder(body, res) {
- const { root, folderName } = body;
- if (!root || !folderName) return sendJson(res, 400, { error: '参数不完整' });
- const dir = path.join(root, folderName, '_生成图片');
- try {
- fs.mkdirSync(dir, { recursive: true });
- } catch (e) {
- return sendJson(res, 500, { error: '无法创建目录: ' + e.message });
- }
- // explorer.exe frequently exits with a non-zero code even when it opens the window fine,
- // so its callback result is ignored rather than treated as a failure.
- execFile('explorer', [dir], () => {});
- sendJson(res, 200, { ok: true });
- }
- // ---------- static frontend ----------
- const STATIC_MAP = {
- '/': ['index.html', 'text/html; charset=utf-8'],
- '/index.html': ['index.html', 'text/html; charset=utf-8'],
- '/app.js': ['app.js', 'application/javascript; charset=utf-8'],
- '/crawl.js': ['crawl.js', 'application/javascript; charset=utf-8'],
- '/gen.js': ['gen.js', 'application/javascript; charset=utf-8'],
- '/history.js': ['history.js', 'application/javascript; charset=utf-8'],
- '/tasks.js': ['tasks.js', 'application/javascript; charset=utf-8'],
- '/reports.js': ['reports.js', 'application/javascript; charset=utf-8'],
- '/vendor/echarts.min.js': ['vendor/echarts.min.js', 'application/javascript; charset=utf-8'],
- '/style.css': ['style.css', 'text/css; charset=utf-8'],
- };
- const STATIC_TYPES = {
- '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml',
- '.ico': 'image/x-icon', '.css': 'text/css', '.js': 'application/javascript',
- };
- function serveStatic(pathname, res) {
- const entry = STATIC_MAP[pathname];
- if (entry) {
- const full = path.join(__dirname, 'public', entry[0]);
- fs.readFile(full, (err, data) => {
- if (err) { res.writeHead(404); return res.end('Not found'); }
- res.writeHead(200, { 'Content-Type': entry[1], 'Cache-Control': 'no-cache' });
- res.end(data);
- });
- return;
- }
- if (pathname.startsWith('/assets/')) {
- const rel = pathname.replace('/assets/', '');
- if (rel.includes('..') || rel.includes('/')) { res.writeHead(403); return res.end('Forbidden'); }
- const full = path.join(__dirname, 'public', 'assets', rel);
- if (!fs.existsSync(full) || !fs.statSync(full).isFile()) { res.writeHead(404); return res.end('Not found'); }
- const ext = path.extname(full).toLowerCase();
- res.writeHead(200, { 'Content-Type': STATIC_TYPES[ext] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
- fs.createReadStream(full).pipe(res);
- return;
- }
- res.writeHead(404);
- res.end('Not found');
- }
- // ---------- server ----------
- const server = http.createServer((req, res) => {
- let parsedUrl;
- try {
- parsedUrl = new URL(req.url, `http://${req.headers.host}`);
- } catch {
- res.writeHead(400);
- return res.end('bad url');
- }
- const pathname = parsedUrl.pathname;
- const query = Object.fromEntries(parsedUrl.searchParams);
- const respond500 = (e) => sendJson(res, 500, { error: e.message || String(e) });
- if (req.method === 'GET' && pathname === '/api/default-root') {
- return sendJson(res, 200, { root: getWorkspaceRoot() });
- }
- if (req.method === 'GET' && pathname === '/healthz') {
- return sendJson(res, 200, { ok: true, workspace: getWorkspaceRoot() });
- }
- if (req.method === 'GET' && pathname === '/readyz') {
- return sendJson(res, 200, {
- ok: !!config.apiKey,
- workspaceReady: fs.existsSync(getWorkspaceRoot()),
- crawlReady: !!getKsid(),
- });
- }
- if (req.method === 'GET' && pathname === '/api/tasks') {
- try {
- return handleTasks(query, res);
- } catch (e) {
- return respond500(e);
- }
- }
- if (req.method === 'GET' && pathname === '/api/session') {
- return sendJson(res, 200, {
- cookieConfigured: !!session.cookie,
- ksidConfigured: !!getKsid(),
- });
- }
- if (req.method === 'POST' && pathname === '/api/session') {
- return readBody(req)
- .then((body) => {
- session.cookie = String((body && body.cookie) || '');
- saveSession();
- pushSystemLog('采集 Cookie 已更新', 'success');
- sendJson(res, 200, { ok: true });
- })
- .catch(respond500);
- }
- if (req.method === 'GET' && pathname === '/api/shops') {
- const encodedRoot = parsedUrl.searchParams.get('root');
- const root = encodedRoot ? Buffer.from(encodedRoot, 'base64url').toString('utf8') : '';
- if (root && !isWorkspaceRoot(root)) return sendJson(res, 403, { error: '仅允许访问当前输出根目录' });
- return handleShopsList(root, res);
- }
- if (req.method === 'POST' && pathname === '/api/shops/manual') {
- return readBody(req).then((body) => handleShopsManual(body, res)).catch(respond500);
- }
- if (req.method === 'POST' && pathname === '/api/crawl/start') {
- return readBody(req).then((body) => startCrawl(body, res)).catch(respond500);
- }
- if (req.method === 'POST' && pathname === '/api/crawl/stop') {
- return stopCrawl(res);
- }
- if (req.method === 'GET' && pathname === '/api/crawl/status') {
- return sendJson(res, 200, crawlState);
- }
- if (req.method === 'GET' && pathname === '/api/logs') {
- return sendJson(res, 200, { logs: getMergedLogs() });
- }
- if (req.method === 'POST' && pathname === '/api/logs/clear') {
- crawlState.log = [];
- systemLogs.length = 0;
- pushSystemLog('日志已清空', 'warn');
- return sendJson(res, 200, { ok: true });
- }
- if (req.method === 'GET' && pathname === '/api/models') {
- return sendJson(res, 200, { models: MODELS, default: config.model });
- }
- if (req.method === 'GET' && pathname === '/api/settings') {
- return sendJson(res, 200, {
- apiKey: config.apiKey ? config.apiKey.slice(0, 8) + '••••••••' : '',
- apiBase: config.apiBase,
- model: config.model,
- rootDir: getWorkspaceRoot(),
- pageSize: config.pageSize,
- delayMs: config.delayMs,
- cookieConfigured: !!session.cookie && !!getKsid(),
- port: config.port,
- chatModel: config.chatModel || '',
- chatApiBase: config.chatApiBase || config.apiBase,
- chatApiKey: config.chatApiKey ? config.chatApiKey.slice(0, 8) + '••••••••' : '',
- chatKeyFallback: !config.chatApiKey && !!config.apiKey,
- });
- }
- if (req.method === 'POST' && pathname === '/api/settings') {
- return readBody(req).then((body) => {
- const previousApiKey = config.apiKey;
- const previousCookie = session.cookie;
- if (body.apiKey && !body.apiKey.includes('••••')) config.apiKey = body.apiKey;
- if (body.model && MODEL_IDS.has(body.model)) config.model = body.model;
- if (body.rootDir) {
- const rootDir = path.resolve(String(body.rootDir).trim());
- if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
- return sendJson(res, 400, { error: '输出根目录不存在: ' + rootDir });
- }
- config.rootDir = rootDir;
- }
- if (body.pageSize !== undefined) {
- const pageSize = Number(body.pageSize);
- if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 200) {
- return sendJson(res, 400, { error: '每页条数必须为 1-200 的整数' });
- }
- config.pageSize = pageSize;
- }
- if (body.delayMs !== undefined) {
- const delayMs = Number(body.delayMs);
- if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > 60000) {
- return sendJson(res, 400, { error: '间隔必须为 0-60000 毫秒' });
- }
- config.delayMs = delayMs;
- }
- if (body.chatModel !== undefined) config.chatModel = String(body.chatModel).trim();
- if (body.chatApiBase !== undefined) config.chatApiBase = String(body.chatApiBase).trim();
- if (body.chatApiKey !== undefined && !String(body.chatApiKey).includes('••••')) config.chatApiKey = String(body.chatApiKey).trim();
- saveConfig();
- if (body.cookie !== undefined) {
- session.cookie = body.cookie;
- saveSession();
- }
- pushSystemLog(
- `系统设置已保存:模型=${config.model},根目录=${config.rootDir},每页=${config.pageSize},间隔=${config.delayMs}ms` +
- (previousApiKey !== config.apiKey ? ',API Key 已更新' : '') +
- (body.cookie !== undefined && previousCookie !== session.cookie ? ',Cookie 已更新' : ''),
- 'success'
- );
- sendJson(res, 200, { ok: true });
- }).catch(respond500);
- }
- if (req.method === 'GET' && pathname === '/api/scan') {
- try {
- return handleScan(query, res);
- } catch (e) {
- return respond500(e);
- }
- }
- if (req.method === 'GET' && pathname === '/api/creations') {
- try {
- return handleCreations(query, res);
- } catch (e) {
- return respond500(e);
- }
- }
- if (req.method === 'GET' && pathname === '/files') {
- try {
- return handleFiles(query, res);
- } catch (e) {
- return respond500(e);
- }
- }
- if (req.method === 'POST' && pathname === '/api/generate/brand') {
- return readBody(req).then((body) => handleGenerateBrand(body, res)).catch(respond500);
- }
- if (req.method === 'POST' && pathname === '/api/generate/dish') {
- return readBody(req).then((body) => handleGenerateDish(body, res)).catch(respond500);
- }
- if (req.method === 'GET' && pathname.startsWith('/api/job/')) {
- try {
- return handleJob(pathname, res);
- } catch (e) {
- return respond500(e);
- }
- }
- if (req.method === 'POST' && pathname === '/api/save-config') {
- return readBody(req).then((body) => handleSaveConfig(body, res)).catch(respond500);
- }
- if (req.method === 'POST' && pathname === '/api/save-poster-canvas') {
- return readBody(req).then((body) => handleSavePosterCanvas(body, res)).catch(respond500);
- }
- if (req.method === 'POST' && pathname === '/api/open-folder') {
- return readBody(req).then((body) => {
- if (body.root && !isWorkspaceRoot(body.root)) return sendJson(res, 403, { error: '仅允许访问当前输出根目录' });
- const dir = body.dir || path.join(body.root || getWorkspaceRoot(), body.folderName || '', '_生成图片');
- const fallbackDir = body.dir ? null : path.join(body.root || getWorkspaceRoot(), body.folderName || '');
- const targetDir = fs.existsSync(dir) ? dir : (fallbackDir && fs.existsSync(fallbackDir) ? fallbackDir : null);
- if (!targetDir || !isWorkspacePath(targetDir)) return sendJson(res, 400, { error: '目录不存在或不在输出根目录内: ' + dir });
- const command = process.platform === 'win32' ? 'explorer' : process.platform === 'darwin' ? 'open' : 'xdg-open';
- execFile(command, [targetDir], () => {});
- sendJson(res, 200, { ok: true, opened: targetDir });
- }).catch(respond500);
- }
- // ---------- 数据报表(淘宝闪购经营数据中台) ----------
- if (pathname === '/api/reports/status') {
- return Promise.all([naposService.naposStatus()])
- .then(([napos]) => sendJson(res, 200, { napos, entities: naposService.store.listEntities() }))
- .catch(respond500);
- }
- // ---------- 智能问数(NL2Query,对话模型驱动) ----------
- const DEFAULT_CHAT_MODEL = 'deepseek-v4.1-flash';
- function chatCfg() {
- return {
- chatApiBase: config.chatApiBase || config.apiBase,
- chatApiKey: config.chatApiKey || config.apiKey,
- chatModel: config.chatModel || DEFAULT_CHAT_MODEL,
- };
- }
- if (req.method === 'POST' && pathname === '/api/reports/ask') {
- return readBody(req).then(async (body) => {
- const entity = body.entity || (naposService.store.listEntities()[0] || {}).key;
- if (!entity) { const e = new Error('暂无数据主体,请先完成一次同步'); e.code = 'ASK_NO_ENTITY'; throw e; }
- const result = await nlQuery.ask({ q: body.q, entity, cfg: chatCfg(), svc: naposService, history: Array.isArray(body.history) ? body.history : undefined });
- sendJson(res, 200, result);
- }).catch((e) => sendJson(res, e.code === 'ASK_NO_MODEL' || e.code === 'ASK_EMPTY' || e.code === 'ASK_NO_ENTITY' ? 400 : 502, { error: e.message, code: e.code }));
- }
- if (req.method === 'POST' && pathname === '/api/chat/test') {
- return readBody(req).then(async (body) => {
- const cfg = {
- chatApiBase: body.chatApiBase || config.chatApiBase || config.apiBase,
- chatApiKey: (body.chatApiKey && !String(body.chatApiKey).includes('••••')) ? body.chatApiKey : (config.chatApiKey || config.apiKey),
- chatModel: body.chatModel || config.chatModel || DEFAULT_CHAT_MODEL,
- };
- const reply = await nlQuery.ping(cfg);
- sendJson(res, 200, { ok: true, reply });
- }).catch((e) => sendJson(res, 502, { error: e.message }));
- }
- // 生图 API 连通性测试:GET /v1/models(轻量、不产生生图费用)
- if (req.method === 'POST' && pathname === '/api/image/test') {
- return new Promise((resolve) => {
- let base;
- try { base = new URL(config.apiBase); } catch { return sendJson(res, 400, { error: 'API 地址不合法: ' + config.apiBase }); }
- const options = {
- hostname: base.hostname, port: base.port || 443, path: '/v1/models', method: 'GET',
- headers: { Authorization: `Bearer ${config.apiKey}` }, timeout: 15000,
- };
- const up = https.request(options, (upRes) => {
- const chunks = [];
- upRes.on('data', (c) => chunks.push(c));
- upRes.on('end', () => {
- let json = null;
- try { json = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { /* 保留空 */ }
- const models = json && Array.isArray(json.data) ? json.data.map((m) => (m && m.id) || '').filter(Boolean) : null;
- sendJson(res, 200, { statusCode: upRes.statusCode, models, modelFound: !!(models && models.includes(config.model)), model: config.model });
- });
- });
- up.on('error', (e) => sendJson(res, 200, { statusCode: 0, error: e.message || String(e) }));
- up.on('timeout', () => up.destroy(new Error('请求超时')));
- up.end();
- });
- }
- if (req.method === 'GET' && pathname === '/api/reports/report-html') {
- try {
- const entity = query.entity || (naposService.store.listEntities()[0] || {}).key;
- if (!entity) {
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- return res.end('<meta charset="utf-8"><body style="font-family:sans-serif;padding:40px">暂无数据主体,请先在「数据报表」完成一次同步。</body>');
- }
- const range = nlQuery.lakeDateRange(entity, naposService);
- const from = /^\d{8}$/.test(query.from || '') ? query.from : range.from;
- const to = /^\d{8}$/.test(query.to || '') ? query.to : range.to;
- const html = reportHtml.buildReportHtml({ entity, from, to });
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- return res.end(html);
- } catch (e) {
- return respond500(e);
- }
- }
- if (req.method === 'GET' && pathname === '/api/reports/entities') {
- return sendJson(res, 200, { entities: naposService.store.listEntities() });
- }
- if (req.method === 'GET' && pathname === '/api/reports/tree') {
- return naposService.fetchTree({ refresh: query.refresh === '1' })
- .then((tree) => sendJson(res, 200, {
- merchant: tree.merchant, chains: tree.chains,
- shops: tree.shops.map((s) => ({ shopId: String(s.shopId), shopName: s.shopName, chainId: s.chainId ? String(s.chainId) : '', chainName: s.chainName || '', busyLevel: s.busyLevel || null })),
- entity: tree.entity,
- }))
- .catch((e) => sendJson(res, 502, { error: e.message || String(e), code: e.code }));
- }
- if (req.method === 'GET' && pathname === '/api/reports/columns') {
- return sendJson(res, 200, { columns: naposService.REPORT_COLUMNS });
- }
- if (req.method === 'POST' && pathname === '/api/reports/sync') {
- return readBody(req).then((body) => {
- naposService.runSync({
- from: body.from, to: body.to,
- scope: body.scope || 'all',
- chainId: body.chainId || '',
- shopIds: Array.isArray(body.shopIds) ? body.shopIds : undefined,
- }).catch(() => {});
- return sendJson(res, 200, { ok: true, ...naposService.syncSnapshot() });
- }).catch(respond500);
- }
- if (req.method === 'GET' && pathname === '/api/reports/sync/status') {
- return sendJson(res, 200, naposService.syncSnapshot());
- }
- if (req.method === 'POST' && pathname === '/api/reports/sync/cancel') {
- return sendJson(res, 200, naposService.requestSyncCancel());
- }
- if (req.method === 'GET' && pathname === '/api/reports/daily') {
- try {
- return sendJson(res, 200, naposService.queryReport({
- entity: query.entity, from: query.from, to: query.to,
- shopId: query.shopId,
- shops: query.shops ? query.shops.split(',').filter(Boolean) : undefined,
- scope: query.scope || 'shop', q: query.q,
- }));
- } catch (e) {
- return respond500(e);
- }
- }
- if (req.method === 'GET' && pathname === '/api/reports/aggregate') {
- try {
- return sendJson(res, 200, naposService.aggregateReport({
- entity: query.entity, from: query.from, to: query.to,
- group: query.group || 'shop',
- shops: query.shops ? query.shops.split(',').filter(Boolean) : undefined,
- }));
- } catch (e) {
- return respond500(e);
- }
- }
- if (req.method === 'GET' && pathname === '/api/reports/export') {
- try {
- const group = query.group === 'date' ? 'date' : (query.group === 'shop' ? 'shop' : null);
- let rows;
- if (group) {
- const agg = naposService.aggregateReport({ entity: query.entity, from: query.from, to: query.to, group });
- rows = agg.rows;
- } else {
- const daily = naposService.queryReport({
- entity: query.entity, from: query.from, to: query.to,
- shopId: query.shopId,
- shops: query.shops ? query.shops.split(',').filter(Boolean) : undefined,
- scope: query.scope || 'shop', q: query.q,
- });
- rows = daily.rows;
- }
- const columns = naposService.REPORT_COLUMNS;
- const csv = naposService.rowsToCsv(columns, rows);
- res.writeHead(200, {
- 'Content-Type': 'text/csv; charset=utf-8',
- 'Content-Disposition': `attachment; filename="report-${query.entity || 'all'}-${query.from || ''}-${query.to || ''}.csv"`,
- });
- return res.end(csv);
- } catch (e) {
- return respond500(e);
- }
- }
- if (req.method === 'GET' && pathname === '/api/reports/syncs') {
- const key = naposService.store.sanitizeKey(query.entity);
- return sendJson(res, 200, { runs: naposService.store.loadSyncLogs(key) });
- }
- if (req.method === 'DELETE' && pathname === '/api/reports/data') {
- if (!query.entity) return sendJson(res, 400, { error: '缺少 entity 参数' });
- try {
- naposService.store.deleteEntityData(query.entity);
- pushSystemLog(`数据报表:已清除主体 ${query.entity} 的本地数据`, 'warn');
- return sendJson(res, 200, { ok: true });
- } catch (e) {
- return respond500(e);
- }
- }
- return serveStatic(pathname, res);
- });
- loadPersistedJobs();
- // PORT 环境变量可临时覆盖 config.json 的端口(多实例/调试用,不落盘)
- const LISTEN_PORT = Number(process.env.PORT || config.port) || config.port;
- function runCmd(cmd, args, timeoutMs = 8000) {
- return new Promise((resolve) => {
- execFile(cmd, args, { timeout: timeoutMs }, (err, stdout) => resolve(err ? '' : String(stdout || '')));
- });
- }
- /** 找出正在监听指定端口的 PID 列表 */
- async function pidsListeningOnPort(port) {
- if (process.platform === 'win32') {
- const out = await runCmd('powershell', ['-NoProfile', '-Command',
- `(Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique) -join ','`]);
- return out.trim().split(',').map((s) => parseInt(s, 10)).filter((n) => Number.isInteger(n) && n > 0);
- }
- const out = await runCmd('lsof', ['-ti', `tcp:${port}`, '-s', 'TCP:LISTEN']);
- return out.trim().split('\n').map((s) => parseInt(s, 10)).filter((n) => Number.isInteger(n) && n > 0);
- }
- /** 校验该 PID 是否是「本项目的 server.js」(命令行 + 工作目录双重确认,避免误杀无关进程) */
- async function isOurServerProcess(pid) {
- try {
- if (process.platform === 'win32') {
- const out = await runCmd('powershell', ['-NoProfile', '-Command',
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`]);
- return /server\.js/i.test(out) && !!out;
- }
- const cmd = await runCmd('ps', ['-p', String(pid), '-o', 'command=']);
- if (!/server\.js/i.test(cmd)) return false;
- const cwdOut = await runCmd('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn']);
- const cwdLine = cwdOut.split('\n').find((l) => l.startsWith('n')) || '';
- const cwdPath = cwdLine.slice(1);
- return !cwdPath || cwdPath === __dirname || cwdPath.startsWith(__dirname + path.sep) || cmd.includes(__dirname);
- } catch {
- return false;
- }
- }
- /** 端口被占时,自动退出本项目遗留的旧实例并等待端口释放 */
- async function reclaimPortFromStaleInstance(port) {
- const pids = await pidsListeningOnPort(port);
- let killedAny = false;
- for (const pid of pids) {
- if (pid === process.pid) continue;
- if (!(await isOurServerProcess(pid))) continue;
- try {
- process.kill(pid, 'SIGTERM');
- killedAny = true;
- console.log(`已自动退出旧实例(PID ${pid}),正在重新启动...`);
- } catch { /* 无权限等,忽略 */ }
- }
- if (!killedAny) return false;
- for (let i = 0; i < 20; i++) {
- await new Promise((r) => setTimeout(r, 200));
- if (!(await pidsListeningOnPort(port)).length) return true;
- }
- // SIGTERM 没退干净 → 强杀兜底
- for (const pid of await pidsListeningOnPort(port)) {
- try { process.kill(pid, 'SIGKILL'); } catch { /* ignore */ }
- }
- await new Promise((r) => setTimeout(r, 400));
- return !(await pidsListeningOnPort(port)).length;
- }
- function printPortBusyHelp() {
- console.error(`启动失败:端口 ${LISTEN_PORT} 已被其他程序占用(非本工具实例),无法自动处理。`);
- console.error('可任选其一:');
- console.error(` · 退出占用该端口的程序:macOS/Linux 执行 lsof -ti tcp:${LISTEN_PORT} 查 PID,Windows 执行 netstat -ano | findstr :${LISTEN_PORT}`);
- console.error(` · 或修改 config.json 里的 port(或以 PORT=xxxx 环境变量临时指定)后再启动。`);
- }
- let listenAttempts = 0;
- const MAX_LISTEN_ATTEMPTS = 3;
- server.on('error', async (err) => {
- if (err && err.code === 'EADDRINUSE' && listenAttempts < MAX_LISTEN_ATTEMPTS) {
- listenAttempts += 1;
- console.log(`端口 ${LISTEN_PORT} 被占用,正在检测是否为本工具的旧实例...`);
- let reclaimed = false;
- try {
- reclaimed = await reclaimPortFromStaleInstance(LISTEN_PORT);
- } catch { /* 检测失败按未回收处理 */ }
- if (reclaimed) {
- server.listen(LISTEN_PORT, HOST);
- return;
- }
- printPortBusyHelp();
- process.exit(1);
- }
- if (err && err.code === 'EADDRINUSE') {
- printPortBusyHelp();
- process.exit(1);
- }
- throw err;
- });
- server.listen(LISTEN_PORT, HOST, () => {
- const url = `http://${HOST === '0.0.0.0' ? 'localhost' : HOST}:${LISTEN_PORT}`;
- pushSystemLog(`服务已启动:${url}`, 'success');
- console.log(`智慧运营中台已启动: ${url}`);
- // "start" is a cmd.exe builtin (not a standalone executable), so it must be run via cmd /c;
- // the empty "" argument is the window-title placeholder start expects before the URL.
- execFile('cmd', ['/c', 'start', '', url], () => {});
- });
|