(chore): initial MVP release v0.1.0

This commit is contained in:
2025-04-28 23:49:42 +05:30
commit c73022b1a2
200 changed files with 24562 additions and 0 deletions

651
src/pages/downloader.tsx Normal file
View File

@@ -0,0 +1,651 @@
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 } from "lucide-react";
import { FormatSelectionGroup, FormatSelectionGroupItem } from "@/components/custom/formatSelectionGroup";
import { useEffect, useRef } from "react";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
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<HTMLDivElement>(null);
const bottomBarRef = useRef<HTMLDivElement>(null);
const searchForm = useForm<z.infer<typeof searchFormSchema>>({
resolver: zodResolver(searchFormSchema),
defaultValues: {
url: videoUrl,
},
mode: "onChange",
})
const watchedUrl = searchForm.watch("url");
function handleSearchSubmit(values: z.infer<typeof searchFormSchema>) {
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 (
<div className="container mx-auto p-4 space-y-4 relative" ref={containerRef}>
<Card>
<CardHeader>
<CardTitle>{config.appName} Search</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<Form {...searchForm}>
<form onSubmit={searchForm.handleSubmit(handleSearchSubmit)} className="flex gap-2 w-full" autoComplete="off">
<FormField
control={searchForm.control}
name="url"
disabled={isMetadataLoading}
render={({ field }) => (
<FormItem className="w-full">
<FormControl>
<Input
className="focus-visible:ring-0"
placeholder="Enter URL to search..."
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
type="submit"
disabled={!videoUrl || isMetadataLoading}
>
{isMetadataLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Searching
</>
) : (
'Search'
)}
</Button>
</form>
</Form>
</CardContent>
</Card>
{!isMetadataLoading && videoMetadata && videoMetadata._type === 'video' && ( // === Single Video ===
<div className="flex">
<div className="flex flex-col w-[55%] border-r border-border pr-4">
<h3 className="text-sm mb-4 flex items-center gap-2">
<Info className="w-4 h-4" />
<span>Metadata</span>
</h3>
<div className="flex flex-col overflow-y-scroll max-h-[53vh] no-scrollbar">
<AspectRatio ratio={16 / 9} className={clsx("w-full rounded-lg overflow-hidden mb-2 border border-border", videoMetadata.aspect_ratio && videoMetadata.aspect_ratio === 0.56 && "relative")}>
<ProxyImage src={videoMetadata.thumbnail} alt="thumbnail" className={clsx(videoMetadata.aspect_ratio && videoMetadata.aspect_ratio === 0.56 && "absolute h-full w-auto top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2")} />
</AspectRatio>
<h2 className="mb-1">{videoMetadata.title ? videoMetadata.title : 'UNTITLED'}</h2>
<p className="text-muted-foreground text-xs mb-2">{videoMetadata.channel || videoMetadata.uploader || 'unknown'}</p>
<div className="flex items-center mb-2">
<span className="text-xs text-muted-foreground flex items-center pr-3"><Clock className="w-4 h-4 mr-2"/> {videoMetadata.duration_string ? formatDurationString(videoMetadata.duration_string) : 'unknown'}</span>
<Separator orientation="vertical" />
<span className="text-xs text-muted-foreground flex items-center px-3"><Eye className="w-4 h-4 mr-2"/> {videoMetadata.view_count ? formatYtStyleCount(videoMetadata.view_count) : 'unknown'}</span>
<Separator orientation="vertical" />
<span className="text-xs text-muted-foreground flex items-center pl-3"><ThumbsUp className="w-4 h-4 mr-2"/> {videoMetadata.like_count ? formatYtStyleCount(videoMetadata.like_count) : 'unknown'}</span>
</div>
<p className="text-xs text-muted-foreground flex items-center gap-2 mb-2">
<Calendar className="w-4 h-4" />
<span className="">{videoMetadata.upload_date ? formatReleaseDate(videoMetadata.upload_date) : 'unknown'}</span>
</p>
<div className="flex flex-wrap gap-2 text-xs mb-2">
{videoMetadata.resolution && (
<span className="border border-border py-1 px-2 rounded">{videoMetadata.resolution}</span>
)}
{videoMetadata.tbr && (
<span className="border border-border py-1 px-2 rounded">{formatBitrate(videoMetadata.tbr)}</span>
)}
{videoMetadata.fps && (
<span className="border border-border py-1 px-2 rounded">{videoMetadata.fps} fps</span>
)}
{videoMetadata.subtitles && !isObjEmpty(videoMetadata.subtitles) && (
<span className="border border-border py-1 px-2 rounded">SUB</span>
)}
{videoMetadata.dynamic_range && videoMetadata.dynamic_range !== 'SDR' && (
<span className="border border-border py-1 px-2 rounded">{videoMetadata.dynamic_range}</span>
)}
</div>
<div className="flex items-center text-muted-foreground">
<Info className="w-3 h-3 mr-2" />
<span className="text-xs">Extracted from {videoMetadata.extractor ? videoMetadata.extractor.charAt(0).toUpperCase() + videoMetadata.extractor.slice(1) : 'Unknown'}</span>
</div>
<div className="spacer mb-14"></div>
</div>
</div>
<div className="flex flex-col w-full pl-4">
<h3 className="text-sm mb-4 flex items-center gap-2">
<DownloadCloud className="w-4 h-4" />
<span>Download Options</span>
</h3>
<div className="flex flex-col overflow-y-scroll max-h-[53vh] no-scrollbar">
{subtitles && !isObjEmpty(subtitles) && (
<ToggleGroup
type="multiple"
variant="outline"
className="flex flex-col items-start gap-2 mb-2"
value={selectedSubtitles}
onValueChange={(value) => setSelectedSubtitles(value)}
disabled={selectedFormat?.ext !== 'mp4' && selectedFormat?.ext !== 'mkv' && selectedFormat?.ext !== 'webm'}
>
<p className="text-xs">Subtitle Languages</p>
<div className="flex gap-2 flex-wrap items-center">
{subtitleLanguages.map((lang) => (
<ToggleGroupItem
className="text-xs text-nowrap border-2 data-[state=on]:border-2 data-[state=on]:border-primary data-[state=on]:bg-muted/70 hover:bg-muted/70"
value={lang.code}
size="sm"
aria-label={lang.lang}
key={lang.code}>
{lang.lang}
</ToggleGroupItem>
))}
</div>
</ToggleGroup>
)}
<FormatSelectionGroup
value={selctedDownloadFormat}
onValueChange={(value) => {
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([]);
}
}}
>
<p className="text-xs">Suggested (Best)</p>
<div className="">
<FormatSelectionGroupItem
key="best"
value="best"
format={videoMetadata.requested_downloads[0]}
/>
</div>
{qualityPresetFormats && qualityPresetFormats.length > 0 && (
<>
<p className="text-xs">Quality Presets</p>
<div className="grid grid-cols-2 xl:grid-cols-3 gap-2">
{qualityPresetFormats.map((format) => (
<FormatSelectionGroupItem
key={format.format_id}
value={format.format_id}
format={format}
/>
))}
</div>
</>
)}
{audioOnlyFormats && audioOnlyFormats.length > 0 && (
<>
<p className="text-xs">Audio</p>
<div className="grid grid-cols-2 xl:grid-cols-3 gap-2">
{audioOnlyFormats.map((format) => (
<FormatSelectionGroupItem
key={format.format_id}
value={format.format_id}
format={format}
/>
))}
</div>
</>
)}
{videoOnlyFormats && videoOnlyFormats.length > 0 && (
<>
<p className="text-xs">Video {videoOnlyFormats.every(format => format.acodec === 'none') ? '(no audio)' : ''}</p>
<div className="grid grid-cols-2 xl:grid-cols-3 gap-2">
{videoOnlyFormats.map((format) => (
<FormatSelectionGroupItem
key={format.format_id}
value={format.format_id}
format={format}
/>
))}
</div>
</>
)}
{combinedFormats && combinedFormats.length > 0 && (
<>
<p className="text-xs">Video</p>
<div className="grid grid-cols-2 xl:grid-cols-3 gap-2">
{combinedFormats.map((format) => (
<FormatSelectionGroupItem
key={format.format_id}
value={format.format_id}
format={format}
/>
))}
</div>
</>
)}
</FormatSelectionGroup>
<div className="spacer mb-14"></div>
</div>
</div>
</div>
)}
{!isMetadataLoading && videoMetadata && videoMetadata._type === 'playlist' && ( // === Playlists ===
<div className="flex">
<div className="flex flex-col w-[55%] border-r border-border pr-4">
<h3 className="text-sm mb-4 flex items-center gap-2">
<ListVideo className="w-4 h-4" />
<span>Playlist ({videoMetadata.entries[0].n_entries})</span>
</h3>
<div className="flex flex-col overflow-y-scroll max-h-[53vh] no-scrollbar">
<h2 className="mb-1">{videoMetadata.entries[0].playlist_title ? videoMetadata.entries[0].playlist_title : 'UNTITLED'}</h2>
<p className="text-muted-foreground text-xs mb-4">{videoMetadata.entries[0].playlist_channel || videoMetadata.entries[0].playlist_uploader || 'unknown'}</p>
{/* <PlaylistToggleGroup
className="mb-2"
type="multiple"
value={selectedVideos}
onValueChange={setSelectedVideos}
>
{videoMetadata.entries.map((entry) => entry ? (
<PlaylistToggleGroupItem
key={entry.playlist_index}
value={entry.playlist_index.toString()}
video={entry}
/>
) : null)}
</PlaylistToggleGroup> */}
<PlaylistSelectionGroup
className="mb-2"
value={selectedPlaylistVideoIndex}
onValueChange={(value) => {
setSelectedPlaylistVideoIndex(value);
setSelctedDownloadFormat('best');
setSelectedSubtitles([]);
}}
>
{videoMetadata.entries.map((entry) => entry ? (
<PlaylistSelectionGroupItem
key={entry.playlist_index}
value={entry.playlist_index.toString()}
video={entry}
/>
) : null)}
</PlaylistSelectionGroup>
<div className="flex items-center text-muted-foreground">
<Info className="w-3 h-3 mr-2" />
<span className="text-xs">Extracted from {videoMetadata.entries[0].extractor ? videoMetadata.entries[0].extractor.charAt(0).toUpperCase() + videoMetadata.entries[0].extractor.slice(1) : 'Unknown'}</span>
</div>
<div className="spacer mb-14"></div>
</div>
</div>
<div className="flex flex-col w-full pl-4">
<h3 className="text-sm mb-4 flex items-center gap-2">
<DownloadCloud className="w-4 h-4" />
<span>Download Options</span>
</h3>
<div className="flex flex-col overflow-y-scroll max-h-[53vh] no-scrollbar">
{subtitles && !isObjEmpty(subtitles) && (
<ToggleGroup
type="multiple"
variant="outline"
className="flex flex-col items-start gap-2 mb-2"
value={selectedSubtitles}
onValueChange={(value) => setSelectedSubtitles(value)}
disabled={selectedFormat?.ext !== 'mp4' && selectedFormat?.ext !== 'mkv' && selectedFormat?.ext !== 'webm'}
>
<p className="text-xs">Subtitle Languages</p>
<div className="flex gap-2 flex-wrap items-center">
{subtitleLanguages.map((lang) => (
<ToggleGroupItem
className="text-xs text-nowrap border-2 data-[state=on]:border-2 data-[state=on]:border-primary data-[state=on]:bg-muted/70 hover:bg-muted/70"
value={lang.code}
size="sm"
aria-label={lang.lang}
key={lang.code}>
{lang.lang}
</ToggleGroupItem>
))}
</div>
</ToggleGroup>
)}
<FormatSelectionGroup
value={selctedDownloadFormat}
onValueChange={(value) => {
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([]);
}
}}
>
<p className="text-xs">Suggested (Best)</p>
<div className="">
<FormatSelectionGroupItem
key="best"
value="best"
format={videoMetadata.entries[Number(selectedPlaylistVideoIndex) - 1].requested_downloads[0]}
/>
</div>
{qualityPresetFormats && qualityPresetFormats.length > 0 && (
<>
<p className="text-xs">Quality Presets</p>
<div className="grid grid-cols-2 xl:grid-cols-3 gap-2">
{qualityPresetFormats.map((format) => (
<FormatSelectionGroupItem
key={format.format_id}
value={format.format_id}
format={format}
/>
))}
</div>
</>
)}
{audioOnlyFormats && audioOnlyFormats.length > 0 && (
<>
<p className="text-xs">Audio</p>
<div className="grid grid-cols-2 xl:grid-cols-3 gap-2">
{audioOnlyFormats.map((format) => (
<FormatSelectionGroupItem
key={format.format_id}
value={format.format_id}
format={format}
/>
))}
</div>
</>
)}
{videoOnlyFormats && videoOnlyFormats.length > 0 && (
<>
<p className="text-xs">Video {videoOnlyFormats.every(format => format.acodec === 'none') ? '(no audio)' : ''}</p>
<div className="grid grid-cols-2 xl:grid-cols-3 gap-2">
{videoOnlyFormats.map((format) => (
<FormatSelectionGroupItem
key={format.format_id}
value={format.format_id}
format={format}
/>
))}
</div>
</>
)}
{combinedFormats && combinedFormats.length > 0 && (
<>
<p className="text-xs">Video</p>
<div className="grid grid-cols-2 xl:grid-cols-3 gap-2">
{combinedFormats.map((format) => (
<FormatSelectionGroupItem
key={format.format_id}
value={format.format_id}
format={format}
/>
))}
</div>
</>
)}
</FormatSelectionGroup>
<div className="spacer mb-14"></div>
</div>
</div>
</div>
)}
{!isMetadataLoading && videoMetadata && selctedDownloadFormat && ( // === Bottom Bar ===
<div className="flex justify-between items-center gap-2 fixed bottom-0 right-0 p-4 w-full bg-background rounded-t-lg border-t border-border z-20" ref={bottomBarRef}>
<div className="flex items-center gap-4">
<div className="flex justify-center items-center p-3 rounded-md border border-border">
{selectedFormatFileType && (selectedFormatFileType === 'video' || selectedFormatFileType === 'video+audio') && (
<Video className="w-4 h-4" />
)}
{selectedFormatFileType && selectedFormatFileType === 'audio' && (
<Music className="w-4 h-4" />
)}
{(!selectedFormatFileType) || (selectedFormatFileType && selectedFormatFileType !== 'video' && selectedFormatFileType !== 'audio' && selectedFormatFileType !== 'video+audio') && (
<File className="w-4 h-4" />
)}
</div>
<div className="flex flex-col gap-1">
<span className="text-sm text-nowrap max-w-[30rem] xl:max-w-[50rem] overflow-hidden text-ellipsis">{videoMetadata._type === 'video' ? videoMetadata.title : videoMetadata._type === 'playlist' ? videoMetadata.entries[Number(selectedPlaylistVideoIndex) - 1].title : 'Unknown' }</span>
<span className="text-xs text-muted-foreground">{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'}</span>
</div>
</div>
<Button
onClick={async () => {
setIsStartingDownload(true);
try {
if (videoMetadata._type === 'playlist') {
await startDownload(
videoMetadata.original_url,
selctedDownloadFormat === 'best' ? videoMetadata.entries[Number(selectedPlaylistVideoIndex) - 1].requested_downloads[0].format_id : selctedDownloadFormat,
selectedSubtitles.length > 0 ? selectedSubtitles.join(',') : null,
undefined,
selectedPlaylistVideoIndex
);
} else if (videoMetadata._type === 'video') {
await startDownload(
videoMetadata.webpage_url,
selctedDownloadFormat === 'best' ? videoMetadata.requested_downloads[0].format_id : selctedDownloadFormat,
selectedSubtitles.length > 0 ? selectedSubtitles.join(',') : null
);
}
// toast({
// title: 'Download Initiated',
// description: 'Download initiated, it will start shortly.',
// });
} catch (error) {
console.error('Download failed to start:', error);
toast({
title: 'Failed to Start Download',
description: 'There was an error initiating the download.',
variant: "destructive"
});
} finally {
setIsStartingDownload(false);
}
}}
disabled={isStartingDownload}
>
{isStartingDownload ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Starting
</>
) : (
'Start Download'
)}
</Button>
</div>
)}
</div>
);
}

