fix: SITE_URL

This commit is contained in:
ner committed 2024-10-28 17:20:05 +02:00
1 parent 1fe912f4bd
commit dfdfb79169
66 files changed
+1352 -240

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
type Search = Record<string, string | number | boolean | null | undefined>;
class Http {
constructor(
private base: string,
private authorization?: string
) {}
private async request<T, B = unknown>({
method,
url,
base = this.base,
search,
body,
preventCache = true
}: {
method: 'GET' | 'POST';
url: string;
base?: string;
search?: Search;
body?: B;
preventCache?: boolean;
}): Promise<T> {
const serializedParams = new URLSearchParams(
Object.entries(search ?? {}).reduce((params, [key, value]) => {
if (value != null && value !== '') {
params.set(key, String(value));
}
return params;
}, new URLSearchParams())
);
try {
const response = await fetch(`${base}${url}?${serializedParams}`, {
method,
headers: {
Authorization: this.authorization || '',
'Content-Type': 'application/json'
},
body: body ? JSON.stringify(body) : undefined,
next: preventCache ? undefined : { revalidate: 3600 }
});
if (!response.ok) {
return Promise.reject({
status: response.status,
statusText: response.statusText
});
}
return response.json();
} catch (error) {
return Promise.reject({ message: 'Network or parsing error', error });
}
}
get<T>(
url: string,
{ params, preventCache }: { params?: Search; preventCache?: boolean } = {},
base?: string
): Promise<T> {
return this.request<T>({
url,
method: 'GET',
search: params,
preventCache,
base
});
}
post<T, B = unknown>(
url: string,
{ params, preventCache }: { params?: Search; preventCache?: boolean } = {},
body?: B,
base?: string
): Promise<T> {
return this.request<T>({
url,
method: 'POST',
search: params,
body,
base,
preventCache
});
}
}
export default Http;
+10
View File
@@ -0,0 +1,10 @@
import Http from './Http';
const BASE =
process.env.NEXT_PUBLIC_VERCEL_ENV === 'production'
? process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL
: process.env.NEXT_PUBLIC_VERCEL_URL;
const movieAdvisor = new Http(`${BASE?.startsWith('http') ? BASE : `https://${BASE}`}/api/tmdb`);
export default movieAdvisor;
+7
View File
@@ -0,0 +1,7 @@
import { MOVIE_DB_TOKEN } from '@/env';
import Http from './Http';
const theMovieDb = new Http('https://api.themoviedb.org/3', `Bearer ${MOVIE_DB_TOKEN}`);
export default theMovieDb;
+33
View File
@@ -0,0 +1,33 @@
export const mapMovieSeriesToShow = (
{ id, overview, backdrop_path, poster_path, vote_average, vote_count, ...item }: Movie | Series,
type: Show['type'] = 'movie'
): Show => ({
id,
type,
overview,
rating: vote_average,
votes: vote_count,
backdrop: backdrop_path ? `https://image.tmdb.org/t/p/w1280${backdrop_path}` : '',
poster: poster_path
? {
'1x': `https://image.tmdb.org/t/p/w342${poster_path}`,
'1.5x': `https://image.tmdb.org/t/p/w500${poster_path}`,
'2x': `https://image.tmdb.org/t/p/w780${poster_path}`
}
: { '1x': '', '1.5x': '', '2x': '' },
release: 'release_date' in item ? item.release_date : item.first_air_date,
title: 'release_date' in item ? item.title : item.name
});
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)
});
export default mapMoviesSeriesResponseToShows;
+75
View File
@@ -0,0 +1,75 @@
'use server';
import { cookies } from 'next/headers';
import http from './clients/theMovieDb';
import mapMoviesSeriesResponseToShows from './dto/Show';
export const session = async () => cookies().get('session')?.value;
export const createRequestToken = async () => {
return http.get<RequestToken>('/authentication/token/new', { preventCache: true }).then(({ request_token }) => ({
redirectUrl: `https://www.themoviedb.org/authenticate/${request_token}`,
requestToken: request_token
}));
};
export const createSession = async ({ requestToken }: { requestToken: string }) => {
return http.post<Session>('/authentication/session/new', {
params: { request_token: requestToken },
preventCache: true
});
};
export const account = async () => {
return http.get<Account>('/account/null', {
params: { session_id: await session() },
preventCache: true
});
};
export const accountStates = async ({ showId, showType }: { showId: Show['id']; showType: Show['type'] }) => {
return http.get<ShowState>(`/${showType}/${showId}/account_states`, {
params: { session_id: await session() },
preventCache: true
});
};
export const updateAccountStates = async ({
showId,
showType,
list,
value
}: {
showId: Show['id'];
showType: Show['type'];
list: 'favorite' | 'watchlist';
value: boolean;
}) => {
http.post(
`/account/null/${list}`,
{ params: { session_id: await session() }, preventCache: true },
{
media_id: showId,
media_type: showType,
[list]: value
}
);
};
export const usersShows = async ({
showType,
list,
page
}: {
showType: Show['type'];
list: 'favorite' | 'watchlist';
page: string;
}): Promise<Pagination<Show>> => {
return http
.get<TMDBPagination<Movie>>(`/account/null/${list}/${showType === 'tv' ? 'tv' : 'movies'}`, {
params: { page, sort_by: 'created_at.desc', session_id: await session() },
preventCache: true
})
.then((response) => mapMoviesSeriesResponseToShows(response, showType));
};
+4
View File
@@ -0,0 +1,4 @@
export enum Sort {
size = 'size',
seeds = 'seeds'
}
+132
View File
@@ -0,0 +1,132 @@
import axios, { AxiosInstance } from 'axios';
import { wrapper } from 'axios-cookiejar-support';
import { load } from 'cheerio';
import parseTorrent, { Instance } from 'parse-torrent';
import torrentTitle from 'parse-torrent-title';
import { CookieJar } from 'tough-cookie';
import { TOLOKA_HOST, TOLOKA_PASSWORD, TOLOKA_USERNAME } from '@/env';
import { Sort } from '../index';
export class Toloka {
private client: AxiosInstance;
private host: string;
private sort = {
[Sort.size]: 7,
[Sort.seeds]: 10
};
private cookieJar = new CookieJar();
private magnets: Record<string, string> = {};
constructor() {
this.host = TOLOKA_HOST || 'https://toloka.to';
this.client = wrapper(
axios.create({
jar: this.cookieJar,
baseURL: this.host,
withCredentials: true
})
);
}
private async isAuthorized(data: string) {
return !load(data)('[href="/login.php"]').length;
}
private async auth() {
const data = new FormData();
data.append('username', TOLOKA_USERNAME as string);
data.append('password', TOLOKA_PASSWORD as string);
data.append('autologin', 'on');
data.append('ssl', 'on');
data.append('login', 'Вхід');
await this.client.post('/login.php', data, {
headers: { 'Content-Type': 'multipart/form-data' }
});
}
async search({ query, sort = Sort.size }: { query: string; sort?: Sort }): Promise<Torrent[]> {
const fetchPage = () => this.client.get(`/tracker.php?o=${this.sort[sort]}&nm=${query}`);
const parseTorrents = (data: string) => {
const $ = load(data);
const rows = $('.prow1, .prow2');
return rows
.map((_, row) => {
const originalTitle = $(row).find('td:nth-child(3)').text();
const size = $(row).find('td:nth-child(7)').text();
const seeders = $(row).find('td:nth-child(10)').text();
const download = $(row).find('td:nth-child(6) a').attr('href');
const { year, source, codec, container, title, season, episode, resolution } = torrentTitle.parse(
originalTitle || ''
);
return {
year: year?.toString(),
source,
codec,
container,
originalTitle,
title: `${title}${season && episode ? ` [S${season}:E${episode}]` : ''}`,
id: originalTitle || '',
size,
seeders: parseInt(seeders || '0'),
quality: resolution,
magnet: '',
download
};
})
.get();
};
let page = await fetchPage();
if (await this.isAuthorized(page.data)) return parseTorrents(page.data);
await this.auth();
page = await fetchPage();
return parseTorrents(page.data);
}
async magnet(url: string) {
if (this.magnets[url]) return this.magnets[url];
const fetchTorrent = async () => {
const { data: buffer } = await this.client.get(`/${url}`, {
responseType: 'arraybuffer'
});
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() || '')}`;
this.magnets[url] = magnet;
return this.magnets[url];
}
}
const parser = new Toloka();
export default parser;
+85
View File
@@ -0,0 +1,85 @@
import axios, { AxiosInstance } from 'axios';
import { load } from 'cheerio';
import torrentTitle from 'parse-torrent-title';
import { PIRATE_BAY_HOST } from '@/env';
import { Sort } from '../index';
export class PirateBay {
private client: AxiosInstance;
private host: string;
private sort = {
[Sort.size]: 5,
[Sort.seeds]: 7
};
constructor() {
this.host = PIRATE_BAY_HOST || 'https://thepiratebay10.info';
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 $ = load(data);
const table = $('#searchResult');
const rows = table.find('tr:not(.header)');
const titles = rows
.map((_, row) => $(row).find('td:nth-child(2) a').text())
.get()
.filter(Boolean);
const seeders = rows.map((_, row) => $(row).find('td:nth-child(6)').text()).get();
const sizes = rows
.map((_, row) => {
const size = $(row).find('td:nth-child(5)').text();
return size ? size.replace('&nbsp;', ' ').replace('Size ', '') : null;
})
.get()
.filter(Boolean);
const magnets = table
.find('a[href^="magnet:"]')
.map((_, link) => $(link).attr('href'))
.get();
return titles.map((originalTitle, index) => {
const { title, resolution, source, codec, container, season, episode, year } = torrentTitle.parse(
originalTitle || ''
);
return {
year: year?.toString(),
source,
codec,
container,
originalTitle,
title: `${title} ${season && episode ? `[S${season}:E${episode}]` : ''}`,
id: title,
size: sizes[index],
seeders: parseInt(seeders[index] || '0', 10),
quality: resolution,
magnet: magnets[index] || ''
};
});
});
}
}
const parser = new PirateBay();
export default parser;
+74
View File
@@ -0,0 +1,74 @@
import axios, { AxiosInstance } from 'axios';
import { YTS_HOST } from '@/env';
import { Sort } from '../index';
import { YTSResponse } from './models';
export class YTS {
private client: AxiosInstance;
private host: string;
constructor() {
this.host = 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,
seeders: torrent.seeds,
size: torrent.size,
quality: torrent.quality,
source: torrent.type,
year: movie.year?.toString(),
magnet: `magnet:?xt=urn:btih:${torrent.hash}&dn=${encodeURIComponent(query)}&tr=${trackers.join('&tr=')}`
};
}) || []
);
});
}
}
const yts = new YTS();
export default yts;
+98
View File
@@ -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'
}
+21
View File
@@ -0,0 +1,21 @@
import movieAdvisor from '../clients/movieAdvisor';
export type AccountQueryProps = {
session?: string | null;
};
export const KEY = ({ session }: AccountQueryProps) => ['account', session];
const accountQuery = ({ session }: AccountQueryProps) => ({
enabled: Boolean(session),
queryKey: KEY({ session }),
staleTime: Infinity,
notifyOnChangeProps: ['data' as const],
queryFn: () =>
movieAdvisor.get<Account>('/account/null', {
params: { session_id: session },
preventCache: true
})
});
export default accountQuery;
+31
View File
@@ -0,0 +1,31 @@
import movieAdvisor from '../clients/movieAdvisor';
export type CreditsQueryProps = {
showId?: Show['id'];
showType?: Show['type'];
};
const creditsQuery = ({ showId, showType }: CreditsQueryProps) => ({
enabled: Boolean(showId),
queryKey: ['credits', showId, showType],
queryFn: () =>
movieAdvisor
.get<{
cast: Array<Actor | AggregatedActor>;
}>(`/${showType}/${showId}/${showType === 'tv' ? 'aggregate_credits' : 'credits'}`)
.then(({ cast }) => {
return cast
.filter((person) => person.profile_path)
.map((actor) => {
const photoUrl = `https://image.tmdb.org/t/p/w185${actor.profile_path}`;
if ('character' in actor) return { ...actor, photoUrl };
const [{ character }] = actor.roles || [{}];
return { ...actor, character, photoUrl };
});
})
});
export default creditsQuery;
+18
View File
@@ -0,0 +1,18 @@
import movieAdvisor from '../clients/movieAdvisor';
import { mapMovieSeriesToShow } from '../dto/Show';
export type DetailsQueryProps = {
showId?: Show['id'];
showType?: Show['type'];
};
const detailsQuery = ({ showId, showType }: DetailsQueryProps) => ({
enabled: Boolean(showId),
queryKey: ['details', showId, showType],
queryFn: () =>
movieAdvisor
.get<(Movie | Series) & Details>(`/${showType}/${showId}`)
.then((response) => ({ ...response, ...mapMovieSeriesToShow(response, showType) }))
});
export default detailsQuery;
+29
View File
@@ -0,0 +1,29 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type PopularQueryProps = {
sortBy?: string;
starring?: string;
};
const popularQuery = ({ sortBy = 'popularity.desc', starring }: PopularQueryProps = {}) => ({
suspense: true,
queryKey: ['popular', sortBy, starring],
initialPageParam: '1',
queryFn: ({ pageParam = '1' }: { pageParam?: string }) =>
movieAdvisor
.get<TMDBPagination<Movie>>('/discover/movie', {
params: {
page: pageParam,
sort_by: sortBy,
with_cast: starring,
with_people: starring,
'vote_count.gte': 300,
'vote_average.lte': 10,
'vote_average.gte': 5
}
})
.then(mapMoviesSeriesResponseToShows)
});
export default popularQuery;
+27
View File
@@ -0,0 +1,27 @@
import { createUniqueRandomGenerator } from '@/lib/utils';
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
const TOTAL_PAGES = 400;
export const generatePage = createUniqueRandomGenerator(TOTAL_PAGES);
const randomQuery = () => ({
suspense: true,
queryKey: ['random-movie'],
initialPageParam: '1',
queryFn: () =>
movieAdvisor
.get<TMDBPagination<Movie>>('/discover/movie', {
params: {
'vote_count.gte': 300,
sort_by: 'popularity.desc',
with_origin_country: 'UA|GB|JP|AU|US|IT|DE|FR',
page: generatePage()
}
})
.then(mapMoviesSeriesResponseToShows)
});
export default randomQuery;
+15
View File
@@ -0,0 +1,15 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type SearchQueryProps = { query: string; type: Show['type'] };
const searchQuery = ({ query, type }: SearchQueryProps) => ({
queryKey: ['search', query, type],
queryFn: ({ pageParam }: { pageParam: string }) =>
movieAdvisor
.get<TMDBPagination<Movie>>(`/search/${type}`, { params: { page: pageParam, query } })
.then((response) => mapMoviesSeriesResponseToShows(response, type)),
enabled: Boolean(query)
});
export default searchQuery;
+23
View File
@@ -0,0 +1,23 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type SimilarQueryProps = {
showId: string;
showType: Show['type'];
};
const similarQuery = ({ showId, showType }: SimilarQueryProps) => ({
enabled: Boolean(showId),
queryKey: ['similar', showId, showType],
initialPageParam: '1',
queryFn: ({ pageParam = '1' }: { pageParam?: string }) =>
movieAdvisor
.get<TMDBPagination<Movie> | TMDBPagination<Series>>(`/${showType}/${showId}/recommendations`, {
params: {
page: pageParam
}
})
.then((response) => mapMoviesSeriesResponseToShows(response, showType))
});
export default similarQuery;
+37
View File
@@ -0,0 +1,37 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type TrendingQueryProps = {
type: 'trending' | 'streaming' | 'theater';
};
const trendingQuery = ({ type }: TrendingQueryProps) => ({
queryKey: ['trending', `type-${type}`],
queryFn: () => {
const params: Record<string, string | number> = {};
if (type !== 'trending') {
params['watch_region'] = 'US';
}
if (type === 'theater') {
params['with_release_type'] = 3;
}
if (type === 'streaming') {
params['with_watch_monetization_types'] = 'flatrate';
}
return movieAdvisor
.get<TMDBPagination<Movie>>(type === 'trending' ? '/trending/movie/day' : '/discover/movie', {
params
})
.then((response) => {
const data = mapMoviesSeriesResponseToShows(response);
return data.results;
});
}
});
export default trendingQuery;
+25
View File
@@ -0,0 +1,25 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type UsersShowsQueryProps = {
showType: Show['type'];
list: 'favorite' | 'watchlist';
session?: string | null;
};
export const KEY = ({ list, showType, session }: UsersShowsQueryProps) => [`users-${list}`, showType, session];
const usersShowsQuery = ({ showType, list, session }: UsersShowsQueryProps) => ({
suspense: true,
queryKey: KEY({ list, showType, session }),
initialPageParam: '1',
queryFn: ({ pageParam = '1' }: { pageParam?: string }) =>
movieAdvisor
.get<TMDBPagination<Movie>>(`/account/null/${list}/${showType === 'tv' ? 'tv' : 'movies'}`, {
params: { page: pageParam, sort_by: 'created_at.desc', session_id: session },
preventCache: true
})
.then((response) => mapMoviesSeriesResponseToShows(response, showType))
});
export default usersShowsQuery;