feat: torrent player
This commit is contained in:
1 parent
b379bc229d
commit
f6cb8df39b
17 files changed
+1699
-3683
No files matched your search
+2
-2
@@ -1,7 +1,7 @@
|
||||
class Http {
|
||||
base = 'https://api.themoviedb.org/3';
|
||||
|
||||
get<T>(url: string, { params }: { params?: Record<string, unknown> } = {}): Promise<T> {
|
||||
get<T>(url: string, { params }: { params?: Record<string, unknown> } = {}, base?: string): Promise<T> {
|
||||
const serializedParams = Object.entries(params || {}).reduce((params, [key, value]) => {
|
||||
if (!['', undefined, null].includes(value as string)) {
|
||||
params.set(key, value as string);
|
||||
@@ -10,7 +10,7 @@ class Http {
|
||||
return params;
|
||||
}, new URLSearchParams());
|
||||
|
||||
return fetch(`${this.base}${url}?${serializedParams}`, {
|
||||
return fetch(`${base || this.base}${url}?${serializedParams}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.MOVIE_DB_TOKEN}`
|
||||
},
|
||||
|
||||
@@ -174,6 +174,22 @@ export const trailers = async ({
|
||||
.then((data) => data.results);
|
||||
};
|
||||
|
||||
export const torrentFiles = (magnet: string): Promise<Video[]> => {
|
||||
return http
|
||||
.get<{ name: string; subtitles: Subtitles[] }[]>('/files', { params: { magnet } }, process.env.TRACKER_PROXY_BASE)
|
||||
.then((files) =>
|
||||
files.map((file) => {
|
||||
const base = `${process.env.TRACKER_PROXY_BASE}/stream?magnet=${encodeURIComponent(magnet)}}`;
|
||||
|
||||
return {
|
||||
name: file.name,
|
||||
src: `${base}&filename=${encodeURIComponent(file.name)}`,
|
||||
subtitles: file.subtitles
|
||||
};
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
export const YTSTorrents = async ({
|
||||
query,
|
||||
sort,
|
||||
|
||||
@@ -53,6 +53,7 @@ export class YTS {
|
||||
title: `${movie.title_english} ${torrent.quality ? `[${torrent.quality}]` : ''}`,
|
||||
seeders: torrent.seeds,
|
||||
size: torrent.size,
|
||||
type: torrent.type,
|
||||
magnet: `magnet:?xt=urn:btih:${torrent.hash}&dn=${encodeURIComponent(query)}&tr=${trackers.join('&tr=')}`
|
||||
};
|
||||
}) || []
|
||||
|
||||
@@ -9,6 +9,7 @@ import Header from '@/components/Header';
|
||||
import Providers from '@/providers';
|
||||
|
||||
import '@/styles/index.css';
|
||||
import '@/styles/player.css';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Movie advisor | Discover Your Next Favorite Movie',
|
||||
|
||||
@@ -4,6 +4,7 @@ import { FC } from 'react';
|
||||
import { Heart } from 'lucide-react';
|
||||
|
||||
import { useFavoriteToggle } from '@/app/(site)/favorites/useFavorites';
|
||||
import useMounted from '@/hooks/useMounted';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface Props {
|
||||
@@ -11,11 +12,16 @@ interface Props {
|
||||
}
|
||||
|
||||
const Favorite: FC<Props> = ({ show }) => {
|
||||
const isMounted = useMounted();
|
||||
const { isFavorite, toggle } = useFavoriteToggle(show);
|
||||
|
||||
return (
|
||||
<span onClick={toggle} className='cursor-pointer' title={isFavorite ? 'Remove from favorites' : 'Add to favorite'}>
|
||||
<Heart className={cn(isFavorite && 'fill-white')} size={20} />
|
||||
<span
|
||||
onClick={toggle}
|
||||
className='cursor-pointer'
|
||||
title={isMounted && isFavorite ? 'Remove from favorites' : 'Add to favorite'}
|
||||
>
|
||||
<Heart className={cn(isMounted && isFavorite && 'fill-white')} size={20} />
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { FC, useEffect, useRef } from 'react';
|
||||
import { InstanceProps } from 'react-modal-promise';
|
||||
import video from 'video.js';
|
||||
import WebTorrent from 'webtorrent/dist/webtorrent.min.js';
|
||||
|
||||
import { Modal } from '@/components/ui/dialog';
|
||||
|
||||
import 'video.js/dist/video-js.css';
|
||||
|
||||
interface Props extends InstanceProps<void> {
|
||||
magnet: string;
|
||||
}
|
||||
|
||||
const Player: FC<Props> = ({ onResolve, magnet }) => {
|
||||
const videoRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let skip = false;
|
||||
const client = new WebTorrent();
|
||||
|
||||
navigator.serviceWorker.register('./sw.min.js', { scope: './' }).then((registration) => {
|
||||
const worker = registration.active || registration.waiting || registration.installing;
|
||||
|
||||
const createServer = (worker: ServiceWorker | null) => {
|
||||
if (worker?.state !== 'activated' || skip) return false;
|
||||
|
||||
client.createServer({ controller: registration });
|
||||
|
||||
console.log(client);
|
||||
};
|
||||
|
||||
if (!createServer(worker)) {
|
||||
worker?.addEventListener('statechange', ({ target }) => createServer(target as ServiceWorker));
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
skip = true;
|
||||
client.removeAllListeners();
|
||||
client.destroy();
|
||||
navigator.serviceWorker.getRegistration('./sw.min.js').then((registration) => registration?.unregister());
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Modal className='block p-0 max-w-[930px] border-none bg-black' style={{ aspectRatio: '16/9' }} onClose={onResolve}>
|
||||
<div ref={videoRef} className='w-full h-full' />
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default Player;
|
||||
@@ -1,8 +1,77 @@
|
||||
import { create } from 'react-modal-promise';
|
||||
import dynamic from 'next/dynamic';
|
||||
'use client';
|
||||
|
||||
const Player = dynamic(() => import('./Player'), { ssr: false });
|
||||
import { useState } from 'react';
|
||||
import { create, InstanceProps } from 'react-modal-promise';
|
||||
import { Loader } from 'lucide-react';
|
||||
import { BigPlayButton, ClosedCaptionButton, ControlBar, Player } from 'video-react';
|
||||
|
||||
const showPlayer = create(Player);
|
||||
import { Modal } from '@/components/ui/dialog';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
import showFiles from './components/Files';
|
||||
import useFiles from './useFiles';
|
||||
|
||||
interface Props extends InstanceProps<void> {
|
||||
magnet: string;
|
||||
}
|
||||
|
||||
const showPlayer = create(({ onResolve, magnet }: Props) => {
|
||||
const [source, setSource] = useState<string | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
const { data, isFetched } = useFiles({
|
||||
magnet,
|
||||
onSuccess(files) {
|
||||
if (!files.length) {
|
||||
toast({ title: 'This torrent doesn\'t contain any compatible video files' });
|
||||
return onResolve();
|
||||
}
|
||||
|
||||
if (files.length === 1) {
|
||||
const [file] = files;
|
||||
|
||||
return setSource(file.src);
|
||||
}
|
||||
|
||||
showFiles({ files }).then((file) => setSource(file.src));
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Modal
|
||||
className='p-0 border-none rounded-lg overflow-hidden flex items-center justify-center relative'
|
||||
style={{ aspectRatio: '16/9' }}
|
||||
onClose={onResolve}
|
||||
>
|
||||
<Player autoPlay aspectRatio='16:9'>
|
||||
{!isFetched && (
|
||||
<>
|
||||
<div className='w-full h-full left-0 top-0 absolute flex items-center justify-center'>
|
||||
<div className='animate-spin'>
|
||||
<Loader color='white' />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{source && <source src={source} />}
|
||||
{isFetched &&
|
||||
data?.map((file) =>
|
||||
file.subtitles.map(({ name, content }) => (
|
||||
<track
|
||||
key={name}
|
||||
kind='captions'
|
||||
src={URL.createObjectURL(new Blob([content], { type: 'text/vtt' }))}
|
||||
label={name}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
<ControlBar autoHide={false}>
|
||||
<ClosedCaptionButton order={7} />
|
||||
</ControlBar>
|
||||
<BigPlayButton position='center' />
|
||||
</Player>
|
||||
</Modal>
|
||||
);
|
||||
});
|
||||
|
||||
export default showPlayer;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { torrentFiles } from '@/api';
|
||||
|
||||
interface Props {
|
||||
magnet: string;
|
||||
onSuccess: (files: Source[]) => void;
|
||||
}
|
||||
|
||||
const useFiles = ({ magnet, onSuccess }: Props) =>
|
||||
useQuery({
|
||||
queryKey: [magnet],
|
||||
queryFn: () =>
|
||||
torrentFiles(magnet).then((files) => {
|
||||
onSuccess(files);
|
||||
return files;
|
||||
})
|
||||
});
|
||||
|
||||
export default useFiles;
|
||||
@@ -95,19 +95,25 @@ const showTorrentsModal = create(({ title, year, showType, showId, onResolve }:
|
||||
</TableRow>
|
||||
)}
|
||||
<TableRow>
|
||||
{!isMobile && <TableCell className='break-all p-2'>{torrent.title}</TableCell>}
|
||||
{!isMobile && (
|
||||
<TableCell className='break-all p-2'>
|
||||
{torrent.title} {torrent.type && `[${torrent.type?.toUpperCase()}]`}
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell className='p-2'>
|
||||
<div className='flex items-center gap-1 shrink-0'>{torrent.size}</div>
|
||||
</TableCell>
|
||||
<TableCell className='p-2'>{torrent.seeders}</TableCell>
|
||||
<TableCell className='text-center p-1 pr-2'>
|
||||
<div className='flex gap-2 justify-end'>
|
||||
{Boolean(key === providers.yts.key && torrent.seeders) && (
|
||||
<div
|
||||
className='flex items-center justify-center h-8 w-8 border rounded-lg cursor-pointer'
|
||||
onClick={() => showPlayer({ magnet: torrent.magnet })}
|
||||
>
|
||||
<Play size={20} />
|
||||
</div>
|
||||
)}
|
||||
<a href={torrent.magnet} className='flex items-center justify-center h-8 w-8 border rounded-lg'>
|
||||
<Magnet size={20} />
|
||||
</a>
|
||||
|
||||
@@ -175,7 +175,7 @@ const Modal: React.FC<{
|
||||
</DialogHeader>
|
||||
<DialogContent style={style} scrollRef={scrollRef} forceMount onClose={handleClose} className={className}>
|
||||
{children}
|
||||
<DialogDescription />
|
||||
<DialogDescription className='hidden' />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
Vendored
-5
@@ -1,5 +0,0 @@
|
||||
declare module 'webtorrent/dist/webtorrent.min.js' {
|
||||
import WebTorrent = require('webtorrent');
|
||||
|
||||
export = WebTorrent;
|
||||
}
|
||||
Generated
+1547
-3609
File diff suppressed because it is too large.
Load diff
+4
-3
@@ -15,6 +15,7 @@
|
||||
"@radix-ui/react-separator": "^1.0.3",
|
||||
"@radix-ui/react-slot": "^1.0.2",
|
||||
"@radix-ui/react-tabs": "^1.0.4",
|
||||
"@radix-ui/react-toast": "^1.2.2",
|
||||
"@radix-ui/react-toggle": "^1.0.3",
|
||||
"@tanstack/react-query": "^5.17.3",
|
||||
"axios": "^1.4.0",
|
||||
@@ -37,15 +38,15 @@
|
||||
"tailwindcss-animate": "^1.0.6",
|
||||
"typescript": "5.1.6",
|
||||
"vaul": "^0.8.9",
|
||||
"video.js": "^8.17.4",
|
||||
"webtorrent": "^2.5.1"
|
||||
"video-react": "^0.16.0",
|
||||
"video.js": "^8.17.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/js-cookie": "^3.0.3",
|
||||
"@types/node": "20.4.4",
|
||||
"@types/react": "18.2.15",
|
||||
"@types/react-dom": "18.2.7",
|
||||
"@types/webtorrent": "^0.109.8",
|
||||
"@types/video-react": "^0.15.8",
|
||||
"autoprefixer": "^10.4.14",
|
||||
"eslint-plugin-simple-import-sort": "^10.0.0",
|
||||
"postcss": "^8.4.27",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { FC, ReactNode, useState } from 'react';
|
||||
import ModalContainer from 'react-modal-promise';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
|
||||
import { Toaster } from '@/components/ui/toaster';
|
||||
import { queryClientOptions } from '@/lib/queryClient';
|
||||
|
||||
import ThemeProvider from './Theme';
|
||||
@@ -20,6 +21,7 @@ const Providers: FC<Props> = ({ children, theme }) => {
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider theme={theme}>{children}</ThemeProvider>
|
||||
<ModalContainer exitTimeout={500} enterTimeout={0} />
|
||||
<Toaster />
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
Vendored
-2
@@ -1,2 +0,0 @@
|
||||
(()=>{"use strict";let e=!1;self.addEventListener("install",(()=>{self.skipWaiting()})),self.addEventListener("fetch",(s=>{const t=(s=>{const{url:t}=s.request;return t.includes(self.registration.scope+"webtorrent/")?t.includes(self.registration.scope+"webtorrent/keepalive/")?new Response:t.includes(self.registration.scope+"webtorrent/cancel/")?new Response(new ReadableStream({cancel(){e=!0}})):async function({request:s}){const{url:t,method:n,headers:o,destination:a}=s,l=await clients.matchAll({type:"window",includeUncontrolled:!0}),[r,i]=await new Promise((e=>{for(const s of l){const l=new MessageChannel,{port1:r,port2:i}=l;r.onmessage=({data:s})=>{e([s,r])},s.postMessage({url:t,method:n,headers:Object.fromEntries(o.entries()),scope:self.registration.scope,destination:a,type:"webtorrent"},[i])}}));let c=null;const d=()=>{i.postMessage(!1),clearTimeout(c),i.onmessage=null};return"STREAM"!==r.body?(d(),new Response(r.body,r)):new Response(new ReadableStream({pull:s=>new Promise((t=>{i.onmessage=({data:e})=>{e?s.enqueue(e):(d(),s.close()),t()},e||(clearTimeout(c),"document"!==a&&(c=setTimeout((()=>{d(),t()}),5e3))),i.postMessage(!0)})),cancel(){d()}}),r)}(s):null})(s);t&&s.respondWith(t)})),self.addEventListener("activate",(()=>{self.clients.claim()}))})();
|
||||
//# sourceMappingURL=sw.min.js.map
|
||||
@@ -2,6 +2,8 @@
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@import url('video-react/dist/video-react.css');
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
|
||||
Vendored
+15
@@ -119,6 +119,21 @@ interface Torrent {
|
||||
seeders: number;
|
||||
size: string;
|
||||
magnet: string;
|
||||
type: 'web' | 'bluray';
|
||||
}
|
||||
|
||||
interface Source {
|
||||
name: string;
|
||||
src: string;
|
||||
}
|
||||
|
||||
interface Subtitles {
|
||||
name: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface Video extends Source {
|
||||
subtitles: Subtitles[];
|
||||
}
|
||||
|
||||
interface ExternalIDS {
|
||||
|
||||
Reference in new issue
Block a user