-
Notifications
You must be signed in to change notification settings - Fork 434
/
playlist.go
256 lines (206 loc) · 6.62 KB
/
playlist.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
package youtube
import (
"context"
"encoding/json"
"fmt"
"regexp"
"runtime/debug"
"strconv"
"time"
sjson "github.com/bitly/go-simplejson"
)
var (
playlistIDRegex = regexp.MustCompile("^[A-Za-z0-9_-]{13,42}$")
playlistInURLRegex = regexp.MustCompile("[&?]list=([A-Za-z0-9_-]{13,42})(&.*)?$")
)
type Playlist struct {
ID string
Title string
Description string
Author string
Videos []*PlaylistEntry
}
type PlaylistEntry struct {
ID string
Title string
Author string
Duration time.Duration
Thumbnails Thumbnails
}
func extractPlaylistID(url string) (string, error) {
if playlistIDRegex.Match([]byte(url)) {
return url, nil
}
matches := playlistInURLRegex.FindStringSubmatch(url)
if matches != nil {
return matches[1], nil
}
return "", ErrInvalidPlaylist
}
// structs for playlist extraction
// Title: metadata.playlistMetadataRenderer.title | sidebar.playlistSidebarRenderer.items[0].playlistSidebarPrimaryInfoRenderer.title.runs[0].text
// Description: metadata.playlistMetadataRenderer.description
// Author: sidebar.playlistSidebarRenderer.items[1].playlistSidebarSecondaryInfoRenderer.videoOwner.videoOwnerRenderer.title.runs[0].text
// Videos: contents.twoColumnBrowseResultsRenderer.tabs[0].tabRenderer.content.sectionListRenderer.contents[0].itemSectionRenderer.contents[0].playlistVideoListRenderer.contents
// ID: .videoId
// Title: title.runs[0].text
// Author: .shortBylineText.runs[0].text
// Duration: .lengthSeconds
// Thumbnails .thumbnails
// TODO?: Author thumbnails: sidebar.playlistSidebarRenderer.items[0].playlistSidebarPrimaryInfoRenderer.thumbnailRenderer.playlistVideoThumbnailRenderer.thumbnail.thumbnails
func (p *Playlist) parsePlaylistInfo(ctx context.Context, client *Client, body []byte) (err error) {
var j *sjson.Json
j, err = sjson.NewJson(body)
if err != nil {
return err
}
defer func() {
stack := debug.Stack()
if r := recover(); r != nil {
err = fmt.Errorf("JSON parsing error: %v\n%s", r, stack)
}
}()
renderer := j.GetPath("alerts").GetIndex(0).GetPath("alertRenderer")
if renderer != nil && renderer.GetPath("type").MustString() == "ERROR" {
message := renderer.GetPath("text", "runs").GetIndex(0).GetPath("text").MustString()
return ErrPlaylistStatus{Reason: message}
}
// Metadata can be located in multiple places depending on client type
var metadata *sjson.Json
if node, ok := j.CheckGet("metadata"); ok {
metadata = node
} else if node, ok := j.CheckGet("header"); ok {
metadata = node
} else {
return fmt.Errorf("no playlist header / metadata found")
}
metadata = metadata.Get("playlistHeaderRenderer")
p.Title = sjsonGetText(metadata, "title")
p.Description = sjsonGetText(metadata, "description", "descriptionText")
p.Author = j.GetPath("sidebar", "playlistSidebarRenderer", "items").GetIndex(1).
GetPath("playlistSidebarSecondaryInfoRenderer", "videoOwner", "videoOwnerRenderer", "title", "runs").
GetIndex(0).Get("text").MustString()
if len(p.Author) == 0 {
p.Author = sjsonGetText(metadata, "owner", "ownerText")
}
contents, ok := j.CheckGet("contents")
if !ok {
return fmt.Errorf("contents not found in json body")
}
// contents can have different keys with same child structure
firstPart := getFirstKeyJSON(contents).GetPath("tabs").GetIndex(0).
GetPath("tabRenderer", "content", "sectionListRenderer", "contents").GetIndex(0)
// This extra nested item is only set with the web client
if n := firstPart.GetPath("itemSectionRenderer", "contents").GetIndex(0); isValidJSON(n) {
firstPart = n
}
vJSON, err := firstPart.GetPath("playlistVideoListRenderer", "contents").MarshalJSON()
if err != nil {
return err
}
if len(vJSON) <= 4 {
return fmt.Errorf("no video data found in JSON")
}
entries, continuation, err := extractPlaylistEntries(vJSON)
if err != nil {
return err
}
if len(continuation) == 0 {
continuation = getContinuation(firstPart.Get("playlistVideoListRenderer"))
}
if len(entries) == 0 {
return fmt.Errorf("no videos found in playlist")
}
p.Videos = entries
for continuation != "" {
data := prepareInnertubePlaylistData(continuation, true, *client.client)
body, err := client.httpPostBodyBytes(ctx, "https://www.youtube.com/youtubei/v1/browse?key="+client.client.key, data)
if err != nil {
return err
}
j, err := sjson.NewJson(body)
if err != nil {
return err
}
next := j.GetPath("onResponseReceivedActions").GetIndex(0).
GetPath("appendContinuationItemsAction", "continuationItems")
if !isValidJSON(next) {
next = j.GetPath("continuationContents", "playlistVideoListContinuation", "contents")
}
vJSON, err := next.MarshalJSON()
if err != nil {
return err
}
entries, token, err := extractPlaylistEntries(vJSON)
if err != nil {
return err
}
if len(token) > 0 {
continuation = token
} else {
continuation = getContinuation(j.GetPath("continuationContents", "playlistVideoListContinuation"))
}
p.Videos = append(p.Videos, entries...)
}
return err
}
func extractPlaylistEntries(data []byte) ([]*PlaylistEntry, string, error) {
var vids []*videosJSONExtractor
if err := json.Unmarshal(data, &vids); err != nil {
return nil, "", err
}
entries := make([]*PlaylistEntry, 0, len(vids))
var continuation string
for _, v := range vids {
if v.Renderer == nil {
if v.Continuation.Endpoint.Command.Token != "" {
continuation = v.Continuation.Endpoint.Command.Token
}
continue
}
entries = append(entries, v.PlaylistEntry())
}
return entries, continuation, nil
}
type videosJSONExtractor struct {
Renderer *struct {
ID string `json:"videoId"`
Title withRuns `json:"title"`
Author withRuns `json:"shortBylineText"`
Duration string `json:"lengthSeconds"`
Thumbnail struct {
Thumbnails []Thumbnail `json:"thumbnails"`
} `json:"thumbnail"`
} `json:"playlistVideoRenderer"`
Continuation struct {
Endpoint struct {
Command struct {
Token string `json:"token"`
} `json:"continuationCommand"`
} `json:"continuationEndpoint"`
} `json:"continuationItemRenderer"`
}
func (vje videosJSONExtractor) PlaylistEntry() *PlaylistEntry {
ds, err := strconv.Atoi(vje.Renderer.Duration)
if err != nil {
panic("invalid video duration: " + vje.Renderer.Duration)
}
return &PlaylistEntry{
ID: vje.Renderer.ID,
Title: vje.Renderer.Title.String(),
Author: vje.Renderer.Author.String(),
Duration: time.Second * time.Duration(ds),
Thumbnails: vje.Renderer.Thumbnail.Thumbnails,
}
}
type withRuns struct {
Runs []struct {
Text string `json:"text"`
} `json:"runs"`
}
func (wr withRuns) String() string {
if len(wr.Runs) > 0 {
return wr.Runs[0].Text
}
return ""
}