disk.js 61 KB

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