feat: added download status

This commit is contained in:
ner committed 2025-08-14 21:38:24 +03:00
1 parent cd3fabc0d8
commit 82c14c1d5c
17 files changed
+189 -88

No files matched your search

@@ -16,7 +16,7 @@ import { PlyrLayout, plyrLayoutIcons } from '@vidstack/react/player/layouts/plyr
import { cn } from '@/lib/utils';
import CaptionsMenu from './components/CaptionsMenu';
import VideosMenu from './components/VideosMenu';
import PlaylistMenu from './components/PlaylistMenu';
import useSource from './useSource';
import '@vidstack/react/player/styles/plyr/theme.css';
@@ -25,10 +25,9 @@ interface Props {
magnet: string;
subtitles: Source[];
videos: Source[];
onReady: () => void;
}
const Player: FC<Props> = ({ videos, subtitles, magnet, onReady }) => {
const Player: FC<Props> = ({ videos, subtitles, magnet }) => {
const { index, setIndex } = useSource({ magnet });
const player = useRef<MediaPlayerInstance>(null);
@@ -48,7 +47,6 @@ const Player: FC<Props> = ({ videos, subtitles, magnet, onReady }) => {
return (
<MediaPlayer
autoPlay
onCanPlay={onReady}
load='eager'
storage='movie-advisor'
ref={player}
@@ -75,7 +73,7 @@ const Player: FC<Props> = ({ videos, subtitles, magnet, onReady }) => {
afterVolumeSlider: <ul className='w-2' />,
beforeSettings: Boolean(subtitles.length) && <CaptionsMenu />,
settings: videos.length > 1 && (
<VideosMenu key={source?.src} source={source} sources={videos} onChange={setIndex} />
<PlaylistMenu key={source?.src} source={source} sources={videos} onChange={setIndex} />
)
}}
/>
@@ -10,6 +10,7 @@ const CaptionsMenu = () => {
return (
<PlayerMenu
closeOnSelect
value={tracks.selectedValue}
options={tracks.map((track) => ({ label: track.label, value: track.value, onSelect: () => track.select() }))}
>
@@ -1,7 +1,9 @@
import { FC, forwardRef, ReactNode, useRef } from 'react';
import React, { FC, forwardRef, MutableRefObject, ReactNode, useRef } from 'react';
import { create, InstanceProps } from 'react-modal-promise';
import { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
import { Menu } from '@vidstack/react';
import { Modal } from '@/components/ui/dialog';
import { cn } from '@/lib/utils';
type Option = { onSelect: (value: string) => void; value: string; label: string };
@@ -10,32 +12,42 @@ interface Props {
children: ReactNode;
options: Option[];
value: string;
className?: string;
closeOnSelect?: boolean;
}
const PlayerMenu: FC<Props> = ({ children, options, value, className }) => {
const virtuosoRef = useRef<VirtuosoHandle | null>(null);
const showMenu = create(
({ onResolve, options, value, closeOnSelect }: InstanceProps<void> & Omit<Props, 'children'>) => {
const virtuosoRef = useRef<VirtuosoHandle | null>(null);
const scrollRef = useRef<HTMLDivElement>(null) as MutableRefObject<HTMLDivElement>;
return (
<Menu.Root
className={cn('plyr__menu')}
onOpen={() =>
setTimeout(() => {
virtuosoRef.current?.scrollToIndex({ behavior: 'smooth', index: +value });
}, 100)
}
>
<Menu.Button className={cn('plyr__controls__item plyr__control')}>{children}</Menu.Button>
<Menu.Items className={cn('!bg-background rounded-lg h-60 after:hidden p-2', className)} placement='top end'>
return (
<Modal className='max-w-screen-xs rounded-xl p-2' onClose={onResolve} scrollRef={scrollRef}>
<Virtuoso
useWindowScroll
initialTopMostItemIndex={+value || 0}
overscan={20}
initialItemCount={20}
ref={virtuosoRef}
className='h-full w-72'
initialItemCount={10}
customScrollParent={scrollRef.current}
data={options}
context={value}
components={components}
onClick={closeOnSelect ? () => onResolve() : undefined}
/>
</Menu.Items>
</Modal>
);
}
);
const PlayerMenu: FC<Props> = ({ children, options, value, closeOnSelect }) => {
return (
<Menu.Root className={cn('plyr__menu')}>
<Menu.Button
onClick={() => showMenu({ options, value, closeOnSelect })}
className={cn('plyr__controls__item plyr__control')}
>
{children}
</Menu.Button>
</Menu.Root>
);
};
@@ -45,31 +57,27 @@ const components: VirtuosoProps<Option, string>['components'] = {
if (!option) return null;
return (
<Menu.Radio asChild>
<div
{...props}
key={option.value}
title={option.label}
onClick={() => option.onSelect(option.value)}
className={cn(
'!m-0 cursor-pointer whitespace-normal break-all rounded-sm bg-secondary text-left !px-2 !py-1 text-foreground',
{
'bg-secondary-foreground text-secondary': context === option.value
}
)}
>
{option.label}
</div>
</Menu.Radio>
<div
{...props}
key={option.value}
title={option.label}
onClick={() => option.onSelect(option.value)}
className={cn(
'!m-0 cursor-pointer whitespace-normal break-all rounded-sm bg-secondary text-left !px-2 !py-1 text-foreground',
{
'bg-secondary-foreground text-secondary': context === option.value
}
)}
>
{option.label}
</div>
);
},
List: forwardRef(function List({ children, ...props }, ref) {
return (
<Menu.RadioGroup asChild className='flex flex-col gap-2' value={props.context}>
<div {...props} ref={ref}>
{children}
</div>
</Menu.RadioGroup>
<div className='flex flex-col gap-2' {...props} ref={ref}>
{children}
</div>
);
})
};
@@ -1,4 +1,4 @@
import { FC } from 'react';
import React, { FC } from 'react';
import { PlaylistIcon } from '@vidstack/react/icons';
import { cn } from '@/lib/utils';
@@ -16,13 +16,13 @@ const VideosMenu: FC<Props> = ({ sources, source, onChange }) => {
return (
<PlayerMenu
closeOnSelect
value={value.toString()}
options={sources.map(({ name }, index) => ({
label: name,
value: index.toString(),
onSelect: () => onChange(index)
}))}
className='max-h-80'
>
<PlaylistIcon className={cn('vds-icon !transform-none')} />
<span className={cn('plyr__tooltip')}>Playlist</span>
@@ -1,30 +1,31 @@
import { useState } from 'react';
import { create, InstanceProps } from 'react-modal-promise';
import { Loader } from 'lucide-react';
import dynamic from 'next/dynamic';
import { Modal } from '@/components/ui/dialog';
import { useToast } from '@/hooks/useToast';
import { formatBytes } from '@/lib/utils';
import useFiles from './useFiles';
import { useStats } from './useStats';
const Player = dynamic(() => import('./Player'));
interface Props extends InstanceProps<void> {
magnet: string;
hash?: string;
backdrop: string;
title: string;
}
const showPlayer = create(({ onResolve, magnet, backdrop, title }: Props) => {
const [isReady, setIsReady] = useState(false);
const showPlayer = create(({ onResolve, magnet, hash, backdrop, title }: Props) => {
const {
data: { subtitles, videos },
error,
isFetched,
isLoading
} = useFiles(magnet);
isFetched
} = useFiles({ magnet });
const { isReady, preloadingProgress, downloadSpeed, peers } = useStats({ hash });
const { toast } = useToast();
@@ -42,16 +43,31 @@ const showPlayer = create(({ onResolve, magnet, backdrop, title }: Props) => {
<Modal className='overflow-hidden border-none bg-black p-0' onClose={onResolve}>
<div className='relative w-full overflow-hidden pt-[56.25%]'>
<div className='absolute left-0 top-0 size-full'>
<Player magnet={magnet} subtitles={subtitles} videos={videos} onReady={() => setIsReady(true)} />
<Player magnet={magnet} subtitles={subtitles} videos={videos} />
</div>
{(!isReady || isLoading) && (
{!isReady && (
<div className='absolute left-0 top-0 size-full'>
<img src={backdrop} className='absolute left-0 top-0 size-full' alt={title} />
<div className='absolute left-0 top-0 flex size-full items-center justify-center bg-black/60'>
<div className='animate-spin'>
<Loader color='white' />
</div>
<div
className='absolute left-0 top-0 flex size-full items-center justify-center bg-black/60 transition-all'
style={{
height: `${100 - preloadingProgress}%`
}}
>
{!preloadingProgress && !peers && (
<div className='animate-spin'>
<Loader color='white' />
</div>
)}
</div>
{(downloadSpeed || peers) && (
<div className='absolute left-0 top-0 flex size-full flex-col items-center justify-center text-white'>
<div className='flex h-[90px] w-[230px] flex-col items-center justify-center gap-2 rounded-xl bg-black/80 p-4 shadow-2xl'>
{Boolean(peers) && <p>Peers: {peers}</p>}
{Boolean(downloadSpeed) && <p>Download speed: {downloadSpeed}</p>}
</div>
</div>
)}
</div>
)}
</div>
@@ -5,11 +5,15 @@ import { useStreamUrl } from '@/hooks/useStreamUrl';
export type Source = { name: string; src: string; type: string };
type Sources = { subtitles: Source[]; videos: Source[] };
const useFiles = (magnet: string) => {
const streamUrl = `${useStreamUrl()}?link=${encodeURIComponent(magnet)}`;
interface Props {
magnet: string;
}
const useFiles = ({ magnet }: Props) => {
const streamUrl = `${useStreamUrl()}/stream?link=${encodeURIComponent(magnet)}`;
const query = useQuery<Stream>({
queryKey: ['files', magnet],
queryFn: () => fetch(`${streamUrl}&stat`).then((response) => response.json())
queryFn: () => fetch(`${streamUrl}&stat&preload`).then((response) => response.json())
});
return {
@@ -0,0 +1,49 @@
import { useQuery } from '@tanstack/react-query';
import { PRELOAD_CACHE_LIMIT } from '@/env';
import { useStreamUrl } from '@/hooks/useStreamUrl';
import { formatBytes } from '@/lib/utils';
interface Props {
hash?: string;
}
export enum StreamStatus {
init = 1,
preload = 2,
ready = 3
}
export const useStats = ({ hash }: Props) => {
const streamUrl = useStreamUrl();
const { data } = useQuery<Stream & { stat: StreamStatus }>({
enabled: Boolean(hash),
queryKey: ['stats', hash],
refetchInterval: ({ state }) => {
if (state.data?.stat === StreamStatus.ready) return false;
return 500;
},
queryFn: () =>
fetch(`${streamUrl}/torrents`, {
method: 'POST',
body: JSON.stringify({
action: 'get',
hash
})
}).then((response) => response.json())
});
const preloadCacheLimitBytes = PRELOAD_CACHE_LIMIT * 1_048_576;
return {
isReady: data?.stat === StreamStatus.ready,
downloadSpeed: data?.download_speed ? `${formatBytes(data?.download_speed)}/s` : '',
peers: [(data?.active_peers ?? 0) + (data?.half_open_peers ?? 0), data?.total_peers].filter(Boolean).join('/'),
preloadingProgress: Math.min(
data?.preloaded_bytes ? (data?.preloaded_bytes * 100) / preloadCacheLimitBytes : 0,
100
)
};
};
@@ -5,7 +5,7 @@ import { Button } from '@/components/ui/button';
import ButtonsGroup from '@/components/ui/buttons-group';
import { Quality } from '@/data/parsers/yts/models';
import { useStreamUrl } from '@/hooks/useStreamUrl';
import { cn } from '@/lib/utils';
import { cn, getMagnetHash } from '@/lib/utils';
import { providers } from '../../../../constants';
import { useCastMagnet, usePrefix } from '../../../../hooks/useMagnetHosts';
@@ -36,6 +36,8 @@ const Actions: FC<Props> = ({ torrent, backdrop, title, provider }) => {
const magnet = fetchMagnet.data || torrent.magnet;
const hash = getMagnetHash(magnet);
const supportedForCast = prefix && !prefix.includes('{host}');
return (
@@ -48,7 +50,7 @@ const Actions: FC<Props> = ({ torrent, backdrop, title, provider }) => {
'flex-grow-0 px-3 bg-red-600',
'hover:shadow-lg hover:shadow-red-600/60 duration-200 transition-all hover:bg-red-600'
)}
onClick={() => showPlayer({ magnet, backdrop, title })}
onClick={() => showPlayer({ magnet, backdrop, title, hash })}
title='Play'
>
<Play size={15} />
@@ -59,7 +61,7 @@ const Actions: FC<Props> = ({ torrent, backdrop, title, provider }) => {
className='absolute left-0 top-0 size-full'
target='_blank'
rel='noopener noreferrer'
href={`${streamUrl}?m3u&link=${encodeURIComponent(magnet)}`}
href={`${streamUrl}/stream?m3u&link=${encodeURIComponent(magnet)}`}
/>
<ListVideo size={20} />
</Button>
@@ -46,7 +46,6 @@ const TorrentsTable: FC<Props> = ({ title, torrents, backdrop, sort, sortable, p
<TableBody>
{torrents?.map((torrent) => {
const yearView = torrent.year && year.toString() != torrent.year && `[${torrent.year}]`;
return (
<Fragment key={torrent.magnet + torrent.id + torrent.download}>
<TableRow className='table-row border-b-0 hover:bg-transparent md:hidden'>