This repository has been archived by the owner on Apr 13, 2022. It is now read-only.
/
youtube.go
166 lines (143 loc) · 4.13 KB
/
youtube.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package main
import (
"errors"
"fmt"
"log"
"net/url"
"regexp"
"strings"
"github.com/Jeffail/gabs"
"github.com/parnurzeal/gorequest"
)
// Logic borrowed and refactored from http://github.com/kkdai/youtube
type stream map[string]string
type youtube struct {
streamList []stream
videoID string
videoInfo string
}
func (y *youtube) parseVideoInfo() error {
answer, err := url.ParseQuery(y.videoInfo)
if err != nil {
return err
}
status, ok := answer["status"]
if !ok {
err = fmt.Errorf("no response status found in the server's answer")
return err
}
if status[0] == "fail" {
reason, ok := answer["reason"]
if ok {
err = fmt.Errorf("'fail' response status found in the server's answer, reason: '%s'", reason[0])
} else {
err = errors.New(fmt.Sprint("'fail' response status found in the server's answer, no reason given"))
}
return err
}
if status[0] != "ok" {
err = fmt.Errorf("non-success response status found in the server's answer (status: '%s')", status)
return err
}
// read the streams map
streamMap, ok := answer["url_encoded_fmt_stream_map"]
if !ok {
err = errors.New(fmt.Sprint("no stream map found in the server's answer"))
return err
}
// read each stream
for streamPos, streamRaw := range strings.Split(streamMap[0], ",") {
streamQry, err := url.ParseQuery(streamRaw)
if err != nil {
log.Println(fmt.Sprintf("An error occured while decoding one of the video's stream's information: stream %d: %s\n", streamPos, err))
continue
}
stream := stream{
"quality": streamQry["quality"][0],
"type": streamQry["type"][0],
"url": streamQry["url"][0],
"sig": "",
"title": answer["title"][0],
"author": answer["author"][0],
}
if _, exist := streamQry["sig"]; exist {
stream["sig"] = streamQry["sig"][0]
}
y.streamList = append(y.streamList, stream)
}
return nil
}
func (y *youtube) getVideoInfo() error {
url := "http://youtube.com/get_video_info?video_id=" + y.videoID
_, body, err := gorequest.New().Get(url).End()
if err != nil {
return err[0]
}
y.videoInfo = body
return nil
}
func (y *youtube) findVideoID(videoID string) error {
if strings.Contains(videoID, "youtu") || strings.ContainsAny(videoID, "\"?&/<%=") {
reList := []*regexp.Regexp{
regexp.MustCompile(`(?:v|embed|watch\?v)(?:=|/)([^"&?/=%]{11})`),
regexp.MustCompile(`(?:=|/)([^"&?/=%]{11})`),
regexp.MustCompile(`([^"&?/=%]{11})`),
}
for _, re := range reList {
if isMatch := re.MatchString(videoID); isMatch {
subs := re.FindStringSubmatch(videoID)
videoID = subs[1]
break
}
}
}
y.videoID = videoID
if strings.ContainsAny(videoID, "?&/<%=") {
return errors.New("invalid characters in video id")
}
if len(videoID) < 10 {
return errors.New("the video id must be at least 10 characters long")
}
return nil
}
func searchYoutube(text string) (string, error) {
formattedURL := fmt.Sprintf("https://www.googleapis.com/youtube/v3/search?part=snippet&q=%s&key=%s", url.QueryEscape(text), *googleKey)
_, body, err := gorequest.New().Get(formattedURL).EndBytes()
if err != nil {
fmt.Println(err)
}
jsonParsed, _ := gabs.ParseJSON(body)
children, _ := jsonParsed.S("items").Children()
if len(children) == 0 {
return "", fmt.Errorf("No video found")
}
videoID, _ := children[0].Path("id.videoId").Data().(string)
return videoID, nil
}
// GetYoutubeURL converts a standard Youtube URL or ID to an mp4 download link,
// or searches Youtube and picks the first result.
func GetYoutubeURL(query string) (string, string, error) {
y := new(youtube)
if len(query) < 4 || query[:4] != "http" {
link, err := searchYoutube(query)
if err != nil {
return "", "", err
}
query = link
}
err := y.findVideoID(query)
if err != nil {
return "", "", fmt.Errorf("findVideoID error=%s", err)
}
err = y.getVideoInfo()
if err != nil {
return "", "", fmt.Errorf("getVideoInfo error=%s", err)
}
err = y.parseVideoInfo()
if err != nil {
return "", "", fmt.Errorf("parse video info failed, err=%s", err)
}
targetStream := y.streamList[0]
downloadURL := targetStream["url"] + "&signature=" + targetStream["sig"]
return downloadURL, targetStream["title"], nil
}