document.addEventListener('DOMContentLoaded', () => {
const nowPlayingElement = document.getElementById('lastfm-contents');
const lastfmArtElement = document.getElementById('lastfm-artbox');
function fetchNowPlaying() {
fetch('https://quinten0508.com/api/nowplaying')
.then(response => response.json())
.then(data => {
if (data.recenttracks.track && data.recenttracks.track.length > 0) {
const tracks = data.recenttracks.track;
const nowPlaying = tracks[0];
const lastPlayedSong = tracks[1];
const lastlastPlayedSong = tracks[2];
if (nowPlaying['@attr'] && nowPlaying['@attr'].nowplaying) {
const nowPlayingHtml = `
Now Playing:
1. ${nowPlaying.artist['#text']} - ${nowPlaying.name}
2. ${lastPlayedSong.artist['#text']} - ${lastPlayedSong.name}
3. ${lastlastPlayedSong.artist['#text']} - ${lastlastPlayedSong.name}
`;
nowPlayingElement.innerHTML = nowPlayingHtml;
const albumArt = nowPlaying.image.find(img => img.size === 'large')['#text'];
lastfmArtElement.innerHTML = `
`;
} else {
const lastPlayed = tracks[0];
const lastPlayedTime = new Date(lastPlayed.date.uts * 1000);
const currentTime = new Date();
const timeDiff = Math.floor((currentTime - lastPlayedTime) / 1000);
const timeSince = formatTimeSince(timeDiff);
const lastPlayedHtml = `
Last Played:
${lastPlayed.artist['#text']} - ${lastPlayed.name}
${timeSince} ago
`;
nowPlayingElement.innerHTML = lastPlayedHtml;
const albumArt = lastPlayed.image.find(img => img.size === 'large')['#text'];
lastfmArtElement.innerHTML = `
`;
}
} else {
nowPlayingElement.innerHTML = `Now Playing:
Nothing`;
lastfmArtElement.innerHTML = '';
}
})
.catch(error => {
nowPlayingElement.textContent = 'Error fetching last.fm status.';
lastfmArtElement.innerHTML = '';
console.error('Error fetching now playing status:', error);
});
}
function formatTimeSince(seconds) {
const intervals = [
{ label: 'year', seconds: 31536000 },
{ label: 'month', seconds: 2592000 },
{ label: 'day', seconds: 86400 },
{ label: 'hour', seconds: 3600 },
{ label: 'minute', seconds: 60 },
{ label: 'second', seconds: 1 }
];
for (const interval of intervals) {
const count = Math.floor(seconds / interval.seconds);
if (count > 0) {
return `${count} ${interval.label}${count !== 1 ? 's' : ''}`;
}
}
return 'just now';
}
fetchNowPlaying();
setInterval(fetchNowPlaying, 10000);
});