feat: multi-language subtitle support (SRT/VTT)

This commit is contained in:
Nice Try
2026-06-26 20:12:48 +00:00
parent 33e5e61b11
commit 7d0f976da0
6 changed files with 98 additions and 6 deletions
+1 -1
View File
@@ -457,7 +457,7 @@ Supported video extensions include common browser-playable formats such as `.mp4
### Subtitles
OfflineAcademy supports subtitle files stored beside the matching video. Use `.vtt` for the best browser compatibility; `.srt` files are detected as best-effort tracks.
OfflineAcademy supports subtitle files stored beside the matching video. `.vtt` files are served directly; `.srt` files are detected and converted to browser-compatible WebVTT when served to the video player.
Single subtitle track:
+18 -1
View File
@@ -1,8 +1,9 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { existsSync, statSync, createReadStream } from 'fs'
import { readFile } from 'fs/promises'
import { join, resolve } from 'path'
import { getCoursesRootPath } from '@/lib/scanner'
import { convertSrtToVtt } from '@/lib/subtitles'
export async function GET(
request: NextRequest,
@@ -79,6 +80,22 @@ export async function GET(
txt: 'text/plain; charset=utf-8',
}
const contentType = mimeTypes[actualExt || ''] || 'application/octet-stream'
// Browsers expect WebVTT for <track>. Serve .srt subtitles as converted WebVTT.
if (actualExt === 'srt') {
const srtContent = await readFile(actualPath, 'utf8')
const vttContent = convertSrtToVtt(srtContent)
return new NextResponse(vttContent, {
status: 200,
headers: {
'Content-Length': Buffer.byteLength(vttContent, 'utf8').toString(),
'Content-Type': 'text/vtt; charset=utf-8',
'Cache-Control': 'no-cache',
'Content-Disposition': `inline; filename="${actualPath.split('/').pop()?.replace(/\.srt$/i, '.vtt')}"`,
'X-Content-Type-Options': 'nosniff',
},
})
}
// Handle range requests (video seeking)
if (range) {
+28
View File
@@ -410,6 +410,18 @@ export function VideoPlayer({
}
}, [selectedSubtitle, subtitles])
const hasSubtitles = Boolean(subtitles && subtitles.length > 0)
const captionsEnabled = selectedSubtitle !== 'off'
const toggleCaptions = () => {
if (!hasSubtitles) return
if (captionsEnabled) {
setSelectedSubtitle('off')
return
}
const defaultIndex = subtitles?.findIndex(track => track.default) ?? -1
setSelectedSubtitle(defaultIndex >= 0 ? defaultIndex : 0)
}
return (
<div
className="video-player-container"
@@ -563,6 +575,22 @@ export function VideoPlayer({
/>
</div>
{hasSubtitles && (
<Button
variant="ghost"
size="icon"
className={cn(
'text-white hover:bg-white/20 font-bold text-xs',
captionsEnabled && 'bg-primary text-primary-foreground hover:bg-primary/90'
)}
onClick={toggleCaptions}
aria-label={captionsEnabled ? 'Turn captions off' : 'Turn captions on'}
title={captionsEnabled ? 'Captions on' : 'Captions off'}
>
CC
</Button>
)}
{/* Fullscreen - FIRST */}
<Button
variant="ghost"
+26
View File
@@ -142,3 +142,29 @@ export function sortSubtitleTracks(tracks: SubtitleTrackInput[]): SubtitleTrackI
return a.label.localeCompare(b.label)
})
}
export function convertSrtToVtt(content: string): string {
const normalized = content
.replace(/^\uFEFF/, '')
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
.trim()
if (!normalized) return 'WEBVTT\n\n'
if (normalized.startsWith('WEBVTT')) return normalized.endsWith('\n') ? normalized : `${normalized}\n`
const vttBody = normalized
.split('\n')
.map(line => {
if (/^\d+$/.test(line.trim())) return ''
return line.replace(
/(\d{2}:\d{2}:\d{2}),(\d{3})\s+-->\s+(\d{2}:\d{2}:\d{2}),(\d{3})/g,
'$1.$2 --> $3.$4'
)
})
.join('\n')
.replace(/\n{3,}/g, '\n\n')
.trim()
return `WEBVTT\n\n${vttBody}\n`
}
+19 -3
View File
@@ -1,7 +1,7 @@
// OfflineAcademy Service Worker v3Minimal, Chrome-install-criteria focused
// OfflineAcademy Service Worker v4Offline support without stale Next.js dev chunks
// Logs to console so you can verify it's controlling the page
const CACHE = "oa-v5"
const CACHE = "oa-v6"
const ASSETS = [
'/',
'/site.webmanifest',
@@ -29,6 +29,22 @@ self.addEventListener('fetch', e => {
const url = new URL(e.request.url)
console.log('[SW] Fetch:', url.pathname)
// Never cache Next.js runtime/dev chunks or HMR/RSC payloads. Stale chunks can keep old runtime errors alive.
if (
url.pathname.startsWith('/_next/') ||
url.pathname === '/__nextjs_original-stack-frame' ||
url.pathname === '/__nextjs_launch-editor'
) {
e.respondWith(fetch(e.request))
return
}
// Keep analytics fully live while debugging/runtime data is dynamic.
if (url.pathname === '/analytics') {
e.respondWith(fetch(e.request))
return
}
// Navigation (main page) — network first, cache fallback
if (e.request.mode === 'navigate') {
e.respondWith(networkFirst(e.request))
@@ -86,4 +102,4 @@ self.addEventListener('message', e => {
}
})
console.log('[SW] Loaded - version 3')
console.log('[SW] Loaded - version 4')
+6 -1
View File
@@ -1,4 +1,4 @@
import { buildSubtitleTrackMap, languageCodeToLabel, normalizeSubtitleLang } from '@/lib/subtitles'
import { buildSubtitleTrackMap, convertSrtToVtt, languageCodeToLabel, normalizeSubtitleLang } from '@/lib/subtitles'
function assert(condition: unknown, message: string) {
if (!condition) {
@@ -34,4 +34,9 @@ assert(normalizeSubtitleLang('PT-br') === 'pt-BR', 'pt-BR normalization failed')
assert(languageCodeToLabel('fil') === 'Filipino', 'Filipino label failed')
assert(!tracks.has('unrelated'), 'unrelated subtitle should not create a track group')
const converted = convertSrtToVtt('1\n00:00:01,250 --> 00:00:04,500\nHello captions\n')
assert(converted.startsWith('WEBVTT'), 'SRT conversion should emit WEBVTT header')
assert(converted.includes('00:00:01.250 --> 00:00:04.500'), 'SRT conversion should rewrite comma timestamps')
assert(!converted.includes('00:00:01,250'), 'SRT conversion should not keep comma timestamps')
console.log('subtitle parser verification passed')