OoCites Missing Resource Fixer

Attempts to fix missing resources on OoCities by drawing from Wayback Machine

目前为 2016-05-19 提交的版本。查看 最新版本

// ==UserScript==
// @name          OoCites Missing Resource Fixer
// @namespace     DoomTay
// @description   Attempts to fix missing resources on OoCities by drawing from Wayback Machine
// @include       http://www.oocities.org/*
// @version       1.1.0
// @grant         GM_xmlhttpRequest

// ==/UserScript==

var pics = document.images;
var timestamp = "20091026194848";
var lastModifiedRegex = /(?:last updated(?: on |:)|since )([^\n]+)\n/i;
var substitutionTable = {};

if(document.body.innerHTML.includes("<!-- following code added by server"))
{
	var scriptToRemove = document.body.innerHTML.substring(document.body.innerHTML.indexOf("<!-- following code added by server"),document.body.innerHTML.indexOf("<!-- preceding code added by server. PLEASE REMOVE -->") + 54);
	document.body.innerHTML = document.body.innerHTML.replace(scriptToRemove,"");
}

if(lastModifiedRegex.test(document.body.textContent))
{
	var modifiedDate = document.body.textContent.match(lastModifiedRegex)[1];
	if(modifiedDate.endsWith(".")) modifiedDate = modifiedDate.substring(0, modifiedDate.length - 1);
	if(!isNaN(Date.parse(modifiedDate)))
	{
		timestamp = dateToTimestamp(new Date(modifiedDate));
		scanResources();
	}
}

function zeroPad(str,len) {
	return "0".repeat(len - str.toString().length) + str.toString();
}

function dateToTimestamp(date) {
	return date.getUTCFullYear() +
		zeroPad(date.getUTCMonth()+1,2) +
		zeroPad(date.getUTCDate()+1,2) +
		zeroPad(date.getUTCHours(),2) +
		zeroPad(date.getUTCMinutes(),2) +
		zeroPad(date.getUTCSeconds(),2);
}


if(document.contentType == "text/plain")
{
	var decodedCode = decodeHTML(document.body.innerHTML).replace(/geocities/g,"oocities");
	if(decodedCode.includes("<html>") && decodedCode.includes("</html>")) decodedCode = decodedCode.substring(decodedCode.indexOf("<html>") + 6,decodedCode.indexOf("</html>"));
	if(decodedCode.includes("<head>") && decodedCode.includes("</head>"))
	{
		document.head.innerHTML = decodedCode.substring(decodedCode.toLowerCase().indexOf("<head>") + 6,decodedCode.toLowerCase().indexOf("</head>"));
		document.body.outerHTML = decodedCode.substring(decodedCode.toLowerCase().indexOf("</head>") + 7);
	}
	else document.documentElement.innerHTML = decodedCode;
}
if(document.title.includes("<body>"))
{
	var decodedCode = decodeHTML(document.body.innerHTML).replace(/geocities/g,"oocities");
	if(decodedCode.includes("<title>") && decodedCode.includes("</title>"))
	{
		decodedCode = decodedCode.replace("</title>","");
		decodedCode = decodedCode.replace("<title>","<title></title>");
	}
	document.documentElement.innerHTML = decodedCode;
	
	Array.prototype.forEach.call(document.scripts,function(script){
		var newScript = document.createElement("script");
		newScript.type = "text/javascript";
		if(script.innerHTML)
		{
			newScript.innerHTML = script.innerHTML;
			script.parentNode.replaceChild(newScript,script);
		}
		else if(script.src)
		{
			newScript.src = script.src;
			script.parentNode.replaceChild(newScript,script);
		}
	});
}
	
if(frames[1])
{
	if(frames[1].name == window.eval("mFr")) frames[1].addEventListener('DOMContentLoaded', function() { document.title = frames[1].document.title; });
}

if(timestamp == "20091026194848")
{
	getTimestamp(window.location.href.includes("?") ? window.location.href.substring(0,window.location.href.indexOf("?")) : window.location.href).then(null,function(timestamp)
	{
		if(document.body.background) return(getTimestamp(document.body.background));
		else return(timestamp);
	}).then(null,function(timestamp)
	{
		if(pics[0]) return(getTimestamp(pics[0].src));
		else return(timestamp);
	}).then(null,function(timestamp)
	{
		if(pics[0] && pics[1]) return(getTimestamp(pics[1].src));
		else return(timestamp);
	}).then(null,function(timestamp)
	{
		return(timestamp);
	}).then(function(finalTimestamp)
	{
		timestamp = finalTimestamp;
		scanResources();
	});
}

