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
+168 -67

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 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'>
<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,7 +57,6 @@ const components: VirtuosoProps<Option, string>['components'] = {
if (!option) return null;
return (
<Menu.Radio asChild>
<div
{...props}
key={option.value}
@@ -60,16 +71,13 @@ const components: VirtuosoProps<Option, string>['components'] = {
>
{option.label}
</div>
</Menu.Radio>
);
},
List: forwardRef(function List({ children, ...props }, ref) {
return (
<Menu.RadioGroup asChild className='flex flex-col gap-2' value={props.context}>
<div {...props} ref={ref}>
<div className='flex flex-col gap-2' {...props} ref={ref}>
{children}
</div>
</Menu.RadioGroup>
);
})
};
@@ -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='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'>
+2 -1
View File
@@ -73,7 +73,8 @@ export class PirateBay {
size: sizes[index],
seeders: parseInt(seeders[index] || '0', 10),
quality: resolution,
magnet: magnets[index] || ''
magnet: magnets[index] || '',
hash: ''
};
});
});
+2 -1
View File
@@ -61,7 +61,8 @@ export class YTS {
quality: torrent.quality,
source: torrent.type,
year: movie.year?.toString(),
magnet: `magnet:?xt=urn:btih:${torrent.hash}&dn=${encodeURIComponent(query)}&tr=${trackers.join('&tr=')}`
magnet: `magnet:?xt=urn:btih:${torrent.hash}&dn=${encodeURIComponent(query)}&tr=${trackers.join('&tr=')}`,
hash: torrent.hash
};
}) || []
);
+2 -1
View File
@@ -9,7 +9,8 @@ export const SITE_URL = `${BASE?.startsWith('http') ? BASE : `https://${BASE}`}`
export const MOVIE_DB_TOKEN = process.env.MOVIE_DB_TOKEN;
export const MOVIE_DB_API_URL = process.env.MOVIE_DB_API_URL || 'https://api.themoviedb.org/3';
export const STREAM_URL = `${process.env.NEXT_PUBLIC_TORRENT_PROXY}/stream`;
export const STREAM_URL = process.env.NEXT_PUBLIC_TORRENT_PROXY || '';
export const PRELOAD_CACHE_LIMIT = +(process.env.NEXT_PUBLIC_PRELOAD_CACHE_LIMIT || 32);
export const TOLOKA_HOST = process.env.TOLOKA_HOST;
export const TOLOKA_USERNAME = process.env.TOLOKA_USERNAME;
+1 -1
View File
@@ -185,4 +185,4 @@ function useToast() {
};
}
export { toast,useToast };
export { toast, useToast };
+21
View File
@@ -21,3 +21,24 @@ export const createUniqueRandomGenerator = (max: number) => {
return numbers[index++];
};
};
export const getMagnetHash = (link: string) => {
const [, hash] = link.match(/btih:([A-Fa-f0-9]{40}|[A-Za-z0-9]{32})/) || [];
return hash?.toUpperCase();
};
export const formatBytes = (bytes?: number) => {
if (bytes == null || !isFinite(bytes)) return '';
const units = ['B', 'KB', 'MB', 'GB', 'TB'] as const;
let i = 0;
let v = bytes;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
return `${v.toFixed(v < 10 && i > 0 ? 1 : 0)} ${units[i]}`;
};
+14 -9
View File
@@ -15,7 +15,7 @@
"@tanstack/react-query": "^5.59.15",
"@tanstack/react-query-next-experimental": "^5.59.16",
"@types/cheerio": "^0.22.35",
"@vidstack/react": "^1.12.11",
"@vidstack/react": "^1.12.13",
"axios": "^1.7.7",
"axios-cookiejar-support": "^5.0.3",
"cheerio": "^1.0.0",
@@ -60,6 +60,9 @@
"tailwindcss": "^3.3.3",
"tailwindcss-animate": "^1.0.7",
"tailwindcss-touch": "^1.0.1"
},
"engines": {
"node": "22.x"
}
},
"node_modules/@aashutoshrathi/word-wrap": {
@@ -4541,9 +4544,10 @@
}
},
"node_modules/@vidstack/react": {
"version": "1.12.11",
"resolved": "https://registry.npmjs.org/@vidstack/react/-/react-1.12.11.tgz",
"integrity": "sha512-rtSRjjob1k/mkzImN0wWPKYFi/Y7bsuSkDl/RfTxTKlDs4QzFtVwkUfgN1h8y+EUKJvMe9ozVHKdBtGYKDr6FQ==",
"version": "1.12.13",
"resolved": "https://registry.npmjs.org/@vidstack/react/-/react-1.12.13.tgz",
"integrity": "sha512-zyNydy1+HtoK6cJ8EmqFNkPPGHIFMrr2KH+ef3654EqXx4IcJ8A5LCNMXBuALQE8IMxtk040JMoR9OKyeXjBOQ==",
"license": "MIT",
"dependencies": {
"@floating-ui/dom": "^1.6.10",
"media-captions": "^1.0.4"
@@ -4552,8 +4556,8 @@
"node": ">=18"
},
"peerDependencies": {
"@types/react": "^18.0.0",
"react": "^18.0.0"
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
}
},
"node_modules/@webassemblyjs/ast": {
@@ -9026,6 +9030,7 @@
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/media-captions/-/media-captions-1.0.4.tgz",
"integrity": "sha512-cyDNmuZvvO4H27rcBq2Eudxo9IZRDCOX/I7VEyqbxsEiD2Ei7UYUhG/Sc5fvMZjmathgz3fEK7iAKqvpY+Ux1w==",
"license": "MIT",
"engines": {
"node": ">=16"
}
@@ -15085,9 +15090,9 @@
}
},
"@vidstack/react": {
"version": "1.12.11",
"resolved": "https://registry.npmjs.org/@vidstack/react/-/react-1.12.11.tgz",
"integrity": "sha512-rtSRjjob1k/mkzImN0wWPKYFi/Y7bsuSkDl/RfTxTKlDs4QzFtVwkUfgN1h8y+EUKJvMe9ozVHKdBtGYKDr6FQ==",
"version": "1.12.13",
"resolved": "https://registry.npmjs.org/@vidstack/react/-/react-1.12.13.tgz",
"integrity": "sha512-zyNydy1+HtoK6cJ8EmqFNkPPGHIFMrr2KH+ef3654EqXx4IcJ8A5LCNMXBuALQE8IMxtk040JMoR9OKyeXjBOQ==",
"requires": {
"@floating-ui/dom": "^1.6.10",
"media-captions": "^1.0.4"
+1 -1
View File
@@ -23,7 +23,7 @@
"@tanstack/react-query": "^5.59.15",
"@tanstack/react-query-next-experimental": "^5.59.16",
"@types/cheerio": "^0.22.35",
"@vidstack/react": "^1.12.11",
"@vidstack/react": "^1.12.13",
"axios": "^1.7.7",
"axios-cookiejar-support": "^5.0.3",
"cheerio": "^1.0.0",
Vendored
+3 -8
View File
@@ -132,6 +132,7 @@ interface Torrent {
container?: string;
year?: string;
download?: string;
hash: string;
}
interface Source {
@@ -166,6 +167,8 @@ interface Stream {
bytes_written: number;
bytes_read: number;
file_stats: FileStat[];
download_speed: number;
preloaded_bytes: number;
}
interface FileStat {
@@ -190,11 +193,3 @@ interface Account {
username: string;
avatar: Avatar;
}
interface Gravatar {
hash: string;
}
interface Tmdb {
avatar_path: null;
}