-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
65 lines (63 loc) · 3.01 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
const dotenv = require('dotenv').config();
const fetch = require('node-fetch');
const moment = require('moment');
class searchPlaylist {
async searchPlaylist(playlistURL, result) {
if (!dotenv.parsed.YT_API_KEY) {
// Check for API Key
throw new Error('Youtube API Key not found. Enter your API key into a .env file such as: YT_API_KEY=MYAPIKEY');
}
if (!playlistURL) {
// Check for playlistURL argument
throw new Error('A playlist URL is needed.');
}
if (!/list=/.test(playlistURL)) {
// Check if the list is defined
throw new Error('Invalid playlist URL.');
}
let playlistID = /[a-zA-Z0-9_\.-]+/g.exec(playlistURL.split('list=')[1])[0]; // Get playlist ID
// Search for playlist
fetch(`https://www.googleapis.com/youtube/v3/playlistItems?key=${dotenv.parsed.YT_API_KEY}&part=snippet&playlistId=${playlistID}&maxResults=50`, {method: 'GET'})
.then(res => res.json())
.then(json => {
if (!json) {
throw new Error('Data not received.');
}
if (json.error && json.error.message == 'API key not valid. Please pass a valid API key.') {
throw new Error('API key is invalid.');
} else if (json.error && json.error.message == "The playlist identified with the request's <code>playlistId</code> parameter cannot be found.") {
throw new Error('Playlist not found.');
}
let videoIDs = [];
// Push video ID's into array
Object.values(json.items).forEach(video => {
videoIDs.push(video.snippet.resourceId.videoId);
});
fetch(`https://www.googleapis.com/youtube/v3/videos?key=${dotenv.parsed.YT_API_KEY}&id=${videoIDs.toString()}&part=contentDetails`, {method: 'GET'})
.then(res => res.json())
.then(videoJSON => {
if (!videoJSON) {
throw new Error('Data not received.');
}
if (json.error && json.error.message == 'API key not valid. Please pass a valid API key.') {
throw new Error('API key is invalid.');
}
var videos = [];
// Loop through results
for (let i = 0; i < json.items.length; i++) {
let video = json.items[i].snippet;
let videoObject = {
channelName: video.channelTitle,
title: video.title,
thumbnails: video.thumbnails,
duration: moment.duration(Object.values(videoJSON.items)[i].contentDetails.duration, moment.ISO_8601).asSeconds(),
url: `https://youtube.com/watch?v=${video.resourceId.videoId}`
}
videos.push(videoObject);
}
return result(videos);
});
});
}
}
module.exports = new searchPlaylist;