context.js 9.0 KB

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