forked from kkdai/youtube
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
301 lines (246 loc) · 7.43 KB
/
client.go
File metadata and controls
301 lines (246 loc) · 7.43 KB
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
package youtube
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
// Client offers methods to download video metadata and video streams.
type Client struct {
// Debug enables debugging output through log package
Debug bool
// HTTPClient can be used to set a custom HTTP client.
// If not set, http.DefaultClient will be used
HTTPClient *http.Client
// decipherOpsCache cache decipher operations
decipherOpsCache DecipherOperationsCache
}
// GetVideo fetches video metadata
func (c *Client) GetVideo(url string) (*Video, error) {
return c.GetVideoContext(context.Background(), url)
}
// GetVideoContext fetches video metadata with a context
func (c *Client) GetVideoContext(ctx context.Context, url string) (*Video, error) {
id, err := ExtractVideoID(url)
if err != nil {
return nil, fmt.Errorf("extractVideoID failed: %w", err)
}
return c.videoFromID(ctx, id)
}
func (c *Client) videoFromID(ctx context.Context, id string) (*Video, error) {
body, err := c.videoDataByInnertube(ctx, id)
if err != nil {
return nil, err
}
v := &Video{
ID: id,
}
err = v.parseVideoInfo(body)
// If the uploader has disabled embedding the video on other sites, parse video page
if err == ErrNotPlayableInEmbed {
html, err := c.httpGetBodyBytes(ctx, "https://www.youtube.com/watch?v="+id)
if err != nil {
return nil, err
}
return v, v.parseVideoPage(html)
}
return v, err
}
type innertubeRequest struct {
VideoID string `json:"videoId"`
Context inntertubeContext `json:"context"`
PlaybackContext playbackContext `json:"playbackContext"`
}
type playbackContext struct {
ContentPlaybackContext contentPlaybackContext `json:"contentPlaybackContext"`
}
type contentPlaybackContext struct {
SignatureTimestamp string `json:"signatureTimestamp"`
}
type inntertubeContext struct {
Client innertubeClient `json:"client"`
}
type innertubeClient struct {
HL string `json:"hl"`
GL string `json:"gl"`
ClientName string `json:"clientName"`
ClientVersion string `json:"clientVersion"`
}
func (c *Client) videoDataByInnertube(ctx context.Context, id string) ([]byte, error) {
// fetch sts first
sts, err := c.getSignatureTimestamp(ctx, id)
if err != nil {
return nil, err
}
// seems like same token for all WEB clients
//nolint:gosec
const webToken = "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8"
u := fmt.Sprintf("https://www.youtube.com/youtubei/v1/player?key=%s", webToken)
data := innertubeRequest{
VideoID: id,
Context: inntertubeContext{
Client: innertubeClient{
HL: "en",
GL: "US",
ClientName: "WEB",
ClientVersion: "2.20210617.01.00",
},
},
PlaybackContext: playbackContext{
ContentPlaybackContext: contentPlaybackContext{
SignatureTimestamp: sts,
},
},
}
reqData, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(reqData))
if err != nil {
return nil, err
}
resp, err := c.httpDo(req)
if err != nil {
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
return io.ReadAll(resp.Body)
}
// GetPlaylist fetches playlist metadata
func (c *Client) GetPlaylist(url string) (*Playlist, error) {
return c.GetPlaylistContext(context.Background(), url)
}
// GetPlaylistContext fetches playlist metadata, with a context, along with a list of Videos, and some basic information
// for these videos. Playlist entries cannot be downloaded, as they lack all the required metadata, but
// can be used to enumerate all IDs, Authors, Titles, etc.
func (c *Client) GetPlaylistContext(ctx context.Context, url string) (*Playlist, error) {
id, err := extractPlaylistID(url)
if err != nil {
return nil, fmt.Errorf("extractPlaylistID failed: %w", err)
}
requestURL := fmt.Sprintf(playlistFetchURL, id)
resp, err := c.httpGet(ctx, requestURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := extractPlaylistJSON(resp.Body)
if err != nil {
return nil, err
}
p := &Playlist{ID: id}
return p, json.Unmarshal(data, p)
}
func (c *Client) VideoFromPlaylistEntry(entry *PlaylistEntry) (*Video, error) {
return c.videoFromID(context.Background(), entry.ID)
}
func (c *Client) VideoFromPlaylistEntryContext(ctx context.Context, entry *PlaylistEntry) (*Video, error) {
return c.videoFromID(ctx, entry.ID)
}
// GetStream returns the stream and the total size for a specific format
func (c *Client) GetStream(video *Video, format *Format) (io.ReadCloser, int64, error) {
return c.GetStreamContext(context.Background(), video, format)
}
// GetStream returns the stream and the total size for a specific format with a context.
func (c *Client) GetStreamContext(ctx context.Context, video *Video, format *Format) (io.ReadCloser, int64, error) {
url, err := c.GetStreamURL(video, format)
if err != nil {
return nil, 0, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, 0, err
}
const chunkSize int64 = 10_000_000
r, w := io.Pipe()
// Loads a chunk a returns the written bytes.
// Downloading in multiple chunks is much faster:
// https://github.com/kkdai/youtube/pull/190
loadChunk := func(pos int64) (int64, error) {
req.Header.Set("Range", fmt.Sprintf("bytes=%v-%v", pos, pos+chunkSize-1))
resp, err := c.httpDo(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusPartialContent {
return 0, ErrUnexpectedStatusCode(resp.StatusCode)
}
return io.Copy(w, resp.Body)
}
//nolint:revive,errcheck
go func() {
// load all the chunks
for pos := int64(0); pos < format.ContentLength; {
written, err := loadChunk(pos)
if err != nil {
w.CloseWithError(err)
return
}
pos += written
}
w.Close()
}()
return r, format.ContentLength, nil
}
// GetStreamURL returns the url for a specific format
func (c *Client) GetStreamURL(video *Video, format *Format) (string, error) {
return c.GetStreamURLContext(context.Background(), video, format)
}
// GetStreamURLContext returns the url for a specific format with a context
func (c *Client) GetStreamURLContext(ctx context.Context, video *Video, format *Format) (string, error) {
if format.URL != "" {
return format.URL, nil
}
cipher := format.Cipher
if cipher == "" {
return "", ErrCipherNotFound
}
return c.decipherURL(ctx, video.ID, cipher)
}
// httpDo sends an HTTP request and returns an HTTP response.
func (c *Client) httpDo(req *http.Request) (*http.Response, error) {
client := c.HTTPClient
if client == nil {
client = http.DefaultClient
}
if c.Debug {
log.Println(req.Method, req.URL)
}
res, err := client.Do(req)
if c.Debug && res != nil {
log.Println(res.Status)
}
return res, err
}
// httpGet does a HTTP GET request, checks the response to be a 200 OK and returns it
func (c *Client) httpGet(ctx context.Context, url string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := c.httpDo(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, ErrUnexpectedStatusCode(resp.StatusCode)
}
return resp, nil
}
// httpGetBodyBytes reads the whole HTTP body and returns it
func (c *Client) httpGetBodyBytes(ctx context.Context, url string) ([]byte, error) {
resp, err := c.httpGet(ctx, url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}