jehan / Newscorp Paywall Reset

// ==UserScript==
// @name	Newscorp Paywall Reset
// @description	Resets the article limit for Newscorp online content including: www.news.com.au, www.theaustralian.com.au - The Australian, www.dailytelegraph.com.au - Daily Telegraph, www.heraldsun.com.au - Herald Sun, www.couriermail.com.au - Courier Mail, www.adelaidenow.com.au - Adelaide Now, www.perthnow.com.au - Perth Now, www.businessspectator.com.au - Business Spectator, www.eurekareport.com.au - Eureka Report
// @match		*://*.news.com.au/*
// @match		*://*.theaustralian.com.au/*
// @match		*://*.dailytelegraph.com.au/*
// @match		*://*.heraldsun.com.au/*
// @match		*://*.couriermail.com.au/*
// @match		*://*.adelaidenow.com.au/*
// @match		*://*.perthnow.com.au/*
// @match		*://*.businessspectator.com.au/*
// @match		*://*.eurekareport.com.au/*
// @exclude		*://*.eurekareport.com.au/subscribe/*
// @run-at		document-start
// @version		2.6
// @grant       GM_log
// @grant       GM_addStyle
// @grant		GM_xmlhttpRequest
// ==/UserScript==

function Log(msg){
	console.log(msg);
}

timeout = 50, article = null;
switch(window.location.hostname) {

	case 'www.eurekareport.com.au':
	//case 'www.businessspectator.com.au':
		preloadPremiumPage();
		checkPremium();
		break;
		
	//case 'm.theaustralian.com.au':
	default:
		delCookies();
		setCookies();
		if(window.location.search.indexOf('&dest=')>=0){
			window.stop();
			var url = window.location.search.match(/&dest=([^&?]+)/)[1];
			getPage(url);
			history.pushState({abc: 2}, "N", url);
			break;
		}
}

GM_addStyle(".story-promo.story-promo-bottom, .mm-reveal.account-lightbox, .module.prm.prm-preview.prm-preview-, .bs-paywall-modal, body > .ui-widget-overlay, #aibm_channels_paywall_container, .mm-ribbon-container { display: none!important; }");

function checkPremium(){
	var nn = null, pageTitle = null;
	(function(){
		var ready = true;
		if(!pageTitle)
			pageTitle = document.getElementById('page-title');
		if(!article)
			ready = false;
		else
			if(pageTitle && (pageTitle.childElementCount==0))
				return article = null;
		if(!nn)
			nn = document.getElementById('aibm_channels_paywall_container');
		if(!nn)
			ready = false;
		if(!ready)
			return window.setTimeout(arguments.callee, timeout);
		nn.parentNode.insertBefore(article, nn);
		article = null;
	})();
};

function removeModaldialog(){
	var dialog = document.getElementById('bs-paywall-modal');	
	(function(){
		if(dialog.className.indexOf('ui-dialog-content')<0)
			return window.setTimeout(arguments.callee, timeout);
		unsafeWindow.jQuery(dialog).dialog('close');
	})();
}
	
observer = new MutationObserver(function(mutations) {
	mutations.forEach(function(mutation) {
		if(mutation.target.id != 'bs-paywall-modal')
			return;
		removeModaldialog();
		observer.disconnect();
	});   
});
observer.observe(document.documentElement, { attributes: true, subtree: true } );

function preloadPremiumPage(){
	var nid_ = document.querySelector("link[rel='shortlink']");
	if(!nid_)
		return window.setTimeout(arguments.callee, timeout);
	var nid = nid_.href.split('/')[4];
	var url = window.location.protocol + '//' + window.location.host + '/print/' + nid;
	delCookies();
	ajaxReq(url, function(res){
		div.innerHTML = res.responseText;
		article = div.querySelector('.field-body, .field--body'), div = null;
	});
	var div = document.createElement('div');
}

function getPage(url, css){
	if(typeof url == 'undefined')
		var url = window.location.href;
	ajaxReq(url, function(response){
		if((typeof css == 'undefined') || !css){
			document.documentElement.innerHTML = response.responseText;
			return;
		}
		var nStoryBody = div.querySelector(css);
		(function(){
			var storyBody = document.querySelector(css);
			if(storyBody === null)
				return setTimeout(arguments.callee, timeout);
			storyBody.parentNode.replaceChild(nStoryBody, storyBody);
		})();
	});
	var div = document.createElement('div');
}

function ajaxReq(url, callback){
	var count = 0;
	(function(){
		if(count++>10)
			return;
		GM_xmlhttpRequest({
			method : "GET",
			url : url,
			headers : {
				Referer : "http://news.google.com/url?sa=" + rndStr(),
				Cookie: 'gr=;'
			},
			onload : callback,
			ontimeout : arguments.callee,
			onerror : arguments.callee,
			timeout : 20000 - 17000 / count
		});
	})();
}

function tld(){
	var d = window.location.hostname.split('.');
	d.splice(0, d.indexOf('com') - 1);
	return d.join('.');
}

function delCookies(){
	localStorage.clear();
	var ck = document.cookie.match ( '(^|;) ?([a-z0-9]{13})=([a-zA-Z0-9]{48})(;|$)' );
	if ( ck )
		delCookie(ck[2], '/', tld());
	delCookie(['gr', 'n_rme', 'n_regis', 'breach_lp']);
}

function delCookie(name, path, domain){
	if(typeof path == 'undefined')
		var path = '/';
	if(typeof domain == 'undefined')
		var domain = '';
	else
		domain = ';domain=' + domain;
	if(typeof name != 'object')
		name = [name];
	for(var i in name)
		document.cookie = name[i] + "=;path=" + path + domain + ";expires=expires=Thu, 01-Jan-1970 00:00:01 GMT;";
}

function setCookies(){
	document.cookie = 'n_regis=' + (Math.round(new Date().getTime() / 1000) + 200) + ";path=/;";
}

function rndStr(){
	var s = '';
	for(var i = 0, l = Math.random()*5+5; i<l; i++)
		s += String.fromCharCode(Math.floor(Math.random()*26) + 97);
	return s;
}