disk.js 61 KB

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