feat(tlk): cartoon/anime sections and alias-aware search
This commit is contained in:
1 parent
c2947bed32
commit
75880e5ac7
3 files changed
+134
-11
No files matched your search
@@ -0,0 +1,22 @@
|
||||
// Toloka release names often carry the original (romanized) title instead of the English one,
|
||||
// so "attack on titan" does not match "Shingeki no Kyojin (Season 1) ...". Keys are normalized
|
||||
// TMDB titles (lowercase, straight apostrophes folded to U+2019, no trailing year/period); values
|
||||
// are the queries to additionally run against Toloka.
|
||||
const ALIASES: Record<string, string> = {
|
||||
'attack on titan': 'shingeki no kyojin',
|
||||
'fire force': 'enen no shouboutai',
|
||||
'howl’s moving castle': 'ugoku shiro',
|
||||
'princess mononoke': 'mononoke hime',
|
||||
'spirited away': 'sen to chihiro',
|
||||
'your name': 'kimi no na wa'
|
||||
};
|
||||
|
||||
export const normalizeQuery = (query: string) =>
|
||||
query
|
||||
.toLowerCase()
|
||||
.replace(/'/g, '’')
|
||||
.replace(/\s\d{4}$/, '')
|
||||
.replace(/\.$/, '')
|
||||
.trim();
|
||||
|
||||
export const aliasFor = (query: string) => ALIASES[normalizeQuery(query)];
|
||||
+110
-11
@@ -1,14 +1,16 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import axios, { AxiosError, AxiosInstance } from 'axios';
|
||||
import { wrapper } from 'axios-cookiejar-support';
|
||||
import { load } from 'cheerio';
|
||||
import parseTorrent, { Instance } from 'parse-torrent';
|
||||
import { Cookie, CookieJar, SerializedCookieJar } from 'tough-cookie';
|
||||
|
||||
import movieAdvisor from '@/data/clients/movieAdvisor';
|
||||
import redis from '@/data/clients/redis';
|
||||
import { TOLOKA_HOST, TOLOKA_PASSWORD, TOLOKA_USERNAME } from '@/env';
|
||||
|
||||
import { Sort, TRACKERS } from '../index';
|
||||
|
||||
import { aliasFor, normalizeQuery } from './aliases';
|
||||
import { parseTolokaTitle } from './title';
|
||||
|
||||
const COOKIE_JAR_KEY = 'toloka:cookie-jar';
|
||||
@@ -16,13 +18,23 @@ const COOKIE_JAR_KEY = 'toloka:cookie-jar';
|
||||
type ShowType = 'movie' | 'tv';
|
||||
|
||||
// Section ids for the `f[]` search filter: the movie/TV sets keep releases of the
|
||||
// other media type (and non-video sections) out of the results.
|
||||
const MOVIE_SECTIONS = [16, 42, 55, 70, 96, 129];
|
||||
const TV_SECTIONS = [32, 124, 173, 192];
|
||||
// other media type (and non-video sections) out of the results. Cartoons and anime
|
||||
// live in their own sections (Мультфільми/Мультсеріали, Аніме); the anime sections
|
||||
// mix films and series, so they are whitelisted in both sets.
|
||||
const MOVIE_SECTIONS = [16, 19, 42, 55, 70, 84, 96, 127, 129, 139, 193, 194];
|
||||
const TV_SECTIONS = [32, 44, 124, 125, 127, 173, 174, 192, 194, 195];
|
||||
|
||||
const redisWarn = (message: string, error: unknown) =>
|
||||
console.warn(message, error instanceof Error ? error.message.split(', command was:')[0] : error);
|
||||
|
||||
const SIZE_UNITS: Record<string, number> = { B: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3, TB: 1024 ** 4 };
|
||||
|
||||
const parseSize = (size?: string) => {
|
||||
const [value, unit] = (size || '').trim().split(/\s+/);
|
||||
|
||||
return Number.parseFloat(value) * (SIZE_UNITS[unit] ?? 1) || 0;
|
||||
};
|
||||
|
||||
export class Toloka {
|
||||
private client: AxiosInstance;
|
||||
private host: string;
|
||||
@@ -113,9 +125,25 @@ export class Toloka {
|
||||
return `/tracker.php?${params.toString()}`;
|
||||
}
|
||||
|
||||
private async runSearch(url: string): Promise<Torrent[]> {
|
||||
const fetchPage = () => this.client.get(url);
|
||||
private async fetchPage(url: string) {
|
||||
try {
|
||||
return await this.client.get(url);
|
||||
} 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(`[tlk] rate limited by Toloka, retrying in ${retryAfter}s`);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
|
||||
|
||||
return this.client.get(url);
|
||||
}
|
||||
}
|
||||
|
||||
private async runSearch(url: string): Promise<Torrent[]> {
|
||||
const parseTorrents = (data: string) => {
|
||||
const $ = load(data);
|
||||
const rows = $('.prow1, .prow2');
|
||||
@@ -148,25 +176,43 @@ export class Toloka {
|
||||
.get();
|
||||
};
|
||||
|
||||
let page = await fetchPage();
|
||||
let page = await this.fetchPage(url);
|
||||
|
||||
if (await this.isAuthorized(page.data)) return parseTorrents(page.data);
|
||||
|
||||
await this.auth();
|
||||
|
||||
page = await fetchPage();
|
||||
page = await this.fetchPage(url);
|
||||
|
||||
return parseTorrents(page.data);
|
||||
}
|
||||
|
||||
async search({ query, sort = Sort.size, type }: { query: string; sort?: Sort; type?: ShowType }): Promise<Torrent[]> {
|
||||
async search({
|
||||
query,
|
||||
sort = Sort.size,
|
||||
type,
|
||||
imdbID
|
||||
}: {
|
||||
query: string;
|
||||
sort?: Sort;
|
||||
type?: ShowType;
|
||||
imdbID?: string;
|
||||
}): Promise<Torrent[]> {
|
||||
await this.hydrate();
|
||||
|
||||
const sections = type === 'tv' ? TV_SECTIONS : type === 'movie' ? MOVIE_SECTIONS : [];
|
||||
|
||||
const search = (searchQuery: string) => this.runSearch(this.buildSearchUrl(searchQuery, sections, sort));
|
||||
|
||||
const torrents = await search(query);
|
||||
let torrents = await search(query);
|
||||
|
||||
const alias = aliasFor(query);
|
||||
|
||||
if (alias) {
|
||||
const aliased = await search(this.scoped(alias, query, type));
|
||||
|
||||
if (aliased.length) torrents = this.merge(torrents, aliased, sort);
|
||||
}
|
||||
|
||||
if (torrents.length) return torrents;
|
||||
|
||||
@@ -174,7 +220,60 @@ export class Toloka {
|
||||
// release year can differ from the year in release names, so fall back to the bare title.
|
||||
const fallback = query.replace(/\s\d{4}$/, '');
|
||||
|
||||
return fallback === query ? torrents : search(fallback);
|
||||
if (fallback !== query) {
|
||||
const bare = await search(fallback);
|
||||
|
||||
if (bare.length) return bare;
|
||||
}
|
||||
|
||||
const original = await this.originalName(imdbID, type, query);
|
||||
|
||||
if (original && original.toLowerCase() !== fallback.toLowerCase()) {
|
||||
torrents = await search(this.scoped(original, query, type));
|
||||
}
|
||||
|
||||
return torrents;
|
||||
}
|
||||
|
||||
private scoped(query: string, source: string, type?: ShowType) {
|
||||
const year = /\s(\d{4})$/.exec(source)?.[1];
|
||||
|
||||
return type === 'movie' && year && !query.includes(year) ? `${query} ${year}` : query;
|
||||
}
|
||||
|
||||
private merge(base: Torrent[], extra: Torrent[], sort: Sort): Torrent[] {
|
||||
if (!extra.length) return base;
|
||||
|
||||
const seen = new Set(base.map((torrent) => torrent.id));
|
||||
const merged = [...base, ...extra.filter((torrent) => !seen.has(torrent.id))];
|
||||
|
||||
return sort === Sort.size
|
||||
? merged.sort((a, b) => parseSize(b.size) - parseSize(a.size))
|
||||
: merged.sort((a, b) => b.seeders - a.seeders);
|
||||
}
|
||||
|
||||
private async originalName(imdbID: string | undefined, type: ShowType | undefined, query: string): Promise<string> {
|
||||
const media = type === 'tv' ? 'tv' : type === 'movie' ? 'movie' : '';
|
||||
|
||||
if (!imdbID || !media) return '';
|
||||
|
||||
try {
|
||||
const { name, original_name, original_title, title } = await movieAdvisor.get<{
|
||||
name?: string;
|
||||
original_name?: string;
|
||||
original_title?: string;
|
||||
title?: string;
|
||||
}>(`/${media}/${imdbID}`, { params: { external_ids: imdbID } });
|
||||
|
||||
const showTitle = title || name;
|
||||
|
||||
// Only fall back to the original name for the show's own title, not for manual queries.
|
||||
if (!showTitle || normalizeQuery(query) !== normalizeQuery(showTitle)) return '';
|
||||
|
||||
return original_title || original_name || '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
async magnet(url: string) {
|
||||
|
||||
Reference in new issue
Block a user