-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1732 lines (1492 loc) · 55.5 KB
/
server.js
File metadata and controls
1732 lines (1492 loc) · 55.5 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
import express from 'express';
import cors from 'cors';
import { spawn } from 'child_process';
import { WebSocketServer } from 'ws';
import { createServer } from 'http';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import crypto from 'crypto';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
import { v4 as uuidv4 } from 'uuid';
import { createLogger } from './logger.js';
// Load environment variables from frontend directory
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });
// Create component-specific loggers
const apiLogger = createLogger('api');
const wsLogger = createLogger('websocket');
const processingLogger = createLogger('processing');
// Request correlation ID middleware
app.use((req, res, next) => {
req.correlationId = uuidv4();
res.set('X-Correlation-ID', req.correlationId);
const start = Date.now();
apiLogger.apiRequest(req.method, req.path, req.correlationId, {
ip: req.ip,
userAgent: req.get('User-Agent')
});
// Log response when request completes
res.on('finish', () => {
const duration = Date.now() - start;
apiLogger.apiResponse(req.method, req.path, res.statusCode, duration, req.correlationId);
});
next();
});
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
// Serve Vite build files in production
if (process.env.NODE_ENV === 'production') {
const distPath = path.join(__dirname, 'dist');
// Serve static assets with proper MIME types
app.use(express.static(distPath, {
setHeaders: (res, filePath) => {
// Correct MIME type for ES modules
if (filePath.endsWith('.js') || filePath.endsWith('.mjs')) {
res.type('application/javascript');
}
}
}));
}
// Serve generated podcast files - updated path to parent directory
app.use('/generated', express.static(path.join(__dirname, '..', 'generated_podcasts')));
// JSON validation middleware for POST endpoints
const validateJSON = (req, res, next) => {
if (req.method === 'POST' && req.headers['content-type']?.includes('application/json')) {
if (!req.body || typeof req.body !== 'object' || Array.isArray(req.body)) {
return res.status(400).json({
error: 'Invalid request',
message: 'Request body must be a valid JSON object (not array, string, or null)'
});
}
}
next();
};
// Apply JSON validation to all routes
app.use(validateJSON);
// Store active processing sessions
const activeSessions = new Map();
// API Keys from environment variables
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
// Podcast Index API configuration
const PODCAST_API_KEY = process.env.PODCAST_API_KEY;
const PODCAST_API_SECRET = process.env.PODCAST_API_SECRET;
// Helper function to create Podcast Index API headers
function createPodcastApiHeaders() {
const apiHeaderTime = Math.floor(Date.now() / 1000);
const hashString = `${PODCAST_API_KEY}${PODCAST_API_SECRET}${apiHeaderTime}`;
const authHash = crypto.createHash('sha1').update(hashString).digest('hex');
return {
'User-Agent': 'cast-dread-technology/1.0',
'X-Auth-Key': PODCAST_API_KEY,
'X-Auth-Date': apiHeaderTime.toString(),
'Authorization': authHash
};
}
// Helper function to check if URL is from YouTube
function isYouTubeUrl(url) {
if (!url || typeof url !== 'string') return false;
try {
const urlObj = new URL(url.toLowerCase().trim());
const hostname = urlObj.hostname;
return (
hostname === 'youtube.com' ||
hostname === 'www.youtube.com' ||
hostname === 'youtu.be' ||
hostname === 'm.youtube.com'
);
} catch (error) {
return false;
}
}
// Helper function to check for existing YouTube URL
async function checkExistingYouTubeUrl(youtubeUrl, outputDir) {
try {
if (!await fs.pathExists(outputDir)) {
return null;
}
const files = await fs.readdir(outputDir);
const metadataFiles = files.filter(file => file.endsWith('_metadata.json'));
for (const metadataFile of metadataFiles) {
try {
const metadataPath = path.join(outputDir, metadataFile);
const metadata = await fs.readJson(metadataPath);
// Check if this metadata file contains the same YouTube URL
if (metadata.youtubeUrl === youtubeUrl) {
const baseName = metadataFile.replace('_metadata.json', '');
// Check if corresponding transcript file exists
const transcriptPath = path.join(outputDir, `${baseName}_transcript.jsonl`);
if (await fs.pathExists(transcriptPath)) {
// Read transcript content
const transcriptContent = await fs.readFile(transcriptPath, 'utf-8');
const transcript = transcriptContent
.split('\n')
.filter(line => line.trim())
.map(line => JSON.parse(line));
return {
id: baseName,
baseName: baseName,
...metadata,
transcript,
cached: true
};
}
}
} catch (error) {
processingLogger.error(`Error reading metadata for ${metadataFile}`, {
error: error.message,
stack: error.stack,
metadataFile
});
}
}
return null;
} catch (error) {
processingLogger.error('Error checking for existing YouTube URL', {
error: error.message,
stack: error.stack
});
return null;
}
}
// WebSocket connection for real-time progress updates
wss.on('connection', (ws) => {
const wsConnectionId = uuidv4();
wsLogger.info('Client connected for progress updates', { connectionId: wsConnectionId });
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
if (data.type === 'subscribe' && data.sessionId) {
ws.sessionId = data.sessionId;
wsLogger.info('Client subscribed to session', {
connectionId: wsConnectionId,
sessionId: data.sessionId
});
}
} catch (error) {
wsLogger.error('Error parsing WebSocket message', {
connectionId: wsConnectionId,
error: error.message,
message: message.toString()
});
}
});
ws.on('close', () => {
wsLogger.info('Client disconnected', {
connectionId: wsConnectionId,
sessionId: ws.sessionId
});
});
});
// Broadcast progress to all clients subscribed to a session
function broadcastProgress(sessionId, progress) {
// Create a clean copy of progress data without circular references
const cleanProgress = {
type: 'progress',
sessionId,
progress: progress.progress || 0,
message: progress.message || '',
status: progress.status || 'processing',
startTime: progress.startTime,
lastUpdate: progress.lastUpdate,
estimatedDuration: progress.estimatedDuration,
audioLength: progress.audioLength
};
// Add result and error if they exist
if (progress.result) cleanProgress.result = progress.result;
if (progress.error) cleanProgress.error = progress.error;
if (progress.completedAt) cleanProgress.completedAt = progress.completedAt;
wss.clients.forEach((client) => {
if (client.sessionId === sessionId && client.readyState === 1) {
client.send(JSON.stringify(cleanProgress));
}
});
}
// Cache utility functions
// Generate safe title from episode metadata (matches Python script logic)
function generateSafeTitle(episodeTitle) {
// Remove non-alphanumeric characters except spaces, hyphens, and underscores
const safeTitle = episodeTitle.replace(/[^a-zA-Z0-9 \-_]/g, '').trim();
// Replace spaces with underscores
return safeTitle.replace(/\s+/g, '_');
}
// Check if cached files exist for an episode
async function checkCachedFiles(episodeMetadata, outputDir) {
try {
const episodeTitle = episodeMetadata?.title || 'Unknown_Episode';
const safeTitle = generateSafeTitle(episodeTitle);
const metadataPath = path.join(outputDir, `${safeTitle}_metadata.json`);
const transcriptPath = path.join(outputDir, `${safeTitle}_transcript.jsonl`);
// Check if both essential files exist
const metadataExists = await fs.pathExists(metadataPath);
const transcriptExists = await fs.pathExists(transcriptPath);
if (metadataExists && transcriptExists) {
// Return the cached data
const metadata = await fs.readJson(metadataPath);
const transcriptContent = await fs.readFile(transcriptPath, 'utf-8');
// Parse JSONL to array
const transcript = transcriptContent
.split('\n')
.filter(line => line.trim())
.map(line => JSON.parse(line));
return {
id: safeTitle,
...metadata,
transcript,
cached: true
};
}
return null;
} catch (error) {
processingLogger.error('Error checking cached files', {
error: error.message,
stack: error.stack
});
return null;
}
}
// API Routes
// Search podcasts using Podcast Index API
app.post('/api/search-podcasts', async (req, res) => {
try {
const { searchTerm } = req.body;
if (!searchTerm) {
apiLogger.warn('Search podcasts request missing search term', {
correlationId: req.correlationId
});
return res.status(400).json({ error: 'Search term is required' });
}
apiLogger.info('Searching for podcasts', {
correlationId: req.correlationId,
searchTerm
});
// Call Podcast Index API
const headers = createPodcastApiHeaders();
const searchUrl = `https://api.podcastindex.org/api/1.0/search/byterm?q=${encodeURIComponent(searchTerm)}`;
const response = await fetch(searchUrl, { headers });
if (!response.ok) {
throw new Error(`Podcast API returned ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data.feeds || data.feeds.length === 0) {
apiLogger.info('No podcasts found for search term', {
correlationId: req.correlationId,
searchTerm
});
return res.json({ feeds: [] });
}
// Limit to top 10 results and clean up the data
const cleanedFeeds = data.feeds.slice(0, 10).map(feed => ({
id: feed.id,
title: feed.title,
author: feed.author,
description: feed.description,
image: feed.image,
url: feed.url,
categories: feed.categories
}));
apiLogger.info('Podcast search completed successfully', {
correlationId: req.correlationId,
searchTerm,
resultCount: cleanedFeeds.length
});
res.json({ feeds: cleanedFeeds });
} catch (error) {
apiLogger.error('Error searching podcasts', {
correlationId: req.correlationId,
searchTerm: req.body.searchTerm,
error: error.message,
stack: error.stack
});
res.status(500).json({ error: 'Failed to search podcasts. Please try again.' });
}
});
// Get episodes for a selected podcast
app.post('/api/get-episodes', async (req, res) => {
try {
const { podcastId, page = 1, limit = 10, sortBy = 'recent', search = '' } = req.body;
if (!podcastId) {
return res.status(400).json({ error: 'Podcast ID is required' });
}
// Validate pagination parameters
const currentPage = Math.max(1, parseInt(page));
const itemsPerPage = Math.min(Math.max(parseInt(limit), 1), 100); // Max 100 items per page
// For server-side pagination, we need to fetch more episodes than requested
// to handle sorting and filtering on the server side
const maxEpisodesToFetch = 150; // Fetch up to 150 episodes to enable proper server-side sorting
apiLogger.info('Getting episodes for podcast', {
correlationId: req.correlationId,
podcastId,
page: currentPage,
limit: itemsPerPage,
sortBy,
search: search.trim(),
maxEpisodesToFetch
});
// Call Podcast Index API for episodes
const headers = createPodcastApiHeaders();
const episodesUrl = `https://api.podcastindex.org/api/1.0/episodes/byfeedid?id=${podcastId}&max=${maxEpisodesToFetch}`;
const response = await fetch(episodesUrl, { headers });
if (!response.ok) {
throw new Error(`Podcast API returned ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data.items || data.items.length === 0) {
return res.json({
items: [],
pagination: {
currentPage: 1,
totalPages: 0,
totalItems: 0,
hasNext: false,
hasPrevious: false,
itemsPerPage
}
});
}
// Clean up episode data
let cleanedEpisodes = data.items.map(episode => ({
id: episode.id,
title: episode.title,
description: episode.description,
enclosureUrl: episode.enclosureUrl,
datePublished: episode.datePublished,
duration: episode.duration,
episodeType: episode.episodeType
}));
// Apply server-side search filter
if (search.trim()) {
const query = search.toLowerCase();
cleanedEpisodes = cleanedEpisodes.filter(episode =>
episode.title?.toLowerCase().includes(query) ||
episode.description?.toLowerCase().includes(query)
);
}
// Apply server-side sorting
cleanedEpisodes.sort((a, b) => {
switch (sortBy) {
case 'recent':
return new Date(b.datePublished || 0) - new Date(a.datePublished || 0);
case 'oldest':
return new Date(a.datePublished || 0) - new Date(b.datePublished || 0);
case 'duration-desc':
return (b.duration || 0) - (a.duration || 0);
case 'duration-asc':
return (a.duration || 0) - (b.duration || 0);
case 'title-asc':
return (a.title || '').localeCompare(b.title || '');
default:
return 0;
}
});
// Calculate pagination
const totalItems = cleanedEpisodes.length;
const totalPages = Math.ceil(totalItems / itemsPerPage);
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
// Get the page slice
const paginatedEpisodes = cleanedEpisodes.slice(startIndex, endIndex);
// Create pagination metadata
const pagination = {
currentPage,
totalPages,
totalItems,
hasNext: currentPage < totalPages,
hasPrevious: currentPage > 1,
itemsPerPage
};
apiLogger.info('Episodes retrieved successfully', {
correlationId: req.correlationId,
podcastId,
episodeCount: paginatedEpisodes.length,
totalItems,
currentPage,
totalPages
});
res.json({
items: paginatedEpisodes,
pagination
});
} catch (error) {
apiLogger.error('Error getting episodes', {
correlationId: req.correlationId,
error: error.message,
stack: error.stack
});
res.status(500).json({ error: 'Failed to get episodes. Please try again.' });
}
});
// Process a selected podcast episode or YouTube video
app.post('/api/process-podcast', async (req, res) => {
try {
const { episodeUrl, podcastMetadata, sessionId, youtubeUrl, forceReprocess } = req.body;
// Support both podcast episodes and YouTube URLs
const contentUrl = youtubeUrl || episodeUrl;
if (!contentUrl || !sessionId) {
return res.status(400).json({ error: 'Content URL and session ID are required' });
}
// Check if session already exists
if (activeSessions.has(sessionId)) {
return res.status(409).json({ error: 'Session already in progress' });
}
// Validate YouTube URL if provided
if (youtubeUrl && !isYouTubeUrl(youtubeUrl)) {
return res.status(400).json({ error: 'Invalid YouTube URL format' });
}
const outputDir = path.join(__dirname, '..', 'generated_podcasts');
// Check for existing YouTube URL processing (skip if forceReprocess is true)
if (youtubeUrl && !forceReprocess) {
processingLogger.info('Checking for existing YouTube URL', {
sessionId,
youtubeUrl
});
const existingData = await checkExistingYouTubeUrl(youtubeUrl, outputDir);
if (existingData) {
processingLogger.info('Found existing processed YouTube video', {
sessionId,
title: existingData.title,
cached: true
});
// Set session as completed immediately with existing data
activeSessions.set(sessionId, {
status: 'completed',
progress: 100,
message: 'YouTube video already processed - loaded from cache!',
result: existingData,
completedAt: Date.now(),
startTime: Date.now(),
cached: true
});
// Send immediate response with cache indicator
res.json({
sessionId,
status: 'completed',
message: 'YouTube video already processed - loaded from cache!',
cached: true,
result: existingData
});
// Broadcast completion to WebSocket clients
broadcastProgress(sessionId, activeSessions.get(sessionId));
// Clean up session after 5 minutes
setTimeout(() => {
activeSessions.delete(sessionId);
}, 5 * 60 * 1000);
return;
}
}
// Check for cached files first (only for podcast episodes, not YouTube since we already checked above)
// Skip cache check if forceReprocess is true
if (!youtubeUrl && !forceReprocess) {
const episodeMetadata = podcastMetadata?.episode;
if (episodeMetadata) {
processingLogger.info('Checking cache for episode', {
sessionId,
episodeTitle: episodeMetadata.title
});
const cachedData = await checkCachedFiles(episodeMetadata, outputDir);
if (cachedData) {
processingLogger.info('Found cached transcript for episode', {
sessionId,
episodeTitle: episodeMetadata.title,
cached: true
});
// Set session as completed immediately with cached data
activeSessions.set(sessionId, {
status: 'completed',
progress: 100,
message: 'Loaded from cache instantly!',
result: cachedData,
completedAt: Date.now(),
startTime: Date.now(),
cached: true
});
// Send immediate response with cache indicator
res.json({
sessionId,
status: 'completed',
message: 'Podcast loaded from cache instantly!',
cached: true,
result: cachedData
});
// Broadcast completion to WebSocket clients
broadcastProgress(sessionId, activeSessions.get(sessionId));
// Clean up session after 5 minutes
setTimeout(() => {
activeSessions.delete(sessionId);
}, 5 * 60 * 1000);
return;
}
}
// No cache found, proceed with normal processing
processingLogger.info('No cache found, starting processing', {
sessionId,
episodeTitle: episodeMetadata?.title || 'Unknown Episode'
});
}
// Log if force reprocessing
if (forceReprocess) {
processingLogger.info('Force reprocessing requested', {
sessionId,
content: youtubeUrl || podcastMetadata?.episode?.title || 'Unknown',
forceReprocess: true
});
}
// Start processing
activeSessions.set(sessionId, { status: 'starting', startTime: Date.now() });
// Send immediate response
const contentType = youtubeUrl ? 'YouTube video' : 'podcast episode';
const processingMessage = forceReprocess
? `Re-processing ${contentType}. This will replace the existing transcript.`
: `${contentType} processing started. Monitor progress via WebSocket.`;
res.json({
sessionId,
status: 'started',
message: processingMessage,
cached: false
});
// Start the Python script asynchronously
if (youtubeUrl) {
processYouTubeAsync(youtubeUrl, podcastMetadata || {}, sessionId);
} else {
processEpisodeAsync(episodeUrl, podcastMetadata, sessionId);
}
} catch (error) {
processingLogger.error('Error starting content processing', {
sessionId,
error: error.message,
stack: error.stack
});
res.status(500).json({ error: 'Failed to start processing' });
}
});
// Get processing status
app.get('/api/status/:sessionId', (req, res) => {
const { sessionId } = req.params;
const session = activeSessions.get(sessionId);
if (!session) {
return res.status(404).json({ error: 'Session not found' });
}
// Create a clean copy without circular references
const cleanSession = {
progress: session.progress || 0,
message: session.message || '',
status: session.status || 'processing',
startTime: session.startTime,
lastUpdate: session.lastUpdate,
estimatedDuration: session.estimatedDuration,
audioLength: session.audioLength
};
// Add result and error if they exist
if (session.result) cleanSession.result = session.result;
if (session.error) cleanSession.error = session.error;
if (session.completedAt) cleanSession.completedAt = session.completedAt;
res.json(cleanSession);
});
// Check if podcasts/episodes are already processed
app.post('/api/check-processed', async (req, res) => {
try {
const { podcasts } = req.body; // Array of podcast objects with titles
if (!podcasts || !Array.isArray(podcasts)) {
return res.status(400).json({ error: 'Podcasts array is required' });
}
const generatedDir = path.join(__dirname, '..', 'generated_podcasts');
const processedStatus = {};
if (await fs.pathExists(generatedDir)) {
const files = await fs.readdir(generatedDir);
const metadataFiles = files.filter(file => file.endsWith('_metadata.json'));
// Load all processed podcasts
const processedPodcasts = [];
for (const metadataFile of metadataFiles) {
try {
const metadataPath = path.join(generatedDir, metadataFile);
const metadata = await fs.readJson(metadataPath);
const baseName = metadataFile.replace('_metadata.json', '');
// Check if transcript exists
const transcriptPath = path.join(generatedDir, `${baseName}_transcript.jsonl`);
if (await fs.pathExists(transcriptPath)) {
processedPodcasts.push({
id: baseName,
title: metadata.title,
podcastTitle: metadata.podcast_info?.title,
podcastAuthor: metadata.podcast_info?.author
});
}
} catch (error) {
processingLogger.error(`Error reading metadata for ${metadataFile}`, {
error: error.message,
stack: error.stack,
metadataFile
});
}
}
// Check each requested podcast
for (const podcast of podcasts) {
const podcastKey = `${podcast.id}`;
processedStatus[podcastKey] = {
isProcessed: false,
processedEpisodes: []
};
// Check if any episodes from this podcast are processed
const matchingEpisodes = processedPodcasts.filter(processed =>
processed.podcastTitle?.toLowerCase().includes(podcast.title?.toLowerCase()) ||
processed.podcastAuthor?.toLowerCase().includes(podcast.author?.toLowerCase())
);
if (matchingEpisodes.length > 0) {
processedStatus[podcastKey] = {
isProcessed: true,
processedEpisodes: matchingEpisodes,
count: matchingEpisodes.length
};
}
}
}
res.json(processedStatus);
} catch (error) {
apiLogger.error('Error checking processed podcasts', {
correlationId: req.correlationId,
error: error.message,
stack: error.stack
});
res.status(500).json({ error: 'Failed to check processed podcasts' });
}
});
// Get available generated podcasts
app.get('/api/generated-podcasts', async (req, res) => {
try {
const generatedDir = path.join(__dirname, '..', 'generated_podcasts');
if (!await fs.pathExists(generatedDir)) {
return res.json([]);
}
const files = await fs.readdir(generatedDir);
const podcasts = [];
// Look for metadata files directly in the directory
const metadataFiles = files.filter(file => file.endsWith('_metadata.json'));
for (const metadataFile of metadataFiles) {
try {
const metadataPath = path.join(generatedDir, metadataFile);
const metadata = await fs.readJson(metadataPath);
// Extract the base name from the filename (remove _metadata.json)
const baseName = metadataFile.replace('_metadata.json', '');
// Check if corresponding transcript file exists
const transcriptPath = path.join(generatedDir, `${baseName}_transcript.jsonl`);
const transcriptExists = await fs.pathExists(transcriptPath);
if (transcriptExists) {
const originalId = metadata.id;
const podcastData = {
...metadata,
baseName: baseName,
originalId: originalId
};
// Override the ID with baseName for API compatibility
podcastData.id = baseName;
podcasts.push(podcastData);
}
} catch (error) {
processingLogger.error(`Error reading metadata for ${metadataFile}`, {
error: error.message,
stack: error.stack,
metadataFile
});
}
}
// Sort by generation date (newest first)
podcasts.sort((a, b) => new Date(b.generated_at) - new Date(a.generated_at));
res.json(podcasts);
} catch (error) {
apiLogger.error('Error getting generated podcasts', {
correlationId: req.correlationId,
error: error.message,
stack: error.stack
});
res.status(500).json({ error: 'Failed to get generated podcasts' });
}
});
// Get specific podcast data
app.get('/api/podcast/:id', async (req, res) => {
try {
const { id } = req.params;
const generatedDir = path.join(__dirname, '..', 'generated_podcasts');
// Files are saved directly in generated_podcasts directory with the pattern {id}_metadata.json
const metadataPath = path.join(generatedDir, `${id}_metadata.json`);
if (!await fs.pathExists(metadataPath)) {
return res.status(404).json({ error: 'Podcast not found' });
}
// Read metadata
const metadata = await fs.readJson(metadataPath);
// Read transcript
const transcriptPath = path.join(generatedDir, `${id}_transcript.jsonl`);
const transcriptContent = await fs.readFile(transcriptPath, 'utf-8');
// Parse JSONL to array
const transcript = transcriptContent
.split('\n')
.filter(line => line.trim())
.map(line => JSON.parse(line));
res.json({
...metadata,
transcript,
id
});
} catch (error) {
apiLogger.error('Error getting podcast data', {
correlationId: req.correlationId,
error: error.message,
stack: error.stack
});
res.status(500).json({ error: 'Failed to get podcast data' });
}
});
// Get system prompt for podcast with robust filename matching
app.get('/api/system-prompt/:podcastId', async (req, res) => {
try {
const { podcastId } = req.params;
const generatedDir = path.join(__dirname, '..', 'generated_podcasts');
apiLogger.info('System prompt request', {
correlationId: req.correlationId,
podcastId: podcastId,
originalPodcastId: podcastId
});
// Strategy 1: Direct match
let filename = `${podcastId}_system_prompt.txt`;
let filePath = path.join(generatedDir, filename);
let matchStrategy = 'direct';
if (await fs.pathExists(filePath)) {
apiLogger.info('System prompt found via direct match', {
correlationId: req.correlationId,
podcastId,
filename,
strategy: matchStrategy
});
} else {
// Strategy 2: URL decode match (handles %20, %2D, etc.)
try {
const decodedPodcastId = decodeURIComponent(podcastId);
if (decodedPodcastId !== podcastId) {
filename = `${decodedPodcastId}_system_prompt.txt`;
filePath = path.join(generatedDir, filename);
matchStrategy = 'url-decoded';
if (await fs.pathExists(filePath)) {
apiLogger.info('System prompt found via URL decode match', {
correlationId: req.correlationId,
originalPodcastId: podcastId,
decodedPodcastId,
filename,
strategy: matchStrategy
});
}
}
} catch (decodeError) {
apiLogger.warn('URL decode failed', {
correlationId: req.correlationId,
podcastId,
error: decodeError.message
});
}
}
// Strategy 3: Fuzzy search if direct methods failed
if (!await fs.pathExists(filePath)) {
const files = await fs.readdir(generatedDir);
const systemPromptFiles = files.filter(f => f.endsWith('_system_prompt.txt'));
// Look for partial matches
let bestMatch = null;
let bestScore = 0;
for (const file of systemPromptFiles) {
const baseName = file.replace('_system_prompt.txt', '');
// Exact match after removing file extension
if (baseName === podcastId) {
bestMatch = file;
bestScore = 1;
break;
}
// Partial match scoring
const podcastIdLower = podcastId.toLowerCase();
const baseNameLower = baseName.toLowerCase();
if (baseNameLower.includes(podcastIdLower) || podcastIdLower.includes(baseNameLower)) {
const score = Math.min(podcastIdLower.length, baseNameLower.length) /
Math.max(podcastIdLower.length, baseNameLower.length);
if (score > bestScore) {
bestMatch = file;
bestScore = score;
}
}
}
if (bestMatch && bestScore > 0.5) { // Require at least 50% similarity
filename = bestMatch;
filePath = path.join(generatedDir, filename);
matchStrategy = 'fuzzy';
apiLogger.info('System prompt found via fuzzy match', {
correlationId: req.correlationId,
originalPodcastId: podcastId,
matchedFile: bestMatch,
similarity: bestScore,
strategy: matchStrategy
});
}
}
// Check if file exists after all strategies
if (!await fs.pathExists(filePath)) {
apiLogger.warn('System prompt not found after all strategies', {
correlationId: req.correlationId,
podcastId,
searchedStrategies: ['direct', 'url-decoded', 'fuzzy'],
generatedDir
});
return res.status(404).json({
error: 'System prompt not found',
podcastId,
searchedStrategies: ['direct', 'url-decoded', 'fuzzy']
});
}
// Read and return the system prompt content
const content = await fs.readFile(filePath, 'utf-8');