feat: added torrents list

This commit is contained in:
ner committed 2023-08-11 15:23:01 +03:00
1 parent 5d7a3464ed
commit dd7339b62c
11 files changed
+2303 -5

No files matched your search

+16
View File
@@ -29,6 +29,22 @@ const API = {
'release_date.lte': filters.year?.[1] 'release_date.lte': filters.year?.[1]
} }
}); });
},
torrents: {
tracker({ query }: { query: string }): Promise<Torrent[]> {
return client.get('/torrents/tracker', {
params: {
query
}
});
},
pirateBay({ query }: { query: string }): Promise<Torrent[]> {
return client.get('/torrents/pirate-bay', {
params: {
query
}
});
}
} }
}; };
+29
View File
@@ -0,0 +1,29 @@
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import API from './api';
const useTorrents = ({ query }: { query: string }) => {
const { data: trackersTorrents, ...tracker } = useQuery({
enabled: Boolean(query),
queryKey: ['tracker', query],
queryFn: () => API.torrents.tracker({ query })
});
const { data: piratesTorrents, ...pirateBay } = useQuery({
enabled: Boolean(query),
queryKey: ['pirate-bay', query],
queryFn: () => API.torrents.pirateBay({ query })
});
return {
torrents: useMemo(
() => [...(trackersTorrents || []), ...(piratesTorrents || [])],
[trackersTorrents, piratesTorrents]
),
isLoading: tracker.isLoading || pirateBay.isLoading,
isFetched: tracker.isFetched && pirateBay.isFetched
};
};
export default useTorrents;
+24
View File
@@ -0,0 +1,24 @@
import { NextResponse } from 'next/server';
import PirateBay from 'thepiratebayfixed';
export async function GET(request: Request) {
const params = Object.fromEntries(new URL(request.url).searchParams.entries());
try {
const results: PirateTorrent[] = await PirateBay.search(params.query, {
category: 'video'
});
return NextResponse.json(
results?.map(({ seeders, name, id, magnetLink, size }) => ({
id,
title: name,
magnetLink,
size,
seeders: parseInt(seeders)
})) || []
);
} catch (error) {
return NextResponse.json([]);
}
}
+35
View File
@@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import Tracker from 'rutracker-api-with-proxy';
const tracker = new Tracker();
const api = tracker.login({ username: process.env.TRACKER_LOGIN, password: process.env.TRACKER_PASSWORD });
export async function GET(request: Request) {
const params = Object.fromEntries(new URL(request.url).searchParams.entries());
try {
await api;
const results: TrackerTorrent[] = await tracker.search({ query: params.query });
const movies = results.filter((torrent) => torrent.category.includes('кино'));
const links = ((await Promise.all(movies?.map(({ id }) => tracker.getMagnetLink(id)))) || []) as string[];
const torrents =
movies?.map(
({ seeds, title, id, size }, index) =>
({
seeders: seeds,
title,
id,
magnetLink: links[index],
size: `${(size / (1024 * 1024 * 1024)).toFixed(2)} GiB`
}) as Torrent
) || [];
return NextResponse.json(torrents);
} catch (error) {
return NextResponse.json([]);
}
}
+7
View File
@@ -6,7 +6,9 @@ import Credits from '@/components/Movie/components/Credits';
import Poster from '@/components/Movie/components/Poster'; import Poster from '@/components/Movie/components/Poster';
import Rating from '@/components/Movie/components/Rating'; import Rating from '@/components/Movie/components/Rating';
import Title from '@/components/Movie/components/Title'; import Title from '@/components/Movie/components/Title';
import Torrents from '@/components/Movie/components/Torrents';
import Trailer from '@/components/Movie/components/Trailer'; import Trailer from '@/components/Movie/components/Trailer';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator'; import { Separator } from '@/components/ui/separator';
interface Props { interface Props {
@@ -18,6 +20,7 @@ interface Props {
const Preview: FC<Props> = ({ movie, className, onPersonClick }) => { const Preview: FC<Props> = ({ movie, className, onPersonClick }) => {
const [isShowTrailer, setIsShowTrailer] = useState(false); const [isShowTrailer, setIsShowTrailer] = useState(false);
const { data: trailer } = useTrailer({ movieId: movie?.id }); const { data: trailer } = useTrailer({ movieId: movie?.id });
const [isShowTorrents, setIsShowTorrents] = useState(false);
if (!movie) return null; if (!movie) return null;
@@ -59,11 +62,15 @@ const Preview: FC<Props> = ({ movie, className, onPersonClick }) => {
<div className='flex flex-col items-start grow justify-between'> <div className='flex flex-col items-start grow justify-between'>
<p className='leading-7'>{movie.overview}</p> <p className='leading-7'>{movie.overview}</p>
</div> </div>
<Button size='sm' className='h-8 mt-2' onClick={() => setIsShowTorrents(true)}>
Torrents
</Button>
</div> </div>
</div> </div>
<Credits movieId={movie.id} onPersonClick={onPersonClick} /> <Credits movieId={movie.id} onPersonClick={onPersonClick} />
</div> </div>
{isShowTrailer && <Trailer trailerKey={trailer?.key} onClose={() => setIsShowTrailer(false)} />} {isShowTrailer && <Trailer trailerKey={trailer?.key} onClose={() => setIsShowTrailer(false)} />}
{isShowTorrents && <Torrents title={movie.title} onClose={() => setIsShowTorrents(false)} />}
</> </>
); );
}; };
@@ -0,0 +1,130 @@
import { Dispatch, FC, SetStateAction, useMemo, useState } from 'react';
import { ArrowDownIcon, ArrowUpIcon, CaretSortIcon } from '@radix-ui/react-icons';
import { Loader, Magnet } from 'lucide-react';
import useTorrents from '@/app/(site)/useTorrents';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
interface Props {
title: string;
onClose: () => void;
}
type Sorting = {
by: 'seeders' | 'size';
direction: 'asc' | 'desc';
};
function convertToBytes(size: string) {
const units: Record<string, number> = { B: 1, KiB: 1024, MiB: 1024 * 1024, GiB: 1024 * 1024 * 1024 };
const [value, unit] = size.split(' ');
return parseFloat(value) * units[unit];
}
function compareSizes(size1: string, size2: string) {
return convertToBytes(size1) - convertToBytes(size2);
}
const TableHeadSortable = ({
title,
by,
onChange,
value
}: {
title: string;
by: Sorting['by'];
value: Sorting;
onChange: Dispatch<SetStateAction<Sorting>>;
}) => {
return (
<TableHead
onClick={() =>
onChange((sorting) => ({
...sorting,
by,
direction: sorting.by !== by ? 'desc' : sorting.direction === 'asc' ? 'desc' : 'asc'
}))
}
className='cursor-pointer select-none'
>
<div className='flex gap-1 items-center'>
<span>{title}</span>
{value.by === by &&
(value.direction === 'desc' ? (
<ArrowDownIcon className='ml-2 h-4 w-4' />
) : (
<ArrowUpIcon className='ml-2 h-4 w-4' />
))}
{value.by !== by && <CaretSortIcon className='ml-2 h-4 w-4' />}
</div>
</TableHead>
);
};
const Torrents: FC<Props> = ({ title, onClose }) => {
const { torrents, isLoading, isFetched } = useTorrents({ query: title });
const [sorting, setSorting] = useState<Sorting>({ by: 'seeders', direction: 'desc' });
const sortedTorrents = useMemo(() => {
return [...torrents].sort((a, b) => {
if (sorting.by === 'size')
return sorting.direction === 'asc' ? compareSizes(a.size, b.size) : compareSizes(b.size, a.size);
return sorting.direction === 'asc' ? a.seeders - b.seeders : b.seeders - a.seeders;
});
}, [torrents, sorting]);
return (
<Dialog defaultOpen={true} onOpenChange={(isOpen) => !isOpen && onClose()}>
<DialogContent className='p-0'>
<Table>
<TableHeader>
<TableRow>
<TableHead>Title</TableHead>
<TableHeadSortable title='Size' by='size' value={sorting} onChange={setSorting} />
<TableHeadSortable title='Seeders' by='seeders' value={sorting} onChange={setSorting} />
<TableHead>Magnet</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedTorrents.map((torrent) => (
<TableRow key={torrent.id}>
<TableCell>{torrent.title}</TableCell>
<TableCell>
<div className='flex items-center gap-1 shrink-0'>{torrent.size}</div>
</TableCell>
<TableCell className='text-center'>{torrent.seeders}</TableCell>
<TableCell className='text-center'>
<a href={torrent.magnetLink} className='flex items-center justify-center h-8 w-8 border rounded-lg'>
<Magnet size={20} />
</a>
</TableCell>
</TableRow>
))}
{isLoading && (
<TableRow>
<TableCell colSpan={4}>
<div className='h-40 w-full flex items-center justify-center'>
<Loader className='animate-spin' />
</div>
</TableCell>
</TableRow>
)}
{isFetched && !torrents.length && (
<TableRow>
<TableCell colSpan={4}>
<div className='h-40 w-full flex items-center justify-center text-xl text-muted-foreground'>
Nothing was found
</div>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</DialogContent>
</Dialog>
);
};
export default Torrents;
+72
View File
@@ -0,0 +1,72 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className='w-full overflow-auto'>
<table ref={ref} className={cn('w-full caption-bottom text-sm', className)} {...props} />
</div>
)
);
Table.displayName = 'Table';
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => <thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />
);
TableHeader.displayName = 'TableHeader';
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} />
)
);
TableBody.displayName = 'TableBody';
const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tfoot ref={ref} className={cn('bg-primary font-medium text-primary-foreground', className)} {...props} />
)
);
TableFooter.displayName = 'TableFooter';
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn('border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted', className)}
{...props}
/>
)
);
TableRow.displayName = 'TableRow';
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
'h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0',
className
)}
{...props}
/>
)
);
TableHead.displayName = 'TableHead';
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<td ref={ref} className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)} {...props} />
)
);
TableCell.displayName = 'TableCell';
const TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(
({ className, ...props }, ref) => (
<caption ref={ref} className={cn('mt-4 text-sm text-muted-foreground', className)} {...props} />
)
);
TableCaption.displayName = 'TableCaption';
export { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow };
+11
View File
@@ -7,6 +7,17 @@ const nextConfig = {
hostname: '**' hostname: '**'
} }
] ]
},
future: {
webpack5: true
},
webpack(config) {
config.resolve.fallback = {
...config.resolve.fallback,
encoding: false
};
return config;
} }
}; };
+1930 -5
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -11,6 +11,7 @@
"dependencies": { "dependencies": {
"@radix-ui/react-dialog": "^1.0.4", "@radix-ui/react-dialog": "^1.0.4",
"@radix-ui/react-dropdown-menu": "^2.0.5", "@radix-ui/react-dropdown-menu": "^2.0.5",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.0.2", "@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-menubar": "^1.0.3", "@radix-ui/react-menubar": "^1.0.3",
"@radix-ui/react-popover": "^1.0.6", "@radix-ui/react-popover": "^1.0.6",
@@ -40,8 +41,10 @@
"react": "18.2.0", "react": "18.2.0",
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-fast-marquee": "^1.6.0", "react-fast-marquee": "^1.6.0",
"rutracker-api-with-proxy": "^2.0.6",
"tailwind-merge": "^1.14.0", "tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.6", "tailwindcss-animate": "^1.0.6",
"thepiratebayfixed": "^1.5.0",
"typescript": "5.1.6", "typescript": "5.1.6",
"webtorrent": "^2.1.21" "webtorrent": "^2.1.21"
}, },
Vendored
+46
View File
@@ -73,3 +73,49 @@ interface IDName<T = number> {
id: T; id: T;
name: string; name: string;
} }
interface TrackerTorrent {
author: string;
category: string;
id: string;
leeches: number;
seeds: number;
size: number;
state: string;
title: string;
downloads: number;
registered: Date;
host: string;
}
interface PirateTorrent {
id: string;
name: string;
size: string;
link: string;
category: Category;
seeders: string;
leechers: string;
uploadDate: Date;
magnetLink: string;
subcategory: Category;
uploader: string;
verified: boolean;
uploaderLink: string;
}
interface Torrent {
id: string;
title: string;
seeders: number;
size: string;
magnetLink: string;
}
interface Category {
id: string;
name: string;
}
declare module 'rutracker-api-with-proxy';
declare module 'thepiratebayfixed';