feat(player): external subtitles via OpenSubtitles

Add an OpenSubtitles client, /api/subtitles routes and useSubtitles to
fetch subtitles by show/episode/filename, wire them as player tracks
alongside embedded ones, and strip hls.js's auto-added tracks. New
OPENSUBTITLES_* / SUBTITLE_LANGUAGES env vars (documented in env.example).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
nerandClaude Opus 4.8 committed 2026-08-08 13:17:12 +03:00
1 parent c695697c4f
commit ecc57ff135
24 files changed
+372 -67

No files matched your search

-5
View File
@@ -3,11 +3,6 @@ import { NextRequest, NextResponse } from 'next/server';
import tlk from '@/data/parsers/tlk';
import { STREAM_URL } from '@/env';
// Public proxy the TV calls to re-pull a Toloka thread's CURRENT magnet.
// Given a Toloka topic/thread id (the `id` in download.php?id=<id>), it
// re-downloads the thread's .torrent server-side (auth handled by the Toloka
// client) and returns a fresh magnet + the derived stream m3u. The TV holds
// only the numeric id — never Toloka's authenticated URL.
export async function GET({ nextUrl: { searchParams } }: NextRequest) {
const tid = searchParams.get('tid');
+39
View File
@@ -0,0 +1,39 @@
import { NextResponse } from 'next/server';
import { downloadSubtitle } from '@/data/clients/openSubtitles';
import redis from '@/data/clients/redis';
type SubtitleParams = {
params: {
fileId: string;
};
};
const CACHE_TTL = 60 * 60 * 24 * 30;
export async function GET(_: Request, { params: { fileId } }: SubtitleParams) {
const id = fileId.replace(/\.vtt$/i, '');
if (!/^\d+$/.test(id)) {
return NextResponse.json({ error: 'Invalid subtitle file id' }, { status: 400 });
}
const key = `subtitles:${id}`;
try {
const cached = await redis?.get<string>(key).catch(() => null);
const content = cached ?? (await downloadSubtitle(Number(id)));
if (!cached) await redis?.set(key, content, { ex: CACHE_TTL }).catch(() => null);
return new NextResponse(content, {
headers: {
'Content-Type': 'text/vtt; charset=utf-8',
'Cache-Control': 'public, max-age=31536000, immutable'
}
});
} catch (error) {
console.error('[subtitles] download', error);
return NextResponse.json({ error: 'Failed to download subtitle' }, { status: 502 });
}
}
+34
View File
@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from 'next/server';
import { searchSubtitles } from '@/data/clients/openSubtitles';
import { SUBTITLE_LANGUAGES } from '@/env';
export async function GET({ nextUrl: { searchParams } }: NextRequest) {
const imdbId = searchParams.get('imdb_id') || undefined;
const tmdbId = searchParams.get('tmdb_id') || undefined;
if (!imdbId && !tmdbId) {
return NextResponse.json({ error: 'imdb_id or tmdb_id is required' }, { status: 400 });
}
const season = searchParams.get('season');
const episode = searchParams.get('episode');
try {
const subtitles = await searchSubtitles({
type: searchParams.get('type') === 'tv' ? 'tv' : 'movie',
imdbId,
tmdbId,
season: season ? Number(season) : undefined,
episode: episode ? Number(episode) : undefined,
languages: searchParams.get('languages') || SUBTITLE_LANGUAGES
});
return NextResponse.json(subtitles, {
headers: { 'Cache-Control': 'public, s-maxage=86400, stale-while-revalidate=86400' }
});
} catch (error) {
console.error('[subtitles] search', error);
return NextResponse.json({ error: 'Failed to search subtitles' }, { status: 502 });
}
}
-2
View File
@@ -9,7 +9,6 @@ const LIST_PAGES = 25;
const PERSON_PAGES = 10;
const BATCH_SIZE = 20;
// Mirrors the discover filters used by the /popular and /top pages (data/queries/popular.ts)
const DISCOVER_FILTERS = {
'vote_count.gte': '300',
'vote_average.gte': '5',
@@ -36,7 +35,6 @@ const fetchEntries = async (path: string, params: Record<string, string>): Promi
return results.map(({ id, title, name }) => ({ id, title: title || name || '' }));
};
// TMDB allows ~50 requests per second, so the task list is drained in small batches
const collectEntries = async (tasks: (() => Promise<Entry[]>)[]) => {
const entries = new Map<number, string>();
@@ -14,7 +14,6 @@ interface Props {
const Handlers: FC<Props> = ({ href, onClick, show }) => {
const { mutate } = useMutateShowState(show);
// The link exists for crawlers and new-tab clicks; a plain click opens the preview modal in place
const handleClick = (event: MouseEvent<HTMLElement>) => {
if (!onClick) return;
@@ -1,4 +1,4 @@
import { useMemo } from 'react';
import { useMemo, useRef } from 'react';
import { CaptionOption, useCaptionOptions } from '@vidstack/react';
import { ClosedCaptionsIcon, ClosedCaptionsOnIcon } from '@vidstack/react/icons';
@@ -9,6 +9,9 @@ import PlayerMenu from '../Menu';
const CaptionsMenu = () => {
const tracks = useCaptionOptions();
const live = useRef(tracks);
live.current = tracks;
const captions = useMemo(() => {
const record = tracks.reduce<Record<string, CaptionOption>>((record, track) => {
record[track.value] = track;
@@ -27,7 +30,7 @@ const CaptionsMenu = () => {
options={captions.map((track) => ({
label: track.label,
value: track.value,
onSelect: () => track.select()
onSelect: (value) => (live.current.find((option) => option.value === value) ?? track).select()
}))}
>
{tracks.selectedTrack ? (
@@ -64,7 +64,7 @@ const components: VirtuosoProps<Option, string>['components'] = {
const index = props['data-index'];
return (
<div {...props} key={option.label} title={option.label} onClick={() => option.onSelect(option.value)}>
<div {...props} key={option.value} title={option.label} onClick={() => option.onSelect(option.value)}>
{!index && <div className='h-2 w-full' />}
<div
className={cn(
@@ -23,6 +23,7 @@ import Captions from './components/Captions';
import Playlist from './components/Playlist';
import { useGstAudio } from './useGstAudio';
import useSource from './useSource';
import { useSubtitles } from './useSubtitles';
import '@vidstack/react/player/styles/plyr/theme.css';
@@ -30,10 +31,12 @@ interface Props {
magnet: string;
subtitles: Source[];
playlist: Source[];
show?: Show & Partial<Details>;
episodes?: string;
onStreamError?: (reason?: string) => void;
}
const Player: FC<Props> = ({ magnet, playlist, subtitles, onStreamError }) => {
const Player: FC<Props> = ({ magnet, playlist, subtitles, show, episodes, onStreamError }) => {
const setCanPlay = useSetCanPlay();
const { index, setIndex } = useSource({ magnet });
@@ -49,8 +52,27 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles, onStreamError }) => {
setIndex((index) => index + 1);
}, [isEnded, hasNext, setIndex]);
useEffect(() => {
const textTracks = player.current?.textTracks;
if (!textTracks) return;
const removeHlsTracks = () => {
for (const track of textTracks.toArray()) {
if (track.id.startsWith('hls-')) textTracks.remove(track);
}
};
removeHlsTracks();
textTracks.addEventListener('add', removeHlsTracks);
return () => textTracks.removeEventListener('add', removeHlsTracks);
}, []);
const source = playlist[index];
const externalSubtitles = useSubtitles({ show, episodes, filename: source?.name });
const tracks = useMemo(() => [...subtitles, ...externalSubtitles], [subtitles, externalSubtitles]);
const { tracks: audioTracks, audio, setAudio, resolvedSrc, error } = useGstAudio(source?.src);
const resumeTime = useRef(0);
@@ -60,7 +82,6 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles, onStreamError }) => {
setAudio(track);
};
// report the transcoder rejection up to the modal and stop hls.js from retrying a dead stream
useEffect(() => {
onStreamError?.(error);
}, [error, onStreamError]);
@@ -102,15 +123,16 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles, onStreamError }) => {
className={cn('relative size-full select-none')}
>
<MediaProvider className='relative flex size-full justify-center [&>video]:!h-full'>
{subtitles.map((track, index) => (
{tracks.map((track, index) => (
<Track
key={track.name}
key={track.src}
src={track.src}
kind='subtitles'
label={track.name}
type='srt'
default={!index}
id={track.name}
lang={track.lang}
type={track.type as 'srt' | 'vtt'}
default={!index && !!subtitles.length}
id={track.src}
/>
))}
</MediaProvider>
@@ -35,13 +35,11 @@ export const useGstAudio = (src?: string) => {
const { data: tracks = [], error } = useQuery<GstAudioTrack[]>({
enabled: Boolean(hash && index),
// a rejected codec/container won't change on retry
retry: false,
queryKey: ['gst-audio', hash, index],
queryFn: async () => {
const response = await fetch(`${base}/gst/${hash}/probe?index=${index}`);
// the transcoder answers 5xx with a plain-text reason, e.g. "unsupported video codec"
if (!response.ok) throw new Error((await response.text()).trim() || `stream error ${response.status}`);
const data: { Tracks?: ProbeTrack[] } = await response.json();
@@ -54,7 +52,6 @@ export const useGstAudio = (src?: string) => {
const reason = error instanceof Error ? error.message : undefined;
// codec/container rejections are permanent for this backend — remember them to grey out Play
useEffect(() => {
if (reason && /unsupported (video codec|container)/i.test(reason)) markUnplayable(hash, reason);
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -0,0 +1,41 @@
import { useQuery } from '@tanstack/react-query';
import { parseSeasonEpisode } from '@/lib/utils';
interface Props {
show?: Show & Partial<Details>;
episodes?: string;
filename?: string;
}
export const useSubtitles = ({ show, episodes, filename }: Props): Source[] => {
const fromFile = parseSeasonEpisode(filename);
const fromTorrent = parseSeasonEpisode(episodes);
const season = fromFile.season ?? fromTorrent.season;
const episode = fromFile.episode ?? fromTorrent.episode;
const isSeries = show?.type === 'tv';
const enabled = Boolean(show?.id && (!isSeries || (season != null && episode != null)));
const { data } = useQuery<Source[]>({
enabled,
staleTime: Infinity,
retry: false,
queryKey: ['subtitles', show?.type, show?.id, season, episode],
queryFn: () => {
const params = new URLSearchParams({ type: show!.type, tmdb_id: show!.id.toString() });
if (show!.imdb_id) params.set('imdb_id', show!.imdb_id);
if (isSeries) {
params.set('season', season!.toString());
params.set('episode', episode!.toString());
}
return fetch(`/api/subtitles?${params}`).then((response) => (response.ok ? response.json() : []));
}
});
return data ?? [];
};
@@ -14,9 +14,11 @@ interface Props extends InstanceProps<void> {
backdrop: string;
title: string;
magnet: string;
show?: Show & Partial<Details>;
episodes?: string;
}
const showPlayerModal = create(({ onResolve, hash, backdrop, title, magnet }: Props) => {
const showPlayerModal = create(({ onResolve, hash, backdrop, title, magnet, show, episodes }: Props) => {
const canPlay = useCanPlay();
const setCanPlay = useSetCanPlay();
const { isReady, preloadingProgress, downloadSpeed } = useStats({ hash, canPlay });
@@ -33,8 +35,6 @@ const showPlayerModal = create(({ onResolve, hash, backdrop, title, magnet }: Pr
return (
<Modal className='overflow-hidden border-none bg-black p-0' onClose={handleClose}>
<div className='relative w-full overflow-hidden rounded-xl pt-[56.25%]'>
{/* keep the player mounted (Safari needs it for autoplay) but hidden until buffering is done,
so its UI doesn't flash through the splash screen */}
<div
className={cn('absolute left-0 top-0 size-full', {
'pointer-events-none opacity-0': streamError || !isReady || !canPlay
@@ -45,6 +45,8 @@ const showPlayerModal = create(({ onResolve, hash, backdrop, title, magnet }: Pr
magnet={magnet}
playlist={sources.playlist}
subtitles={sources.subtitles}
show={show}
episodes={episodes}
onStreamError={setStreamError}
/>
)}
@@ -62,7 +64,6 @@ const showPlayerModal = create(({ onResolve, hash, backdrop, title, magnet }: Pr
{!streamError && (!isReady || !canPlay) && (
<div className='absolute left-0 top-0 size-full overflow-hidden rounded-xl'>
<img src={backdrop} className='absolute left-0 top-0 size-full' alt={title} />
{/* dark cover recedes from the centre out to the top and bottom edges as it preloads */}
<div
className='absolute inset-x-0 top-0 bg-black/60 transition-[height] duration-700 ease-out'
style={{ height: `${(100 - (canPlay ? 100 : preloadingProgress)) / 2}%` }}
@@ -52,21 +52,17 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
const key = torrentKey(torrent);
const pinned = isPinned(key);
// savedMagnet keeps a pinned Toloka torrent playable after a reload without re-fetching
const magnet = fetchMagnet.data || torrent.magnet || savedMagnet(key) || '';
const hash = getMagnetHash(magnet);
// a release that already failed transcoding stays greyed out so we don't hit the same 502 twice
const unplayable = reasonFor(hash);
// persist the fetched magnet while pinned; only Toloka needs it (others carry it in the result)
useEffect(() => {
if (pinned && magnet && !torrent.magnet) rememberMagnet(key, magnet);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pinned, magnet, key, torrent.magnet]);
// starting to watch a torrent pins it to the top for next time
const pinPlayed = () => pin(key);
const supportedForCast = prefix && !prefix.includes('{host}');
@@ -87,21 +83,20 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
runtime: show.runtime?.toString() ?? ''
});
// This app's origin — the TV calls back to /api/subtitles (and, for Toloka
// series, /api/refresh) here. Distinct from the m3u stream host.
params.set('app', window.location.origin);
if (show.type === 'tv') {
const season = seasonFromEpisodes(torrent.episodes) ?? show.airing?.season;
if (season != null) params.set('season', season.toString());
// Toloka thread id (download.php?id=<id>): the TV stores it and later
// asks movie-advisor's /api/refresh to re-pull the thread's current
// magnet, so a still-airing season picks up new episodes on its own.
// Toloka thread id (download.php?id=<id>): the TV stores it and later asks
// movie-advisor's /api/refresh to re-pull the thread's current magnet, so
// a still-airing season picks up new episodes on its own.
if (provider === providers.tlk.key && torrent.download) {
const tid = new URLSearchParams(torrent.download.split('?')[1] || '').get('id');
if (tid) {
params.set('tlk', tid);
// where /api/refresh lives (this app's origin) — distinct from the
// m3u stream host, so the TV knows which host to call back.
params.set('app', window.location.origin);
}
if (tid) params.set('tlk', tid);
}
}
@@ -135,7 +130,7 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
)}
onClick={() => {
pinPlayed();
showPlayerModal({ backdrop: show.backdrop, title, hash, magnet });
showPlayerModal({ backdrop: show.backdrop, title, hash, magnet, show, episodes: torrent.episodes });
}}
title={unplayable ? `Can’t stream in browser: ${unplayable}` : 'Play'}
>
@@ -13,7 +13,6 @@ 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)
@@ -47,13 +46,11 @@ const TorrentsTable: FC<Props> = ({ title, torrents, show, sort, sortable, provi
})
: torrents;
// pinned (previously played) torrents stick to the top, keeping their order within each group
const rows = [
...sorted.filter((torrent) => isPinned(torrentKey(torrent))),
...sorted.filter((torrent) => !isPinned(torrentKey(torrent)))
];
// 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);
@@ -50,7 +50,6 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
const year = new Date(show.release).getFullYear();
// YTS is a movies-only API, so it has nothing to offer for series
const isSeries = show.type === 'tv';
const yts = useTorrents({
@@ -5,8 +5,6 @@ const pinnedAtom = atomWithStorage<string[]>('pinned-torrents', [], undefined, {
unstable_getOnInit: true
});
// Toloka magnets are fetched lazily, so cache the fetched magnet of a pinned torrent
// to keep it playable right after a reload without hitting Toloka again
const magnetsAtom = atomWithStorage<Record<string, string>>('pinned-magnets', {}, undefined, {
unstable_getOnInit: true
});
@@ -1,14 +1,10 @@
import { useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
// Some releases use a video codec/container the TorrServer transcoder can't handle
// (e.g. VC-1 remuxes, AVI). Those fail with a 502 only when you actually press Play, so
// remember them by infohash to grey out Play instead of hitting the same dead-end again.
const unplayableAtom = atomWithStorage<Record<string, string>>('unplayable-torrents', {}, undefined, {
unstable_getOnInit: true
});
// getMagnetHash uppercases, the /gst URL hash is lowercase — normalise so both sides match
const normalize = (hash?: string) => hash?.toLowerCase();
const useUnplayable = () => {
+188
View File
@@ -0,0 +1,188 @@
import { OPENSUBTITLES_API_KEY, OPENSUBTITLES_API_URL, OPENSUBTITLES_PASSWORD, OPENSUBTITLES_USERNAME } from '@/env';
import redis from './redis';
const USER_AGENT = 'movie-advisor v1.0';
const TOKEN_KEY = 'opensubtitles:token';
const TOKEN_TTL = 60 * 60 * 20;
const PER_LANGUAGE = 3;
interface OSFile {
file_id: number;
file_name: string;
}
interface OSSubtitle {
attributes: {
language: string | null;
release: string;
download_count: number;
hearing_impaired: boolean;
machine_translated: boolean;
files: OSFile[];
};
}
interface SearchParams {
type: Show['type'];
imdbId?: string;
tmdbId?: string;
season?: number;
episode?: number;
languages: string;
}
interface Token {
token: string;
expires: number;
}
const headers = () => ({
'Api-Key': OPENSUBTITLES_API_KEY ?? '',
'User-Agent': USER_AGENT,
'Content-Type': 'application/json',
Accept: 'application/json'
});
let memoryToken: Token | null = null;
const login = async (): Promise<string | null> => {
if (!OPENSUBTITLES_USERNAME || !OPENSUBTITLES_PASSWORD) return null;
if (memoryToken && memoryToken.expires > Date.now()) return memoryToken.token;
const cached = await redis?.get<Token>(TOKEN_KEY).catch(() => null);
if (cached && cached.expires > Date.now()) {
memoryToken = cached;
return cached.token;
}
const response = await fetch(`${OPENSUBTITLES_API_URL}/login`, {
method: 'POST',
headers: headers(),
body: JSON.stringify({ username: OPENSUBTITLES_USERNAME, password: OPENSUBTITLES_PASSWORD }),
cache: 'no-store'
});
if (!response.ok) return null;
const { token }: { token: string } = await response.json();
memoryToken = { token, expires: Date.now() + TOKEN_TTL * 1000 };
await redis?.set(TOKEN_KEY, memoryToken, { ex: TOKEN_TTL }).catch(() => null);
return token;
};
const languageName = (code: string) => {
try {
return new Intl.DisplayNames(['en'], { type: 'language' }).of(code) || code;
} catch {
return code;
}
};
const numericId = (value?: string) => {
const digits = value?.replace(/\D/g, '');
return digits ? String(Number(digits)) : undefined;
};
export const searchSubtitles = async ({
type,
imdbId,
tmdbId,
season,
episode,
languages
}: SearchParams): Promise<Source[]> => {
if (!OPENSUBTITLES_API_KEY) return [];
const params = new URLSearchParams({ languages: languages.toLowerCase() });
const imdb = numericId(imdbId);
if (type === 'tv') {
if (imdb) params.set('parent_imdb_id', imdb);
else if (tmdbId) params.set('parent_tmdb_id', tmdbId);
if (season != null) params.set('season_number', season.toString());
if (episode != null) params.set('episode_number', episode.toString());
} else {
if (imdb) params.set('imdb_id', imdb);
else if (tmdbId) params.set('tmdb_id', tmdbId);
}
params.sort();
const response = await fetch(`${OPENSUBTITLES_API_URL}/subtitles?${params}`, {
headers: headers(),
next: { revalidate: 86400 }
});
if (!response.ok) {
throw new Error(`OpenSubtitles search failed: ${response.status} ${await response.text().catch(() => '')}`);
}
const { data }: { data: OSSubtitle[] } = await response.json();
const requested = languages.toLowerCase().split(',');
const grouped = data.reduce<Record<string, OSSubtitle['attributes'][]>>((grouped, { attributes }) => {
const language = attributes.language?.toLowerCase();
if (!language || attributes.machine_translated || !attributes.files.length) return grouped;
(grouped[language] ??= []).push(attributes);
return grouped;
}, {});
const sources = requested
.filter((language) => grouped[language])
.flatMap((language) =>
grouped[language]
.sort((a, b) => b.download_count - a.download_count)
.slice(0, PER_LANGUAGE)
.map((attributes) => {
const [file] = attributes.files;
const release = (attributes.release || file.file_name).slice(0, 50);
return {
name: `${languageName(language)} · ${release}${attributes.hearing_impaired ? ' · HI' : ''}`,
src: `/api/subtitles/${file.file_id}`,
type: 'vtt',
lang: language
};
})
);
return sources.filter(({ name }, index) => sources.findIndex((source) => source.name === name) === index);
};
export const downloadSubtitle = async (fileId: number): Promise<string> => {
if (!OPENSUBTITLES_API_KEY) throw new Error('OpenSubtitles API key is not configured');
const token = await login();
const response = await fetch(`${OPENSUBTITLES_API_URL}/download`, {
method: 'POST',
headers: { ...headers(), ...(token && { Authorization: `Bearer ${token}` }) },
body: JSON.stringify({ file_id: fileId, sub_format: 'webvtt' }),
cache: 'no-store'
});
if (!response.ok) {
throw new Error(
`OpenSubtitles download request failed: ${response.status} ${await response.text().catch(() => '')}`
);
}
const { link }: { link: string } = await response.json();
const file = await fetch(link, { cache: 'no-store' });
if (!file.ok) throw new Error(`OpenSubtitles file fetch failed: ${file.status}`);
return file.text();
};
-1
View File
@@ -13,7 +13,6 @@ import { parseTolokaTitle } from './title';
const COOKIE_JAR_KEY = 'toloka:cookie-jar';
// UpstashError messages embed the full command, including cookie values — never log them
const redisWarn = (message: string, error: unknown) =>
console.warn(message, error instanceof Error ? error.message.split(', command was:')[0] : error);
-9
View File
@@ -1,18 +1,11 @@
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) => {
@@ -22,7 +15,6 @@ export const parseTolokaTitle = (originalTitle: string) => {
.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) {
@@ -33,7 +25,6 @@ export const parseTolokaTitle = (originalTitle: string) => {
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}` : ''}`;
+7
View File
@@ -5,6 +5,13 @@ TOLOKA_HOST=https://toloka.to
TOLOKA_USERNAME=your_toloka_username
TOLOKA_PASSWORD=your_toloka_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
# Optional: logging in raises the download quota (anonymous keys get ~5 downloads/day)
OPENSUBTITLES_USERNAME=your_opensubtitles_username
OPENSUBTITLES_PASSWORD=your_opensubtitles_password
# Comma-separated preferred subtitle languages (ISO 639-1)
SUBTITLE_LANGUAGES=en,uk
# Optional: persists the Toloka session across serverless cold starts (falls back to in-memory)
UPSTASH_REDIS_REST_URL=https://your-db.upstash.io
UPSTASH_REDIS_REST_TOKEN=your_upstash_token
+6
View File
@@ -19,5 +19,11 @@ 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 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;
export const OPENSUBTITLES_PASSWORD = process.env.OPENSUBTITLES_PASSWORD;
export const SUBTITLE_LANGUAGES = process.env.SUBTITLE_LANGUAGES || 'en,uk';
export const UPSTASH_REDIS_REST_URL = process.env.UPSTASH_REDIS_REST_URL || process.env.KV_REST_API_URL;
export const UPSTASH_REDIS_REST_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || process.env.KV_REST_API_TOKEN;
-4
View File
@@ -16,8 +16,6 @@ const makeQueryClient = () => {
let browserQueryClient: QueryClient | undefined = undefined;
// One client per server request (React cache is request-scoped), so generateMetadata
// and the page share fetches instead of hitting TMDB twice for the same data.
const getServerQueryClient = cache(makeQueryClient);
const getQueryClient = () => {
@@ -25,8 +23,6 @@ const getQueryClient = () => {
try {
return getServerQueryClient();
} catch (_) {
// cache() only works in the RSC runtime; the SSR pass of client components
// (e.g. Providers) lands here and keeps its own per-render client as before
return makeQueryClient();
}
}
+7 -4
View File
@@ -13,8 +13,6 @@ export const slugify = (value: string) =>
.slice(0, 60)
.replace(/-+$/, '');
// Keyword-carrying show URL (/movie/27205-inception); the slug is optional decoration —
// routing only relies on the leading numeric id.
export const showPath = ({ type, id, title }: Pick<Show, 'type' | 'id' | 'title'>) => {
const slug = slugify(title || '');
@@ -50,11 +48,16 @@ export const getMagnetHash = (link: string) => {
return hash?.toUpperCase();
};
// Stable identity for a torrent that survives the lazy empty -> fetched magnet transition:
// Toloka has a permanent download URL, the rest always carry a magnet infohash.
export const torrentKey = (torrent: Torrent) =>
torrent.download || getMagnetHash(torrent.magnet) || torrent.hash || torrent.id;
export const parseSeasonEpisode = (value?: string): { season?: number; episode?: number } => {
const [, season, episode] =
value?.match(/S(\d{1,2})[ ._-]*E(\d{1,3})/i) || value?.match(/\b(\d{1,2})x(\d{2,3})\b/) || [];
return season ? { season: Number(season), episode: Number(episode) } : {};
};
export const seasonFromEpisodes = (episodes?: string): number | undefined => {
if (!episodes) return undefined;
if (/^S\d+\s*[-–—]\s*\d+/i.test(episodes)) return undefined;
Vendored
+1
View File
@@ -214,6 +214,7 @@ interface Source {
name: string;
src: string;
type: string;
lang?: string;
}
interface Sources {