Files
ner 1fd8f0f7e5 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.
2026-10-25 17:09:51 +02:00

250 lines
7.1 KiB
TypeScript

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;