disk.js 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766
  1. // 网盘管理系统 - 服务端逻辑
  2. const fs = require('fs');
  3. const path = require('path');
  4. const { promisify } = require('util');
  5. const { spawn } = require('child_process');
  6. const formidable = require('formidable');
  7. const mkdir = promisify(fs.mkdir);
  8. const readdir = promisify(fs.readdir);
  9. const stat = promisify(fs.stat);
  10. const access = promisify(fs.access);
  11. const copyFile = promisify(fs.copyFile);
  12. const rmdir = promisify(fs.rmdir);
  13. const unlink = promisify(fs.unlink);
  14. class DiskManager {
  15. constructor() {
  16. // 用户数据根目录
  17. this.usersDir = path.join(__dirname, 'users');
  18. this.tempDir = path.join(__dirname, 'temp');
  19. this.pythonDir = path.join(__dirname, 'python');
  20. }
  21. // 根据用户名获取用户的数据目录
  22. getUserRootDir(username) {
  23. if (!username) {
  24. throw new Error('用户名不能为空');
  25. }
  26. // 用户名转换为小写,确保一致性
  27. const normalizedUsername = username.toLowerCase();
  28. return path.join(this.usersDir, normalizedUsername, 'disk_data');
  29. }
  30. // 确保用户目录存在
  31. async ensureUserDir(username) {
  32. const userRootDir = this.getUserRootDir(username);
  33. try {
  34. await access(userRootDir);
  35. } catch (error) {
  36. await mkdir(userRootDir, { recursive: true });
  37. console.log('创建用户disk_data目录:', userRootDir);
  38. }
  39. }
  40. // 从请求中获取用户名(支持查询参数和请求体)
  41. getUsernameFromRequest(req, fields = null) {
  42. // 先尝试从查询参数获取
  43. const url = new URL(req.url, `http://${req.headers.host}`);
  44. let username = url.searchParams.get('username');
  45. // 如果查询参数没有,尝试从请求体(fields)获取
  46. if (!username && fields) {
  47. username = Array.isArray(fields.username) ? fields.username[0] : (fields.username || null);
  48. }
  49. return username;
  50. }
  51. // 获取Python命令(尝试python或python3)
  52. async getPythonCommand() {
  53. return new Promise((resolve) => {
  54. const python = spawn('python', ['--version']);
  55. python.on('close', (code) => {
  56. if (code === 0) {
  57. resolve('python');
  58. } else {
  59. const python3 = spawn('python3', ['--version']);
  60. python3.on('close', (code) => {
  61. resolve(code === 0 ? 'python3' : null);
  62. });
  63. }
  64. });
  65. python.on('error', () => {
  66. const python3 = spawn('python3', ['--version']);
  67. python3.on('close', (code) => {
  68. resolve(code === 0 ? 'python3' : null);
  69. });
  70. python3.on('error', () => resolve(null));
  71. });
  72. });
  73. }
  74. // 调用Python抠图脚本
  75. async runImageMatting(inputFolder, outputFolder, onProgress) {
  76. const pythonCmd = await this.getPythonCommand();
  77. if (!pythonCmd) {
  78. throw new Error('未找到Python环境,请安装Python 3.7+');
  79. }
  80. const pythonExe = path.join(this.pythonDir, 'venv', 'Scripts', 'python.exe');
  81. const scriptPath = path.join(this.pythonDir, 'rembg-matting.py');
  82. // 检查是否使用虚拟环境
  83. const usePython = await new Promise((resolve) => {
  84. fs.access(pythonExe, fs.constants.F_OK, (err) => {
  85. resolve(err ? pythonCmd : pythonExe);
  86. });
  87. });
  88. return new Promise((resolve, reject) => {
  89. console.log('\n' + '='.repeat(70));
  90. console.log('【Python】🚀 启动AI抠图进程');
  91. console.log('='.repeat(70));
  92. console.log('【Python】命令:', usePython);
  93. console.log('【Python】脚本:', scriptPath);
  94. console.log('【Python】输入文件夹:', inputFolder);
  95. console.log('【Python】输出文件夹:', outputFolder);
  96. console.log('='.repeat(70) + '\n');
  97. // 使用 -u 参数让Python输出无缓冲
  98. const python = spawn(usePython, ['-u', scriptPath, inputFolder, outputFolder]);
  99. console.log('【Python】进程已启动,PID:', python.pid);
  100. let stdout = '';
  101. let stderr = '';
  102. let processed = 0;
  103. python.stdout.on('data', (data) => {
  104. const output = data.toString();
  105. stdout += output;
  106. // 分行打印,保持格式
  107. const lines = output.split('\n');
  108. lines.forEach(line => {
  109. if (line.trim()) {
  110. console.log(`【Python】抠图: ${line}`);
  111. // 捕获进度信息: PROGRESS: 1/22
  112. const progressMatch = line.match(/PROGRESS:\s*(\d+)\/(\d+)/);
  113. if (progressMatch) {
  114. const current = parseInt(progressMatch[1], 10);
  115. const total = parseInt(progressMatch[2], 10);
  116. console.log(`【Python】进度: ${current}/${total} (${Math.round(current/total*100)}%)`);
  117. // 调用进度回调
  118. if (onProgress) {
  119. onProgress(current, total);
  120. }
  121. }
  122. }
  123. });
  124. const successMatch = output.match(/成功:?\s*(\d+)|成功\s*(\d+)|Success:\s*(\d+)/);
  125. if (successMatch) {
  126. processed = parseInt(successMatch[1] || successMatch[2] || successMatch[3], 10);
  127. }
  128. });
  129. python.stderr.on('data', (data) => {
  130. const error = data.toString();
  131. stderr += error;
  132. // 实时打印stderr
  133. const lines = error.split('\n');
  134. lines.forEach(line => {
  135. if (line.trim()) {
  136. console.error(`【Python】抠图错误: ${line}`);
  137. }
  138. });
  139. });
  140. python.on('close', (code) => {
  141. console.log('\n' + '='.repeat(70));
  142. console.log(`【Python】抠图进程结束,退出码: ${code}`);
  143. if (code === 0) {
  144. console.log(`【Python】✅ 抠图成功!处理了 ${processed} 张图片`);
  145. console.log('='.repeat(70) + '\n');
  146. resolve({ success: true, processed, message: '抠图完成' });
  147. } else {
  148. console.error(`【Python】❌ 抠图失败,退出码: ${code}`);
  149. if (stderr) console.error(`【Python】错误详情:\n${stderr}`);
  150. console.log('='.repeat(70) + '\n');
  151. reject(new Error(`抠图失败,退出码: ${code}\n${stderr}`));
  152. }
  153. });
  154. python.on('error', (error) => {
  155. console.error(`【Python】❌ 启动进程失败:`, error);
  156. reject(new Error(`启动Python进程失败: ${error.message}`));
  157. });
  158. });
  159. }
  160. // 调用Python裁剪脚本
  161. async runCutMiniSize(inputFolder, outputFolder, onProgress) {
  162. const pythonCmd = await this.getPythonCommand();
  163. if (!pythonCmd) {
  164. throw new Error('未找到Python环境,请安装Python 3.7+');
  165. }
  166. const pythonExe = path.join(this.pythonDir, 'venv', 'Scripts', 'python.exe');
  167. const scriptPath = path.join(this.pythonDir, 'cut-mini-size.py');
  168. const usePython = await new Promise((resolve) => {
  169. fs.access(pythonExe, fs.constants.F_OK, (err) => {
  170. resolve(err ? pythonCmd : pythonExe);
  171. });
  172. });
  173. return new Promise((resolve, reject) => {
  174. console.log('\n' + '='.repeat(70));
  175. console.log('【Python】✂️ 启动智能裁剪进程');
  176. console.log('='.repeat(70));
  177. console.log('【Python】命令:', usePython);
  178. console.log('【Python】脚本:', scriptPath);
  179. console.log('【Python】输入文件夹:', inputFolder);
  180. console.log('【Python】输出文件夹:', outputFolder);
  181. console.log('='.repeat(70) + '\n');
  182. // 使用 -u 参数让Python输出无缓冲
  183. const python = spawn(usePython, ['-u', scriptPath, inputFolder, outputFolder]);
  184. console.log('【Python】进程已启动,PID:', python.pid);
  185. let stdout = '';
  186. let stderr = '';
  187. let processed = 0;
  188. let width = 0;
  189. let height = 0;
  190. python.stdout.on('data', (data) => {
  191. const output = data.toString();
  192. stdout += output;
  193. // 分行打印,保持格式
  194. const lines = output.split('\n');
  195. lines.forEach(line => {
  196. if (line.trim()) {
  197. console.log(`【Python】裁剪: ${line}`);
  198. // 捕获进度信息: PROGRESS: 1/22
  199. const progressMatch = line.match(/PROGRESS:\s*(\d+)\/(\d+)/);
  200. if (progressMatch) {
  201. const current = parseInt(progressMatch[1], 10);
  202. const total = parseInt(progressMatch[2], 10);
  203. console.log(`【Python】进度: ${current}/${total} (${Math.round(current/total*100)}%)`);
  204. // 调用进度回调
  205. if (onProgress) {
  206. onProgress(current, total);
  207. }
  208. }
  209. }
  210. });
  211. const successMatch = output.match(/成功:?\s*(\d+)|成功\s*(\d+)|Success:\s*(\d+)/);
  212. if (successMatch) {
  213. processed = parseInt(successMatch[1] || successMatch[2] || successMatch[3], 10);
  214. }
  215. const sizeMatch = output.match(/width=(\d+).*height=(\d+)/);
  216. if (sizeMatch) {
  217. width = parseInt(sizeMatch[1], 10);
  218. height = parseInt(sizeMatch[2], 10);
  219. }
  220. });
  221. python.stderr.on('data', (data) => {
  222. const error = data.toString();
  223. stderr += error;
  224. // 实时打印stderr
  225. const lines = error.split('\n');
  226. lines.forEach(line => {
  227. if (line.trim()) {
  228. console.error(`【Python】裁剪错误: ${line}`);
  229. }
  230. });
  231. });
  232. python.on('close', (code) => {
  233. console.log('\n' + '='.repeat(70));
  234. console.log(`【Python】裁剪进程结束,退出码: ${code}`);
  235. if (code === 0) {
  236. console.log(`【Python】✅ 裁剪成功!处理了 ${processed} 张图片`);
  237. console.log(`【Python】📐 最终尺寸: ${width}x${height}`);
  238. console.log('='.repeat(70) + '\n');
  239. resolve({
  240. success: true,
  241. processed,
  242. width,
  243. height,
  244. message: `裁剪完成,尺寸: ${width}x${height}`
  245. });
  246. } else {
  247. console.error(`【Python】❌ 裁剪失败,退出码: ${code}`);
  248. if (stderr) console.error(`【Python】错误详情:\n${stderr}`);
  249. console.log('='.repeat(70) + '\n');
  250. reject(new Error(`裁剪失败,退出码: ${code}\n${stderr}`));
  251. }
  252. });
  253. python.on('error', (error) => {
  254. console.error(`【Python】❌ 启动进程失败:`, error);
  255. reject(new Error(`启动Python进程失败: ${error.message}`));
  256. });
  257. });
  258. }
  259. // 获取安全的文件路径(基于用户名)
  260. getSafePath(relativePath, username) {
  261. if (!username) {
  262. throw new Error('用户名不能为空');
  263. }
  264. const userRootDir = this.getUserRootDir(username);
  265. // 移除开头的斜杠
  266. relativePath = relativePath.replace(/^\/+/, '');
  267. // 解析路径,防止目录遍历攻击
  268. const fullPath = path.join(userRootDir, relativePath);
  269. // 确保路径在用户根目录内
  270. if (!fullPath.startsWith(userRootDir)) {
  271. throw new Error('非法路径');
  272. }
  273. return fullPath;
  274. }
  275. // 检查文件夹是否包含预览图
  276. async checkFolderPreview(folderPath) {
  277. const commonNames = ['01.png', '00.png', '001.png', '0001.png', '1.png', '0.png'];
  278. try {
  279. const items = await readdir(folderPath);
  280. // 首先检查常见的帧文件名
  281. for (const name of commonNames) {
  282. if (items.includes(name)) {
  283. return {
  284. hasPreview: true,
  285. previewFile: name
  286. };
  287. }
  288. }
  289. // 检查是否有任何PNG文件
  290. const pngFiles = items.filter(item => item.toLowerCase().endsWith('.png'));
  291. if (pngFiles.length > 0) {
  292. // 按文件名排序,取第一个
  293. pngFiles.sort();
  294. return {
  295. hasPreview: true,
  296. previewFile: pngFiles[0]
  297. };
  298. }
  299. return {
  300. hasPreview: false,
  301. previewFile: null
  302. };
  303. } catch (error) {
  304. return {
  305. hasPreview: false,
  306. previewFile: null
  307. };
  308. }
  309. }
  310. // 检查文件夹是否需要抠图(检测PNG图片是否有非透明背景)
  311. async checkNeedMatting(folderPath) {
  312. try {
  313. const sharp = require('sharp');
  314. const items = await readdir(folderPath);
  315. // 获取所有PNG文件(只计算一次,不区分大小写)
  316. const pngFiles = items.filter(item => item.toLowerCase().endsWith('.png'));
  317. if (pngFiles.length === 0) {
  318. return {
  319. needsMatting: false,
  320. pngCount: 0
  321. };
  322. }
  323. // 检查前3张PNG图片是否有非透明背景(采样检测,提高性能)
  324. const samplesToCheck = Math.min(3, pngFiles.length);
  325. let hasOpaqueBackground = false;
  326. for (let i = 0; i < samplesToCheck; i++) {
  327. const filePath = path.join(folderPath, pngFiles[i]);
  328. const hasOpaque = await this.checkImageHasOpaqueBackground(filePath);
  329. if (hasOpaque) {
  330. hasOpaqueBackground = true;
  331. break; // 只要有一张有非透明背景,就需要抠图
  332. }
  333. }
  334. return {
  335. needsMatting: hasOpaqueBackground,
  336. pngCount: pngFiles.length
  337. };
  338. } catch (error) {
  339. console.error('[DiskManager] 检查抠图需求失败:', error);
  340. return {
  341. needsMatting: true, // 出错时默认显示抠图选项(保守策略)
  342. pngCount: 0
  343. };
  344. }
  345. }
  346. // 检查单个图片是否有非透明背景
  347. async checkImageHasOpaqueBackground(imagePath) {
  348. try {
  349. const sharp = require('sharp');
  350. const image = sharp(imagePath);
  351. const metadata = await image.metadata();
  352. // 如果图片没有alpha通道,肯定有不透明背景
  353. if (!metadata.hasAlpha) {
  354. return true;
  355. }
  356. // 获取图片数据,快速检查边缘像素
  357. const { data, info } = await image
  358. .ensureAlpha()
  359. .raw()
  360. .toBuffer({ resolveWithObject: true });
  361. const { width, height, channels } = info;
  362. // 采样检测:检查四个角和边缘的像素
  363. const samplePoints = [
  364. { x: 0, y: 0 }, // 左上
  365. { x: width - 1, y: 0 }, // 右上
  366. { x: 0, y: height - 1 }, // 左下
  367. { x: width - 1, y: height - 1 }, // 右下
  368. { x: Math.floor(width / 2), y: 0 }, // 顶部中间
  369. { x: Math.floor(width / 2), y: height - 1 }, // 底部中间
  370. ];
  371. let opaqueCount = 0;
  372. for (const point of samplePoints) {
  373. const idx = (point.y * width + point.x) * channels;
  374. const alpha = data[idx + 3];
  375. // 如果alpha接近255(不透明),说明可能有背景
  376. if (alpha > 250) {
  377. const r = data[idx];
  378. const g = data[idx + 1];
  379. const b = data[idx + 2];
  380. // 检查是否是白色或浅色背景(可能需要抠图)
  381. if (r > 230 && g > 230 && b > 230) {
  382. opaqueCount++;
  383. }
  384. }
  385. }
  386. // 如果超过一半的采样点都是不透明的浅色,判断为需要抠图
  387. return opaqueCount >= 3;
  388. } catch (error) {
  389. console.error('[DiskManager] 检查图片背景失败:', error);
  390. return true; // 出错时默认需要抠图
  391. }
  392. }
  393. // 处理文件列表请求
  394. async handleListRequest(req, res) {
  395. try {
  396. const url = new URL(req.url, `http://${req.headers.host}`);
  397. const username = url.searchParams.get('username');
  398. if (!username) {
  399. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  400. res.end(JSON.stringify({ success: false, error: '缺少用户名参数' }));
  401. return;
  402. }
  403. const relativePath = url.searchParams.get('path') || '';
  404. const recursive = url.searchParams.get('recursive') === 'true'; // 是否递归获取所有子文件夹
  405. // 确保用户目录存在
  406. await this.ensureUserDir(username);
  407. const fullPath = this.getSafePath(relativePath, username);
  408. // 检查目录是否存在
  409. try {
  410. await access(fullPath);
  411. } catch (error) {
  412. // 目录不存在,创建它
  413. await mkdir(fullPath, { recursive: true });
  414. }
  415. if (recursive) {
  416. // 递归获取所有文件夹结构
  417. const allFiles = await this.getFilesRecursive(fullPath, relativePath);
  418. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  419. res.end(JSON.stringify({
  420. success: true,
  421. files: allFiles,
  422. recursive: true
  423. }));
  424. } else {
  425. // 只获取当前目录
  426. const items = await readdir(fullPath);
  427. const files = [];
  428. for (const item of items) {
  429. const itemPath = path.join(fullPath, item);
  430. const stats = await stat(itemPath);
  431. const itemRelativePath = path.join(relativePath, item).replace(/\\/g, '/');
  432. const fileInfo = {
  433. name: item,
  434. path: itemRelativePath,
  435. type: stats.isDirectory() ? 'directory' : 'file',
  436. size: stats.size,
  437. modifiedTime: stats.mtime
  438. };
  439. // 如果是文件夹,检查是否包含PNG预览图,并提供完整的预览URL
  440. if (stats.isDirectory()) {
  441. const previewInfo = await this.checkFolderPreview(itemPath);
  442. fileInfo.hasPreview = previewInfo.hasPreview;
  443. if (previewInfo.hasPreview && previewInfo.previewFile) {
  444. // 返回完整的预览URL路径(包含用户名)
  445. fileInfo.previewUrl = `/api/disk/preview?username=${encodeURIComponent(username)}&path=${encodeURIComponent(itemRelativePath + '/' + previewInfo.previewFile)}`;
  446. }
  447. // 检查是否需要抠图(是否有非透明背景的PNG)
  448. const mattingInfo = await this.checkNeedMatting(itemPath);
  449. fileInfo.needsMatting = mattingInfo.needsMatting;
  450. fileInfo.pngCount = mattingInfo.pngCount;
  451. }
  452. files.push(fileInfo);
  453. }
  454. // 排序:文件夹在前,然后按名称排序
  455. files.sort((a, b) => {
  456. if (a.type === 'directory' && b.type !== 'directory') return -1;
  457. if (a.type !== 'directory' && b.type === 'directory') return 1;
  458. return a.name.localeCompare(b.name, 'zh-CN');
  459. });
  460. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  461. res.end(JSON.stringify({
  462. success: true,
  463. files: files,
  464. recursive: false
  465. }));
  466. }
  467. } catch (error) {
  468. console.error('获取文件列表失败:', error);
  469. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  470. res.end(JSON.stringify({
  471. success: false,
  472. message: error.message
  473. }));
  474. }
  475. }
  476. // 递归获取所有文件夹结构(用于前端缓存)
  477. async getFilesRecursive(fullPath, relativePath) {
  478. const allFiles = [];
  479. const processDirectory = async (dirFullPath, dirRelativePath) => {
  480. try {
  481. const items = await readdir(dirFullPath);
  482. for (const item of items) {
  483. const itemPath = path.join(dirFullPath, item);
  484. const stats = await stat(itemPath);
  485. const itemRelativePath = dirRelativePath ?
  486. path.join(dirRelativePath, item).replace(/\\/g, '/') :
  487. item;
  488. const fileInfo = {
  489. name: item,
  490. path: itemRelativePath,
  491. type: stats.isDirectory() ? 'directory' : 'file',
  492. size: stats.size,
  493. modifiedTime: stats.mtime
  494. };
  495. // 如果是文件夹,检查是否包含PNG
  496. if (stats.isDirectory()) {
  497. const previewInfo = await this.checkFolderPreview(itemPath);
  498. fileInfo.hasPreview = previewInfo.hasPreview;
  499. if (previewInfo.hasPreview && previewInfo.previewFile) {
  500. fileInfo.previewUrl = `/api/disk/preview?path=${encodeURIComponent(itemRelativePath + '/' + previewInfo.previewFile)}`;
  501. }
  502. const mattingInfo = await this.checkNeedMatting(itemPath);
  503. fileInfo.needsMatting = mattingInfo.needsMatting;
  504. fileInfo.pngCount = mattingInfo.pngCount;
  505. // 递归处理子文件夹
  506. await processDirectory(itemPath, itemRelativePath);
  507. }
  508. allFiles.push(fileInfo);
  509. }
  510. } catch (error) {
  511. console.error(`递归读取目录失败: ${dirRelativePath}`, error);
  512. }
  513. };
  514. await processDirectory(fullPath, relativePath);
  515. // 排序:文件夹在前,然后按路径排序
  516. allFiles.sort((a, b) => {
  517. if (a.type === 'directory' && b.type !== 'directory') return -1;
  518. if (a.type !== 'directory' && b.type === 'directory') return 1;
  519. return a.path.localeCompare(b.path, 'zh-CN');
  520. });
  521. return allFiles;
  522. }
  523. // 处理文件上传请求
  524. async handleUploadRequest(req, res) {
  525. try {
  526. const form = formidable.formidable({
  527. multiples: true,
  528. maxFileSize: 500 * 1024 * 1024, // 500MB
  529. keepExtensions: true
  530. });
  531. form.parse(req, async (err, fields, files) => {
  532. if (err) {
  533. console.error('解析上传文件失败:', err);
  534. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  535. res.end(JSON.stringify({
  536. success: false,
  537. message: '上传失败'
  538. }));
  539. return;
  540. }
  541. try {
  542. // 获取用户名
  543. const username = this.getUsernameFromRequest(req, fields);
  544. if (!username) {
  545. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  546. res.end(JSON.stringify({ success: false, message: '缺少用户名参数' }));
  547. return;
  548. }
  549. // 确保用户目录存在
  550. await this.ensureUserDir(username);
  551. // 新版 formidable 将字段解析为数组,需要取第一个元素
  552. const relativePath = Array.isArray(fields.path) ? fields.path[0] : (fields.path || '');
  553. const fileRelativePath = Array.isArray(fields.relativePath) ? fields.relativePath[0] : (fields.relativePath || '');
  554. // 获取上传文件的完整路径
  555. const uploadPath = path.join(relativePath, fileRelativePath);
  556. const targetPath = this.getSafePath(uploadPath, username);
  557. // 确保目标目录存在
  558. const targetDir = path.dirname(targetPath);
  559. await mkdir(targetDir, { recursive: true });
  560. // 获取上传的文件
  561. const uploadedFile = Array.isArray(files.file) ? files.file[0] : files.file;
  562. // 移动文件
  563. await this.moveFile(uploadedFile.filepath, targetPath);
  564. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  565. res.end(JSON.stringify({
  566. success: true,
  567. message: '上传成功'
  568. }));
  569. } catch (error) {
  570. console.error('保存文件失败:', error);
  571. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  572. res.end(JSON.stringify({
  573. success: false,
  574. message: error.message
  575. }));
  576. }
  577. });
  578. } catch (error) {
  579. console.error('处理上传请求失败:', error);
  580. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  581. res.end(JSON.stringify({
  582. success: false,
  583. message: error.message
  584. }));
  585. }
  586. }
  587. // 移动文件
  588. async moveFile(source, target) {
  589. return new Promise((resolve, reject) => {
  590. const readStream = fs.createReadStream(source);
  591. const writeStream = fs.createWriteStream(target);
  592. readStream.on('error', reject);
  593. writeStream.on('error', reject);
  594. writeStream.on('finish', () => {
  595. // 删除临时文件
  596. fs.unlink(source, (err) => {
  597. if (err) console.error('删除临时文件失败:', err);
  598. resolve();
  599. });
  600. });
  601. readStream.pipe(writeStream);
  602. });
  603. }
  604. // 处理创建文件夹请求
  605. async handleCreateFolderRequest(req, res) {
  606. try {
  607. let body = '';
  608. req.on('data', chunk => {
  609. body += chunk.toString();
  610. });
  611. req.on('end', async () => {
  612. try {
  613. const data = JSON.parse(body);
  614. const username = data.username;
  615. if (!username) {
  616. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  617. res.end(JSON.stringify({ success: false, message: '缺少用户名参数' }));
  618. return;
  619. }
  620. // 确保用户目录存在
  621. await this.ensureUserDir(username);
  622. const relativePath = data.path || '';
  623. const folderName = data.name;
  624. if (!folderName) {
  625. throw new Error('文件夹名称不能为空');
  626. }
  627. // 验证文件夹名称
  628. if (/[\\/:*?"<>|]/.test(folderName)) {
  629. throw new Error('文件夹名称包含非法字符');
  630. }
  631. const folderPath = path.join(relativePath, folderName);
  632. const fullPath = this.getSafePath(folderPath, username);
  633. // 检查文件夹是否已存在
  634. try {
  635. await access(fullPath);
  636. throw new Error('文件夹已存在');
  637. } catch (error) {
  638. if (error.message === '文件夹已存在') {
  639. throw error;
  640. }
  641. // 文件夹不存在,创建它
  642. await mkdir(fullPath, { recursive: true });
  643. }
  644. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  645. res.end(JSON.stringify({
  646. success: true,
  647. message: '创建成功'
  648. }));
  649. } catch (error) {
  650. console.error('创建文件夹失败:', error);
  651. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  652. res.end(JSON.stringify({
  653. success: false,
  654. message: error.message
  655. }));
  656. }
  657. });
  658. } catch (error) {
  659. console.error('处理创建文件夹请求失败:', error);
  660. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  661. res.end(JSON.stringify({
  662. success: false,
  663. message: error.message
  664. }));
  665. }
  666. }
  667. // 处理重命名请求
  668. async handleRenameRequest(req, res) {
  669. try {
  670. let body = '';
  671. req.on('data', chunk => {
  672. body += chunk.toString();
  673. });
  674. req.on('end', async () => {
  675. try {
  676. const data = JSON.parse(body);
  677. const username = data.username;
  678. if (!username) {
  679. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  680. res.end(JSON.stringify({ success: false, message: '缺少用户名参数' }));
  681. return;
  682. }
  683. const oldPath = data.oldPath;
  684. const newName = data.newName;
  685. if (!oldPath || !newName) {
  686. throw new Error('路径和新名称不能为空');
  687. }
  688. // 验证新名称
  689. if (/[\\/:*?"<>|]/.test(newName)) {
  690. throw new Error('名称包含非法字符');
  691. }
  692. const userRootDir = this.getUserRootDir(username);
  693. const oldFullPath = this.getSafePath(oldPath, username);
  694. const parentDir = path.dirname(oldFullPath);
  695. const newFullPath = path.join(parentDir, newName);
  696. // 确保新路径也在用户根目录内
  697. if (!newFullPath.startsWith(userRootDir)) {
  698. throw new Error('非法路径');
  699. }
  700. // 检查旧文件是否存在
  701. await access(oldFullPath);
  702. // 检查新名称是否已存在
  703. try {
  704. await access(newFullPath);
  705. throw new Error('该名称已存在');
  706. } catch (error) {
  707. if (error.message === '该名称已存在') {
  708. throw error;
  709. }
  710. // 文件不存在,可以重命名
  711. }
  712. // 执行重命名
  713. await promisify(fs.rename)(oldFullPath, newFullPath);
  714. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  715. res.end(JSON.stringify({
  716. success: true,
  717. message: '重命名成功'
  718. }));
  719. } catch (error) {
  720. console.error('重命名失败:', error);
  721. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  722. res.end(JSON.stringify({
  723. success: false,
  724. message: error.message
  725. }));
  726. }
  727. });
  728. } catch (error) {
  729. console.error('处理重命名请求失败:', error);
  730. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  731. res.end(JSON.stringify({
  732. success: false,
  733. message: error.message
  734. }));
  735. }
  736. }
  737. // 处理文件下载请求
  738. async handleDownloadRequest(req, res) {
  739. try {
  740. const url = new URL(req.url, `http://${req.headers.host}`);
  741. const username = url.searchParams.get('username');
  742. if (!username) {
  743. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  744. res.end(JSON.stringify({ success: false, message: '缺少用户名参数' }));
  745. return;
  746. }
  747. const relativePath = url.searchParams.get('path') || '';
  748. const fullPath = this.getSafePath(relativePath, username);
  749. // 检查文件是否存在
  750. await access(fullPath);
  751. const stats = await stat(fullPath);
  752. if (stats.isDirectory()) {
  753. throw new Error('无法下载文件夹');
  754. }
  755. // 设置响应头
  756. const fileName = path.basename(fullPath);
  757. res.writeHead(200, {
  758. 'Content-Type': 'application/octet-stream',
  759. 'Content-Disposition': `attachment; filename="${encodeURIComponent(fileName)}"`,
  760. 'Content-Length': stats.size
  761. });
  762. // 创建读取流并发送文件
  763. const readStream = fs.createReadStream(fullPath);
  764. readStream.pipe(res);
  765. } catch (error) {
  766. console.error('下载文件失败:', error);
  767. res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
  768. res.end(JSON.stringify({
  769. success: false,
  770. message: '文件不存在'
  771. }));
  772. }
  773. }
  774. // 处理获取用户网盘中的帧文件列表
  775. async handleGetUserFrames(username, folderName, res) {
  776. try {
  777. console.log(`[DiskManager] 获取用户帧列表: username=${username}, folderName=${folderName}`);
  778. const userRootDir = this.getUserRootDir(username);
  779. // 处理URL编码和空格
  780. const decodedFolderName = decodeURIComponent(folderName).replace(/%20/g, ' ');
  781. const folderPath = path.join(userRootDir, decodedFolderName);
  782. console.log(`[DiskManager] 用户网盘目录: ${userRootDir}`);
  783. console.log(`[DiskManager] 解码后的文件夹名: ${decodedFolderName}`);
  784. console.log(`[DiskManager] 完整路径: ${folderPath}`);
  785. // 检查目录是否存在
  786. try {
  787. await access(folderPath);
  788. } catch (accessErr) {
  789. console.error(`[DiskManager] 文件夹不存在: ${folderPath}`);
  790. res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
  791. res.end(JSON.stringify({
  792. error: 'Folder not found',
  793. details: `文件夹不存在: ${folderPath}`,
  794. folderPath: folderPath
  795. }));
  796. return;
  797. }
  798. // 读取文件夹内容
  799. const files = await readdir(folderPath);
  800. console.log(`[DiskManager] 找到 ${files.length} 个文件`);
  801. // 过滤出 PNG 文件,并按数字排序
  802. const pngFiles = files
  803. .filter(file => file.toLowerCase().endsWith('.png'))
  804. .map(file => {
  805. let frameNum = null;
  806. // 先尝试匹配纯数字格式:00.png, 01.png
  807. let match = /^(\d+)\.png$/i.exec(file);
  808. if (match) {
  809. frameNum = parseInt(match[1], 10);
  810. } else {
  811. // 再尝试匹配文件名末尾的数字格式
  812. match = /(\d+)\.png$/i.exec(file);
  813. if (match) {
  814. frameNum = parseInt(match[1], 10);
  815. }
  816. }
  817. if (frameNum !== null) {
  818. return {
  819. frameNum: frameNum,
  820. fileName: file
  821. };
  822. }
  823. return null;
  824. })
  825. .filter(item => item !== null)
  826. .sort((a, b) => a.frameNum - b.frameNum);
  827. if (pngFiles.length === 0) {
  828. console.log(`[DiskManager] 文件夹中没有PNG文件`);
  829. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  830. res.end(JSON.stringify({
  831. error: '该文件夹中没有图片',
  832. frames: []
  833. }));
  834. return;
  835. }
  836. const result = {
  837. frames: pngFiles.map(item => item.frameNum),
  838. fileNames: pngFiles.map(item => item.fileName),
  839. maxFrame: pngFiles.length > 0 ? Math.max(...pngFiles.map(item => item.frameNum)) : 0
  840. };
  841. console.log(`[DiskManager] ✓ 成功获取 ${result.frames.length} 帧`);
  842. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  843. res.end(JSON.stringify(result));
  844. } catch (error) {
  845. console.error('[DiskManager] 获取用户帧列表失败:', error);
  846. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  847. res.end(JSON.stringify({
  848. error: 'Failed to get frames',
  849. details: error.message
  850. }));
  851. }
  852. }
  853. // 处理图片预览请求
  854. async handlePreviewRequest(req, res) {
  855. try {
  856. const url = new URL(req.url, `http://${req.headers.host}`);
  857. const username = url.searchParams.get('username');
  858. if (!username) {
  859. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  860. res.end(JSON.stringify({ success: false, message: '缺少用户名参数' }));
  861. return;
  862. }
  863. const relativePath = url.searchParams.get('path') || '';
  864. const fullPath = this.getSafePath(relativePath, username);
  865. // 检查文件是否存在
  866. await access(fullPath);
  867. const stats = await stat(fullPath);
  868. if (stats.isDirectory()) {
  869. throw new Error('无法预览文件夹');
  870. }
  871. // 获取文件扩展名
  872. const ext = path.extname(fullPath).toLowerCase();
  873. const mimeTypes = {
  874. '.jpg': 'image/jpeg',
  875. '.jpeg': 'image/jpeg',
  876. '.png': 'image/png',
  877. '.gif': 'image/gif',
  878. '.bmp': 'image/bmp',
  879. '.webp': 'image/webp',
  880. '.svg': 'image/svg+xml'
  881. };
  882. const contentType = mimeTypes[ext];
  883. if (!contentType) {
  884. throw new Error('不支持的图片格式');
  885. }
  886. // 设置响应头,添加缓存
  887. res.writeHead(200, {
  888. 'Content-Type': contentType,
  889. 'Content-Length': stats.size,
  890. 'Cache-Control': 'public, max-age=86400'
  891. });
  892. // 创建读取流并发送文件
  893. const readStream = fs.createReadStream(fullPath);
  894. readStream.pipe(res);
  895. } catch (error) {
  896. console.error('预览图片失败:', error);
  897. res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
  898. res.end(JSON.stringify({
  899. success: false,
  900. message: '图片不存在'
  901. }));
  902. }
  903. }
  904. // 处理移动文件/文件夹请求
  905. async handleMoveRequest(req, res) {
  906. try {
  907. let body = '';
  908. req.on('data', chunk => {
  909. body += chunk.toString();
  910. });
  911. req.on('end', async () => {
  912. try {
  913. const data = JSON.parse(body);
  914. const username = data.username;
  915. if (!username) {
  916. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  917. res.end(JSON.stringify({ success: false, message: '缺少用户名参数' }));
  918. return;
  919. }
  920. const sourcePath = data.sourcePath;
  921. const targetFolder = data.targetFolder;
  922. if (!sourcePath) {
  923. throw new Error('源路径不能为空');
  924. }
  925. const userRootDir = this.getUserRootDir(username);
  926. const sourceFullPath = this.getSafePath(sourcePath, username);
  927. const fileName = path.basename(sourceFullPath);
  928. // 目标路径
  929. const targetPath = targetFolder ? path.join(targetFolder, fileName) : fileName;
  930. const targetFullPath = this.getSafePath(targetPath, username);
  931. // 确保源文件存在
  932. await access(sourceFullPath);
  933. // 检查是否移动到自身或子目录
  934. if (targetFullPath.startsWith(sourceFullPath + path.sep) || targetFullPath === sourceFullPath) {
  935. throw new Error('不能移动到自身或子目录');
  936. }
  937. // 确保目标路径也在用户根目录内
  938. if (!targetFullPath.startsWith(userRootDir)) {
  939. throw new Error('非法路径');
  940. }
  941. // 检查目标是否已存在
  942. try {
  943. await access(targetFullPath);
  944. throw new Error('目标位置已存在同名文件或文件夹');
  945. } catch (error) {
  946. if (error.message === '目标位置已存在同名文件或文件夹') {
  947. throw error;
  948. }
  949. // 文件不存在,可以移动
  950. }
  951. // 确保目标目录存在
  952. const targetDir = path.dirname(targetFullPath);
  953. await mkdir(targetDir, { recursive: true });
  954. // 执行移动
  955. await promisify(fs.rename)(sourceFullPath, targetFullPath);
  956. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  957. res.end(JSON.stringify({
  958. success: true,
  959. message: '移动成功'
  960. }));
  961. } catch (error) {
  962. console.error('移动失败:', error);
  963. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  964. res.end(JSON.stringify({
  965. success: false,
  966. message: error.message
  967. }));
  968. }
  969. });
  970. } catch (error) {
  971. console.error('处理移动请求失败:', error);
  972. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  973. res.end(JSON.stringify({
  974. success: false,
  975. message: error.message
  976. }));
  977. }
  978. }
  979. // 处理复制文件/文件夹请求
  980. async handleCopyRequest(req, res) {
  981. try {
  982. let body = '';
  983. req.on('data', chunk => {
  984. body += chunk.toString();
  985. });
  986. req.on('end', async () => {
  987. try {
  988. const data = JSON.parse(body);
  989. const username = data.username;
  990. if (!username) {
  991. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  992. res.end(JSON.stringify({ success: false, message: '缺少用户名参数' }));
  993. return;
  994. }
  995. const sourcePath = data.sourcePath;
  996. const targetFolder = data.targetFolder;
  997. if (!sourcePath) {
  998. throw new Error('源路径不能为空');
  999. }
  1000. const userRootDir = this.getUserRootDir(username);
  1001. const sourceFullPath = this.getSafePath(sourcePath, username);
  1002. const fileName = path.basename(sourceFullPath);
  1003. const targetPath = targetFolder ? path.join(targetFolder, fileName) : fileName;
  1004. const targetFullPath = this.getSafePath(targetPath, username);
  1005. await access(sourceFullPath);
  1006. if (targetFullPath === sourceFullPath || targetFullPath.startsWith(sourceFullPath + path.sep)) {
  1007. throw new Error('不能复制到自身或子目录');
  1008. }
  1009. // 确保目标路径也在用户根目录内
  1010. if (!targetFullPath.startsWith(userRootDir)) {
  1011. throw new Error('非法路径');
  1012. }
  1013. try {
  1014. await access(targetFullPath);
  1015. throw new Error('目标位置已存在同名文件或文件夹');
  1016. } catch (error) {
  1017. if (error.message === '目标位置已存在同名文件或文件夹') {
  1018. throw error;
  1019. }
  1020. }
  1021. await this.copyItemRecursive(sourceFullPath, targetFullPath);
  1022. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  1023. res.end(JSON.stringify({
  1024. success: true,
  1025. message: '复制成功'
  1026. }));
  1027. } catch (error) {
  1028. console.error('复制失败:', error);
  1029. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  1030. res.end(JSON.stringify({
  1031. success: false,
  1032. message: error.message
  1033. }));
  1034. }
  1035. });
  1036. } catch (error) {
  1037. console.error('处理复制请求失败:', error);
  1038. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  1039. res.end(JSON.stringify({
  1040. success: false,
  1041. message: error.message
  1042. }));
  1043. }
  1044. }
  1045. async copyItemRecursive(source, target) {
  1046. const stats = await stat(source);
  1047. if (stats.isDirectory()) {
  1048. await mkdir(target, { recursive: true });
  1049. const entries = await readdir(source);
  1050. for (const entry of entries) {
  1051. const childSource = path.join(source, entry);
  1052. const childTarget = path.join(target, entry);
  1053. await this.copyItemRecursive(childSource, childTarget);
  1054. }
  1055. } else {
  1056. const targetDir = path.dirname(target);
  1057. await mkdir(targetDir, { recursive: true });
  1058. await copyFile(source, target);
  1059. }
  1060. }
  1061. // 处理删除文件/文件夹请求
  1062. async handleDeleteRequest(req, res) {
  1063. try {
  1064. let body = '';
  1065. req.on('data', chunk => {
  1066. body += chunk.toString();
  1067. });
  1068. req.on('end', async () => {
  1069. try {
  1070. const data = JSON.parse(body);
  1071. const username = data.username;
  1072. if (!username) {
  1073. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  1074. res.end(JSON.stringify({ success: false, message: '缺少用户名参数' }));
  1075. return;
  1076. }
  1077. const paths = data.paths;
  1078. if (!paths || !Array.isArray(paths) || paths.length === 0) {
  1079. throw new Error('请选择要删除的文件');
  1080. }
  1081. const errors = [];
  1082. for (const filePath of paths) {
  1083. try {
  1084. const fullPath = this.getSafePath(filePath, username);
  1085. await access(fullPath);
  1086. const stats = await stat(fullPath);
  1087. if (stats.isDirectory()) {
  1088. // 递归删除文件夹
  1089. await this.deleteDirectory(fullPath);
  1090. } else {
  1091. // 删除文件
  1092. await promisify(fs.unlink)(fullPath);
  1093. }
  1094. } catch (error) {
  1095. errors.push(`${filePath}: ${error.message}`);
  1096. }
  1097. }
  1098. if (errors.length > 0) {
  1099. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  1100. res.end(JSON.stringify({
  1101. success: true,
  1102. message: `部分删除成功,${errors.length} 个失败`,
  1103. errors: errors
  1104. }));
  1105. } else {
  1106. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  1107. res.end(JSON.stringify({
  1108. success: true,
  1109. message: '删除成功'
  1110. }));
  1111. }
  1112. } catch (error) {
  1113. console.error('删除失败:', error);
  1114. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  1115. res.end(JSON.stringify({
  1116. success: false,
  1117. message: error.message
  1118. }));
  1119. }
  1120. });
  1121. } catch (error) {
  1122. console.error('处理删除请求失败:', error);
  1123. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  1124. res.end(JSON.stringify({
  1125. success: false,
  1126. message: error.message
  1127. }));
  1128. }
  1129. }
  1130. // 递归删除目录
  1131. async deleteDirectory(dirPath) {
  1132. const items = await readdir(dirPath);
  1133. for (const item of items) {
  1134. const itemPath = path.join(dirPath, item);
  1135. const stats = await stat(itemPath);
  1136. if (stats.isDirectory()) {
  1137. await this.deleteDirectory(itemPath);
  1138. } else {
  1139. await promisify(fs.unlink)(itemPath);
  1140. }
  1141. }
  1142. await promisify(fs.rmdir)(dirPath);
  1143. }
  1144. // 处理一键抠图请求(使用SSE实时推送进度)
  1145. async handleRemoveBackgroundRequest(req, res) {
  1146. console.log('\n' + '▓'.repeat(70));
  1147. console.log('[API] 收到一键抠图请求');
  1148. console.log('▓'.repeat(70));
  1149. // 设置SSE响应头
  1150. res.writeHead(200, {
  1151. 'Content-Type': 'text/event-stream',
  1152. 'Cache-Control': 'no-cache',
  1153. 'Connection': 'keep-alive',
  1154. 'Access-Control-Allow-Origin': '*'
  1155. });
  1156. // 发送进度的辅助函数
  1157. const sendProgress = (data) => {
  1158. console.log('[API] → 发送SSE事件:', data);
  1159. const message = `data: ${JSON.stringify(data)}\n\n`;
  1160. res.write(message);
  1161. console.log('[API] ✓ SSE事件已发送');
  1162. };
  1163. let body = '';
  1164. req.on('data', chunk => {
  1165. body += chunk.toString();
  1166. console.log('[API] → 接收请求数据...');
  1167. });
  1168. req.on('end', async () => {
  1169. try {
  1170. console.log('[API] ✓ 请求数据接收完成');
  1171. console.log('[API] → 解析JSON数据...');
  1172. const data = JSON.parse(body);
  1173. const { paths, username } = data;
  1174. console.log('[API] ✓ JSON解析成功');
  1175. console.log('[API] 请求路径:', paths);
  1176. console.log('[API] 用户名:', username);
  1177. if (!username) {
  1178. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  1179. res.end(JSON.stringify({
  1180. success: false,
  1181. message: '缺少用户名参数'
  1182. }));
  1183. return;
  1184. }
  1185. if (!paths || !Array.isArray(paths) || paths.length === 0) {
  1186. console.warn('[API] ⚠ 路径为空或无效');
  1187. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  1188. res.end(JSON.stringify({
  1189. success: false,
  1190. message: '请选择要处理的文件或文件夹'
  1191. }));
  1192. return;
  1193. }
  1194. console.log(`[API] → 开始批量处理,共 ${paths.length} 个项目`);
  1195. let totalProcessed = 0;
  1196. let totalFolders = 0;
  1197. for (let i = 0; i < paths.length; i++) {
  1198. const relativePath = paths[i];
  1199. console.log(`\n[API] 处理项目 ${i + 1}/${paths.length}: ${relativePath}`);
  1200. // 发送开始处理的进度
  1201. sendProgress({
  1202. type: 'folder-start',
  1203. current: i + 1,
  1204. total: paths.length,
  1205. folderName: relativePath
  1206. });
  1207. console.log('[API] → 获取安全路径...');
  1208. const fullPath = this.getSafePath(relativePath, username);
  1209. console.log('[API] ✓ 完整路径:', fullPath);
  1210. console.log('[API] → 读取文件状态...');
  1211. const stats = await stat(fullPath);
  1212. console.log('[API] ✓ 文件状态:', stats.isDirectory() ? '文件夹' : '文件');
  1213. if (stats.isDirectory()) {
  1214. console.log('[API] → 开始处理文件夹...');
  1215. const result = await this.processFolder(fullPath, sendProgress, relativePath);
  1216. console.log('[API] ✓ 文件夹处理完成');
  1217. console.log('[API] 结果:', result);
  1218. if (result.success) {
  1219. totalProcessed += result.processed;
  1220. totalFolders++;
  1221. // 发送文件夹完成的进度
  1222. sendProgress({
  1223. type: 'folder-complete',
  1224. current: i + 1,
  1225. total: paths.length,
  1226. folderName: relativePath,
  1227. processed: result.processed
  1228. });
  1229. } else {
  1230. console.error('[API] ✗ 文件夹处理失败:', result.message);
  1231. sendProgress({
  1232. type: 'folder-error',
  1233. current: i + 1,
  1234. total: paths.length,
  1235. folderName: relativePath,
  1236. error: result.message
  1237. });
  1238. }
  1239. } else {
  1240. console.log('[API] ⚠ 跳过单个文件(暂不支持)');
  1241. }
  1242. }
  1243. console.log('\n' + '▓'.repeat(70));
  1244. console.log('[API] ✓✓✓ 所有项目处理完成!');
  1245. console.log(`[API] 处理文件夹: ${totalFolders} 个`);
  1246. console.log(`[API] 处理图片: ${totalProcessed} 张`);
  1247. console.log('▓'.repeat(70));
  1248. console.log('[API] → 发送完成消息...');
  1249. sendProgress({
  1250. type: 'complete',
  1251. success: true,
  1252. processed: totalProcessed,
  1253. folders: totalFolders,
  1254. message: `处理完成!处理了 ${totalFolders} 个文件夹,共 ${totalProcessed} 张图片`
  1255. });
  1256. res.end();
  1257. console.log('[API] ✓ SSE连接已关闭\n');
  1258. } catch (error) {
  1259. console.error('\n' + '▓'.repeat(70));
  1260. console.error('[API] ✗✗✗ 请求处理失败');
  1261. console.error('[API] 错误类型:', error.name);
  1262. console.error('[API] 错误信息:', error.message);
  1263. console.error('[API] 错误堆栈:', error.stack);
  1264. console.error('▓'.repeat(70) + '\n');
  1265. sendProgress({
  1266. type: 'error',
  1267. success: false,
  1268. message: error.message
  1269. });
  1270. res.end();
  1271. }
  1272. });
  1273. }
  1274. // 处理单个文件夹:只抠图(不裁剪)
  1275. async processFolder(folderPath, sendProgress, relativePath) {
  1276. const timestamp = Date.now();
  1277. const folderName = path.basename(folderPath);
  1278. // 创建临时目录
  1279. const tempBase = path.join(this.tempDir, `matting_${timestamp}_${folderName}`);
  1280. const tempMatting = path.join(tempBase, 'output');
  1281. try {
  1282. console.log(`\n${'='.repeat(70)}`);
  1283. console.log(`[DiskManager] 开始抠背景: ${folderName}`);
  1284. console.log(`${'='.repeat(70)}`);
  1285. console.log(`[DiskManager] 原始路径: ${folderPath}`);
  1286. // 创建临时目录
  1287. console.log(`[DiskManager] 创建临时目录...`);
  1288. await mkdir(tempBase, { recursive: true });
  1289. await mkdir(tempMatting, { recursive: true });
  1290. console.log(`[DiskManager] ✓ 临时目录创建完成`);
  1291. console.log(`[DiskManager] - 抠图输出: ${tempMatting}`);
  1292. // 使用Python脚本进行抠图
  1293. console.log(`\n[DiskManager] >>> 开始AI抠背景 <<<`);
  1294. const mattingResult = await this.runImageMatting(folderPath, tempMatting, (current, total) => {
  1295. if (sendProgress) {
  1296. sendProgress({
  1297. type: 'image-progress',
  1298. current: current,
  1299. total: total,
  1300. folderName: relativePath || folderName
  1301. });
  1302. }
  1303. });
  1304. if (!mattingResult.success) {
  1305. throw new Error(`抠背景失败: ${mattingResult.message}`);
  1306. }
  1307. console.log(`[DiskManager] ✓ 抠背景完成,处理了 ${mattingResult.processed} 张图片`);
  1308. // 将处理后的文件复制回原文件夹
  1309. console.log(`\n[DiskManager] >>> 保存结果到原文件夹 <<<`);
  1310. const saveResult = await this.saveProcessedFiles(tempMatting, folderPath);
  1311. console.log(`[DiskManager] ✓ 保存完成,已替换 ${saveResult.saved} 张图片`);
  1312. console.log(`\n${'='.repeat(70)}`);
  1313. console.log(`[DiskManager] ✓✓✓ 处理完成!文件夹: ${folderName} ✓✓✓`);
  1314. console.log(`${'='.repeat(70)}\n`);
  1315. return {
  1316. success: true,
  1317. processed: saveResult.saved
  1318. };
  1319. } catch (error) {
  1320. console.error(`\n${'='.repeat(70)}`);
  1321. console.error(`[DiskManager] ✗✗✗ 处理失败: ${folderName} ✗✗✗`);
  1322. console.error(`[DiskManager] 错误信息: ${error.message}`);
  1323. console.error(`${'='.repeat(70)}\n`);
  1324. return {
  1325. success: false,
  1326. processed: 0,
  1327. message: error.message
  1328. };
  1329. } finally {
  1330. // 清理临时文件
  1331. try {
  1332. console.log('[DiskManager] 清理临时文件...');
  1333. await this.deleteDirectory(tempBase);
  1334. console.log('[DiskManager] ✓ 临时文件已清理');
  1335. } catch (error) {
  1336. console.warn('[DiskManager] ⚠ 清理临时文件失败:', error.message);
  1337. }
  1338. }
  1339. }
  1340. // 处理单个文件夹:只裁剪
  1341. async processFolderCropOnly(folderPath, sendProgress, relativePath) {
  1342. const timestamp = Date.now();
  1343. const folderName = path.basename(folderPath);
  1344. // 创建临时目录
  1345. const tempBase = path.join(this.tempDir, `crop_${timestamp}_${folderName}`);
  1346. const tempCrop = path.join(tempBase, 'output');
  1347. try {
  1348. console.log(`\n${'='.repeat(70)}`);
  1349. console.log(`[DiskManager] 开始剪裁: ${folderName}`);
  1350. console.log(`${'='.repeat(70)}`);
  1351. console.log(`[DiskManager] 原始路径: ${folderPath}`);
  1352. // 创建临时目录
  1353. console.log(`[DiskManager] 创建临时目录...`);
  1354. await mkdir(tempBase, { recursive: true });
  1355. await mkdir(tempCrop, { recursive: true });
  1356. console.log(`[DiskManager] ✓ 临时目录创建完成`);
  1357. console.log(`[DiskManager] - 裁剪输出: ${tempCrop}`);
  1358. // 使用Python脚本裁剪多余透明区域
  1359. console.log(`\n[DiskManager] >>> 开始智能裁剪 <<<`);
  1360. const folderBaseName = path.basename(folderPath);
  1361. const cropResult = await this.runCutMiniSize(folderPath, tempCrop, (current, total) => {
  1362. if (sendProgress) {
  1363. sendProgress({
  1364. type: 'image-progress',
  1365. current: current,
  1366. total: total,
  1367. folderName: relativePath || folderBaseName
  1368. });
  1369. }
  1370. });
  1371. if (!cropResult.success) {
  1372. throw new Error(`裁剪失败: ${cropResult.message}`);
  1373. }
  1374. console.log(`[DiskManager] ✓ 裁剪完成,最终尺寸: ${cropResult.width}x${cropResult.height}`);
  1375. // 将处理后的文件复制回原文件夹
  1376. console.log(`\n[DiskManager] >>> 保存结果到原文件夹 <<<`);
  1377. const saveResult = await this.saveProcessedFiles(tempCrop, folderPath);
  1378. console.log(`[DiskManager] ✓ 保存完成,已替换 ${saveResult.saved} 张图片`);
  1379. console.log(`\n${'='.repeat(70)}`);
  1380. console.log(`[DiskManager] ✓✓✓ 裁剪完成!文件夹: ${folderName} ✓✓✓`);
  1381. console.log(`${'='.repeat(70)}\n`);
  1382. return {
  1383. success: true,
  1384. processed: saveResult.saved,
  1385. width: cropResult.width,
  1386. height: cropResult.height
  1387. };
  1388. } catch (error) {
  1389. console.error(`\n${'='.repeat(70)}`);
  1390. console.error(`[DiskManager] ✗✗✗ 裁剪失败: ${folderName} ✗✗✗`);
  1391. console.error(`[DiskManager] 错误信息: ${error.message}`);
  1392. console.error(`${'='.repeat(70)}\n`);
  1393. return {
  1394. success: false,
  1395. processed: 0,
  1396. message: error.message
  1397. };
  1398. } finally {
  1399. // 清理临时文件
  1400. try {
  1401. console.log('[DiskManager] 清理临时文件...');
  1402. await this.deleteDirectory(tempBase);
  1403. console.log('[DiskManager] ✓ 临时文件已清理');
  1404. } catch (error) {
  1405. console.warn('[DiskManager] ⚠ 清理临时文件失败:', error.message);
  1406. }
  1407. }
  1408. }
  1409. // 保存处理后的文件到原文件夹(直接替换)
  1410. async saveProcessedFiles(sourceFolder, targetFolder) {
  1411. console.log('[DiskManager] → 开始保存文件...');
  1412. console.log('[DiskManager] 源文件夹:', sourceFolder);
  1413. console.log('[DiskManager] 目标文件夹:', targetFolder);
  1414. let saved = 0;
  1415. try {
  1416. console.log('[DiskManager] → 读取源文件夹...');
  1417. const files = await readdir(sourceFolder);
  1418. console.log(`[DiskManager] ✓ 找到 ${files.length} 个文件`);
  1419. for (let i = 0; i < files.length; i++) {
  1420. const file = files[i];
  1421. const sourcePath = path.join(sourceFolder, file);
  1422. const targetPath = path.join(targetFolder, file);
  1423. console.log(`[DiskManager] [${i + 1}/${files.length}] 替换: ${file}`);
  1424. // 不备份,直接替换原文件
  1425. await copyFile(sourcePath, targetPath);
  1426. saved++;
  1427. console.log(`[DiskManager] ✓ 已替换`);
  1428. }
  1429. console.log(`[DiskManager] ✓ 所有文件保存完成,共 ${saved} 个`);
  1430. return { saved };
  1431. } catch (error) {
  1432. console.error('[DiskManager] ✗ 保存文件失败:', error);
  1433. throw error;
  1434. }
  1435. }
  1436. // 处理剪裁最小区域请求(使用SSE实时推送进度)
  1437. async handleCropMiniRequest(req, res) {
  1438. console.log('\n' + '▓'.repeat(70));
  1439. console.log('[API] 收到剪裁最小区域请求');
  1440. console.log('▓'.repeat(70));
  1441. // 设置SSE响应头
  1442. res.writeHead(200, {
  1443. 'Content-Type': 'text/event-stream',
  1444. 'Cache-Control': 'no-cache',
  1445. 'Connection': 'keep-alive',
  1446. 'Access-Control-Allow-Origin': '*'
  1447. });
  1448. // 发送进度的辅助函数
  1449. const sendProgress = (data) => {
  1450. console.log('[API] → 发送SSE事件:', data);
  1451. const message = `data: ${JSON.stringify(data)}\n\n`;
  1452. res.write(message);
  1453. console.log('[API] ✓ SSE事件已发送');
  1454. };
  1455. let body = '';
  1456. req.on('data', chunk => {
  1457. body += chunk.toString();
  1458. });
  1459. req.on('end', async () => {
  1460. try {
  1461. const data = JSON.parse(body);
  1462. const { paths, username } = data;
  1463. if (!username) {
  1464. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  1465. res.end(JSON.stringify({
  1466. success: false,
  1467. message: '缺少用户名参数'
  1468. }));
  1469. return;
  1470. }
  1471. if (!paths || !Array.isArray(paths) || paths.length === 0) {
  1472. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  1473. res.end(JSON.stringify({
  1474. success: false,
  1475. message: '请选择要处理的文件或文件夹'
  1476. }));
  1477. return;
  1478. }
  1479. console.log(`[API] → 开始批量裁剪,共 ${paths.length} 个项目`);
  1480. let totalProcessed = 0;
  1481. let totalFolders = 0;
  1482. for (let i = 0; i < paths.length; i++) {
  1483. const relativePath = paths[i];
  1484. console.log(`\n[API] 裁剪项目 ${i + 1}/${paths.length}: ${relativePath}`);
  1485. const fullPath = this.getSafePath(relativePath, username);
  1486. const stats = await stat(fullPath);
  1487. if (stats.isDirectory()) {
  1488. const result = await this.processFolderCropOnly(fullPath, sendProgress, relativePath);
  1489. if (result.success) {
  1490. totalProcessed += result.processed;
  1491. totalFolders++;
  1492. }
  1493. }
  1494. }
  1495. console.log('\n' + '▓'.repeat(70));
  1496. console.log('[API] ✓✓✓ 所有项目裁剪完成!');
  1497. console.log(`[API] 处理文件夹: ${totalFolders} 个`);
  1498. console.log(`[API] 处理图片: ${totalProcessed} 张`);
  1499. console.log('▓'.repeat(70));
  1500. sendProgress({
  1501. type: 'complete',
  1502. success: true,
  1503. processed: totalProcessed,
  1504. folders: totalFolders,
  1505. message: `裁剪完成!处理了 ${totalFolders} 个文件夹,共 ${totalProcessed} 张图片`
  1506. });
  1507. res.end();
  1508. } catch (error) {
  1509. console.error('[API] 裁剪请求处理失败:', error);
  1510. sendProgress({
  1511. type: 'error',
  1512. success: false,
  1513. message: error.message
  1514. });
  1515. res.end();
  1516. }
  1517. });
  1518. }
  1519. }
  1520. module.exports = DiskManager;