-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathyoutube.js
81 lines (70 loc) · 2.13 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
var website_name = 'Youtube';
var website_description = '\
<p>Welcome to Youtube!<p>\
<p>\
Before using, you need to\
<a href="plugin:set-api-key">set Youtube API Key</a>\
first.\
</p>\
<p>\
<a href="https://www.slickremix.com/docs/get-api-key-for-youtube/">How to get the API Key?</a>\
</p>'
var api_key = moonplayer.get_configuration('api_key');
var pageTokens = [];
function serialize(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
// Search
function search(key, page) {
if (key === 'plugin:set-api-key') {
set_api_key();
return;
}
if (api_key === undefined) {
moonplayer.warning('Please set the API key first!');
return;
}
var qs = {
'q': key,
'maxResults': 25,
'safeSearch': 'none',
'part': 'id,snippet',
'type': 'video',
'key': api_key
};
if (page === 1)
pageTokens = ['', ''];
else if (page < pageTokens.length)
qs['pageToken'] = pageTokens[page];
else {
moonplayer.warning("Cannot skip page due to the limitation of Youtube's API.");
return;
}
var url = 'https://www.googleapis.com/youtube/v3/search?' + serialize(qs);
moonplayer.get_content(url, function(content) {
var data = JSON.parse(content);
var result = [];
for (var i in data.items) {
var item = data.items[i];
var t = {
title: item.snippet.title,
url: 'https://www.youtube.com/watch?v=' + item.id.videoId
};
result.push(t);
}
if (page + 1 === pageTokens.length && 'nextPageToken' in data)
pageTokens.push(data.nextPageToken);
moonplayer.show_result(result);
});
}
// Set API key
function set_api_key() {
moonplayer.get_text('Please enter a new API Key:', api_key, function(text) {
api_key = text;
moonplayer.set_configuration('api_key', api_key);
moonplayer.information('Successfully set the API Key.');
});
}