import clsx from "clsx"; import { ProxyImage } from "@/components/custom/proxyImage"; import { AspectRatio } from "@/components/ui/aspect-ratio"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Separator } from "@/components/ui/separator"; import { useToast } from "@/hooks/use-toast"; import { useAppContext } from "@/providers/appContextProvider"; import { useCurrentVideoMetadataStore, useDownloaderPageStatesStore } from "@/services/store"; import { determineFileType, fileFormatFilter, formatBitrate, formatDurationString, formatFileSize, formatReleaseDate, formatYtStyleCount, isObjEmpty, sortByBitrate } from "@/utils"; import { Calendar, Clock, DownloadCloud, Eye, Info, Loader2, Music, ThumbsUp, Video, File, ListVideo, PackageSearch } from "lucide-react"; import { FormatSelectionGroup, FormatSelectionGroupItem } from "@/components/custom/formatSelectionGroup"; import { useEffect, useRef } from "react"; import { ToggleGroup, ToggleGroupItem } from "@/components/custom/legacyToggleGroup"; import { VideoFormat } from "@/types/video"; // import { PlaylistToggleGroup, PlaylistToggleGroupItem } from "@/components/custom/playlistToggleGroup"; import { PlaylistSelectionGroup, PlaylistSelectionGroupItem } from "@/components/custom/playlistSelectionGroup"; import { z } from "zod"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod" import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form"; import { config } from "@/config"; const searchFormSchema = z.object({ url: z.string().min(1, { message: "URL is required" }) .url({message: "Invalid URL format." }), }); export default function DownloaderPage() { const { fetchVideoMetadata, startDownload } = useAppContext(); const { toast } = useToast(); const videoUrl = useCurrentVideoMetadataStore((state) => state.videoUrl); const videoMetadata = useCurrentVideoMetadataStore((state) => state.videoMetadata); const isMetadataLoading = useCurrentVideoMetadataStore((state) => state.isMetadataLoading); const requestedUrl = useCurrentVideoMetadataStore((state) => state.requestedUrl); const autoSubmitSearch = useCurrentVideoMetadataStore((state) => state.autoSubmitSearch); const setVideoUrl = useCurrentVideoMetadataStore((state) => state.setVideoUrl); const setVideoMetadata = useCurrentVideoMetadataStore((state) => state.setVideoMetadata); const setIsMetadataLoading = useCurrentVideoMetadataStore((state) => state.setIsMetadataLoading); const setRequestedUrl = useCurrentVideoMetadataStore((state) => state.setRequestedUrl); const setAutoSubmitSearch = useCurrentVideoMetadataStore((state) => state.setAutoSubmitSearch); const isStartingDownload = useDownloaderPageStatesStore((state) => state.isStartingDownload); const selctedDownloadFormat = useDownloaderPageStatesStore((state) => state.selctedDownloadFormat); const selectedSubtitles = useDownloaderPageStatesStore((state) => state.selectedSubtitles); const selectedPlaylistVideoIndex = useDownloaderPageStatesStore((state) => state.selectedPlaylistVideoIndex); const setIsStartingDownload = useDownloaderPageStatesStore((state) => state.setIsStartingDownload); const setSelctedDownloadFormat = useDownloaderPageStatesStore((state) => state.setSelctedDownloadFormat); const setSelectedSubtitles = useDownloaderPageStatesStore((state) => state.setSelectedSubtitles); const setSelectedPlaylistVideoIndex = useDownloaderPageStatesStore((state) => state.setSelectedPlaylistVideoIndex); const audioOnlyFormats = videoMetadata?._type === 'video' ? sortByBitrate(videoMetadata?.formats.filter(fileFormatFilter('audio'))) : videoMetadata?._type === 'playlist' ? sortByBitrate(videoMetadata?.entries[Number(selectedPlaylistVideoIndex) - 1].formats.filter(fileFormatFilter('audio'))) : []; const videoOnlyFormats = videoMetadata?._type === 'video' ? sortByBitrate(videoMetadata?.formats.filter(fileFormatFilter('video'))) : videoMetadata?._type === 'playlist' ? sortByBitrate(videoMetadata?.entries[Number(selectedPlaylistVideoIndex) - 1].formats.filter(fileFormatFilter('video'))) : []; const combinedFormats = videoMetadata?._type === 'video' ? sortByBitrate(videoMetadata?.formats.filter(fileFormatFilter('video+audio'))) : videoMetadata?._type === 'playlist' ? sortByBitrate(videoMetadata?.entries[Number(selectedPlaylistVideoIndex) - 1].formats.filter(fileFormatFilter('video+audio'))) : []; const av1VideoFormats = videoMetadata?.webpage_url_domain === 'youtube.com' && videoMetadata?._type === 'video' ? sortByBitrate(videoMetadata?.formats.filter((format) => format.vcodec?.startsWith('av01'))) : videoMetadata?.webpage_url_domain === 'youtube.com' && videoMetadata?._type === 'playlist' ? sortByBitrate(videoMetadata?.entries[Number(selectedPlaylistVideoIndex) - 1].formats.filter((format) => format.vcodec?.startsWith('av01'))) : []; const opusAudioFormats = videoMetadata?.webpage_url_domain === 'youtube.com' && videoMetadata?._type === 'video' ? sortByBitrate(videoMetadata?.formats.filter((format) => format.acodec?.startsWith('opus'))) : videoMetadata?.webpage_url_domain === 'youtube.com' && videoMetadata?._type === 'playlist' ? sortByBitrate(videoMetadata?.entries[Number(selectedPlaylistVideoIndex) - 1].formats.filter((format) => format.acodec?.startsWith('opus'))) : []; const qualityPresetFormats: VideoFormat[] | undefined = videoMetadata?.webpage_url_domain === 'youtube.com' ? av1VideoFormats && opusAudioFormats ? av1VideoFormats.map((av1Format) => { const opusFormat = av1Format.format_note.startsWith('144p') || av1Format.format_note.startsWith('240p') ? opusAudioFormats[opusAudioFormats.length - 1] : opusAudioFormats[0] return { ...av1Format, format: `${av1Format.format}+${opusFormat?.format}`, format_id: `${av1Format.format_id}+${opusFormat?.format_id}`, format_note: `${av1Format.format_note}+${opusFormat?.format_note}`, filesize_approx: av1Format.filesize_approx && opusFormat.filesize_approx ? av1Format.filesize_approx + opusFormat.filesize_approx : null, acodec: opusFormat?.acodec, audio_ext: opusFormat.audio_ext, ext: 'webm', tbr: av1Format.tbr && opusFormat.tbr ? av1Format.tbr + opusFormat.tbr : null, }; }) : [] : []; const allFilteredFormats = [...(audioOnlyFormats || []), ...(videoOnlyFormats || []), ...(combinedFormats || []), ...(qualityPresetFormats || [])]; const selectedFormat = (() => { if (videoMetadata?._type === 'video') { if (selctedDownloadFormat === 'best') { return videoMetadata?.requested_downloads[0]; } return allFilteredFormats.find( (format) => format.format_id === selctedDownloadFormat ); } else if (videoMetadata?._type === 'playlist') { if (selctedDownloadFormat === 'best') { return videoMetadata?.entries[Number(selectedPlaylistVideoIndex) - 1].requested_downloads[0]; } return allFilteredFormats.find( (format) => format.format_id === selctedDownloadFormat ); } })(); const selectedFormatFileType = determineFileType(selectedFormat?.vcodec, selectedFormat?.acodec); const subtitles = videoMetadata?._type === 'video' ? (videoMetadata?.subtitles || {}) : videoMetadata?._type === 'playlist' ? (videoMetadata?.entries[Number(selectedPlaylistVideoIndex) - 1].subtitles || {}) : {}; const subtitleLanguages = Object.keys(subtitles).map(langCode => ({ code: langCode, lang: subtitles[langCode][0].name || langCode })); const containerRef = useRef(null); const bottomBarRef = useRef(null); const searchForm = useForm>({ resolver: zodResolver(searchFormSchema), defaultValues: { url: videoUrl, }, mode: "onChange", }) const watchedUrl = searchForm.watch("url"); function handleSearchSubmit(values: z.infer) { setVideoMetadata(null); setIsMetadataLoading(true); setSelctedDownloadFormat('best'); setSelectedSubtitles([]); setSelectedPlaylistVideoIndex('1'); fetchVideoMetadata(values.url).then((metadata) => { if (!metadata || (metadata._type !== 'video' && metadata._type !== 'playlist') || (metadata && metadata._type === 'video' && metadata.formats.length <= 0) || (metadata && metadata._type === 'playlist' && metadata.entries.length <= 0)) { toast({ title: 'Opps! No results found', description: 'The provided URL does not contain any downloadable content. Please check the URL and try again.', variant: "destructive" }); } if (metadata && (metadata._type === 'video' || metadata._type === 'playlist') && ((metadata._type === 'video' && metadata.formats.length > 0) || (metadata._type === 'playlist' && metadata.entries.length > 0))) setVideoMetadata(metadata); if (metadata) console.log(metadata); setIsMetadataLoading(false); }); } useEffect(() => { const updateBottomBarWidth = (): void => { if (containerRef.current && bottomBarRef.current) { bottomBarRef.current.style.width = `${containerRef.current.offsetWidth}px`; const containerRect = containerRef.current.getBoundingClientRect(); bottomBarRef.current.style.left = `${containerRect.left}px`; } }; updateBottomBarWidth(); const resizeObserver = new ResizeObserver(() => { updateBottomBarWidth(); }); if (containerRef.current) { resizeObserver.observe(containerRef.current); } window.addEventListener('resize', updateBottomBarWidth); window.addEventListener('scroll', updateBottomBarWidth); return () => { resizeObserver.disconnect(); window.removeEventListener('resize', updateBottomBarWidth); window.removeEventListener('scroll', updateBottomBarWidth); }; }, []); useEffect(() => { if (watchedUrl !== videoUrl) { setVideoUrl(watchedUrl); } }, [watchedUrl, videoUrl, setVideoUrl]); useEffect(() => { const handleAutoSubmitRequest = async () => { // Update form and state when requestedUrl changes if (requestedUrl && requestedUrl !== searchForm.getValues("url") && !isMetadataLoading) { searchForm.setValue("url", requestedUrl); setVideoUrl(requestedUrl); } // Auto-submit the form if the flag is set if (autoSubmitSearch && requestedUrl) { if (!isMetadataLoading) { // trigger a validation check on the URL field first then get the result await searchForm.trigger("url"); const isValidUrl = !searchForm.getFieldState("url").invalid; if (isValidUrl) { // Reset the flag first to prevent loops setAutoSubmitSearch(false); // Submit the form with a small delay to ensure UI is ready setTimeout(() => { handleSearchSubmit({ url: requestedUrl }); setRequestedUrl(''); }, 300); } else { // If URL is invalid, just reset the flag setAutoSubmitSearch(false); setRequestedUrl(''); toast({ title: 'Invalid URL', description: 'The provided URL is not valid.', variant: "destructive" }); } } else { // If metadata is loading, just reset the flag setAutoSubmitSearch(false); setRequestedUrl(''); toast({ title: 'Search in progress', description: 'Search in progress, try again later.', variant: "destructive" }); } } else { // If auto-submit is not set, reset the flag setAutoSubmitSearch(false); setRequestedUrl(''); } } handleAutoSubmitRequest(); }, [requestedUrl, autoSubmitSearch, isMetadataLoading]); // useEffect(() => { // console.log("Selected playlist items:", selectedVideos) // }), [selectedVideos] return (
{config.appName} Search
( )} />
{!isMetadataLoading && videoMetadata && videoMetadata._type === 'video' && ( // === Single Video ===

Metadata

{videoMetadata.title ? videoMetadata.title : 'UNTITLED'}

{videoMetadata.channel || videoMetadata.uploader || 'unknown'}

{videoMetadata.duration_string ? formatDurationString(videoMetadata.duration_string) : 'unknown'} {videoMetadata.view_count ? formatYtStyleCount(videoMetadata.view_count) : 'unknown'} {videoMetadata.like_count ? formatYtStyleCount(videoMetadata.like_count) : 'unknown'}

{videoMetadata.upload_date ? formatReleaseDate(videoMetadata.upload_date) : 'unknown'}

{videoMetadata.resolution && ( {videoMetadata.resolution} )} {videoMetadata.tbr && ( {formatBitrate(videoMetadata.tbr)} )} {videoMetadata.fps && ( {videoMetadata.fps} fps )} {videoMetadata.subtitles && !isObjEmpty(videoMetadata.subtitles) && ( SUB )} {videoMetadata.dynamic_range && videoMetadata.dynamic_range !== 'SDR' && ( {videoMetadata.dynamic_range} )}
Extracted from {videoMetadata.extractor ? videoMetadata.extractor.charAt(0).toUpperCase() + videoMetadata.extractor.slice(1) : 'Unknown'}

Download Options

{subtitles && !isObjEmpty(subtitles) && ( setSelectedSubtitles(value)} disabled={selectedFormat?.ext !== 'mp4' && selectedFormat?.ext !== 'mkv' && selectedFormat?.ext !== 'webm'} >

Subtitle Languages

{subtitleLanguages.map((lang) => ( {lang.lang} ))}
)} { setSelctedDownloadFormat(value); const currentlySelectedFormat = value === 'best' ? videoMetadata?.requested_downloads[0] : allFilteredFormats.find((format) => format.format_id === value); if (currentlySelectedFormat?.ext !== 'mp4' && currentlySelectedFormat?.ext !== 'mkv' && currentlySelectedFormat?.ext !== 'webm') { setSelectedSubtitles([]); } }} >

