MCPcopy
hub / github.com/filebrowser/filebrowser / subtitleFileHandler

Function subtitleFileHandler

http/subtitle.go:41–88  ·  view source on GitHub ↗
(w http.ResponseWriter, r *http.Request, file *files.FileInfo)

Source from the content-addressed store, hash-verified

39})
40
41func subtitleFileHandler(w http.ResponseWriter, r *http.Request, file *files.FileInfo) (int, error) {
42 // if its not a subtitle file, reject
43 if !files.IsSupportedSubtitle(file.Name) {
44 return http.StatusBadRequest, nil
45 }
46
47 fd, err := file.Fs.Open(file.Path)
48 if err != nil {
49 return http.StatusInternalServerError, err
50 }
51 defer fd.Close()
52
53 // load subtitle for conversion to vtt
54 var sub *astisub.Subtitles
55 if strings.HasSuffix(file.Name, ".srt") {
56 content, readErr := io.ReadAll(fd)
57 if readErr != nil {
58 return http.StatusInternalServerError, readErr
59 }
60 sub, err = astisub.ReadFromSRT(bytes.NewReader(normalizeSRTLineBreaks(content)))
61 } else if strings.HasSuffix(file.Name, ".ass") || strings.HasSuffix(file.Name, ".ssa") {
62 sub, err = astisub.ReadFromSSA(fd)
63 }
64 if err != nil {
65 return http.StatusInternalServerError, err
66 }
67
68 setContentDisposition(w, r, file)
69 w.Header().Add("Content-Security-Policy", `script-src 'none';`)
70 w.Header().Set("Cache-Control", "private")
71 // force type to text/vtt
72 w.Header().Set("Content-Type", "text/vtt")
73
74 // serve vtt file directly
75 if sub == nil {
76 http.ServeContent(w, r, file.Name, file.ModTime, fd)
77 return 0, nil
78 }
79
80 // convert others to vtt and serve from buffer
81 var buf = &bytes.Buffer{}
82 err = sub.WriteToWebVTT(buf)
83 if err != nil {
84 return http.StatusInternalServerError, err
85 }
86 http.ServeContent(w, r, file.Name, file.ModTime, bytes.NewReader(buf.Bytes()))
87 return 0, nil
88}
89
90func normalizeSRTLineBreaks(content []byte) []byte {
91 return srtLineBreakTag.ReplaceAll(content, []byte("\n"))

Callers 2

subtitle.goFile · 0.85

Calls 5

IsSupportedSubtitleFunction · 0.92
normalizeSRTLineBreaksFunction · 0.85
setContentDispositionFunction · 0.85
CloseMethod · 0.65
OpenMethod · 0.45