server.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 PORT = 3000;
  13. const SERVER_DIR = __dirname; // Server 目录
  14. const CLIENT_DIR = path.join(__dirname, '..', 'Client'); // Client 目录
  15. // MIME 类型映射
  16. const mimeTypes = {
  17. '.html': 'text/html',
  18. '.js': 'text/javascript',
  19. '.css': 'text/css',
  20. '.png': 'image/png',
  21. '.jpg': 'image/jpeg',
  22. '.gif': 'image/gif',
  23. '.json': 'application/json',
  24. };
  25. // 初始化 TextureReader
  26. const textureReader = new TextureReader(SERVER_DIR);
  27. // 初始化 DiskManager
  28. const diskManager = new DiskManager();
  29. // 创建 HTTP 服务器
  30. const server = http.createServer((req, res) => {
  31. const parsedUrl = url.parse(req.url, true);
  32. let pathname = parsedUrl.pathname;
  33. // API: 获取可用的文件夹列表
  34. if (pathname === '/api/folders') {
  35. textureReader.handleGetFolders(res);
  36. return;
  37. }
  38. // API: 获取指定文件夹中的帧文件列表
  39. if (pathname.startsWith('/api/frames/')) {
  40. const encodedPath = pathname.replace('/api/frames/', '');
  41. // 对路径的每一段进行解码
  42. const folderName = encodedPath.split('/').map(seg => decodeURIComponent(seg)).join('/');
  43. console.log('[Server] API请求帧列表, 原始:', encodedPath, '解码后:', folderName);
  44. textureReader.handleGetFrames(folderName, res);
  45. return;
  46. }
  47. // API: 打包 sprite sheet 为 ZIP
  48. if (pathname === '/api/pack') {
  49. ZipHandler.handlePackRequest(req, res);
  50. return;
  51. }
  52. // API: 角色替换(图生图)
  53. if (pathname === '/api/replace-character') {
  54. ReplaceCharacterHandler.handleReplaceRequest(req, res);
  55. return;
  56. }
  57. // API: Base64 图片抠图
  58. if (pathname === '/api/remove-background-base64') {
  59. RemoveBackgroundBase64.handleRequest(req, res);
  60. return;
  61. }
  62. // API: 网盘 - 获取文件列表
  63. if (pathname === '/api/disk/list') {
  64. diskManager.handleListRequest(req, res);
  65. return;
  66. }
  67. // API: 网盘 - 上传文件
  68. if (pathname === '/api/disk/upload') {
  69. diskManager.handleUploadRequest(req, res);
  70. return;
  71. }
  72. // API: 网盘 - 创建文件夹
  73. if (pathname === '/api/disk/create-folder') {
  74. diskManager.handleCreateFolderRequest(req, res);
  75. return;
  76. }
  77. // API: 网盘 - 下载文件
  78. if (pathname === '/api/disk/download') {
  79. diskManager.handleDownloadRequest(req, res);
  80. return;
  81. }
  82. // API: 网盘 - 重命名
  83. if (pathname === '/api/disk/rename') {
  84. diskManager.handleRenameRequest(req, res);
  85. return;
  86. }
  87. // API: 网盘 - 图片预览
  88. if (pathname === '/api/disk/preview') {
  89. diskManager.handlePreviewRequest(req, res);
  90. return;
  91. }
  92. // API: 网盘 - 移动文件/文件夹
  93. if (pathname === '/api/disk/move') {
  94. diskManager.handleMoveRequest(req, res);
  95. return;
  96. }
  97. // API: 网盘 - 复制文件/文件夹
  98. if (pathname === '/api/disk/copy') {
  99. diskManager.handleCopyRequest(req, res);
  100. return;
  101. }
  102. // API: 网盘 - 删除文件/文件夹
  103. if (pathname === '/api/disk/delete') {
  104. diskManager.handleDeleteRequest(req, res);
  105. return;
  106. }
  107. // API: 网盘 - 一键抠背景
  108. if (pathname === '/api/disk/remove-background') {
  109. diskManager.handleRemoveBackgroundRequest(req, res);
  110. return;
  111. }
  112. // API: 网盘 - 剪裁最小区域
  113. if (pathname === '/api/disk/crop-mini') {
  114. diskManager.handleCropMiniRequest(req, res);
  115. return;
  116. }
  117. // 默认首页
  118. if (pathname === '/') {
  119. pathname = '/index.html';
  120. }
  121. let filePath;
  122. // 如果是 texture 或 disk_data 相关的请求,从 server 目录提供
  123. if (pathname.startsWith('/texture/') || pathname.startsWith('/disk_data/')) {
  124. // 移除开头的 /,然后拼接路径
  125. const relativePath = pathname.substring(1); // 移除开头的 /
  126. // 解码 URL 编码的路径(处理中文、空格等特殊字符)
  127. const decodedPath = decodeURIComponent(relativePath);
  128. filePath = path.join(SERVER_DIR, decodedPath);
  129. } else {
  130. // 其他请求从 Client 目录提供
  131. const relativePath = pathname.startsWith('/') ? pathname.substring(1) : pathname;
  132. // 解码 URL 编码的路径
  133. const decodedPath = decodeURIComponent(relativePath);
  134. filePath = path.join(CLIENT_DIR, decodedPath);
  135. }
  136. // 检查文件是否存在并获取文件信息
  137. fs.stat(filePath, (statErr, stats) => {
  138. if (statErr) {
  139. // 文件不存在,返回 404(静默处理)
  140. res.writeHead(404, { 'Content-Type': 'text/plain' });
  141. res.end('');
  142. return;
  143. }
  144. // 获取文件扩展名
  145. const ext = path.extname(filePath).toLowerCase();
  146. const contentType = mimeTypes[ext] || 'application/octet-stream';
  147. // 构建响应头
  148. const headers = {
  149. 'Content-Type': contentType
  150. };
  151. // 如果是图片文件,添加缓存头
  152. if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
  153. // 设置长期缓存(1年)
  154. headers['Cache-Control'] = 'public, max-age=31536000, immutable';
  155. // 添加 ETag 用于缓存验证
  156. const etag = `"${stats.mtime.getTime()}-${stats.size}"`;
  157. headers['ETag'] = etag;
  158. // 检查客户端是否发送了 If-None-Match 头(缓存验证)
  159. const ifNoneMatch = req.headers['if-none-match'];
  160. if (ifNoneMatch === etag) {
  161. // 文件未修改,返回 304 Not Modified
  162. res.writeHead(304, headers);
  163. res.end();
  164. return;
  165. }
  166. }
  167. // 读取文件
  168. fs.readFile(filePath, (readErr, data) => {
  169. if (readErr) {
  170. res.writeHead(500, { 'Content-Type': 'text/plain' });
  171. res.end('Internal Server Error');
  172. return;
  173. }
  174. // 返回文件
  175. res.writeHead(200, headers);
  176. res.end(data);
  177. });
  178. });
  179. });
  180. // 启动服务器
  181. server.listen(PORT, () => {
  182. console.log('========================================');
  183. console.log(' PNG 序列动画预览工具 - 服务器');
  184. console.log('========================================');
  185. console.log(`服务器运行在: http://localhost:${PORT}`);
  186. console.log(`图片资源路径: ${path.join(SERVER_DIR, 'disk_data')}`);
  187. console.log('========================================');
  188. console.log('按 Ctrl+C 或关闭此窗口停止服务器');
  189. console.log('');
  190. });
  191. // 优雅关闭处理
  192. function gracefulShutdown() {
  193. console.log('\n正在关闭服务器...');
  194. server.close(() => {
  195. console.log('服务器已关闭');
  196. process.exit(0);
  197. });
  198. }
  199. process.on('SIGINT', gracefulShutdown);
  200. process.on('SIGTERM', gracefulShutdown);
  201. // Windows 下处理窗口关闭事件
  202. if (process.platform === 'win32') {
  203. const readline = require('readline');
  204. const rl = readline.createInterface({
  205. input: process.stdin,
  206. output: process.stdout
  207. });
  208. rl.on('SIGINT', () => {
  209. process.emit('SIGINT');
  210. });
  211. }