-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathyoutube.go
253 lines (197 loc) · 5.33 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
package youtube
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"sync"
"time"
googleapiTransport "google.golang.org/api/googleapi/transport"
"google.golang.org/api/youtube/v3"
)
var (
envAPIKeyKey = "YOUTUBE_API_KEY"
envResolvedKey = strings.TrimSpace(os.Getenv(envAPIKeyKey))
)
type Client struct {
sync.RWMutex
apiKey string
service *youtube.Service
}
var (
errEmptyEnvAPIKey = fmt.Errorf("empty API Key from environment. Expecting env %q", envAPIKeyKey)
errEmptyAPIKey = fmt.Errorf("expecting a non-empty API key")
)
func clientWithKey(key string) (*Client, error) {
hc := &http.Client{
Transport: &googleapiTransport.APIKey{Key: key},
}
return NewWithHTTPClient(hc)
}
// New returns a client with an API Key derived
// from the environment, set as YOUTUBE_API_KEY.
func New() (*Client, error) {
apiKey := envResolvedKey
if apiKey == "" {
return nil, errEmptyEnvAPIKey
}
return clientWithKey(envResolvedKey)
}
// NewWithKey creates a client
// with the provided API Key.
func NewWithKey(apiKey string) (*Client, error) {
if apiKey == "" {
return nil, errEmptyAPIKey
}
return clientWithKey(envResolvedKey)
}
func NewWithHTTPClient(hc *http.Client) (*Client, error) {
service, err := youtube.New(hc)
if err != nil {
return nil, err
}
client := new(Client)
client.service = service
return client, nil
}
type SearchParam struct {
PageToken string `json:"page_token"`
// Query is the content to search for.
Query string `json:"query"`
// MaxPage is the maximum number of
// pages of items that you want returned
MaxPage uint64 `json:"max_page"`
// MaxResultsPerPage is the maximum number of
// items to be returned per pagination/page fetch.
MaxResultsPerPage uint64 `json:"max_results_per_page"`
// MaxRequestedItems is the threshold for the number
// of items that you'd like to stop the search after.
MaxRequestedItems uint64 `json:"max_requested_items"`
}
type SearchPage struct {
Index uint64
Err error
Items []*youtube.SearchResult
}
type ResultsPage struct {
Index uint64
Err error
Items []*youtube.Video
}
var videoListFields = []string{"id", "snippet", "statistics"}
func (c *Client) ById(ctx context.Context, ids ...string) (chan *ResultsPage, error) {
idsCSV := strings.Join(ids, ",")
req := c.service.Videos.List(videoListFields).Id(idsCSV)
return c.doVideos(ctx, req, nil)
}
// MostPopular returns the currently most popular videos.
// Specifying MaxPage, MaxResultsPerPage help
// control how many items should be retrieved.
func (c *Client) MostPopular(ctx context.Context, param *SearchParam) (chan *ResultsPage, error) {
req := c.service.Videos.List(videoListFields).Chart("mostPopular")
return c.doVideos(ctx, req, param)
}
func (c *Client) doVideos(ctx context.Context, req *youtube.VideosListCall, param *SearchParam) (chan *ResultsPage, error) {
pagesChan := make(chan *ResultsPage)
if param == nil {
param = new(SearchParam)
}
go func() {
defer close(pagesChan)
ticker := time.NewTicker(1e8)
defer ticker.Stop()
maxPageIndex := param.MaxPage
maxResultsPerPage := param.MaxResultsPerPage
maxRequestedItems := param.MaxRequestedItems
pageIndex := uint64(0)
itemsCount := uint64(0)
pageToken := param.PageToken
req = req.Context(ctx)
for {
if maxRequestedItems > 0 && itemsCount >= maxRequestedItems {
break
}
if maxPageIndex > 0 && pageIndex >= maxPageIndex {
break
}
// If there are still more pages, let's keep searching
if pageToken != "" {
req = req.PageToken(pageToken)
}
if maxResultsPerPage > 0 {
req = req.MaxResults(int64(maxResultsPerPage))
}
res, err := req.Do()
if err != nil {
pagesChan <- &ResultsPage{Err: err, Index: pageIndex}
return
}
pageToken = res.NextPageToken
// Increment our stoppers and that pageIndex
itemsCount += uint64(len(res.Items))
pageIndex += 1
page := &ResultsPage{
Index: pageIndex,
Items: res.Items,
}
pagesChan <- page
if pageToken == "" {
break
}
<-ticker.C
}
}()
return pagesChan, nil
}
func (c *Client) Search(ctx context.Context, param *SearchParam) (chan *SearchPage, error) {
pagesChan := make(chan *SearchPage)
go func() {
defer close(pagesChan)
ticker := time.NewTicker(1e8)
defer ticker.Stop()
query := param.Query
maxPageIndex := param.MaxPage
maxResultsPerPage := param.MaxResultsPerPage
maxRequestedItems := param.MaxRequestedItems
req := c.service.Search.List([]string{"id", "snippet"}).Q(query)
if maxResultsPerPage > 0 {
req = req.MaxResults(int64(maxResultsPerPage))
}
req = req.Context(ctx)
pageIndex := uint64(0)
itemsCount := uint64(0)
pageToken := param.PageToken
for {
if maxRequestedItems > 0 && itemsCount >= maxRequestedItems {
break
}
if maxPageIndex > 0 && pageIndex >= maxPageIndex {
break
}
// If there are still more pages, let's keep searching
if pageToken != "" {
req = req.PageToken(pageToken)
}
res, err := req.Do()
if err != nil {
pagesChan <- &SearchPage{Err: err, Index: pageIndex}
return
}
pageToken = res.NextPageToken
// Increment our stoppers and that pageIndex
itemsCount += uint64(len(res.Items))
pageIndex += 1
page := &SearchPage{
Index: pageIndex,
Items: res.Items,
}
pagesChan <- page
if pageToken == "" {
break
}
<-ticker.C
}
}()
return pagesChan, nil
}