forked from rylio/ytdl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
video_info.go
402 lines (371 loc) · 10.9 KB
/
video_info.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package ytdl
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
log "github.com/sirupsen/logrus"
)
const youtubeBaseURL = "https://www.youtube.com/watch"
const youtubeEmbededBaseURL = "https://www.youtube.com/embed/"
const youtubeVideoEURL = "https://youtube.googleapis.com/v/"
const youtubeVideoInfoURL = "https://www.youtube.com/get_video_info"
const youtubeDateFormat = "2006-01-02"
// VideoInfo contains the info a youtube video
type VideoInfo struct {
// The video ID
ID string `json:"id"`
// The video title
Title string `json:"title"`
// The video description
Description string `json:"description"`
// The date the video was published
DatePublished time.Time `json:"datePublished"`
// Formats the video is available in
Formats FormatList `json:"formats"`
// List of keywords associated with the video
Keywords []string `json:"keywords"`
// Author of the video
Author string `json:"author"`
// Duration of the video
Duration time.Duration
htmlPlayerFile string
}
// GetVideoInfo fetches info from a url string, url object, or a url string
func GetVideoInfo(value interface{}) (*VideoInfo, error) {
switch t := value.(type) {
case *url.URL:
return GetVideoInfoFromURL(t)
case string:
u, err := url.ParseRequestURI(t)
if err != nil {
return GetVideoInfoFromID(t)
}
if u.Host == "youtu.be" {
return GetVideoInfoFromShortURL(u)
}
return GetVideoInfoFromURL(u)
default:
return nil, fmt.Errorf("Identifier type must be a string, *url.URL, or []byte")
}
}
// GetVideoInfoFromURL fetches video info from a youtube url
func GetVideoInfoFromURL(u *url.URL) (*VideoInfo, error) {
videoID := u.Query().Get("v")
if len(videoID) == 0 {
return nil, fmt.Errorf("Invalid youtube url, no video id")
}
return GetVideoInfoFromID(videoID)
}
// GetVideoInfoFromShortURL fetches video info from a short youtube url
func GetVideoInfoFromShortURL(u *url.URL) (*VideoInfo, error) {
if len(u.Path) >= 1 {
if path := u.Path[1:]; path != "" {
return GetVideoInfoFromID(path)
}
}
return nil, errors.New("Could not parse short URL")
}
// GetVideoInfoFromID fetches video info from a youtube video id
func GetVideoInfoFromID(id string) (*VideoInfo, error) {
u, _ := url.ParseRequestURI(youtubeBaseURL)
values := u.Query()
values.Set("v", id)
u.RawQuery = values.Encode()
resp, err := http.Get(u.String())
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Invalid status code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return getVideoInfoFromHTML(id, body)
}
// GetDownloadURL gets the download url for a format
func (info *VideoInfo) GetDownloadURL(format Format) (*url.URL, error) {
return getDownloadURL(format, info.htmlPlayerFile)
}
// GetThumbnailURL returns a url for the thumbnail image
// with the given quality
func (info *VideoInfo) GetThumbnailURL(quality ThumbnailQuality) *url.URL {
u, _ := url.Parse(fmt.Sprintf("http://img.youtube.com/vi/%s/%s.jpg",
info.ID, quality))
return u
}
// Download is a convenience method to download a format to an io.Writer
func (info *VideoInfo) Download(format Format, dest io.Writer) error {
u, err := info.GetDownloadURL(format)
if err != nil {
return err
}
resp, err := http.Get(u.String())
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("Invalid status code: %d", resp.StatusCode)
}
_, err = io.Copy(dest, resp.Body)
return err
}
func getVideoInfoFromHTML(id string, html []byte) (*VideoInfo, error) {
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(html))
if err != nil {
return nil, err
}
info := &VideoInfo{}
// extract description and title
info.Description = strings.TrimSpace(doc.Find("#eow-description").Text())
info.Title = strings.TrimSpace(doc.Find("#eow-title").Text())
info.ID = id
dateStr, ok := doc.Find("meta[itemprop=\"datePublished\"]").Attr("content")
if !ok {
log.Debug("Unable to extract date published")
} else {
date, err := time.Parse(youtubeDateFormat, dateStr)
if err == nil {
info.DatePublished = date
} else {
log.Debug("Unable to parse date published", err.Error())
}
}
// match json in javascript
re := regexp.MustCompile("ytplayer.config = (.*?);ytplayer.load")
matches := re.FindSubmatch(html)
var jsonConfig map[string]interface{}
if len(matches) > 1 {
err = json.Unmarshal(matches[1], &jsonConfig)
if err != nil {
return nil, err
}
} else {
log.Debug("Unable to extract json from default url, trying embedded url")
var resp *http.Response
resp, err = http.Get(youtubeEmbededBaseURL + id)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Embeded url request returned status code %d ", resp.StatusCode)
}
html, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// re = regexp.MustCompile("\"sts\"\\s*:\\s*(\\d+)")
re = regexp.MustCompile("yt.setConfig\\({'PLAYER_CONFIG': (.*?)}\\);")
matches := re.FindSubmatch(html)
if len(matches) < 2 {
return nil, fmt.Errorf("Error extracting sts from embedded url response")
}
dec := json.NewDecoder(bytes.NewBuffer(matches[1]))
err = dec.Decode(&jsonConfig)
if err != nil {
return nil, fmt.Errorf("Unable to extract json from embedded url: %s", err.Error())
}
query := url.Values{
"sts": []string{strconv.Itoa(int(jsonConfig["sts"].(float64)))},
"video_id": []string{id},
"eurl": []string{youtubeVideoEURL + id},
}
resp, err = http.Get(youtubeVideoInfoURL + "?" + query.Encode())
if err != nil {
return nil, fmt.Errorf("Error fetching video info: %s", err.Error())
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Video info response invalid status code")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Unable to read video info response body: %s", err.Error())
}
query, err = url.ParseQuery(string(body))
if err != nil {
return nil, fmt.Errorf("Unable to parse video info data: %s", err.Error())
}
args := make(map[string]interface{})
for k, v := range query {
if len(v) > 0 {
args[k] = v[0]
}
}
jsonConfig["args"] = args
}
inf := jsonConfig["args"].(map[string]interface{})
if status, ok := inf["status"].(string); ok && status == "fail" {
return nil, fmt.Errorf("Error %d:%s", inf["errorcode"], inf["reason"])
}
if a, ok := inf["author"].(string); ok {
info.Author = a
} else {
log.Debug("Unable to extract author")
}
if length, ok := inf["length_seconds"].(string); ok {
if duration, err := strconv.ParseInt(length, 10, 64); err == nil {
info.Duration = time.Second * time.Duration(duration)
} else {
log.Debug("Unable to parse duration string: ", length)
}
} else {
log.Debug("Unable to extract duration")
}
// For the future maybe
parseKey := func(key string) []string {
val, ok := inf[key].(string)
if !ok {
return nil
}
vals := []string{}
split := strings.Split(val, ",")
for _, v := range split {
if v != "" {
vals = append(vals, v)
}
}
return vals
}
info.Keywords = parseKey("keywords")
info.htmlPlayerFile = jsonConfig["assets"].(map[string]interface{})["js"].(string)
/*
fmtList := parseKey("fmt_list")
fexp := parseKey("fexp")
watermark := parseKey("watermark")
if len(fmtList) != 0 {
vals := []string{}
for _, v := range fmtList {
vals = append(vals, strings.Split(v, "/")...)
} else {
info["fmt_list"] = []string{}
}
videoVerticals := []string{}
if videoVertsStr, ok := inf["video_verticals"].(string); ok {
videoVertsStr = string([]byte(videoVertsStr)[1 : len(videoVertsStr)-2])
videoVertsSplit := strings.Split(videoVertsStr, ", ")
for _, v := range videoVertsSplit {
if v != "" {
videoVerticals = append(videoVerticals, v)
}
}
}
*/
var formatStrings []string
if fmtStreamMap, ok := inf["url_encoded_fmt_stream_map"].(string); ok {
formatStrings = append(formatStrings, strings.Split(fmtStreamMap, ",")...)
}
if adaptiveFormats, ok := inf["adaptive_fmts"].(string); ok {
formatStrings = append(formatStrings, strings.Split(adaptiveFormats, ",")...)
}
var formats FormatList
for _, v := range formatStrings {
query, err := url.ParseQuery(v)
if err == nil {
itag, _ := strconv.Atoi(query.Get("itag"))
if format, ok := newFormat(itag); ok {
if strings.HasPrefix(query.Get("conn"), "rtmp") {
format.meta["rtmp"] = true
}
for k, v := range query {
if len(v) == 1 {
format.meta[k] = v[0]
} else {
format.meta[k] = v
}
}
formats = append(formats, format)
} else {
log.Debug("No metadata found for itag: ", itag, ", skipping...")
}
} else {
log.Debug("Unable to format string", err.Error())
}
}
if dashManifestURL, ok := inf["dashmpd"].(string); ok {
tokens, err := getSigTokens(info.htmlPlayerFile)
if err != nil {
return nil, fmt.Errorf("Unable to extract signature tokens: %s", err.Error())
}
regex := regexp.MustCompile("\\/s\\/([a-fA-F0-9\\.]+)")
regexSub := regexp.MustCompile("([a-fA-F0-9\\.]+)")
dashManifestURL = regex.ReplaceAllStringFunc(dashManifestURL, func(str string) string {
return "/signature/" + decipherTokens(tokens, regexSub.FindString(str))
})
dashFormats, err := getDashManifest(dashManifestURL)
if err != nil {
return nil, fmt.Errorf("Unable to extract dash manifest: %s", err.Error())
}
for _, dashFormat := range dashFormats {
added := false
for j, format := range formats {
if dashFormat.Itag == format.Itag {
formats[j] = dashFormat
added = true
break
}
}
if !added {
formats = append(formats, dashFormat)
}
}
}
info.Formats = formats
return info, nil
}
type representation struct {
Itag int `xml:"id,attr"`
Height int `xml:"height,attr"`
URL string `xml:"BaseURL"`
}
func getDashManifest(urlString string) (formats []Format, err error) {
resp, err := http.Get(urlString)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Invalid status code %d", resp.StatusCode)
}
dec := xml.NewDecoder(resp.Body)
var token xml.Token
for ; err == nil; token, err = dec.Token() {
if el, ok := token.(xml.StartElement); ok && el.Name.Local == "Representation" {
var rep representation
err = dec.DecodeElement(&rep, &el)
if err != nil {
break
}
if format, ok := newFormat(rep.Itag); ok {
format.meta["url"] = rep.URL
if rep.Height != 0 {
format.Resolution = strconv.Itoa(rep.Height) + "p"
} else {
format.Resolution = ""
}
formats = append(formats, format)
} else {
log.Debug("No metadata found for itag: ", rep.Itag, ", skipping...")
}
}
}
if err != io.EOF {
return nil, err
}
return formats, nil
}