-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube.go
327 lines (261 loc) · 6.83 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
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
package youtube
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/rubpy/crawly-live-youtube/xmlapi"
)
//////////////////////////////////////////////////
func (cr *Crawler) ChannelID(channelURL string) (channelID string, ok bool) {
return cr.loadChannelID(channelURL)
}
func (cr *Crawler) loadChannelID(channelURL string) (channelID string, ok bool) {
return cr.channelIDCache.Load(channelURL)
}
func (cr *Crawler) storeChannelID(channelURL string, channelID string) {
cr.channelIDCache.Store(channelURL, channelID)
}
func (cr *Crawler) canonicalHandle(handle Handle) Handle {
if handle.Type == HandleChannelURL {
if channelID, ok := cr.loadChannelID(handle.Value); ok {
handle = ChannelID(channelID)
}
}
return handle
}
func (cr *Crawler) IsTracked(handle Handle) bool {
return cr.Crawler.IsTracked(cr.canonicalHandle(handle))
}
//////////////////////////////////////////////////
func (cr *Crawler) CheckLiveVideoState(ctx context.Context, videoID string) (live bool, finished bool, err error) {
if videoID == "" || !IsValidVideoID(videoID) {
err = InvalidVideoID
return
}
if cr.service == nil {
err = NilService
return
}
if ctx == nil {
ctx = context.Background()
} else {
if err = ctx.Err(); err != nil {
return
}
}
part := []string{"liveStreamingDetails"}
call := cr.service.Videos.List(part)
call.Context(ctx)
call.Id(videoID)
resp, err := call.Do()
if err != nil {
err = fmt.Errorf("youtube.VideosService.List: %w", err)
return
}
for _, item := range resp.Items {
if item.Id != videoID || item.LiveStreamingDetails == nil {
continue
}
d := item.LiveStreamingDetails
if d.ActualEndTime != "" {
finished = true
} else {
if d.ActualStartTime != "" {
live = true
}
}
return
}
return
}
func (cr *Crawler) FetchChannelXMLFeed(ctx context.Context, channelID string) (feed *xmlapi.ChannelFeed, err error) {
if channelID == "" || !IsValidChannelID(channelID) {
err = InvalidChannelID
return
}
if cr.client == nil {
err = NilClient
return
}
if ctx == nil {
ctx = context.Background()
} else {
if err = ctx.Err(); err != nil {
return
}
}
feedURL := &url.URL{
Scheme: "https",
Host: "www.youtube.com",
Path: "feeds/videos.xml",
}
q := feedURL.Query()
q.Set("channel_id", channelID)
q.Set(nonceKey, generateNonce())
feedURL.RawQuery = q.Encode()
rawFeedURL := feedURL.String()
resp, err := cr.client.Request(ctx, "GET", rawFeedURL, nil, http.Header{
"Cookie": {generateConsentCookie()},
})
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
feed, err = xmlapi.ParseChannelFeed(body)
if err != nil {
return nil, err
}
return feed, nil
}
func (cr *Crawler) FetchChannelIndex(ctx context.Context, channelURL string) (index *xmlapi.ChannelIndex, err error) {
if channelURL == "" || !IsValidChannelURL(channelURL) {
err = InvalidChannelURL
return
}
if cr.client == nil {
err = NilClient
return
}
if ctx == nil {
ctx = context.Background()
} else {
if err = ctx.Err(); err != nil {
return
}
}
resp, err := cr.client.Request(ctx, "GET", channelURL, nil, http.Header{
"Cookie": {generateConsentCookie()},
})
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
index, err = xmlapi.ParseChannelIndex(body)
if err != nil {
return nil, err
}
return index, nil
}
// NOTE: thumbnailURL is an optional 'hint'.
func (cr *Crawler) CheckLiveVideoThumbnail(ctx context.Context, videoID string, thumbnailURL string) (exists bool, err error) {
if videoID == "" || !IsValidVideoID(videoID) {
err = InvalidVideoID
return
}
if cr.client == nil {
err = NilClient
return
}
if ctx == nil {
ctx = context.Background()
} else {
if err = ctx.Err(); err != nil {
return
}
}
var u *url.URL
var uerr error
if thumbnailURL != "" {
u, uerr = url.Parse(thumbnailURL)
if uerr == nil {
containsExtension := false
for _, suffix := range validVideoThumbnailSuffixes {
if strings.Contains(u.Path, suffix) {
containsExtension = true
break
}
}
if !containsExtension {
u = nil
}
}
}
if u == nil || uerr != nil {
thumbnailURL = "https://i.ytimg.com/vi/" + url.PathEscape(videoID) + "/sddefault.jpg"
u, uerr = url.Parse(thumbnailURL)
}
if u == nil || uerr != nil {
err = InvalidVideoThumbnailURL
return
}
sepPos := strings.LastIndex(u.Path, ".")
if sepPos < 0 {
// NOTE: should never happen; weird edge case.
err = InvalidVideoThumbnailURL
return
}
pathFile := u.Path[:sepPos]
if !strings.Contains(pathFile, liveVideoThumbnailFilenameSuffix) {
var newPath strings.Builder
newPath.WriteString(pathFile)
newPath.WriteString(liveVideoThumbnailFilenameSuffix)
newPath.WriteString(u.Path[sepPos:])
u.Path = newPath.String()
}
q := u.Query()
q.Set(nonceKey, generateNonce())
u.RawQuery = q.Encode()
thumbnailURL = u.String()
resp, err := cr.client.Request(ctx, "GET", thumbnailURL, nil, http.Header{
"Cookie": {generateConsentCookie()},
})
if err != nil {
return
}
defer resp.Body.Close()
switch resp.StatusCode {
case 404:
return false, nil
case 200, 302, 304:
return true, nil
}
return false, UncertainLiveVideoThumbnail
}
//////////////////////////////////////////////////
type VideoCandidate struct {
ID string `json:"id"`
ChannelID string `json:"channel_id"`
LastProcess time.Time `json:"last_process"`
Live bool `json:"live"`
LiveGenuine bool `json:"live_genuine"`
LiveCheckAttempt int `json:"live_check_attempt"`
LastLive time.Time `json:"last_live"`
LivestreamFinished bool `json:"livestream_finished"`
LastLivestreamFinished time.Time `json:"last_livestream_finished"`
NotLivestream bool `json:"not_livestream"`
LastNotLivestream time.Time `json:"last_not_livestream"`
}
var (
ExceededCheckVideoTimeout = errors.New("exceeded check video timeout")
)
//////////////////////////////////////////////////
var (
InvalidChannelID = errors.New("invalid channel ID")
InvalidChannelURL = errors.New("invalid channel URL")
InvalidVideoID = errors.New("invalid video ID")
InvalidVideoThumbnailURL = errors.New("invalid video thumbnail URL")
UncertainLiveVideoThumbnail = errors.New("uncertain live video thumbnail status")
)
func IsValidChannelID(s string) bool { return xmlapi.IsValidChannelID(s) }
func IsValidChannelURL(s string) bool { return isValidURL(s) }
func IsValidVideoID(s string) bool { return xmlapi.IsValidVideoID(s) }
var (
validVideoThumbnailSuffixes = []string{".jpg", ".webp"}
liveVideoThumbnailFilenameSuffix = "_live"
)
func generateConsentCookie() string {
return "SOCS=CAESEwgDEgk0ODE3Nzk3MjQaAmVuIAEaBgiA_LyaBg"
}