context.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. 'use strict';
  2. // 共享状态装配:config / session / 手动店铺 / workspace 路径守卫 / 日志。
  3. // 由 server.js 在启动时调用一次 createContext(),得到的 ctx 贯穿所有服务与路由。
  4. // 语义与拆分前一致:config 为同一个可变对象;getWorkspaceRoot() 每次重读 config.rootDir。
  5. const fs = require('fs');
  6. const path = require('path');
  7. const ROOT_DIR = path.resolve(__dirname, '..');
  8. const PUBLIC_DIR = path.join(ROOT_DIR, 'public');
  9. const CONFIG_PATH = path.join(ROOT_DIR, 'config.json');
  10. const CONFIG_EXAMPLE_PATH = path.join(ROOT_DIR, 'config.example.json');
  11. const SESSION_PATH = path.join(ROOT_DIR, 'session.json');
  12. const MANUAL_SHOPS_PATH = path.join(ROOT_DIR, 'manual-shops.json');
  13. const CONFIG_DEFAULTS = {
  14. port: 5177,
  15. apiKey: '',
  16. apiBase: 'https://api.lk888.ai',
  17. model: 'gpt-image-2',
  18. maxConcurrentJobs: 4,
  19. pageSize: 50,
  20. delayMs: 300,
  21. requestTimeoutMs: 20000,
  22. chatModel: '',
  23. chatApiBase: '',
  24. chatApiKey: '',
  25. accessToken: '',
  26. // HTTP 访问日志:true 时在控制台打印每个请求(5xx 与超过 1s 的慢请求始终打印)
  27. httpLog: false,
  28. // 经营数据每日自动同步(商家客户端在线时自动补昨日数据),默认关闭
  29. autoSync: { enabled: false, time: '06:00' },
  30. };
  31. function writeConfigFile(cfg) {
  32. const temp = CONFIG_PATH + '.tmp';
  33. fs.writeFileSync(temp, JSON.stringify(cfg, null, 2), 'utf8');
  34. fs.renameSync(temp, CONFIG_PATH);
  35. }
  36. // 缺失/损坏时自动用模板(或内置默认)在本机生成新的 config.json —— 分发包开箱即用
  37. function loadConfig() {
  38. try {
  39. return { ...CONFIG_DEFAULTS, ...JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) };
  40. } catch (e) {
  41. if (e.code !== 'ENOENT') {
  42. console.warn(`config.json 解析失败(${e.message || e}),已改用默认配置;保存设置后会重建该文件。`);
  43. }
  44. let seeded = {};
  45. try { seeded = JSON.parse(fs.readFileSync(CONFIG_EXAMPLE_PATH, 'utf8')); } catch { /* 无模板则用内置默认 */ }
  46. const cfg = { ...CONFIG_DEFAULTS, ...seeded };
  47. try {
  48. writeConfigFile(cfg);
  49. console.log('已生成本机默认 config.json —— 请在「系统设置」中填写你自己的 API Key。');
  50. } catch { /* 只读目录等场景忽略 */ }
  51. return cfg;
  52. }
  53. }
  54. const MODELS = [
  55. { id: 'gpt-image-2', label: 'GPT Image 2(默认)' },
  56. { id: 'gpt-image-2-guan', label: 'GPT Image 2 官转' },
  57. { id: 'doubao-seedream-5-0-pro-260628', label: '豆包 Seedream 5.0 Pro' },
  58. { id: 'doubao-seedream-5-0-260128', label: '即梦 5.0(Seedream 5.0)' },
  59. { id: 'doubao-seedream-4-5-251128', label: '即梦 4.5(Seedream 4.5)' },
  60. { id: 'wan2.6-image', label: '通义万相 wan2.6-image' },
  61. ];
  62. const MODEL_IDS = new Set(MODELS.map((m) => m.id));
  63. // These seedream variants don't support the '1K' tier the UI's size dropdown offers by
  64. // default (doubao-seedream-4-5-251128: 2K/4K only; doubao-seedream-5-0-260128: 2K/3K only) -
  65. // map it up to '2K' rather than sending an invalid enum value.
  66. const NO_1K_SUPPORT = new Set(['doubao-seedream-4-5-251128', 'doubao-seedream-5-0-260128']);
  67. // ---------- workspace 路径守卫 ----------
  68. function createWorkspaceService(config) {
  69. const WORKSPACE_ROOT = path.join(path.dirname(ROOT_DIR), 'workspace');
  70. function getWorkspaceRoot() {
  71. const configuredRoot = String(config.rootDir || WORKSPACE_ROOT).trim() || WORKSPACE_ROOT;
  72. return path.resolve(configuredRoot);
  73. }
  74. function isWorkspaceRoot(candidate) {
  75. try {
  76. return !!candidate && path.resolve(String(candidate)) === getWorkspaceRoot();
  77. } catch {
  78. return false;
  79. }
  80. }
  81. function isWorkspacePath(candidate) {
  82. try {
  83. const resolved = path.resolve(String(candidate));
  84. const root = getWorkspaceRoot();
  85. return resolved === root || resolved.startsWith(root + path.sep);
  86. } catch {
  87. return false;
  88. }
  89. }
  90. function safeShopDir(root, folderName) {
  91. if (!isWorkspaceRoot(root) || typeof folderName !== 'string' ||
  92. !folderName || folderName === '.' || folderName === '..' ||
  93. folderName.includes('/') || folderName.includes('\\')) return null;
  94. const rootDir = path.resolve(root);
  95. const shopDir = path.resolve(rootDir, folderName);
  96. return shopDir.startsWith(rootDir + path.sep) ? shopDir : null;
  97. }
  98. return { WORKSPACE_ROOT, getWorkspaceRoot, isWorkspaceRoot, isWorkspacePath, safeShopDir };
  99. }
  100. // ---------- 采集 Cookie 会话 ----------
  101. function extractCookieValue(cookie, name) {
  102. const match = String(cookie || '').match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
  103. if (!match) return '';
  104. try { return decodeURIComponent(match[1]); } catch { return match[1]; }
  105. }
  106. function createSessionService() {
  107. const session = { cookie: '' };
  108. function loadSession() {
  109. try {
  110. const saved = JSON.parse(fs.readFileSync(SESSION_PATH, 'utf8'));
  111. session.cookie = String(saved.cookie || '');
  112. } catch { /* no saved session */ }
  113. }
  114. function saveSession() {
  115. fs.writeFileSync(SESSION_PATH, JSON.stringify(session, null, 2), 'utf8');
  116. }
  117. function getKsid() { return extractCookieValue(session.cookie, 'ksid'); }
  118. loadSession();
  119. return {
  120. get cookie() { return session.cookie; },
  121. set cookie(v) { session.cookie = v; },
  122. saveSession,
  123. getKsid,
  124. };
  125. }
  126. // ---------- 手动店铺清单 ----------
  127. function createShopsService() {
  128. let shopList = [];
  129. function loadManualShops() {
  130. try {
  131. const data = JSON.parse(fs.readFileSync(MANUAL_SHOPS_PATH, 'utf8'));
  132. if (data.version !== 1 || !Array.isArray(data.shops)) throw new Error('清单格式无效');
  133. const shopsById = new Map();
  134. for (const shop of data.shops) {
  135. if (!shop || !Number.isInteger(shop.shopId) || shop.shopId <= 0) continue;
  136. shopsById.set(shop.shopId, { shopId: shop.shopId, shopName: String(shop.shopName || shop.shopId), source: 'manual' });
  137. }
  138. shopList = Array.from(shopsById.values());
  139. } catch (e) {
  140. if (e.code !== 'ENOENT') console.warn(`读取手动店铺清单失败: ${e.message || e}`);
  141. }
  142. }
  143. function saveManualShops(shops) {
  144. const temp = `${MANUAL_SHOPS_PATH}.${process.pid}.tmp`;
  145. fs.writeFileSync(temp, JSON.stringify({ version: 1, shops }, null, 2), 'utf8');
  146. fs.renameSync(temp, MANUAL_SHOPS_PATH);
  147. }
  148. function mergeShops(newOnes) {
  149. const shopsById = new Map(shopList.map((shop) => [shop.shopId, shop]));
  150. for (const shop of newOnes) shopsById.set(shop.shopId, shop);
  151. return Array.from(shopsById.values());
  152. }
  153. loadManualShops();
  154. return {
  155. getList: () => shopList,
  156. setList: (v) => { shopList = v; },
  157. mergeShops,
  158. saveManualShops,
  159. };
  160. }
  161. // ---------- 日志(系统日志 + 统一序号;采集任务日志由 crawl 服务持有,这里负责合并) ----------
  162. function createLogsService() {
  163. const systemLogs = [];
  164. let logSeq = 0;
  165. function detectLogLevel(message) {
  166. if (/失败|错误|异常|过期|error|鉴权/i.test(message)) return 'error';
  167. if (/停止|跳过|警告|warn/i.test(message)) return 'warn';
  168. if (/完成|成功|已保存|已启动|done/i.test(message)) return 'success';
  169. return 'info';
  170. }
  171. function createLogEntry(message, source = 'task', level = 'info') {
  172. const now = new Date();
  173. return {
  174. seq: ++logSeq,
  175. id: `${source}-${logSeq}`,
  176. source,
  177. level,
  178. time: now.toTimeString().slice(0, 8),
  179. timestamp: now.getTime(),
  180. message: String(message),
  181. };
  182. }
  183. function pushSystemLog(msg, level = 'info') {
  184. systemLogs.push(createLogEntry(msg, 'system', level));
  185. if (systemLogs.length > 500) systemLogs.shift();
  186. }
  187. function mergeLogs(crawlLog) {
  188. return [...crawlLog, ...systemLogs]
  189. .sort((a, b) => b.seq - a.seq)
  190. .slice(0, 500);
  191. }
  192. function clearAll(crawlLog) {
  193. if (crawlLog) crawlLog.length = 0;
  194. systemLogs.length = 0;
  195. }
  196. return { detectLogLevel, createLogEntry, pushSystemLog, mergeLogs, clearAll };
  197. }
  198. function createContext() {
  199. const config = loadConfig();
  200. // 局域网访问口令:环境变量可临时覆盖(不落盘),便于临时开启/测试
  201. if (process.env.ACCESS_TOKEN) config.accessToken = process.env.ACCESS_TOKEN;
  202. const workspace = createWorkspaceService(config);
  203. try {
  204. fs.mkdirSync(workspace.getWorkspaceRoot(), { recursive: true });
  205. } catch (e) {
  206. // 历史配置的 rootDir 在本机不可创建(权限/目录被移动)时不要崩,允许进设置页修改
  207. console.warn(`输出根目录不可用:${workspace.getWorkspaceRoot()}(${e.code || e.message})。请到「系统设置」修改输出根目录。`);
  208. }
  209. const session = createSessionService();
  210. const shops = createShopsService();
  211. const logs = createLogsService();
  212. function saveConfig() {
  213. writeConfigFile(config);
  214. }
  215. return {
  216. ROOT_DIR,
  217. PUBLIC_DIR,
  218. config,
  219. saveConfig,
  220. models: { MODELS, MODEL_IDS, NO_1K_SUPPORT },
  221. workspace,
  222. session,
  223. shops,
  224. logs,
  225. };
  226. }
  227. // 智能问数的对话模型:未在设置中选择时使用的兜底模型,以及「生图 Key 复用」推导。
  228. // 不放入 CONFIG_DEFAULTS —— 避免落盘到 config.json(保持拆分前的持久化内容)。
  229. const DEFAULT_CHAT_MODEL = 'deepseek-v4.1-flash';
  230. function makeChatCfg(ctx) {
  231. return {
  232. chatApiBase: ctx.config.chatApiBase || ctx.config.apiBase,
  233. chatApiKey: ctx.config.chatApiKey || ctx.config.apiKey,
  234. chatModel: ctx.config.chatModel || DEFAULT_CHAT_MODEL,
  235. };
  236. }
  237. module.exports = {
  238. createContext,
  239. CONFIG_DEFAULTS,
  240. MODELS,
  241. MODEL_IDS,
  242. NO_1K_SUPPORT,
  243. DEFAULT_CHAT_MODEL,
  244. makeChatCfg,
  245. };