kulmapaikka-ircbot/plugins/helpers/googleapi.js
2018-04-29 17:37:07 +03:00

102 lines
3.1 KiB
JavaScript

const Promise = require('promise');
const requestPromise = require('./requestPromise.js');
const {google} = require('googleapis');
const youtube = google.youtube('v3');
const apis = google.getSupportedAPIs();
module.exports = function(config) {
'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
};
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;
}
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) {
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);
}
if(resp === null || resp.items === null) {
reject('No results (null)');
return;
}
if(resp.items.length <= 0) {
reject('No results');
return;
}
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
};
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);
});
});
});
return promise;
}
};
};