~gjabell/go-yt

ref: 0eb039002194dfea6aec89cdc9013f95c21d4a3d go-yt/yt.go -rw-r--r-- 5.0 KiB
0eb03900Galen Abell Refactor extractor to use HTML instead of regex 5 months ago
                                                                                
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
package yt

import (
	"encoding/json"
	"errors"
	"io"

	"net/http"
	"net/url"
	"strings"

	"golang.org/x/net/html"
)

// SearchResult contains metadata about a Youtube video.
type SearchResult struct {
	Description string
	Channel     Channel
	ID          string
	Length      string // TODO convert to int?
	Title       string
	Thumbnails  []Thumbnail
	ViewCount   string
	VideoURL    string
}

// Channel contains a video's channel metadata.
type Channel struct {
	ID           string
	Name         string
	CanonicalURL string
}

// Thumbnail contains a video's thumbnail URL and dimensions.
type Thumbnail struct {
	URL    string
	Height int
	Width  int
}

var (
	searchURL    = "https://www.youtube.com/results"
	searchParams = "EgIQAQ%3D%3D"
	watchURL     = "https://www.youtube.com/watch"
)

// Search Youtube for a given query by page.
// Returns a list of SearchResults or an error if one occurred.
func Search(query string, page int) ([]SearchResult, error) {
	url, err := makeURL(searchURL, map[string]string{
		"search_query": query,
		"sp":           searchParams,
		"page":         string(page),
	})
	if err != nil {
		return nil, err
	}

	result, err := http.Get(url)
	if err != nil {
		return nil, err
	}

	data, err := parseDataFromHtml(result.Body)
	if err != nil {
		return nil, err
	}

	return parseDataFromJson(data)
}

func parseDataFromHtml(r io.Reader) (string, error) {
	n, err := html.Parse(r)
	if err != nil {
		return "", err
	}

	n = findNode(n)
	if n == nil {
		return "", errors.New("failed to parse YouTube data from HTML")
	}

	data := n.Data
	data = strings.TrimLeftFunc(data, func(r rune) bool {
		return r != '{'
	})
	data = strings.TrimRightFunc(data, func(r rune) bool {
		return r != '}'
	})

	return data, nil
}

func nodeMatches(n *html.Node) bool {
	if n == nil || n.Type != html.ElementNode || n.Data != "script" || n.FirstChild == nil {
		return false
	}

	return strings.HasPrefix(n.FirstChild.Data, "var ytInitialData")
}

func findNode(n *html.Node) *html.Node {
	if nodeMatches(n) {
		return n.FirstChild
	}

	for c := n.FirstChild; c != nil; c = c.NextSibling {
		result := findNode(c)
		if result != nil {
			return result
		}
	}

	return nil
}

func makeURL(path string, params map[string]string) (string, error) {
	parsedURL, err := url.Parse(path)
	if err != nil {
		return "", err
	}

	query := url.Values{}
	for key, param := range params {
		query.Set(key, param)
	}

	parsedURL.RawQuery = query.Encode()
	return parsedURL.String(), nil
}

type wrapper struct {
	Contents struct {
		TwoColumnSearchResultsRenderer struct {
			PrimaryContents struct {
				SectionListRenderer struct {
					Contents []struct {
						ItemSectionRenderer struct {
							Contents []struct {
								VideoRenderer videoRenderer
							}
						}
					}
				}
			}
		}
	}
}

type videoRenderer struct {
	DescriptionSnippet struct {
		Runs []struct {
			Text string
		}
	}
	LengthText struct {
		SimpleText string
	}
	OwnerText struct {
		Runs []struct {
			NavigationEndpoint struct {
				BrowseEndpoint struct {
					BrowseID         string
					CanonicalBaseURL string
				}
			}
			Text string
		}
	}
	Title struct {
		Runs []struct {
			Text string
		}
	}
	Thumbnail struct {
		Thumbnails []Thumbnail
	}
	VideoID       string
	ViewCountText struct {
		SimpleText string
	}
}

func parseDataFromJson(data string) ([]SearchResult, error) {
	var w wrapper

	if err := json.Unmarshal([]byte(data), &w); err != nil {
		return nil, err
	}

	sectionListRendererContents := w.Contents.TwoColumnSearchResultsRenderer.
		PrimaryContents.SectionListRenderer.Contents
	if len(sectionListRendererContents) < 1 {
		return nil, errors.New("parse error: SectionListRenderer contents too short")
	}
	videoRenderers := sectionListRendererContents[0].ItemSectionRenderer.Contents

	var videoData []SearchResult
	for _, renderer := range videoRenderers {
		result := convertYoutubeData(renderer.VideoRenderer)
		if result != nil {
			videoData = append(videoData, *result)
		}
	}

	return videoData, nil
}

func convertYoutubeData(renderer videoRenderer) *SearchResult {
	// check for invalid data (video ID should always be non-empty)
	if renderer.VideoID == "" {
		return nil
	}

	description := ""
	if len(renderer.DescriptionSnippet.Runs) > 0 {
		description = renderer.DescriptionSnippet.Runs[0].Text
	}

	var channel Channel
	if len(renderer.OwnerText.Runs) > 0 {
		owner := renderer.OwnerText.Runs[0]
		channel = Channel{
			ID:           owner.NavigationEndpoint.BrowseEndpoint.BrowseID,
			Name:         owner.Text,
			CanonicalURL: owner.NavigationEndpoint.BrowseEndpoint.CanonicalBaseURL,
		}
	}

	title := ""
	if len(renderer.Title.Runs) > 0 {
		title = renderer.Title.Runs[0].Text
	}

	videoURL, err := makeURL(watchURL, map[string]string{
		"v": renderer.VideoID,
	})
	if err != nil {
		videoURL = ""
	}

	return &SearchResult{
		Description: description,
		Channel:     channel,
		ID:          renderer.VideoID,
		Length:      renderer.LengthText.SimpleText,
		Title:       title,
		Thumbnails:  renderer.Thumbnail.Thumbnails,
		ViewCount:   renderer.ViewCountText.SimpleText,
		VideoURL:    videoURL,
	}
}