3
0
mirror of https://github.com/reality/dbot.git synced 2024-11-24 21:09:31 +01:00
dbot/modules/youtube/youtube.js

97 lines
3.1 KiB
JavaScript
Raw Normal View History

2013-07-15 20:52:40 +02:00
/**
* Module Name: youtube
* Description: Various Youtube functionality
*/
var _ = require('underscore')._,
request = require('request');
var youtube = function(dbot) {
this.ApiRoot = 'https://gdata.youtube.com/feeds/api';
this.params = {
'alt': 'json',
'v': 2
};
2013-07-25 19:16:57 +02:00
this.LinkRegex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
2013-07-15 20:52:40 +02:00
this.api = {
'search': function(term, callback) {
var qs = _.clone(this.params);
request.get(this.ApiRoot + '/videos', {
'qs': _.extend(qs, {
'q': term,
'max-results': 1
}),
'json': true
}, function(error, response, body) {
callback(body);
}.bind(this));
}
};
this.internalAPI = {
'formatLink': function(v) {
var seconds = v['media$group']['yt$duration'].seconds,
minutes = Math.floor(seconds / 60),
seconds = ((seconds%60 < 10) ? "0"+seconds%60 : seconds%60);
if(!_.has(v, 'yt$rating')) {
v['yt$rating'] = {
'numLikes': 0,
'numDislikes': 0
};
}
if(!_.has(v, 'yt$statistics')) {
v['yt$statistics'] = { 'viewCount': 0 };
}
2013-10-13 06:17:17 +02:00
var res = dbot.t('yt_video', {
'title': v.title['$t'],
'plays': v['yt$statistics'].viewCount.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"),
'author': v.author[0].name['$t'],
'likes': v['yt$rating'].numLikes,
'dislikes': v['yt$rating'].numDislikes,
'minutes': minutes,
'seconds': seconds
2013-10-13 06:17:17 +02:00
});
2013-10-23 12:00:40 +02:00
var link = v.link[0].href.match(this.LinkRegex);
if(link) {
2014-01-27 02:45:00 +01:00
res += ' - https://youtu.be/' + link[2];
2013-10-13 06:17:17 +02:00
}
return res;
}.bind(this)
};
2013-07-19 22:15:50 +02:00
this.commands = {
2014-07-14 15:41:29 +02:00
'~yt': function(event) {
this.api.search(event.input[1], function(body) {
2013-07-25 19:07:00 +02:00
if(_.isObject(body) && _.has(body, 'feed') && _.has(body.feed, 'entry')) {
event.reply(this.internalAPI.formatLink(body.feed.entry[0]));
2013-07-19 22:15:50 +02:00
} else {
event.reply(dbot.t('yt_noresults'));
}
2013-07-25 19:16:57 +02:00
}.bind(this));
2013-07-19 22:15:50 +02:00
}
};
2014-07-14 15:42:56 +02:00
this.commands['~yt'].regex = [/^yt (.+)$/, 2];
2013-07-19 22:15:50 +02:00
2013-07-15 20:52:40 +02:00
this.onLoad = function() {
2013-07-25 19:16:57 +02:00
dbot.api.link.addHandler(this.name, this.LinkRegex,
function(match, name, callback) {
2013-07-15 20:52:40 +02:00
request.get(this.ApiRoot + '/videos/' + match[2], {
'qs': this.params,
'json': true
}, function(error, response, body) {
if(_.isObject(body) && _.has(body, 'entry')) {
callback(this.internalAPI.formatLink(body.entry));
2013-07-15 20:52:40 +02:00
}
}.bind(this));
2013-07-15 20:52:40 +02:00
}.bind(this));
}.bind(this);
};
exports.fetch = function(dbot) {
return new youtube(dbot);
};