forked from Norsico/Video-Materials-AutoGEN-Workstation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1302 lines (1083 loc) · 49.1 KB
/
server.js
File metadata and controls
1302 lines (1083 loc) · 49.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const { exec, execFile } = require('child_process');
const yaml = require('js-yaml');
const PORT = 8765;
// 读取配置文件
function loadConfig() {
try {
const configPath = path.join(__dirname, 'env.yaml');
const fileContents = fs.readFileSync(configPath, 'utf8');
const config = yaml.load(fileContents);
return config;
} catch (error) {
console.error('❌ 读取配置文件失败:', error);
return {};
}
}
const config = loadConfig();
// 检测当前是否处于无桌面环境(如 Docker 容器)
function isHeadlessEnvironment() {
if (process.env.HEADLESS === '1' || process.env.DISABLE_FOLDER_OPEN === '1') {
return true;
}
try {
// 常见容器标识文件
if (fs.existsSync('/.dockerenv') || fs.existsSync('/run/.containerenv')) {
return true;
}
} catch (error) {
return true;
}
// Linux 无显示变量时大概率没有桌面
if (process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
return true;
}
return false;
}
// 下载文件辅助函数
function downloadFile(url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest);
https.get(url, (response) => {
response.pipe(file);
file.on('finish', () => {
file.close(resolve);
});
}).on('error', (err) => {
fs.unlink(dest, () => {}); // 删除失败的文件
reject(err);
});
});
}
// MIME类型映射
const MIME_TYPES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
const server = http.createServer((req, res) => {
// 处理CORS
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
console.log(`${req.method} ${req.url}`);
// 处理API请求 - 保存文案文件
if (req.url === '/api/save-copywriting' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = JSON.parse(body);
const { projectPath, ttsData, imageData } = data;
// 创建文案文件夹
const copywritingFolder = path.join(projectPath, '文案');
if (!fs.existsSync(copywritingFolder)) {
fs.mkdirSync(copywritingFolder, { recursive: true });
}
// 保存TTS文案
const ttsFilePath = path.join(copywritingFolder, 'TTS文案.json');
fs.writeFileSync(ttsFilePath, JSON.stringify(ttsData, null, 2), 'utf-8');
// 保存图像文案
const imageFilePath = path.join(copywritingFolder, '图像文案.json');
fs.writeFileSync(imageFilePath, JSON.stringify(imageData, null, 2), 'utf-8');
// 保存完整数据
const fullDataPath = path.join(copywritingFolder, '完整数据.json');
fs.writeFileSync(fullDataPath, JSON.stringify({ TTS文案: ttsData, 图像文案: imageData }, null, 2), 'utf-8');
console.log(`✅ 文案已保存到: ${copywritingFolder}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
message: '文案保存成功',
path: copywritingFolder
}));
} catch (error) {
console.error('❌ 保存文案失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `保存失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 生成TTS(同步)
if (req.url === '/api/generate-tts' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const data = JSON.parse(body);
const { projectPath, apiKey, promptAudioUrl, promptText, inputs, emoText, useEmoText } = data;
// 构建请求体
const requestBody = {
input: inputs,
model: 'IndexTTS-2',
prompt_audio_url: promptAudioUrl,
prompt_text: promptText,
voice: 'alloy',
use_emo_text: useEmoText
};
// 只有在useEmoText为true时才添加emo_text字段
if (useEmoText && emoText) {
requestBody.emo_text = emoText;
}
console.log('🎙️ 开始生成TTS...');
// 调用同步TTS API
const response = await fetch('https://ai.gitee.com/v1/audio/speech', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// 创建TTS文件夹
const ttsFolder = path.join(projectPath, 'tts');
if (!fs.existsSync(ttsFolder)) {
fs.mkdirSync(ttsFolder, { recursive: true });
}
// 创建文本文件夹
const textFolder = path.join(ttsFolder, 'text');
if (!fs.existsSync(textFolder)) {
fs.mkdirSync(textFolder, { recursive: true });
}
// 获取下一个编号
const files = fs.readdirSync(ttsFolder).filter(f => f.match(/^\d+\.wav$/));
const nextNumber = files.length > 0
? Math.max(...files.map(f => parseInt(f.split('.')[0]))) + 1
: 1;
const audioPath = path.join(ttsFolder, `${nextNumber}.wav`);
// 保存音频流
const buffer = await response.arrayBuffer();
fs.writeFileSync(audioPath, Buffer.from(buffer));
console.log(`✅ 音频已保存: ${audioPath}`);
// 保存文本到 text/{nextNumber}.txt
const textPath = path.join(textFolder, `${nextNumber}.txt`);
fs.writeFileSync(textPath, inputs, 'utf-8');
console.log(`✅ 文本已保存: ${textPath}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
filename: `${nextNumber}.wav`,
message: '语音生成成功'
}));
} catch (error) {
console.error('❌ TTS生成失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `生成失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 打开TTS文件夹
if (req.url === '/api/open-tts-folder' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = JSON.parse(body);
const { projectPath } = data;
const ttsFolder = path.join(projectPath, 'tts');
if (!fs.existsSync(ttsFolder)) {
fs.mkdirSync(ttsFolder, { recursive: true });
}
// 无桌面环境(如 Docker)直接返回路径,避免 xdg-open 等命令失败
if (isHeadlessEnvironment()) {
console.log(`🗂️ 运行在无桌面环境,已返回路径: ${ttsFolder}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
message: '容器/无桌面环境,请在宿主机手动打开此路径',
path: ttsFolder
}));
return;
}
// 使用系统命令打开文件夹
const command = process.platform === 'win32'
? `explorer "${ttsFolder}"`
: process.platform === 'darwin'
? `open "${ttsFolder}"`
: `xdg-open "${ttsFolder}"`;
exec(command, (error) => {
if (error) {
console.error('打开文件夹失败:', error);
}
});
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ success: true }));
} catch (error) {
console.error('❌ 打开文件夹失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `打开失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 打开项目目录
if (req.url === '/api/open-project-folder' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = body ? JSON.parse(body) : {};
const { projectPath } = data;
if (!projectPath || typeof projectPath !== 'string') {
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: '无效的项目路径'
}));
return;
}
const resolvedPath = path.resolve(projectPath);
if (!fs.existsSync(resolvedPath)) {
res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: '项目路径不存在'
}));
return;
}
if (isHeadlessEnvironment()) {
console.log(`🗂️ 运行在无桌面环境,已返回路径: ${resolvedPath}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
message: '容器/无桌面环境,请在宿主机手动打开此路径',
path: resolvedPath
}));
return;
}
const command = process.platform === 'win32'
? `explorer "${resolvedPath}"`
: process.platform === 'darwin'
? `open "${resolvedPath}"`
: `xdg-open "${resolvedPath}"`;
exec(command, (error) => {
if (error) {
console.error('打开项目目录失败:', error);
}
});
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ success: true }));
} catch (error) {
console.error('打开项目目录失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `打开失败: ${error.message}`
}));
}
});
return;
}
if (req.url === '/api/default-tts-config' && req.method === 'GET') {
const defaultConfig = {
apiKey: config ? config['TTS-API-KEY'] || '' : '',
promptAudioUrl: config ? config['TTS-Prompt-Audio-URL'] || '' : '',
promptText: config ? config['TTS-Prompt-Text'] || '' : '',
defaultProjectRoot: config ? config['Default-Project-Root'] || '' : ''
};
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
data: defaultConfig
}));
return;
}
if (req.url === '/api/open-asr-tool' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const asrToolPath = path.join(__dirname, 'asr', 'AsrTools.exe');
if (!fs.existsSync(asrToolPath)) {
res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: '未找到字幕生成工具'
}));
return;
}
if (process.platform !== 'win32') {
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: '当前系统不支持启动字幕生成工具'
}));
return;
}
const child = execFile(asrToolPath, {
cwd: path.dirname(asrToolPath)
}, (error) => {
if (error) {
console.error('打开字幕生成工具失败:', error);
}
});
if (child && typeof child.unref === 'function') {
child.unref();
}
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
message: '字幕生成工具已打开'
}));
} catch (error) {
console.error('启动字幕生成工具失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `打开失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 生成图片(文本模式)
if (req.url === '/api/generate-image-text' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const data = JSON.parse(body);
const { projectPath, imageType, prompt, aspectRatio, characterName, backgroundName } = data;
// 确定保存目录
let saveDir;
let filename;
let name = characterName || backgroundName; // 支持两种参数名
if (imageType === 'character') {
saveDir = path.join(projectPath, 'image', 'character');
filename = `${name}.png`;
} else if (imageType === 'background') {
saveDir = path.join(projectPath, 'image', 'background');
// 如果提供了背景名称,直接使用;否则自动编号
if (name && name.trim()) {
filename = `${name}.png`;
} else {
// 获取下一个编号
if (!fs.existsSync(saveDir)) {
fs.mkdirSync(saveDir, { recursive: true });
}
const files = fs.readdirSync(saveDir).filter(f => f.match(/^\d+\.png$/));
const nextNumber = files.length > 0
? Math.max(...files.map(f => parseInt(f.split('.')[0]))) + 1
: 1;
filename = `${nextNumber}.png`;
}
} else {
throw new Error('无效的imageType');
}
// 确保目录存在
if (!fs.existsSync(saveDir)) {
fs.mkdirSync(saveDir, { recursive: true });
}
const savePath = path.join(saveDir, filename);
// 调用Gemini API生成图片
const apiKey = config['Gemini-API-KEY'];
const baseUrl = config['Gemini-BASE-URL'];
const model = config['Gemini-MODEL'];
const endpoint = `${baseUrl}/v1beta/models/${model}:generateContent`;
const requestBody = {
contents: [{
parts: [
{ text: prompt }
]
}]
};
if (aspectRatio) {
requestBody.generationConfig = {
imageConfig: {
aspectRatio: aspectRatio
}
};
}
console.log(endpoint);
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'x-goog-api-key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody),
timeout: 120000
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const responseData = await response.json();
// 提取图像数据
if (!responseData.candidates || responseData.candidates.length === 0) {
throw new Error('API响应中没有找到生成的图像');
}
const candidate = responseData.candidates[0];
if (!candidate.content || !candidate.content.parts) {
throw new Error('API响应格式不正确');
}
let imageData = null;
for (const part of candidate.content.parts) {
if (part.inlineData && part.inlineData.data) {
imageData = part.inlineData.data;
break;
}
}
if (!imageData) {
throw new Error('未找到图像数据');
}
// 解码并保存图像
const imageBytes = Buffer.from(imageData, 'base64');
fs.writeFileSync(savePath, imageBytes);
console.log(`✅ 图片生成成功: ${savePath}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
file_path: savePath,
file_size: imageBytes.length,
message: `图片生成成功: ${savePath}`
}));
} catch (error) {
console.error('❌ 图片生成失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `生成失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 生成图片(参考图模式)
if (req.url === '/api/generate-image-reference' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const data = JSON.parse(body);
const { projectPath, imageType, imagePaths, prompt, aspectRatio, characterName, backgroundName } = data;
// 验证参考图片路径
const validImagePaths = imagePaths.filter(p => {
const trimmed = p.trim();
return trimmed && fs.existsSync(trimmed);
});
if (validImagePaths.length === 0) {
throw new Error('没有找到有效的参考图片文件');
}
// 确定保存目录和文件名
let saveDir;
let filename;
let name = characterName || backgroundName; // 支持两种参数名
if (imageType === 'character') {
saveDir = path.join(projectPath, 'image', 'character');
filename = `${name}.png`;
} else if (imageType === 'background') {
saveDir = path.join(projectPath, 'image', 'background');
// 如果提供了背景名称,直接使用;否则自动编号
if (name && name.trim()) {
filename = `${name}.png`;
} else {
// 获取下一个编号
if (!fs.existsSync(saveDir)) {
fs.mkdirSync(saveDir, { recursive: true });
}
const files = fs.readdirSync(saveDir).filter(f => f.match(/^\d+\.png$/));
const nextNumber = files.length > 0
? Math.max(...files.map(f => parseInt(f.split('.')[0]))) + 1
: 1;
filename = `${nextNumber}.png`;
}
} else {
throw new Error('无效的imageType');
}
if (!fs.existsSync(saveDir)) {
fs.mkdirSync(saveDir, { recursive: true });
}
const savePath = path.join(saveDir, filename);
// 读取参考图片并转换为base64
const parts = [];
for (const imagePath of validImagePaths) {
const trimmedPath = imagePath.trim();
if (fs.existsSync(trimmedPath)) {
const imageBuffer = fs.readFileSync(trimmedPath);
const base64Image = imageBuffer.toString('base64');
// 获取文件扩展名以确定MIME类型
const ext = path.extname(trimmedPath).toLowerCase();
let mimeType = 'image/jpeg';
if (ext === '.png') mimeType = 'image/png';
else if (ext === '.gif') mimeType = 'image/gif';
else if (ext === '.webp') mimeType = 'image/webp';
parts.push({
inlineData: {
mimeType: mimeType,
data: base64Image
}
});
}
}
parts.push({ text: prompt });
// 调用Gemini API
const apiKey = config['Gemini-API-KEY'];
const baseUrl = config['Gemini-BASE-URL'];
const model = config['Gemini-MODEL'];
const endpoint = `${baseUrl}/v1beta/models/${model}:generateContent`;
const requestBody = {
contents: [{
parts: parts
}]
};
if (aspectRatio) {
requestBody.generationConfig = {
imageConfig: {
aspectRatio: aspectRatio
}
};
}
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'x-goog-api-key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody),
timeout: 120000
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const responseData = await response.json();
// 提取图像数据
if (!responseData.candidates || responseData.candidates.length === 0) {
throw new Error('API响应中没有找到生成的图像');
}
const candidate = responseData.candidates[0];
if (!candidate.content || !candidate.content.parts) {
throw new Error('API响应格式不正确');
}
let imageData = null;
for (const part of candidate.content.parts) {
if (part.inlineData && part.inlineData.data) {
imageData = part.inlineData.data;
break;
}
}
if (!imageData) {
throw new Error('未找到图像数据');
}
// 解码并保存图像
const imageBytes = Buffer.from(imageData, 'base64');
fs.writeFileSync(savePath, imageBytes);
console.log(`✅ 图片生成成功: ${savePath}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
file_path: savePath,
file_size: imageBytes.length,
message: `图片生成成功: ${savePath}`
}));
} catch (error) {
console.error('❌ 图片生成失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `生成失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 保存草稿
if (req.url === '/api/save-draft' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = JSON.parse(body);
const { projectPath, draftData } = data;
// 创建draft文件夹
const draftFolder = path.join(projectPath, '.draft');
if (!fs.existsSync(draftFolder)) {
fs.mkdirSync(draftFolder, { recursive: true });
}
// 保存草稿文件
const draftPath = path.join(draftFolder, 'workspace-draft.json');
fs.writeFileSync(draftPath, JSON.stringify(draftData, null, 2), 'utf-8');
console.log(`✅ 草稿已保存: ${draftPath}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
message: '草稿已保存'
}));
} catch (error) {
console.error('❌ 保存草稿失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `保存失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 加载草稿
if (req.url === '/api/load-draft' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = JSON.parse(body);
const { projectPath } = data;
// 读取草稿文件
const draftPath = path.join(projectPath, '.draft', 'workspace-draft.json');
if (!fs.existsSync(draftPath)) {
res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: '没有找到保存的草稿'
}));
return;
}
const draftContent = fs.readFileSync(draftPath, 'utf-8');
const draftData = JSON.parse(draftContent);
console.log(`✅ 草稿已加载: ${draftPath}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
data: draftData
}));
} catch (error) {
console.error('❌ 加载草稿失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `加载失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 清空草稿
if (req.url === '/api/clear-draft' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = JSON.parse(body);
const { projectPath } = data;
// 删除草稿文件
const draftPath = path.join(projectPath, '.draft', 'workspace-draft.json');
if (fs.existsSync(draftPath)) {
fs.unlinkSync(draftPath);
console.log(`✅ 草稿已清空: ${draftPath}`);
}
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
message: '草稿已清空'
}));
} catch (error) {
console.error('❌ 清空草稿失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `清空失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 打开图片所在文件夹
if (req.url === '/api/open-image-folder' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = JSON.parse(body);
const { filePath } = data;
if (!filePath) {
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: '未提供文件路径'
}));
return;
}
// 提取文件所在的目录
const folderPath = path.dirname(filePath);
if (!fs.existsSync(folderPath)) {
res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: '目录不存在'
}));
return;
}
if (isHeadlessEnvironment()) {
console.log(`🗂️ 运行在无桌面环境,已返回路径: ${folderPath}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
message: '容器/无桌面环境,请在宿主机手动打开此路径',
path: folderPath
}));
return;
}
// 使用系统命令打开文件夹
const command = process.platform === 'win32'
? `explorer "${folderPath}"`
: process.platform === 'darwin'
? `open "${folderPath}"`
: `xdg-open "${folderPath}"`;
exec(command, (error) => {
if (error) {
console.error('❌ 打开文件夹失败:', error);
}
});
console.log(`✅ 已打开文件夹: ${folderPath}`);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: true,
message: '文件夹已打开'
}));
} catch (error) {
console.error('❌ 打开文件夹失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: `打开失败: ${error.message}`
}));
}
});
return;
}
// 处理API请求 - 自由创作图片
if (req.url === '/api/free-create-image' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const data = JSON.parse(body);
const { projectPath, prompt, aspectRatio, saveFolder, referenceImages } = data;
if (!prompt) {
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
success: false,
message: '请提供提示词'
}));
return;
}
// 确定保存目录
const saveDir = saveFolder || path.join(projectPath, 'free-create');
// 确保目录存在
if (!fs.existsSync(saveDir)) {
fs.mkdirSync(saveDir, { recursive: true });
}
// 生成文件名(使用时间戳)
const timestamp = Date.now();
const filename = `free-create-${timestamp}.png`;