diff --git a/components/Preview/components/Torrents/components/Player/Player.tsx b/components/Preview/components/Torrents/components/Player/Player.tsx index 7b1bfb9..34d8a97 100644 --- a/components/Preview/components/Torrents/components/Player/Player.tsx +++ b/components/Preview/components/Torrents/components/Player/Player.tsx @@ -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 = ({ videos, subtitles, magnet, onReady }) => { +const Player: FC = ({ videos, subtitles, magnet }) => { const { index, setIndex } = useSource({ magnet }); const player = useRef(null); @@ -48,7 +47,6 @@ const Player: FC = ({ videos, subtitles, magnet, onReady }) => { return ( = ({ videos, subtitles, magnet, onReady }) => { afterVolumeSlider:
    , beforeSettings: Boolean(subtitles.length) && , settings: videos.length > 1 && ( - + ) }} /> diff --git a/components/Preview/components/Torrents/components/Player/components/CaptionsMenu/index.tsx b/components/Preview/components/Torrents/components/Player/components/CaptionsMenu/index.tsx index f276bc1..1e13ff7 100644 --- a/components/Preview/components/Torrents/components/Player/components/CaptionsMenu/index.tsx +++ b/components/Preview/components/Torrents/components/Player/components/CaptionsMenu/index.tsx @@ -10,6 +10,7 @@ const CaptionsMenu = () => { return ( ({ label: track.label, value: track.value, onSelect: () => track.select() }))} > diff --git a/components/Preview/components/Torrents/components/Player/components/PlayerMenu/index.tsx b/components/Preview/components/Torrents/components/Player/components/PlayerMenu/index.tsx index fd0bde9..999038b 100644 --- a/components/Preview/components/Torrents/components/Player/components/PlayerMenu/index.tsx +++ b/components/Preview/components/Torrents/components/Player/components/PlayerMenu/index.tsx @@ -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 = ({ children, options, value, className }) => { - const virtuosoRef = useRef(null); +const showMenu = create( + ({ onResolve, options, value, closeOnSelect }: InstanceProps & Omit) => { + const virtuosoRef = useRef(null); + const scrollRef = useRef(null) as MutableRefObject; - return ( - - setTimeout(() => { - virtuosoRef.current?.scrollToIndex({ behavior: 'smooth', index: +value }); - }, 100) - } - > - {children} - + return ( + onResolve() : undefined} /> - + + ); + } +); + +const PlayerMenu: FC = ({ children, options, value, closeOnSelect }) => { + return ( + + showMenu({ options, value, closeOnSelect })} + className={cn('plyr__controls__item plyr__control')} + > + {children} + ); }; @@ -45,31 +57,27 @@ const components: VirtuosoProps['components'] = { if (!option) return null; return ( - -
    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} -
    -
    +
    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} +
    ); }, List: forwardRef(function List({ children, ...props }, ref) { return ( - -
    - {children} -
    -
    +
    + {children} +
    ); }) }; diff --git a/components/Preview/components/Torrents/components/Player/components/VideosMenu/index.tsx b/components/Preview/components/Torrents/components/Player/components/PlaylistMenu/index.tsx similarity index 93% rename from components/Preview/components/Torrents/components/Player/components/VideosMenu/index.tsx rename to components/Preview/components/Torrents/components/Player/components/PlaylistMenu/index.tsx index 4104982..99dfca2 100644 --- a/components/Preview/components/Torrents/components/Player/components/VideosMenu/index.tsx +++ b/components/Preview/components/Torrents/components/Player/components/PlaylistMenu/index.tsx @@ -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 = ({ sources, source, onChange }) => { return ( ({ label: name, value: index.toString(), onSelect: () => onChange(index) }))} - className='max-h-80' > Playlist diff --git a/components/Preview/components/Torrents/components/Player/index.tsx b/components/Preview/components/Torrents/components/Player/index.tsx index a7fd28f..a4ade11 100644 --- a/components/Preview/components/Torrents/components/Player/index.tsx +++ b/components/Preview/components/Torrents/components/Player/index.tsx @@ -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 { 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) => {
    - setIsReady(true)} /> +
    - {(!isReady || isLoading) && ( + {!isReady && (
    {title} -
    -
    - -
    +
    + {!preloadingProgress && !peers && ( +
    + +
    + )}
    + {(downloadSpeed || peers) && ( +
    +
    + {Boolean(peers) &&

    Peers: {peers}

    } + {Boolean(downloadSpeed) &&

    Download speed: {downloadSpeed}

    } +
    +
    + )}
    )}
    diff --git a/components/Preview/components/Torrents/components/Player/useFiles.ts b/components/Preview/components/Torrents/components/Player/useFiles.ts index 7c55f50..11addf4 100644 --- a/components/Preview/components/Torrents/components/Player/useFiles.ts +++ b/components/Preview/components/Torrents/components/Player/useFiles.ts @@ -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({ queryKey: ['files', magnet], - queryFn: () => fetch(`${streamUrl}&stat`).then((response) => response.json()) + queryFn: () => fetch(`${streamUrl}&stat&preload`).then((response) => response.json()) }); return { diff --git a/components/Preview/components/Torrents/components/Player/useStats.ts b/components/Preview/components/Torrents/components/Player/useStats.ts new file mode 100644 index 0000000..4d509a1 --- /dev/null +++ b/components/Preview/components/Torrents/components/Player/useStats.ts @@ -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({ + 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 + ) + }; +}; diff --git a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx index ba317dc..0e208df 100644 --- a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx +++ b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx @@ -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 = ({ 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 = ({ 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' > @@ -59,7 +61,7 @@ const Actions: FC = ({ 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)}`} /> diff --git a/components/Preview/components/Torrents/components/TorrentsTable/index.tsx b/components/Preview/components/Torrents/components/TorrentsTable/index.tsx index 1c265d7..9c89f9c 100644 --- a/components/Preview/components/Torrents/components/TorrentsTable/index.tsx +++ b/components/Preview/components/Torrents/components/TorrentsTable/index.tsx @@ -46,7 +46,6 @@ const TorrentsTable: FC = ({ title, torrents, backdrop, sort, sortable, p {torrents?.map((torrent) => { const yearView = torrent.year && year.toString() != torrent.year && `[${torrent.year}]`; - return ( diff --git a/data/parsers/tpb/index.ts b/data/parsers/tpb/index.ts index 814b5be..9d1b05c 100644 --- a/data/parsers/tpb/index.ts +++ b/data/parsers/tpb/index.ts @@ -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: '' }; }); }); diff --git a/data/parsers/yts/index.ts b/data/parsers/yts/index.ts index 2897d8e..2c0def7 100644 --- a/data/parsers/yts/index.ts +++ b/data/parsers/yts/index.ts @@ -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 }; }) || [] ); diff --git a/env.ts b/env.ts index 3923f28..94c76e0 100644 --- a/env.ts +++ b/env.ts @@ -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; diff --git a/hooks/useToast.ts b/hooks/useToast.ts index c23e8d0..097c013 100644 --- a/hooks/useToast.ts +++ b/hooks/useToast.ts @@ -185,4 +185,4 @@ function useToast() { }; } -export { toast,useToast }; +export { toast, useToast }; diff --git a/lib/utils.ts b/lib/utils.ts index d5ac8e9..ae77617 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -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]}`; +}; diff --git a/package-lock.json b/package-lock.json index 13efb73..6d86d26 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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" diff --git a/package.json b/package.json index 626f975..b9d4586 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/types.d.ts b/types.d.ts index 6c70e74..bd5b799 100644 --- a/types.d.ts +++ b/types.d.ts @@ -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; -}