feat(torrents): add 0day.community tracker as a torrent provider
Private xbtit tracker (tracker.0day.community): session login via takelogin.php with cookie jar persisted to Redis, cp1251-decoded word-AND search scoped to movie/TV categories, magnet built from the fetched .torrent (download.php requires the name param) + public trackers. Generalizes /api/magnet to dispatch by provider.
This commit is contained in:
1 parent
87513bb6a8
commit
1fd8f0f7e5
11 files changed
+291
-11
No files matched your search
@@ -1,12 +1,14 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import odc from '@/data/parsers/odc';
|
||||
import tlk from '@/data/parsers/tlk';
|
||||
|
||||
export async function GET({ nextUrl: { searchParams } }: NextRequest) {
|
||||
const url = searchParams.get('url') as string;
|
||||
const provider = searchParams.get('provider') as string;
|
||||
|
||||
try {
|
||||
return NextResponse.json(await tlk.magnet(url));
|
||||
return NextResponse.json(provider === 'odc' ? await odc.magnet(url) : await tlk.magnet(url));
|
||||
} catch (error) {
|
||||
return NextResponse.error();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { Sort } from '@/data/parsers';
|
||||
import odc from '@/data/parsers/odc';
|
||||
import tlk from '@/data/parsers/tlk';
|
||||
import tpb from '@/data/parsers/tpb';
|
||||
import yts from '@/data/parsers/yts';
|
||||
@@ -15,7 +16,7 @@ export async function GET({ nextUrl: { searchParams } }: NextRequest) {
|
||||
const sort = searchParams.get('sort') as Sort;
|
||||
const type = searchParams.get('type') as 'movie' | 'tv' | null;
|
||||
|
||||
const providers = { yts, tpb, tlk };
|
||||
const providers = { yts, tpb, tlk, odc };
|
||||
|
||||
try {
|
||||
const torrents = await providers[key].search({ imdbID, query, sort, type: type ?? undefined });
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
|
||||
return !container || /mp4|mkv|webm|mov|m4v|avi|ts/.test(container);
|
||||
}, [torrent, provider]);
|
||||
|
||||
const fetchMagnet = useMagnet(torrent);
|
||||
const fetchMagnet = useMagnet(torrent, provider);
|
||||
|
||||
const { savedMagnet, rememberMagnet } = usePinnedTorrents();
|
||||
const { isLaunched, launch } = useLaunchedTorrents();
|
||||
|
||||
+6
-2
@@ -1,11 +1,15 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
const useMagnet = (torrent: Torrent) => {
|
||||
const useMagnet = (torrent: Torrent, provider?: string) => {
|
||||
return useMutation({
|
||||
retry: 4,
|
||||
mutationFn: async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/magnet?url=${torrent.download}`);
|
||||
const params = new URLSearchParams({ url: torrent.download as string });
|
||||
|
||||
if (provider) params.set('provider', provider);
|
||||
|
||||
const response = await fetch(`/api/magnet?${params.toString()}`);
|
||||
|
||||
if (!response.ok) return Promise.reject();
|
||||
|
||||
|
||||
@@ -25,5 +25,11 @@ export const providers = {
|
||||
key: 'tlk',
|
||||
queryFn: (options: Options) => queryFn({ ...options, key: 'tlk' }),
|
||||
sortable: true
|
||||
},
|
||||
odc: {
|
||||
label: '0day',
|
||||
key: 'odc',
|
||||
queryFn: (options: Options) => queryFn({ ...options, key: 'odc' }),
|
||||
sortable: true
|
||||
}
|
||||
};
|
||||
@@ -52,10 +52,10 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
|
||||
|
||||
const isSeries = show.type === 'tv';
|
||||
|
||||
// Toloka's search is a plain "contains" word-AND match with no IMDB filter. For movies,
|
||||
// Toloka's and 0day's searches are plain word-AND matches with no IMDB filter. For movies,
|
||||
// scope the query by the show's year to keep, e.g., "Dune" (2021) away from "Dune: Part Two" (2024);
|
||||
// for series the TV sections do the disambiguation and a year suffix would hide other seasons.
|
||||
const tolokaQuery = isSeries ? query : query && Number.isFinite(year) ? `${query} ${year}` : query;
|
||||
const scopedQuery = isSeries ? query : query && Number.isFinite(year) ? `${query} ${year}` : query;
|
||||
|
||||
const tracked = { id: show.id, type: show.type, title: show.title };
|
||||
|
||||
@@ -78,7 +78,7 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
|
||||
show: tracked
|
||||
});
|
||||
const tlk = useTorrents({
|
||||
query: tolokaQuery,
|
||||
query: scopedQuery,
|
||||
queryFn: providers.tlk.queryFn,
|
||||
sort,
|
||||
key: providers.tlk.key,
|
||||
@@ -86,8 +86,17 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
|
||||
type: show.type,
|
||||
show: tracked
|
||||
});
|
||||
const odc = useTorrents({
|
||||
query: scopedQuery,
|
||||
queryFn: providers.odc.queryFn,
|
||||
sort,
|
||||
key: providers.odc.key,
|
||||
imdbID: show.imdb_id!,
|
||||
type: show.type,
|
||||
show: tracked
|
||||
});
|
||||
|
||||
const queries = { yts, tpb, tlk };
|
||||
const queries = { yts, tpb, tlk, odc };
|
||||
|
||||
const { order, ...dndProps } = useProvidersOrder();
|
||||
|
||||
@@ -117,7 +126,7 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
|
||||
<Button
|
||||
type='submit'
|
||||
className='h-full !px-3 transition-all duration-200 hover:bg-secondary-foreground hover:shadow-lg hover:shadow-secondary-foreground/60'
|
||||
disabled={tpb.isPending || tlk.isPending}
|
||||
disabled={tpb.isPending || tlk.isPending || odc.isPending}
|
||||
>
|
||||
<Search size={16} />
|
||||
</Button>
|
||||
@@ -126,7 +135,7 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
|
||||
<Tabs defaultValue={tabs[0].provider.key} className='w-full rounded-none px-2'>
|
||||
<DndContext {...dndProps}>
|
||||
<SortableContext items={visibleOrder} strategy={horizontalListSortingStrategy}>
|
||||
<TabsList className={cn('grid w-full', isSeries ? 'grid-cols-2' : 'grid-cols-3')}>
|
||||
<TabsList className={cn('grid w-full', isSeries ? 'grid-cols-3' : 'grid-cols-4')}>
|
||||
{tabs.map(({ provider, query }) => (
|
||||
<SortableTabsTrigger key={provider.key} provider={provider} isLoading={query.isLoading} />
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import axios, { AxiosError, AxiosInstance } from 'axios';
|
||||
import { wrapper } from 'axios-cookiejar-support';
|
||||
import { load } from 'cheerio';
|
||||
import iconv from 'iconv-lite';
|
||||
import parseTorrent, { Instance } from 'parse-torrent';
|
||||
import { Cookie, CookieJar, SerializedCookieJar } from 'tough-cookie';
|
||||
|
||||
import redis from '@/data/clients/redis';
|
||||
import { ODC_HOST, ODC_PASSWORD, ODC_USERNAME } from '@/env';
|
||||
|
||||
import { Sort, TRACKERS } from '../index';
|
||||
import { parseTolokaTitle } from '../tlk/title';
|
||||
|
||||
const COOKIE_JAR_KEY = 'odc:cookie-jar';
|
||||
const ENCODING = 'windows-1251';
|
||||
|
||||
type ShowType = 'movie' | 'tv';
|
||||
|
||||
// Category ids: movies (Фільми, HD Фільми, Мультфільми, HD Мультфільми),
|
||||
// TV (Телесеріали, HD Серіали, Мультсеріали).
|
||||
const MOVIE_CATEGORIES = [10, 16, 11, 27];
|
||||
const TV_CATEGORIES = [19, 30, 29];
|
||||
|
||||
const redisWarn = (message: string, error: unknown) =>
|
||||
console.warn(message, error instanceof Error ? error.message.split(', command was:')[0] : error);
|
||||
|
||||
export class ZeroDay {
|
||||
private client: AxiosInstance;
|
||||
private host: string;
|
||||
private sort = {
|
||||
[Sort.size]: 5,
|
||||
[Sort.seeds]: 7
|
||||
};
|
||||
|
||||
private cookieJar = new CookieJar();
|
||||
|
||||
private hydration?: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
this.host = ODC_HOST || 'https://tracker.0day.community';
|
||||
|
||||
this.client = wrapper(
|
||||
axios.create({
|
||||
jar: this.cookieJar,
|
||||
baseURL: this.host,
|
||||
withCredentials: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private decode(data: ArrayBuffer): string {
|
||||
return iconv.decode(Buffer.from(data), ENCODING);
|
||||
}
|
||||
|
||||
private async isAuthorized(data: ArrayBuffer) {
|
||||
return !load(this.decode(data))('[href="/login.php"]').length;
|
||||
}
|
||||
|
||||
private hydrate() {
|
||||
this.hydration ??= (async () => {
|
||||
if (!redis) return;
|
||||
|
||||
const serialized = await redis.get<SerializedCookieJar>(COOKIE_JAR_KEY);
|
||||
const cookies = serialized?.cookies || [];
|
||||
|
||||
for (const data of cookies) {
|
||||
const cookie = Cookie.fromJSON(data);
|
||||
|
||||
if (cookie) await this.cookieJar.store.putCookie(cookie);
|
||||
}
|
||||
|
||||
console.info(`[odc] restored ${cookies.length} session cookies from Redis`);
|
||||
})().catch((error) => {
|
||||
redisWarn('Failed to restore 0day session from Redis:', error);
|
||||
});
|
||||
|
||||
return this.hydration;
|
||||
}
|
||||
|
||||
private async persist() {
|
||||
if (!redis) return;
|
||||
|
||||
try {
|
||||
await redis.set(COOKIE_JAR_KEY, await this.cookieJar.serialize());
|
||||
|
||||
console.info('[odc] session persisted to Redis');
|
||||
} catch (error) {
|
||||
redisWarn('Failed to persist 0day session to Redis:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private async auth() {
|
||||
console.info('[odc] logging in to 0day.community');
|
||||
|
||||
const body = new URLSearchParams();
|
||||
|
||||
body.append('username', ODC_USERNAME as string);
|
||||
body.append('password', ODC_PASSWORD as string);
|
||||
|
||||
await this.client.post('/takelogin.php', body.toString(), {
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
|
||||
});
|
||||
|
||||
await this.persist();
|
||||
}
|
||||
|
||||
private buildSearchUrl(query: string, categories: number[], sort: Sort) {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
params.append('search', query);
|
||||
params.append('incldead', '0');
|
||||
params.append('where', '0');
|
||||
|
||||
for (const category of categories) params.append(`c${category}`, 'on');
|
||||
|
||||
params.append('sort', this.sort[sort].toString());
|
||||
params.append('type', 'desc');
|
||||
|
||||
return `/browse.php?${params.toString()}`;
|
||||
}
|
||||
|
||||
private async fetchPage(url: string) {
|
||||
try {
|
||||
return await this.client.get(url, { responseType: 'arraybuffer' });
|
||||
} catch (error) {
|
||||
const response = error instanceof AxiosError ? error.response : undefined;
|
||||
|
||||
if (response?.status !== 429) throw error;
|
||||
|
||||
const retryAfter = Math.min(Number(response.headers['retry-after']) || 10, 30);
|
||||
|
||||
console.warn(`[odc] rate limited by 0day.community, retrying in ${retryAfter}s`);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
|
||||
|
||||
return this.client.get(url, { responseType: 'arraybuffer' });
|
||||
}
|
||||
}
|
||||
|
||||
private async runSearch(url: string): Promise<Torrent[]> {
|
||||
const parseTorrents = (data: string) => {
|
||||
const $ = load(data);
|
||||
const rows = $('tr.rowtorrentinfo');
|
||||
|
||||
return rows
|
||||
.map((_, row) => {
|
||||
const titleLink = $(row).find('td:nth-child(2) a[href^="details.php"]');
|
||||
const originalTitle = titleLink.text();
|
||||
const size = $(row)
|
||||
.find('td:nth-child(4)')
|
||||
.html()
|
||||
?.replace(/<br\s*\/?>/gi, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
const seeders = $(row).find('td:nth-child(6) a[href$="toseeders=1"]').text();
|
||||
const download = $(row).find('td:nth-child(2) a[href^="download.php"]').attr('href');
|
||||
const id = titleLink.attr('href')?.match(/id=(\d+)/)?.[1];
|
||||
|
||||
const { year, source, codec, container, title, resolution, episodes } = parseTolokaTitle(originalTitle || '');
|
||||
|
||||
return {
|
||||
year: year?.toString(),
|
||||
source,
|
||||
codec,
|
||||
container,
|
||||
originalTitle,
|
||||
title,
|
||||
episodes,
|
||||
id: id || title,
|
||||
size,
|
||||
seeders: parseInt(seeders || '0'),
|
||||
quality: resolution,
|
||||
magnet: '',
|
||||
download
|
||||
};
|
||||
})
|
||||
.get();
|
||||
};
|
||||
|
||||
let page = await this.fetchPage(url);
|
||||
|
||||
if (await this.isAuthorized(page.data)) return parseTorrents(this.decode(page.data));
|
||||
|
||||
await this.auth();
|
||||
|
||||
page = await this.fetchPage(url);
|
||||
|
||||
return parseTorrents(this.decode(page.data));
|
||||
}
|
||||
|
||||
async search({
|
||||
query,
|
||||
sort = Sort.size,
|
||||
type
|
||||
}: {
|
||||
query: string;
|
||||
sort?: Sort;
|
||||
type?: ShowType;
|
||||
imdbID?: string;
|
||||
}): Promise<Torrent[]> {
|
||||
await this.hydrate();
|
||||
|
||||
const categories = type === 'tv' ? TV_CATEGORIES : type === 'movie' ? MOVIE_CATEGORIES : [];
|
||||
|
||||
const search = (searchQuery: string) => this.runSearch(this.buildSearchUrl(searchQuery, categories, sort));
|
||||
|
||||
let torrents = await search(query);
|
||||
|
||||
if (!torrents.length) {
|
||||
// The query is scoped by the show's year to disambiguate sequels, but the TMDB
|
||||
// release year can differ from the year in release names, so fall back to the bare title.
|
||||
const fallback = query.replace(/\s\d{4}$/, '');
|
||||
|
||||
if (fallback !== query) torrents = await search(fallback);
|
||||
}
|
||||
|
||||
return torrents;
|
||||
}
|
||||
|
||||
async magnet(url: string) {
|
||||
await this.hydrate();
|
||||
|
||||
const path = url.startsWith('http') || url.startsWith('/') ? url : `/${url}`;
|
||||
|
||||
const fetchTorrent = async () => {
|
||||
const { data } = await this.client.get(path, { responseType: 'arraybuffer' });
|
||||
|
||||
return parseTorrent(data);
|
||||
};
|
||||
|
||||
let torrent: Instance;
|
||||
|
||||
try {
|
||||
torrent = (await fetchTorrent()) as Instance;
|
||||
} catch (_) {
|
||||
await this.auth();
|
||||
|
||||
torrent = (await fetchTorrent()) as Instance;
|
||||
}
|
||||
|
||||
const trackers = TRACKERS.map((tracker) => `&tr=${encodeURIComponent(tracker)}`).join('');
|
||||
|
||||
return `magnet:?xt=urn:btih:${torrent.infoHash}&dn=${encodeURIComponent(torrent.name?.toString() || '')}${trackers}`;
|
||||
}
|
||||
}
|
||||
|
||||
const parser = new ZeroDay();
|
||||
|
||||
export default parser;
|
||||
@@ -4,6 +4,9 @@ YTS_HOST=https://yts.mx/api/v2/list_movies.json
|
||||
TOLOKA_HOST=https://toloka.to
|
||||
TOLOKA_USERNAME=your_toloka_username
|
||||
TOLOKA_PASSWORD=your_toloka_password
|
||||
ODC_HOST=https://tracker.0day.community
|
||||
ODC_USERNAME=your_0day_username
|
||||
ODC_PASSWORD=your_0day_password
|
||||
NEXT_PUBLIC_TORRENT_PROXY=http://localhost:8090
|
||||
# Optional: external subtitles in the web player — free API key at https://www.opensubtitles.com/en/consumers
|
||||
OPENSUBTITLES_API_KEY=your_api_key
|
||||
|
||||
@@ -19,6 +19,10 @@ export const TOLOKA_PASSWORD = process.env.TOLOKA_PASSWORD;
|
||||
export const PIRATE_BAY_HOST = process.env.PIRATE_BAY_HOST;
|
||||
export const YTS_HOST = process.env.YTS_HOST;
|
||||
|
||||
export const ODC_HOST = process.env.ODC_HOST;
|
||||
export const ODC_USERNAME = process.env.ODC_USERNAME;
|
||||
export const ODC_PASSWORD = process.env.ODC_PASSWORD;
|
||||
|
||||
export const OPENSUBTITLES_API_URL = process.env.OPENSUBTITLES_API_URL || 'https://api.opensubtitles.com/api/v1';
|
||||
export const OPENSUBTITLES_API_KEY = process.env.OPENSUBTITLES_API_KEY;
|
||||
export const OPENSUBTITLES_USERNAME = process.env.OPENSUBTITLES_USERNAME;
|
||||
|
||||
Generated
+1
@@ -26,6 +26,7 @@
|
||||
"cheerio": "^1.0.0",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.0.0",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"jotai": "^2.2.2",
|
||||
"js-cookie": "^3.0.5",
|
||||
"lucide-react": "^0.453.0",
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"cheerio": "^1.0.0",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.0.0",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"jotai": "^2.2.2",
|
||||
"js-cookie": "^3.0.5",
|
||||
"lucide-react": "^0.453.0",
|
||||
|
||||
Reference in new issue
Block a user