-
Notifications
You must be signed in to change notification settings - Fork 0
/
subtitles.go
80 lines (66 loc) · 1.91 KB
/
subtitles.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 main
import (
"encoding/xml"
"errors"
"io"
"io/ioutil"
"os"
)
func addSubToJSON(video *Video, langCode string) {
urlXML := "http://www.youtube.com/api/timedtext?lang=" + langCode + "&v=" + video.ID
urlTTML := "http://www.youtube.com/api/timedtext?lang=" + langCode + "&v=" + video.ID + "&fmt=ttml&name="
urlVTT := "http://www.youtube.com/api/timedtext?lang=" + langCode + "&v=" + video.ID + "&fmt=vtt&name="
video.InfoJSON.subLock.Lock()
video.InfoJSON.Subtitles[langCode] = append(video.InfoJSON.Subtitles[langCode], Subtitle{urlXML, "xml"}, Subtitle{urlTTML, "ttml"}, Subtitle{urlVTT, "vtt"})
video.InfoJSON.subLock.Unlock()
}
func downloadSub(video *Video, langCode string, lang string) error {
addSubToJSON(video, langCode)
// generate subtitle URL
url := "http://www.youtube.com/api/timedtext?lang=" + langCode + "&v=" + video.ID
// get the data
resp, err := getHttpClient().Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// create the file
out, err := os.Create(video.Path + video.ID + "_" + video.Title + "." + langCode + ".xml")
if err != nil {
return err
}
defer out.Close()
// write the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
func fetchSubs(video *Video) error {
var tracks Tracklist
// request subtitles list
res, err := getHttpClient().Get("https://video.google.com/timedtext?hl=en&type=list&v=" + video.ID)
if err != nil {
return err
}
defer res.Body.Close()
// check status, exit if != 200
if res.StatusCode != 200 {
return errors.New("status code of subtitles list != 200, cancelation")
}
// reading tracks list as a byte array
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
// download the subtitles
xml.Unmarshal(data, &tracks)
for _, track := range tracks.Tracks {
err = downloadSub(video, track.LangCode, track.Lang)
if err != nil {
return err
}
}
return nil
}