-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
srt2vtt.go
80 lines (71 loc) · 1.72 KB
/
srt2vtt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package services
import (
"bytes"
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/asticode/go-astisub"
"github.com/djimenez/iconv-go"
"github.com/gogs/chardet"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
type SRT2VTT struct {
sourceURL string
vttText string
inited bool
err error
mux sync.Mutex
}
func NewSRT2VTT(url string) *SRT2VTT {
return &SRT2VTT{sourceURL: url, inited: false}
}
func (s *SRT2VTT) get() (string, error) {
timeout := time.Duration(10 * time.Minute)
client := http.Client{
Timeout: timeout,
}
log.Infof("Loading sourceURL=%v", s.sourceURL)
resp, err := client.Get(s.sourceURL)
if err != nil {
return "", errors.Wrap(err, "Failed to fetch url")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "Failed to read body")
}
bodyStr := string(body)
detector := chardet.NewTextDetector()
enc, err := detector.DetectBest(body)
if err != nil {
return "", errors.Wrap(err, "Failed to detect encoding")
}
if enc.Charset != "UTF-8" {
log.Infof("Converting source encoding=%v to utf-8", enc.Charset)
encoded, _ := iconv.ConvertString(bodyStr, enc.Charset, "utf-8")
bodyStr = encoded
}
srt, err := astisub.ReadFromSRT(bytes.NewReader([]byte(bodyStr)))
if err != nil {
return "", errors.Wrap(err, "Failed to read srt")
}
log.Infof("Writing to vtt")
var buf = &bytes.Buffer{}
err = srt.WriteToWebVTT(buf)
if err != nil {
return "", errors.Wrap(err, "Failed to write vtt")
}
return buf.String(), nil
}
func (s *SRT2VTT) Get() (string, error) {
s.mux.Lock()
defer s.mux.Unlock()
if s.inited {
return s.vttText, s.err
}
s.vttText, s.err = s.get()
s.inited = true
return s.vttText, s.err
}