feat: added torrents and similar for every movie

This commit is contained in:
ner committed 2023-08-18 12:36:10 +03:00
1 parent ada725072f
commit 8bff4d6d80
16 files changed
+91 -117

No files matched your search

+5 -9
View File
@@ -1,6 +1,8 @@
import { Filters } from '@/app/(site)/useFilters'; import { Filters } from '@/app/(site)/useFilters';
import client from '@/network'; import client from '@/network';
import { ORDER } from '../api/torrents/parsers/pirate-bay';
const API = { const API = {
genres(): Promise<IDName[]> { genres(): Promise<IDName[]> {
return client.get('/genres'); return client.get('/genres');
@@ -31,17 +33,11 @@ const API = {
}); });
}, },
torrents: { torrents: {
tracker({ query }: { query: string }): Promise<Torrent[]> { pirateBay({ query, order = ORDER.seeders }: { query: string; order?: ORDER }): Promise<Torrent[]> {
return client.get('/torrents/tracker', {
params: {
query
}
});
},
pirateBay({ query }: { query: string }): Promise<Torrent[]> {
return client.get('/torrents/pirate-bay', { return client.get('/torrents/pirate-bay', {
params: { params: {
query query,
order
} }
}); });
} }
+4 -3
View File
@@ -14,10 +14,11 @@ const API = {
} }
}); });
}, },
person({ id }: { id: string }): Promise<Person> { similar({ page, movieId }: { page: string; movieId: string }): Promise<MovieDBResponse> {
return client.get('/person', { return client.get('/discover/similar', {
params: { params: {
id page,
movieId
} }
}); });
} }
+14 -6
View File
@@ -2,24 +2,32 @@
import { useSearchParams } from 'next/navigation'; import { useSearchParams } from 'next/navigation';
import usePerson from '@/app/(site)/top/usePerson';
import List from '@/components/Movie/List'; import List from '@/components/Movie/List';
import useTop from './useTop'; import useTop from './useTop';
export default function Container() { export default function Container() {
const starring = useSearchParams().get('starring'); const params = useSearchParams();
const { data: person } = usePerson({ id: starring });
const { data: top, hasNextPage, fetchNextPage } = useTop({ starring }); const starring = params.get('starring');
const similar = params.get('similar');
const title = params.get('title');
const { data: top, hasNextPage, fetchNextPage, isFetched, isFetching } = useTop({ starring, similar });
return ( return (
<> <>
{Boolean(person) && ( {Boolean(title && (starring || similar)) && (
<span className='inline-flex w-full h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground mb-2'> <span className='inline-flex w-full h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground mb-2'>
Starring: {person?.name} {starring ? 'Starring' : 'Similar'}: {decodeURIComponent(title || '')}
</span> </span>
)} )}
<List pages={top?.pages || []} fetchNextPage={fetchNextPage} hasNextPage={hasNextPage} /> <List pages={top?.pages || []} fetchNextPage={fetchNextPage} hasNextPage={hasNextPage} />
{isFetched && !top?.pages?.[0]?.results?.length && (
<div className='h-40 w-full flex items-center justify-center text-xl text-muted-foreground'>
Nothing was found
</div>
)}
</> </>
); );
} }
-9
View File
@@ -1,9 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import API from './api';
const usePerson = ({ id }: { id: string | null }) => {
return useQuery({ enabled: Boolean(id), queryKey: ['person', id], queryFn: () => API.person({ id: id! }) });
};
export default usePerson;
+4 -15
View File
@@ -1,31 +1,20 @@
'use client'; 'use client';
import { useInfiniteQuery } from '@tanstack/react-query'; import { useInfiniteQuery } from '@tanstack/react-query';
import { useSearchParams } from 'next/navigation';
import API from './api'; import API from './api';
const useTop = ({ starring }: { starring: string | null }) => { const useTop = ({ starring, similar }: { starring: string | null; similar: string | null }) => {
const page = useSearchParams().get('page');
return useInfiniteQuery({ return useInfiniteQuery({
queryKey: ['top', starring], queryKey: ['top', starring, similar],
queryFn: ({ pageParam: page }) => API.top({ page, starring }), queryFn: ({ pageParam: page }) => (similar ? API.similar({ page, movieId: similar }) : API.top({ page, starring })),
suspense: true, suspense: true,
getNextPageParam({ page, total_pages }) { getNextPageParam({ page, total_pages }) {
if (page === total_pages) return undefined; if (page === total_pages) return undefined;
if (typeof window !== 'undefined') {
const url = new URL(location.href);
url.searchParams.set('page', page.toString());
window.history.pushState(null, '', url.href);
}
return `${page + 1}`; return `${page + 1}`;
}, },
defaultPageParam: page || '1' defaultPageParam: '1'
}); });
}; };
+6 -20
View File
@@ -1,29 +1,15 @@
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { ORDER } from '../api/torrents/parsers/pirate-bay';
import API from './api'; import API from './api';
const useTorrents = ({ query }: { query: string }) => { const useTorrents = ({ query, order }: { query: string; order: ORDER }) => {
const { data: trackersTorrents, ...tracker } = useQuery({ return useQuery({
enabled: Boolean(query), enabled: Boolean(query),
queryKey: ['tracker', query], queryKey: ['pirate-bay', query, order],
queryFn: () => API.torrents.tracker({ query }) queryFn: () => API.torrents.pirateBay({ query, order })
}); });
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; export default useTorrents;
@@ -4,9 +4,11 @@ import server from '@/network/server';
export async function GET(request: Request) { export async function GET(request: Request) {
const params = Object.fromEntries(new URL(request.url).searchParams.entries()); const params = Object.fromEntries(new URL(request.url).searchParams.entries());
const response = await server.get(`/person/${params.id}`); const response = await server.get(`/movie/${params.movieId}/similar`, {
params
});
return NextResponse.json(response); return NextResponse.json(response);
} }
export const revalidate = 3600 * 24; export const revalidate = 0;
+1 -1
View File
@@ -1,7 +1,7 @@
import axios, { AxiosInstance } from 'axios'; import axios, { AxiosInstance } from 'axios';
import { parse } from 'node-html-parser'; import { parse } from 'node-html-parser';
enum ORDER { export enum ORDER {
size = 5, size = 5,
seeders = 7 seeders = 7
} }
+5 -2
View File
@@ -1,12 +1,15 @@
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import pirateBay from '../parsers/pirate-bay'; import pirateBay, { ORDER } from '../parsers/pirate-bay';
export async function GET(request: Request) { export async function GET(request: Request) {
const params = Object.fromEntries(new URL(request.url).searchParams.entries()); const params = Object.fromEntries(new URL(request.url).searchParams.entries());
try { try {
const torrents = await pirateBay.search({ query: params.query }); const torrents = await pirateBay.search({
query: params.query,
order: parseInt(params.order || `${ORDER.seeders}`)
});
return NextResponse.json(torrents); return NextResponse.json(torrents);
} catch (error) { } catch (error) {
return NextResponse.json([]); return NextResponse.json([]);
+1 -1
View File
@@ -61,7 +61,7 @@ const List: FC<Props> = ({ pages, hasNextPage, fetchNextPage }) => {
key={movie.id} key={movie.id}
movie={movie} movie={movie}
className='border-none' className='border-none'
onPersonClick={() => { onClose={() => {
setMovie(null); setMovie(null);
window.scrollTo({ top: 0, behavior: 'smooth' }); window.scrollTo({ top: 0, behavior: 'smooth' });
}} }}
+25 -3
View File
@@ -1,5 +1,6 @@
import { FC, useState } from 'react'; import { FC, useState } from 'react';
import { Play } from 'lucide-react'; import { Play } from 'lucide-react';
import { useRouter } from 'next/navigation';
import useTrailer from '@/app/(site)/useTrailer'; import useTrailer from '@/app/(site)/useTrailer';
import Credits from '@/components/Movie/components/Credits'; import Credits from '@/components/Movie/components/Credits';
@@ -9,15 +10,21 @@ import Title from '@/components/Movie/components/Title';
import Trailer from '@/components/Movie/components/Trailer'; import Trailer from '@/components/Movie/components/Trailer';
import { Separator } from '@/components/ui/separator'; import { Separator } from '@/components/ui/separator';
import { Button } from '../ui/button';
import Torrents from './components/Torrents';
interface Props { interface Props {
movie?: Movie; movie?: Movie;
className?: string; className?: string;
onPersonClick?: (id: string) => void; onClose?: () => void;
} }
const Preview: FC<Props> = ({ movie, className, onPersonClick }) => { const Preview: FC<Props> = ({ movie, className, onClose }) => {
const [isShowTrailer, setIsShowTrailer] = useState(false); const [isShowTrailer, setIsShowTrailer] = useState(false);
const [isShowTorrents, setIsShowTorrents] = useState(false);
const { data: trailer } = useTrailer({ movieId: movie?.id }); const { data: trailer } = useTrailer({ movieId: movie?.id });
const router = useRouter();
if (!movie) return null; if (!movie) return null;
@@ -59,11 +66,26 @@ 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>
<div className='flex w-full mt-2 gap-2'>
<Button className='h-8 grow' onClick={() => setIsShowTorrents(true)}>
Torrents
</Button>
<Button
className='h-8 grow'
onClick={() => {
router.push(`/top?similar=${movie.id}&title=${encodeURIComponent(movie.title)}`);
onClose?.();
}}
>
Similar
</Button>
</div>
</div> </div>
</div> </div>
<Credits movieId={movie.id} onPersonClick={onPersonClick} /> <Credits movieId={movie.id} onPersonClick={() => onClose?.()} />
</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)} />}
</> </>
); );
}; };
@@ -23,7 +23,7 @@ const Credits: FC<Props> = ({ movieId, onPersonClick }) => {
key={`${actor.id}_${actor.cast_id}`} key={`${actor.id}_${actor.cast_id}`}
title={actor.name} title={actor.name}
onClick={() => { onClick={() => {
router.push(`/top?starring=${actor.id}`); router.push(`/top?starring=${actor.id}&title=${encodeURIComponent(actor.name)}`);
onPersonClick?.(actor.id.toString()); onPersonClick?.(actor.id.toString());
}} }}
className='p-2 rounded-lg border bg-card text-card-foreground self-end max-w-[150px] w-full shrink-0 cursor-pointer transition-shadow hover:shadow-lg' className='p-2 rounded-lg border bg-card text-card-foreground self-end max-w-[150px] w-full shrink-0 cursor-pointer transition-shadow hover:shadow-lg'
+4 -1
View File
@@ -14,7 +14,10 @@ interface Props {
const Poster: FC<Props> = ({ title, poster, width, height, size = 250, className, children }) => { const Poster: FC<Props> = ({ title, poster, width, height, size = 250, className, children }) => {
return ( return (
<div className={`w-full flex flex-col rounded-lg overflow-hidden shrink-0 lg:m-0 mx-auto relative ${className}`}> <div
className={`w-full flex flex-col rounded-lg overflow-hidden shrink-0 lg:m-0 mx-auto relative ${className}`}
style={{ minHeight: poster ? '' : height }}
>
{poster ? ( {poster ? (
<Image <Image
className='rounded-lg mx-auto' className='rounded-lg mx-auto'
+16 -33
View File
@@ -1,8 +1,9 @@
import { Dispatch, FC, SetStateAction, useMemo, useState } from 'react'; import { Dispatch, FC, SetStateAction, useState } from 'react';
import { ArrowDownIcon, ArrowUpIcon, CaretSortIcon } from '@radix-ui/react-icons'; import { ArrowDownIcon, CaretSortIcon } from '@radix-ui/react-icons';
import { Loader, Magnet } from 'lucide-react'; import { Loader, Magnet } from 'lucide-react';
import useTorrents from '@/app/(site)/useTorrents'; import useTorrents from '@/app/(site)/useTorrents';
import { ORDER } from '@/app/api/torrents/parsers/pirate-bay';
import { Dialog, DialogContent } from '@/components/ui/dialog'; import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
@@ -12,8 +13,7 @@ interface Props {
} }
type Sorting = { type Sorting = {
by: 'seeders' | 'size'; by: ORDER;
direction: 'asc' | 'desc';
}; };
function convertToBytes(size: string) { function convertToBytes(size: string) {
@@ -29,8 +29,8 @@ function compareSizes(size1: string, size2: string) {
const TableHeadSortable = ({ const TableHeadSortable = ({
title, title,
by, by,
onChange, value,
value onChange
}: { }: {
title: string; title: string;
by: Sorting['by']; by: Sorting['by'];
@@ -41,39 +41,22 @@ const TableHeadSortable = ({
<TableHead <TableHead
onClick={() => onClick={() =>
onChange((sorting) => ({ onChange((sorting) => ({
...sorting, by: sorting.by === ORDER.seeders ? ORDER.size : ORDER.seeders
by,
direction: sorting.by !== by ? 'desc' : sorting.direction === 'asc' ? 'desc' : 'asc'
})) }))
} }
className='cursor-pointer select-none' className='cursor-pointer select-none'
> >
<div className='flex gap-1 items-center'> <div className='flex gap-1 items-center'>
<span>{title}</span> <span>{title}</span>
{value.by === by && {value.by === by ? <ArrowDownIcon className='ml-2 h-4 w-4' /> : <CaretSortIcon className='ml-2 h-4 w-4' />}
(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> </div>
</TableHead> </TableHead>
); );
}; };
const Torrents: FC<Props> = ({ title, onClose }) => { const Torrents: FC<Props> = ({ title, onClose }) => {
const { torrents, isLoading, isFetched } = useTorrents({ query: title }); const [sorting, setSorting] = useState<Sorting>({ by: ORDER.seeders });
const [sorting, setSorting] = useState<Sorting>({ by: 'seeders', direction: 'desc' }); const { data: torrents, isLoading, isFetched } = useTorrents({ query: title, order: sorting.by });
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 ( return (
<Dialog defaultOpen={true} onOpenChange={(isOpen) => !isOpen && onClose()}> <Dialog defaultOpen={true} onOpenChange={(isOpen) => !isOpen && onClose()}>
@@ -82,21 +65,21 @@ const Torrents: FC<Props> = ({ title, onClose }) => {
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Title</TableHead> <TableHead>Title</TableHead>
<TableHeadSortable title='Size' by='size' value={sorting} onChange={setSorting} /> <TableHeadSortable title='Size' by={ORDER.size} value={sorting} onChange={setSorting} />
<TableHeadSortable title='Seeders' by='seeders' value={sorting} onChange={setSorting} /> <TableHeadSortable title='Seeders' by={ORDER.seeders} value={sorting} onChange={setSorting} />
<TableHead>Magnet</TableHead> <TableHead>Magnet</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{sortedTorrents.map((torrent) => ( {torrents?.map((torrent) => (
<TableRow key={torrent.id}> <TableRow key={torrent.magnet + torrent.id}>
<TableCell>{torrent.title}</TableCell> <TableCell>{torrent.title}</TableCell>
<TableCell> <TableCell>
<div className='flex items-center gap-1 shrink-0'>{torrent.size}</div> <div className='flex items-center gap-1 shrink-0'>{torrent.size}</div>
</TableCell> </TableCell>
<TableCell className='text-center'>{torrent.seeders}</TableCell> <TableCell className='text-center'>{torrent.seeders}</TableCell>
<TableCell className='text-center'> <TableCell className='text-center'>
<a href={torrent.magnetLink} className='flex items-center justify-center h-8 w-8 border rounded-lg'> <a href={torrent.magnet} className='flex items-center justify-center h-8 w-8 border rounded-lg'>
<Magnet size={20} /> <Magnet size={20} />
</a> </a>
</TableCell> </TableCell>
@@ -111,7 +94,7 @@ const Torrents: FC<Props> = ({ title, onClose }) => {
</TableCell> </TableCell>
</TableRow> </TableRow>
)} )}
{isFetched && !torrents.length && ( {isFetched && !torrents?.length && (
<TableRow> <TableRow>
<TableCell colSpan={4}> <TableCell colSpan={4}>
<div className='h-40 w-full flex items-center justify-center text-xl text-muted-foreground'> <div className='h-40 w-full flex items-center justify-center text-xl text-muted-foreground'>
-7
View File
@@ -1,7 +0,0 @@
import { FC } from 'react';
const Search: FC = () => {
return <div>Search</div>;
};
export default Search;
Vendored
+1 -4
View File
@@ -109,13 +109,10 @@ interface Torrent {
title: string; title: string;
seeders: number; seeders: number;
size: string; size: string;
magnetLink: string; magnet: string;
} }
interface Category { interface Category {
id: string; id: string;
name: string; name: string;
} }
declare module 'rutracker-api-with-proxy';
declare module 'thepiratebayfixed';