forked from kkdai/youtube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideo.go
75 lines (62 loc) · 1.79 KB
/
video.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
package youtube
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
"time"
)
type Video struct {
ID string
Title string
Description string
Author string
Duration time.Duration
Formats FormatList
DASHManifestURL string // URI of the DASH manifest file
HLSManifestURL string // URI of the HLS manifest file
}
func (v *Video) parseVideoInfo(info string) error {
answer, err := url.ParseQuery(info)
if err != nil {
return err
}
status := answer.Get("status")
if status != "ok" {
return &ErrResponseStatus{
Status: status,
Reason: answer.Get("reason"),
}
}
// read the streams map
playerResponse := answer.Get("player_response")
if playerResponse == "" {
return errors.New("no player_response found in the server's answer")
}
var prData playerResponseData
if err := json.Unmarshal([]byte(playerResponse), &prData); err != nil {
return fmt.Errorf("unable to parse player response JSON: %w", err)
}
v.Title = prData.VideoDetails.Title
v.Description = prData.VideoDetails.ShortDescription
v.Author = prData.VideoDetails.Author
if seconds, _ := strconv.Atoi(prData.Microformat.PlayerMicroformatRenderer.LengthSeconds); seconds > 0 {
v.Duration = time.Duration(seconds) * time.Second
}
// Check if video is downloadable
if prData.PlayabilityStatus.Status != "OK" {
return &ErrPlayabiltyStatus{
Status: prData.PlayabilityStatus.Status,
Reason: prData.PlayabilityStatus.Reason,
}
}
// Assign Streams
v.Formats = append(prData.StreamingData.Formats, prData.StreamingData.AdaptiveFormats...)
if len(v.Formats) == 0 {
return errors.New("no formats found in the server's answer")
}
v.HLSManifestURL = prData.StreamingData.HlsManifestURL
v.DASHManifestURL = prData.StreamingData.DashManifestURL
return nil
}