/
youtube.go
232 lines (197 loc) · 5.91 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
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
package gscrape
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"github.com/yhat/scrape"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
var (
shortDurationRegexp = regexp.MustCompile("^([0-9]*):([0-9]*)$")
longDurationRegexp = regexp.MustCompile("^([0-9]*):([0-9]*):([0-9]*)$")
)
// YoutubeVideoInfo stores various metadata about
// a Youtube video.
type YoutubeVideoInfo struct {
Title string
Description string
Author string
ID string
ThumbnailURL *url.URL
Length time.Duration
}
// A Youtube object wraps a session and provides
// various youtube-related APIs.
type Youtube struct {
s *Session
}
// AuthYoutube authenticates a youtube user using
// a session and returns a Youtube instance for
// using the youtube-related features of the session.
func (s *Session) AuthYoutube(email, password string) (*Youtube, error) {
if err := s.Auth("https://accounts.google.com/ServiceLogin?service=youtube",
"https://accounts.google.com/ServiceLoginAuth", email, password); err != nil {
return nil, err
}
// Get some youtube-specific cookies.
req, _ := http.NewRequest("GET", "https://www.youtube.com/feed/subscriptions", nil)
req.Header.Set("User-Agent", spoofedUserAgent)
resp, err := s.Do(req)
if resp != nil {
resp.Body.Close()
}
if err != nil {
return nil, err
}
return &Youtube{s}, nil
}
// History asynchronously fetches the user's
// video viewing history.
// You may provide a cancel channel which you
// can close to cancel the fetch mid-way.
func (y *Youtube) History(cancel <-chan struct{}) (<-chan *YoutubeVideoInfo, <-chan error) {
videoChan := make(chan *YoutubeVideoInfo)
errChan := make(chan error, 1)
go func() {
defer close(videoChan)
defer close(errChan)
historyReq, _ := http.NewRequest("GET", "https://www.youtube.com/feed/history", nil)
historyReq.Header.Set("User-Agent", spoofedUserAgent)
resp, err := y.s.Do(historyReq)
rootNode, err := html.Parse(resp.Body)
resp.Body.Close()
if err != nil {
errChan <- err
return
}
loadMoreHTML := rootNode
contentHTML := rootNode
for {
items := parseHistoryItems(contentHTML)
for _, item := range items {
select {
case videoChan <- item:
case <-cancel:
return
}
}
if loadMoreHTML == nil {
break
}
loadButton, ok := scrape.Find(loadMoreHTML, scrape.ByClass("yt-uix-load-more"))
if ok {
morePath := scrape.Attr(loadButton, "data-uix-load-more-href")
loadMoreHTML, contentHTML, err = y.fetchMoreHistory(morePath)
if err != nil {
errChan <- err
return
}
}
}
}()
return videoChan, errChan
}
// FullHistory synchronously fetches the user's
// full video watching history.
// If an error occurs, this will return partial
// results and the first error encountered.
func (y *Youtube) FullHistory() ([]YoutubeVideoInfo, error) {
var res []YoutubeVideoInfo
vidChan, errChan := y.History(nil)
for video := range vidChan {
res = append(res, *video)
}
return res, <-errChan
}
func (y *Youtube) fetchMoreHistory(moreHref string) (more, content *html.Node, err error) {
moreURL := "https://www.youtube.com" + moreHref
moreReq, err := http.NewRequest("GET", moreURL, nil)
if err != nil {
return nil, nil, err
}
resp, err := y.s.Do(moreReq)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
var jsonDoc struct {
Content string `json:"content_html"`
More string `json:"load_more_widget_html"`
}
if err := json.NewDecoder(resp.Body).Decode(&jsonDoc); err != nil {
return nil, nil, err
}
content, err = html.Parse(bytes.NewBufferString(jsonDoc.Content))
if err != nil {
return nil, nil, err
}
more, _ = html.Parse(bytes.NewBufferString(jsonDoc.More))
return
}
func parseHistoryItems(rootNode *html.Node) []*YoutubeVideoInfo {
videoElements := scrape.FindAll(rootNode, scrape.ByClass("yt-lockup-video"))
res := make([]*YoutubeVideoInfo, len(videoElements))
for i, element := range videoElements {
res[i] = parseVideoInfo(element)
}
return res
}
func parseVideoInfo(element *html.Node) *YoutubeVideoInfo {
var info YoutubeVideoInfo
info.ID = scrape.Attr(element, "data-context-item-id")
thumbnailContainer, ok := scrape.Find(element, scrape.ByClass("yt-thumb-simple"))
if ok {
thumbnailImage, ok := scrape.Find(thumbnailContainer, scrape.ByTag(atom.Img))
if ok {
thumb := scrape.Attr(thumbnailImage, "data-thumb")
if thumb == "" {
thumb = scrape.Attr(thumbnailImage, "src")
}
info.ThumbnailURL, _ = url.Parse(thumb)
}
}
videoTimeElement, ok := scrape.Find(element, scrape.ByClass("video-time"))
if ok {
durationStr := strings.TrimSpace(scrape.Text(videoTimeElement))
info.Length, _ = parseVideoDuration(durationStr)
}
linkFieldClasses := []string{"yt-lockup-title", "yt-lockup-byline"}
linkFieldPtrs := []*string{&info.Title, &info.Author}
for i, class := range linkFieldClasses {
linkContainer, ok := scrape.Find(element, scrape.ByClass(class))
if ok {
link, ok := scrape.Find(linkContainer, scrape.ByTag(atom.A))
if ok {
*linkFieldPtrs[i] = strings.TrimSpace(scrape.Text(link))
}
}
}
descBox, ok := scrape.Find(element, scrape.ByClass("yt-lockup-description"))
if ok {
info.Description = strings.TrimSpace(scrape.Text(descBox))
}
return &info
}
func parseVideoDuration(duration string) (time.Duration, error) {
shortParsed := shortDurationRegexp.FindStringSubmatch(duration)
if shortParsed != nil {
minutes, _ := strconv.Atoi(shortParsed[1])
seconds, _ := strconv.Atoi(shortParsed[2])
return time.Second * time.Duration(minutes*60+seconds), nil
}
longParsed := longDurationRegexp.FindStringSubmatch(duration)
if longParsed != nil {
hours, _ := strconv.Atoi(longParsed[1])
minutes, _ := strconv.Atoi(longParsed[2])
seconds, _ := strconv.Atoi(longParsed[3])
return time.Second * time.Duration(hours*60*60+minutes*60+seconds), nil
}
return 0, errors.New("unable to parse duration: " + duration)
}