22
src/pages/layout/root.tsx Normal file
View File

@@ -0,0 +1,22 @@
import { Outlet } from "react-router-dom";
import { SidebarProvider } from "@/components/ui/sidebar";
import { AppSidebar } from "@/components/sidebar";
import Navbar from "@/components/navbar";
import Footer from "@/components/footer";
export default function RootLayout() {
return (
<>
<div className="flex min-h-screen">
<SidebarProvider>
<AppSidebar />
<div className="w-full h-screen overflow-y-scroll relative">
<Navbar/>
<Outlet />
<Footer/>
</div>
</SidebarProvider>
</div>
</>
);
}

424
src/pages/library.tsx Normal file
View File

@@ -0,0 +1,424 @@
import { IndeterminateProgress } from "@/components/custom/indeterminateProgress";
import { ProxyImage } from "@/components/custom/proxyImage";
import { AspectRatio } from "@/components/ui/aspect-ratio";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { Separator } from "@/components/ui/separator";
import { useToast } from "@/hooks/use-toast";
import { useAppContext } from "@/providers/appContextProvider";
import { useDownloadActionStatesStore, useDownloadStatesStore } from "@/services/store";
import { formatBitrate, formatCodec, formatDurationString, formatFileSize, formatSecToTimeString, formatSpeed } from "@/utils";
import { AudioLines, CircleArrowDown, CircleCheck, Clock, File, FileAudio2, FileQuestion, FileVideo2, FolderInput, ListVideo, Loader2, Music, Pause, Play, Trash2, Video, X } from "lucide-react";
import { invoke } from "@tauri-apps/api/core";
import * as fs from "@tauri-apps/plugin-fs";
import { DownloadState } from "@/types/download";
import { useQueryClient } from "@tanstack/react-query";
import { useDeleteDownloadState } from "@/services/mutations";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import Heading from "@/components/heading";
export default function LibraryPage() {
const downloadStates = useDownloadStatesStore(state => state.downloadStates);
const downloadActions = useDownloadActionStatesStore(state => state.downloadActions);
const setIsResumingDownload = useDownloadActionStatesStore(state => state.setIsResumingDownload);
const setIsPausingDownload = useDownloadActionStatesStore(state => state.setIsPausingDownload);
const setIsCancelingDownload = useDownloadActionStatesStore(state => state.setIsCancelingDownload);
const setIsDeleteFileChecked = useDownloadActionStatesStore(state => state.setIsDeleteFileChecked);
const { pauseDownload, resumeDownload, cancelDownload } = useAppContext()
const { toast } = useToast();
const queryClient = useQueryClient();
const downloadStateDeleter = useDeleteDownloadState();
const incompleteDownloads = downloadStates.filter(state => state.download_status !== 'completed');
const completedDownloads = downloadStates.filter(state => state.download_status === 'completed');
const openFile = async (filePath: string | null, app: string | null) => {
if (filePath && await fs.exists(filePath)) {
try {
await invoke('open_file_with_app', { filePath: filePath, appName: app }).then(() => {
toast({
title: 'Opening file',
description: `Opening the file with ${app ? app : 'default app'}.`,
})
});
} catch (e) {
console.error(e);
toast({
title: 'Failed to open file',
description: 'An error occurred while trying to open the file.',
variant: "destructive"
})
}
} else {
toast({
title: 'File unavailable',
description: 'The file you are trying to open does not exist.',
variant: "destructive"
})
}
}
const removeFromDownloads = async (downloadState: DownloadState, delete_file: boolean) => {
if (delete_file && downloadState.filepath) {
try {
if (await fs.exists(downloadState.filepath)) {
await fs.remove(downloadState.filepath);
} else {
console.error(`File not found: ${downloadState.filepath}`);
}
} catch (e) {
console.error(e);
}
}
downloadStateDeleter.mutate(downloadState.download_id, {
onSuccess: (data) => {
console.log("Download State deleted successfully:", data);
queryClient.invalidateQueries({ queryKey: ['download-states'] });
toast({
title: 'Removed from downloads',
description: 'The download has been removed successfully.',
})
},
onError: (error) => {
console.error("Failed to delete download state:", error);
toast({
title: 'Failed to remove download',
description: 'An error occurred while trying to remove the download.',
variant: "destructive"
})
}
})
}
return (
<div className="container mx-auto p-4 space-y-4">
<Heading title="Library" description="Manage all your downloads in one place" />
<div className="w-full fle flex-col">
<div className="flex w-full items-center gap-2 mb-2">
<CircleArrowDown className="size-4" />
<h3 className="text-nowrap font-semibold">Incomplete Downloads</h3>
</div>
<Separator orientation="horizontal" className="" />
</div>
<div className="w-full flex flex-col gap-2">
{incompleteDownloads.length > 0 ? (
incompleteDownloads.map((state) => {
const itemActionStates = downloadActions[state.download_id] || {
isResuming: false,
isPausing: false,
isCanceling: false,
isDeleteFileChecked: false,
};
return (
<div className="p-4 border border-border rounded-lg flex gap-4" key={state.download_id}>
<div className="w-[30%] flex flex-col justify-between gap-2">
<AspectRatio ratio={16 / 9} className="w-full rounded-lg overflow-hidden border border-border">
<ProxyImage src={state.thumbnail || ""} alt="thumbnail" className="" />
</AspectRatio>
{state.ext && (
<span className="w-full flex items-center justify-center text-xs border border-border py-1 px-2 rounded">
{state.filetype && (state.filetype === 'video' || state.filetype === 'video+audio') && (
<Video className="w-4 h-4 mr-2" />
)}
{state.filetype && state.filetype === 'audio' && (
<Music className="w-4 h-4 mr-2" />
)}
{(!state.filetype) || (state.filetype && state.filetype !== 'video' && state.filetype !== 'audio' && state.filetype !== 'video+audio') && (
<File className="w-4 h-4 mr-2" />
)}
{state.ext.toUpperCase()} {state.resolution ? `(${state.resolution})` : null}
</span>
)}
</div>
<div className="w-full flex flex-col justify-between">
<div className="flex flex-col gap-1">
<h4>{state.title}</h4>
{((state.download_status === 'starting') || (state.download_status === 'downloading' && state.status === 'finished')) && (
<IndeterminateProgress indeterminate={true} className="w-full" />
)}
{(state.download_status === 'downloading' || state.download_status === 'paused') && state.progress && state.status !== 'finished' && (
<div className="w-full flex items-center gap-2">
<span className="text-sm text-nowrap">{state.progress}%</span>
<Progress value={state.progress} />
<span className="text-sm text-nowrap">{
state.downloaded && state.total
? `(${formatFileSize(state.downloaded)} / ${formatFileSize(state.total)})`
: null
}</span>
</div>
)}
<div className="text-xs text-muted-foreground">{ state.download_status && (
`${state.download_status === 'downloading' && state.status === 'finished' ? 'Processing' : state.download_status.charAt(0).toUpperCase() + state.download_status.slice(1)} ${state.download_status === 'downloading' && state.status !== 'finished' && state.speed ? `• Speed: ${formatSpeed(state.speed)}` : ""} ${state.download_status === 'downloading' && state.eta ? `• ETA: ${formatSecToTimeString(state.eta)}` : ""}`
)}</div>
</div>
<div className="w-full flex items-center gap-2 mt-2">
{state.download_status === 'paused' ? (
<Button
size="sm"
className="w-fill"
onClick={async () => {
setIsResumingDownload(state.download_id, true);
try {
await resumeDownload(state)
// toast({
// title: 'Resumed Download',
// description: 'Download resumed, it will re-start shortly.',
// })
} catch (e) {
console.error(e);
toast({
title: 'Failed to Resume Download',
description: 'An error occurred while trying to resume the download.',
variant: "destructive"
})
} finally {
setIsResumingDownload(state.download_id, false);
}
}}
disabled={itemActionStates.isResuming || itemActionStates.isCanceling}
>
{itemActionStates.isResuming ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Resuming
</>
) : (
<>
<Play className="w-4 h-4" />
Resume
</>
)}
</Button>
) : (
<Button
size="sm"
className="w-fill"
onClick={async () => {
setIsPausingDownload(state.download_id, true);
try {
await pauseDownload(state)
// toast({
// title: 'Paused Download',
// description: 'Download paused successfully.',
// })
} catch (e) {
console.error(e);
toast({
title: 'Failed to Pause Download',
description: 'An error occurred while trying to pause the download.',
variant: "destructive"
})
} finally {
setIsPausingDownload(state.download_id, false);
}
}}
disabled={itemActionStates.isPausing || itemActionStates.isCanceling || state.download_status !== 'downloading' || (state.download_status === 'downloading' && state.status === 'finished')}
>
{itemActionStates.isPausing ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Pausing
</>
) : (
<>
<Pause className="w-4 h-4" />
Pause
</>
)}
</Button>
)}
<Button
size="sm"
variant="destructive"
onClick={async () => {
setIsCancelingDownload(state.download_id, true);
try {
await cancelDownload(state)
toast({
title: 'Canceled Download',
description: 'Download canceled successfully.',
})
} catch (e) {
console.error(e);
toast({
title: 'Failed to Cancel Download',
description: 'An error occurred while trying to cancel the download.',
variant: "destructive"
})
} finally {
setIsCancelingDownload(state.download_id, false);
}
}}
disabled={itemActionStates.isCanceling || itemActionStates.isResuming || itemActionStates.isPausing || state.download_status === 'starting' || (state.download_status === 'downloading' && state.status === 'finished')}
>
{itemActionStates.isCanceling ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Canceling
</>
) : (
<>
<X className="w-4 h-4" />
Cancel
</>
)}
</Button>
</div>
</div>
</div>
)
})
) : (
<div className="w-full flex items-center justify-center text-muted-foreground text-sm">No Incomplete downloads!</div>
)}
</div>
<div className="w-full fle flex-col">
<div className="flex w-full items-center gap-2 mb-2">
<CircleCheck className="size-4" />
<h3 className="text-nowrap font-semibold">Completed Downloads</h3>
</div>
<Separator orientation="horizontal" className="" />
</div>
<div className="w-full flex flex-col gap-2">
{completedDownloads.length > 0 ? (
completedDownloads.map((state) => {
const itemActionStates = downloadActions[state.download_id] || {
isResuming: false,
isPausing: false,
isCanceling: false,
isDeleteFileChecked: false,
};
return (
<div className="p-4 border border-border rounded-lg flex gap-4" key={state.download_id}>
<div className="w-[30%] flex flex-col justify-between gap-2">
<AspectRatio ratio={16 / 9} className="w-full rounded-lg overflow-hidden border border-border mb-2">
<ProxyImage src={state.thumbnail || ""} alt="thumbnail" className="" />
</AspectRatio>
<span className="w-full flex items-center justify-center text-xs border border-border py-1 px-2 rounded">
{state.filetype && (state.filetype === 'video' || state.filetype === 'video+audio') && (
<Video className="w-4 h-4 mr-2" />
)}
{state.filetype && state.filetype === 'audio' && (
<Music className="w-4 h-4 mr-2" />
)}
{(!state.filetype) || (state.filetype && state.filetype !== 'video' && state.filetype !== 'audio' && state.filetype !== 'video+audio') && (
<File className="w-4 h-4 mr-2" />
)}
{state.ext?.toUpperCase()} {state.resolution ? `(${state.resolution})` : null}
</span>
</div>
<div className="w-full flex flex-col justify-between gap-2">
<div className="flex flex-col gap-1">
<h4 className="">{state.title}</h4>
<p className="text-xs text-muted-foreground">{state.channel ? state.channel : 'unknown'} {state.host ? `${state.host}` : 'unknown'}</p>
<div className="flex items-center mt-1">
<span className="text-xs text-muted-foreground flex items-center pr-3"><Clock className="w-4 h-4 mr-2"/> {state.duration_string ? formatDurationString(state.duration_string) : 'unknown'}</span>
<Separator orientation="vertical" />
<span className="text-xs text-muted-foreground flex items-center px-3">
{state.filetype && (state.filetype === 'video' || state.filetype === 'video+audio') && (
<FileVideo2 className="w-4 h-4 mr-2"/>
)}
{state.filetype && state.filetype === 'audio' && (
<FileAudio2 className="w-4 h-4 mr-2" />
)}
{(!state.filetype) || (state.filetype && state.filetype !== 'video' && state.filetype !== 'audio' && state.filetype !== 'video+audio') && (
<FileQuestion className="w-4 h-4 mr-2" />
)}
{state.filesize ? formatFileSize(state.filesize) : 'unknown'}
</span>
<Separator orientation="vertical" />
<span className="text-xs text-muted-foreground flex items-center pl-3"><AudioLines className="w-4 h-4 mr-2"/>
{state.vbr && state.abr ? (
formatBitrate(state.vbr + state.abr)
) : state.vbr ? (
formatBitrate(state.vbr)
) : state.abr ? (
formatBitrate(state.abr)
) : (
'unknown'
)}
</span>
</div>
<div className="hidden xl:flex items-center mt-1 gap-2 flex-wrap text-xs">
{state.playlist_id && state.playlist_index && (
<span
className="border border-border py-1 px-2 rounded flex items-center cursor-pointer"
title={`${state.playlist_title ?? 'UNKNOWN PLAYLIST'}` + ' by ' + `${state.playlist_channel ?? 'UNKNOWN CHANNEL'}`}
>
<ListVideo className="w-4 h-4 mr-2" /> Playlist ({state.playlist_index} of {state.playlist_n_entries})
</span>
)}
{state.vcodec && (
<span className="border border-border py-1 px-2 rounded">{formatCodec(state.vcodec)}</span>
)}
{state.acodec && (
<span className="border border-border py-1 px-2 rounded">{formatCodec(state.acodec)}</span>
)}
{state.dynamic_range && state.dynamic_range !== 'SDR' && (
<span className="border border-border py-1 px-2 rounded">{state.dynamic_range}</span>
)}
{state.subtitle_id && (
<span
className="border border-border py-1 px-2 rounded cursor-pointer"
title={`EMBEDED SUBTITLE (${state.subtitle_id})`}
>
ESUB
</span>
)}
</div>
</div>
<div className="w-full flex items-center gap-2">
<Button size="sm" onClick={() => openFile(state.filepath, null)}>
<Play className="w-4 h-4" />
Open
</Button>
<Button size="sm" variant="outline" onClick={() => openFile(state.filepath, 'explorer')}>
<FolderInput className="w-4 h-4" />
Open in Explorer
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="sm" variant="destructive">
<Trash2 className="w-4 h-4" />
Remove
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone! it will permanently remove this from downloads.
</AlertDialogDescription>
<div className="flex items-center space-x-2">
<Checkbox id="delete-file" checked={itemActionStates.isDeleteFileChecked} onCheckedChange={() => {setIsDeleteFileChecked(state.download_id, !itemActionStates.isDeleteFileChecked)}} />
<Label htmlFor="delete-file">Delete the downloaded file</Label>
</div>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={
() => removeFromDownloads(state, itemActionStates.isDeleteFileChecked).then(() => {
setIsDeleteFileChecked(state.download_id, false);
})
}>Remove</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
</div>
)
})
) : (
<div className="w-full flex items-center justify-center text-muted-foreground text-sm">No Completed downloads!</div>
)}
</div>
</div>
);
}

