kulmapaikka-ircbot/plugins/helpers/googleapi.js

102 lines
3.1 KiB
JavaScript
Raw Normal View History

2018-04-29 17:37:07 +03:00
const Promise = require('promise');
const requestPromise = require('./requestPromise.js');
const {google} = require('googleapis');
const youtube = google.youtube('v3');
const apis = google.getSupportedAPIs();
2015-07-17 01:12:59 +03:00
module.exports = function(config) {
2018-04-29 17:37:07 +03:00
'use strict';
var apikey = config.keys.google.apiKey;
return {
getYoutubeVideoById: function(videoId) {
var promise = new Promise(function(resolve, reject) {
var videosParams = {
part: 'snippet,contentDetails,statistics',
id: videoId,
key: apikey
};
2018-04-29 17:37:07 +03:00
var thisResolve = resolve;
var thisReject = reject;
youtube.videos.list(videosParams, function(err, response) {
let resp = response.data;
if(typeof resp === 'undefined' || resp === null || typeof resp.items === 'undefined' || resp.items === null || resp.items.length <= 0) {
thisReject('No results');
return;
}
2015-07-17 01:12:59 +03:00
2018-04-29 17:37:07 +03:00
var duration = resp.items[0].contentDetails.duration;
var formattedTime = duration.replace("PT","").replace("H","t ").replace("M","m ").replace("S","s");
var data = {
videoId: videoId,
url: 'https://youtu.be/'+videoId,
title: resp.items[0].snippet.title,
channelTitle: resp.items[0].snippet.channelTitle,
statistics: resp.items[0].statistics,
duration: formattedTime
};
thisResolve(data);
});
});
return promise;
},
getYoutubeVideo: function(query) {
2015-07-17 01:12:59 +03:00
2018-04-29 17:37:07 +03:00
var params = {
part: 'snippet',
q: query,
type: 'video',
order: 'viewCount',
key: apikey
};
console.log(params);
var promise = new Promise(function(resolve, reject) {
youtube.search.list(params, function(err, resp) {
if (err) {
console.log('An error occured', err);
reject(err);
}
2015-07-17 01:12:59 +03:00
2018-04-29 17:37:07 +03:00
if(resp === null || resp.items === null) {
reject('No results (null)');
return;
}
2018-04-29 17:37:07 +03:00
if(resp.items.length <= 0) {
reject('No results');
return;
}
2015-07-17 01:12:59 +03:00
2018-04-29 17:37:07 +03:00
var videoId = resp.items[0].id.videoId;
var data = {
videoId: videoId,
url: 'https://youtu.be/'+videoId,
title: resp.items[0].snippet.title,
channelTitle: resp.items[0].snippet.channelTitle
};
2015-07-17 01:12:59 +03:00
2018-04-29 17:37:07 +03:00
var videosParams = {
part: 'snippet,contentDetails,statistics',
id: videoId,
key: apikey
};
youtube.videos.list(videosParams, function(err2, resp2) {
//console.log('respo', resp2);
if(resp2.items.length <= 0) {
reject('No results');
return;
}
data.statistics = resp2.items[0].statistics;
var duration = resp2.items[0].contentDetails.duration;
var formattedTime = duration.replace("PT","").replace("H","t ").replace("M","m ").replace("S","s");
data.duration = formattedTime;
resolve(data);
});
});
});
2015-07-17 01:12:59 +03:00
2018-04-29 17:37:07 +03:00
return promise;
}
};
2015-07-17 01:12:59 +03:00
};