kulmapaikka-ircbot/plugins/helpers/googleapi.js

107 lines
3.0 KiB
JavaScript

var Promise = require('promise');
var requestPromise = require('./requestPromise.js');
var google = require('googleapis');
var youtube = google.youtube('v3');
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
};
console.log(videosParams);
var thisResolve = resolve;
var thisReject = reject;
youtube.videos.list(videosParams, function(err, resp) {
//console.log('respo', resp);
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
};
console.log(resp);
console.log(resp.items[0]);
console.log(data);
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;
}
};
};