diff --git a/components/Preview/components/Torrents/components/Player/Player.tsx b/components/Preview/components/Torrents/components/Player/Player.tsx deleted file mode 100644 index ef24312..0000000 --- a/components/Preview/components/Torrents/components/Player/Player.tsx +++ /dev/null @@ -1,84 +0,0 @@ -'use client'; - -import { FC, useEffect, useRef } from 'react'; -import { - MediaPlayer, - MediaPlayerInstance, - MediaProvider, - PlayButton, - Track, - useMediaState, - VideoSrc -} from '@vidstack/react'; -import { NextIcon } from '@vidstack/react/icons'; -import { PlyrLayout, plyrLayoutIcons } from '@vidstack/react/player/layouts/plyr'; - -import { cn } from '@/lib/utils'; - -import CaptionsMenu from './components/CaptionsMenu'; -import PlaylistMenu from './components/PlaylistMenu'; -import useSource from './useSource'; - -import '@vidstack/react/player/styles/plyr/theme.css'; - -interface Props { - magnet: string; - subtitles: Source[]; - videos: Source[]; -} - -const Player: FC = ({ videos, subtitles, magnet }) => { - const { index, setIndex } = useSource({ magnet }); - - const player = useRef(null); - - const isEnded = useMediaState('ended', player); - - const hasNext = index + 1 < videos?.length; - - useEffect(() => { - if (!isEnded || !hasNext) return; - - setIndex((index) => index + 1); - }, [isEnded, hasNext, setIndex]); - - const source = videos[index]; - - return ( - - - {subtitles.map((track, index) => ( - - ))} - - setIndex(index + 1)} className={cn('plyr__controls__item plyr__control')}> - - Next - - ), - afterVolumeSlider:
    , - beforeSettings: Boolean(subtitles.length) && , - settings: videos.length > 1 && ( - - ) - }} - /> - - ); -}; - -export default Player; diff --git a/components/Preview/components/Torrents/components/Player/components/CaptionsMenu/index.tsx b/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx similarity index 95% rename from components/Preview/components/Torrents/components/Player/components/CaptionsMenu/index.tsx rename to components/Preview/components/Torrents/components/Player/components/Captions/index.tsx index 1e13ff7..22f1282 100644 --- a/components/Preview/components/Torrents/components/Player/components/CaptionsMenu/index.tsx +++ b/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx @@ -3,7 +3,7 @@ import { ClosedCaptionsIcon, ClosedCaptionsOnIcon } from '@vidstack/react/icons' import { cn } from '@/lib/utils'; -import PlayerMenu from '../PlayerMenu'; +import PlayerMenu from '../Menu'; const CaptionsMenu = () => { const tracks = useCaptionOptions(); diff --git a/components/Preview/components/Torrents/components/Player/components/PlayerMenu/index.tsx b/components/Preview/components/Torrents/components/Player/components/Menu/index.tsx similarity index 74% rename from components/Preview/components/Torrents/components/Player/components/PlayerMenu/index.tsx rename to components/Preview/components/Torrents/components/Player/components/Menu/index.tsx index 999038b..8eee7b3 100644 --- a/components/Preview/components/Torrents/components/Player/components/PlayerMenu/index.tsx +++ b/components/Preview/components/Torrents/components/Player/components/Menu/index.tsx @@ -1,4 +1,4 @@ -import React, { FC, forwardRef, MutableRefObject, ReactNode, useRef } from 'react'; +import React, { FC, forwardRef, MutableRefObject, ReactNode, useLayoutEffect, useRef } from 'react'; import { create, InstanceProps } from 'react-modal-promise'; import { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso'; import { Menu } from '@vidstack/react'; @@ -20,15 +20,29 @@ const showMenu = create( const virtuosoRef = useRef(null); const scrollRef = useRef(null) as MutableRefObject; + useLayoutEffect(() => { + const index = +value || 0; + + if (!index || !virtuosoRef.current) return; + + setTimeout(() => virtuosoRef.current?.scrollToIndex(index), 1000); + }, [value]); + return ( - + ['components'] = { 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', + '!m-0 cursor-pointer line-clamp-2 rounded-sm bg-secondary text-left !px-2 !py-1 text-foreground !mb-2', { 'bg-secondary-foreground text-secondary': context === option.value } @@ -75,7 +89,7 @@ const components: VirtuosoProps['components'] = { }, List: forwardRef(function List({ children, ...props }, ref) { return ( -
    +
    {children}
    ); diff --git a/components/Preview/components/Torrents/components/Player/components/PlaylistMenu/index.tsx b/components/Preview/components/Torrents/components/Player/components/Playlist/index.tsx similarity index 95% rename from components/Preview/components/Torrents/components/Player/components/PlaylistMenu/index.tsx rename to components/Preview/components/Torrents/components/Player/components/Playlist/index.tsx index 99dfca2..488530e 100644 --- a/components/Preview/components/Torrents/components/Player/components/PlaylistMenu/index.tsx +++ b/components/Preview/components/Torrents/components/Player/components/Playlist/index.tsx @@ -3,7 +3,7 @@ import { PlaylistIcon } from '@vidstack/react/icons'; import { cn } from '@/lib/utils'; -import PlayerMenu from '../PlayerMenu'; +import PlayerMenu from '../Menu'; interface Props { source: Source; diff --git a/components/Preview/components/Torrents/components/Player/index.tsx b/components/Preview/components/Torrents/components/Player/index.tsx index e9ee442..02275b4 100644 --- a/components/Preview/components/Torrents/components/Player/index.tsx +++ b/components/Preview/components/Torrents/components/Player/index.tsx @@ -1,58 +1,143 @@ -import { useEffect, useRef } from 'react'; -import { create, InstanceProps } from 'react-modal-promise'; +'use client'; + +import { FC, MutableRefObject, useEffect, useImperativeHandle, useRef, useState } from 'react'; +import { + MediaPlayer, + MediaPlayerInstance, + MediaProvider, + PlayButton, + Track, + useMediaState, + VideoSrc +} from '@vidstack/react'; +import { NextIcon } from '@vidstack/react/icons'; +import { PlyrLayout, plyrLayoutIcons } from '@vidstack/react/player/layouts/plyr'; 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 { cn } from '@/lib/utils'; -import useFiles from './useFiles'; -import { useStats } from './useStats'; +import Captions from './components/Captions'; +import Playlist from './components/Playlist'; +import useSource from './useSource'; -const Player = dynamic(() => import('./Player')); +import '@vidstack/react/player/styles/plyr/theme.css'; -interface Props extends InstanceProps { +interface Stream { magnet: string; - hash?: string; - backdrop: string; - title: string; + subtitles: Source[]; + playlist: Source[]; } -const showPlayer = create(({ onResolve, magnet, hash, backdrop, title }: Props) => { - const { subtitles, videos } = useFiles({ magnet, onResolve }); +const sample = { type: 'video/mp4', src: '/sample.mp4', name: 'Sample' }; - const { isReady, preloadingProgress, downloadSpeed, peers } = useStats({ hash }); +const initialStream: Stream = { + magnet: '', + subtitles: [], + playlist: [sample] +}; + +export type PlayerControlRef = MutableRefObject<{ + sample: () => void; + play: (options: { sources: Sources; magnet: string }) => void; + stop: () => void; +}>; + +interface Props { + controlRef: PlayerControlRef; +} + +const Player: FC = ({ controlRef }) => { + const [{ magnet, playlist, subtitles }, setStream] = useState(initialStream); + const [canPlay, setCanPlay] = useState(false); + + const { index, setIndex } = useSource({ magnet }); + + const player = useRef(null); + + const isEnded = useMediaState('ended', player); + + const hasNext = index + 1 < playlist?.length; + + useEffect(() => { + if (!isEnded || !hasNext) return; + + setIndex((index) => index + 1); + }, [isEnded, hasNext, setIndex]); + + const source = playlist[index]; + + const handlePlay = () => { + if (!player.current) return; + + player.current + .play() + .catch(() => {}) + .finally(() => setCanPlay(true)); + }; + + useImperativeHandle(controlRef, () => ({ + sample() { + handlePlay(); + setCanPlay(false); + }, + play({ magnet, sources }) { + setStream({ magnet, ...sources }); + }, + stop() { + setStream(initialStream); + } + })); + + const pending = !canPlay || source === sample; return ( - -
    -
    - -
    - {!isReady && ( -
    - {title} -
    - {!preloadingProgress && !peers && ( -
    - -
    - )} + <> + + + {subtitles.map((track, index) => ( + + ))} + + setIndex(index + 1)} className={cn('plyr__controls__item plyr__control')}> + + Next + + ), + afterVolumeSlider:
      , + beforeSettings: Boolean(subtitles.length) && , + settings: playlist.length > 1 && ( + + ) + }} + /> + + {pending && ( +
      +
      +
      +
      - {(downloadSpeed || peers) && ( -
      -
      -

      Buffering: {preloadingProgress.toFixed()}%

      -

      Download speed: {downloadSpeed || '0 B/s'}

      -
      -
      - )}
      - )} -
      - +
    + )} + ); -}); +}; -export default showPlayer; +export default Player; diff --git a/components/Preview/components/Torrents/components/Player/useFiles.ts b/components/Preview/components/Torrents/components/Player/useFiles.ts deleted file mode 100644 index bec1dc0..0000000 --- a/components/Preview/components/Torrents/components/Player/useFiles.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { useEffect, useRef } from 'react'; -import { useQuery } from '@tanstack/react-query'; - -import { useStreamUrl } from '@/hooks/useStreamUrl'; -import { useToast } from '@/hooks/useToast'; - -export type Source = { name: string; src: string; type: string }; -type Sources = { subtitles: Source[]; videos: Source[] }; - -interface Props { - magnet: string; - onResolve: () => void; -} - -const useFiles = ({ magnet, onResolve }: Props) => { - const streamUrl = `${useStreamUrl()}/stream?link=${encodeURIComponent(magnet)}`; - const query = useQuery({ - queryKey: ['files', magnet], - queryFn: () => fetch(`${streamUrl}&stat&preload`).then((response) => response.json()) - }); - - const data = (query.data?.file_stats || []).reduce( - (sources, file) => { - if (file.path.endsWith('.mp4')) { - sources.videos.push({ src: `${streamUrl}&index=${file.id}&play`, name: file.path, type: 'video/mp4' }); - } - - if (file.path.endsWith('.srt')) { - sources.subtitles.push({ src: `${streamUrl}&index=${file.id}&play`, name: file.path, type: 'srt' }); - } - - return sources; - }, - { subtitles: [], videos: [] } - ); - - const isResolvedRef = useRef(false); - - const { toast } = useToast(); - - useEffect(() => { - const close = () => { - if (isResolvedRef.current) return; - - isResolvedRef.current = true; - onResolve(); - }; - - if (query.error) { - toast({ description: 'Download Failed: unable to retrieve the video' }); - close(); - } - - if (query.isFetched && !data.videos.length) { - toast({ description: 'This torrent doesn’t contain any compatible video files' }); - close(); - } - }, [query.isFetched, data.videos.length, query.error]); - - return data; -}; - -export default useFiles; diff --git a/components/Preview/components/Torrents/components/Player/useSource.ts b/components/Preview/components/Torrents/components/Player/useSource.ts index 630f90c..7fd8b76 100644 --- a/components/Preview/components/Torrents/components/Player/useSource.ts +++ b/components/Preview/components/Torrents/components/Player/useSource.ts @@ -10,7 +10,11 @@ const sourceStateAtom = atomWithStorage('current-video-source', {}, unstable_getOnInit: true }); -const useSource = ({ magnet }: { magnet: string }) => { +interface Props { + magnet: string; +} + +const useSource = ({ magnet }: Props) => { const [source, setSource] = useAtom(sourceStateAtom); const account = useAccount(); diff --git a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/components/Player/index.tsx b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/components/Player/index.tsx new file mode 100644 index 0000000..18a14dc --- /dev/null +++ b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/components/Player/index.tsx @@ -0,0 +1,53 @@ +import { create, InstanceProps } from 'react-modal-promise'; +import { DialogContentProps } from '@radix-ui/react-dialog'; + +import { Modal } from '@/components/ui/dialog'; + +import { useStats } from './useStats'; + +interface Props extends InstanceProps { + hash: string; + backdrop: string; + title: string; + playerEntryId: string; +} + +const showPlayerModal = create(({ onResolve, hash, backdrop, title, playerEntryId }: Props) => { + const { isReady, preloadingProgress, downloadSpeed, peers } = useStats({ hash }); + + const handlePlayerInteraction: DialogContentProps['onInteractOutside'] = (event) => { + if (document.getElementById(playerEntryId)?.contains(event.target as Node)) event.preventDefault(); + }; + + return ( + +
    + {!isReady && ( +
    + {title} +
    +
    +
    +

    Buffering: {preloadingProgress.toFixed()}%

    +
    +
    +

    Download speed: {downloadSpeed || '0 B/s'}

    +
    +
    +
    + )} +
    +
    + + ); +}); + +export default showPlayerModal; diff --git a/components/Preview/components/Torrents/components/Player/useStats.ts b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/components/Player/useStats.ts similarity index 100% rename from components/Preview/components/Torrents/components/Player/useStats.ts rename to components/Preview/components/Torrents/components/TorrentsTable/components/Actions/components/Player/useStats.ts 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 0fed86f..2bf5ecc 100644 --- a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx +++ b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx @@ -9,8 +9,9 @@ import { cn, detectSafari, getMagnetHash } from '@/lib/utils'; import { providers } from '../../../../constants'; import { useCastMagnet, usePrefix } from '../../../../hooks/useMagnetHosts'; -import showPlayer from '../../../Player'; +import showPlayerModal from './components/Player'; +import useFiles from './useFiles'; import useMagnet from './useMagnet'; interface Props { @@ -18,9 +19,11 @@ interface Props { backdrop: string; title: string; provider: string; + onPlay: (options: Promise<{ sources: Sources; magnet: string }>) => void; + playerEntryId: string; } -const Actions: FC = ({ torrent, backdrop, title, provider }) => { +const Actions: FC = ({ torrent, backdrop, title, provider, playerEntryId, onPlay }) => { const prefix = usePrefix(); const cast = useCastMagnet(); const streamUrl = useStreamUrl(); @@ -45,6 +48,8 @@ const Actions: FC = ({ torrent, backdrop, title, provider }) => { const magnet = fetchMagnet.data || torrent.magnet; + const fetchSources = useFiles({ magnet }); + const hash = getMagnetHash(magnet); const supportedForCast = prefix && !prefix.includes('{host}'); @@ -59,7 +64,10 @@ 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, hash })} + onClick={() => { + showPlayerModal({ backdrop, title, hash, playerEntryId }); + onPlay(fetchSources.mutateAsync().then((sources) => ({ sources, magnet }))); + }} title='Play' > diff --git a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/useFiles.ts b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/useFiles.ts new file mode 100644 index 0000000..60d63f4 --- /dev/null +++ b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/useFiles.ts @@ -0,0 +1,47 @@ +import { useMutation } from '@tanstack/react-query'; + +import { useStreamUrl } from '@/hooks/useStreamUrl'; + +interface Props { + magnet: string; +} + +const useFiles = ({ magnet }: Props) => { + const streamUrl = `${useStreamUrl()}/stream?link=${encodeURIComponent(magnet)}`; + + return useMutation({ + mutationFn: () => + fetch(`${streamUrl}&stat&preload`) + .then((response) => { + if (!response.ok) return Promise.reject('Download Failed: unable to retrieve the video'); + + return response.json(); + }) + .then(({ file_stats: stats }: Stream) => { + const sources = stats.reduce( + (sources, file) => { + const src = `${streamUrl}&index=${file.id}&play`; + const name = file.path; + + if (file.path.endsWith('.mp4')) { + sources.playlist.push({ src, name, type: 'video/mp4' }); + } + + if (file.path.endsWith('.srt')) { + sources.subtitles.push({ src, name, type: 'srt' }); + } + + return sources; + }, + { subtitles: [], playlist: [] } + ); + + if (!sources.playlist.length) + return Promise.reject('This torrent doesn’t contain any compatible video files'); + + return sources; + }) + }); +}; + +export default useFiles; diff --git a/components/Preview/components/Torrents/components/TorrentsTable/index.tsx b/components/Preview/components/Torrents/components/TorrentsTable/index.tsx index 9c89f9c..b540d58 100644 --- a/components/Preview/components/Torrents/components/TorrentsTable/index.tsx +++ b/components/Preview/components/Torrents/components/TorrentsTable/index.tsx @@ -17,9 +17,22 @@ interface Props { provider: string; year: number; onChangeSort: (sort: Sort) => void; + onPlay: (options: Promise<{ sources: Sources; magnet: string }>) => void; + playerEntryId: string; } -const TorrentsTable: FC = ({ title, torrents, backdrop, sort, sortable, provider, year, onChangeSort }) => { +const TorrentsTable: FC = ({ + title, + torrents, + backdrop, + sort, + sortable, + provider, + year, + onChangeSort, + onPlay, + playerEntryId +}) => { const colSpan = 5; return ( @@ -68,7 +81,14 @@ const TorrentsTable: FC = ({ title, torrents, backdrop, sort, sortable, p {torrent.seeders} - + diff --git a/components/Preview/components/Torrents/index.tsx b/components/Preview/components/Torrents/index.tsx index 60116b8..189595a 100644 --- a/components/Preview/components/Torrents/index.tsx +++ b/components/Preview/components/Torrents/index.tsx @@ -1,4 +1,5 @@ -import React, { FormEvent, useState } from 'react'; +import React, { FormEvent, useId, useRef, useState } from 'react'; +import { createPortal } from 'react-dom'; import { create, InstanceProps } from 'react-modal-promise'; import { TabsContent } from '@radix-ui/react-tabs'; import { Loader } from 'lucide-react'; @@ -11,6 +12,7 @@ import { Input } from '@/components/ui/input'; import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Sort } from '@/data/parsers'; +import Player, { PlayerControlRef } from './components/Player'; import TorrentsTable from './components/TorrentsTable'; import { providers } from './constants'; import useTorrents from './useTorrents'; @@ -68,6 +70,12 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop, } ]; + const playerControlRef = useRef() as PlayerControlRef; + + const playerEntryId = useId(); + + const playerEntryRef = useRef(null); + const handleSearch = (event: FormEvent) => { event.preventDefault(); @@ -78,64 +86,79 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop, query.isFetched && !query.isLoading && !query.data?.length; return ( - -
    - - setTitle(target.value)} - placeholder='Start typing title...' - /> - - -
    - - - {tabs.map(({ provider, query }) => ( - - {query.isLoading ? : provider.label} - - ))} - - {tabs.map(({ provider, query }, index) => { - const isEmpty = checkIsEmpty(query); + <> +
    + {createPortal( + , + document.getElementById(playerEntryId) || playerEntryRef.current || document.body + )} +
    + +
    + + setTitle(target.value)} + placeholder='Start typing title...' + /> + + +
    + + + {tabs.map(({ provider, query }) => ( + + {query.isLoading ? : provider.label} + + ))} + + {tabs.map(({ provider, query }) => { + const isEmpty = checkIsEmpty(query); - return ( - - + return ( + + { + if (!playerControlRef.current) return; - {(query.isLoading || query.isFetching) && ( -
    - -
    - )} + playerControlRef.current.sample(); + options.then((options) => playerControlRef.current.play(options)); + }} + /> - {isEmpty && ( -
    - Nothing was found -
    - )} -
    - ); - })} -
    -
    + {(query.isLoading || query.isFetching) && ( +
    + +
    + )} + + {isEmpty && ( +
    + Nothing was found +
    + )} + + ); + })} +
    +
    + ); }); diff --git a/components/ui/dialog.tsx b/components/ui/dialog.tsx index f1e60dc..bc1ea43 100644 --- a/components/ui/dialog.tsx +++ b/components/ui/dialog.tsx @@ -3,6 +3,7 @@ import * as React from 'react'; import { CSSProperties, useState } from 'react'; import * as DialogPrimitive from '@radix-ui/react-dialog'; +import { DialogContentProps } from '@radix-ui/react-dialog'; import useScrollDelta from '@/hooks/useScrollDelta'; import { cn } from '@/lib/utils'; @@ -37,8 +38,9 @@ const DialogContent = React.forwardRef< React.ComponentPropsWithoutRef & { onClose?: () => void; scrollRef?: React.MutableRefObject; + portal?: HTMLElement; } ->(({ className, children, onClose, scrollRef, ...props }, ref) => { +>(({ className, children, onClose, scrollRef, portal, ...props }, ref) => { const FULL_OPACITY = 1; const position = React.useRef(0); @@ -101,7 +103,7 @@ const DialogContent = React.forwardRef< }; return ( - +
    { @@ -172,7 +174,10 @@ const Modal: React.FC<{ style?: CSSProperties; onClose: () => void; scrollRef?: React.MutableRefObject; -}> = ({ children, onClose, className, style, scrollRef }) => { + onInteractOutside?: DialogContentProps['onInteractOutside']; + onPointerDownOutside?: DialogContentProps['onPointerDownOutside']; + portal?: HTMLElement; +}> = ({ children, onClose, className, style, scrollRef, onInteractOutside, onPointerDownOutside, portal }) => { const [open, setOpen] = useState(true); React.useLayoutEffect(() => { @@ -194,7 +199,16 @@ const Modal: React.FC<{ - + {children} diff --git a/public/sample.mp4 b/public/sample.mp4 new file mode 100644 index 0000000..b11552f Binary files /dev/null and b/public/sample.mp4 differ diff --git a/types.d.ts b/types.d.ts index bd5b799..2b0a688 100644 --- a/types.d.ts +++ b/types.d.ts @@ -141,6 +141,11 @@ interface Source { type: string; } +interface Sources { + playlist: Source[]; + subtitles: Source[]; +} + interface Subtitles { name: string; content: string;