flash.moe/public/assets/lastfm2020.js
2020-08-20 00:02:37 +00:00

93 lines
No EOL
3 KiB
JavaScript

function createXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
return null;
}
function getNowListening(username, cb) {
var xhr = createXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4)
return;
var xml = null;
if(window.DOMParser) {
var parser = new DOMParser();
xml = parser.parseFromString(xhr.responseText, 'text/xml');
} else {
xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = 'false';
xml.loadXML(xhr.responseText);
xml = xml.childNodes[1];
}
cb(xml.getElementsByTagName('Track')[0]);
};
xhr.open('GET', '/np.php?t=' + (new Date().getTime()) + '&u=' + username, true);
xhr.send();
}
function getNodeText(node) {
if (typeof node.textContent === 'undefined') {
return node.text;
} else {
return node.textContent;
}
}
function setNodeText(node, text) {
if (typeof node.textContent === 'undefined') {
node.innerText = text;
} else {
node.textContent = text;
}
}
function setNowListening(track) {
var cover = document.getElementById('music-cover'),
title = document.getElementById('music-title'),
artist = document.getElementById('music-artist'),
header = document.getElementById('music-header'),
content = document.getElementById('music'),
coverUrl = getNodeText(track.getElementsByTagName('Medium')[0]);
if (content.className.indexOf('hidden') >= 0)
content.className = content.className.replace('hidden', '');
setNodeText(header, getNodeText(track.getElementsByTagName('IsPlaying')[0]) != '0' ? 'Listening to' : 'Last listened to');
cover.src = coverUrl.length < 1 ? '//now.flash.moe/resources/no-cover.png' : coverUrl.replace('/64s/', '/100s/').replace('https:', '');
setNodeText(title, getNodeText(track.getElementsByTagName('Name')[0]));
title.href = getNodeText(track.getElementsByTagName('Url')[0]);
setNodeText(artist, getNodeText(track.getElementsByTagName('Name')[1]));
artist.href = title.href.substring(0, title.href.indexOf('/_/'));
}
window.onload = function() {
var lastFmUsername = '',
lastFmFind = '//www.last.fm/user/';
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var indexOf = links[i].href.indexOf(lastFmFind);
if(indexOf > -1) {
lastFmUsername = links[i].href.substring(indexOf + lastFmFind.length);
break;
}
}
if(lastFmUsername) {
setInterval(function() { getNowListening(lastFmUsername, function(track) { setNowListening(track); }); }, 60000);
getNowListening(lastFmUsername, function(track) { setNowListening(track); });
}
};