context.js 9.1 KB

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