internal/providers/senshi/subtitles.go

242 lines · 6784 bytes

  1package senshi
  2
  3import (
  4	"crypto/sha256"
  5	"fmt"
  6	"io"
  7	"net/http"
  8	"net/url"
  9	"os"
 10	"path/filepath"
 11	"regexp"
 12	"strings"
 13	"time"
 14
 15	"github.com/wraient/curd/internal/curdhost"
 16)
 17
 18const maxSenshiSubtitleSize = 8 << 20
 19
 20var senshiVTTTimingLine = regexp.MustCompile(`^\s*(?:(?:\d{2}:)?\d{2}:\d{2}\.\d{3})\s+-->\s+(?:(?:\d{2}:)?\d{2}:\d{2}\.\d{3})(?:\s|$)`)
 21
 22type senshiSubtitleTrack struct {
 23	Src     string `json:"src"`
 24	Label   string `json:"label"`
 25	Default bool   `json:"default"`
 26}
 27
 28func pickSenshiSubtitleTrack(tracks []senshiSubtitleTrack) string {
 29	// Senshi can put a forced/signs-only English track before the full dialogue
 30	// track. Prefer a non-forced default before considering label fallbacks.
 31	for _, track := range tracks {
 32		file := strings.TrimSpace(track.Src)
 33		if file != "" && track.Default && !isSenshiForcedSubtitleLabel(track.Label) {
 34			return file
 35		}
 36	}
 37	for _, track := range tracks {
 38		file := strings.TrimSpace(track.Src)
 39		label := strings.ToLower(strings.TrimSpace(track.Label))
 40		if file != "" && strings.Contains(label, "eng") && !isSenshiForcedSubtitleLabel(label) {
 41			return file
 42		}
 43	}
 44	for _, track := range tracks {
 45		file := strings.TrimSpace(track.Src)
 46		if file != "" && track.Default {
 47			return file
 48		}
 49	}
 50	for _, track := range tracks {
 51		file := strings.TrimSpace(track.Src)
 52		label := strings.ToLower(strings.TrimSpace(track.Label))
 53		if file != "" && strings.Contains(label, "eng") {
 54			return file
 55		}
 56	}
 57	for _, track := range tracks {
 58		if file := strings.TrimSpace(track.Src); file != "" {
 59			return file
 60		}
 61	}
 62	return ""
 63}
 64
 65func isSenshiForcedSubtitleLabel(label string) bool {
 66	label = strings.ToLower(strings.TrimSpace(label))
 67	return strings.Contains(label, "forced") ||
 68		strings.Contains(label, "sign") ||
 69		strings.Contains(label, "song")
 70}
 71
 72func prepareSenshiSubtitle(subtitleURL string) string {
 73	subtitleURL = strings.TrimSpace(subtitleURL)
 74	if subtitleURL == "" {
 75		return ""
 76	}
 77	if styled := validatedSenshiASSURL(subtitleURL); styled != "" {
 78		return styled
 79	}
 80	if local, err := cacheSanitizedSenshiVTT(subtitleURL, senshiSubtitleCacheDir()); err == nil {
 81		return local
 82	}
 83	return subtitleURL
 84}
 85
 86func validatedSenshiASSURL(subtitleURL string) string {
 87	parsed, err := url.Parse(strings.TrimSpace(subtitleURL))
 88	if err != nil || parsed.Scheme == "" || parsed.Host == "" || !strings.EqualFold(filepath.Ext(parsed.Path), ".vtt") {
 89		return ""
 90	}
 91	parsed.Path = strings.TrimSuffix(parsed.Path, filepath.Ext(parsed.Path)) + ".ass"
 92	candidate := parsed.String()
 93
 94	req, err := newRequest(http.MethodGet, candidate)
 95	if err != nil {
 96		return ""
 97	}
 98	req.Header.Set("Range", "bytes=0-8191")
 99	resp, err := curdhost.HTTPClient().Do(req)
100	if err != nil {
101		return ""
102	}
103	defer resp.Body.Close()
104	if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
105		return ""
106	}
107	prefix, err := io.ReadAll(io.LimitReader(resp.Body, 8192))
108	if err != nil {
109		return ""
110	}
111	text := strings.TrimSpace(strings.TrimPrefix(string(prefix), "\ufeff"))
112	if !strings.HasPrefix(text, "[Script Info]") || !strings.Contains(text, "[V4+ Styles]") {
113		return ""
114	}
115	return candidate
116}
117
118func senshiSubtitleCacheDir() string {
119	return filepath.Join(os.TempDir(), "curd", "subtitles")
120}
121
122func cacheSanitizedSenshiVTT(subtitleURL, cacheDir string) (string, error) {
123	parsed, err := url.Parse(strings.TrimSpace(subtitleURL))
124	if err != nil || parsed.Scheme == "" || parsed.Host == "" || !strings.EqualFold(filepath.Ext(parsed.Path), ".vtt") {
125		return "", fmt.Errorf("not a remote WebVTT subtitle")
126	}
127	if err := os.MkdirAll(cacheDir, 0o700); err != nil {
128		return "", err
129	}
130	cleanupOldSenshiSubtitles(cacheDir)
131
132	cacheKey := fmt.Sprintf("%x", sha256.Sum256([]byte(subtitleURL)))
133	cachePath := filepath.Join(cacheDir, cacheKey+".vtt")
134	if info, statErr := os.Stat(cachePath); statErr == nil && info.Size() > 0 && time.Since(info.ModTime()) < 12*time.Hour {
135		return cachePath, nil
136	}
137
138	req, err := newRequest(http.MethodGet, subtitleURL)
139	if err != nil {
140		return "", err
141	}
142	resp, err := curdhost.HTTPClient().Do(req)
143	if err != nil {
144		return "", err
145	}
146	defer resp.Body.Close()
147	if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
148		return "", fmt.Errorf("subtitle request failed with status %d", resp.StatusCode)
149	}
150	raw, err := io.ReadAll(io.LimitReader(resp.Body, maxSenshiSubtitleSize+1))
151	if err != nil {
152		return "", err
153	}
154	if len(raw) > maxSenshiSubtitleSize {
155		return "", fmt.Errorf("subtitle is too large")
156	}
157	sanitized, changed := sanitizeSenshiWebVTT(raw)
158	if !changed {
159		return subtitleURL, nil
160	}
161	tempPath := cachePath + ".tmp"
162	if err := os.WriteFile(tempPath, sanitized, 0o600); err != nil {
163		return "", err
164	}
165	if err := os.Rename(tempPath, cachePath); err != nil {
166		_ = os.Remove(tempPath)
167		return "", err
168	}
169	return cachePath, nil
170}
171
172func sanitizeSenshiWebVTT(raw []byte) ([]byte, bool) {
173	text := strings.TrimPrefix(strings.ReplaceAll(string(raw), "\r\n", "\n"), "\ufeff")
174	lines := strings.Split(text, "\n")
175	timingIndexes := make([]int, 0)
176	for index, line := range lines {
177		if senshiVTTTimingLine.MatchString(strings.TrimSpace(line)) {
178			timingIndexes = append(timingIndexes, index)
179		}
180	}
181	if len(timingIndexes) == 0 {
182		return raw, false
183	}
184
185	changed := strings.Contains(text, "\\h")
186	out := []string{"WEBVTT", ""}
187	for cueIndex, timingIndex := range timingIndexes {
188		end := len(lines)
189		if cueIndex+1 < len(timingIndexes) {
190			end = timingIndexes[cueIndex+1]
191		}
192		content := append([]string(nil), lines[timingIndex+1:end]...)
193		for len(content) > 0 && strings.TrimSpace(content[len(content)-1]) == "" {
194			content = content[:len(content)-1]
195		}
196		for len(content) > 0 && strings.TrimSpace(content[0]) == "" {
197			content = content[1:]
198		}
199		if len(content) == 0 {
200			continue
201		}
202		out = append(out, strings.TrimSpace(lines[timingIndex]))
203		for _, line := range content {
204			line = strings.ReplaceAll(strings.TrimSuffix(line, "\r"), "\\h", "\u00a0")
205			if strings.TrimSpace(line) == "" {
206				line = "\u00a0"
207				changed = true
208			}
209			out = append(out, line)
210		}
211		out = append(out, "")
212	}
213	if !changed {
214		return raw, false
215	}
216	return []byte(strings.Join(out, "\n")), true
217}
218
219func cleanupOldSenshiSubtitles(cacheDir string) {
220	entries, err := os.ReadDir(cacheDir)
221	if err != nil {
222		return
223	}
224	for _, entry := range entries {
225		if entry.IsDir() || !strings.HasSuffix(strings.ToLower(entry.Name()), ".vtt") {
226			continue
227		}
228		info, err := entry.Info()
229		if err == nil && time.Since(info.ModTime()) > 48*time.Hour {
230			_ = os.Remove(filepath.Join(cacheDir, entry.Name()))
231		}
232	}
233}
234
235func isSubEmbedStatus(status string) bool {
236	switch strings.ToLower(strings.TrimSpace(status)) {
237	case "hardsub", "softsub", "sub":
238		return true
239	default:
240		return false
241	}
242}