-
Notifications
You must be signed in to change notification settings - Fork 0
/
youtube-helper.js
73 lines (64 loc) · 1.99 KB
/
youtube-helper.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
const _ = require('lodash');
const googleapis = require('googleapis');
const youtube = googleapis.youtube({
version: 'v3',
auth: process.env.YOUTUBE_API_KEY
});
const request = require('request');
/**
* Thanks to https://gist.github.com/takien/4077195
*/
const getYoutubeIdFromUrl = (url) => {
let ID = '';
url = url.replace(/(>|<)/gi, '').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
if (url[2] !== undefined) {
ID = url[2].split(/[^0-9a-z_\-]/i);
ID = ID[0];
}
else {
ID = url;
}
return ID;
};
const getYoutubeUrlFromId = (id) => `https://www.youtube.com/watch?v=${id}`;
const YOUTUBE_MATCHER = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?/;
const getFirstSearchResultBySearchTerm = (searchTerm, cb) => {
youtube.search.list({
part: 'id,snippet',
q: searchTerm,
}, (err, data) => {
if (err) {
console.error('Error: ' + err);
}
if (!data || !data.items) {
return cb();
}
const firstResult = _.head(data.items);
console.log(firstResult);
cb({id: firstResult.id.videoId, title: firstResult.snippet.title});
});
};
const sanitizeYoutubeUrl = (youtubeUrl) => {
return getYoutubeUrlFromId(getYoutubeIdFromUrl(youtubeUrl));
};
const getTitleForYoutubeId = (id, cb) => {
const params = {part: 'snippet', id: id, key: process.env.YOUTUBE_API_KEY};
request({url: 'https://www.googleapis.com/youtube/v3/videos', qs: params}, (err, resp) => {
if (err) {
console.error('Error: ' + err);
}
const data = resp.body;
console.log(data);
const firstResult = _.head(data.items);
console.log(firstResult.snippet.title);
cb(firstResult.snippet.title);
});
};
module.exports = {
getYoutubeIdFromUrl,
getYoutubeUrlFromId,
YOUTUBE_MATCHER,
getTitleForYoutubeId,
sanitizeYoutubeUrl,
getFirstSearchResultBySearchTerm
};