Twitter Message Notifier

By Erik Vold Uploaded Nov 16, 2009
jetpack.future.import("storage.simple");
(function(){
	var storage = jetpack.storage.simple, msgs=[], types=["dm","mention"], count=1, apiInterval=300000, notificationInterval=7500;
	types.forEach(function(e){if(!storage[e]) storage[e]="";});
	var handleData=function(data,type){
		var dms=eval(data);
		if(!dms || dms.length==0) return false;
		storage[type]=dms[0].id;
		if(type=="dm") msgs=dms.map(function(e){return {title:e.sender_screen_name, body:e.text}}).concat(msgs);
		else if (type=="mention") msgs=dms.map(function(e){return {title:e.user.screen_name, body:e.text}}).concat(msgs);
		return true;
	}
	var checkForMsgs=function(justOne){
		var i=0, cont=function(){ if(i==2) handleMsgs();};
		jetpack.lib.twitter.direct_messages({
			since_id:storage[types[0]],
			count:count,
			success: function (data, status){
				if (status == "success") handleData(data, types[0]);
				cont(i++);
			},
			error: function(xhr, errMsg, errObj){ cont(i++); }
		});
		if(justOne) return handleMsgs();
		jetpack.lib.twitter.statuses.mentions({
			since_id:storage[types[1]],
			count:count,
			success: function (data, status){
				if(status == "success") handleData(data,types[1]);
				cont(i++);
			},
			error: function(xhr, errMsg, errObj){ cont(i++); }
		});
	};
	var handleMsgs=function(){
		if (!msgs.length) return setTimeout(checkForMsgs, apiInterval);
		var msg=msgs.pop();
		jetpack.notifications.show({ title: msg.title, body: msg.body, icon: "http://a1.twimg.com/a/1258070043/images/favicon.ico" });
		return setTimeout(handleMsgs,notificationInterval);
	}
	checkForMsgs(true);
	count=50;
})();