diff --git a/app/api/refresh/route.ts b/app/api/refresh/route.ts index 6fc564d..a58731f 100644 --- a/app/api/refresh/route.ts +++ b/app/api/refresh/route.ts @@ -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=), 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'); diff --git a/app/api/subtitles/[fileId]/route.ts b/app/api/subtitles/[fileId]/route.ts new file mode 100644 index 0000000..7cbc953 --- /dev/null +++ b/app/api/subtitles/[fileId]/route.ts @@ -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(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 }); + } +} diff --git a/app/api/subtitles/route.ts b/app/api/subtitles/route.ts new file mode 100644 index 0000000..ea9e4cc --- /dev/null +++ b/app/api/subtitles/route.ts @@ -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 }); + } +} diff --git a/app/server-sitemap.xml/route.ts b/app/server-sitemap.xml/route.ts index 6d7579c..5088407 100644 --- a/app/server-sitemap.xml/route.ts +++ b/app/server-sitemap.xml/route.ts @@ -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): 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)[]) => { const entries = new Map(); diff --git a/components/Poster/components/Handlers/index.tsx b/components/Poster/components/Handlers/index.tsx index 9135b98..015561d 100644 --- a/components/Poster/components/Handlers/index.tsx +++ b/components/Poster/components/Handlers/index.tsx @@ -14,7 +14,6 @@ interface Props { const Handlers: FC = ({ 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) => { if (!onClick) return; diff --git a/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx b/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx index e6f12f8..bb2808d 100644 --- a/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx +++ b/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx @@ -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, 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 ? ( diff --git a/components/Preview/components/Torrents/components/Player/components/Menu/index.tsx b/components/Preview/components/Torrents/components/Player/components/Menu/index.tsx index 7f1e953..40e491e 100644 --- a/components/Preview/components/Torrents/components/Player/components/Menu/index.tsx +++ b/components/Preview/components/Torrents/components/Player/components/Menu/index.tsx @@ -64,7 +64,7 @@ const components: VirtuosoProps['components'] = { const index = props['data-index']; return ( -
option.onSelect(option.value)}> +
option.onSelect(option.value)}> {!index &&
}
; + episodes?: string; onStreamError?: (reason?: string) => void; } -const Player: FC = ({ magnet, playlist, subtitles, onStreamError }) => { +const Player: FC = ({ magnet, playlist, subtitles, show, episodes, onStreamError }) => { const setCanPlay = useSetCanPlay(); const { index, setIndex } = useSource({ magnet }); @@ -49,8 +52,27 @@ const Player: FC = ({ 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 = ({ 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 = ({ magnet, playlist, subtitles, onStreamError }) => { className={cn('relative size-full select-none')} > - {subtitles.map((track, index) => ( + {tracks.map((track, index) => ( ))} diff --git a/components/Preview/components/Torrents/components/Player/useGstAudio.ts b/components/Preview/components/Torrents/components/Player/useGstAudio.ts index d636460..f987ef4 100644 --- a/components/Preview/components/Torrents/components/Player/useGstAudio.ts +++ b/components/Preview/components/Torrents/components/Player/useGstAudio.ts @@ -35,13 +35,11 @@ export const useGstAudio = (src?: string) => { const { data: tracks = [], error } = useQuery({ 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 diff --git a/components/Preview/components/Torrents/components/Player/useSubtitles.ts b/components/Preview/components/Torrents/components/Player/useSubtitles.ts new file mode 100644 index 0000000..12b71e2 --- /dev/null +++ b/components/Preview/components/Torrents/components/Player/useSubtitles.ts @@ -0,0 +1,41 @@ +import { useQuery } from '@tanstack/react-query'; + +import { parseSeasonEpisode } from '@/lib/utils'; + +interface Props { + show?: Show & Partial
; + 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({ + 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 ?? []; +}; diff --git a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/components/Player/index.tsx b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/components/Player/index.tsx index d085d9c..ce03f95 100644 --- a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/components/Player/index.tsx +++ b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/components/Player/index.tsx @@ -14,9 +14,11 @@ interface Props extends InstanceProps { backdrop: string; title: string; magnet: string; + show?: Show & Partial
; + 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 (
- {/* 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 */}
)} @@ -62,7 +64,6 @@ const showPlayerModal = create(({ onResolve, hash, backdrop, title, magnet }: Pr {!streamError && (!isReady || !canPlay) && (
{title} - {/* dark cover recedes from the centre out to the top and bottom edges as it preloads */}
= ({ 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 = ({ 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=): 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=): 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 = ({ 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'} > diff --git a/components/Preview/components/Torrents/components/TorrentsTable/index.tsx b/components/Preview/components/Torrents/components/TorrentsTable/index.tsx index e2f7d6f..ec2b478 100644 --- a/components/Preview/components/Torrents/components/TorrentsTable/index.tsx +++ b/components/Preview/components/Torrents/components/TorrentsTable/index.tsx @@ -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 = ({ 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); diff --git a/components/Preview/components/Torrents/index.tsx b/components/Preview/components/Torrents/index.tsx index 7f2d322..a288458 100644 --- a/components/Preview/components/Torrents/index.tsx +++ b/components/Preview/components/Torrents/index.tsx @@ -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({ diff --git a/components/Preview/components/Torrents/usePinnedTorrents.ts b/components/Preview/components/Torrents/usePinnedTorrents.ts index 67f0c96..edd8bff 100644 --- a/components/Preview/components/Torrents/usePinnedTorrents.ts +++ b/components/Preview/components/Torrents/usePinnedTorrents.ts @@ -5,8 +5,6 @@ const pinnedAtom = atomWithStorage('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>('pinned-magnets', {}, undefined, { unstable_getOnInit: true }); diff --git a/components/Preview/components/Torrents/useUnplayable.ts b/components/Preview/components/Torrents/useUnplayable.ts index 9d23b8f..20eb2ee 100644 --- a/components/Preview/components/Torrents/useUnplayable.ts +++ b/components/Preview/components/Torrents/useUnplayable.ts @@ -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>('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 = () => { diff --git a/data/clients/openSubtitles.ts b/data/clients/openSubtitles.ts new file mode 100644 index 0000000..4844613 --- /dev/null +++ b/data/clients/openSubtitles.ts @@ -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 => { + if (!OPENSUBTITLES_USERNAME || !OPENSUBTITLES_PASSWORD) return null; + + if (memoryToken && memoryToken.expires > Date.now()) return memoryToken.token; + + const cached = await redis?.get(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 => { + 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>((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 => { + 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(); +}; diff --git a/data/parsers/tlk/index.ts b/data/parsers/tlk/index.ts index 898d178..136161b 100644 --- a/data/parsers/tlk/index.ts +++ b/data/parsers/tlk/index.ts @@ -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); diff --git a/data/parsers/tlk/title.ts b/data/parsers/tlk/title.ts index 623e7fe..2a4eedf 100644 --- a/data/parsers/tlk/title.ts +++ b/data/parsers/tlk/title.ts @@ -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}` : ''}`; diff --git a/env.example b/env.example index a37d02a..aa0ff24 100644 --- a/env.example +++ b/env.example @@ -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 \ No newline at end of file diff --git a/env.ts b/env.ts index bef7705..a878fe4 100644 --- a/env.ts +++ b/env.ts @@ -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; diff --git a/lib/queryClient.ts b/lib/queryClient.ts index f0f8b0d..13a8037 100644 --- a/lib/queryClient.ts +++ b/lib/queryClient.ts @@ -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(); } } diff --git a/lib/utils.ts b/lib/utils.ts index 7eaaad5..97f1c1a 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -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) => { 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; diff --git a/types.d.ts b/types.d.ts index 745d11d..54134d6 100644 --- a/types.d.ts +++ b/types.d.ts @@ -214,6 +214,7 @@ interface Source { name: string; src: string; type: string; + lang?: string; } interface Sources {