server.js 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. 'use strict';
  2. const http = require('http');
  3. const https = require('https');
  4. const fs = require('fs');
  5. const path = require('path');
  6. const crypto = require('crypto');
  7. const { execFile } = require('child_process');
  8. const { URL } = require('url');
  9. const jpeg = require('jpeg-js');
  10. const { PNG } = require('pngjs');
  11. const { getImageSize } = require('./imageMeta.js');
  12. let config = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json'), 'utf8'));
  13. function saveConfig() {
  14. const temp = path.join(__dirname, 'config.json.tmp');
  15. fs.writeFileSync(temp, JSON.stringify(config, null, 2), 'utf8');
  16. fs.renameSync(temp, path.join(__dirname, 'config.json'));
  17. }
  18. const WORKSPACE_ROOT = path.join(path.dirname(__dirname), 'workspace');
  19. function getWorkspaceRoot() {
  20. const configuredRoot = String(config.rootDir || WORKSPACE_ROOT).trim() || WORKSPACE_ROOT;
  21. return path.resolve(configuredRoot);
  22. }
  23. fs.mkdirSync(getWorkspaceRoot(), { recursive: true });
  24. const SESSION_PATH = path.join(__dirname, 'session.json');
  25. const MANUAL_SHOPS_PATH = path.join(__dirname, 'manual-shops.json');
  26. const MODELS = [
  27. { id: 'gpt-image-2', label: 'GPT Image 2(默认)' },
  28. { id: 'gpt-image-2-guan', label: 'GPT Image 2 官转' },
  29. { id: 'doubao-seedream-5-0-pro-260628', label: '豆包 Seedream 5.0 Pro' },
  30. { id: 'doubao-seedream-5-0-260128', label: '即梦 5.0(Seedream 5.0)' },
  31. { id: 'doubao-seedream-4-5-251128', label: '即梦 4.5(Seedream 4.5)' },
  32. { id: 'wan2.6-image', label: '通义万相 wan2.6-image' },
  33. ];
  34. const MODEL_IDS = new Set(MODELS.map((m) => m.id));
  35. // These seedream variants don't support the '1K' tier the UI's size dropdown offers by
  36. // default (doubao-seedream-4-5-251128: 2K/4K only; doubao-seedream-5-0-260128: 2K/3K only) -
  37. // map it up to '2K' rather than sending an invalid enum value.
  38. const NO_1K_SUPPORT = new Set(['doubao-seedream-4-5-251128', 'doubao-seedream-5-0-260128']);
  39. const IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
  40. const MIME_BY_EXT = {
  41. '.jpg': 'image/jpeg',
  42. '.jpeg': 'image/jpeg',
  43. '.png': 'image/png',
  44. '.webp': 'image/webp',
  45. '.gif': 'image/gif',
  46. };
  47. const POSTER_CANVAS_SPECS = {
  48. banner: { fileName: '店内海报_1138x292.png', width: 1138, height: 292 },
  49. signage: { fileName: '招牌头图_750x288.png', width: 750, height: 288 },
  50. };
  51. 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';
  52. const SKIP_DIR_NAMES = new Set(['膳绘']);
  53. // ---------- small utils ----------
  54. function sendJson(res, statusCode, obj) {
  55. const data = JSON.stringify(obj);
  56. res.writeHead(statusCode, { 'Content-Type': 'application/json; charset=utf-8' });
  57. res.end(data);
  58. }
  59. function sleep(ms) {
  60. return new Promise((resolve) => setTimeout(resolve, ms));
  61. }
  62. function sanitizeFileName(name) {
  63. return String(name).replace(/[\\/:*?"<>|]/g, '_').trim() || 'file';
  64. }
  65. function readBody(req) {
  66. return new Promise((resolve, reject) => {
  67. const chunks = [];
  68. req.on('data', (c) => chunks.push(c));
  69. req.on('end', () => {
  70. if (!chunks.length) return resolve({});
  71. try {
  72. resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
  73. } catch (e) {
  74. reject(e);
  75. }
  76. });
  77. req.on('error', reject);
  78. });
  79. }
  80. // ============================================================
  81. // CRAWLER MODULE — 闪购菜品图爬取
  82. // ============================================================
  83. let session = { cookie: '' };
  84. function extractCookieValue(cookie, name) {
  85. const match = String(cookie || '').match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
  86. if (!match) return '';
  87. try { return decodeURIComponent(match[1]); } catch { return match[1]; }
  88. }
  89. function getKsid() { return extractCookieValue(session.cookie, 'ksid'); }
  90. function loadSession() {
  91. try {
  92. const saved = JSON.parse(fs.readFileSync(SESSION_PATH, 'utf8'));
  93. session.cookie = String(saved.cookie || '');
  94. } catch { /* no saved session */ }
  95. }
  96. function saveSession() {
  97. fs.writeFileSync(SESSION_PATH, JSON.stringify(session, null, 2), 'utf8');
  98. }
  99. loadSession();
  100. function invokeApi(service, method, requestParams, extraMetas) {
  101. return new Promise((resolve, reject) => {
  102. const body = {
  103. id: crypto.randomBytes(16).toString('hex').toUpperCase() + '|' + Date.now(),
  104. method, service,
  105. params: { request: requestParams || {} },
  106. metas: Object.assign({ appName: 'melody', appVersion: '4.4.0', ksid: getKsid() }, extraMetas || {}),
  107. ncp: '2.0.0', adapter: 'ncp',
  108. extendConfig: { docMode: 'master,,' },
  109. };
  110. const data = JSON.stringify(body);
  111. const options = {
  112. hostname: 'app-api.shop.ele.me', port: 443,
  113. path: `/nevermore.goods/invoke?method=${encodeURIComponent(service + '.' + method)}`,
  114. method: 'POST',
  115. headers: {
  116. 'Content-Type': 'application/json; charset=UTF-8', Accept: 'application/json',
  117. Origin: 'https://napos-goods-pc.faas.ele.me', Referer: 'https://napos-goods-pc.faas.ele.me/',
  118. Cookie: session.cookie || '', 'User-Agent': UA,
  119. 'Content-Length': Buffer.byteLength(data),
  120. },
  121. timeout: config.requestTimeoutMs,
  122. };
  123. const req = https.request(options, (res) => {
  124. const chunks = [];
  125. res.on('data', (c) => chunks.push(c));
  126. res.on('end', () => {
  127. const raw = Buffer.concat(chunks).toString('utf8');
  128. let json = null;
  129. try { json = JSON.parse(raw); } catch { /* keep raw */ }
  130. resolve({ statusCode: res.statusCode, json, raw });
  131. });
  132. });
  133. req.on('error', reject);
  134. req.on('timeout', () => req.destroy(new Error('请求超时')));
  135. req.write(data);
  136. req.end();
  137. });
  138. }
  139. function isAuthError(resp) {
  140. if (resp.statusCode === 401 || resp.statusCode === 403) return true;
  141. const j = resp.json;
  142. if (!j) return false;
  143. if (j.result !== undefined) return false;
  144. return /未登录|请登录|login|unauthorized|token.*expired|session.*expired/i.test(JSON.stringify(j));
  145. }
  146. function downloadImage(urlStr, redirectsLeft) {
  147. if (redirectsLeft === undefined) redirectsLeft = 5;
  148. return new Promise((resolve, reject) => {
  149. let u;
  150. try { u = new URL(urlStr); } catch (e) { return reject(new Error('无效的图片地址: ' + urlStr)); }
  151. const mod = u.protocol === 'http:' ? http : https;
  152. mod.get(u, { headers: { Referer: 'https://melody.shop.ele.me/', 'User-Agent': UA } }, (res) => {
  153. if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location && redirectsLeft > 0) {
  154. res.resume();
  155. return resolve(downloadImage(res.headers.location, redirectsLeft - 1));
  156. }
  157. if (res.statusCode !== 200) { res.resume(); return reject(new Error('下载图片失败 HTTP ' + res.statusCode)); }
  158. const chunks = [];
  159. res.on('data', (c) => chunks.push(c));
  160. res.on('end', () => resolve(Buffer.concat(chunks)));
  161. }).on('error', reject);
  162. });
  163. }
  164. let shopList = [];
  165. function loadManualShops() {
  166. try {
  167. const data = JSON.parse(fs.readFileSync(MANUAL_SHOPS_PATH, 'utf8'));
  168. if (data.version !== 1 || !Array.isArray(data.shops)) throw new Error('清单格式无效');
  169. const shopsById = new Map();
  170. for (const shop of data.shops) {
  171. if (!shop || !Number.isInteger(shop.shopId) || shop.shopId <= 0) continue;
  172. shopsById.set(shop.shopId, { shopId: shop.shopId, shopName: String(shop.shopName || shop.shopId), source: 'manual' });
  173. }
  174. shopList = Array.from(shopsById.values());
  175. } catch (e) {
  176. if (e.code !== 'ENOENT') console.warn(`读取手动店铺清单失败: ${e.message || e}`);
  177. }
  178. }
  179. function saveManualShops(shops) {
  180. const temp = `${MANUAL_SHOPS_PATH}.${process.pid}.tmp`;
  181. fs.writeFileSync(temp, JSON.stringify({ version: 1, shops }, null, 2), 'utf8');
  182. fs.renameSync(temp, MANUAL_SHOPS_PATH);
  183. }
  184. function mergeShops(newOnes) {
  185. const shopsById = new Map(shopList.map((shop) => [shop.shopId, shop]));
  186. for (const shop of newOnes) shopsById.set(shop.shopId, shop);
  187. return Array.from(shopsById.values());
  188. }
  189. loadManualShops();
  190. function completionStatePath(root) { return path.join(root, '_膳绘_店铺状态.json'); }
  191. function readCompletionState(root) {
  192. try {
  193. const data = JSON.parse(fs.readFileSync(completionStatePath(root), 'utf8'));
  194. return data.version === 1 && data.shops && typeof data.shops === 'object' ? data.shops : {};
  195. } catch { return {}; }
  196. }
  197. function writeCompletionState(root, shops) {
  198. const target = completionStatePath(root);
  199. const temp = `${target}.${process.pid}.tmp`;
  200. fs.writeFileSync(temp, JSON.stringify({ version: 1, shops }, null, 2), 'utf8');
  201. fs.renameSync(temp, target);
  202. }
  203. function markShopCompleted(root, shopEntry) {
  204. const shops = readCompletionState(root);
  205. shops[String(shopEntry.shopId)] = {
  206. shopId: shopEntry.shopId, shopName: shopEntry.shopName, folderName: shopEntry.folderName,
  207. completedAt: new Date().toISOString(), downloaded: shopEntry.downloaded,
  208. skipped: shopEntry.skipped, total: shopEntry.total,
  209. };
  210. writeCompletionState(root, shops);
  211. }
  212. function handleShopsManual(body, res) {
  213. const lines = String((body && body.text) || '').split(/\r?\n/);
  214. const parsed = [];
  215. for (const line of lines) {
  216. const t = line.trim();
  217. if (!t) continue;
  218. const parts = t.split(/[\s,,]+/).filter(Boolean);
  219. const idPart = parts.find((p) => /^\d+$/.test(p));
  220. if (!idPart) continue;
  221. const shopId = Number(idPart);
  222. const shopName = parts.filter((p) => p !== idPart).join(' ') || String(shopId);
  223. parsed.push({ shopId, shopName, source: 'manual' });
  224. }
  225. const previousShops = shopList;
  226. const mergedShops = mergeShops(parsed);
  227. try { saveManualShops(mergedShops); shopList = mergedShops; }
  228. catch (e) { shopList = previousShops; throw e; }
  229. sendJson(res, 200, { shops: shopList, addedCount: parsed.length });
  230. }
  231. function handleShopsList(root, res) {
  232. const completed = root && fs.existsSync(root) ? readCompletionState(root) : {};
  233. sendJson(res, 200, {
  234. shops: shopList.map((shop) => ({ ...shop, completed: completed[String(shop.shopId)] || null })),
  235. });
  236. }
  237. function listRootDirs(root) {
  238. return fs.readdirSync(root, { withFileTypes: true })
  239. .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !SKIP_DIR_NAMES.has(e.name))
  240. .map((e) => e.name);
  241. }
  242. function resolveShopDir(root, shopId, shopName) {
  243. const dirs = listRootDirs(root);
  244. const suffix = '_' + String(shopId);
  245. const match = dirs.find((d) => d.endsWith(suffix));
  246. if (match) return { dir: path.join(root, match), folderName: match, reused: true };
  247. let maxSeq = 0;
  248. for (const d of dirs) {
  249. const mm = /^(\d+)_/.exec(d);
  250. if (mm) maxSeq = Math.max(maxSeq, parseInt(mm[1], 10));
  251. }
  252. const seq = String(maxSeq + 1).padStart(3, '0');
  253. const folderName = `${seq}_${sanitizeFileName(shopName)}_${shopId}`;
  254. const dir = path.join(root, folderName);
  255. fs.mkdirSync(dir, { recursive: true });
  256. return { dir, folderName, reused: false };
  257. }
  258. let crawlState = { status: 'idle', startedAt: null, finishedAt: null, shops: [], log: [] };
  259. let cancelFlag = false;
  260. const systemLogs = [];
  261. let logSeq = 0;
  262. function detectLogLevel(message) {
  263. if (/失败|错误|异常|过期|error|鉴权/i.test(message)) return 'error';
  264. if (/停止|跳过|警告|warn/i.test(message)) return 'warn';
  265. if (/完成|成功|已保存|已启动|done/i.test(message)) return 'success';
  266. return 'info';
  267. }
  268. function createLogEntry(message, source = 'task', level = 'info') {
  269. const now = new Date();
  270. return {
  271. seq: ++logSeq,
  272. id: `${source}-${logSeq}`,
  273. source,
  274. level,
  275. time: now.toTimeString().slice(0, 8),
  276. timestamp: now.getTime(),
  277. message: String(message),
  278. };
  279. }
  280. function pushLog(msg) {
  281. const entry = createLogEntry(msg, 'task', detectLogLevel(msg));
  282. crawlState.log.push(entry);
  283. if (crawlState.log.length > 500) crawlState.log.shift();
  284. }
  285. function pushSystemLog(msg, level = 'info') {
  286. systemLogs.push(createLogEntry(msg, 'system', level));
  287. if (systemLogs.length > 500) systemLogs.shift();
  288. }
  289. function getMergedLogs() {
  290. return [...crawlState.log, ...systemLogs]
  291. .sort((a, b) => b.seq - a.seq)
  292. .slice(0, 500);
  293. }
  294. async function startCrawl(body, res) {
  295. if (crawlState.status === 'running') return sendJson(res, 409, { error: '已有抓取任务在进行中' });
  296. if (!session.cookie || !getKsid()) return sendJson(res, 400, { error: '请先填写包含 ksid 的 Cookie' });
  297. const root = String((body && body.root) || getWorkspaceRoot()).trim();
  298. if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
  299. return sendJson(res, 400, { error: '输出根目录不存在: ' + root });
  300. }
  301. const shopIds = Array.isArray(body && body.shopIds) ? body.shopIds.map(Number) : [];
  302. const selectedShops = shopIds.map((id) => shopList.find((s) => s.shopId === id)).filter(Boolean);
  303. if (!selectedShops.length) return sendJson(res, 400, { error: '没有可抓取的店铺,请先填写手动店铺清单并勾选' });
  304. const forceFullCrawl = Boolean(body && body.forceFullCrawl);
  305. const completed = readCompletionState(root);
  306. const skippedCompleted = forceFullCrawl ? [] : selectedShops.filter((s) => completed[String(s.shopId)]);
  307. const shops = forceFullCrawl ? selectedShops : selectedShops.filter((s) => !completed[String(s.shopId)]);
  308. const pageSize = Number(body && body.pageSize) || config.pageSize;
  309. const delayMs = Number(body && body.delayMs) || config.delayMs;
  310. cancelFlag = false;
  311. crawlState = {
  312. status: shops.length ? 'running' : 'done', startedAt: Date.now(),
  313. finishedAt: shops.length ? null : Date.now(), forceFullCrawl,
  314. shops: [
  315. ...skippedCompleted.map((s) => ({
  316. shopId: s.shopId, shopName: s.shopName, folderName: completed[String(s.shopId)].folderName || null,
  317. state: 'skipped_completed', total: completed[String(s.shopId)].total || 0,
  318. downloaded: 0, skipped: 0, failed: 0, error: null,
  319. })),
  320. ...shops.map((s) => ({
  321. shopId: s.shopId, shopName: s.shopName, folderName: null, state: 'pending',
  322. total: 0, downloaded: 0, skipped: 0, failed: 0, error: null,
  323. })),
  324. ],
  325. log: [],
  326. };
  327. pushLog(`开始抓取,实际抓取 ${shops.length} 家${skippedCompleted.length ? `,历史完成跳过 ${skippedCompleted.length} 家` : ''},root=${root}`);
  328. sendJson(res, 200, { ok: true, crawlCount: shops.length, skippedCompletedCount: skippedCompleted.length });
  329. if (!shops.length) return pushLog('所选店铺均已完成;勾选"强制全量抓取"可重新下载');
  330. runCrawlLoop(root, pageSize, delayMs, forceFullCrawl).catch((e) => {
  331. crawlState.status = 'error';
  332. crawlState.finishedAt = Date.now();
  333. pushLog('抓取流程异常终止: ' + (e.message || e));
  334. });
  335. }
  336. async function runCrawlLoop(root, pageSize, delayMs, forceFullCrawl) {
  337. for (const shopEntry of crawlState.shops) {
  338. if (shopEntry.state === 'skipped_completed') continue;
  339. if (cancelFlag) {
  340. crawlState.status = 'stopped';
  341. crawlState.finishedAt = Date.now();
  342. pushLog('已停止');
  343. return;
  344. }
  345. shopEntry.state = 'running';
  346. pushLog(`[${shopEntry.shopName}] 开始`);
  347. let dirInfo;
  348. try { dirInfo = resolveShopDir(root, shopEntry.shopId, shopEntry.shopName); }
  349. catch (e) {
  350. shopEntry.state = 'failed';
  351. shopEntry.error = '创建目录失败: ' + (e.message || e);
  352. pushLog(`[${shopEntry.shopName}] 创建目录失败: ${e.message || e}`);
  353. continue;
  354. }
  355. shopEntry.folderName = dirInfo.folderName;
  356. pushLog(`[${shopEntry.shopName}] ${dirInfo.reused ? '复用已有目录' : '新建目录'} ${dirInfo.folderName}`);
  357. const allItems = [];
  358. const seen = new Set();
  359. let nextId;
  360. let page = 0;
  361. const MAX_PAGES = 200;
  362. let authFailed = false;
  363. while (page < MAX_PAGES) {
  364. if (cancelFlag) break;
  365. page++;
  366. const requestParams = {
  367. shopId: shopEntry.shopId, pageSize, queryType: 'SHOP',
  368. searchKey: '', searchType: ['ITEM_NAME'],
  369. };
  370. if (nextId) requestParams.nextId = nextId;
  371. let resp;
  372. try { resp = await invokeApi('ItemPhotoProcessService', 'getItemPhotoGallery', requestParams, { shopId: shopEntry.shopId }); }
  373. catch (e) {
  374. shopEntry.error = '请求失败: ' + (e.message || e);
  375. pushLog(`[${shopEntry.shopName}] 请求失败: ${e.message || e}`);
  376. break;
  377. }
  378. if (isAuthError(resp)) {
  379. authFailed = true;
  380. shopEntry.error = '会话可能已过期,请重新登录后更新 Cookie';
  381. pushLog(`[${shopEntry.shopName}] 鉴权失败(ksid/Cookie 可能已过期)`);
  382. break;
  383. }
  384. const items = (resp.json && resp.json.result && resp.json.result.result) || [];
  385. nextId = resp.json && resp.json.result && resp.json.result.nextId;
  386. if (!items.length) {
  387. pushLog(`[${shopEntry.shopName}] 第${page}页无数据,结束翻页`);
  388. break;
  389. }
  390. let newCount = 0;
  391. for (const it of items) {
  392. const gid = it.itemGlobalId;
  393. if (gid !== undefined && gid !== null && seen.has(gid)) continue;
  394. if (gid !== undefined && gid !== null) seen.add(gid);
  395. allItems.push(it);
  396. newCount++;
  397. }
  398. pushLog(`[${shopEntry.shopName}] 第${page}页 新增${newCount}条`);
  399. if (!nextId) break;
  400. await sleep(200);
  401. }
  402. shopEntry.total = allItems.length;
  403. if (authFailed && !allItems.length) {
  404. shopEntry.state = 'failed';
  405. continue;
  406. }
  407. pushLog(`[${shopEntry.shopName}] 共${allItems.length}个菜品,开始下载`);
  408. const manifest = [];
  409. const usedNames = new Set();
  410. for (const it of allItems) {
  411. if (cancelFlag) break;
  412. const itemName = String(it.itemName || it.itemGlobalId || 'unnamed').trim();
  413. const photoUrl = it.photoUrl || it.thumbnailUrl;
  414. if (!photoUrl) {
  415. shopEntry.skipped++;
  416. manifest.push({ itemName, itemGlobalId: it.itemGlobalId, photoUrl: null, savedFile: null, status: 'no_photo' });
  417. continue;
  418. }
  419. let finalBase = sanitizeFileName(itemName);
  420. let n = 1;
  421. while (usedNames.has(finalBase)) { finalBase = `${sanitizeFileName(itemName)}_${n++}`; }
  422. usedNames.add(finalBase);
  423. try {
  424. const buf = await downloadImage(photoUrl);
  425. const ext = guessExtFromUrl(photoUrl);
  426. const fileName = `${finalBase}.${ext}`;
  427. fs.writeFileSync(path.join(dirInfo.dir, fileName), buf);
  428. shopEntry.downloaded++;
  429. manifest.push({ itemName, itemGlobalId: it.itemGlobalId, photoUrl, savedFile: fileName, status: 'downloaded' });
  430. } catch (e) {
  431. shopEntry.failed++;
  432. manifest.push({ itemName, itemGlobalId: it.itemGlobalId, photoUrl, savedFile: null, status: 'download_failed', error: e.message || String(e) });
  433. pushLog(`[${shopEntry.shopName}] 下载失败 ${itemName}: ${e.message || e}`);
  434. }
  435. await sleep(delayMs);
  436. }
  437. try {
  438. fs.writeFileSync(path.join(dirInfo.dir, '_菜品图爬取记录.json'), JSON.stringify(manifest, null, 2), 'utf8');
  439. if (!shopEntry.failed && !cancelFlag) markShopCompleted(root, shopEntry);
  440. } catch (e) {
  441. shopEntry.failed++;
  442. shopEntry.error = `保存抓取状态失败: ${e.message || e}`;
  443. pushLog(`[${shopEntry.shopName}] 保存抓取状态失败: ${e.message || e}`);
  444. }
  445. shopEntry.state = shopEntry.failed ? 'failed' : cancelFlag ? 'stopped' : 'done';
  446. pushLog(`[${shopEntry.shopName}] 完成: 成功${shopEntry.downloaded} 跳过${shopEntry.skipped} 失败${shopEntry.failed}`);
  447. }
  448. crawlState.status = cancelFlag ? 'stopped' : 'done';
  449. crawlState.finishedAt = Date.now();
  450. pushLog('抓取任务结束');
  451. }
  452. function stopCrawl(res) {
  453. if (crawlState.status !== 'running') return sendJson(res, 200, { ok: true, note: '当前没有正在进行的任务' });
  454. cancelFlag = true;
  455. pushLog('收到停止请求,将在当前步骤完成后停止');
  456. sendJson(res, 200, { ok: true });
  457. }
  458. // ============================================================
  459. // GENERATOR MODULE — 店铺视觉图生成
  460. // ============================================================
  461. const OVERLAY_POSITION_LABELS = {
  462. 'top-left': '左上角',
  463. 'top-right': '右上角',
  464. 'bottom-left': '左下角',
  465. 'bottom-right': '右下角',
  466. };
  467. function findExistingAsset(shopDir, baseName) {
  468. const dir = path.join(shopDir, '_生成图片');
  469. for (const ext of IMAGE_EXT) {
  470. const p = path.join(dir, baseName + ext);
  471. if (fs.existsSync(p)) return p;
  472. }
  473. return null;
  474. }
  475. const findExistingLogo = (shopDir) => findExistingAsset(shopDir, 'logo');
  476. const findExistingSticker = (shopDir) => findExistingAsset(shopDir, '贴纸');
  477. function readAsDataUri(filePath) {
  478. const buf = fs.readFileSync(filePath);
  479. let ext = path.extname(filePath).toLowerCase().replace('.', '');
  480. if (ext === 'jpg') ext = 'jpeg';
  481. return `data:image/${ext};base64,${buf.toString('base64')}`;
  482. }
  483. // Builds the reference-image list and final prompt for a generation request, optionally
  484. // fusing the shop's already-generated LOGO and/or 贴纸(sticker) into the frame. Each overlay
  485. // can use either of two modes:
  486. // - 'ai' (default): the asset is passed as an extra reference image and the model is asked
  487. // to paint it into the frame itself.
  488. // - 'composite': the model is only asked to leave the target corner visually clean; the
  489. // actual pixel fusion is done afterwards by compositeOverlaysOntoImage() with no LLM call.
  490. function buildImagesAndPrompt(shopDir, basePrompt, refDishFiles, opts) {
  491. const { addLogo, logoPosition, logoMode, addSticker, stickerPosition, stickerMode } = opts || {};
  492. const images = [];
  493. for (const f of (refDishFiles || []).slice(0, 3)) {
  494. try {
  495. images.push(readAsDataUri(path.join(shopDir, f)));
  496. } catch {
  497. // skip unreadable reference image
  498. }
  499. }
  500. const warnings = [];
  501. const overlayClauses = [];
  502. const compositeOverlays = [];
  503. if (addLogo) {
  504. const logoPath = findExistingLogo(shopDir);
  505. if (logoPath) {
  506. const posLabel = OVERLAY_POSITION_LABELS[logoPosition] || OVERLAY_POSITION_LABELS['bottom-right'];
  507. if (logoMode === 'composite') {
  508. compositeOverlays.push({ type: 'logo', path: logoPath, position: logoPosition || 'bottom-right' });
  509. overlayClauses.push(
  510. opts.sourceImageFirst
  511. ? `第一张图是菜品原图,第二张图是店铺指定LOGO。必须彻底移除菜品原图中已有的LOGO、水印、店铺名、徽章和旧品牌标识,并自然修复该区域背景;不要模仿或保留这些旧标识。画面${posLabel}保持干净,留出用于程序叠加店铺指定LOGO的区域。`
  512. : `画面的${posLabel}请保持背景简洁、不绘制任何LOGO或品牌图案(该区域将在生成后由程序直接叠加店铺LOGO图片)`
  513. );
  514. } else {
  515. try {
  516. images.push(readAsDataUri(logoPath));
  517. overlayClauses.push(
  518. opts.sourceImageFirst
  519. ? `第一张图是菜品原图,第二张图是店铺指定LOGO。店铺指定LOGO是唯一权威品牌标识;必须彻底移除菜品原图中已有的LOGO、水印、店铺名、徽章和旧品牌标识,并自然修复该区域背景。只在画面${posLabel}使用店铺指定LOGO,严格保持其图形、文字、配色和比例完整清晰,不要复制、模仿或保留原图旧标识。`
  520. : `参考图中的店铺LOGO图案(简洁品牌标识)请原样添加到画面的${posLabel}`
  521. );
  522. } catch {
  523. warnings.push('读取已生成的LOGO文件失败,本次生成未附加LOGO');
  524. }
  525. }
  526. } else {
  527. warnings.push('未找到可用LOGO,请先生成');
  528. }
  529. }
  530. if (addSticker) {
  531. const stickerPath = findExistingSticker(shopDir);
  532. if (stickerPath) {
  533. const posLabel = OVERLAY_POSITION_LABELS[stickerPosition] || OVERLAY_POSITION_LABELS['bottom-left'];
  534. if (stickerMode === 'composite') {
  535. compositeOverlays.push({ type: 'sticker', path: stickerPath, position: stickerPosition || 'bottom-left' });
  536. overlayClauses.push(`画面的${posLabel}请保持背景简洁、不绘制任何贴纸/徽章图案(该区域将在生成后由程序直接叠加店铺贴纸图片)`);
  537. } else {
  538. try {
  539. images.push(readAsDataUri(stickerPath));
  540. overlayClauses.push(`参考图中的店铺贴纸插画(徽章/贴纸风格图案)请原样叠加到画面的${posLabel}`);
  541. } catch {
  542. warnings.push('读取已生成的贴纸文件失败,本次生成未附加贴纸');
  543. }
  544. }
  545. } else {
  546. warnings.push('未找到可用贴纸,请先生成');
  547. }
  548. }
  549. let prompt = basePrompt;
  550. if (overlayClauses.length) {
  551. prompt += `\n\n${overlayClauses.join(';')},保持图案本身完整、清晰、不变形、不被裁切,不要遮挡画面主体;其余参考图仅作为风格/内容参考,不必出现在画面里。`;
  552. }
  553. return { images, prompt, warning: warnings.length ? warnings.join(';') : null, compositeOverlays };
  554. }
  555. // ---------- sticker: chroma-key background removal (pure-JS, no image editor needed) ----------
  556. // The generation model has no true alpha-channel/transparent-background output, so for the
  557. // "贴纸" (sticker) asset we ask it to render on a flat key-color background and cut that
  558. // color out ourselves, producing a real transparent PNG.
  559. const STICKER_KEY_COLOR = [255, 0, 255]; // pure magenta, rarely present in food photography
  560. const STICKER_THRESHOLD = 60;
  561. const STICKER_FEATHER = 40;
  562. function decodeToRGBA(buf) {
  563. if (buf.length > 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
  564. const png = PNG.sync.read(buf);
  565. return { width: png.width, height: png.height, data: png.data };
  566. }
  567. const img = jpeg.decode(buf, { useTArray: true });
  568. return { width: img.width, height: img.height, data: img.data };
  569. }
  570. function chromaKeyToTransparentPng(decoded, keyColor, threshold, feather) {
  571. const { width, height, data } = decoded;
  572. const png = new PNG({ width, height });
  573. const [kr, kg, kb] = keyColor;
  574. for (let i = 0; i < width * height; i++) {
  575. const o = i * 4;
  576. const r = data[o];
  577. const g = data[o + 1];
  578. const b = data[o + 2];
  579. const dist = Math.sqrt((r - kr) ** 2 + (g - kg) ** 2 + (b - kb) ** 2);
  580. let alpha;
  581. if (dist <= threshold) alpha = 0;
  582. else if (dist >= threshold + feather) alpha = 255;
  583. else alpha = Math.round(((dist - threshold) / feather) * 255);
  584. png.data[o] = r;
  585. png.data[o + 1] = g;
  586. png.data[o + 2] = b;
  587. png.data[o + 3] = alpha;
  588. }
  589. return PNG.sync.write(png);
  590. }
  591. // ---------- pure image-processing overlay compositing (no LLM call) ----------
  592. // Alternative to the AI-fusion overlay path above: pastes an already-generated logo/sticker
  593. // image directly onto the generated result via alpha blending, entirely in-process.
  594. function resizeRGBA(src, srcW, srcH, dstW, dstH) {
  595. if (srcW === dstW && srcH === dstH) return src;
  596. const dst = Buffer.alloc(dstW * dstH * 4);
  597. for (let y = 0; y < dstH; y++) {
  598. const srcYf = Math.min(srcH - 1, Math.max(0, ((y + 0.5) * srcH) / dstH - 0.5));
  599. const y0 = Math.floor(srcYf);
  600. const y1 = Math.min(srcH - 1, y0 + 1);
  601. const wy = srcYf - y0;
  602. for (let x = 0; x < dstW; x++) {
  603. const srcXf = Math.min(srcW - 1, Math.max(0, ((x + 0.5) * srcW) / dstW - 0.5));
  604. const x0 = Math.floor(srcXf);
  605. const x1 = Math.min(srcW - 1, x0 + 1);
  606. const wx = srcXf - x0;
  607. const o = (y * dstW + x) * 4;
  608. for (let c = 0; c < 4; c++) {
  609. const p00 = src[(y0 * srcW + x0) * 4 + c];
  610. const p10 = src[(y0 * srcW + x1) * 4 + c];
  611. const p01 = src[(y1 * srcW + x0) * 4 + c];
  612. const p11 = src[(y1 * srcW + x1) * 4 + c];
  613. const top = p00 + (p10 - p00) * wx;
  614. const bottom = p01 + (p11 - p01) * wx;
  615. dst[o + c] = Math.round(top + (bottom - top) * wy);
  616. }
  617. }
  618. }
  619. return dst;
  620. }
  621. const OVERLAY_WIDTH_RATIO = { logo: 0.16, sticker: 0.22 };
  622. // Alpha-blends `overlay` (resized to a fraction of the base width, keeping its aspect ratio)
  623. // onto `base` at the given corner and returns a new decoded-RGBA object. Both inputs and the
  624. // output are the same {width, height, data} shape produced by decodeToRGBA().
  625. function compositeOverlayOntoBase(base, overlay, position, widthRatio) {
  626. const targetW = Math.max(1, Math.round(base.width * widthRatio));
  627. const targetH = Math.max(1, Math.round((overlay.height / overlay.width) * targetW));
  628. const resized = resizeRGBA(overlay.data, overlay.width, overlay.height, targetW, targetH);
  629. const margin = Math.round(base.width * 0.04);
  630. let x, y;
  631. if (position === 'top-left') { x = margin; y = margin; }
  632. else if (position === 'top-right') { x = base.width - margin - targetW; y = margin; }
  633. else if (position === 'bottom-left') { x = margin; y = base.height - margin - targetH; }
  634. else { x = base.width - margin - targetW; y = base.height - margin - targetH; } // bottom-right (default)
  635. x = Math.max(0, Math.min(x, base.width - targetW));
  636. y = Math.max(0, Math.min(y, base.height - targetH));
  637. const out = Buffer.from(base.data);
  638. for (let j = 0; j < targetH; j++) {
  639. const by = y + j;
  640. if (by < 0 || by >= base.height) continue;
  641. for (let i = 0; i < targetW; i++) {
  642. const bx = x + i;
  643. if (bx < 0 || bx >= base.width) continue;
  644. const so = (j * targetW + i) * 4;
  645. const alpha = resized[so + 3] / 255;
  646. if (alpha <= 0) continue;
  647. const bo = (by * base.width + bx) * 4;
  648. out[bo] = Math.round(resized[so] * alpha + out[bo] * (1 - alpha));
  649. out[bo + 1] = Math.round(resized[so + 1] * alpha + out[bo + 1] * (1 - alpha));
  650. out[bo + 2] = Math.round(resized[so + 2] * alpha + out[bo + 2] * (1 - alpha));
  651. }
  652. }
  653. return { width: base.width, height: base.height, data: out };
  654. }
  655. function encodeRGBAToPng(decoded) {
  656. const png = new PNG({ width: decoded.width, height: decoded.height });
  657. Buffer.from(decoded.data).copy(png.data);
  658. return PNG.sync.write(png);
  659. }
  660. // Applies a list of {type, path, position} overlays (from buildImagesAndPrompt's composite
  661. // mode) onto an already-generated result image. Returns {buf, ext} - falls back to the
  662. // original buffer/ext (with a warning appended to job.warning) if the base image can't be
  663. // decoded (e.g. a webp/gif result, which decodeToRGBA doesn't support).
  664. function applyCompositeOverlays(job, buf, ext) {
  665. if (!job.compositeOverlays || !job.compositeOverlays.length) return { buf, ext };
  666. let base;
  667. try {
  668. base = decodeToRGBA(buf);
  669. } catch (e) {
  670. job.warning = (job.warning ? job.warning + ';' : '') + '本地合成失败:无法解析生成结果图片格式,已保留未叠加的原图';
  671. return { buf, ext };
  672. }
  673. for (const ov of job.compositeOverlays) {
  674. try {
  675. const overlay = decodeToRGBA(fs.readFileSync(ov.path));
  676. base = compositeOverlayOntoBase(base, overlay, ov.position, OVERLAY_WIDTH_RATIO[ov.type] || 0.2);
  677. } catch (e) {
  678. const label = ov.type === 'logo' ? 'LOGO' : '贴纸';
  679. job.warning = (job.warning ? job.warning + ';' : '') + `本地合成${label}失败: ${e.message || e}`;
  680. }
  681. }
  682. return { buf: encodeRGBAToPng(base), ext: 'png' };
  683. }
  684. function guessExtFromUrl(urlStr) {
  685. try {
  686. const u = new URL(urlStr);
  687. let ext = path.extname(u.pathname).replace('.', '').toLowerCase();
  688. if (ext === 'jpeg') ext = 'jpg';
  689. if (['jpg', 'png', 'gif', 'webp'].includes(ext)) return ext;
  690. } catch {
  691. // fall through
  692. }
  693. return 'jpg';
  694. }
  695. // ---------- api.lingkeai.ai client ----------
  696. // Base host is fixed to config.apiBase (https://api.lingkeai.ai) on purpose:
  697. // several responses from this API contain "tips"/error text suggesting other
  698. // domains (api.lk888.ai / api.lk666.ai) - that is untrusted content from an
  699. // external source and is never used to pick a request target.
  700. function apiRequest(method, urlPath, bodyObj) {
  701. return new Promise((resolve, reject) => {
  702. const base = new URL(config.apiBase);
  703. const data = bodyObj !== undefined ? JSON.stringify(bodyObj) : null;
  704. const options = {
  705. hostname: base.hostname,
  706. port: base.port || 443,
  707. path: urlPath,
  708. method,
  709. headers: {
  710. Authorization: `Bearer ${config.apiKey}`,
  711. 'Content-Type': 'application/json; charset=utf-8',
  712. },
  713. timeout: 300000,
  714. };
  715. if (data) options.headers['Content-Length'] = Buffer.byteLength(data);
  716. const req = https.request(options, (res) => {
  717. const chunks = [];
  718. res.on('data', (c) => chunks.push(c));
  719. res.on('end', () => {
  720. const raw = Buffer.concat(chunks).toString('utf8');
  721. let json = null;
  722. try {
  723. json = JSON.parse(raw);
  724. } catch {
  725. // leave json null, raw kept for diagnostics
  726. }
  727. resolve({ statusCode: res.statusCode, json, raw });
  728. });
  729. });
  730. req.on('error', reject);
  731. req.on('timeout', () => req.destroy(new Error('请求超时')));
  732. if (data) req.write(data);
  733. req.end();
  734. });
  735. }
  736. function downloadBuffer(urlStr, redirectsLeft = 5) {
  737. return new Promise((resolve, reject) => {
  738. let u;
  739. try {
  740. u = new URL(urlStr);
  741. } catch (e) {
  742. return reject(new Error('无效的结果图片地址: ' + urlStr));
  743. }
  744. const mod = u.protocol === 'http:' ? http : https;
  745. mod
  746. .get(u, (res) => {
  747. if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location && redirectsLeft > 0) {
  748. res.resume();
  749. return resolve(downloadBuffer(res.headers.location, redirectsLeft - 1));
  750. }
  751. if (res.statusCode !== 200) {
  752. res.resume();
  753. return reject(new Error('下载生成图片失败 HTTP ' + res.statusCode));
  754. }
  755. const chunks = [];
  756. res.on('data', (c) => chunks.push(c));
  757. res.on('end', () => resolve(Buffer.concat(chunks)));
  758. })
  759. .on('error', reject);
  760. });
  761. }
  762. // ---------- job queue ----------
  763. const jobs = new Map();
  764. const pendingQueue = [];
  765. let activeCount = 0;
  766. function createJob(opts) {
  767. const id = crypto.randomUUID();
  768. const job = {
  769. id,
  770. root: opts.root,
  771. folderName: opts.folderName,
  772. kind: opts.kind,
  773. shopName: opts.shopName,
  774. dishName: opts.dishName || null,
  775. model: MODEL_IDS.has(opts.model) ? opts.model : config.model,
  776. prompt: opts.prompt,
  777. size: opts.size,
  778. aspectRatio: opts.aspectRatio,
  779. images: opts.images || [],
  780. outputDir: opts.outputDir,
  781. outputBaseName: opts.outputBaseName,
  782. compositeOverlays: opts.compositeOverlays || [],
  783. state: 'queued',
  784. progress: '0%',
  785. taskId: null,
  786. cost: null,
  787. resultUrl: null,
  788. remoteUrl: null,
  789. width: null,
  790. height: null,
  791. fileSizeBytes: null,
  792. error: null,
  793. warning: opts.warning || null,
  794. createdAt: Date.now(),
  795. };
  796. jobs.set(id, job);
  797. const jobTitle = job.dishName ? `${job.shopName} / ${job.dishName}` : `${job.shopName} / ${job.kind}`;
  798. pushSystemLog(`生成任务已提交:${jobTitle}(${job.model})`);
  799. if (activeCount < config.maxConcurrentJobs) {
  800. startJob(job);
  801. } else {
  802. pendingQueue.push(id);
  803. }
  804. return job;
  805. }
  806. function startJob(job) {
  807. activeCount++;
  808. job.state = 'running';
  809. processJob(job)
  810. .catch((e) => {
  811. job.state = 'failed';
  812. job.error = job.error || e.message || String(e);
  813. })
  814. .finally(() => {
  815. const jobTitle = job.dishName ? `${job.shopName} / ${job.dishName}` : `${job.shopName} / ${job.kind}`;
  816. if (job.state === 'success') pushSystemLog(`生成完成:${jobTitle}`, 'success');
  817. else if (job.state === 'failed') pushSystemLog(`生成失败:${jobTitle},${job.error || '未知错误'}`, 'error');
  818. activeCount--;
  819. const nextId = pendingQueue.shift();
  820. if (nextId) {
  821. const nextJob = jobs.get(nextId);
  822. if (nextJob) startJob(nextJob);
  823. }
  824. });
  825. }
  826. // Builds the model-specific `params` object for the /v1/media/generate request. Different
  827. // image models on this API expose different (and sometimes confusingly named) parameters -
  828. // e.g. wan2.6-image has no separate aspect_ratio field, its required "size" param IS the
  829. // aspect-ratio string (auto/1:1/16:9/...), plus an optional prompt_extend flag.
  830. function buildParamsForModel(modelId, job) {
  831. const params = {};
  832. if (modelId === 'gpt-image-2') {
  833. params.size = 'auto';
  834. params.quality = 'auto';
  835. params.resolution = job.size || '1K';
  836. params.n = 1;
  837. params.response_format = 'url';
  838. if (job.aspectRatio && job.aspectRatio !== 'auto') params.aspect_ratio = job.aspectRatio;
  839. } else if (modelId === 'gpt-image-2-guan') {
  840. params.size = 'auto';
  841. params.quality = 'auto';
  842. } else if (modelId === 'wan2.6-image') {
  843. params.size = job.aspectRatio || job.size || 'auto';
  844. params.prompt_extend = true;
  845. } else {
  846. if (job.size) params.size = NO_1K_SUPPORT.has(modelId) && job.size === '1K' ? '2K' : job.size;
  847. if (job.aspectRatio) params.aspect_ratio = job.aspectRatio;
  848. }
  849. let images = job.images;
  850. if (modelId === 'wan2.6-image' && images.length > 4) {
  851. job.warning = (job.warning ? job.warning + ';' : '') + 'wan2.6-image 最多支持4张参考图,已自动截取前4张';
  852. images = images.slice(0, 4);
  853. }
  854. if (images.length === 1) params.images = images[0];
  855. else if (images.length > 1) params.images = images;
  856. return params;
  857. }
  858. async function processJob(job) {
  859. const body = {
  860. model: job.model,
  861. prompt: job.prompt,
  862. params: buildParamsForModel(job.model, job),
  863. };
  864. const submit = await apiRequest('POST', '/v1/media/generate', body);
  865. const taskId = submit.json && (submit.json.task_id || (submit.json.data && submit.json.data.task_id));
  866. if (submit.statusCode !== 200 || !submit.json || !taskId) {
  867. throw new Error('提交生成任务失败: ' + (submit.json ? JSON.stringify(submit.json) : submit.raw.slice(0, 500)));
  868. }
  869. job.taskId = taskId;
  870. await sleep(7000);
  871. const start = Date.now();
  872. const TIMEOUT_MS = 10 * 60 * 1000;
  873. for (;;) {
  874. if (Date.now() - start > TIMEOUT_MS) {
  875. job.state = 'failed';
  876. job.error = '轮询超时(10分钟未完成)';
  877. return;
  878. }
  879. const statusPath = (job.model === 'gpt-image-2' || job.model === 'gpt-image-2-guan')
  880. ? `/v1/media/status?task_id=${encodeURIComponent(job.taskId)}`
  881. : `/v1/skills/task-status?task_id=${encodeURIComponent(job.taskId)}`;
  882. const statusResp = await apiRequest('GET', statusPath);
  883. const status = statusResp.json;
  884. if (!status) {
  885. await sleep(5000);
  886. continue;
  887. }
  888. job.progress = String(status.progress ?? job.progress);
  889. if (status.cost !== undefined) job.cost = status.cost;
  890. if (status.is_final) {
  891. if (status.state === 'success' && status.result_url) {
  892. job.remoteUrl = status.result_url;
  893. const buf = await downloadBuffer(status.result_url);
  894. let finalBuf, ext;
  895. finalBuf = buf;
  896. ext = guessExtFromUrl(status.result_url);
  897. ({ buf: finalBuf, ext } = applyCompositeOverlays(job, finalBuf, ext));
  898. fs.mkdirSync(job.outputDir, { recursive: true });
  899. const savePath = path.join(job.outputDir, `${job.outputBaseName}.${ext}`);
  900. fs.writeFileSync(savePath, finalBuf);
  901. const dims = getImageSize(finalBuf) || {};
  902. job.width = dims.width || null;
  903. job.height = dims.height || null;
  904. job.fileSizeBytes = finalBuf.length;
  905. job.resultPath = savePath;
  906. job.resultUrl = '/files?path=' + encodeURIComponent(savePath);
  907. const creationHistoryDir = path.basename(job.outputDir) === '菜品图'
  908. ? path.dirname(job.outputDir)
  909. : job.outputDir;
  910. appendCreationHistory(creationHistoryDir, {
  911. id: job.id,
  912. root: job.root,
  913. folderName: job.folderName,
  914. shopName: job.shopName,
  915. kind: job.kind,
  916. name: job.dishName || job.kind,
  917. dishName: job.dishName,
  918. fileName: path.basename(savePath),
  919. relativePath: path.relative(creationHistoryDir, savePath),
  920. remoteUrl: job.remoteUrl,
  921. model: job.model,
  922. cost: job.cost,
  923. width: job.width,
  924. height: job.height,
  925. fileSizeBytes: job.fileSizeBytes,
  926. generatedAt: new Date().toISOString(),
  927. });
  928. job.state = 'success';
  929. } else {
  930. job.state = 'failed';
  931. job.error = status.error || status.status || '生成失败';
  932. job.cost = status.cost ?? job.cost;
  933. }
  934. return;
  935. }
  936. await sleep(5000);
  937. }
  938. }
  939. // ---------- scan helpers ----------
  940. function fileInfo(p) {
  941. const buf = fs.readFileSync(p);
  942. const dims = getImageSize(buf) || {};
  943. return {
  944. url: '/files?path=' + encodeURIComponent(p),
  945. width: dims.width || null,
  946. height: dims.height || null,
  947. fileSizeBytes: buf.length,
  948. };
  949. }
  950. function scanGenerated(shopDir) {
  951. const dir = path.join(shopDir, '_生成图片');
  952. const result = { logo: null, banner: null, signage: null, sticker: null, dishes: {} };
  953. if (!fs.existsSync(dir)) return result;
  954. for (const [kind, base] of [['logo', 'logo'], ['banner', 'banner'], ['signage', '招牌头图'], ['sticker', '贴纸']]) {
  955. for (const ext of IMAGE_EXT) {
  956. const p = path.join(dir, base + ext);
  957. if (fs.existsSync(p)) {
  958. try {
  959. result[kind] = fileInfo(p);
  960. } catch {
  961. // ignore unreadable file
  962. }
  963. break;
  964. }
  965. }
  966. }
  967. const dishDir = path.join(dir, '菜品图');
  968. if (fs.existsSync(dishDir)) {
  969. for (const f of fs.readdirSync(dishDir)) {
  970. const ext = path.extname(f).toLowerCase();
  971. if (!IMAGE_EXT.has(ext)) continue;
  972. const name = f.slice(0, -ext.length);
  973. try {
  974. result.dishes[name] = fileInfo(path.join(dishDir, f));
  975. } catch {
  976. // ignore unreadable file
  977. }
  978. }
  979. }
  980. return result;
  981. }
  982. function loadCreationHistory(outputDir) {
  983. const historyPath = path.join(outputDir, 'generation-history.json');
  984. if (!fs.existsSync(historyPath)) return [];
  985. try {
  986. const records = JSON.parse(fs.readFileSync(historyPath, 'utf8'));
  987. return Array.isArray(records) ? records : [];
  988. } catch {
  989. return [];
  990. }
  991. }
  992. function appendCreationHistory(outputDir, record) {
  993. fs.mkdirSync(outputDir, { recursive: true });
  994. const historyPath = path.join(outputDir, 'generation-history.json');
  995. const records = loadCreationHistory(outputDir).filter((item) => item.id !== record.id);
  996. records.push(record);
  997. const tempPath = historyPath + '.tmp';
  998. fs.writeFileSync(tempPath, JSON.stringify(records, null, 2));
  999. fs.renameSync(tempPath, historyPath);
  1000. }
  1001. function handleScan(query, res) {
  1002. const root = query.root;
  1003. if (!root || !fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
  1004. return sendJson(res, 400, { error: '目录不存在: ' + root });
  1005. }
  1006. let selectedFolders = null;
  1007. if (query.folders) {
  1008. try {
  1009. selectedFolders = JSON.parse(query.folders);
  1010. } catch {
  1011. return sendJson(res, 400, { error: '指定店铺参数无效' });
  1012. }
  1013. if (!Array.isArray(selectedFolders) || !selectedFolders.length ||
  1014. selectedFolders.some((name) => typeof name !== 'string' || !name ||
  1015. name === '.' || name === '..' || name.includes('/') || name.includes('\\'))) {
  1016. return sendJson(res, 400, { error: '指定店铺参数无效' });
  1017. }
  1018. selectedFolders = [...new Set(selectedFolders)];
  1019. }
  1020. let entries;
  1021. try {
  1022. entries = fs.readdirSync(root, { withFileTypes: true });
  1023. } catch (e) {
  1024. return sendJson(res, 400, { error: '无法读取目录: ' + e.message });
  1025. }
  1026. const shops = [];
  1027. for (const ent of entries) {
  1028. if (!ent.isDirectory()) continue;
  1029. if (ent.name.startsWith('.') || ent.name === '图片生成工具') continue;
  1030. if (selectedFolders && !selectedFolders.includes(ent.name)) continue;
  1031. const folderName = ent.name;
  1032. const shopDir = path.join(root, folderName);
  1033. let files;
  1034. try {
  1035. files = fs.readdirSync(shopDir, { withFileTypes: true });
  1036. } catch {
  1037. continue;
  1038. }
  1039. const dishes = [];
  1040. for (const f of files) {
  1041. if (!f.isFile()) continue;
  1042. const ext = path.extname(f.name).toLowerCase();
  1043. if (!IMAGE_EXT.has(ext)) continue;
  1044. dishes.push({
  1045. file: f.name,
  1046. name: f.name.slice(0, -ext.length).replace(/^\d+_/, ''),
  1047. url: '/files?path=' + encodeURIComponent(path.join(shopDir, f.name)),
  1048. });
  1049. }
  1050. if (!dishes.length) continue;
  1051. dishes.sort((a, b) => a.file.localeCompare(b.file, 'zh'));
  1052. let overrides = {};
  1053. const cfgPath = path.join(shopDir, '_生成图片', 'prompt-config.json');
  1054. if (fs.existsSync(cfgPath)) {
  1055. try {
  1056. overrides = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
  1057. } catch {
  1058. // ignore malformed override file
  1059. }
  1060. }
  1061. const parsedName = folderName.replace(/^\d+_/, '').replace(/_\d+$/, '');
  1062. shops.push({
  1063. folderName,
  1064. shopName: overrides.shopName || parsedName,
  1065. dishes,
  1066. promptOverrides: overrides.prompts || {},
  1067. generated: scanGenerated(shopDir),
  1068. });
  1069. }
  1070. shops.sort((a, b) => a.folderName.localeCompare(b.folderName, 'zh'));
  1071. sendJson(res, 200, { root, shops });
  1072. }
  1073. const CREATION_KINDS = new Set(['logo', 'banner', 'signage', 'sticker', 'dish']);
  1074. function getCreationKind(directoryName, fileName) {
  1075. if (directoryName === '菜品图') return 'dish';
  1076. if (/^logo\./i.test(fileName)) return 'logo';
  1077. if (/^(banner|店内海报)/i.test(fileName)) return 'banner';
  1078. if (/^招牌头图/i.test(fileName)) return 'signage';
  1079. if (/^贴纸/i.test(fileName)) return 'sticker';
  1080. return 'other';
  1081. }
  1082. function handleCreations(query, res) {
  1083. const root = query.root;
  1084. if (!root) return sendJson(res, 400, { error: '参数不完整' });
  1085. const resolvedRoot = path.resolve(String(root));
  1086. if (!fs.existsSync(resolvedRoot) || !fs.statSync(resolvedRoot).isDirectory()) {
  1087. return sendJson(res, 400, { error: '目录不存在: ' + resolvedRoot });
  1088. }
  1089. const limit = Math.min(Math.max(Number(query.limit) || 300, 1), 600);
  1090. const retentionCutoff = Date.now() - 48 * 60 * 60 * 1000;
  1091. const items = [];
  1092. let entries;
  1093. try {
  1094. entries = fs.readdirSync(resolvedRoot, { withFileTypes: true });
  1095. } catch (e) {
  1096. return sendJson(res, 400, { error: '无法读取目录: ' + e.message });
  1097. }
  1098. for (const entry of entries) {
  1099. if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === '图片生成工具' || SKIP_DIR_NAMES.has(entry.name)) continue;
  1100. const shopDir = path.join(resolvedRoot, entry.name);
  1101. const outputDir = path.join(shopDir, '_生成图片');
  1102. if (!fs.existsSync(outputDir) || !fs.statSync(outputDir).isDirectory()) continue;
  1103. let shopName = entry.name.replace(/^\d+_/, '').replace(/_\d+$/, '');
  1104. const cfgPath = path.join(outputDir, 'prompt-config.json');
  1105. if (fs.existsSync(cfgPath)) {
  1106. try {
  1107. const config = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
  1108. shopName = config.shopName || shopName;
  1109. } catch {}
  1110. }
  1111. const nestedHistoryRecords = loadCreationHistory(path.join(outputDir, '菜品图'))
  1112. .map((record) => ({
  1113. ...record,
  1114. relativePath: path.normalize(path.join('菜品图', record.relativePath || record.fileName || '.')),
  1115. }));
  1116. const historyRecords = [...loadCreationHistory(outputDir), ...nestedHistoryRecords];
  1117. const seenHistoryIds = new Set();
  1118. const historyPaths = new Set();
  1119. for (const record of historyRecords) {
  1120. if (record.id && seenHistoryIds.has(record.id)) continue;
  1121. if (record.id) seenHistoryIds.add(record.id);
  1122. if (!record.remoteUrl || !record.fileName) continue;
  1123. const generatedAt = record.generatedAt || record.modifiedAt;
  1124. const generatedTimeMs = generatedAt ? new Date(generatedAt).getTime() : 0;
  1125. if (!Number.isFinite(generatedTimeMs) || generatedTimeMs < retentionCutoff) continue;
  1126. const kind = CREATION_KINDS.has(record.kind) ? record.kind : getCreationKind(record.relativePath || '.', record.fileName);
  1127. if (!kind || kind === 'other') continue;
  1128. const relativePath = path.normalize(record.relativePath || record.fileName);
  1129. historyPaths.add(relativePath);
  1130. items.push({
  1131. folderName: entry.name,
  1132. shopName: record.shopName || shopName,
  1133. kind,
  1134. name: record.name || record.dishName || path.basename(record.fileName, path.extname(record.fileName)),
  1135. fileName: record.fileName,
  1136. url: record.remoteUrl,
  1137. remoteUrl: record.remoteUrl,
  1138. localPath: path.join(outputDir, relativePath),
  1139. source: 'remote',
  1140. model: record.model,
  1141. cost: record.cost,
  1142. modifiedAt: generatedAt,
  1143. modifiedTimeMs: generatedTimeMs,
  1144. width: record.width,
  1145. height: record.height,
  1146. fileSizeBytes: record.fileSizeBytes,
  1147. });
  1148. }
  1149. for (const relativeDir of ['.', '菜品图']) {
  1150. const currentDir = path.join(outputDir, relativeDir);
  1151. if (!fs.existsSync(currentDir) || !fs.statSync(currentDir).isDirectory()) continue;
  1152. let files;
  1153. try {
  1154. files = fs.readdirSync(currentDir, { withFileTypes: true });
  1155. } catch {
  1156. continue;
  1157. }
  1158. for (const file of files) {
  1159. if (!file.isFile()) continue;
  1160. const ext = path.extname(file.name).toLowerCase();
  1161. if (!IMAGE_EXT.has(ext)) continue;
  1162. const kind = getCreationKind(relativeDir, file.name);
  1163. if (kind === 'other') continue;
  1164. const fullPath = path.join(currentDir, file.name);
  1165. const relativePath = path.relative(outputDir, fullPath);
  1166. if (historyPaths.has(path.normalize(relativePath))) continue;
  1167. let stat;
  1168. try {
  1169. stat = fs.statSync(fullPath);
  1170. } catch {
  1171. continue;
  1172. }
  1173. if (stat.mtimeMs < retentionCutoff) continue;
  1174. items.push({
  1175. folderName: entry.name,
  1176. shopName,
  1177. kind,
  1178. name: path.basename(file.name, ext),
  1179. fileName: file.name,
  1180. url: '/files?path=' + encodeURIComponent(fullPath),
  1181. modifiedAt: stat.mtime.toISOString(),
  1182. modifiedTimeMs: stat.mtimeMs,
  1183. fileSizeBytes: stat.size,
  1184. });
  1185. }
  1186. }
  1187. }
  1188. items.sort((a, b) => b.modifiedTimeMs - a.modifiedTimeMs);
  1189. sendJson(res, 200, { root: resolvedRoot, total: items.length, items: items.slice(0, limit) });
  1190. }
  1191. function handleFiles(query, res) {
  1192. const p = query.path;
  1193. if (!p) {
  1194. res.writeHead(400);
  1195. return res.end('missing path');
  1196. }
  1197. const resolved = path.resolve(p);
  1198. if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
  1199. res.writeHead(404);
  1200. return res.end('not found');
  1201. }
  1202. const ext = path.extname(resolved).toLowerCase();
  1203. if (!IMAGE_EXT.has(ext)) {
  1204. res.writeHead(403);
  1205. return res.end('forbidden');
  1206. }
  1207. res.writeHead(200, { 'Content-Type': MIME_BY_EXT[ext], 'Cache-Control': 'no-cache' });
  1208. fs.createReadStream(resolved).pipe(res);
  1209. }
  1210. async function handleGenerateBrand(body, res) {
  1211. const { root, folderName, shopName, kind, prompt, size, aspectRatio, refDishFiles, addLogo, logoPosition, logoMode, model } = body;
  1212. const outNameMap = { logo: 'logo', banner: 'banner', signage: '招牌头图', sticker: '贴纸' };
  1213. if (!root || !folderName || !kind || !outNameMap[kind] || !prompt) {
  1214. return sendJson(res, 400, { error: '参数不完整' });
  1215. }
  1216. const shopDir = path.join(root, folderName);
  1217. // logo/sticker are themselves brand-mark assets, adding the shop logo onto them is not applicable
  1218. const shouldAddLogo = !!addLogo && kind !== 'logo';
  1219. const { images, prompt: finalPrompt, warning, compositeOverlays } = buildImagesAndPrompt(shopDir, prompt, refDishFiles, {
  1220. addLogo: shouldAddLogo,
  1221. logoPosition,
  1222. logoMode,
  1223. });
  1224. const job = createJob({
  1225. kind,
  1226. root,
  1227. folderName,
  1228. shopName,
  1229. model,
  1230. prompt: finalPrompt,
  1231. size: size || '1K',
  1232. aspectRatio: aspectRatio || undefined,
  1233. images,
  1234. outputDir: path.join(shopDir, '_生成图片'),
  1235. outputBaseName: outNameMap[kind],
  1236. warning,
  1237. compositeOverlays,
  1238. });
  1239. sendJson(res, 200, { jobId: job.id });
  1240. }
  1241. async function handleGenerateDish(body, res) {
  1242. const { root, folderName, shopName, dishFile, dishName, prompt, size, addLogo, logoPosition, logoMode, addSticker, stickerPosition, stickerMode, model } = body;
  1243. if (!root || !folderName || !dishFile || !prompt) {
  1244. return sendJson(res, 400, { error: '参数不完整' });
  1245. }
  1246. const shopDir = path.join(root, folderName);
  1247. let dishImage;
  1248. try {
  1249. dishImage = readAsDataUri(path.join(shopDir, dishFile));
  1250. } catch (e) {
  1251. return sendJson(res, 400, { error: '读取菜品原图失败: ' + e.message });
  1252. }
  1253. const { images: overlayImages, prompt: finalPrompt, warning, compositeOverlays } = buildImagesAndPrompt(shopDir, prompt, [], {
  1254. addLogo: !!addLogo,
  1255. logoPosition,
  1256. logoMode,
  1257. addSticker: !!addSticker,
  1258. stickerPosition,
  1259. stickerMode,
  1260. sourceImageFirst: true,
  1261. });
  1262. const job = createJob({
  1263. kind: 'dish',
  1264. root,
  1265. folderName,
  1266. shopName,
  1267. dishName,
  1268. model,
  1269. prompt: finalPrompt,
  1270. size: size || '1K',
  1271. aspectRatio: '1:1',
  1272. images: [dishImage, ...overlayImages],
  1273. outputDir: path.join(shopDir, '_生成图片', '菜品图'),
  1274. outputBaseName: sanitizeFileName(dishName),
  1275. warning,
  1276. compositeOverlays,
  1277. });
  1278. sendJson(res, 200, { jobId: job.id });
  1279. }
  1280. function handleJob(pathname, res) {
  1281. const id = pathname.split('/').pop();
  1282. const job = jobs.get(id);
  1283. if (!job) return sendJson(res, 404, { error: 'job not found' });
  1284. sendJson(res, 200, {
  1285. id: job.id,
  1286. kind: job.kind,
  1287. dishName: job.dishName,
  1288. state: job.state,
  1289. progress: job.progress,
  1290. cost: job.cost,
  1291. resultUrl: job.resultUrl,
  1292. width: job.width,
  1293. height: job.height,
  1294. fileSizeBytes: job.fileSizeBytes,
  1295. error: job.error,
  1296. warning: job.warning,
  1297. });
  1298. }
  1299. async function handleSaveConfig(body, res) {
  1300. const { root, folderName, shopName, prompts } = body;
  1301. if (!root || !folderName) return sendJson(res, 400, { error: '参数不完整' });
  1302. const dir = path.join(root, folderName, '_生成图片');
  1303. fs.mkdirSync(dir, { recursive: true });
  1304. const cfgPath = path.join(dir, 'prompt-config.json');
  1305. let existing = {};
  1306. if (fs.existsSync(cfgPath)) {
  1307. try {
  1308. existing = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
  1309. } catch {
  1310. // start fresh if corrupt
  1311. }
  1312. }
  1313. const merged = {
  1314. shopName: shopName !== undefined ? shopName : existing.shopName,
  1315. prompts: { ...(existing.prompts || {}), ...(prompts || {}) },
  1316. };
  1317. fs.writeFileSync(cfgPath, JSON.stringify(merged, null, 2), 'utf8');
  1318. sendJson(res, 200, { ok: true });
  1319. }
  1320. async function handleSavePosterCanvas(body, res) {
  1321. const { root, folderName, kind, imageDataUrl } = body;
  1322. const spec = POSTER_CANVAS_SPECS[kind];
  1323. if (!root || !folderName || !spec || !imageDataUrl) {
  1324. return sendJson(res, 400, { error: '参数不完整' });
  1325. }
  1326. if (typeof folderName !== 'string' || folderName === '.' || folderName === '..' || /[\\/]/.test(folderName)) {
  1327. return sendJson(res, 400, { error: '店铺目录名无效' });
  1328. }
  1329. const dataUrlMatch = typeof imageDataUrl === 'string' && /^data:image\/png;base64,([A-Za-z0-9+/=]+)$/.exec(imageDataUrl);
  1330. if (!dataUrlMatch) {
  1331. return sendJson(res, 400, { error: '画板图必须为 PNG 格式' });
  1332. }
  1333. const base64 = dataUrlMatch[1];
  1334. if (!base64 || base64.length > 10 * 1024 * 1024) {
  1335. return sendJson(res, 400, { error: '画板图数据无效或过大' });
  1336. }
  1337. let imageBuffer;
  1338. try {
  1339. imageBuffer = Buffer.from(base64, 'base64');
  1340. } catch {
  1341. return sendJson(res, 400, { error: '画板图数据无法读取' });
  1342. }
  1343. const pngSignature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  1344. if (!imageBuffer.length || !imageBuffer.subarray(0, 8).equals(pngSignature)) {
  1345. return sendJson(res, 400, { error: '画板图不是有效的 PNG 文件' });
  1346. }
  1347. const dimensions = getImageSize(imageBuffer);
  1348. if (!dimensions || dimensions.width !== spec.width || dimensions.height !== spec.height) {
  1349. return sendJson(res, 400, { error: `画板图尺寸必须为 ${spec.width}×${spec.height}` });
  1350. }
  1351. const resolvedRoot = path.resolve(root);
  1352. const shopDir = path.resolve(resolvedRoot, folderName);
  1353. if (shopDir !== path.join(resolvedRoot, folderName) || !shopDir.startsWith(resolvedRoot + path.sep)) {
  1354. return sendJson(res, 400, { error: '店铺目录无效' });
  1355. }
  1356. const dir = path.join(shopDir, '_生成图片');
  1357. const savePath = path.join(dir, spec.fileName);
  1358. try {
  1359. fs.mkdirSync(dir, { recursive: true });
  1360. fs.writeFileSync(savePath, imageBuffer);
  1361. } catch (e) {
  1362. return sendJson(res, 500, { error: '保存画板图失败: ' + e.message });
  1363. }
  1364. sendJson(res, 200, { ok: true, fileName: spec.fileName, width: dimensions.width, height: dimensions.height, fileSizeBytes: imageBuffer.length });
  1365. }
  1366. function handleOpenFolder(body, res) {
  1367. const { root, folderName } = body;
  1368. if (!root || !folderName) return sendJson(res, 400, { error: '参数不完整' });
  1369. const dir = path.join(root, folderName, '_生成图片');
  1370. try {
  1371. fs.mkdirSync(dir, { recursive: true });
  1372. } catch (e) {
  1373. return sendJson(res, 500, { error: '无法创建目录: ' + e.message });
  1374. }
  1375. // explorer.exe frequently exits with a non-zero code even when it opens the window fine,
  1376. // so its callback result is ignored rather than treated as a failure.
  1377. execFile('explorer', [dir], () => {});
  1378. sendJson(res, 200, { ok: true });
  1379. }
  1380. // ---------- static frontend ----------
  1381. const STATIC_MAP = {
  1382. '/': ['index.html', 'text/html; charset=utf-8'],
  1383. '/index.html': ['index.html', 'text/html; charset=utf-8'],
  1384. '/app.js': ['app.js', 'application/javascript; charset=utf-8'],
  1385. '/crawl.js': ['crawl.js', 'application/javascript; charset=utf-8'],
  1386. '/gen.js': ['gen.js', 'application/javascript; charset=utf-8'],
  1387. '/history.js': ['history.js', 'application/javascript; charset=utf-8'],
  1388. '/style.css': ['style.css', 'text/css; charset=utf-8'],
  1389. };
  1390. const STATIC_TYPES = {
  1391. '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml',
  1392. '.ico': 'image/x-icon', '.css': 'text/css', '.js': 'application/javascript',
  1393. };
  1394. function serveStatic(pathname, res) {
  1395. const entry = STATIC_MAP[pathname];
  1396. if (entry) {
  1397. const full = path.join(__dirname, 'public', entry[0]);
  1398. fs.readFile(full, (err, data) => {
  1399. if (err) { res.writeHead(404); return res.end('Not found'); }
  1400. res.writeHead(200, { 'Content-Type': entry[1], 'Cache-Control': 'no-cache' });
  1401. res.end(data);
  1402. });
  1403. return;
  1404. }
  1405. if (pathname.startsWith('/assets/')) {
  1406. const rel = pathname.replace('/assets/', '');
  1407. if (rel.includes('..') || rel.includes('/')) { res.writeHead(403); return res.end('Forbidden'); }
  1408. const full = path.join(__dirname, 'public', 'assets', rel);
  1409. if (!fs.existsSync(full) || !fs.statSync(full).isFile()) { res.writeHead(404); return res.end('Not found'); }
  1410. const ext = path.extname(full).toLowerCase();
  1411. res.writeHead(200, { 'Content-Type': STATIC_TYPES[ext] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
  1412. fs.createReadStream(full).pipe(res);
  1413. return;
  1414. }
  1415. res.writeHead(404);
  1416. res.end('Not found');
  1417. }
  1418. // ---------- server ----------
  1419. const server = http.createServer((req, res) => {
  1420. let parsedUrl;
  1421. try {
  1422. parsedUrl = new URL(req.url, `http://${req.headers.host}`);
  1423. } catch {
  1424. res.writeHead(400);
  1425. return res.end('bad url');
  1426. }
  1427. const pathname = parsedUrl.pathname;
  1428. const query = Object.fromEntries(parsedUrl.searchParams);
  1429. const respond500 = (e) => sendJson(res, 500, { error: e.message || String(e) });
  1430. if (req.method === 'GET' && pathname === '/api/default-root') {
  1431. return sendJson(res, 200, { root: getWorkspaceRoot() });
  1432. }
  1433. if (req.method === 'GET' && pathname === '/api/session') {
  1434. return sendJson(res, 200, session);
  1435. }
  1436. if (req.method === 'POST' && pathname === '/api/session') {
  1437. return readBody(req)
  1438. .then((body) => {
  1439. session.cookie = String((body && body.cookie) || '');
  1440. saveSession();
  1441. pushSystemLog('采集 Cookie 已更新', 'success');
  1442. sendJson(res, 200, { ok: true });
  1443. })
  1444. .catch(respond500);
  1445. }
  1446. if (req.method === 'GET' && pathname === '/api/shops') {
  1447. const encodedRoot = parsedUrl.searchParams.get('root');
  1448. const root = encodedRoot ? Buffer.from(encodedRoot, 'base64url').toString('utf8') : '';
  1449. return handleShopsList(root, res);
  1450. }
  1451. if (req.method === 'POST' && pathname === '/api/shops/manual') {
  1452. return readBody(req).then((body) => handleShopsManual(body, res)).catch(respond500);
  1453. }
  1454. if (req.method === 'POST' && pathname === '/api/crawl/start') {
  1455. return readBody(req).then((body) => startCrawl(body, res)).catch(respond500);
  1456. }
  1457. if (req.method === 'POST' && pathname === '/api/crawl/stop') {
  1458. return stopCrawl(res);
  1459. }
  1460. if (req.method === 'GET' && pathname === '/api/crawl/status') {
  1461. return sendJson(res, 200, crawlState);
  1462. }
  1463. if (req.method === 'GET' && pathname === '/api/logs') {
  1464. return sendJson(res, 200, { logs: getMergedLogs() });
  1465. }
  1466. if (req.method === 'POST' && pathname === '/api/logs/clear') {
  1467. crawlState.log = [];
  1468. systemLogs.length = 0;
  1469. pushSystemLog('日志已清空', 'warn');
  1470. return sendJson(res, 200, { ok: true });
  1471. }
  1472. if (req.method === 'GET' && pathname === '/api/models') {
  1473. return sendJson(res, 200, { models: MODELS, default: config.model });
  1474. }
  1475. if (req.method === 'GET' && pathname === '/api/settings') {
  1476. return sendJson(res, 200, {
  1477. apiKey: config.apiKey ? config.apiKey.slice(0, 8) + '••••••••' : '',
  1478. apiBase: config.apiBase,
  1479. model: config.model,
  1480. rootDir: getWorkspaceRoot(),
  1481. pageSize: config.pageSize,
  1482. delayMs: config.delayMs,
  1483. cookie: session.cookie,
  1484. port: config.port,
  1485. });
  1486. }
  1487. if (req.method === 'POST' && pathname === '/api/settings') {
  1488. return readBody(req).then((body) => {
  1489. const previousApiKey = config.apiKey;
  1490. const previousCookie = session.cookie;
  1491. if (body.apiKey && !body.apiKey.includes('••••')) config.apiKey = body.apiKey;
  1492. if (body.model && MODEL_IDS.has(body.model)) config.model = body.model;
  1493. if (body.rootDir) {
  1494. const rootDir = path.resolve(String(body.rootDir).trim());
  1495. if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
  1496. return sendJson(res, 400, { error: '输出根目录不存在: ' + rootDir });
  1497. }
  1498. config.rootDir = rootDir;
  1499. }
  1500. if (body.pageSize !== undefined) {
  1501. const pageSize = Number(body.pageSize);
  1502. if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 200) {
  1503. return sendJson(res, 400, { error: '每页条数必须为 1-200 的整数' });
  1504. }
  1505. config.pageSize = pageSize;
  1506. }
  1507. if (body.delayMs !== undefined) {
  1508. const delayMs = Number(body.delayMs);
  1509. if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > 60000) {
  1510. return sendJson(res, 400, { error: '间隔必须为 0-60000 毫秒' });
  1511. }
  1512. config.delayMs = delayMs;
  1513. }
  1514. saveConfig();
  1515. if (body.cookie !== undefined) {
  1516. session.cookie = body.cookie;
  1517. saveSession();
  1518. }
  1519. pushSystemLog(
  1520. `系统设置已保存:模型=${config.model},根目录=${config.rootDir},每页=${config.pageSize},间隔=${config.delayMs}ms` +
  1521. (previousApiKey !== config.apiKey ? ',API Key 已更新' : '') +
  1522. (body.cookie !== undefined && previousCookie !== session.cookie ? ',Cookie 已更新' : ''),
  1523. 'success'
  1524. );
  1525. sendJson(res, 200, { ok: true });
  1526. }).catch(respond500);
  1527. }
  1528. if (req.method === 'GET' && pathname === '/api/scan') {
  1529. try {
  1530. return handleScan(query, res);
  1531. } catch (e) {
  1532. return respond500(e);
  1533. }
  1534. }
  1535. if (req.method === 'GET' && pathname === '/api/creations') {
  1536. try {
  1537. return handleCreations(query, res);
  1538. } catch (e) {
  1539. return respond500(e);
  1540. }
  1541. }
  1542. if (req.method === 'GET' && pathname === '/files') {
  1543. try {
  1544. return handleFiles(query, res);
  1545. } catch (e) {
  1546. return respond500(e);
  1547. }
  1548. }
  1549. if (req.method === 'POST' && pathname === '/api/generate/brand') {
  1550. return readBody(req).then((body) => handleGenerateBrand(body, res)).catch(respond500);
  1551. }
  1552. if (req.method === 'POST' && pathname === '/api/generate/dish') {
  1553. return readBody(req).then((body) => handleGenerateDish(body, res)).catch(respond500);
  1554. }
  1555. if (req.method === 'GET' && pathname.startsWith('/api/job/')) {
  1556. try {
  1557. return handleJob(pathname, res);
  1558. } catch (e) {
  1559. return respond500(e);
  1560. }
  1561. }
  1562. if (req.method === 'POST' && pathname === '/api/save-config') {
  1563. return readBody(req).then((body) => handleSaveConfig(body, res)).catch(respond500);
  1564. }
  1565. if (req.method === 'POST' && pathname === '/api/save-poster-canvas') {
  1566. return readBody(req).then((body) => handleSavePosterCanvas(body, res)).catch(respond500);
  1567. }
  1568. if (req.method === 'POST' && pathname === '/api/open-folder') {
  1569. return readBody(req).then((body) => {
  1570. const dir = body.dir || path.join(body.root || getWorkspaceRoot(), body.folderName || '', '_生成图片');
  1571. const fallbackDir = body.dir ? null : path.join(body.root || getWorkspaceRoot(), body.folderName || '');
  1572. const targetDir = fs.existsSync(dir) ? dir : (fallbackDir && fs.existsSync(fallbackDir) ? fallbackDir : null);
  1573. if (!targetDir) return sendJson(res, 400, { error: '目录不存在: ' + dir });
  1574. const command = process.platform === 'win32' ? 'explorer' : process.platform === 'darwin' ? 'open' : 'xdg-open';
  1575. execFile(command, [targetDir], () => {});
  1576. sendJson(res, 200, { ok: true, opened: targetDir });
  1577. }).catch(respond500);
  1578. }
  1579. return serveStatic(pathname, res);
  1580. });
  1581. server.listen(config.port, () => {
  1582. const url = `http://localhost:${config.port}`;
  1583. pushSystemLog(`服务已启动:${url}`, 'success');
  1584. console.log(`门店装修工具已启动: ${url}`);
  1585. // "start" is a cmd.exe builtin (not a standalone executable), so it must be run via cmd /c;
  1586. // the empty "" argument is the window-title placeholder start expects before the URL.
  1587. execFile('cmd', ['/c', 'start', '', url], () => {});
  1588. });