Suggested

{qualityPresetFormats && qualityPresetFormats.length > 0 && ( <>

Quality Presets

{qualityPresetFormats.map((format) => ( ))}
)} {audioOnlyFormats && audioOnlyFormats.length > 0 && ( <>

Audio

{audioOnlyFormats.map((format) => ( ))}
)} {videoOnlyFormats && videoOnlyFormats.length > 0 && ( <>

Video {videoOnlyFormats.every(format => format.acodec === 'none') ? '(no audio)' : ''}

{videoOnlyFormats.map((format) => ( ))}
)} {combinedFormats && combinedFormats.length > 0 && ( <>

Video

{combinedFormats.map((format) => ( ))}
)}
)} {!isMetadataLoading && videoMetadata && videoMetadata._type === 'playlist' && ( // === Playlists ===

Playlist ({videoMetadata.entries[0].n_entries})

{videoMetadata.entries[0].playlist_title ? videoMetadata.entries[0].playlist_title : 'UNTITLED'}

{videoMetadata.entries[0].playlist_channel || videoMetadata.entries[0].playlist_uploader || 'unknown'}

{/* {videoMetadata.entries.map((entry) => entry ? ( ) : null)} */} { setSelectedPlaylistVideoIndex(value); setSelctedDownloadFormat('best'); setSelectedSubtitles([]); }} > {videoMetadata.entries.map((entry) => entry ? ( ) : null)}
Extracted from {videoMetadata.entries[0].extractor ? videoMetadata.entries[0].extractor.charAt(0).toUpperCase() + videoMetadata.entries[0].extractor.slice(1) : 'Unknown'}

Download Options

{subtitles && !isObjEmpty(subtitles) && ( setSelectedSubtitles(value)} disabled={selectedFormat?.ext !== 'mp4' && selectedFormat?.ext !== 'mkv' && selectedFormat?.ext !== 'webm'} >

Subtitle Languages

{subtitleLanguages.map((lang) => ( {lang.lang} ))}
)} { setSelctedDownloadFormat(value); const currentlySelectedFormat = value === 'best' ? videoMetadata?.entries[Number(value) - 1].requested_downloads[0] : allFilteredFormats.find((format) => format.format_id === value); if (currentlySelectedFormat?.ext !== 'mp4' && currentlySelectedFormat?.ext !== 'mkv' && currentlySelectedFormat?.ext !== 'webm') { setSelectedSubtitles([]); } }} >

