feat: fetch toloka's magnets

This commit is contained in:
ner committed 2024-10-27 12:13:02 +02:00
1 parent 3792e3face
commit 8691c7d66d
4 files changed
+49 -36

No files matched your search

+17 -7
View File
@@ -2,7 +2,7 @@ import axios, { AxiosInstance } from 'axios';
import torrentTitle from 'parse-torrent-title'; import torrentTitle from 'parse-torrent-title';
import { load } from 'cheerio'; import { load } from 'cheerio';
import parseTorrent from 'parse-torrent'; import parseTorrent, { Instance } from 'parse-torrent';
import { CookieJar } from 'tough-cookie'; import { CookieJar } from 'tough-cookie';
import { wrapper } from 'axios-cookiejar-support'; import { wrapper } from 'axios-cookiejar-support';
@@ -65,8 +65,6 @@ export class Toloka {
const seeders = $(row).find('td:nth-child(10)').text(); const seeders = $(row).find('td:nth-child(10)').text();
const download = $(row).find('td:nth-child(6) a').attr('href'); const download = $(row).find('td:nth-child(6) a').attr('href');
const sid = this.cookieJar.toJSON()?.cookies.find(({ key }) => key === 'toloka_sid')?.value;
const { year, source, codec, container, title, season, episode, resolution } = torrentTitle.parse( const { year, source, codec, container, title, season, episode, resolution } = torrentTitle.parse(
originalTitle || '' originalTitle || ''
); );
@@ -103,11 +101,23 @@ export class Toloka {
async magnet(url: string) { async magnet(url: string) {
if (this.magnets[url]) return this.magnets[url]; if (this.magnets[url]) return this.magnets[url];
const { data: buffer } = await this.client.get(`/${url}`, { const fetchTorrent = async () => {
responseType: 'arraybuffer' const { data: buffer } = await this.client.get(`/${url}`, {
}); responseType: 'arraybuffer'
});
const torrent = await parseTorrent(buffer); return parseTorrent(buffer);
};
let torrent: Instance;
try {
torrent = (await fetchTorrent()) as Instance;
} catch (_) {
await this.auth();
torrent = (await fetchTorrent()) as Instance;
}
const magnet = `magnet:?xt=urn:btih:${torrent.infoHash}&dn=${encodeURIComponent(torrent.name?.toString() || '')}`; const magnet = `magnet:?xt=urn:btih:${torrent.infoHash}&dn=${encodeURIComponent(torrent.name?.toString() || '')}`;
+2 -3
View File
@@ -7,8 +7,7 @@ export async function GET({ nextUrl: { searchParams } }: NextRequest) {
try { try {
return NextResponse.json(await tlk.magnet(url)); return NextResponse.json(await tlk.magnet(url));
} catch (_) { } catch (error) {
console.log('error', _); return NextResponse.error();
return NextResponse.json([]);
} }
} }
@@ -1,10 +1,9 @@
import { FC } from 'react'; import { FC } from 'react';
import { Cast, ListVideo, Magnet, Play } from 'lucide-react'; import { Cast, ChevronLeft,ListVideo, Magnet, Play } from 'lucide-react';
import { Quality } from '@/api/parsers/yts/models'; import { Quality } from '@/api/parsers/yts/models';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import ButtonsGroup from '@/components/ui/buttons-group'; import ButtonsGroup from '@/components/ui/buttons-group';
import { toast, useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { providers } from '../../../../constants'; import { providers } from '../../../../constants';
@@ -24,8 +23,6 @@ const Actions: FC<Props> = ({ torrent, backdrop, title, provider }) => {
const prefix = usePrefix(); const prefix = usePrefix();
const cast = useCastMagnet(); const cast = useCastMagnet();
const { toast } = useToast();
const supportedForStream = Boolean( const supportedForStream = Boolean(
(provider === providers.yts.key && (provider === providers.yts.key &&
torrent.seeders && torrent.seeders &&
@@ -33,49 +30,46 @@ const Actions: FC<Props> = ({ torrent, backdrop, title, provider }) => {
torrent.container?.includes('mp4') torrent.container?.includes('mp4')
); );
const magnet = useMagnet(torrent); const fetchMagnet = useMagnet(torrent);
const magnet = fetchMagnet.data || torrent.magnet;
const supportedForCast = prefix && !prefix.includes('{host}'); const supportedForCast = prefix && !prefix.includes('{host}');
if (!magnet)
return (
<ButtonsGroup className='ml-auto justify-end bg-transparent'>
<Button className='grow-0 px-2' disabled={fetchMagnet.isPending} onClick={() => fetchMagnet.mutate()}>
<ChevronLeft size={15} />
</Button>
</ButtonsGroup>
);
return ( return (
<ButtonsGroup className='ml-auto w-fit grow-0'> <ButtonsGroup className='ml-auto w-fit grow-0'>
{supportedForStream && ( {supportedForStream && (
<Button <Button
variant='destructive' variant='destructive'
className={cn('flex-grow-0 px-3 bg-red-600')} className={cn('flex-grow-0 px-3 bg-red-600')}
onClick={() => showPlayer({ magnet: torrent.download || torrent.magnet, backdrop, title })} onClick={() => showPlayer({ magnet, backdrop, title })}
title='Play' title='Play'
> >
<Play size={15} /> <Play size={15} />
</Button> </Button>
)} )}
<Button
variant='outline'
className='relative grow-0 px-3'
disabled={magnet.isPending}
onClick={() => magnet.mutateAsync().then((magnet) => toast({ description: magnet }))}
>
Get magnet
</Button>
<Button variant='outline' className='relative grow-0 px-3' title='Play using your native video player'> <Button variant='outline' className='relative grow-0 px-3' title='Play using your native video player'>
<a <a
className='absolute left-0 top-0 size-full' className='absolute left-0 top-0 size-full'
href={`${process.env.NEXT_PUBLIC_TORRENT_PROXY}/stream?m3u&link=${encodeURIComponent( href={`${process.env.NEXT_PUBLIC_TORRENT_PROXY}/stream?m3u&link=${encodeURIComponent(magnet)}`}
torrent.download || torrent.magnet
)}`}
/> />
<ListVideo size={20} /> <ListVideo size={20} />
</Button> </Button>
<Button <Button className='relative grow-0 px-3' variant='outline' title='Download magnet'>
className='relative grow-0 px-3' <a className='absolute left-0 top-0 size-full' href={magnet} />
variant='outline'
title={`Download ${torrent.download ? 'torrent' : 'magnet'}`}
>
<a className='absolute left-0 top-0 size-full' href={torrent.download || torrent.magnet} />
<Magnet size={20} /> <Magnet size={20} />
</Button> </Button>
{supportedForCast && ( {supportedForCast && (
<Button className='grow-0 px-3' variant='outline' onClick={() => cast(torrent.download || torrent.magnet)}> <Button className='grow-0 px-3' variant='outline' onClick={() => cast(magnet)}>
<Cast size={20} /> <Cast size={20} />
</Button> </Button>
)} )}
@@ -2,8 +2,18 @@ import { useMutation } from '@tanstack/react-query';
const useMagnet = (torrent: Torrent) => { const useMagnet = (torrent: Torrent) => {
return useMutation({ return useMutation({
mutationFn: async () => retry: 4,
torrent.magnet ? torrent.magnet : fetch(`/api/magnet?url=${torrent.download}`).then((response) => response.json()) mutationFn: async () => {
try {
const response = await fetch(`/api/magnet?url=${torrent.download}`);
if (!response.ok) return Promise.reject();
return response.json();
} catch (error) {
return Promise.reject(error);
}
}
}); });
}; };