From 614520443fe135a5de6d54f7903ee8591a07ee05 Mon Sep 17 00:00:00 2001 From: reality Date: Thu, 24 Oct 2013 09:47:56 +0000 Subject: [PATCH] get a youtube link for last fm ~listening. note: clean up yt api later --- modules/lastfm/lastfm.js | 20 ++++++++++++++++---- modules/youtube/youtube.js | 24 ++++++++++++++++-------- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/modules/lastfm/lastfm.js b/modules/lastfm/lastfm.js index 10f3733..952c41f 100644 --- a/modules/lastfm/lastfm.js +++ b/modules/lastfm/lastfm.js @@ -29,19 +29,31 @@ var lastfm = function(dbot) { event.reply('Unknown Last.FM user.'); } else if(_.has(body, 'recenttracks') && !_.isUndefined(body.recenttracks.track[0])) { var track = body.recenttracks.track[0]; + term = track.name + ' ' + track.artist['#text'], + output = ''; if(_.has(track, '@attr') && _.has(track['@attr'], 'nowplaying') && track['@attr'].nowplaying == 'true') { - event.reply(dbot.t('now_listening', { + output = dbot.t('now_listening', { 'user': event.user, 'track': track.name, 'artist': track.artist['#text'] - })); + }); } else { - event.reply(dbot.t('last_listened', { + output = dbot.t('last_listened', { 'user': event.user, 'track': track.name, 'artist': track.artist['#text'] - })); + }); } + dbot.api.youtube.search(term, function(body) { + if(_.isObject(body) && _.has(body, 'feed') && _.has(body.feed, 'entry')) { + var v = body.feed.entry[0]; + link = v.link[0].href.match(dbot.modules.youtube.LinkRegex); + if(link) { + output += ' - http://youtu.be/' + link[2]; + } + } + event.reply(output); + }); } else { event.reply(dbot.t('no_listen', { 'user': event.user })); } diff --git a/modules/youtube/youtube.js b/modules/youtube/youtube.js index 1c8ee7d..60c1812 100644 --- a/modules/youtube/youtube.js +++ b/modules/youtube/youtube.js @@ -13,6 +13,21 @@ var youtube = function(dbot) { }; this.LinkRegex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/; + 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, @@ -50,14 +65,7 @@ var youtube = function(dbot) { this.commands = { '~youtube': function(event) { - var qs = _.clone(this.params); - request.get(this.ApiRoot + '/videos', { - 'qs': _.extend(qs, { - 'q': event.input[1], - 'max-results': 1 - }), - 'json': true - }, function(error, response, body) { + this.api.search(event.input[1], function(body) { if(_.isObject(body) && _.has(body, 'feed') && _.has(body.feed, 'entry')) { event.reply(this.internalAPI.formatLink(body.feed.entry[0])); } else {