Suggested (Best)

{qualityPresetFormats && qualityPresetFormats.length > 0 && ( <>

Quality Presets

{qualityPresetFormats.map((format) => ( ))}
)} {audioOnlyFormats && audioOnlyFormats.length > 0 && ( <>

Audio

{audioOnlyFormats.map((format) => ( ))}
)} {videoOnlyFormats && videoOnlyFormats.length > 0 && ( <>

Video {videoOnlyFormats.every(format => format.acodec === 'none') ? '(no audio)' : ''}

{videoOnlyFormats.map((format) => ( ))}
)} {combinedFormats && combinedFormats.length > 0 && ( <>

Video

{combinedFormats.map((format) => ( ))}
)}
)} {!isMetadataLoading && videoMetadata && selctedDownloadFormat && ( // === Bottom Bar ===
{selectedFormatFileType && (selectedFormatFileType === 'video' || selectedFormatFileType === 'video+audio') && (
{videoMetadata._type === 'video' ? videoMetadata.title : videoMetadata._type === 'playlist' ? videoMetadata.entries[Number(selectedPlaylistVideoIndex) - 1].title : 'Unknown' } {selectedFormat?.ext ? selectedFormat.ext.toUpperCase() : 'unknown'} ({selectedFormat?.resolution ? selectedFormat.resolution : 'unknown'}) {selectedFormat?.dynamic_range && selectedFormat.dynamic_range !== 'SDR' ? selectedFormat.dynamic_range : null } {selectedSubtitles.length > 0 ? `• ESUB` : null} • {selectedFormat?.filesize_approx ? formatFileSize(selectedFormat?.filesize_approx) : 'unknown filesize'}
)}
); }