server.js 17 KB

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