refactor: clean code and remove unnecessary dependencies
This commit is contained in:
1 parent
eceae6fec7
commit
ebf599eed6
92 files changed
+1152
-2842
No files matched your search
+28
@@ -0,0 +1,28 @@
|
||||
class Http {
|
||||
base = 'https://api.themoviedb.org/3';
|
||||
|
||||
get<T>(url: string, { params }: { params?: Record<string, unknown> } = {}): Promise<T> {
|
||||
const serializedParams = Object.entries(params || {}).reduce((params, [key, value]) => {
|
||||
if (!['', undefined, null].includes(value as string)) {
|
||||
params.set(key, value as string);
|
||||
}
|
||||
|
||||
return params;
|
||||
}, new URLSearchParams());
|
||||
|
||||
return fetch(`${this.base}${url}?${serializedParams}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.MOVIE_DB_TOKEN}`
|
||||
},
|
||||
next: { revalidate: 3600 }
|
||||
}).then((response) => {
|
||||
if (!response.ok) return Promise.reject(response);
|
||||
|
||||
return response.json();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const http = new Http();
|
||||
|
||||
export default http;
|
||||
@@ -0,0 +1,23 @@
|
||||
const mapMoviesSeriesResponseToShows = (
|
||||
{ total_pages, page, results }: TMDBPagination<Movie> | TMDBPagination<Series>,
|
||||
type: Show['type'] = 'movie'
|
||||
): Pagination<Show> => ({
|
||||
page,
|
||||
total: total_pages,
|
||||
results: results
|
||||
.map(({ id, overview, backdrop_path, poster_path, vote_average, vote_count, ...item }) => ({
|
||||
id,
|
||||
type,
|
||||
overview,
|
||||
backdrop: backdrop_path,
|
||||
poster: poster_path,
|
||||
rating: vote_average,
|
||||
votes: vote_count,
|
||||
release: 'release_date' in item ? item.release_date : item.first_air_date,
|
||||
title: 'release_date' in item ? item.title : item.name,
|
||||
genres: []
|
||||
}))
|
||||
.filter((show) => show.votes && show.release)
|
||||
});
|
||||
|
||||
export default mapMoviesSeriesResponseToShows;
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
'use server';
|
||||
|
||||
import { createUniqueRandomGenerator } from '../lib/utils';
|
||||
|
||||
import mapMoviesSeriesResponseToShows from './dto/Show';
|
||||
import pirateBay from './parsers/pirate-bay';
|
||||
import yts from './parsers/yts';
|
||||
import http from './Http';
|
||||
import { Sort } from './parsers';
|
||||
|
||||
export const search = async ({
|
||||
query,
|
||||
page,
|
||||
type = 'movie'
|
||||
}: {
|
||||
query: string;
|
||||
page: string;
|
||||
type: Show['type'];
|
||||
}): Promise<Pagination<Show>> => {
|
||||
return http
|
||||
.get<TMDBPagination<Movie>>(`/search/${type}`, {
|
||||
params: {
|
||||
query,
|
||||
page
|
||||
}
|
||||
})
|
||||
.then((response) => mapMoviesSeriesResponseToShows(response, type));
|
||||
};
|
||||
|
||||
const generatePage = createUniqueRandomGenerator(500);
|
||||
|
||||
export const randomMovies = async (): Promise<Pagination<Show>> => {
|
||||
return http
|
||||
.get<TMDBPagination<Movie>>('/discover/movie', {
|
||||
params: {
|
||||
sort_by: 'popularity.desc',
|
||||
with_origin_country: 'UA|GB|JP|AU|US|IT|DE|FR',
|
||||
page: generatePage()
|
||||
}
|
||||
})
|
||||
.then(mapMoviesSeriesResponseToShows);
|
||||
};
|
||||
|
||||
export const popularByType = async ({ type }: { type: 'streaming' | 'theater' | 'rent' }): Promise<Show[]> => {
|
||||
const params =
|
||||
type === 'theater'
|
||||
? { with_release_type: 3 }
|
||||
: { with_watch_monetization_types: type === 'streaming' ? 'flatrate' : 'rent' };
|
||||
|
||||
return http
|
||||
.get<TMDBPagination<Movie>>('/discover/movie', {
|
||||
params: {
|
||||
...params,
|
||||
watch_region: 'US'
|
||||
}
|
||||
})
|
||||
.then((response) => {
|
||||
const data = mapMoviesSeriesResponseToShows(response);
|
||||
|
||||
return data.results;
|
||||
});
|
||||
};
|
||||
|
||||
export const popularMovies = async ({ page }: { page?: string } = {}): Promise<Pagination<Show>> => {
|
||||
return http
|
||||
.get<TMDBPagination<Movie>>('/discover/movie', {
|
||||
params: {
|
||||
page,
|
||||
sort_by: 'popularity.desc',
|
||||
'vote_count.gte': 0,
|
||||
'vote_average.lte': 10,
|
||||
'vote_average.gte': 0,
|
||||
'with_runtime.gte': 0,
|
||||
'with_runtime.lte': 400
|
||||
}
|
||||
})
|
||||
.then(mapMoviesSeriesResponseToShows);
|
||||
};
|
||||
|
||||
export const trendingMovies = async ({ page }: { page?: string } = {}): Promise<Show[]> => {
|
||||
return http
|
||||
.get<TMDBPagination<Movie>>('/trending/movie/day', {
|
||||
params: {
|
||||
page
|
||||
}
|
||||
})
|
||||
.then((response) => {
|
||||
const data = mapMoviesSeriesResponseToShows(response);
|
||||
|
||||
return data.results;
|
||||
});
|
||||
};
|
||||
|
||||
export const topMovies = async ({ page, starring }: { page?: string; starring?: string } = {}): Promise<
|
||||
Pagination<Show>
|
||||
> => {
|
||||
return http
|
||||
.get<TMDBPagination<Movie>>('/discover/movie', {
|
||||
params: {
|
||||
page,
|
||||
with_cast: starring,
|
||||
with_people: starring,
|
||||
sort_by: 'vote_average.desc',
|
||||
'vote_count.gte': 300,
|
||||
'vote_average.lte': 10,
|
||||
'vote_average.gte': 0
|
||||
}
|
||||
})
|
||||
.then(mapMoviesSeriesResponseToShows);
|
||||
};
|
||||
|
||||
export const similarShows = async ({
|
||||
page,
|
||||
showId,
|
||||
showType = 'movie'
|
||||
}: {
|
||||
page?: string;
|
||||
showId: string;
|
||||
showType: Show['type'];
|
||||
}): Promise<Pagination<Show>> => {
|
||||
return http
|
||||
.get<TMDBPagination<Movie> | TMDBPagination<Series>>(`/${showType}/${showId}/recommendations`, {
|
||||
params: {
|
||||
page
|
||||
}
|
||||
})
|
||||
.then((response) => mapMoviesSeriesResponseToShows(response, showType));
|
||||
};
|
||||
|
||||
export const externalIDs = async ({
|
||||
showId,
|
||||
showType = 'movie'
|
||||
}: {
|
||||
showType: Show['type'];
|
||||
showId: Show['id'];
|
||||
}): Promise<string> => {
|
||||
return http.get<ExternalIDS>(`/${showType}/${showId}/external_ids`).then(({ imdb_id }) => imdb_id);
|
||||
};
|
||||
|
||||
export const credits = async ({
|
||||
showId,
|
||||
showType = 'movie'
|
||||
}: {
|
||||
showId: Show['id'];
|
||||
showType?: Show['type'];
|
||||
}): Promise<Array<Actor>> => {
|
||||
return http
|
||||
.get<{ cast: Array<unknown> }>(`/${showType}/${showId}/${showType === 'tv' ? 'aggregate_credits' : 'credits'}`)
|
||||
.then((data) => {
|
||||
if (showType === 'tv') {
|
||||
return data.cast.map((item) => {
|
||||
const actor = item as AggregatedActor;
|
||||
const [role] = actor.roles || [{}];
|
||||
return { ...actor, ...role } as unknown as Actor;
|
||||
});
|
||||
}
|
||||
return data.cast as Array<Actor>;
|
||||
});
|
||||
};
|
||||
|
||||
export const trailers = async ({
|
||||
showId,
|
||||
showType
|
||||
}: {
|
||||
showId: Show['id'];
|
||||
showType?: Show['type'];
|
||||
}): Promise<Trailer[]> => {
|
||||
return http
|
||||
.get<{ id: number; results: Trailer[] }>(`/${showType}/${showId}/videos`, {
|
||||
params: {
|
||||
language: 'en-US'
|
||||
}
|
||||
})
|
||||
.then((data) => data.results);
|
||||
};
|
||||
|
||||
export const YTSTorrents = async ({
|
||||
query,
|
||||
sort,
|
||||
showType,
|
||||
showId
|
||||
}: {
|
||||
query: string;
|
||||
sort: Sort;
|
||||
showId: Show['id'];
|
||||
showType: Show['type'];
|
||||
}) => {
|
||||
try {
|
||||
const imdbID = await externalIDs({ showType, showId });
|
||||
const torrents = await yts.search({
|
||||
imdbID,
|
||||
query,
|
||||
sort
|
||||
});
|
||||
return torrents;
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const TPBTorrents = async ({
|
||||
query,
|
||||
sort
|
||||
}: {
|
||||
query: string;
|
||||
sort: Sort;
|
||||
showId: Show['id'];
|
||||
showType: Show['type'];
|
||||
}) => {
|
||||
try {
|
||||
const torrents = await pirateBay.search({
|
||||
query,
|
||||
sort
|
||||
});
|
||||
return torrents;
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
export enum Sort {
|
||||
size = 'size',
|
||||
seeds = 'seeds'
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import { parse } from 'node-html-parser';
|
||||
|
||||
import { Sort } from './index';
|
||||
|
||||
export class PirateBay {
|
||||
private client: AxiosInstance;
|
||||
private sort = {
|
||||
[Sort.size]: 5,
|
||||
[Sort.seeds]: 7
|
||||
};
|
||||
|
||||
constructor(private host: string = process.env.PIRATE_BAY_HOST || 'https://thepiratebay10.org') {
|
||||
this.host = host;
|
||||
this.client = axios.create({
|
||||
baseURL: this.host
|
||||
});
|
||||
}
|
||||
|
||||
async search({
|
||||
query,
|
||||
page = 1,
|
||||
category = 200,
|
||||
sort = Sort.size
|
||||
}: {
|
||||
query: string;
|
||||
page?: number;
|
||||
category?: number;
|
||||
sort?: Sort;
|
||||
}): Promise<Torrent[]> {
|
||||
return this.client.post(`/search/${query}/${page}/${this.sort[sort]}/${category}`, null).then(({ data }) => {
|
||||
const html = parse(data);
|
||||
const table = html?.getElementById('searchResult');
|
||||
const rows = table?.querySelectorAll('tr:not(.header)');
|
||||
|
||||
const titles = rows?.map((row) => row.querySelector('td:nth-child(2) a')?.innerText).filter(Boolean);
|
||||
const seeders = rows?.map((row) => row.querySelector('td:nth-child(6)')?.innerText);
|
||||
|
||||
const sizes = rows?.reduce((sizes, row) => {
|
||||
const size = row.querySelector('td:nth-child(5)')?.innerText;
|
||||
|
||||
if (!size) return sizes;
|
||||
|
||||
sizes.push(size.replace(' ', ' ').replace('Size ', ''));
|
||||
return sizes;
|
||||
}, [] as string[]);
|
||||
|
||||
const magnets = table?.querySelectorAll('a[href^="magnet:"]').map((link) => link.getAttribute('href'));
|
||||
|
||||
return titles.map((title, index) => {
|
||||
return {
|
||||
title,
|
||||
id: title,
|
||||
size: sizes[index],
|
||||
seeders: parseInt(seeders[index]!),
|
||||
magnet: magnets[index]!
|
||||
};
|
||||
}) as Torrent[];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const parser = new PirateBay();
|
||||
|
||||
export default parser;
|
||||
@@ -0,0 +1,66 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
|
||||
import { Sort } from '../index';
|
||||
|
||||
import { YTSResponse } from './models';
|
||||
|
||||
export class YTS {
|
||||
private client: AxiosInstance;
|
||||
|
||||
constructor(private host: string = process.env.YTS_HOST || 'https://yts.mx/api/v2/list_movies.json') {
|
||||
this.client = axios.create({
|
||||
baseURL: this.host
|
||||
});
|
||||
}
|
||||
|
||||
async search({
|
||||
query,
|
||||
page = 1,
|
||||
sort = Sort.size,
|
||||
imdbID
|
||||
}: {
|
||||
query: string;
|
||||
imdbID: string;
|
||||
page?: number;
|
||||
sort?: Sort;
|
||||
}): Promise<Torrent[]> {
|
||||
return this.client
|
||||
.get<YTSResponse>('', {
|
||||
params: {
|
||||
page,
|
||||
query_term: query,
|
||||
sort_by: sort
|
||||
}
|
||||
})
|
||||
.then(({ data }) => {
|
||||
const movie = data?.data?.movies?.find((movie) => movie.imdb_code === imdbID);
|
||||
|
||||
return (
|
||||
movie?.torrents.map((torrent) => {
|
||||
const trackers = [
|
||||
'udp://open.demonii.com:1337/announce',
|
||||
'udp://tracker.openbittorrent.com:80',
|
||||
'udp://tracker.coppersurfer.tk:6969',
|
||||
'udp://glotorrents.pw:6969/announce',
|
||||
'udp://tracker.opentrackr.org:1337/announce',
|
||||
'udp://torrent.gresille.org:80/announce',
|
||||
'udp://p4p.arenabg.com:1337',
|
||||
'udp://tracker.leechers-paradise.org:6969'
|
||||
];
|
||||
|
||||
return {
|
||||
id: movie.id?.toString(),
|
||||
title: `${movie.title_english} ${torrent.quality ? `[${torrent.quality}]` : ''}`,
|
||||
seeders: torrent.seeds,
|
||||
size: torrent.size,
|
||||
magnet: `magnet:?xt=urn:btih:${torrent.hash}&dn=${encodeURIComponent(query)}&tr=${trackers.join('&tr=')}`
|
||||
};
|
||||
}) || []
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const yts = new YTS();
|
||||
|
||||
export default yts;
|
||||
@@ -0,0 +1,98 @@
|
||||
export interface YTSResponse {
|
||||
status: Stat;
|
||||
status_message: string;
|
||||
data: Data;
|
||||
'@meta': Meta;
|
||||
}
|
||||
|
||||
export interface Meta {
|
||||
server_time: number;
|
||||
server_timezone: string;
|
||||
api_version: number;
|
||||
execution_time: string;
|
||||
}
|
||||
|
||||
export interface Data {
|
||||
movie_count: number;
|
||||
limit: number;
|
||||
page_number: number;
|
||||
movies: Movie[];
|
||||
}
|
||||
|
||||
export interface Movie {
|
||||
id: number;
|
||||
url: string;
|
||||
imdb_code: string;
|
||||
title: string;
|
||||
title_english: string;
|
||||
title_long: string;
|
||||
slug: string;
|
||||
year: number;
|
||||
rating: number;
|
||||
runtime: number;
|
||||
genres: string[];
|
||||
summary: string;
|
||||
description_full: string;
|
||||
synopsis: string;
|
||||
yt_trailer_code: string;
|
||||
language: Language;
|
||||
mpa_rating: MpaRating;
|
||||
background_image: string;
|
||||
background_image_original: string;
|
||||
small_cover_image: string;
|
||||
medium_cover_image: string;
|
||||
large_cover_image: string;
|
||||
state: Stat;
|
||||
torrents: Torrent[];
|
||||
date_uploaded: Date;
|
||||
date_uploaded_unix: number;
|
||||
}
|
||||
|
||||
export enum Language {
|
||||
En = 'en',
|
||||
Ja = 'ja'
|
||||
}
|
||||
|
||||
export enum MpaRating {
|
||||
Empty = '',
|
||||
PG13 = 'PG-13',
|
||||
R = 'R'
|
||||
}
|
||||
|
||||
export enum Stat {
|
||||
Ok = 'ok'
|
||||
}
|
||||
|
||||
export interface Torrent {
|
||||
url: string;
|
||||
hash: string;
|
||||
quality: Quality;
|
||||
type: Type;
|
||||
is_repack: string;
|
||||
video_codec: VideoCodec;
|
||||
bit_depth: string;
|
||||
audio_channels: string;
|
||||
seeds: number;
|
||||
peers: number;
|
||||
size: string;
|
||||
size_bytes: number;
|
||||
date_uploaded: Date;
|
||||
date_uploaded_unix: number;
|
||||
}
|
||||
|
||||
export enum Quality {
|
||||
The1080P = '1080p',
|
||||
The2160P = '2160p',
|
||||
The3D = '3D',
|
||||
The720P = '720p'
|
||||
}
|
||||
|
||||
export enum Type {
|
||||
Bluray = 'bluray',
|
||||
Web = 'web'
|
||||
}
|
||||
|
||||
export enum VideoCodec {
|
||||
X264 = 'x264',
|
||||
X265 = 'x265'
|
||||
}
|
||||
Reference in new issue
Block a user