feat(torrents): series parsing, S:E/Year columns, magnet cache

- parse Toloka Ukrainian season/episode naming (Сезони 1-10,
  серій 7 з 8, homoglyphs) into a clean title + episodes field
- add series-only sortable S:E column, desktop-only Year column;
  strip year/source meta from the title cell
- filter out torrents with fewer than 5 seeders in the API route
- cache Toloka magnets in Redis so each .torrent is downloaded once
  across serverless instances; append public trackers to magnets
  (never the passkey-bearing announce URLs from the .torrent)
- fix play button hover state while magnet is pending

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
nerandClaude Fable 5 committed 2026-08-06 22:14:58 +03:00
1 parent 131beeb07f
commit 2e81908b22
9 files changed
+163 -34

No files matched your search

+5 -1
View File
@@ -5,6 +5,8 @@ import tlk from '@/data/parsers/tlk';
import tpb from '@/data/parsers/tpb';
import yts from '@/data/parsers/yts';
const MIN_SEEDERS = 5;
export async function GET({ nextUrl: { searchParams } }: NextRequest) {
const key = searchParams.get('key') as keyof typeof providers;
@@ -15,7 +17,9 @@ export async function GET({ nextUrl: { searchParams } }: NextRequest) {
const providers = { yts, tpb, tlk };
try {
return NextResponse.json(await providers[key].search({ imdbID, query, sort }));
const torrents = await providers[key].search({ imdbID, query, sort });
return NextResponse.json(torrents.filter((torrent) => torrent.seeders >= MIN_SEEDERS));
} catch (_) {
return NextResponse.json([]);
}
@@ -86,7 +86,7 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
className={cn(
'flex-grow-0 px-3 bg-red-600',
'hover:shadow-lg hover:shadow-red-600/60 duration-200 transition-all hover:bg-red-600',
{ 'bg-transparent': !magnet || fetchMagnet.isPending }
{ invisible: !magnet || fetchMagnet.isPending }
)}
onClick={() => {
showPlayerModal({ backdrop: show.backdrop, title, hash, magnet });
@@ -1,13 +1,23 @@
import { FC, Fragment } from 'react';
import { FC, Fragment, useState } from 'react';
import { ArrowDownIcon } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Sort } from '@/data/parsers';
import { cn } from '@/lib/utils';
import showHostManagerModal from '../HostManager';
import TableHeadSortable from '../TableHeadSortable';
import Actions from './components/Actions';
type EpisodesSort = 'asc' | 'desc';
// "S3:E7/8" -> [3, 7]; "S1-9" -> [1, 0]; missing info sorts last
const seasonEpisode = (episodes?: string): [number, number] => [
Number(episodes?.match(/S(\d+)/)?.[1] ?? 9999),
Number(episodes?.match(/E(\d+)/)?.[1] ?? 0)
];
type Props = {
show: Show & Partial<Details>;
title: string;
@@ -19,8 +29,28 @@ type Props = {
};
const TorrentsTable: FC<Props> = ({ title, torrents, show, sort, sortable, provider, onChangeSort }) => {
const colSpan = 5;
const year = new Date(show.release).getFullYear();
const isSeries = show.type === 'tv';
const colSpan = 7;
const [episodesSort, setEpisodesSort] = useState<EpisodesSort | null>(null);
const rows = episodesSort
? [...torrents].sort((a, b) => {
const [seasonA, episodeA] = seasonEpisode(a.episodes);
const [seasonB, episodeB] = seasonEpisode(b.episodes);
const diff = seasonA - seasonB || episodeA - episodeB;
return episodesSort === 'asc' ? diff : -diff;
})
: torrents;
// server sort (size/seeds) refetches in a new order, so drop the client-side S:E sort
const handleChangeSort = (next: Sort) => {
setEpisodesSort(null);
onChangeSort(next);
};
const toggleEpisodesSort = () => setEpisodesSort((current) => (current === 'asc' ? 'desc' : 'asc'));
return (
<Table className='overflow-hidden rounded-xl'>
@@ -28,15 +58,32 @@ const TorrentsTable: FC<Props> = ({ title, torrents, show, sort, sortable, provi
<TableHeader>
<TableRow className='hover:bg-transparent'>
<TableHead className='hidden px-2 md:table-cell'>Title</TableHead>
{isSeries && (
<TableHead className='hidden cursor-pointer select-none px-2 md:table-cell' onClick={toggleEpisodesSort}>
<div className='flex items-center gap-1'>
<span>S:E</span>
{episodesSort && (
<ArrowDownIcon className={cn('ml-2 size-4 shrink-0', episodesSort === 'asc' && 'rotate-180')} />
)}
</div>
</TableHead>
)}
<TableHead className='hidden px-2 lg:table-cell'>Year</TableHead>
<TableHead className='hidden px-2 md:table-cell'>Resolution</TableHead>
<TableHeadSortable sortable={sortable} title='Size' sort={Sort.size} value={sort} onChange={onChangeSort} />
<TableHeadSortable
sortable={sortable}
title='Size'
sort={Sort.size}
value={sort}
onChange={handleChangeSort}
/>
<TableHeadSortable
sortable={sortable}
title='Seeders'
className='max-w-10'
sort={Sort.seeds}
value={sort}
onChange={onChangeSort}
onChange={handleChangeSort}
/>
<TableHead className='cursor-pointer select-none px-2' onClick={() => showHostManagerModal()} />
</TableRow>
@@ -44,21 +91,28 @@ const TorrentsTable: FC<Props> = ({ title, torrents, show, sort, sortable, provi
)}
<TableBody>
{torrents?.map((torrent) => {
const yearView = torrent.year && year.toString() != torrent.year && `[${torrent.year}]`;
{rows?.map((torrent) => {
return (
<Fragment key={torrent.magnet + torrent.id + torrent.download}>
<TableRow className='table-row border-b-0 hover:bg-transparent md:hidden'>
<TableCell className='break-all p-2' colSpan={colSpan}>
<span className='flex w-full flex-wrap items-center gap-3'>
{torrent.title} {yearView} {torrent.quality && `[${torrent.quality}]`}
{torrent.title} {isSeries && torrent.episodes && `[${torrent.episodes}]`}{' '}
{torrent.quality && `[${torrent.quality}]`}
</span>
</TableCell>
</TableRow>
<TableRow className='hover:bg-transparent'>
<TableCell className='hidden break-all p-2 md:table-cell' title={torrent.originalTitle}>
{torrent.title} {yearView}{' '}
<span className='uppercase'>{torrent.source && `[${torrent.source}]`}</span>
{torrent.title}
</TableCell>
{isSeries && (
<TableCell className='hidden p-2 md:table-cell'>
<div className='flex shrink-0 items-center gap-1'>{torrent.episodes}</div>
</TableCell>
)}
<TableCell className='hidden p-2 lg:table-cell'>
<div className='flex shrink-0 items-center gap-1'>{torrent.year}</div>
</TableCell>
<TableCell className='hidden p-2 md:table-cell'>
<div className='flex shrink-0 items-center gap-1'>{torrent.quality}</div>
+11
View File
@@ -2,3 +2,14 @@ export enum Sort {
size = 'size',
seeds = 'seeds'
}
export 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'
];
+34 -8
View File
@@ -2,15 +2,17 @@ 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 { Cookie, CookieJar, SerializedCookieJar } from 'tough-cookie';
import redis from '@/data/clients/redis';
import { TOLOKA_HOST, TOLOKA_PASSWORD, TOLOKA_USERNAME } from '@/env';
import { Sort } from '../index';
import { Sort, TRACKERS } from '../index';
import { parseTolokaTitle } from './title';
const COOKIE_JAR_KEY = 'toloka:cookie-jar';
const MAGNET_KEY_PREFIX = 'toloka:magnet:';
// UpstashError messages embed the full command, including cookie values — never log them
const redisWarn = (message: string, error: unknown) =>
@@ -113,9 +115,7 @@ export class Toloka {
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 || ''
);
const { year, source, codec, container, title, resolution, episodes } = parseTolokaTitle(originalTitle || '');
return {
year: year?.toString(),
@@ -123,7 +123,8 @@ export class Toloka {
codec,
container,
originalTitle,
title: `${title}${season && episode ? ` [S${season}:E${episode}]` : ''}`,
title,
episodes,
id: originalTitle || '',
size,
seeders: parseInt(seeders || '0'),
@@ -151,6 +152,20 @@ export class Toloka {
await this.hydrate();
// an infohash never changes for a given torrent, so a cached magnet is valid forever
// and saves a .torrent download from Toloka on every cold start
try {
const cached = await redis?.get<string>(`${MAGNET_KEY_PREFIX}${url}`);
if (cached) {
this.magnets[url] = cached;
return cached;
}
} catch (error) {
redisWarn('Failed to read Toloka magnet from Redis:', error);
}
const fetchTorrent = async () => {
const { data: buffer } = await this.client.get(`/${url}`, {
responseType: 'arraybuffer'
@@ -169,11 +184,22 @@ export class Toloka {
torrent = (await fetchTorrent()) as Instance;
}
const magnet = `magnet:?xt=urn:btih:${torrent.infoHash}&dn=${encodeURIComponent(torrent.name?.toString() || '')}`;
console.info(`[tlk] downloaded .torrent for ${url}`);
// the .torrent's own announce URLs embed the account passkey — never expose them in a magnet;
// public trackers help discover cross-seeded peers, the rest is covered by DHT
const trackers = TRACKERS.map((tracker) => `&tr=${encodeURIComponent(tracker)}`).join('');
const magnet = `magnet:?xt=urn:btih:${torrent.infoHash}&dn=${encodeURIComponent(torrent.name?.toString() || '')}${trackers}`;
this.magnets[url] = magnet;
return this.magnets[url];
try {
await redis?.set(`${MAGNET_KEY_PREFIX}${url}`, magnet);
} catch (error) {
redisWarn('Failed to persist Toloka magnet to Redis:', error);
}
return magnet;
}
}
+43
View File
@@ -0,0 +1,43 @@
import torrentTitle from 'parse-torrent-title';
// Toloka series naming comes in several shapes, often bilingual with both parentheticals present:
// "Офіс (Сезон 1) / The Office (Season 1) (2005) BDRemux"
// "Друзі (Сезони 1-10) / Friends (Seasons 1-10) 720p"
// "Дім дракона (Сезон 3, серій 7 з 8) / House of the Dragon [2026] WEB-DL"
// "Томас і його друзі (1—4 сезони, 88 зі 104) / Thomas the Tank Engine & Friends (Seasons 1-4, 88 of 104)"
// "[cс]езон" tolerates the Latin "C" homoglyph some uploaders use
const SEASONS = [
/\(\s*[cс]езон[а-яіїєґ]*\s*(\d+)(?:\s*[-–—−]\s*(\d+))?([^)]*)\)/i,
/\(\s*(\d+)(?:\s*[-–—−]\s*(\d+))?\s*[cс]езон[а-яіїєґ]*([^)]*)\)/i,
/\(\s*seasons?\s*(\d+)(?:\s*[-–—−]\s*(\d+))?([^)]*)\)/i
];
// ", Серії 6-7" | ", серій 7 з 8" | ", 85 серій з 106" | ", 88 зі 104" | ", 88 of 104"
const EPISODES = /,\s*(?:сері[яїй][^\d)]*)?(\d+)(?:\s*[-–—−]\s*(\d+))?(?:[^\d)]*?\s(?:зі?|of)\s*(\d+))?/i;
export const parseTolokaTitle = (originalTitle: string) => {
const seasonMatch = SEASONS.map((pattern) => originalTitle.match(pattern)).find(Boolean);
const cleaned = SEASONS.reduce((title, pattern) => title.replace(pattern, ' '), originalTitle)
.replace(/\s+/g, ' ')
.trim();
const parsed = torrentTitle.parse(cleaned);
// a season parenthetical between the two title parts leaves a dangling separator behind
const title = parsed.title.replace(/\s*[/|]\s*$/, '');
if (!seasonMatch) {
const { season, episode } = parsed;
return { ...parsed, title, episodes: season && episode ? `S${season}:E${episode}` : undefined };
}
const [, seasonFrom, seasonTo, details] = seasonMatch;
const [, from, to, total] = details.match(EPISODES) || [];
// a bare number with no range, no total and no "серія" marker is not episode info (e.g. a year)
const hasEpisodes = from && (to || total || /сері/i.test(details));
const season = `S${seasonFrom}${seasonTo ? `-${seasonTo}` : ''}`;
const episodes = hasEpisodes ? `:E${from}${to ? `-${to}` : ''}${total ? `/${total}` : ''}` : '';
return { ...parsed, title, episodes: `${season}${episodes}` };
};
+2 -1
View File
@@ -68,7 +68,8 @@ export class PirateBay {
codec,
container,
originalTitle,
title: `${title} ${season && episode ? `[S${season}:E${episode}]` : ''}`,
title,
episodes: season && episode ? `S${season}:E${episode}` : undefined,
id: title,
size: sizes[index],
seeders: parseInt(seeders[index] || '0', 10),
+2 -13
View File
@@ -2,7 +2,7 @@ import axios, { AxiosInstance } from 'axios';
import { YTS_HOST } from '@/env';
import { Sort } from '../index';
import { Sort, TRACKERS } from '../index';
import { YTSResponse } from './models';
@@ -42,17 +42,6 @@ export class YTS {
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,
@@ -61,7 +50,7 @@ export class YTS {
quality: torrent.quality,
source: torrent.type,
year: movie.year?.toString(),
magnet: `magnet:?xt=urn:btih:${torrent.hash}&dn=${encodeURIComponent(query)}&tr=${trackers.join('&tr=')}`,
magnet: `magnet:?xt=urn:btih:${torrent.hash}&dn=${encodeURIComponent(query)}&tr=${TRACKERS.join('&tr=')}`,
hash: torrent.hash,
codec: torrent.video_codec
};
Vendored
+1
View File
@@ -205,6 +205,7 @@ interface Torrent {
codec?: string;
container?: string;
year?: string;
episodes?: string;
download?: string;
hash: string;
}