Artifact Content
Not logged in

Artifact 1fdf7ce3e9abed8367e625a81ba7c9987fcc0f95:


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Codebit Grake \_(°-°)_/[\/]
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// GMail Javascript Handler
// part of the project "Opera Google Mail Extension"
// (see http://codebit.de/oex/google-mail for more info)
// @author Tom Schreiber (tom.schreiber@codebit.de)
// @version SVN: 196 2012-06-20 11:49:58Z tom.schreiber@tomhost.de $
function Gmail_Account() {
	this.UniqueID = this.name = this.FeedLabel = this.AccountLink = "";
	this.UnreadCount = 0; this.HasNewMessages = false;
	this.UnreadMessages = new Array(), UpdateRunningTO = null;
}
function Gmail_Message() {
	this.Modified = new Date(); this.Timestring = this.Id = "";
}
function Grake() {
	var GmailURL="https://mail.google.com/mail/",
		GmailAccountsURL="https://accounts.google.com/AddSession",
		EmailPattern=/([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4})/ig,
		Accounts=[], AccountsNew=[], AccountsCompleted=0, ReqRunning=false,
		RequestTimer='';
	this.GetAccounts = function() { return Accounts; }
	this.GetAccountsCount = function() { return Accounts.length; }
	this.GetTotalUnreadCount = function() {
		var unreadCount=0;
		for(var i=0; i<Accounts.length;i++)
			unreadCount += Number(Accounts[i].UnreadCount);
		return unreadCount;
	}
	this.GetRealNewMessageBool = function() {
		for(var i=0;i<Accounts.length;i++)
			if(Accounts[i].HasNewMessages) return true;
		return false;
	}
	this.UpdateAccounts = function() {
		UpdateRunningTO = setTimeout(function(){Grake.UpdateAccounts()},60000);
		if(ReqRunning) return;
		ReqRunning = true;
		RequestTimer = window.setTimeout(function(){ReqRunning=false;},15000);
		var http1 = new XMLHttpRequest(), result1='';
		if(http1.overrideMimeType) http1.overrideMimeType('text/xml');
		http1.open("GET",GmailAccountsURL,false);
		http1.onreadystatechange = function() {
			if(http1.readyState==4&&http1.status==200&&http1.responseText)
				result1 = http1.responseText;
			else result1 = false;
		}
		http1.send(null);
		if(result1) {
			var accounts = result1.match(EmailPattern), mailTes = null;
			if(accounts&&accounts.length) {
				DebugMessage("Found "+accounts.length+" active Accounts");
				var detectedAccounts=[], accountDetectionCompleted=0, http2 = '';
				for(var i=0;i<accounts.length;i++) {
					http2 = new XMLHttpRequest(), result2='';
					if(http2.overrideMimeType) http2.overrideMimeType('text/xml');
					http2.open("GET",GmailURL+"u/"+i+"/feed/atom/",false);
					http2.onreadystatechange = function() {
						if(http2.readyState==4&&http2.status==200&&http2.responseText)
							result2 = http2.responseXML;
						else result2 = false;
					}
					http2.send(null);
					if(result2) {
						mailTes = result2.documentElement;
						mailTes = mailTes.getElementsByTagName("title")[0].childNodes[0];
						var mail = ""+mailTes.nodeValue.match(EmailPattern);
						var link = GmailURL+"u/"+i+"";
						detectedAccounts.push({name:mail,url:link});
					}
					else DebugMessage("Ajax-Error 1");
					accountDetectionCompleted++;
					if(accountDetectionCompleted==accounts.length)
					if(detectedAccounts.length>0) GetFeeds(detectedAccounts);
					else {
						Accounts = [];
						ReqRunning = false;
						clearTimeout(RequestTimer);
						DebugMessage("No active Account found");
						Update_callback();
					}
				}
			}
			else {
				Accounts = [];
				ReqRunning = false;
				clearTimeout(RequestTimer);
				DebugMessage("No active Account found");
				Update_callback();
			}
		}
		else DebugMessage("Ajax-Error 2");
	}
	function GetFeeds(detectedAccounts) {
		DebugMessage("Get "+detectedAccounts.length+" Message-Feeds now");
		FeedsCompleted = 0;
		AccountsNew = [];
		for(var i=0;i<detectedAccounts.length;i++) {
			var unique=detectedAccounts[i].name.replace(/[^a-zA-Z 0-9]+/g,'');
			var feedLabel="inbox";
			// WORKAROUND: Use label '' for 'inbox' (becuase of counter) -> Issue 75
			// -> http://code.google.com/p/google-mail-oex/issues/detail?id=75
			if(feedLabel=="inbox") feedLabel = '';
			var feed=detectedAccounts[i].url+"/feed/atom/"+feedLabel;
			DebugMessage("Get Feed for "+detectedAccounts[i].name+" : "+feed );
			var http3 = new XMLHttpRequest(), result3='';
			if(http3.overrideMimeType) http3.overrideMimeType('text/xml');
			http3.open("GET",feed,false);
			http3.onreadystatechange = function() {
				if(http3.readyState==4&&http3.status==200&&http3.responseText)
					result3 = http3.responseXML;
				else result3 = false;
			}
			http3.send(null);
			if(result3) {
				var mt = result3.documentElement.getElementsByTagName("title")[0];
				var mail = mt.childNodes[0].nodeValue.match(EmailPattern);
				var link = feed;
				link = link.replace(/http:/g,'https:')
				link = link.replace(/\/feed\/atom\//g,'')
				var mailLink=link, currentAccountNumber=0,
					numMatches=feed.match(/\/u\/([^\/]*)\//);
				if(numMatches!=null&&numMatches.length>0)
					currentAccountNumber = numMatches[1];
				var currentAccount=new Gmail_Account();
				currentAccount.Name = ""+mail;
				var cn = currentAccount.Name.replace(/[^a-zA-Z 0-9]+/g,'');
				currentAccount.UniqueId = cn.toLowerCase();
				currentAccount.FeedLabel = "inbox";
				var messages=[],
					nodes=result3.documentElement.getElementsByTagName("entry");
				for(var i=0;i<nodes.length;i++) {
					var msg = new Gmail_Message(), ns = nodes[i];
					var nsd = ns.getElementsByTagName("modified")[0];
					msg.Id = ns.getElementsByTagName("id")[0].childNodes[0].nodeValue;
					msg.Modified = new Date(nsd.childNodes[0].nodeValue);
					messages.push(msg);
				}
				var currentIndex=-1;
				for(var x=0; x<Accounts.length;x++) {
					if(Accounts[x].Name==currentAccount.Name) {
						currentIndex = x;
						DebugMessage("Account "+mail+" is found at index "+currentIndex);
						break;
					}
				}
				if(currentIndex==-1) {
						if(messages.length>0) currentAccount.HasNewMessages = true;
				}
				else {
					if(messages.length>Accounts[currentIndex].UnreadMessages.length)
						currentAccount.HasNewMessages = true;
					else if(messages.length==0)
						currentAccount.HasNewMessages = false;
					else {
						for(var j=0;j<messages.length;j++) {
							var isUnique = true, ciTest = null;
							for(var ii=0;ii<Accounts[currentIndex].UnreadMessages.length;ii++)
								ciTest = Accounts[currentIndex].UnreadMessages[ii];
								ciTest = ciTest.Id.localeCompare(messages[j].Id);
								if(ciTest==0) { isUnique = false; break; }
								if(isUnique) { currentAccount.HasNewMessages = true; break; }
						}
					}
				}
				messages.sort(function(a,b){
					var t1=new Date(a.modified), t2=new Date(b.modified);
					return t2.getTime()-t1.getTime();
				});
				currentAccount.UnreadMessages = messages;
				currentAccount.AccountLink = mailLink;
				var cUn = result3.documentElement.getElementsByTagName("fullcount")[0];
				currentAccount.UnreadCount = cUn.childNodes[0].nodeValue;
				if(messages.length>currentAccount.UnreadCount)
					currentAccount.UnreadCount = messages.length;
				AccountsNew.push(currentAccount);
				DebugMessage("Got "+currentAccount.UnreadCount+" unread for "+mail);
			}
			FeedsCompleted++;
			if(FeedsCompleted==detectedAccounts.length) {
				AccountsNew.sort(function(a,b) {
					if(a.UniqueId<b.UniqueId) return -1
					if(a.UniqueId>b.UniqueId) return 1
					return 0
				});
				Accounts = AccountsNew;
				ReqRunning = false;
				clearTimeout(RequestTimer);
				DebugMessage("Every Request is returned, calling the Update_callback");
				Update_callback();
			}
		}
	}
	function DebugMessage(message,type) {
		if(!type) type = "info";
		opera.postError("Grake,"+type+" : "+message);
	}
}

/**
 * ~~~ Codebit ~~~
 * Opera Google Mail Extension - Background-Process
 * --------------------------------------------------
 * http://codebit.de/oex/google-mail
 * @author Tom Schreiber (tom.schreiber@codebit.de)
 * @version SVN 224 2012-09-19 05:50:54Z tom.schreiber@tomhost.de $
 */
var StandardHeight=135, Grake, AudioObject, MyButton;
var UpdateTimer=60000; // 1 minute
var ToolbarUIItemProperties = {
	disabled:false,
	title:"GMailNotifier",
	icon:"icon.png",
	badge:{display:"block",textContent:"x",color:"#fff",backgroundColor:"#d00"},
	onclick:function(){
		opera.extension.tabs.create({url:'https://mail.google.com/',focused:true});
	}
}
window.addEventListener("load",function() {
	DebugMessage("Background-Process is initializing, Debug Mode is ready");
	MyButton = opera.contexts.toolbar.createItem(this.ToolbarUIItemProperties);
	opera.contexts.toolbar.addItem(this.MyButton);
	Grake = new Grake();
	Grake.UpdateAccounts();
},false);
function Update_callback() {
	var accounts=Grake.GetAccounts();
	var num=Grake.GetAccountsCount();
	if(accounts==null||num==0) {
		MyButton.badge.display="block";
		MyButton.badge.textContent = "x";
		DebugMessage("No active accounts are found");
	}
	else {
		var unreadCount=Grake.GetTotalUnreadCount();
		var newMail=Grake.GetRealNewMessageBool();
		DebugMessage(num+" Accounts with "+unreadCount+" Messages");
		if(unreadCount>0) MyButton.badge.textContent = unreadCount;
		else MyButton.badge.textContent = "";
	}
	UpdateTimer = 60000;
}
function DebugMessage(message,type) {
	if(!type) type = "info";
		opera.postError("GMNEx,bg,"+type+" : "+message);
}