function scanResources()
{
	for(var i = 0; i < pics.length; i++)
	{
		if(pics[i].complete && pics[i].naturalWidth == 0) attemptReplacement(pics[i]);
		pics[i].addEventListener("error", function(e) { attemptReplacement(e.target); }, true);
	}
		
	if(document.body.background)
	{
		GM_xmlhttpRequest({
			url: document.body.background,
			method: "HEAD",
			onload: function(response) {
				if(response.status == 404)
				{
					testResource(this.url).then(function(response) {
						document.body.background = response.finalUrl;
					},function() { });
				}
			}
		});
	}
}

function decodeHTML(text) {
    var textarea = document.createElement("textarea");
    textarea.innerHTML = text;
    return textarea.value;
}

function testResource(url)
{
	var promise = new Promise(function(resolve,reject) {
		GM_xmlhttpRequest({
			url: "http://web.archive.org/web/" + timestamp + "/" + url.replace(/oocities\.(org|com)/,"geocities.com"),
			method: "HEAD",
			onload: function(response) {
				if(response.status == 200) resolve(response);
				else reject(response);
			}
		});
	});
	return promise;
}

function getTimestamp(url)
{
	var promise = new Promise(function(resolve,reject) {
		testResource(url).then(function(response) {
			var timestamp = "20091026194848";
			if(response.responseHeaders.includes("X-Archive-Orig-last-modified"))
			{
				var headers = response.responseHeaders;
				var lastModified = new Date(headers.substring(headers.indexOf("X-Archive-Orig-last-modified: ") + 30,headers.indexOf("\n",headers.indexOf("X-Archive-Orig-last-modified: "))));
				timestamp = dateToTimestamp(lastModified);
				resolve(timestamp);
			}
			else reject(timestamp);
			}, function() { reject(timestamp); });
	});
	return promise;
}

function attemptReplacement(pic)
{
	GM_xmlhttpRequest({
		url: pic.src,
		method: "GET",
		onload: function(response) {
			if(response.status == 404)
			{
				Promise.resolve(this.url).then(function(originalSrc) {
					APITest(originalSrc.replace(/oocities\.(org|com)/,"geocities.com")).then(function(result){
						if(result !== null)
						{
							//Adding the image with the original source so the mutation observer can swap it in manually next time. This is mainly for mouseover events and the like so that we won't be making XHR calls every time the user mouses over the element
							substitutionTable[originalSrc] = result;
							pic.src = result;
						}
					});
				});
			}
			else if(response.responseText.includes("The document has moved"))
			{
				testResource(new DOMParser().parseFromString(response.responseText, "text/html").links[0].href).then(function(response) { pic.src = response.finalUrl; });
			}
		},
		onerror: function() {
			APITest(pic.src.replace(/oocities\.(org|com)/,"geocities.com")).then(function(result){
				if(result !== null) pic.src = result;
			});
		}
	});
	
	function APITest(url)
	{
		return new Promise(function(resolve,reject)
		{
			GM_xmlhttpRequest({
				url: "http://archive.org/wayback/available?url=" + url + "&timestamp=" + timestamp,
				method: "GET",
				headers: {"Accept": "application/json"},
				onload: function(response) {
					if(response.status == 503) reject(response.status + ": " + response.statusText);
					else if(JSON.parse(response.responseText).archived_snapshots.closest !== undefined)
					{
						resolve(JSON.parse(response.responseText).archived_snapshots.closest.url);
					}
					else resolve(null);
				}
			});
		}).catch(function(e) { return APITest(url); });
	}
}

var observer = new MutationObserver(function(mutations) {
	mutations.forEach(function(mutation) {
		if(substitutionTable.hasOwnProperty(mutation.target.src))
		{
			observer.disconnect();
			mutation.target.src = substitutionTable[mutation.target.src];
			observer.observe(document, config);
		}
	});
});

var config = { attributes: true, subtree: true, attributeFilter: ["src"] };
observer.observe(document, config);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址