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:
1 parent
c695697c4f
commit
ecc57ff135
24 files changed
+372
-67
No files matched your search
@@ -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;
|
||||
|
||||
|
||||
+5
-2
@@ -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 ?? [];
|
||||
};
|
||||
+5
-4
@@ -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}%` }}
|
||||
|
||||
+9
-14
@@ -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 = () => {
|
||||
|
||||
Reference in new issue
Block a user