feat: alt player

This commit is contained in:
ner committed 2025-08-17 18:31:42 +03:00
1 parent 6fc34e3797
commit 2e16746a40
16 files changed
+333 -207

No files matched your search

@@ -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<Props> = ({ videos, subtitles, magnet }) => {
const { index, setIndex } = useSource({ magnet });
const player = useRef<MediaPlayerInstance>(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 (
<MediaPlayer
playsInline
load='eager'
storage='movie-advisor'
ref={player}
src={(source as VideoSrc) || []}
className='relative size-full select-none'
>
<MediaProvider className='relative flex size-full justify-center [&>video]:!h-full'>
{subtitles.map((track, index) => (
<Track key={track.name} src={track.src} kind='subtitles' label={track.name} type='srt' default={!index} />
))}
</MediaProvider>
<PlyrLayout
icons={plyrLayoutIcons}
slots={{
playLargeButton: null,
settingsMenu: null,
captionsButton: null,
afterPlayButton: hasNext && (
<PlayButton onClick={() => setIndex(index + 1)} className={cn('plyr__controls__item plyr__control')}>
<NextIcon className={cn('vds-icon')} />
<span className={cn('plyr__tooltip')}>Next</span>
</PlayButton>
),
afterVolumeSlider: <ul className='w-2' />,
beforeSettings: Boolean(subtitles.length) && <CaptionsMenu />,
settings: videos.length > 1 && (
<PlaylistMenu key={source?.src} source={source} sources={videos} onChange={setIndex} />
)
}}
/>
</MediaPlayer>
);
};
export default Player;
@@ -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();
@@ -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<VirtuosoHandle | null>(null);
const scrollRef = useRef<HTMLDivElement>(null) as MutableRefObject<HTMLDivElement>;
useLayoutEffect(() => {
const index = +value || 0;
if (!index || !virtuosoRef.current) return;
setTimeout(() => virtuosoRef.current?.scrollToIndex(index), 1000);
}, [value]);
return (
<Modal className='max-w-screen-xs rounded-xl p-2' onClose={onResolve} scrollRef={scrollRef}>
<Modal
className='max-w-screen-xs rounded-xl p-2'
onClose={onResolve}
scrollRef={scrollRef}
portal={(document.fullscreenElement || document.body) as HTMLElement}
>
<Virtuoso
useWindowScroll
initialTopMostItemIndex={+value || 0}
overscan={20}
initialItemCount={20}
overscan={10}
initialItemCount={50}
ref={virtuosoRef}
customScrollParent={scrollRef.current}
defaultItemHeight={56}
fixedItemHeight={56}
data={options}
context={value}
components={components}
@@ -63,7 +77,7 @@ const components: VirtuosoProps<Option, string>['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<Option, string>['components'] = {
},
List: forwardRef(function List({ children, ...props }, ref) {
return (
<div className='flex flex-col gap-2' {...props} ref={ref}>
<div className='flex flex-col' {...props} ref={ref}>
{children}
</div>
);
@@ -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;
@@ -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<void> {
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<Props> = ({ controlRef }) => {
const [{ magnet, playlist, subtitles }, setStream] = useState<Stream>(initialStream);
const [canPlay, setCanPlay] = useState(false);
const { index, setIndex } = useSource({ magnet });
const player = useRef<MediaPlayerInstance>(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 (
<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} />
</div>
{!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 transition-all'>
{!preloadingProgress && !peers && (
<>
<MediaPlayer
load='eager'
preload='none'
storage='movie-advisor'
ref={player}
src={(source as VideoSrc) || []}
onCanPlay={handlePlay}
className={cn('relative size-full select-none', { invisible: pending })}
>
<MediaProvider className='relative flex size-full justify-center [&>video]:!h-full'>
{subtitles.map((track, index) => (
<Track key={track.name} src={track.src} kind='subtitles' label={track.name} type='srt' default={!index} />
))}
</MediaProvider>
<PlyrLayout
className='hidden'
icons={plyrLayoutIcons}
slots={{
playLargeButton: null,
settingsMenu: null,
captionsButton: null,
afterPlayButton: hasNext && (
<PlayButton onClick={() => setIndex(index + 1)} className={cn('plyr__controls__item plyr__control')}>
<NextIcon className={cn('vds-icon')} />
<span className={cn('plyr__tooltip')}>Next</span>
</PlayButton>
),
afterVolumeSlider: <ul className='w-2' />,
beforeSettings: Boolean(subtitles.length) && <Captions />,
settings: playlist.length > 1 && (
<Playlist key={source?.src} source={source} sources={playlist} onChange={setIndex} />
)
}}
/>
</MediaPlayer>
{pending && (
<div className='absolute left-0 top-0 flex size-full items-center justify-center'>
<div className='flex size-12 items-center justify-center rounded bg-black/60'>
<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'>
<p className='text-white/90'>Buffering: {preloadingProgress.toFixed()}%</p>
<p className='text-white/90'>Download speed: {downloadSpeed || '0 B/s'}</p>
</div>
</div>
)}
</div>
)}
</div>
</Modal>
</>
);
});
};
export default showPlayer;
export default Player;
@@ -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<Stream>({
queryKey: ['files', magnet],
queryFn: () => fetch(`${streamUrl}&stat&preload`).then((response) => response.json())
});
const data = (query.data?.file_stats || []).reduce<Sources>(
(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;
@@ -10,7 +10,11 @@ const sourceStateAtom = atomWithStorage<SourceState>('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();
@@ -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<void> {
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 (
<Modal
className='overflow-hidden border-none bg-black p-0'
onClose={onResolve}
onInteractOutside={handlePlayerInteraction}
onPointerDownOutside={handlePlayerInteraction}
>
<div className='relative w-full overflow-hidden pt-[56.25%]'>
{!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 transition-all'
style={{ width: `${100 - preloadingProgress}%` }}
/>
<div className='absolute left-0 top-0 flex size-full flex-col items-center justify-between text-sm text-white/90'>
<div className='grid w-full items-center bg-black/80 p-2 text-center'>
<p>Buffering: {preloadingProgress.toFixed()}%</p>
</div>
<div className='grid w-full items-center gap-2 bg-black/80 p-2 text-center'>
<p>Download speed: {downloadSpeed || '0 B/s'}</p>
</div>
</div>
</div>
)}
<div className='absolute left-0 top-0 size-full' id={playerEntryId} />
</div>
</Modal>
);
});
export default showPlayerModal;
@@ -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<Props> = ({ torrent, backdrop, title, provider }) => {
const Actions: FC<Props> = ({ torrent, backdrop, title, provider, playerEntryId, onPlay }) => {
const prefix = usePrefix();
const cast = useCastMagnet();
const streamUrl = useStreamUrl();
@@ -45,6 +48,8 @@ const Actions: FC<Props> = ({ 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<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, hash })}
onClick={() => {
showPlayerModal({ backdrop, title, hash, playerEntryId });
onPlay(fetchSources.mutateAsync().then((sources) => ({ sources, magnet })));
}}
title='Play'
>
<Play size={15} />
@@ -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<Sources>({
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>(
(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;
@@ -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<Props> = ({ title, torrents, backdrop, sort, sortable, provider, year, onChangeSort }) => {
const TorrentsTable: FC<Props> = ({
title,
torrents,
backdrop,
sort,
sortable,
provider,
year,
onChangeSort,
onPlay,
playerEntryId
}) => {
const colSpan = 5;
return (
@@ -68,7 +81,14 @@ const TorrentsTable: FC<Props> = ({ title, torrents, backdrop, sort, sortable, p
</TableCell>
<TableCell className='truncate p-2'>{torrent.seeders}</TableCell>
<TableCell className='p-1 pr-2 text-center'>
<Actions title={title} backdrop={backdrop} torrent={torrent} provider={provider} />
<Actions
title={title}
backdrop={backdrop}
torrent={torrent}
provider={provider}
onPlay={onPlay}
playerEntryId={playerEntryId}
/>
</TableCell>
</TableRow>
</Fragment>
@@ -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<HTMLDivElement>(null);
const handleSearch = (event: FormEvent) => {
event.preventDefault();
@@ -78,6 +86,13 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
query.isFetched && !query.isLoading && !query.data?.length;
return (
<>
<div className='hidden' ref={playerEntryRef}>
{createPortal(
<Player controlRef={playerControlRef} />,
document.getElementById(playerEntryId) || playerEntryRef.current || document.body
)}
</div>
<Modal className='rounded-xl p-0' onClose={onResolve}>
<form className='p-2' tabIndex={1} onSubmit={handleSearch}>
<ButtonsGroup className='h-10'>
@@ -104,7 +119,7 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
</TabsTrigger>
))}
</TabsList>
{tabs.map(({ provider, query }, index) => {
{tabs.map(({ provider, query }) => {
const isEmpty = checkIsEmpty(query);
return (
@@ -118,6 +133,13 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
onChangeSort={setSort}
provider={provider.key}
torrents={query.data || []}
playerEntryId={playerEntryId}
onPlay={(options) => {
if (!playerControlRef.current) return;
playerControlRef.current.sample();
options.then((options) => playerControlRef.current.play(options));
}}
/>
{(query.isLoading || query.isFetching) && (
@@ -136,6 +158,7 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
})}
</Tabs>
</Modal>
</>
);
});
+18 -4
View File
@@ -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<typeof DialogPrimitive.Content> & {
onClose?: () => void;
scrollRef?: React.MutableRefObject<HTMLDivElement>;
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 (
<DialogPortal>
<DialogPortal container={portal}>
<div className='fixed inset-0 z-50 size-full bg-black/80' data-overlay ref={wrapperRef}>
<DialogOverlay
ref={(element) => {
@@ -172,7 +174,10 @@ const Modal: React.FC<{
style?: CSSProperties;
onClose: () => void;
scrollRef?: React.MutableRefObject<HTMLDivElement>;
}> = ({ 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<{
<DialogHeader>
<DialogTitle />
</DialogHeader>
<DialogContent style={style} scrollRef={scrollRef} forceMount onClose={handleClose} className={className}>
<DialogContent
onInteractOutside={onInteractOutside}
onPointerDownOutside={onPointerDownOutside}
style={style}
scrollRef={scrollRef}
forceMount
onClose={handleClose}
className={className}
portal={portal}
>
{children}
<DialogDescription className='hidden' />
</DialogContent>
BIN
View File
Binary file not shown.
Vendored
+5
View File
@@ -141,6 +141,11 @@ interface Source {
type: string;
}
interface Sources {
playlist: Source[];
subtitles: Source[];
}
interface Subtitles {
name: string;
content: string;