kulmapaikka-ircbot/plugins/helpers/googleapi.js
2019-08-13 19:37:22 +03:00

104 lines
3.2 KiB
JavaScript

const Promise = require('promise')
const {google} = require('googleapis')
const youtube = google.youtube('v3')
const logger = require('../../logger')
module.exports = function (config) {
'use strict'
var apikey = config.keys.google.apiKey
return {
getYoutubeVideoById: function (videoId) {
return 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) {
if (err !== null) {
logger.error(err)
thisReject(new Error('Google error'))
return
}
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)
})
})
},
getYoutubeVideo: function (query) {
var params = {
part: 'snippet',
q: query,
type: 'video',
order: 'viewCount',
key: apikey
}
logger.debug(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(new Error('No results (null)'))
return
}
if (resp.items.length <= 0) {
reject(new Error('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(new Error('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
}
}
}