refactoring: improved types

This commit is contained in:
ner committed 2024-10-10 17:10:37 +03:00
1 parent 272178d668
commit 5c42608e99
10 files changed
+90 -85

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
class Http { class Http {
base = 'https://api.themoviedb.org/3'; private base = 'https://api.themoviedb.org/3';
get<T>(url: string, { params }: { params?: Record<string, unknown> } = {}, base?: string): Promise<T> { get<T>(url: string, { params }: { params?: Record<string, unknown> } = {}, base?: string): Promise<T> {
const serializedParams = Object.entries(params || {}).reduce((params, [key, value]) => { const serializedParams = Object.entries(params || {}).reduce((params, [key, value]) => {
+15 -11
View File
@@ -1,11 +1,7 @@
const mapMoviesSeriesResponseToShows = ( export const mapMovieSeriesToShow = (
{ total_pages, page, results }: TMDBPagination<Movie> | TMDBPagination<Series>, { id, overview, backdrop_path, poster_path, vote_average, vote_count, ...item }: Movie | Series,
type: Show['type'] = 'movie' type: Show['type'] = 'movie'
): Pagination<Show> => ({ ): Show => ({
page,
total: total_pages,
results: results
.map(({ id, overview, backdrop_path, poster_path, vote_average, vote_count, ...item }) => ({
id, id,
type, type,
overview, overview,
@@ -14,10 +10,18 @@ const mapMoviesSeriesResponseToShows = (
backdrop: backdrop_path ? `https://image.tmdb.org/t/p/w1280/${backdrop_path}` : '', backdrop: backdrop_path ? `https://image.tmdb.org/t/p/w1280/${backdrop_path}` : '',
poster: poster_path ? `https://image.tmdb.org/t/p/w500/${poster_path}` : '', poster: poster_path ? `https://image.tmdb.org/t/p/w500/${poster_path}` : '',
release: 'release_date' in item ? item.release_date : item.first_air_date, release: 'release_date' in item ? item.release_date : item.first_air_date,
title: 'release_date' in item ? item.title : item.name, title: 'release_date' in item ? item.title : item.name
genres: [] });
}))
.filter((show) => show.votes && show.release && show.backdrop && show.poster) const mapMoviesSeriesResponseToShows = (
{ total_pages, page, results }: TMDBPagination<Movie> | TMDBPagination<Series>,
type: Show['type'] = 'movie'
): Pagination<Show> => ({
page,
total: total_pages,
results: results
.map(show => mapMovieSeriesToShow(show, type))
.filter((show) => show.votes && show.release && show.backdrop && show.poster && show.votes > 500)
}); });
export default mapMoviesSeriesResponseToShows; export default mapMoviesSeriesResponseToShows;
+32 -40
View File
@@ -1,8 +1,8 @@
'use server'; 'use server';
import { createUniqueRandomGenerator } from '../lib/utils'; import { createUniqueRandomGenerator } from '@/lib/utils';
import mapMoviesSeriesResponseToShows from './dto/Show'; import mapMoviesSeriesResponseToShows, { mapMovieSeriesToShow } from './dto/Show';
import pirateBay from './parsers/pirate-bay'; import pirateBay from './parsers/pirate-bay';
import yts from './parsers/yts'; import yts from './parsers/yts';
import http from './Http'; import http from './Http';
@@ -27,14 +27,27 @@ export const search = async ({
.then((response) => mapMoviesSeriesResponseToShows(response, type)); .then((response) => mapMoviesSeriesResponseToShows(response, type));
}; };
const TOTAL_PAGES = 500; const TOTAL_PAGES = 400;
const generatePage = createUniqueRandomGenerator(TOTAL_PAGES); const generatePage = createUniqueRandomGenerator(TOTAL_PAGES);
export const details = async ({
showId,
showType = 'movie'
}: {
showId: Show['id'];
showType: Show['type'];
}): Promise<Show & Details> => {
return http
.get<(Movie | Series) & Details>(`/${showType}/${showId}`)
.then((response) => ({ ...mapMovieSeriesToShow(response, showType), ...response }));
};
export const randomMovies = async (): Promise<Pagination<Show>> => { export const randomMovies = async (): Promise<Pagination<Show>> => {
return http return http
.get<TMDBPagination<Movie>>('/discover/movie', { .get<TMDBPagination<Movie>>('/discover/movie', {
params: { params: {
'vote_count.gte': 300,
sort_by: 'popularity.desc', sort_by: 'popularity.desc',
with_origin_country: 'UA|GB|JP|AU|US|IT|DE|FR', with_origin_country: 'UA|GB|JP|AU|US|IT|DE|FR',
page: generatePage() page: generatePage()
@@ -147,16 +160,17 @@ export const credits = async ({
showType?: Show['type']; showType?: Show['type'];
}): Promise<Array<Actor>> => { }): Promise<Array<Actor>> => {
return http return http
.get<{ cast: Array<unknown> }>(`/${showType}/${showId}/${showType === 'tv' ? 'aggregate_credits' : 'credits'}`) .get<{ cast: Array<Actor | AggregatedActor> }>(
.then((data) => { `/${showType}/${showId}/${showType === 'tv' ? 'aggregate_credits' : 'credits'}`
if (showType === 'tv') { )
return data.cast.map((item) => { .then(({ cast }) => {
const actor = item as AggregatedActor; return cast.map((actor) => {
const [role] = actor.roles || [{}]; if ('character' in actor) return actor;
return { ...actor, ...role } as unknown as Actor;
const [{ character }] = actor.roles || [{}];
return { ...actor, character };
}); });
}
return data.cast as Array<Actor>;
}); });
}; };
@@ -176,41 +190,21 @@ export const trailers = async ({
.then((data) => data.results); .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 ({ export const YTSTorrents = async ({
query, query,
sort, sort,
showType, imdbID
showId
}: { }: {
imdbID: string;
query: string; query: string;
sort: Sort; sort: Sort;
showId: Show['id'];
showType: Show['type'];
}) => { }) => {
try { try {
const imdbID = await externalIDs({ showType, showId }); return yts.search({
const torrents = await yts.search({
imdbID, imdbID,
query, query,
sort sort
}); });
return torrents;
} catch (error) { } catch (error) {
return []; return [];
} }
@@ -220,17 +214,15 @@ export const TPBTorrents = async ({
query, query,
sort sort
}: { }: {
imdbID: string;
query: string; query: string;
sort: Sort; sort: Sort;
showId: Show['id'];
showType: Show['type'];
}) => { }) => {
try { try {
const torrents = await pirateBay.search({ return pirateBay.search({
query, query,
sort sort
}); })
return torrents;
} catch (error) { } catch (error) {
return []; return [];
} }
+2 -3
View File
@@ -7,7 +7,7 @@ import ToggleTrailer from '@/components/Show/components/Trailer';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
interface Props { interface Props {
show: Show; show: Show & Partial<Details>;
onClose?: () => void; onClose?: () => void;
} }
@@ -24,8 +24,7 @@ const Actions = ({ onClose, show }: Props) => (
className='h-8 w-1/2 grow' className='h-8 w-1/2 grow'
onClick={() => onClick={() =>
showTorrentsModal({ showTorrentsModal({
showId: show.id, imdbID: show.imdb_id!,
showType: show.type,
title: show.title, title: show.title,
backdrop: show.backdrop, backdrop: show.backdrop,
year: new Date(show.release).getFullYear() year: new Date(show.release).getFullYear()
+7 -2
View File
@@ -3,6 +3,7 @@
import { FC, ReactNode } from 'react'; import { FC, ReactNode } from 'react';
import { create, InstanceProps } from 'react-modal-promise'; import { create, InstanceProps } from 'react-modal-promise';
import useDetails from '@/components/Preview/useDetails';
import Card from '@/components/Show'; import Card from '@/components/Show';
import Credits from '@/components/Show/components/Credits'; import Credits from '@/components/Show/components/Credits';
import { Modal } from '@/components/ui/dialog'; import { Modal } from '@/components/ui/dialog';
@@ -19,8 +20,12 @@ interface Props {
card?: ReactNode; card?: ReactNode;
} }
const Preview: FC<Props> = ({ show, className, onClose, children, card }) => { const Preview: FC<Props> = ({ show: baseShow, className, onClose, children, card }) => {
if (!show) return null; const { data: detailedShow } = useDetails({ showId: baseShow?.id, showType: baseShow?.type });
if (!baseShow) return null;
const show: Show & Partial<Details> | undefined = detailedShow || baseShow;
return ( return (
<div className={cn('flex flex-col md:flex-row gap-2 rounded-xl', { 'p-2': Boolean(onClose) }, className)}> <div className={cn('flex flex-col md:flex-row gap-2 rounded-xl', { 'p-2': Boolean(onClose) }, className)}>
+12
View File
@@ -0,0 +1,12 @@
import { useQuery } from '@tanstack/react-query';
import { details } from '@/api';
const useDetails = ({ showId, showType = 'movie' }: { showId?: Show['id']; showType?: Show['type'] }) =>
useQuery({
enabled: Boolean(showId && showType),
queryKey: ['details', showId, showType],
queryFn: () => details({ showId: showId!, showType })
});
export default useDetails;
@@ -16,14 +16,13 @@ import showHostManagerModal from './HostManager';
import useTorrents from './useTorrents'; import useTorrents from './useTorrents';
interface Props extends InstanceProps<void> { interface Props extends InstanceProps<void> {
showId: Show['id']; imdbID: string;
showType: Show['type'];
title: string; title: string;
year: number; year: number;
backdrop: string; backdrop: string;
} }
const showTorrentsModal = create(({ title, year, showType, showId, backdrop, onResolve }: Props) => { const showTorrentsModal = create(({ title, year, imdbID, backdrop, onResolve }: Props) => {
const isMobile = matchMedia('(max-width: 600px)').matches; const isMobile = matchMedia('(max-width: 600px)').matches;
const prefix = usePrefix(); const prefix = usePrefix();
const [sort, setSort] = useState<Sort>(Sort.seeds); const [sort, setSort] = useState<Sort>(Sort.seeds);
@@ -39,8 +38,7 @@ const showTorrentsModal = create(({ title, year, showType, showId, backdrop, onR
} = useTorrents({ } = useTorrents({
query, query,
sort, sort,
showId, imdbID,
showType,
key, key,
queryFn queryFn
}); });
@@ -5,22 +5,20 @@ import { Sort } from '@/api/parsers';
const useTorrents = ({ const useTorrents = ({
query, query,
sort, sort,
showId, imdbID,
showType,
key, key,
queryFn queryFn
}: { }: {
showId: Show['id'];
showType: Show['type'];
key: string; key: string;
query: string; query: string;
sort: Sort; sort: Sort;
queryFn: (params: { query: string; sort: Sort; showId: Show['id']; showType: Show['type'] }) => Promise<Torrent[]>; imdbID: string;
queryFn: (params: { query: string; sort: Sort; imdbID: string; }) => Promise<Torrent[]>;
}) => { }) => {
return useQuery({ return useQuery({
enabled: Boolean(query), enabled: Boolean(query),
queryKey: [key, query, sort, showId, showType], queryKey: [key, query, sort, imdbID],
queryFn: () => queryFn({ query, sort, showId, showType }) queryFn: () => queryFn({ query, sort, imdbID })
}); });
}; };
-1
View File
@@ -1,5 +1,4 @@
MOVIE_DB_TOKEN=YOUR_TOKEN MOVIE_DB_TOKEN=YOUR_TOKEN
TRACKER_PROXY_BASE=HOST_URL_OF_YOUR_INSTANCE #https://github.com/noisy5ilence/tracker-proxy
NEXT_PUBLIC_TRACKER_PROXY_BASE=HOST_URL_OF_YOUR_INSTANCE #https://github.com/noisy5ilence/tracker-proxy NEXT_PUBLIC_TRACKER_PROXY_BASE=HOST_URL_OF_YOUR_INSTANCE #https://github.com/noisy5ilence/tracker-proxy
PIRATE_BAY_HOST=https://thepiratebay10.org PIRATE_BAY_HOST=https://thepiratebay10.org
YTS_HOST=https://yts.mx/api/v2/list_movies.json YTS_HOST=https://yts.mx/api/v2/list_movies.json
Vendored
+13 -15
View File
@@ -13,6 +13,13 @@ interface Pagination<T> {
results: T[]; results: T[];
} }
interface Details {
genres: IDName[];
imdb_id: string;
runtime: number;
tagline: string;
}
interface Movie { interface Movie {
adult: boolean; adult: boolean;
backdrop_path: string; backdrop_path: string;
@@ -57,10 +64,9 @@ interface Show {
release: Date; release: Date;
rating: number; rating: number;
votes: number; votes: number;
genres: string[];
} }
interface Actor { interface Person {
adult: boolean; adult: boolean;
gender: number; gender: number;
id: number; id: number;
@@ -70,23 +76,17 @@ interface Actor {
popularity: number; popularity: number;
profile_path: string; profile_path: string;
cast_id: number; cast_id: number;
character: string;
credit_id: string; credit_id: string;
order: number; order: number;
} }
interface AggregatedActor { interface Actor extends Person {
adult: boolean; character: string;
gender: number; }
id: number;
known_for_department: string; interface AggregatedActor extends Person {
name: string;
original_name: string;
popularity: number;
profile_path: string;
roles: Role[]; roles: Role[];
total_episode_count: number; total_episode_count: number;
order: number;
} }
interface Role { interface Role {
@@ -96,8 +96,6 @@ interface Role {
} }
interface Trailer { interface Trailer {
iso_639_1: string;
iso_3166_1: string;
name: string; name: string;
key: string; key: string;
site: string; site: string;