context.js 9.9 KB

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