From 1fd8f0f7e514558d3c5549d536c2036e7ab06bcc Mon Sep 17 00:00:00 2001 From: ner Date: Sun, 25 Oct 2026 17:09:51 +0200 Subject: [PATCH] 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. --- app/api/magnet/route.ts | 4 +- app/api/torrents/route.ts | 3 +- .../components/Actions/index.tsx | 2 +- .../components/Actions/useMagnet.ts | 8 +- .../Preview/components/Torrents/constants.ts | 6 + .../Preview/components/Torrents/index.tsx | 21 +- data/parsers/odc/index.ts | 249 ++++++++++++++++++ env.example | 3 + env.ts | 4 + package-lock.json | 1 + package.json | 1 + 11 files changed, 291 insertions(+), 11 deletions(-) create mode 100644 data/parsers/odc/index.ts diff --git a/app/api/magnet/route.ts b/app/api/magnet/route.ts index df46411..c491ad8 100644 --- a/app/api/magnet/route.ts +++ b/app/api/magnet/route.ts @@ -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(); } diff --git a/app/api/torrents/route.ts b/app/api/torrents/route.ts index 90e7dbd..a7e7ca6 100644 --- a/app/api/torrents/route.ts +++ b/app/api/torrents/route.ts @@ -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 }); diff --git a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx index 8ea4f0a..bac64f6 100644 --- a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx +++ b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx @@ -52,7 +52,7 @@ const Actions: FC = ({ 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(); diff --git a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/useMagnet.ts b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/useMagnet.ts index cc6fb67..c6aadc7 100644 --- a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/useMagnet.ts +++ b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/useMagnet.ts @@ -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(); diff --git a/components/Preview/components/Torrents/constants.ts b/components/Preview/components/Torrents/constants.ts index f91472a..5966234 100644 --- a/components/Preview/components/Torrents/constants.ts +++ b/components/Preview/components/Torrents/constants.ts @@ -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 } }; diff --git a/components/Preview/components/Torrents/index.tsx b/components/Preview/components/Torrents/index.tsx index 00abfa7..04bb099 100644 --- a/components/Preview/components/Torrents/index.tsx +++ b/components/Preview/components/Torrents/index.tsx @@ -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) => { @@ -126,7 +135,7 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => { - + {tabs.map(({ provider, query }) => ( ))} diff --git a/data/parsers/odc/index.ts b/data/parsers/odc/index.ts new file mode 100644 index 0000000..39073aa --- /dev/null +++ b/data/parsers/odc/index.ts @@ -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; + + 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(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 { + 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(//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 { + 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; diff --git a/env.example b/env.example index 34f583e..d80550d 100644 --- a/env.example +++ b/env.example @@ -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 diff --git a/env.ts b/env.ts index 79456ec..c98974b 100644 --- a/env.ts +++ b/env.ts @@ -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; diff --git a/package-lock.json b/package-lock.json index 0276ef5..889fb3e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index b01f01b..4be14fd 100644 --- a/package.json +++ b/package.json @@ -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",