feat: implement backend episode management and progress tracking controllers and routes

This commit is contained in:
Michael committed 2026-04-16 14:48:32 +02:00
1 parent 686c4d9007
commit aa54304bf3
9 files changed
+325 -30

No files matched your search

+4 -1
View File
@@ -23,7 +23,10 @@
"cors": "^2.8.5",
"zod": "^3.22.4",
"rss-parser": "^3.12.0",
"axios": "^1.5.0"
"axios": "^1.5.0",
"node-cron": "^3.0.3",
"helmet": "^7.1.0",
"express-rate-limit": "^7.1.5"
},
"devDependencies": {
"@types/express": "^4.17.20",
+80 -2
View File
@@ -31,7 +31,24 @@ export const getLatestEpisodes = async (req: Request, res: Response) => {
.limit(Number(limit))
.skip(Number(skip));
res.json({ episodes, count: episodes.length });
// Fetch progress for these episodes
const episodeIds = episodes.map((e) => e._id);
const progresses = await UserProgress.find({
userId: req.user.id,
episodeId: { $in: episodeIds },
});
const episodesWithProgress = episodes.map((episode) => {
const progress = progresses.find(
(p) => p.episodeId.toString() === episode._id.toString()
);
return {
...episode.toJSON(),
progress: progress ? { position: progress.position, isCompleted: progress.isCompleted } : null,
};
});
res.json({ episodes: episodesWithProgress, count: episodesWithProgress.length });
} catch (error) {
console.error('Get latest episodes error:', error);
res.status(500).json({ message: 'Failed to fetch episodes' });
@@ -48,7 +65,25 @@ export const getPodcastEpisodes = async (req: Request, res: Response) => {
.limit(Number(limit))
.skip(Number(skip));
res.json({ episodes, count: episodes.length });
// If user is authenticated, fetch progress
let episodesWithProgress = episodes.map(e => e.toJSON());
if (req.user) {
const progresses = await UserProgress.find({
userId: req.user.id,
episodeId: { $in: episodes.map(e => e._id) }
});
episodesWithProgress = episodes.map((episode) => {
const progress = progresses.find(
(p) => p.episodeId.toString() === episode._id.toString()
);
return {
...episode.toJSON(),
progress: progress ? { position: progress.position, isCompleted: progress.isCompleted } : null,
};
});
}
res.json({ episodes: episodesWithProgress, count: episodes.length });
} catch (error) {
console.error('Get podcast episodes error:', error);
res.status(500).json({ message: 'Failed to fetch episodes' });
@@ -144,3 +179,46 @@ export const getProgress = async (req: Request, res: Response) => {
res.status(500).json({ message: 'Failed to fetch progress' });
}
};
export const searchEpisodes = async (req: Request, res: Response) => {
try {
const { q, limit = 40, skip = 0 } = req.query;
if (!q) {
return res.status(400).json({ message: 'Search query required' });
}
// Search episodes by title/description using text index
const episodes = await Episode.find(
{ $text: { $search: q as string } },
{ score: { $meta: 'textScore' } }
)
.populate('podcastId', 'title author imageUrl')
.sort({ score: { $meta: 'textScore' } })
.limit(Number(limit))
.skip(Number(skip));
// Fetch progress if authenticated
let episodesWithProgress = episodes.map(e => e.toJSON());
if (req.user) {
const progresses = await UserProgress.find({
userId: req.user.id,
episodeId: { $in: episodes.map(e => e._id) }
});
episodesWithProgress = episodes.map((episode) => {
const progress = progresses.find(
(p) => p.episodeId.toString() === episode._id.toString()
);
return {
...episode.toJSON(),
progress: progress ? { position: progress.position, isCompleted: progress.isCompleted } : null,
};
});
}
res.json({ episodes: episodesWithProgress, count: episodesWithProgress.length });
} catch (error) {
console.error('Search episodes error:', error);
res.status(500).json({ message: 'Search failed' });
}
};
+26 -2
View File
@@ -2,8 +2,11 @@ import express from 'express';
import cors from 'cors';
import 'dotenv/config';
import path from 'path';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import { connectDB } from './config/database';
import { initRedis, closeRedis } from './config/redis';
import { syncService } from './services/syncService';
import { errorHandler } from './middleware/errorHandler';
import authRoutes from './routes/authRoutes';
import podcastRoutes from './routes/podcastRoutes';
@@ -12,6 +15,26 @@ import episodeRoutes from './routes/episodeRoutes';
const app = express();
const PORT = process.env.PORT || 5000;
// Security Middleware
app.use(helmet({
contentSecurityPolicy: false, // Disable CSP for simplicity in this development phase
}));
// Rate Limiting
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per window
message: { message: 'Trop de requêtes, veuillez réessayer plus tard.' },
standardHeaders: true,
legacyHeaders: false,
});
const discoveryLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 50, // lower limit for heavy RSS operations
message: { message: 'Limite de recherche atteinte pour cette heure.' },
});
// Middleware
app.use(cors());
app.use(express.json());
@@ -45,8 +68,8 @@ app.get('/api/health', (req, res) => {
});
app.use('/api/auth', authRoutes);
app.use('/api/podcasts', podcastRoutes);
app.use('/api/episodes', episodeRoutes);
app.use('/api/podcasts', apiLimiter, podcastRoutes);
app.use('/api/episodes', apiLimiter, episodeRoutes);
// Serve frontend static files in production
const frontendDist = path.join(__dirname, '..', 'public');
@@ -79,6 +102,7 @@ process.on('SIGINT', gracefulShutdown);
const startServer = async () => {
try {
await initialize();
syncService.startBackgroundSync();
app.listen(PORT, () => {
console.log(`\n${'='.repeat(50)}`);
+2
View File
@@ -5,6 +5,7 @@ import {
getEpisode,
saveProgress,
getProgress,
searchEpisodes,
} from '../controllers/episodeController';
import { authenticate } from '../middleware/auth';
@@ -12,6 +13,7 @@ const router = Router();
// Protected routes
router.get('/latest', authenticate, getLatestEpisodes);
router.get('/search', authenticate, searchEpisodes);
router.post('/progress', authenticate, saveProgress);
router.get('/progress/:episodeId', authenticate, getProgress);
+69
View File
@@ -0,0 +1,69 @@
import cron from 'node-cron';
import { Podcast } from '../models/Podcast';
import { rssParserService } from './rssParserService';
/**
* Service to handle background synchronization of podcast feeds
*/
export const syncService = {
/**
* Initialize background sync jobs
*/
startBackgroundSync: () => {
console.log('✓ Background Sync Engine started');
// Run every 4 hours
// '0 */4 * * *'
cron.schedule('0 */4 * * *', async () => {
console.log(`[Cron] Starting global library sync: ${new Date().toISOString()}`);
await syncService.syncAllPodcasts();
});
// Run a quick sync for "Zero Episode" podcasts every hour
// (Helpful for new additions that failed initial sync)
cron.schedule('0 * * * *', async () => {
await syncService.syncEmptyPodcasts();
});
},
/**
* Sync all podcasts in the database
*/
syncAllPodcasts: async () => {
try {
const podcasts = await Podcast.find({});
console.log(`[Sync Engine] Processing ${podcasts.length} podcasts...`);
for (const podcast of podcasts) {
try {
await rssParserService.syncPodcastEpisodes(podcast._id.toString(), podcast.rssUrl);
// Wait 5 seconds between podcasts to avoid rate limiting from sources
await new Promise(resolve => setTimeout(resolve, 5000));
} catch (error: any) {
console.error(`[Sync Engine] Failed to sync ${podcast.title}:`, error.message);
}
}
console.log('[Sync Engine] Global sync completed');
} catch (error: any) {
console.error('[Sync Engine] Master sync error:', error.message);
}
},
/**
* Specifically target podcasts with 0 episodes
*/
syncEmptyPodcasts: async () => {
try {
const emptyPodcasts = await Podcast.find({ episodeCount: 0 });
if (emptyPodcasts.length === 0) return;
console.log(`[Sync Engine] Retrying ${emptyPodcasts.length} empty podcasts...`);
for (const podcast of emptyPodcasts) {
await rssParserService.syncPodcastEpisodes(podcast._id.toString(), podcast.rssUrl, true);
}
} catch (error: any) {
console.error('[Sync Engine] Empty podcasts sync error:', error.message);
}
}
};
+28 -1
View File
@@ -24,12 +24,27 @@ export default function AudioPlayer({ episode, onClose, userId }: AudioPlayerPro
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
const [volume, setVolume] = useState(1);
const [volume, setVolume] = useState(() => parseFloat(localStorage.getItem('podcastic-volume') || '1'));
const [playbackSpeed, setPlaybackSpeed] = useState(() => parseFloat(localStorage.getItem('podcastic-speed') || '1'));
const [isMuted, setIsMuted] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const podcast = typeof episode?.podcastId === 'object' ? episode.podcastId : null;
// Sync settings to audio element
useEffect(() => {
if (audioRef.current) {
audioRef.current.volume = isMuted ? 0 : volume;
audioRef.current.playbackRate = playbackSpeed;
}
}, [volume, isMuted, playbackSpeed, episode]);
// Save settings
useEffect(() => {
localStorage.setItem('podcastic-volume', volume.toString());
localStorage.setItem('podcastic-speed', playbackSpeed.toString());
}, [volume, playbackSpeed]);
// Save progress periodically
useEffect(() => {
if (!episode || !userId) return;
@@ -60,6 +75,12 @@ export default function AudioPlayer({ episode, onClose, userId }: AudioPlayerPro
setIsPlaying(!isPlaying);
};
const changeSpeed = () => {
const speeds = [1, 1.25, 1.5, 2, 0.75];
const nextIndex = (speeds.indexOf(playbackSpeed) + 1) % speeds.length;
setPlaybackSpeed(speeds[nextIndex]);
};
const handleSeek = (delta: number) => {
if (!audioRef.current) return;
audioRef.current.currentTime = Math.max(0, Math.min(duration, currentTime + delta));
@@ -163,6 +184,9 @@ export default function AudioPlayer({ episode, onClose, userId }: AudioPlayerPro
{/* Right actions */}
<div className="flex items-center gap-2 shrink-0">
<button onClick={changeSpeed} className="px-2 py-1 rounded-lg bg-white/5 text-[10px] font-black text-slate-500 hover:text-white transition-all uppercase tracking-tighter w-10">
{playbackSpeed}x
</button>
<button onClick={toggleMute} className="p-2 text-slate-500 hover:text-white transition-colors">
{isMuted ? <VolumeX className="w-4 h-4" /> : <Volume2 className="w-4 h-4" />}
</button>
@@ -249,6 +273,9 @@ export default function AudioPlayer({ episode, onClose, userId }: AudioPlayerPro
{/* Volume */}
<div className="flex items-center gap-4">
<button onClick={changeSpeed} className="px-3 py-1.5 rounded-xl bg-white/5 text-xs font-black text-slate-400 hover:text-white transition-all uppercase tracking-widest">
{playbackSpeed}x Speed
</button>
<button onClick={toggleMute} className="text-slate-400 hover:text-white transition-colors shrink-0">
{isMuted ? <VolumeX className="w-5 h-5" /> : <Volume2 className="w-5 h-5" />}
</button>
+10
View File
@@ -66,6 +66,16 @@ export default function EpisodeCard({ episode, onPlay }: EpisodeCardProps) {
</div>
</div>
</div>
{/* Local Progress Bar */}
{episode.progress && !episode.progress.isCompleted && (
<div className="absolute bottom-0 left-0 right-0 h-1 bg-white/5 rounded-b-[2rem] overflow-hidden">
<div
className="h-full bg-accent-indigo shadow-glow-indigo transition-all duration-1000"
style={{ width: `${Math.min(100, (episode.progress.position / episode.duration) * 100)}%` }}
/>
</div>
)}
</div>
);
}
+68 -20
View File
@@ -2,8 +2,11 @@ import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { discoveryService, DiscoveryPodcast } from '../services/discoveryService';
import { podcastService } from '../services/podcastService';
import { episodeService, Episode } from '../services/episodeService';
import Header from '../components/Header';
import { Search, Plus, Loader, Rss, Check, Globe, Sparkles, PlusCircle } from 'lucide-react';
import EpisodeCard from '../components/EpisodeCard';
import AudioPlayer from '../components/AudioPlayer';
import { Search, Plus, Loader, Rss, Check, Globe, Sparkles, PlusCircle, LayoutGrid, ListMusic } from 'lucide-react';
import { authService } from '../services/authService';
import SuccessModal from '../components/SuccessModal';
@@ -11,11 +14,13 @@ export default function AddPodcast() {
const queryClient = useQueryClient();
const [user, setUser] = useState<any>(null);
const [searchQuery, setSearchQuery] = useState('');
const [searchType, setSearchType] = useState<'podcasts' | 'episodes'>('podcasts');
const [subscribingId, setSubscribingId] = useState<string | null>(null);
const [rssUrl, setRssUrl] = useState('');
const [rssLoading, setRssLoading] = useState(false);
const [rssError, setRssError] = useState<string | null>(null);
const [rssSuccess, setRssSuccess] = useState<string | null>(null);
const [selectedEpisode, setSelectedEpisode] = useState<Episode | null>(null);
// Modal state
const [showSuccessModal, setShowSuccessModal] = useState(false);
@@ -33,13 +38,22 @@ export default function AddPodcast() {
loadUser();
}, []);
// Podcast Discovery Query
const { data: searchResults, isLoading: isSearching } = useQuery({
queryKey: ['discover', 'search', searchQuery],
queryFn: () => discoveryService.discoverPodcasts(searchQuery, 30),
enabled: searchQuery.length > 2,
enabled: searchQuery.length > 2 && searchType === 'podcasts',
staleTime: 5 * 60 * 1000,
});
// Episode Global Search Query
const { data: episodeResults, isLoading: isSearchingEpisodes } = useQuery({
queryKey: ['episodes', 'search', searchQuery],
queryFn: () => episodeService.searchEpisodes(searchQuery, 40),
enabled: searchQuery.length > 2 && searchType === 'episodes',
staleTime: 2 * 60 * 1000,
});
const { data: subsData } = useQuery({
queryKey: ['podcasts', 'subscriptions'],
queryFn: () => podcastService.getUserSubscriptions(),
@@ -96,28 +110,28 @@ export default function AddPodcast() {
return (
<div className="min-h-screen">
<Header
title="Ajouter"
subtitle="EXPANSION"
title="Exploration"
subtitle="DÉCOUVRIR"
user={user}
onLogout={() => { /* Logout handled in service/navigation usually */ }}
onLogout={() => {}}
/>
<main className="max-w-5xl mx-auto">
{/* RSS Input Area */}
<div className="premium-glass p-8 rounded-[3rem] mb-12 relative overflow-hidden">
<div className="absolute top-0 right-0 w-32 h-32 bg-accent-rose/5 blur-[50px]" />
<div className="absolute top-0 right-0 w-32 h-32 bg-accent-indigo/5 blur-[50px]" />
<div className="relative z-10">
<div className="flex items-center gap-3 mb-6">
<div className="w-10 h-10 rounded-xl bg-accent-rose/10 flex items-center justify-center text-accent-rose shadow-glow-indigo">
<Rss className="w-5 h-5" />
</div>
<h3 className="text-xl font-display font-black text-white">Importation Directe</h3>
<h3 className="text-xl font-display font-black text-white">Flux RSS Direct</h3>
</div>
<form onSubmit={handleRssSubscribe} className="flex flex-col sm:flex-row gap-4">
<input
type="url"
placeholder="Collez une adresse URL de flux RSS ici..."
placeholder="URL du flux RSS (ex: https://feed.podbean.com/...)"
value={rssUrl}
onChange={(e) => { setRssUrl(e.target.value); setRssError(null); setRssSuccess(null); }}
className="input-premium flex-1"
@@ -132,24 +146,44 @@ export default function AddPodcast() {
</button>
</form>
{rssError && <p className="mt-4 text-xs font-bold text-accent-rose animate-pulse">⚠️ {rssError}</p>}
{rssError && <p className="mt-4 text-xs font-bold text-accent-rose">⚠️ {rssError}</p>}
{rssSuccess && <p className="mt-4 text-xs font-bold text-accent-cyan">✨ {rssSuccess}</p>}
</div>
</div>
{/* Global Directory Search */}
{/* Global Search Bar with Tabs */}
<div className="mb-12">
<div className="flex items-center gap-4 mb-8">
<div className="w-10 h-10 rounded-xl bg-accent-indigo/10 flex items-center justify-center text-accent-indigo shadow-glow-indigo">
<Search className="w-5 h-5" />
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-6 mb-8">
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-xl bg-accent-indigo/10 flex items-center justify-center text-accent-indigo shadow-glow-indigo">
<Search className="w-5 h-5" />
</div>
<h3 className="text-xl font-display font-black text-white">Recherche Intelligente</h3>
</div>
{/* Tabs */}
<div className="flex p-1 rounded-2xl bg-white/[0.03] border border-white/5">
<button
onClick={() => setSearchType('podcasts')}
className={`flex items-center gap-2 px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${searchType === 'podcasts' ? 'bg-white text-obsidian shadow-lg' : 'text-slate-500 hover:text-white'}`}
>
<LayoutGrid className="w-3 h-3" />
Podcasts
</button>
<button
onClick={() => setSearchType('episodes')}
className={`flex items-center gap-2 px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${searchType === 'episodes' ? 'bg-white text-obsidian shadow-lg' : 'text-slate-500 hover:text-white'}`}
>
<ListMusic className="w-3 h-3" />
Épisodes
</button>
</div>
<h3 className="text-xl font-display font-black text-white">Annuaire Global</h3>
</div>
<div className="relative group">
<input
type="text"
placeholder="Rechercher par titre, auteur ou thématique..."
placeholder={searchType === 'podcasts' ? "Trouvez un podcast par titre ou auteur..." : "Cherchez un sujet dans tous les épisodes..."}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="input-premium !py-6 !pl-16 text-xl shadow-2xl transition-all group-hover:bg-white/[0.05]"
@@ -159,11 +193,11 @@ export default function AddPodcast() {
</div>
{/* Dynamic Results Grid */}
{isSearching ? (
{(isSearching || isSearchingEpisodes) ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{[1,2,3].map(i => <div key={i} className="premium-glass rounded-[2.5rem] h-64 animate-pulse bg-white/5" />)}
</div>
) : searchResults?.podcasts && searchResults.podcasts.length > 0 ? (
) : searchType === 'podcasts' && searchResults?.podcasts && searchResults.podcasts.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 pb-32">
{searchResults.podcasts.map((podcast) => (
<div key={podcast.id} className="group premium-glass rounded-[2.5rem] overflow-hidden flex flex-col hover:bg-white/[0.05] transition-all duration-500">
@@ -195,21 +229,35 @@ export default function AddPodcast() {
</div>
))}
</div>
) : searchType === 'episodes' && episodeResults?.episodes && episodeResults.episodes.length > 0 ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8 pb-32">
{episodeResults.episodes.map((episode) => (
<EpisodeCard key={episode._id} episode={episode} onPlay={setSelectedEpisode} />
))}
</div>
) : searchQuery.length >= 2 ? (
<div className="premium-glass p-20 rounded-[3rem] text-center max-w-lg mx-auto">
<Globe className="w-12 h-12 text-slate-700 mx-auto mb-6" />
<p className="text-white font-bold uppercase tracking-widest text-sm mb-2">Aucun signal trouvé</p>
<p className="text-slate-500 text-xs">Vérifiez l'orthographe ou essayez d'autres mots-clés.</p>
<p className="text-slate-500 text-xs">Vérifiez l'orthographe ou changez de type de recherche.</p>
</div>
) : (
<div className="text-center py-20">
<div className="p-8 inline-block rounded-full bg-white/[0.02] border border-white/5 animate-aura">
<div className="text-center py-20 opacity-30">
<div className="p-8 inline-block rounded-full bg-white/[0.02] border border-white/5">
<Search className="w-12 h-12 text-slate-700" />
</div>
</div>
)}
</main>
{selectedEpisode && (
<AudioPlayer
episode={selectedEpisode}
onClose={() => setSelectedEpisode(null)}
userId={user?._id}
/>
)}
<SuccessModal
isOpen={showSuccessModal}
onClose={() => setShowSuccessModal(false)}
+38 -4
View File
@@ -46,6 +46,9 @@ export default function Dashboard() {
}
};
// Extract episodes in progress
const episodesInProgress = episodesData?.episodes?.filter(e => e.progress && !e.progress.isCompleted) || [];
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
@@ -79,10 +82,20 @@ export default function Dashboard() {
Vous avez {episodesData?.count || 0} nouveaux épisodes qui n'attendent que vous. Prêt pour une immersion ?
</p>
<div className="flex flex-wrap gap-4">
<button className="neon-button flex items-center gap-2">
<Play className="w-4 h-4 fill-current" />
Reprendre la lecture
</button>
{episodesInProgress.length > 0 ? (
<button
onClick={() => setSelectedEpisode(episodesInProgress[0])}
className="neon-button flex items-center gap-2"
>
<Play className="w-4 h-4 fill-current" />
Reprendre : {episodesInProgress[0].title.substring(0, 20)}...
</button>
) : (
<button className="neon-button flex items-center gap-2">
<TrendingUp className="w-4 h-4" />
Découvrir
</button>
)}
<button className="px-6 py-3 rounded-2xl bg-white/5 text-slate-300 font-bold text-sm hover:bg-white/10 transition-all border border-white/5">
Parcourir les tendances
</button>
@@ -90,6 +103,27 @@ export default function Dashboard() {
</div>
</div>
{/* Continue Listening Section (Only if progression exists) */}
{episodesInProgress.length > 0 && (
<div className="mb-12 animate-fade-in">
<div className="flex items-center gap-3 mb-6">
<div className="w-10 h-10 rounded-xl bg-accent-indigo/10 flex items-center justify-center text-accent-indigo shadow-glow-indigo">
<Play className="w-5 h-5 fill-current" />
</div>
<h3 className="text-2xl font-display font-black text-white">Continuer l'écoute</h3>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{episodesInProgress.map((episode) => (
<EpisodeCard
key={`progress-${episode._id}`}
episode={episode}
onPlay={setSelectedEpisode}
/>
))}
</div>
</div>
)}
{/* Latest Episodes Section */}
<div className="flex items-center justify-between mb-8">
<div className="flex items-center gap-3">