/** * Anime search and episode management */ /** * Display search results */ async function displaySearchResults(data, lang) { const resultsContainer = document.getElementById('searchResults'); const providers = await getProvidersInfo(); let totalResults = 0; let html = ''; for (const [providerId, results] of Object.entries(data.results)) { if (results && results.length > 0) { totalResults += results.length; results.forEach(anime => { const providerInfo = providers.anime_providers[providerId]; html += renderAnimeCard(anime, providerId, providerInfo, lang); }); } } if (totalResults === 0) { html = '
Aucun résultat trouvé
'; } resultsContainer.innerHTML = html; // Auto-load seasons (for Anime-Sama) or episodes for each anime for (const [providerId, results] of Object.entries(data.results)) { if (results && results.length > 0) { results.forEach(anime => { setTimeout(() => { // Try to load seasons first (for Anime-Sama) loadSeasonsForAnime(providerId, encodeURIComponent(anime.url)); }, 100); }); } } } /** * Render anime card HTML */ function renderAnimeCard(anime, providerId, providerInfo, lang) { const metadataHtml = renderAnimeMetadata(anime.metadata); // Check if this is Anime-Sama (for season support) const isAnimeSama = providerId === 'animesama' || anime.url?.includes('anime-sama'); const seasonSelectHtml = isAnimeSama ? ` ` : ''; return `
${escapeHtml(anime.title)}
${providerInfo?.icon || ''} ${providerInfo?.name || providerId}
${metadataHtml}
${seasonSelectHtml}
`; } /** * Render anime metadata */ function renderAnimeMetadata(metadata) { if (!metadata) return ''; let metaParts = []; if (metadata.release_year) metaParts.push(`📅 ${metadata.release_year}`); if (metadata.rating) metaParts.push(`⭐ ${metadata.rating}`); if (metadata.genres && metadata.genres.length > 0) metaParts.push(`🏷️ ${metadata.genres.slice(0, 3).join(', ')}`); if (metadata.total_episodes) metaParts.push(`📺 ${metadata.total_episodes} épisodes`); if (metadata.status) metaParts.push(`📡 ${metadata.status === 'Ongoing' ? 'En cours' : 'Terminé'}`); let html = ''; if (metaParts.length > 0) { html += `
${metaParts.join(' • ')}
`; } if (metadata.synopsis) { html += `
📖 Synopsis

${escapeHtml(metadata.synopsis)}

`; } return html; } /** * Load seasons for Anime-Sama anime */ async function loadSeasonsForAnime(providerId, encodedUrl) { const url = decodeURIComponent(encodedUrl); const seasonSelectId = `seasons-${providerId}-${encodedUrl}`; const seasonSelectElement = document.getElementById(seasonSelectId); if (!seasonSelectElement) return; // Only proceed if this is Anime-Sama if (!url.includes('anime-sama')) { seasonSelectElement.style.display = 'none'; return; } try { const response = await fetch(`${API_BASE}/anime/seasons?url=${encodeURIComponent(url)}`); if (response.ok) { const data = await response.json(); if (data.seasons && data.seasons.length > 0) { seasonSelectElement.innerHTML = ''; data.seasons.forEach(season => { const option = document.createElement('option'); option.value = season.url; option.textContent = `${season.title} (${season.episode_count} épisodes)`; option.dataset.seasonNum = season.season; seasonSelectElement.appendChild(option); }); console.log(`Loaded ${data.seasons.length} seasons`); } else { // No seasons found, hide season selector and load episodes directly seasonSelectElement.style.display = 'none'; loadEpisodesForAnime(providerId, encodedUrl, 'vostfr'); } } else { console.error('Failed to load seasons'); seasonSelectElement.style.display = 'none'; loadEpisodesForAnime(providerId, encodedUrl, 'vostfr'); } } catch (error) { console.error('Error loading seasons:', error); seasonSelectElement.style.display = 'none'; loadEpisodesForAnime(providerId, encodedUrl, 'vostfr'); } } /** * Handle season selection change */ async function handleSeasonChange(providerId, encodedUrl, lang) { const seasonSelectId = `seasons-${providerId}-${encodedUrl}`; const seasonSelectElement = document.getElementById(seasonSelectId); const selectedSeasonUrl = seasonSelectElement.value; const encodedSeasonUrl = encodeURIComponent(selectedSeasonUrl); if (!selectedSeasonUrl) { // Clear episodes if no season selected const episodeSelectId = `episodes-${providerId}-${encodedUrl}`; const episodeSelectElement = document.getElementById(episodeSelectId); episodeSelectElement.innerHTML = ''; episodeSelectElement.disabled = true; return; } // Find the episode select element (it's based on the original anime URL) const episodeSelectId = `episodes-${providerId}-${encodedUrl}`; const selectElement = document.getElementById(episodeSelectId); if (!selectElement) { console.error('Episode select element not found:', episodeSelectId); return; } // Show loading state selectElement.innerHTML = ''; selectElement.disabled = false; try { // Load episodes for the selected season const data = await loadEpisodes(selectedSeasonUrl, lang); if (data.episodes && data.episodes.length > 0) { selectElement.innerHTML = ''; data.episodes.forEach(ep => { const option = document.createElement('option'); option.value = ep.url; option.textContent = `Épisode ${ep.episode}`; selectElement.appendChild(option); }); // Show download buttons const actionsId = `actions-${providerId}-${encodedUrl}`; const actionsDiv = document.getElementById(actionsId); actionsDiv.style.display = 'flex'; } else { selectElement.innerHTML = ''; selectElement.disabled = true; } } catch (error) { console.error('Error loading episodes:', error); selectElement.innerHTML = ''; } } /** * Load episodes for an anime */ async function loadEpisodesForAnime(providerId, encodedUrl, lang) { const url = decodeURIComponent(encodedUrl); const selectId = `episodes-${providerId}-${encodedUrl}`; const actionsId = `actions-${providerId}-${encodedUrl}`; const selectElement = document.getElementById(selectId); if (!selectElement) return; selectElement.innerHTML = ''; try { const data = await loadEpisodes(url, lang); if (data.episodes && data.episodes.length > 0) { selectElement.innerHTML = ''; data.episodes.forEach(ep => { const option = document.createElement('option'); option.value = ep.url; option.textContent = `Épisode ${ep.episode}`; selectElement.appendChild(option); }); // Show download buttons const actionsDiv = document.getElementById(actionsId); actionsDiv.style.display = 'flex'; } else { selectElement.innerHTML = ''; selectElement.disabled = true; // Add warning message const card = document.getElementById(`anime-${providerId}-${encodedUrl}`); if (card) { const warning = document.createElement('div'); warning.style.cssText = 'margin-top: 10px; padding: 10px; background: rgba(255, 100, 100, 0.2); border-radius: 6px; font-size: 12px; color: #ff6b6b;'; warning.textContent = '⚠️ Aucun épisode trouvé. Essayez une recherche exacte ou un autre fournisseur.'; card.appendChild(warning); } } } catch (error) { console.error('Error loading episodes:', error); selectElement.innerHTML = ''; } } /** * Handle episode download */ async function handleDownloadEpisode(encodedUrl, providerId, lang) { const url = decodeURIComponent(encodedUrl); const selectId = `episodes-${providerId}-${encodedUrl}`; const selectElement = document.getElementById(selectId); const episodeUrl = selectElement.value; if (!episodeUrl) { alert('Veuillez sélectionner un épisode'); return; } try { await downloadEpisode(episodeUrl); loadDownloads(); alert('Téléchargement démarré!'); selectElement.value = ''; } catch (error) { console.error('Download error:', error); alert('Erreur lors du démarrage du téléchargement'); } } /** * Handle season download */ async function handleDownloadSeason(encodedUrl, lang) { const url = decodeURIComponent(encodedUrl); if (!confirm(`⚠️ Attention: Vous allez télécharger toute la saison. Cela peut prendre du temps et utiliser beaucoup d'espace disque.\n\nVoulez-vous continuer ?`)) { return; } try { const data = await downloadSeason(url, lang); loadDownloads(); alert(`✅ ${data.message}\n\n${data.total_episodes} épisodes ont été ajoutés à la file de téléchargement!`); } catch (error) { console.error('Season download error:', error); alert('Erreur lors du démarrage du téléchargement de la saison'); } } /** * Handle search form submission */ async function handleSearch() { const query = document.getElementById('searchInput').value.trim(); if (!query) return; // Use the new anime details search await searchAnimeDetails(query); } // Ensure global scope window.handleSearch = handleSearch; /** * Handle direct download form submission */ async function handleDirectDownload(e) { e.preventDefault(); const url = document.getElementById('urlInput').value; try { await startDownload(url); document.getElementById('urlInput').value = ''; loadDownloads(); } catch (error) { console.error('Download error:', error); alert('Erreur lors du démarrage du téléchargement'); } } // Ensure all functions are globally accessible window.displaySearchResults = displaySearchResults; window.renderAnimeCard = renderAnimeCard; window.renderAnimeMetadata = renderAnimeMetadata; window.loadSeasonsForAnime = loadSeasonsForAnime; window.handleSeasonChange = handleSeasonChange; window.loadEpisodesForAnime = loadEpisodesForAnime; window.handleDownloadEpisode = handleDownloadEpisode; window.handleDownloadSeason = handleDownloadSeason; window.handleSearch = handleSearch; window.handleDirectDownload = handleDirectDownload;