-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cjs
More file actions
1760 lines (1515 loc) · 67.9 KB
/
server.cjs
File metadata and controls
1760 lines (1515 loc) · 67.9 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 express = require('express');
const path = require('path');
const fs = require('fs');
const https = require('https');
const http = require('http');
const app = express();
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
// CORS headers
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
if (req.method === 'OPTIONS') {
res.sendStatus(204);
return;
}
next();
});
// Serve static files
app.use(express.static(path.join(__dirname, 'src/ui')));
// Serve the main HTML file at root
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'src/ui/index.html'));
});
// Health endpoint
app.get('/health', (req, res) => {
console.log('🏥 Health check requested');
res.status(200).json({
ok: true,
timestamp: new Date().toISOString(),
uptime: process.uptime(),
memory: process.memoryUsage(),
environment: process.env.NODE_ENV || 'development',
port: process.env.PORT || 8080,
host: process.env.HOST || '0.0.0.0'
});
});
// Profile photos endpoint
app.post('/profile-photos', (req, res) => {
console.log('👤 Profile photos requested');
try {
const { profileName } = req.body;
if (!profileName) {
return res.status(400).json({ error: 'Profile name is required' });
}
const tempDir = path.join(process.cwd(), 'temp_images');
const galleryPath = path.join(tempDir, 'gallery.html');
if (!fs.existsSync(galleryPath)) {
return res.json([]);
}
// Read gallery data
const content = fs.readFileSync(galleryPath, 'utf-8');
const match = content.match(/<script id="gallery-data" type="application\/json">([\s\S]*?)<\/script>/);
if (!match) {
return res.json([]);
}
const data = JSON.parse(match[1]);
// Filter by profile name - only show photos that match the requested profile
const profilePhotos = data.filter(item => {
// Check if the image was generated with this profile name
// We'll use the fileName or metadata to determine the profile
if (item.profileName) {
return item.profileName.toLowerCase() === profileName.toLowerCase();
}
// Fallback: check if the fileName contains the profile name
// This assumes the fileName format includes the profile name
const fileName = item.fileName || '';
return fileName.toLowerCase().includes(profileName.toLowerCase());
});
console.log(`[DEBUG] Profile "${profileName}" requested, found ${profilePhotos.length} photos out of ${data.length} total`);
res.json(profilePhotos);
} catch (error) {
console.error('[DEBUG] Profile photos error:', error);
res.json([]);
}
});
// Public photos endpoint
app.get('/public-photos', (req, res) => {
console.log('🌐 Public photos requested');
try {
const tempDir = path.join(process.cwd(), 'temp_images');
const galleryPath = path.join(tempDir, 'gallery.html');
if (!fs.existsSync(galleryPath)) {
return res.json([]);
}
// Read gallery data
const content = fs.readFileSync(galleryPath, 'utf-8');
const match = content.match(/<script id="gallery-data" type="application\/json">([\s\S]*?)<\/script>/);
if (!match) {
return res.json([]);
}
const data = JSON.parse(match[1]);
// Return all photos as public
res.json(data);
} catch (error) {
console.error('[DEBUG] Public photos error:', error);
res.json([]);
}
});
// Download gallery endpoint
app.get('/download-gallery', (req, res) => {
console.log('📄 Download gallery requested');
try {
const tempDir = path.join(process.cwd(), 'temp_images');
const galleryPath = path.join(tempDir, 'gallery.html');
if (!fs.existsSync(galleryPath)) {
return res.status(404).json({ error: 'No gallery found. Generate some images first!' });
}
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Disposition', 'attachment; filename="gallery.html"');
const galleryContent = fs.readFileSync(galleryPath, 'utf-8');
res.send(galleryContent);
} catch (error) {
console.error('[DEBUG] Download gallery error:', error);
res.status(500).json({ error: 'Failed to download gallery' });
}
});
// Railway gallery data endpoint
app.get('/railway-gallery-data', (req, res) => {
console.log('📊 Railway gallery data requested');
try {
const tempDir = path.join(process.cwd(), 'temp_images');
const galleryPath = path.join(tempDir, 'gallery.html');
console.log('[DEBUG] Looking for gallery at:', galleryPath);
console.log('[DEBUG] Gallery exists:', fs.existsSync(galleryPath));
if (!fs.existsSync(galleryPath)) {
console.log('[DEBUG] No gallery file found, returning empty array');
return res.json([]);
}
// Read gallery data
const content = fs.readFileSync(galleryPath, 'utf-8');
console.log('[DEBUG] Gallery file size:', content.length);
const match = content.match(/<script id="gallery-data" type="application\/json">([\s\S]*?)<\/script>/);
if (!match) {
console.log('[DEBUG] No gallery data script tag found');
return res.json([]);
}
const data = JSON.parse(match[1]);
console.log('[DEBUG] Found', data.length, 'images in gallery data');
res.json(data);
} catch (error) {
console.error('[DEBUG] Railway gallery data error:', error);
res.json([]);
}
});
// Bulk download endpoint for Railway
app.get('/bulk-download', (req, res) => {
console.log('📦 Bulk download requested');
try {
const tempDir = path.join(process.cwd(), 'temp_images');
const galleryPath = path.join(tempDir, 'gallery.html');
if (!fs.existsSync(galleryPath)) {
return res.status(404).json({ error: 'No gallery found. Generate some images first!' });
}
// Read gallery data
const content = fs.readFileSync(galleryPath, 'utf-8');
const match = content.match(/<script id="gallery-data" type="application\/json">([\s\S]*?)<\/script>/);
if (!match) {
return res.status(404).json({ error: 'No gallery data found' });
}
const data = JSON.parse(match[1]);
// Try to use archiver, fallback to individual downloads
try {
const archiver = require('archiver');
const archive = archiver('zip', { zlib: { level: 9 } });
res.attachment('imagefx-gallery.zip');
archive.pipe(res);
// Add all images to ZIP
data.forEach(item => {
if (item.encodedImage) {
const buffer = Buffer.from(item.encodedImage, 'base64');
archive.append(buffer, { name: item.fileName });
}
});
// Add gallery.html to ZIP
if (fs.existsSync(galleryPath)) {
const galleryContent = fs.readFileSync(galleryPath, 'utf-8');
archive.append(galleryContent, { name: 'gallery.html' });
}
archive.finalize();
} catch (archiverError) {
console.error('[DEBUG] Archiver not available, redirecting to gallery:', archiverError);
// Fallback: redirect to gallery where individual downloads are available
res.redirect('/railway-gallery');
}
} catch (error) {
console.error('[DEBUG] Bulk download error:', error);
res.status(500).json({ error: 'Failed to create bulk download' });
}
});
// POST bulk download endpoint for creating ZIP files from frontend
app.post('/bulk-download', async (req, res) => {
console.log('[POST] /bulk-download', { imageCount: req.body?.images?.length });
try {
const { images } = req.body;
if (!images || !Array.isArray(images) || images.length === 0) {
throw new Error('No images provided for download');
}
// Limit the number of images to prevent memory issues
const maxImages = 50;
if (images.length > maxImages) {
throw new Error(`Too many images. Maximum allowed: ${maxImages}`);
}
// Import required modules
const archiver = require('archiver');
// Create a ZIP archive
const archive = archiver('zip', { zlib: { level: 6 } }); // Reduced compression level for speed
// Set response headers
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', `attachment; filename="images-${new Date().toISOString().slice(0, 10)}.zip"`);
// Handle archive errors
archive.on('error', (err) => {
console.error('Archive error:', err);
if (!res.headersSent) {
res.status(500).json({ error: 'Failed to create archive' });
}
});
// Pipe archive to response
archive.pipe(res);
// Add each image to the archive
for (const image of images) {
try {
let imageBuffer;
if (image.encodedImage) {
// Handle base64 encoded images
imageBuffer = Buffer.from(image.encodedImage, 'base64');
} else if (image.downloadUrl) {
// Handle data URLs
if (image.downloadUrl.startsWith('data:')) {
const base64Data = image.downloadUrl.split(',')[1];
imageBuffer = Buffer.from(base64Data, 'base64');
} else {
// Handle regular URLs (fetch the image)
const https = require('https');
const http = require('http');
const url = new URL(image.downloadUrl);
const client = url.protocol === 'https:' ? https : http;
const response = await new Promise((resolve, reject) => {
const req = client.get(url, (res) => {
const chunks = [];
res.on('data', chunk => chunks.push(chunk));
res.on('end', () => resolve(Buffer.concat(chunks)));
res.on('error', reject);
});
req.on('error', reject);
});
imageBuffer = response;
}
} else {
throw new Error('No image data provided');
}
// Add to archive
archive.append(imageBuffer, { name: image.fileName });
} catch (error) {
console.error(`Error processing image ${image.fileName}:`, error);
// Continue with other images even if one fails
}
}
// Finalize the archive
await archive.finalize();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred';
console.error('Bulk download error:', errorMessage);
if (!res.headersSent) {
res.status(500).json({ error: errorMessage });
}
}
});
// Railway gallery endpoint
app.get('/railway-gallery', (req, res) => {
console.log('🖼️ Railway gallery requested');
try {
const tempDir = path.join(process.cwd(), 'temp_images');
const galleryPath = path.join(tempDir, 'gallery.html');
if (!fs.existsSync(galleryPath)) {
return res.status(404).json({ error: 'No gallery found. Generate some images first!' });
}
const galleryContent = fs.readFileSync(galleryPath, 'utf-8');
res.setHeader('Content-Type', 'text/html');
res.send(galleryContent);
} catch (error) {
console.error('[DEBUG] Railway gallery error:', error);
res.status(500).json({ error: 'Failed to load gallery' });
}
});
// Download image endpoint
app.get('/download/:path(*)', (req, res) => {
console.log('💾 Download requested for:', req.params.path);
try {
const decodedPath = decodeURIComponent(req.params.path);
if (!fs.existsSync(decodedPath)) {
return res.status(404).json({ error: 'File not found' });
}
const stat = fs.statSync(decodedPath);
if (!stat.isFile()) {
return res.status(400).json({ error: 'Not a file' });
}
const fileName = path.basename(decodedPath);
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
res.setHeader('Content-Type', 'application/octet-stream');
const fileStream = fs.createReadStream(decodedPath);
fileStream.pipe(res);
} catch (error) {
console.error('[DEBUG] Download error:', error);
res.status(500).json({ error: 'Failed to download file' });
}
});
// Gallery endpoint to serve gallery.html files
app.get('/gallery/:path(*)', (req, res) => {
console.log('🖼️ Gallery requested for path:', req.params.path);
try {
const decodedPath = decodeURIComponent(req.params.path);
const galleryPath = path.join(decodedPath, 'gallery.html');
if (!fs.existsSync(galleryPath)) {
return res.status(404).json({ error: 'Gallery not found' });
}
const galleryContent = fs.readFileSync(galleryPath, 'utf-8');
res.setHeader('Content-Type', 'text/html');
res.send(galleryContent);
} catch (error) {
console.error('[DEBUG] Gallery error:', error);
res.status(500).json({ error: 'Failed to load gallery' });
}
});
// Token validation endpoint
app.post('/validate-token', async (req, res) => {
console.log('🔐 Token validation requested');
try {
const { authToken } = req.body;
if (!authToken) {
return res.status(400).json({
valid: false,
error: 'No auth token provided',
type: 'none'
});
}
const tokenType = authToken.startsWith('AIza') ? 'API_KEY' : 'OAUTH_TOKEN';
console.log('[DEBUG] Token type:', tokenType);
console.log('[DEBUG] Token length:', authToken.length);
console.log('[DEBUG] Token preview:', authToken.substring(0, 20) + '...');
// Test the token with a simple API call
let testResponse;
try {
if (tokenType === 'API_KEY') {
testResponse = await makeRequest({
reqURL: 'https://generativelanguage.googleapis.com/v1beta/models',
authorization: authToken,
method: 'GET'
});
} else {
testResponse = await makeRequest({
reqURL: 'https://aisandbox-pa.googleapis.com/v1:runImageFx',
authorization: authToken,
method: 'POST',
body: JSON.stringify({
prompt: 'test',
imageCount: 1,
aspectRatio: 'IMAGE_ASPECT_RATIO_SQUARE',
modelNameType: 'IMAGEN_3_1',
tool: 'IMAGE_FX'
})
});
}
console.log('[DEBUG] Token test response:', {
hasResponse: !!testResponse,
hasError: !!(testResponse && testResponse.error),
errorCode: testResponse?.error?.code,
errorMessage: testResponse?.error?.message
});
if (testResponse && testResponse.error) {
return res.json({
valid: false,
error: testResponse.error.message,
code: testResponse.error.code,
type: tokenType
});
} else {
return res.json({
valid: true,
type: tokenType,
message: 'Token is valid'
});
}
} catch (error) {
console.error('[DEBUG] Token validation error:', error);
return res.json({
valid: false,
error: error.message,
type: tokenType
});
}
} catch (error) {
console.error('[DEBUG] Token validation endpoint error:', error);
res.status(500).json({
valid: false,
error: error.message
});
}
});
// Test file writing endpoint
app.post('/test-file-write', async (req, res) => {
console.log('🧪 Test file write requested');
try {
const testDir = './test-output';
const testFile = path.join(testDir, 'test.txt');
console.log('[DEBUG] Test directory:', testDir);
console.log('[DEBUG] Test file:', testFile);
console.log('[DEBUG] Current working directory:', process.cwd());
// Check if directory exists
console.log('[DEBUG] Directory exists:', fs.existsSync(testDir));
// Try to create directory
if (!fs.existsSync(testDir)) {
fs.mkdirSync(testDir, { recursive: true });
console.log('[DEBUG] Directory created');
}
// Try to write a test file
const testContent = `Test file created at ${new Date().toISOString()}`;
fs.writeFileSync(testFile, testContent, 'utf8');
console.log('[DEBUG] Test file written');
// Check if file exists
const fileExists = fs.existsSync(testFile);
console.log('[DEBUG] File exists after writing:', fileExists);
// Try to read the file
if (fileExists) {
const readContent = fs.readFileSync(testFile, 'utf8');
console.log('[DEBUG] File content read:', readContent);
}
res.json({
success: true,
message: 'File write test completed',
directoryExists: fs.existsSync(testDir),
fileExists: fileExists,
workingDirectory: process.cwd()
});
} catch (error) {
console.error('[DEBUG] Test file write error:', error);
res.status(500).json({
success: false,
error: error.message,
workingDirectory: process.cwd()
});
}
});
// Simple ping endpoint
app.get('/ping', (req, res) => {
console.log('🏓 Ping requested');
res.status(200).send('pong');
});
// Map UI aspect ratios to API aspect ratios
const aspectRatioMap = {
'landscape': 'IMAGE_ASPECT_RATIO_LANDSCAPE',
'portrait': 'IMAGE_ASPECT_RATIO_PORTRAIT',
'square': 'IMAGE_ASPECT_RATIO_SQUARE',
'mobile_portrait': 'IMAGE_ASPECT_RATIO_PORTRAIT',
'mobile_landscape': 'IMAGE_ASPECT_RATIO_LANDSCAPE'
};
// File management functions
const saveFile = (fileName, fileContent, encoding = "utf-8", filePath = ".") => {
const fullPath = path.join(filePath, fileName);
const parsedPath = path.parse(fullPath);
if (parsedPath.dir && !fs.existsSync(parsedPath.dir) && parsedPath.dir != ".") {
try {
fs.mkdirSync(parsedPath.dir, { recursive: true });
} catch (error) {
console.log(`[!] Failed to create directory: ${parsedPath.dir}`);
console.log(error);
return false;
}
}
try {
fs.writeFileSync(fullPath, fileContent, { encoding });
} catch (error) {
console.log(`[!] Failed to write into file.`);
console.log(error);
return false;
}
return true;
};
const saveImage = (fileName, imageContent, filePath = ".") => {
console.log('[DEBUG] saveImage called with:', {
fileName,
filePath,
imageContentLength: imageContent?.length || 0
});
try {
const result = saveFile(fileName, imageContent, "base64", filePath);
console.log('[DEBUG] saveFile result:', result);
return result;
} catch (error) {
console.error('[DEBUG] saveImage error:', error);
return false;
}
};
// Request function for API calls
const makeRequest = async (options, customHeaders = {}) => {
console.log('[DEBUG] makeRequest called with URL:', options.reqURL);
let defaultHeaders;
if (options.authorization.startsWith('AIza')) {
// API key - use X-goog-api-key header
defaultHeaders = {
'accept': '*/*',
'accept-language': 'en-US,en;q=0.9',
'content-type': 'application/json',
'x-goog-api-key': options.authorization,
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
...customHeaders
};
} else {
// OAuth token - use Authorization header
defaultHeaders = {
'accept': '*/*',
'accept-language': 'en-US,en;q=0.9',
'content-type': 'application/json',
'authorization': options.authorization.startsWith('Bearer') ? options.authorization : `Bearer ${options.authorization}`,
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
...customHeaders
};
}
console.log('[DEBUG] Headers:', {
'content-type': defaultHeaders['content-type'],
'authorization': defaultHeaders['authorization']?.substring(0, 20) + '...',
'x-goog-api-key': defaultHeaders['x-goog-api-key']?.substring(0, 20) + '...',
'origin': defaultHeaders['origin'],
'referer': defaultHeaders['referer']
});
const fetchOptions = {
method: options.method,
headers: defaultHeaders,
body: options.body
};
return new Promise((resolve, reject) => {
const url = new URL(options.reqURL);
const client = url.protocol === 'https:' ? https : http;
console.log('[DEBUG] Making request to:', url.toString());
const req = client.request(url, fetchOptions, (res) => {
console.log('[DEBUG] Response status:', res.statusCode);
console.log('[DEBUG] Response headers:', res.headers);
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('[DEBUG] Response data length:', data.length);
console.log('[DEBUG] Response data preview:', data.substring(0, 200) + '...');
try {
const jsonData = JSON.parse(data);
console.log('[DEBUG] Parsed JSON successfully');
resolve(jsonData);
} catch (error) {
console.error('[DEBUG] Failed to parse JSON:', error);
console.log('[DEBUG] Raw response:', data);
resolve(data);
}
});
});
req.on('error', (error) => {
console.error('[DEBUG] Request error:', error);
reject(error);
});
if (options.body) {
console.log('[DEBUG] Request body length:', options.body.length);
req.write(options.body);
}
req.end();
});
};
// Generate image function
const generateImage = async (params) => {
const {
prompt,
authorization,
imageCount = 1,
seed = null,
aspectRatio = 'IMAGE_ASPECT_RATIO_SQUARE',
modelNameType = 'IMAGEN_3_1',
tool = 'IMAGE_FX',
proxy
} = params;
console.log('[DEBUG] generateImage called with params:', {
prompt: prompt?.substring(0, 50) + '...',
imageCount,
seed,
aspectRatio,
modelNameType,
tool,
authLength: authorization?.length
});
// Check if this is an API key (starts with AIza) or access token
const isApiKey = authorization.startsWith('AIza');
return new Promise((resolve, reject) => {
console.log(`[DEBUG] Making request with ${isApiKey ? 'API Key' : 'Access Token'}`);
console.log(`[DEBUG] Authorization: ${isApiKey ? `Bearer ${authorization.substring(0, 20)}...` : authorization.substring(0, 20) + '...'}`);
console.log(`[DEBUG] Tool: ${tool}, Model: ${modelNameType}`);
if (isApiKey) {
// Use Google's Generative AI Images API for API keys
const modelPath = modelNameType === 'IMAGEN_4_0'
? 'models/imagen-4.0-generate-preview-06-06'
: 'models/imagen-3.0-generate-002';
const body = {
prompt: { text: prompt },
imageGenerationConfig: { numberOfImages: imageCount },
};
const doPost = async (url, payload) => {
console.log(`[DEBUG] POST ${url}`);
console.log(`[DEBUG] Body:`, JSON.stringify(payload, null, 2));
const response = await makeRequest({
reqURL: url,
authorization,
method: 'POST',
body: JSON.stringify(payload)
});
console.log(`[DEBUG] Response:`, JSON.stringify(response, null, 2));
if (response.error) throw response;
return response;
};
(async () => {
try {
// 1) models/{model}:generateImages
const url1 = `https://generativelanguage.googleapis.com/v1beta/${modelPath}:generateImages`;
const data1 = await doPost(url1, body);
const images1 = (data1.images || data1.generatedImages || []);
if (images1.length > 0) {
const converted = {
imagePanels: [{
prompt,
generatedImages: images1.map((img, index) => ({
encodedImage: img?.image?.imageBytes || img?.image?.image_bytes || img?.inlineData?.data || '',
seed: seed || Math.floor(Math.random() * 1000000),
mediaGenerationId: `genai-${Date.now()}-${index}`,
isMaskEditedImage: false,
modelNameType: modelNameType,
workflowId: 'generative-ai-images',
fingerprintLogRecordId: 'genai-images',
})),
}],
};
resolve(converted);
return;
}
console.log('[DEBUG] No images in generateImages; trying images:generate ...');
// 2) images:generate
const url2 = `https://generativelanguage.googleapis.com/v1beta/images:generate`;
const data2 = await doPost(url2, { ...body, model: modelPath });
const images2 = (data2.images || data2.generatedImages || []);
if (images2.length === 0) throw { error: { code: 500, message: 'Images API returned no images', status: 'NO_IMAGES' } };
const converted2 = {
imagePanels: [{
prompt,
generatedImages: images2.map((img, index) => ({
encodedImage: img?.image?.imageBytes || img?.image?.image_bytes || img?.inlineData?.data || '',
seed: seed || Math.floor(Math.random() * 1000000),
mediaGenerationId: `genai-${Date.now()}-${index}`,
isMaskEditedImage: false,
modelNameType: modelNameType,
workflowId: 'generative-ai-images',
fingerprintLogRecordId: 'genai-images',
})),
}],
};
resolve(converted2);
} catch (err) {
console.log('[DEBUG] Images API attempts failed:', err);
reject(err);
}
})();
} else {
// Use ImageFX API for access tokens - CORRECT FORMAT
const requestBody = {
userInput: {
candidatesCount: imageCount,
prompts: [prompt],
seed: seed,
},
clientContext: {
sessionId: ";1740656431200",
tool: tool,
},
modelInput: {
modelNameType: modelNameType,
},
aspectRatio: aspectRatio,
};
console.log('[DEBUG] Using ImageFX API with OAuth token');
console.log('[DEBUG] Request body:', JSON.stringify(requestBody, null, 2));
makeRequest({
reqURL: "https://aisandbox-pa.googleapis.com/v1:runImageFx",
authorization,
method: "POST",
body: JSON.stringify(requestBody)
})
.then((response) => {
console.log(`[DEBUG] ImageFX Response received:`, JSON.stringify(response, null, 2));
if (response.error) {
console.log(`[DEBUG] Error in response:`, response.error);
reject(response);
} else {
console.log(`[DEBUG] ImageFX Success response`);
resolve(response);
}
})
.catch((error) => {
console.log(`[DEBUG] ImageFX Request failed:`, error);
reject(error);
});
}
});
};
// Generate endpoint with real functionality
app.post('/generate', async (req, res) => {
console.log('🖼️ Generate requested');
const { prompt, folderName, authToken, authFile, generationCount, imageCount, aspectRatio, outputDir, proxy, seed, model, noFallback, profileName } = req.body;
// Check if we're on Railway (ephemeral file system)
const isRailway = process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV === 'production';
try {
// Get auth token from file or direct input
let finalAuthToken;
if (authFile) {
finalAuthToken = fs.readFileSync(authFile, { encoding: 'utf-8' }).trim();
} else if (authToken) {
finalAuthToken = authToken;
} else {
throw new Error('No auth token or auth file provided');
}
// Create output directory if it doesn't exist (for local development)
if (!isRailway && !fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Send initial progress
res.write(JSON.stringify({ type: 'progress', data: 'Starting generation...' }) + '\n');
// Generate images for each generation count
for (let gen = 0; gen < generationCount; gen++) {
res.write(JSON.stringify({
type: 'progress',
data: `Starting generation ${gen + 1} of ${generationCount}...`
}) + '\n');
// Generate images with model fallback if needed
let selectedModel = model === 'best' ? 'IMAGEN_4_0' : 'IMAGEN_3_1';
let selectedTool = 'IMAGE_FX';
let response;
try {
console.log(`[SERVER] Attempting generation with model ${selectedModel} and tool ${selectedTool}`);
res.write(JSON.stringify({ type: 'progress', data: `Using model: ${selectedModel === 'IMAGEN_4_0' ? 'Best (Imagen 4)' : 'Quality (Imagen 3)'}` }) + '\n');
response = await generateImage({
prompt,
authorization: finalAuthToken,
imageCount: imageCount,
seed: typeof seed === 'number' ? seed : null,
aspectRatio: aspectRatioMap[aspectRatio],
modelNameType: selectedModel,
tool: selectedTool,
proxy: proxy
});
console.log('[SERVER] generateImage completed successfully');
} catch (e) {
console.error('[SERVER] Generation error details:', {
message: e?.message,
stack: e?.stack,
name: e?.name
});
console.log(`[SERVER] First attempt with ${selectedModel} failed:`, e?.message || e);
if (selectedModel === 'IMAGEN_4_0' && !noFallback) {
selectedModel = 'IMAGEN_3_1';
res.write(JSON.stringify({ type: 'progress', data: 'Falling back to Imagen 3 (quality)...' }) + '\n');
try {
response = await generateImage({
prompt,
authorization: finalAuthToken,
imageCount: imageCount,
seed: typeof seed === 'number' ? seed : null,
aspectRatio: aspectRatioMap[aspectRatio],
modelNameType: selectedModel,
tool: selectedTool,
proxy: proxy
});
console.log('[SERVER] Fallback generation completed successfully');
} catch (fallbackError) {
console.error('[SERVER] Fallback generation also failed:', fallbackError);
throw fallbackError;
}
} else {
if (selectedModel === 'IMAGEN_4_0' && noFallback) {
res.write(JSON.stringify({ type: 'progress', data: `Force no-fallback: Imagen 4 failed: ${e?.message || e}` }) + '\n');
}
throw e;
}
}
// Save images and metadata
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
// Create folder-specific output directory (for local development)
const finalOutputDir = folderName && folderName.trim() !== ''
? path.join(outputDir, folderName.trim())
: outputDir;
console.log('[DEBUG] Final output directory:', finalOutputDir);
if (!isRailway) {
console.log('[DEBUG] Directory exists before creation:', fs.existsSync(finalOutputDir));
if (!fs.existsSync(finalOutputDir)) {
try {
fs.mkdirSync(finalOutputDir, { recursive: true });
console.log('[DEBUG] Directory created successfully');
} catch (error) {
console.error('[DEBUG] Failed to create directory:', error);
res.write(JSON.stringify({ type: 'error', data: `Failed to create output directory: ${error.message}` }) + '\n');
res.end();
return;
}
}
console.log('[DEBUG] Directory exists after creation:', fs.existsSync(finalOutputDir));
}
let imageNumber = 1;
const newEntries = [];
if (response.imagePanels) {
console.log('[DEBUG] Processing image panels:', response.imagePanels.length);
for (const panel of response.imagePanels) {
console.log('[DEBUG] Panel has generated images:', panel.generatedImages?.length || 0);
for (const image of panel.generatedImages) {
const currentNum = imageNumber;
const imageName = `${timestamp}-generation-${gen + 1}-${currentNum}-${aspectRatio}.png`;
imageNumber++;
console.log('[DEBUG] Processing image:', imageName);
console.log('[DEBUG] Image data length:', image.encodedImage?.length || 0);
try {
if (isRailway) {
// On Railway: Save temporarily and provide download link
const tempDir = path.join(process.cwd(), 'temp_images');
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true });
}
const tempPath = path.join(tempDir, imageName);
if (saveImage(imageName, image.encodedImage, tempDir)) {
console.log('[DEBUG] Image saved temporarily for download:', imageName);
const downloadUrl = `/download/${encodeURIComponent(tempPath)}`;
const meta = {
fileName: imageName,
prompt: prompt,
seed: seed,
aspectRatio: aspectRatio,
generationNumber: gen + 1,
imageNumber: currentNum,
savedAt: new Date().toISOString(),
mediaGenerationId: image.mediaGenerationId || null,
model: selectedModel === 'IMAGEN_4_0' ? 'Best (Imagen 4)' : 'Quality (Imagen 3)',
downloadUrl: downloadUrl,
encodedImage: image.encodedImage, // Include the image data for gallery display
isRailway: true,
profileName: profileName || 'default' // Add profile name to metadata
};
newEntries.push(meta);
res.write(JSON.stringify({
type: 'progress',
data: `Generated image ${currentNum}: ${imageName} (Click to download)`
}) + '\n');
}
} else {
// Local development: Save to file system
if (saveImage(imageName, image.encodedImage, finalOutputDir)) {
console.log('[DEBUG] Image saved successfully:', imageName);