diff --git a/backend/package.json b/backend/package.json index f7dc6ab..668c5fd 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/src/controllers/episodeController.ts b/backend/src/controllers/episodeController.ts index 2cbf9e0..0fd2a57 100644 --- a/backend/src/controllers/episodeController.ts +++ b/backend/src/controllers/episodeController.ts @@ -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' }); + } +}; diff --git a/backend/src/index.ts b/backend/src/index.ts index fc1fbf6..a449d42 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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)}`); diff --git a/backend/src/routes/episodeRoutes.ts b/backend/src/routes/episodeRoutes.ts index 16250db..cb80095 100644 --- a/backend/src/routes/episodeRoutes.ts +++ b/backend/src/routes/episodeRoutes.ts @@ -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); diff --git a/backend/src/services/syncService.ts b/backend/src/services/syncService.ts new file mode 100644 index 0000000..eddefdb --- /dev/null +++ b/backend/src/services/syncService.ts @@ -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); + } + } +}; diff --git a/frontend/src/components/AudioPlayer.tsx b/frontend/src/components/AudioPlayer.tsx index ad8a11a..5517397 100644 --- a/frontend/src/components/AudioPlayer.tsx +++ b/frontend/src/components/AudioPlayer.tsx @@ -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 */}
+ @@ -249,6 +273,9 @@ export default function AudioPlayer({ episode, onClose, userId }: AudioPlayerPro {/* Volume */}
+ diff --git a/frontend/src/components/EpisodeCard.tsx b/frontend/src/components/EpisodeCard.tsx index 49cbe8c..f957608 100644 --- a/frontend/src/components/EpisodeCard.tsx +++ b/frontend/src/components/EpisodeCard.tsx @@ -66,6 +66,16 @@ export default function EpisodeCard({ episode, onPlay }: EpisodeCardProps) {
+ + {/* Local Progress Bar */} + {episode.progress && !episode.progress.isCompleted && ( +
+
+
+ )}
); } diff --git a/frontend/src/pages/AddPodcast.tsx b/frontend/src/pages/AddPodcast.tsx index fffd300..9a1aa65 100644 --- a/frontend/src/pages/AddPodcast.tsx +++ b/frontend/src/pages/AddPodcast.tsx @@ -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(null); const [searchQuery, setSearchQuery] = useState(''); + const [searchType, setSearchType] = useState<'podcasts' | 'episodes'>('podcasts'); const [subscribingId, setSubscribingId] = useState(null); const [rssUrl, setRssUrl] = useState(''); const [rssLoading, setRssLoading] = useState(false); const [rssError, setRssError] = useState(null); const [rssSuccess, setRssSuccess] = useState(null); + const [selectedEpisode, setSelectedEpisode] = useState(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 (
{ /* Logout handled in service/navigation usually */ }} + onLogout={() => {}} />
{/* RSS Input Area */}
-
+
-

Importation Directe

+

Flux RSS Direct

{ setRssUrl(e.target.value); setRssError(null); setRssSuccess(null); }} className="input-premium flex-1" @@ -132,24 +146,44 @@ export default function AddPodcast() {
- {rssError &&

⚠️ {rssError}

} + {rssError &&

⚠️ {rssError}

} {rssSuccess &&

✨ {rssSuccess}

}
- {/* Global Directory Search */} + {/* Global Search Bar with Tabs */}
-
-
- +
+
+
+ +
+

Recherche Intelligente

+
+ + {/* Tabs */} +
+ +
-

Annuaire Global

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() {
{/* Dynamic Results Grid */} - {isSearching ? ( + {(isSearching || isSearchingEpisodes) ? (
{[1,2,3].map(i =>
)}
- ) : searchResults?.podcasts && searchResults.podcasts.length > 0 ? ( + ) : searchType === 'podcasts' && searchResults?.podcasts && searchResults.podcasts.length > 0 ? (
{searchResults.podcasts.map((podcast) => (
@@ -195,21 +229,35 @@ export default function AddPodcast() {
))}
+ ) : searchType === 'episodes' && episodeResults?.episodes && episodeResults.episodes.length > 0 ? ( +
+ {episodeResults.episodes.map((episode) => ( + + ))} +
) : searchQuery.length >= 2 ? (

Aucun signal trouvé

-

Vérifiez l'orthographe ou essayez d'autres mots-clés.

+

Vérifiez l'orthographe ou changez de type de recherche.

) : ( -
-
+
+
)}
+ {selectedEpisode && ( + setSelectedEpisode(null)} + userId={user?._id} + /> + )} + setShowSuccessModal(false)} diff --git a/frontend/src/pages/Dashboard.tsx b/frontend/src/pages/Dashboard.tsx index 2c61782..05bef1e 100644 --- a/frontend/src/pages/Dashboard.tsx +++ b/frontend/src/pages/Dashboard.tsx @@ -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 (
@@ -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 ?

- + {episodesInProgress.length > 0 ? ( + + ) : ( + + )} @@ -90,6 +103,27 @@ export default function Dashboard() {
+ {/* Continue Listening Section (Only if progression exists) */} + {episodesInProgress.length > 0 && ( +
+
+
+ +
+

Continuer l'écoute

+
+
+ {episodesInProgress.map((episode) => ( + + ))} +
+
+ )} + {/* Latest Episodes Section */}