c3d2-web/content/static/script/bitlove-enclosures.js

112 lines
2.5 KiB
JavaScript

var XHR = window.AnonXMLHttpRequest || window.XMLHttpRequest;
if (!XHR)
throw new Error("Your browser lacks support for standardized AJAX calls. What the ...?");
var urlCallbacks = {};
function resolve(url, cb) {
if (urlCallbacks.hasOwnProperty(url)) {
urlCallbacks[url].push(cb);
} else {
urlCallbacks[url] = [cb];
}
maySetTimeout();
}
var timeout;
function maySetTimeout() {
var pending = Object.keys(urlCallbacks).length > 0;
if (!timeout && pending) {
timeout = setTimeout(function() {
timeout = undefined;
maySend();
}, 50);
} else if (timeout && !pending) {
clearTimeout(timeout);
}
}
function maySend() {
var urls = Object.keys(urlCallbacks).slice(0, 8);
if (urls.length > 0) {
doSend(urls, function(response) {
/* Dispatch to callbacks */
urls.forEach(function(url) {
var urlResponse = response[url];
var cbs = urlCallbacks[url];
delete urlCallbacks[url];
cbs.forEach(function(cb) {
try {
cb(urlResponse);
} catch(e) {
if (console && console.error)
console.error(e && e.stack || e);
}
});
});
});
}
}
function doSend(urls, cb) {
var q = urls.map(function(url) {
return "url=" + encodeURIComponent(url);
}).join("&");
var cl = new XHR();
cl.open('GET', 'https://api.bitlove.org/by-enclosure.json?' + q);
cl.onreadystatechange = function() {
if (this.readyState == this.DONE) {
var response;
if (this.status == 200 &&
this.responseText) {
try {
response = JSON.parse(this.responseText);
} catch (e) {
if (console && console.error)
console.error(e && e.stack || e);
}
}
cb(response);
/* Continue with next batch: */
maySend();
}
};
cl.send();
}
$(document).ready(function() {
/* For C3D2-Web */
$('a[rel="enclosure"]').each(function() {
var a = $(this);
var li = a.parent();
var url = a.attr('href');
if (/\.torrent$/.test(url))
return;
resolve(url, function(info) {
var torrent = info && info.sources && info.sources[0] && info.sources[0].torrent;
if (info && torrent) {
var a = $('<a type="application/x-bittorrent" class="torrent mime">Torrent</a>');
a.attr('href', torrent);
var title = info.seeders + " Seeder, " + info.leechers + " Leecher";
if (info.downloaded == 1) {
title += ", 1 Download";
} else if (info.downloaded > 1) {
title += ", " + info.downloaded + " Downloads";
}
a.attr('title', title);
li.append(" ");
li.append(a);
}
});
});
});