-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathyoutube.js
298 lines (248 loc) · 7.37 KB
/
youtube.js
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
/*
getting youtube videos
*/
var request = require('request'),
moment = require('moment'),
_ = require('lodash');
var MINIMUM_VIDEO_DURATION_SEC = 18;
var REQUEST_DELAY_MSEC = 2000;
var API_KEY = process.env.YT_API_KEY;
function pad(num, size) {
var s = num + '';
while (s.length < size) s = '0' + s;
return s;
}
function parseVids(obj) {
if (obj.hasOwnProperty('items')) {
var items = obj['items'];
return items.map(function(item) {
var duration = moment.duration(
item['contentDetails']['duration']).asSeconds();
return {
id: item['id'],
uploaded: item['snippet']['publishedAt'],
viewCount: item['statistics']['viewCount'],
duration: duration
};
});
}
return [];
}
function createQueries(startIndex, endIndex, tags) {
queries = [];
// construct queries to consume
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
var j = startIndex;
for (var j = endIndex; j >= startIndex; j--) {
var params = {};
params['q'] = '\"' + tag + ' ' + pad(j, 4) + '\"';
queries.push(params);
}
}
return queries;
}
/*
search youtube
params {
q: the search term
nextPageToken: optional next page token
}
cb(error, vids, nextParams)
*/
function search(params, cb) {
var thisWeek = moment().add(-7, 'days').toISOString();
params['key'] = API_KEY;
params['part'] = params['part'] || 'snippet';
params['type'] = params['type'] || 'video';
params['order'] = params['order'] || 'date';
params['maxResults'] = 50;
params['videoEmbeddable'] = 'true';
params['publishedAfter'] = thisWeek;
request({
uri: 'https://www.googleapis.com/youtube/v3/search',
qs: params
}, function(error, response, body) {
if (error) {
cb(error, [], null);
return;
}
var data = JSON.parse(body);
if (data.hasOwnProperty('error')) {
cb(body, [], null);
return;
}
var ids = data['items'].map(
function(item) {return item['id']['videoId'];});
var nextToken = data['nextPageToken'];
var nextParams;
if (nextToken) {
nextParams = {};
nextParams['nextPageToken'] = nextToken;
nextParams['q'] = params['q'];
nextParams['key'] = params['key'];
nextParams['part'] = params['part'];
nextParams['type'] = params['type'];
nextParams['order'] = params['order'];
nextParams['maxResults'] = params['maxResults'];
nextParams['videoEmbeddable'] = params['videoEmbeddable'];
nextParams['publishedAfter'] = params['publishedAfter'];
}
listVideos(ids, function(error, vids) {
vids = vids.filter(function(vid) {
return vid.duration > MINIMUM_VIDEO_DURATION_SEC;
});
cb(error, vids, nextParams)
});
});
}
/*
List endpoint
gets additional metadata for video ids
videoIds: ['ckjkfjl3', 'lckajckl2']
cb: function(error, videoObjects)
*/
function listVideos(videoIds, cb) {
var params = {};
params['key'] = API_KEY;
params['part'] = 'id,statistics,contentDetails,snippet';
params['id'] = videoIds.join(',');
params['maxResults'] = 50;
request({
uri: 'https://www.googleapis.com/youtube/v3/videos',
qs: params
}, function(error, response, body) {
if (error) {
cb(error, []);
return;
}
var data = JSON.parse(body);
if (data.hasOwnProperty('error')) {
cb(data, []);
return;
}
var videos = parseVids(data);
cb(null, videos);
});
}
/*
GET Playlist
*/
function getPlaylist(playlistId, cb) {
var params = {
key: API_KEY,
part: 'id,snippet',
playlistId: playlistId,
maxResults: 50
}
request({
uri: 'https://www.googleapis.com/youtube/v3/playlistItems',
qs: params,
}, function(error, response, body) {
if (error) {
console.log(error);
cb(error, []);
return;
}
var data = JSON.parse(body);
var vids = data['items'].map(function(item) {
return item['snippet']['resourceId']['videoId'];
});
cb(error, vids);
});
}
function createRandomString() {
return Math.random().toString(36).substring(2, 10);
}
var mockStrings = [
'7lofyg23',
'u3tfzhxh',
'905uypzx',
'wmcbs043',
'aaa',
'bbb'
];
var mockIdx = 0;
function createMockString() {
mockIdx = (mockIdx + 1) % mockStrings.length;
return mockStrings[mockIdx];
}
function mockSearch(params, cb) {
/*
video object
{
id: 'lakjfkjal'
uploaded: timestamp // verify if this is a utc string
viewCount: 34
duration: 2384
}
*/
// returns 2 random generated strings
var videos = [];
for (var i = 0; i < 2; i++) {
videos.push({
id: createMockString(),
uploaded: (new Date()).toISOString(),
viewCount: 10,
duration: 100
});
}
cb(null, videos, null);
}
/*
retrieves youtube videos of the form
TAG 000X
ex. DSC 0001
tags: is an array of number prefixes ex. dsc, img
startIndex: 'DSC 0001' would be 1
endIndex: 'DSC 0234' would be 234
vidCallback: function(query, vids) processes an array of vidids
endCallback: function() called when everything is done
*/
function getVids(args) {
var tags = args.tags || [];
var startIndex = args.startIndex || 1;
var endIndex = args.endIndex || 10;
var maxResultsPerQuery = args.maxResultsPerQuery || -1;
var vidCallback = args.vidCallback;
console.log('Getting youtube vids:');
console.log('tags: ', tags);
console.log('startIndex: ', startIndex);
console.log('endIndex: ', endIndex);
console.log('maxResultsPerQuery: ', maxResultsPerQuery);
console.log('');
var queries = createQueries(startIndex, endIndex, tags);
// shuffle them so the indices are not contiguous
queries = _.shuffle(queries);
var queryVidCount = {}; // keeps track of page counts per query
function work() {
var params = queries.pop();
console.log('search for: ', params['q']);
search(params, function(error, vids, nextParams) {
if (error) {
console.error('Search error: ' + error);
return;
}
console.log('retrieved', vids.length, 'vids');
vidCallback(params.q, vids);
if (queryVidCount[params.q]) {
queryVidCount[params['q']] += vids.length;
} else {
queryVidCount[params['q']] = vids.length;
}
// check if we need to schedule more work
if (nextParams && queryVidCount[params['q']] < maxResultsPerQuery) {
console.log('get more...');
queries.push(nextParams);
}
if (queries.length > 0) {
setTimeout(work, REQUEST_DELAY_MSEC);
}
});
}
work();
}
exports.listVideos = listVideos;
exports.search = search;
exports.getVids = getVids;
exports.getPlaylist = getPlaylist;