-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
77 lines (68 loc) · 2.11 KB
/
index.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
var querystring = require('querystring');
var xhr = require('xhr');
if (!xhr.open) xhr = require('request');
var allowedProperties = [
'key',
'maxResults',
'part',
'playlistId',
'pageToken'
];
module.exports = function (term, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {}
}
var params = {
q: term,
part: opts.part || 'snippet,contentDetails',
maxResults: opts.maxResults || 30
};
var regexp = new RegExp(params.q, "gi");
Object.keys(opts).map(function (k) {
if (allowedProperties.indexOf(k) > -1) params[k] = opts[k]
});
xhr({
url: 'https://www.googleapis.com/youtube/v3/playlistItems?' + querystring.stringify(params),
method: 'GET'
}, function (err, res, body) {
if (err) return cb(err);
try {
var result = JSON.parse(body);
if (result.error) {
var error = new Error(result.error.errors.shift().message);
return cb(error)
}
var pageInfo = {
totalResults: result.pageInfo.totalResults,
resultsPerPage: result.pageInfo.resultsPerPage,
nextPageToken: result.nextPageToken,
prevPageToken: result.prevPageToken
};
var findings = result.items.reduce(function (allItems, item) {
var description = item.snippet.description;
var title = item.snippet.title;
if (regexp.test(title.concat(description))) {
allItems.push({
id: item.snippet.resourceId.videoId,
link: 'https://www.youtube.com/watch?v=' + item.snippet.resourceId.videoId,
kind: item.kind,
etag: item.etag,
publishedAt: item.snippet.publishedAt,
channelId: item.snippet.channelId,
channelTitle: item.snippet.channelTitle,
title: item.snippet.title,
description: item.snippet.description,
thumbnails: item.snippet.thumbnails,
playlistId: item.snippet.playlistId,
position: item.snippet.position
});
}
return allItems;
}, []);
return cb(null, findings, pageInfo)
} catch(e) {
return cb(e)
}
})
};