Add last.fm/scrobble.js

This commit is contained in:
kobayashi90 2025-01-21 06:18:24 +00:00
commit 0895e7ff55

69
last.fm/scrobble.js Normal file
View file

@ -0,0 +1,69 @@
const API_KEY = "YOUR_LASTFM_API_KEY"; // Replace with your Last.fm API Key
const USERNAME = "YOUR_LASTFM_USERNAME"; // Replace with your Last.fm username
const POLLING_INTERVAL = 5000; // Polling interval in milliseconds
const recentScrobblesUrl = `https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${USERNAME}&api_key=${API_KEY}&format=json`;
// Function to fetch recent scrobbles
async function fetchRecentScrobbles() {
try {
const response = await fetch(recentScrobblesUrl);
if (!response.ok) {
throw new Error("Failed to fetch scrobbles");
}
const data = await response.json();
const tracks = data.recenttracks.track;
updatePanel(tracks);
} catch (error) {
console.error("Error fetching scrobbles:", error);
}
}
// Function to update the `panel2` section
function updatePanel(tracks) {
const trackInfoContainer = document.getElementById("track-info-container");
trackInfoContainer.innerHTML = ""; // Clear previous content
if (tracks.length > 0) {
const recentTracks = tracks.slice(0, 12); // Get the latest 5 tracks
// Album cover for the latest track
const albumArt = recentTracks[0]?.image?.[3]?.["#text"] || "default-album-art.jpg"; // Large size image
const albumArtHtml = `
<div class="album-cover">
<img src="${albumArt}" alt="Album Art" class="album-art">
</div>
`;
trackInfoContainer.innerHTML += albumArtHtml;
// Recent tracks list with CD icon and heart if favorited
const playlistHtml = `
<ul class="recent-tracks">
${recentTracks
.map(
(track) => `
<li>
<span class="cd-icon" style="font-size: 20px; margin-right: 5px;">🎶</span>
${track.artist["#text"]} - ${track.name}
${track["@attr"]?.liked ? '❤️' : ''}
</li>`
)
.join("")}
</ul>
`;
trackInfoContainer.innerHTML += playlistHtml;
} else {
trackInfoContainer.innerHTML = "<p>No tracks found.</p>";
}
}
// Start polling for updates
function startPolling() {
fetchRecentScrobbles();
setInterval(fetchRecentScrobbles, POLLING_INTERVAL);
}
// Call the function on page load
document.addEventListener("DOMContentLoaded", () => {
startPolling();
});