467
src/pages/settings.tsx Normal file
View File

@@ -0,0 +1,467 @@
import Heading from "@/components/heading";
import { Card } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useBasePathsStore, useDownloadStatesStore, useSettingsPageStatesStore } from "@/services/store";
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import { ExternalLink, FolderOpen, Loader2, LucideIcon, Monitor, Moon, Radio, RotateCcw, RotateCw, Sun, Terminal } from "lucide-react";
import { cn } from "@/lib/utils";
import { useEffect } from "react";
import { useTheme } from "@/providers/themeProvider";
import { Slider } from "@/components/ui/slider";
import { Input } from "@/components/ui/input";
import { open } from '@tauri-apps/plugin-dialog';
import { useSettings } from "@/helpers/use-settings";
import { useYtDlpUpdater } from "@/helpers/use-ytdlp-updater";
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 { invoke } from "@tauri-apps/api/core";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
const websocketPortSchema = z.object({
port: z.string().min(1, { message: "Websocket port is required" })
.regex(/^\d+$/, { message: "Websocket port must be a number" })
.transform((val) => parseInt(val, 10))
.refine((port) => port >= 50000 && port <= 60000, {
message: "Websocket port must be between 50000 and 60000",
})
});
const proxyUrlSchema = z.object({
url: z.string().min(1, { message: "Proxy URL is required" }).url({ message: "Invalid URL format" })
});
export default function SettingsPage() {
const { toast } = useToast();
const { setTheme } = useTheme();
const activeTab = useSettingsPageStatesStore(state => state.activeTab);
const setActiveTab = useSettingsPageStatesStore(state => state.setActiveTab);
const isUsingDefaultSettings = useSettingsPageStatesStore(state => state.isUsingDefaultSettings);
const ytDlpVersion = useSettingsPageStatesStore(state => state.ytDlpVersion);
const isFetchingYtDlpVersion = useSettingsPageStatesStore(state => state.isFetchingYtDlpVersion);
const isUpdatingYtDlp = useSettingsPageStatesStore(state => state.isUpdatingYtDlp);
const ytDlpUpdateChannel = useSettingsPageStatesStore(state => state.settings.ytdlp_update_channel);
const ytDlpAutoUpdate = useSettingsPageStatesStore(state => state.settings.ytdlp_auto_update);
const appTheme = useSettingsPageStatesStore(state => state.settings.theme);
const maxParallelDownloads = useSettingsPageStatesStore(state => state.settings.max_parallel_downloads);
const preferVideoOverPlaylist = useSettingsPageStatesStore(state => state.settings.prefer_video_over_playlist);
const useProxy = useSettingsPageStatesStore(state => state.settings.use_proxy);
const proxyUrl = useSettingsPageStatesStore(state => state.settings.proxy_url);
const websocketPort = useSettingsPageStatesStore(state => state.settings.websocket_port);
const isChangingWebSocketPort = useSettingsPageStatesStore(state => state.isChangingWebSocketPort);
const setIsChangingWebSocketPort = useSettingsPageStatesStore(state => state.setIsChangingWebSocketPort);
const isRestartingWebSocketServer = useSettingsPageStatesStore(state => state.isRestartingWebSocketServer);
const setIsRestartingWebSocketServer = useSettingsPageStatesStore(state => state.setIsRestartingWebSocketServer);
const downloadStates = useDownloadStatesStore(state => state.downloadStates);
const ongoingDownloads = downloadStates.filter(state =>
['starting', 'downloading', 'queued'].includes(state.download_status)
);
const downloadDirPath = useBasePathsStore((state) => state.downloadDirPath);
const setPath = useBasePathsStore((state) => state.setPath);
const { saveSettingsKey, resetSettings } = useSettings();
const { updateYtDlp } = useYtDlpUpdater();
const themeOptions: { value: string; icon: LucideIcon; label: string }[] = [
{ value: 'light', icon: Sun, label: 'Light' },
{ value: 'dark', icon: Moon, label: 'Dark' },
{ value: 'system', icon: Monitor, label: 'System' },
];
const proxyUrlForm = useForm<z.infer<typeof proxyUrlSchema>>({
resolver: zodResolver(proxyUrlSchema),
defaultValues: {
url: proxyUrl,
},
mode: "onChange",
});
const watchedProxyUrl = proxyUrlForm.watch("url");
const { errors: proxyUrlFormErrors } = proxyUrlForm.formState;
function handleProxyUrlSubmit(values: z.infer<typeof proxyUrlSchema>) {
try {
saveSettingsKey('proxy_url', values.url);
toast({
title: "Proxy URL updated",
description: `Proxy URL changed to ${values.url}`,
});
} catch (error) {
console.error("Error changing proxy URL:", error);
toast({
title: "Failed to change proxy URL",
description: "Please try again.",
variant: "destructive",
});
}
}
interface Config {
port: number;
}
const websocketPortForm = useForm<z.infer<typeof websocketPortSchema>>({
resolver: zodResolver(websocketPortSchema),
defaultValues: {
port: websocketPort,
},
mode: "onChange",
});
const watchedPort = websocketPortForm.watch("port");
const { errors: websocketPortFormErrors } = websocketPortForm.formState;
async function handleWebsocketPortSubmit(values: z.infer<typeof websocketPortSchema>) {
setIsChangingWebSocketPort(true);
try {
// const port = parseInt(values.port, 10);
const updatedConfig: Config = await invoke("update_config", {
newConfig: {
port: values.port,
}
});
saveSettingsKey('websocket_port', updatedConfig.port);
toast({
title: "Websocket port updated",
description: `Websocket port changed to ${values.port}`,
});
} catch (error) {
console.error("Error changing websocket port:", error);
toast({
title: "Failed to change websocket port",
description: "Please try again.",
variant: "destructive",
});
} finally {
setIsChangingWebSocketPort(false);
}
}
useEffect(() => {
const updateTheme = async () => {
setTheme(appTheme);
}
updateTheme().catch(console.error);
}, [appTheme]);
return (
<div className="container mx-auto p-4 space-y-4 min-h-screen">
<Heading title="Settings" description="Manage your preferences and app settings" />
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList>
<TabsTrigger value="general">General</TabsTrigger>
<TabsTrigger value="extension">Extension</TabsTrigger>
</TabsList>
<TabsContent value="general">
<Card className="p-4 space-y-4 my-4">
<div className="w-full flex gap-4 items-center justify-between">
<div className="flex gap-4 items-center">
<div className="imgwrapper w-10 h-10 flex items-center justify-center bg-gradient-to-r from-[#4444FF] to-[#FF43D0] rounded-md overflow-hidden border border-border">
<Terminal className="size-5 text-white" />
</div>
<div className="flex flex-col">
<h3 className="flex items-center gap-2">
<span>YT-DLP</span>
<a href="https://github.com/yt-dlp/yt-dlp" className="" title="yt-dlp homepage" target="_blank">
<ExternalLink className="size-3 text-muted-foreground hover:text-foreground" />
</a>
</h3>
<p className="text-xs text-muted-foreground">Version: {isFetchingYtDlpVersion ? 'Loading...' : ytDlpVersion ?? 'unknown'}</p>
</div>
</div>
<div className="flex gap-4 items-center">
<div className="flex items-center space-x-2">
<Switch
id="ytdlp-auto-update"
checked={ytDlpAutoUpdate}
onCheckedChange={(checked) => saveSettingsKey('ytdlp_auto_update', checked)}
/>
<Label htmlFor="ytdlp-auto-update">Auto Update</Label>
</div>
<Select
value={ytDlpUpdateChannel}
onValueChange={(value) => saveSettingsKey('ytdlp_update_channel', value)}
>
<SelectTrigger className="w-[150px] ring-0 focus:ring-0">
<SelectValue placeholder="Select update channel" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>Update Channels</SelectLabel>
<SelectItem value="stable">Stable</SelectItem>
<SelectItem value="nightly">Nightly</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<Button
disabled={ytDlpAutoUpdate || isUpdatingYtDlp || ongoingDownloads.length > 0}
onClick={async () => await updateYtDlp()}
>
{isUpdatingYtDlp ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Updating
</>
) : (
<>
Update
</>
)}
</Button>
</div>
</div>
</Card>
<div className="flex flex-col w-[50%] gap-4">
<div className="app-theme">
<h3 className="font-semibold">Theme</h3>
<p className="text-sm text-muted-foreground mb-3">Choose app interface theme</p>
<div className={cn('inline-flex gap-1 rounded-lg p-1 bg-muted')}>
{themeOptions.map(({ value, icon: Icon, label }) => (
<button
key={value}
onClick={() => saveSettingsKey('theme', value)}
className={cn(
'flex items-center rounded-md px-3.5 py-1.5 transition-colors',
appTheme === value
? 'bg-white shadow-xs dark:bg-neutral-700 dark:text-neutral-100'
: 'text-neutral-500 hover:bg-neutral-200/60 hover:text-black dark:text-neutral-400 dark:hover:bg-neutral-700/60',
)}
>
<Icon className="-ml-1 h-4 w-4" />
<span className="ml-1.5 text-sm">{label}</span>
</button>
))}
</div>
</div>
<div className="download-dir">
<h3 className="font-semibold">Download Directory</h3>
<p className="text-sm text-muted-foreground mb-3">Set default download directory</p>
<div className="flex items-center gap-4">
<Input className="focus-visible:ring-0" type="text" placeholder="Select download directory" value={downloadDirPath ?? 'Unknown'} readOnly/>
<Button
variant="outline"
onClick={async () => {
try {
const folder = await open({
multiple: false,
directory: true,
});
if (folder) {
saveSettingsKey('download_dir', folder);
setPath('downloadDirPath', folder);
}
} catch (error) {
console.error("Error selecting folder:", error);
toast({
title: "Failed to select folder",
description: "Please try again.",
variant: "destructive",
});
}
}}
>
<FolderOpen className="w-4 h-4" /> Browse
</Button>
</div>
</div>
<div className="max-parallel-downloads">
<h3 className="font-semibold">Max Parallel Downloads</h3>
<p className="text-sm text-muted-foreground mb-3">Set maximum number of allowed parallel downloads</p>
<Slider
id="max-parallel-downloads"
className="w-[350px]"
value={[maxParallelDownloads]}
min={1}
max={5}
onValueChange={(value) => saveSettingsKey('max_parallel_downloads', value[0])}
/>
<Label htmlFor="max-parallel-downloads" className="text-xs text-muted-foreground">(Current: {maxParallelDownloads}) (Default: 2, Maximum: 5)</Label>
</div>
<div className="prefer-video-over-playlist">
<h3 className="font-semibold">Prefer Video Over Playlist</h3>
<p className="text-sm text-muted-foreground mb-3">Prefer only the video, if the URL refers to a video and a playlist</p>
<Switch
id="prefer-video-over-playlist"
checked={preferVideoOverPlaylist}
onCheckedChange={(checked) => saveSettingsKey('prefer_video_over_playlist', checked)}
/>
</div>
<div className="proxy">
<h3 className="font-semibold">Proxy</h3>
<p className="text-sm text-muted-foreground mb-3">Use proxy for downloads, Unblocks blocked sites in your region (Download speed may affect, Some sites may not work)</p>
<div className="flex items-center space-x-2 mb-4">
<Switch
id="use-proxy"
checked={useProxy}
onCheckedChange={(checked) => saveSettingsKey('use_proxy', checked)}
/>
<Label htmlFor="use-proxy">Use Proxy</Label>
</div>
<div className="flex items-center gap-4">
<Form {...proxyUrlForm}>
<form onSubmit={proxyUrlForm.handleSubmit(handleProxyUrlSubmit)} className="flex gap-4 w-full" autoComplete="off">
<FormField
control={proxyUrlForm.control}
name="url"
disabled={!useProxy}
render={({ field }) => (
<FormItem className="w-full">
<FormControl>
<Input
className="focus-visible:ring-0"
placeholder="Enter proxy URL"
{...field}
/>
</FormControl>
<Label htmlFor="url" className="text-xs text-muted-foreground">(Configured: {proxyUrl ? 'Yes' : 'No'}, Status: {useProxy ? 'Enabled' : 'Disabled'})</Label>
<FormMessage />
</FormItem>
)}
/>
<Button
type="submit"
disabled={!watchedProxyUrl || watchedProxyUrl === proxyUrl || Object.keys(proxyUrlFormErrors).length > 0 || !useProxy}
>
Save
</Button>
</form>
</Form>
</div>
</div>
</div>
</TabsContent>
<TabsContent value="extension">
<Card className="p-4 space-y-4 my-4">
<div className="w-full flex gap-4 items-center justify-between">
<div className="flex gap-4 items-center">
<div className="imgwrapper w-10 h-10 flex items-center justify-center bg-gradient-to-r from-[#4444FF] to-[#FF43D0] rounded-md overflow-hidden border border-border">
<Radio className="size-5 text-white" />
</div>
<div className="flex flex-col">
<h3 className="">Extension Websocket Server</h3>
<p className="text-xs text-muted-foreground">{isChangingWebSocketPort || isRestartingWebSocketServer ? 'Restarting...' : 'Running' }</p>
</div>
</div>
<div className="flex gap-4 items-center">
<Button
onClick={async () => {
setIsRestartingWebSocketServer(true);
try {
await invoke("restart_websocket_server");
toast({
title: "Websocket server restarted",
description: "Websocket server restarted successfully.",
});
} catch (error) {
console.error("Error restarting websocket server:", error);
toast({
title: "Failed to restart websocket server",
description: "Please try again.",
variant: "destructive",
});
} finally {
setIsRestartingWebSocketServer(false);
}
}}
disabled={isRestartingWebSocketServer || isChangingWebSocketPort}
>
{isRestartingWebSocketServer ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Restarting
</>
) : (
<>
<RotateCw className="h-4 w-4" />
Restart
</>
)}
</Button>
</div>
</div>
</Card>
<div className="flex flex-col w-[50%] gap-4">
<div className="websocket-port">
<h3 className="font-semibold">Websocket Port</h3>
<p className="text-sm text-muted-foreground mb-3">Change extension websocket server port</p>
<div className="flex items-center gap-4">
<Form {...websocketPortForm}>
<form onSubmit={websocketPortForm.handleSubmit(handleWebsocketPortSubmit)} className="flex gap-4 w-full" autoComplete="off">
<FormField
control={websocketPortForm.control}
name="port"
disabled={isChangingWebSocketPort}
render={({ field }) => (
<FormItem className="w-full">
<FormControl>
<Input
className="focus-visible:ring-0"
placeholder="Enter port number"
{...field}
/>
</FormControl>
<Label htmlFor="port" className="text-xs text-muted-foreground">(Current: {websocketPort}) (Default: 53511, Range: 50000-60000)</Label>
<FormMessage />
</FormItem>
)}
/>
<Button
type="submit"
disabled={!watchedPort || Number(watchedPort) === websocketPort || Object.keys(websocketPortFormErrors).length > 0 || isChangingWebSocketPort || isRestartingWebSocketServer}
>
{isChangingWebSocketPort ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Changing
</>
) : (
'Change'
)}
</Button>
</form>
</Form>
</div>
</div>
</div>
</TabsContent>
</Tabs>
<div className="flex flex-col">
<h3 className="font-semibold">Reset Settings</h3>
<p className="text-sm text-muted-foreground mb-3">Reset all setting to default</p>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
className="w-fit"
variant="destructive"
disabled={isUsingDefaultSettings}
>
<RotateCcw className="h-4 w-4" />
Reset Default
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone! it will permanently reset all settings to default.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={
() => resetSettings()
}>Reset</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
)
}