server.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. // PNG 序列动画预览工具 - 服务器主文件
  2. // 负责启动 HTTP 服务器和静态文件服务
  3. const http = require('http');
  4. const fs = require('fs');
  5. const path = require('path');
  6. const url = require('url');
  7. const TextureReader = require('./texture-reader');
  8. const ZipHandler = require('./zip');
  9. const DiskManager = require('./disk');
  10. const ReplaceCharacterHandler = require('./replace-character');
  11. const RemoveBackgroundBase64 = require('./remove-background-base64');
  12. const { handleLoginRequest, handleCheckPhoneRequest } = require('./login');
  13. const { handleRegisterRequest } = require('./register');
  14. const PORT = 3000;
  15. const SERVER_DIR = __dirname; // Server 目录
  16. const CLIENT_DIR = path.join(__dirname, '..', 'Client'); // Client 目录
  17. const ADMIN_DIR = path.join(__dirname, '..', 'admin'); // Admin 目录
  18. // MIME 类型映射
  19. const mimeTypes = {
  20. '.html': 'text/html',
  21. '.js': 'text/javascript',
  22. '.css': 'text/css',
  23. '.png': 'image/png',
  24. '.jpg': 'image/jpeg',
  25. '.gif': 'image/gif',
  26. '.json': 'application/json',
  27. };
  28. // 初始化 TextureReader
  29. const textureReader = new TextureReader(SERVER_DIR);
  30. // 初始化 DiskManager
  31. const diskManager = new DiskManager();
  32. // 初始化 StoreManager
  33. const StoreManager = require('./store/store');
  34. const storeManager = new StoreManager();
  35. // 初始化 Pay 模块
  36. const { handlePurchaseRequest, handleGetPurchaseHistory } = require('./pay');
  37. // 初始化 WebSocket 服务器(用于 matting-server 连接)
  38. require('./socket-connecting');
  39. // 创建 HTTP 服务器
  40. const server = http.createServer((req, res) => {
  41. const parsedUrl = url.parse(req.url, true);
  42. let pathname = parsedUrl.pathname;
  43. // 添加 CORS 头(允许 file:// 协议访问)
  44. res.setHeader('Access-Control-Allow-Origin', '*');
  45. res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  46. res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  47. // 处理 OPTIONS 预检请求
  48. if (req.method === 'OPTIONS') {
  49. res.writeHead(200);
  50. res.end();
  51. return;
  52. }
  53. // 调试日志:记录所有API请求
  54. if (pathname.startsWith('/api/')) {
  55. console.log(`[Server] ${req.method} ${pathname}`);
  56. }
  57. // API: 获取可用的文件夹列表
  58. if (pathname === '/api/folders') {
  59. textureReader.handleGetFolders(res);
  60. return;
  61. }
  62. // API: 获取指定文件夹中的帧文件列表
  63. if (pathname.startsWith('/api/frames/')) {
  64. const parsedUrl = url.parse(req.url, true);
  65. const encodedPath = pathname.replace('/api/frames/', '');
  66. // 对路径的每一段进行解码
  67. const folderName = encodedPath.split('/').map(seg => decodeURIComponent(seg)).join('/');
  68. const username = parsedUrl.query.username; // 从查询参数获取用户名
  69. console.log('[Server] API请求帧列表, 原始:', encodedPath, '解码后:', folderName, '用户名:', username);
  70. // 如果有用户名,尝试从用户网盘查找
  71. if (username) {
  72. const { handleGetUserFrames } = require('./disk');
  73. diskManager.handleGetUserFrames(username, folderName, res);
  74. } else {
  75. // 回退到旧的 TextureReader(兼容旧代码)
  76. textureReader.handleGetFrames(folderName, res);
  77. }
  78. return;
  79. }
  80. // API: 打包 sprite sheet 为 ZIP
  81. if (pathname === '/api/pack') {
  82. ZipHandler.handlePackRequest(req, res);
  83. return;
  84. }
  85. // API: 角色替换(图生图)- 旧版本,保留兼容
  86. if (pathname === '/api/replace-character') {
  87. ReplaceCharacterHandler.handleReplaceRequest(req, res);
  88. return;
  89. }
  90. // API: AI生图(队列版本)
  91. if (pathname === '/api/ai/generate') {
  92. const { handleAIRequest } = require('./ai-queue');
  93. handleAIRequest(req, res);
  94. return;
  95. }
  96. // API: AI生图重试(免费)
  97. if (pathname === '/api/ai/retry' && req.method === 'POST') {
  98. const { handleRetryRequest } = require('./ai-queue');
  99. handleRetryRequest(req, res);
  100. return;
  101. }
  102. // API: 获取AI生成的图片
  103. if (pathname === '/api/ai/image') {
  104. const parsedUrl = require('url').parse(req.url, true);
  105. const { username, id } = parsedUrl.query;
  106. if (!username || !id) {
  107. res.writeHead(400, { 'Content-Type': 'text/plain' });
  108. res.end('Missing parameters');
  109. return;
  110. }
  111. try {
  112. const fs = require('fs');
  113. const path = require('path');
  114. const usersDir = path.join(__dirname, 'users');
  115. const userDir = path.join(usersDir, username.toLowerCase());
  116. const aiDir = path.join(userDir, 'ai-images');
  117. const imagePath = path.join(aiDir, `${id}.png`);
  118. // 安全检查
  119. const normalizedPath = path.normalize(imagePath);
  120. const normalizedAiDir = path.normalize(aiDir);
  121. if (!normalizedPath.startsWith(normalizedAiDir)) {
  122. res.writeHead(403, { 'Content-Type': 'text/plain' });
  123. res.end('Access denied');
  124. return;
  125. }
  126. if (fs.existsSync(imagePath)) {
  127. const imageData = fs.readFileSync(imagePath);
  128. res.writeHead(200, {
  129. 'Content-Type': 'image/png',
  130. 'Access-Control-Allow-Origin': '*',
  131. 'Cache-Control': 'public, max-age=3600'
  132. });
  133. res.end(imageData);
  134. } else {
  135. res.writeHead(404, { 'Content-Type': 'text/plain' });
  136. res.end('Image not found');
  137. }
  138. } catch (error) {
  139. console.error('[Server] 获取AI图片失败:', error);
  140. res.writeHead(500, { 'Content-Type': 'text/plain' });
  141. res.end('Internal server error');
  142. }
  143. return;
  144. }
  145. // API: 获取AI生成预览图(原始texture)
  146. if (pathname === '/api/ai/preview') {
  147. const parsedUrl = require('url').parse(req.url, true);
  148. const { username, id } = parsedUrl.query;
  149. if (!username || !id) {
  150. res.writeHead(400, { 'Content-Type': 'text/plain' });
  151. res.end('Missing parameters');
  152. return;
  153. }
  154. try {
  155. const fs = require('fs');
  156. const path = require('path');
  157. const usersDir = path.join(__dirname, 'users');
  158. const userDir = path.join(usersDir, username.toLowerCase());
  159. const aiDir = path.join(userDir, 'ai-images');
  160. const imagePath = path.join(aiDir, `${id}_preview.png`);
  161. // 安全检查
  162. const normalizedPath = path.normalize(imagePath);
  163. const normalizedAiDir = path.normalize(aiDir);
  164. if (!normalizedPath.startsWith(normalizedAiDir)) {
  165. res.writeHead(403, { 'Content-Type': 'text/plain' });
  166. res.end('Access denied');
  167. return;
  168. }
  169. if (fs.existsSync(imagePath)) {
  170. const imageData = fs.readFileSync(imagePath);
  171. res.writeHead(200, {
  172. 'Content-Type': 'image/png',
  173. 'Access-Control-Allow-Origin': '*',
  174. 'Cache-Control': 'public, max-age=3600'
  175. });
  176. res.end(imageData);
  177. } else {
  178. res.writeHead(404, { 'Content-Type': 'text/plain' });
  179. res.end('Preview not found');
  180. }
  181. } catch (error) {
  182. console.error('[Server] 获取AI预览图失败:', error);
  183. res.writeHead(500, { 'Content-Type': 'text/plain' });
  184. res.end('Internal server error');
  185. }
  186. return;
  187. }
  188. // API: Base64 图片抠图
  189. if (pathname === '/api/remove-background-base64') {
  190. RemoveBackgroundBase64.handleRequest(req, res);
  191. return;
  192. }
  193. // API: 普通抠图(使用 image-matting.py)
  194. if (pathname === '/api/matting-normal') {
  195. const MattingNormal = require('./matting-normal');
  196. MattingNormal.handleRequest(req, res);
  197. return;
  198. }
  199. // API: VIP抠图(使用 BiRefNet)
  200. if (pathname === '/api/matting-vip') {
  201. const MattingVIP = require('./matting-vip');
  202. MattingVIP.handleRequest(req, res);
  203. return;
  204. }
  205. // API: VIP抠图队列(异步处理)
  206. if (pathname === '/api/vip-matting/queue') {
  207. const VIPMatting = require('./vip-matting');
  208. VIPMatting.handleQueueRequest(req, res);
  209. return;
  210. }
  211. // API: 网盘 - 获取文件列表
  212. if (pathname === '/api/disk/list') {
  213. diskManager.handleListRequest(req, res);
  214. return;
  215. }
  216. // API: 网盘 - 上传文件
  217. if (pathname === '/api/disk/upload') {
  218. diskManager.handleUploadRequest(req, res);
  219. return;
  220. }
  221. // API: 网盘 - 创建文件夹
  222. if (pathname === '/api/disk/create-folder') {
  223. diskManager.handleCreateFolderRequest(req, res);
  224. return;
  225. }
  226. // API: 网盘 - 下载文件
  227. if (pathname === '/api/disk/download') {
  228. diskManager.handleDownloadRequest(req, res);
  229. return;
  230. }
  231. // API: 网盘 - 重命名
  232. if (pathname === '/api/disk/rename') {
  233. diskManager.handleRenameRequest(req, res);
  234. return;
  235. }
  236. // API: 网盘 - 图片预览
  237. if (pathname === '/api/disk/preview') {
  238. diskManager.handlePreviewRequest(req, res);
  239. return;
  240. }
  241. // API: 网盘 - 移动文件/文件夹
  242. if (pathname === '/api/disk/move') {
  243. diskManager.handleMoveRequest(req, res);
  244. return;
  245. }
  246. // API: 网盘 - 复制文件/文件夹
  247. if (pathname === '/api/disk/copy') {
  248. diskManager.handleCopyRequest(req, res);
  249. return;
  250. }
  251. // API: 网盘 - 删除文件/文件夹
  252. if (pathname === '/api/disk/delete') {
  253. diskManager.handleDeleteRequest(req, res);
  254. return;
  255. }
  256. // API: 网盘 - 一键抠背景
  257. if (pathname === '/api/disk/remove-background') {
  258. diskManager.handleRemoveBackgroundRequest(req, res);
  259. return;
  260. }
  261. // API: 网盘 - 剪裁最小区域
  262. if (pathname === '/api/disk/crop-mini') {
  263. diskManager.handleCropMiniRequest(req, res);
  264. return;
  265. }
  266. // API: 用户注册
  267. if (pathname === '/api/register') {
  268. handleRegisterRequest(req, res);
  269. return;
  270. }
  271. // API: 用户登录
  272. if (pathname === '/api/login') {
  273. handleLoginRequest(req, res);
  274. return;
  275. }
  276. // API: 检查手机号是否存在
  277. if (pathname === '/api/check-phone') {
  278. handleCheckPhoneRequest(req, res);
  279. return;
  280. }
  281. // API: 获取用户点数
  282. if (pathname === '/api/user/points') {
  283. const { handleGetUserPoints } = require('./user');
  284. handleGetUserPoints(req, res);
  285. return;
  286. }
  287. // API: 扣除用户点数
  288. if (pathname === '/api/user/deduct-points' && req.method === 'POST') {
  289. const { handleDeductUserPoints } = require('./user');
  290. handleDeductUserPoints(req, res);
  291. return;
  292. }
  293. // API: 获取用户信息
  294. if (pathname === '/api/user/info') {
  295. const { handleGetUserInfo } = require('./user');
  296. handleGetUserInfo(req, res);
  297. return;
  298. }
  299. // API: 更新用户信息
  300. if (pathname === '/api/user/update') {
  301. const { handleUpdateUser } = require('./user');
  302. handleUpdateUser(req, res);
  303. return;
  304. }
  305. // API: 上传头像
  306. if (pathname === '/api/user/avatar') {
  307. const { handleUploadAvatar } = require('./user');
  308. handleUploadAvatar(req, res);
  309. return;
  310. }
  311. // API: 获取AI生图历史
  312. if (pathname === '/api/ai/history') {
  313. const { handleGetAIHistory } = require('./user');
  314. handleGetAIHistory(req, res);
  315. return;
  316. }
  317. // API: 充值
  318. if (pathname === '/api/recharge') {
  319. const { handleRecharge } = require('./user');
  320. handleRecharge(req, res);
  321. return;
  322. }
  323. // API: 管理后台 - 获取所有用户
  324. if (pathname === '/api/admin/users') {
  325. const { handleGetAllUsers } = require('./admin');
  326. handleGetAllUsers(req, res);
  327. return;
  328. }
  329. // API: 管理后台 - 更新用户
  330. if (pathname === '/api/admin/users/update') {
  331. const { handleAdminUpdateUser } = require('./admin');
  332. handleAdminUpdateUser(req, res);
  333. return;
  334. }
  335. // API: 管理后台 - 上传商店素材
  336. if (pathname === '/api/admin/store/upload') {
  337. const { handleAdminUploadStore } = require('./admin');
  338. handleAdminUploadStore(req, res);
  339. return;
  340. }
  341. // API: 管理后台 - 删除商店素材
  342. if (pathname === '/api/admin/store/delete') {
  343. console.log('[Server] 处理删除请求');
  344. const { handleAdminDeleteStore } = require('./admin');
  345. handleAdminDeleteStore(req, res);
  346. // 清除分类缓存(删除可能影响分类列表)
  347. storeManager.clearCategoriesCache();
  348. return;
  349. }
  350. // API: 管理后台 - 创建分类文件夹
  351. if (pathname === '/api/admin/store/create-folder') {
  352. const { handleAdminCreateFolder } = require('./admin');
  353. handleAdminCreateFolder(req, res);
  354. // 清除分类缓存
  355. storeManager.clearCategoriesCache();
  356. return;
  357. }
  358. // API: 管理后台 - 重命名商店素材
  359. if (pathname === '/api/admin/store/rename') {
  360. const { handleAdminRenameStore } = require('./admin');
  361. handleAdminRenameStore(req, res);
  362. // 清除分类缓存(重命名可能影响分类列表)
  363. storeManager.clearCategoriesCache();
  364. return;
  365. }
  366. // API: 管理后台 - 更新资源价格
  367. if (pathname === '/api/admin/store/update-price') {
  368. const { handleAdminUpdatePrice } = require('./admin');
  369. handleAdminUpdatePrice(req, res);
  370. // 清除价格缓存
  371. storeManager.clearPricesCache();
  372. return;
  373. }
  374. // API: 管理后台 - 获取货币设置
  375. if (pathname === '/api/admin/currency/settings' && req.method === 'GET') {
  376. const { handleGetCurrencySettings } = require('./admin');
  377. handleGetCurrencySettings(req, res);
  378. return;
  379. }
  380. // API: 管理后台 - 保存货币设置
  381. if (pathname === '/api/admin/currency/settings' && req.method === 'POST') {
  382. const { handleSaveCurrencySettings } = require('./admin');
  383. handleSaveCurrencySettings(req, res);
  384. return;
  385. }
  386. // API: 管理后台 - 获取商品定价设置
  387. if (pathname === '/api/admin/product-pricing/settings' && req.method === 'GET') {
  388. const { handleGetProductPricingSettings } = require('./admin');
  389. handleGetProductPricingSettings(req, res);
  390. return;
  391. }
  392. // API: 管理后台 - 保存商品定价设置
  393. if (pathname === '/api/admin/product-pricing/settings' && req.method === 'POST') {
  394. const { handleSaveProductPricingSettings } = require('./admin');
  395. handleSaveProductPricingSettings(req, res);
  396. return;
  397. }
  398. // API: 客户端 - 获取商品定价(用于显示价格)
  399. if (pathname === '/api/product-pricing' && req.method === 'GET') {
  400. const { handleGetProductPricingSettings } = require('./admin');
  401. handleGetProductPricingSettings(req, res);
  402. return;
  403. }
  404. // API: 管理后台 - 更新分类排序
  405. if (pathname === '/api/admin/store/update-order') {
  406. let body = '';
  407. req.on('data', chunk => { body += chunk.toString(); });
  408. req.on('end', async () => {
  409. try {
  410. const data = JSON.parse(body);
  411. const { order } = data;
  412. if (!order || !Array.isArray(order)) {
  413. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  414. res.end(JSON.stringify({ success: false, message: '缺少排序数据' }));
  415. return;
  416. }
  417. const success = await storeManager.saveCategoryOrder(order);
  418. if (success) {
  419. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  420. res.end(JSON.stringify({ success: true, message: '排序已保存' }));
  421. } else {
  422. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  423. res.end(JSON.stringify({ success: false, message: '保存排序失败' }));
  424. }
  425. } catch (error) {
  426. console.error('[Server] 更新分类排序失败:', error);
  427. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  428. res.end(JSON.stringify({ success: false, message: error.message }));
  429. }
  430. });
  431. return;
  432. }
  433. // API: 商店 - 获取分类列表
  434. if (pathname === '/api/store/categories') {
  435. storeManager.handleGetCategories(req, res);
  436. return;
  437. }
  438. // API: 商店 - 获取资源列表
  439. if (pathname === '/api/store/resources') {
  440. storeManager.handleGetResources(req, res);
  441. return;
  442. }
  443. // API: 商店 - 预览图
  444. if (pathname === '/api/store/preview') {
  445. storeManager.handlePreview(req, res);
  446. return;
  447. }
  448. // API: 商店 - 获取帧列表
  449. if (pathname === '/api/store/frames') {
  450. storeManager.handleGetFrames(req, res);
  451. return;
  452. }
  453. // API: 商店 - 获取帧图片
  454. if (pathname === '/api/store/frame') {
  455. storeManager.handleGetFrame(req, res);
  456. return;
  457. }
  458. // API: 支付 - 购买资源
  459. if (pathname === '/api/pay/purchase') {
  460. handlePurchaseRequest(req, res);
  461. return;
  462. }
  463. // API: 支付 - 检查资源是否存在
  464. if (pathname === '/api/pay/check-resource') {
  465. const { handleCheckResourceRequest } = require('./pay');
  466. handleCheckResourceRequest(req, res);
  467. return;
  468. }
  469. // API: 获取用户购买记录
  470. if (pathname === '/api/pay/purchase-history' && req.method === 'GET') {
  471. handleGetPurchaseHistory(req, res);
  472. return;
  473. }
  474. // API: 获取默认头像列表
  475. if (pathname === '/api/avatars/default') {
  476. const fs = require('fs');
  477. const avatarDir = path.join(__dirname, 'avatar');
  478. fs.readdir(avatarDir, (err, files) => {
  479. if (err) {
  480. res.writeHead(500, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
  481. res.end(JSON.stringify({ success: false, error: '读取头像目录失败' }));
  482. return;
  483. }
  484. // 过滤出图片文件
  485. const imageFiles = files.filter(file => {
  486. const ext = path.extname(file).toLowerCase();
  487. return ['.png', '.jpg', '.jpeg', '.gif'].includes(ext);
  488. });
  489. // 返回头像文件名列表
  490. res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
  491. res.end(JSON.stringify({ success: true, avatars: imageFiles }));
  492. });
  493. return;
  494. }
  495. // 处理 favicon.ico 请求,重定向到 static/favicon.png
  496. if (pathname === '/favicon.ico') {
  497. pathname = '/static/favicon.png';
  498. }
  499. // 默认首页 - 跳转到管理后台
  500. if (pathname === '/') {
  501. res.writeHead(302, { 'Location': '/admin/index.html' });
  502. res.end();
  503. return;
  504. }
  505. // /admin 路径也跳转到管理后台
  506. if (pathname === '/admin' || pathname === '/admin/') {
  507. res.writeHead(302, { 'Location': '/admin/index.html' });
  508. res.end();
  509. return;
  510. }
  511. let filePath;
  512. // 如果是 admin 相关的请求,从 admin 目录提供
  513. if (pathname.startsWith('/admin/')) {
  514. // 移除开头的 /,然后拼接路径
  515. const relativePath = pathname.substring(1); // 移除开头的 /
  516. // 解码 URL 编码的路径(处理中文、空格等特殊字符)
  517. const decodedPath = decodeURIComponent(relativePath);
  518. filePath = path.join(ADMIN_DIR, decodedPath.replace(/^admin\//, ''));
  519. } else if (pathname.startsWith('/texture/') || pathname.startsWith('/avatar/') || pathname.startsWith('/users/')) {
  520. // 如果是 texture、avatar 或 users 相关的请求,从 server 目录提供
  521. // 移除开头的 /,然后拼接路径
  522. const relativePath = pathname.substring(1); // 移除开头的 /
  523. // 解码 URL 编码的路径(处理中文、空格等特殊字符)
  524. const decodedPath = decodeURIComponent(relativePath);
  525. filePath = path.join(SERVER_DIR, decodedPath);
  526. } else {
  527. // 其他请求从 Client 目录提供
  528. const relativePath = pathname.startsWith('/') ? pathname.substring(1) : pathname;
  529. // 解码 URL 编码的路径
  530. const decodedPath = decodeURIComponent(relativePath);
  531. filePath = path.join(CLIENT_DIR, decodedPath);
  532. }
  533. // 检查文件是否存在并获取文件信息
  534. fs.stat(filePath, (statErr, stats) => {
  535. if (statErr) {
  536. // 文件不存在,返回 404(静默处理)
  537. res.writeHead(404, { 'Content-Type': 'text/plain' });
  538. res.end('');
  539. return;
  540. }
  541. // 获取文件扩展名
  542. const ext = path.extname(filePath).toLowerCase();
  543. const contentType = mimeTypes[ext] || 'application/octet-stream';
  544. // 构建响应头
  545. const headers = {
  546. 'Content-Type': contentType
  547. };
  548. // 如果是图片文件,添加缓存头
  549. if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
  550. // 设置长期缓存(1年)
  551. headers['Cache-Control'] = 'public, max-age=31536000, immutable';
  552. // 添加 ETag 用于缓存验证
  553. const etag = `"${stats.mtime.getTime()}-${stats.size}"`;
  554. headers['ETag'] = etag;
  555. // 检查客户端是否发送了 If-None-Match 头(缓存验证)
  556. const ifNoneMatch = req.headers['if-none-match'];
  557. if (ifNoneMatch === etag) {
  558. // 文件未修改,返回 304 Not Modified
  559. res.writeHead(304, headers);
  560. res.end();
  561. return;
  562. }
  563. }
  564. // 读取文件
  565. fs.readFile(filePath, (readErr, data) => {
  566. if (readErr) {
  567. res.writeHead(500, { 'Content-Type': 'text/plain' });
  568. res.end('Internal Server Error');
  569. return;
  570. }
  571. // 返回文件
  572. res.writeHead(200, headers);
  573. res.end(data);
  574. });
  575. });
  576. });
  577. // 启动服务器
  578. server.listen(PORT, () => {
  579. // 立即清屏(使用 ANSI 转义序列)
  580. process.stdout.write('\x1B[2J\x1B[0f');
  581. // 使用 setTimeout 延迟输出,确保批处理脚本的输出先完成
  582. setTimeout(() => {
  583. console.log('========================================');
  584. console.log(' PNG 序列动画预览工具 - 服务器');
  585. console.log('========================================');
  586. console.log(`服务器运行在: http://localhost:${PORT}`);
  587. console.log(`用户数据路径: ${path.join(SERVER_DIR, 'users')}`);
  588. console.log('========================================');
  589. console.log('按 Ctrl+C 或关闭此窗口停止服务器');
  590. console.log('');
  591. }, 1000); // 延迟 1000ms 输出,避免与批处理脚本输出重叠
  592. });
  593. // 优雅关闭处理
  594. function gracefulShutdown() {
  595. console.log('\n正在关闭服务器...');
  596. server.close(() => {
  597. console.log('服务器已关闭');
  598. process.exit(0);
  599. });
  600. }
  601. process.on('SIGINT', gracefulShutdown);
  602. process.on('SIGTERM', gracefulShutdown);
  603. // Windows 下处理窗口关闭事件
  604. if (process.platform === 'win32') {
  605. const readline = require('readline');
  606. const rl = readline.createInterface({
  607. input: process.stdin,
  608. output: process.stdout
  609. });
  610. rl.on('SIGINT', () => {
  611. process.emit('SIGINT');
  612. });
  613. }