filebrowser/http/subtitle.go
Henrique Dias f4982cff5e style: fix linting issues
License: MIT
Signed-off-by: Henrique Dias <hacdias@gmail.com>

Former-commit-id: 10657ab9cff2ee94dd7c0082bfe2cbfa07865022 [formerly 5501af1ace43a089ac4222cf9da2f5176242f817] [formerly 39c72e2e9235a822a30c0b338f55c441f3b3024d [formerly b7022bdfe3]]
Former-commit-id: 5941e4ab1295b90371ba60003f69939559dc8060 [formerly 3513d92ba403133d7b53aa19c92e4356f9e68b75]
Former-commit-id: 3657f6f659e893928bd2b9f64afecdaa41d587a6
2018-08-07 13:34:06 +01:00

84 lines
1.9 KiB
Go

package http
import (
"bytes"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"regexp"
fb "github.com/filebrowser/filebrowser"
)
func subtitlesHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {
files, err := ReadDir(filepath.Dir(c.File.Path))
if err != nil {
return http.StatusInternalServerError, err
}
var subtitles = make([]map[string]string, 0)
for _, file := range files {
ext := filepath.Ext(file.Name())
if ext == ".vtt" || ext == ".srt" {
var sub map[string]string = make(map[string]string)
sub["src"] = filepath.Dir(c.File.Path) + "/" + file.Name()
sub["kind"] = "subtitles"
sub["label"] = file.Name()
subtitles = append(subtitles, sub)
}
}
return renderJSON(w, subtitles)
}
func subtitleHandler(c *fb.Context, w http.ResponseWriter, r *http.Request) (int, error) {
str, err := CleanSubtitle(c.File.Path)
if err != nil {
return http.StatusInternalServerError, err
}
file, err := os.Open(c.File.Path)
if err != nil {
return http.StatusInternalServerError, err
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return http.StatusInternalServerError, err
}
w.Header().Set("Content-Disposition", "inline")
w.Header().Set("Content-Type", "text/vtt")
http.ServeContent(w, r, stat.Name(), stat.ModTime(), bytes.NewReader([]byte(str)))
return 0, nil
}
func CleanSubtitle(filename string) (string, error) {
b, err := ioutil.ReadFile(filename)
if err != nil {
return "", err
}
str := string(b) // convert content to a 'string'
ext := filepath.Ext(filename)
if ext == ".srt" {
re := regexp.MustCompile("([0-9]{2}:[0-9]{2}:[0-9]{2}),([0-9]{3})")
str = "WEBVTT\n\n" + re.ReplaceAllString(str, "$1.$2")
}
return str, err
}
func ReadDir(dirname string) ([]os.FileInfo, error) {
f, err := os.Open(dirname)
if err != nil {
return nil, err
}
list, err := f.Readdir(-1)
f.Close()
if err != nil {
return nil, err
}
return list, nil
}