From 3a7e65ca638bfcd615dcd24d4ee800596621be8b Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Fri, 4 May 2012 16:57:31 +0200 Subject: o Adding a small module to process application/vnd.collection+json documents. --- lib/BitrafBot.js | 47 ++++++++++++++++++++++------------------------- 1 file changed, 22 insertions(+), 25 deletions(-) (limited to 'lib') diff --git a/lib/BitrafBot.js b/lib/BitrafBot.js index 9388ddb..92bb8d9 100644 --- a/lib/BitrafBot.js +++ b/lib/BitrafBot.js @@ -3,9 +3,27 @@ var IRC = require('../node_modules/node-irc/IRC.js').IRC , irc = new IRC('irc.freenode.net', 6667) , url = require('url') , http = require('http') + , collection_json = require('collection_json') , _ = require('underscore'); -var BitrafBot = function(config) { +function onCheckinsEnd(chunks) { + var collection = collection_json.fromString(chunks); +// console.log("collection.items", collection.items); + var checkins = -1, lastCheckin; + collection.mapItemData(function(data) { + checkins = parseInt(data["checkins"]); + lastCheckin = data["last-checkin"]; + }); + if(checkins != -1) { + return 'checkins: ' + checkins + ', last checkin: ' + (typeof lastCheckin === 'undefined' ? 'unknown' : lastCheckin); + } + else { + return 'Could not find any checkins'; + } +} +module.exports.onCheckinsEnd = onCheckinsEnd; + +function BitrafBot(config) { var nick = ''; var nickCount = 0; var nickAdditions = [ '', '^', '-', '_', '\\', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]; @@ -39,28 +57,8 @@ var BitrafBot = function(config) { chunks += chunk; }); res.on('end', function () { - try { - data = JSON.parse(chunks); - var checkins = -1; - var lastCheckin = 'unknown'; - _.each(data['collection'].items, function(item, i) { - _.each(item.data, function(item, i) { - switch(item.name) { - case 'checkins': checkins = parseInt(item.value); break; - case 'last-checkin': lastCheckin = item.value; break; - } - }); - }); - if(checkins != -1) { - irc.privmsg(to, 'checkins: ' + checkins + ', last checkin: ' + lastCheckin); - } - else { - irc.privmsg(to, 'Could not find any checkins'); - } - } - catch(ex) { - irc.privmsg(to, 'Could not parse document'); - } + var s = onCheckinsEnd(chunks); + irc.privmsg(to, s); }); }).on('error', function(e) { irc.privmsg(to, 'Problem with request: ' + e.message); @@ -85,5 +83,4 @@ var BitrafBot = function(config) { irc.quit('bye'); }); } - -module.exports = BitrafBot; +module.exports.BitrafBot = BitrafBot; -- cgit v1.2.3