Initial commit: LastRecc discovery feed and weekly engine
This commit is contained in:
40 files changed
+6972
No files matched your search
+388
@@ -0,0 +1,388 @@
|
||||
const state = {
|
||||
feed: null,
|
||||
filter: "all",
|
||||
days: Number(new URLSearchParams(location.search).get("days")) || 7,
|
||||
loading: false,
|
||||
audio: new Audio(),
|
||||
currentId: null,
|
||||
toastTimer: null,
|
||||
};
|
||||
|
||||
const $ = (selector) => document.querySelector(selector);
|
||||
const $$ = (selector) => Array.from(document.querySelectorAll(selector));
|
||||
|
||||
const esc = (value) =>
|
||||
String(value ?? "").replace(/[&<>"']/g, (char) => ({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
}[char]));
|
||||
|
||||
const hueFor = (value) => {
|
||||
let hash = 0;
|
||||
for (const char of String(value || "")) hash = (hash * 31 + char.charCodeAt(0)) % 360;
|
||||
return hash;
|
||||
};
|
||||
|
||||
const initials = (value) => {
|
||||
const words = String(value || "?").trim().split(/\s+/).slice(0, 2);
|
||||
return words.map((word) => word[0] || "").join("").toUpperCase() || "?";
|
||||
};
|
||||
|
||||
const formatDuration = (seconds) => {
|
||||
if (!seconds) return "";
|
||||
const total = Math.round(seconds);
|
||||
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const formatClock = (seconds) => {
|
||||
if (!Number.isFinite(seconds)) return "0:00";
|
||||
const total = Math.max(0, Math.round(seconds));
|
||||
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const playIcon = `<svg class="icon-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>`;
|
||||
const pauseIcon = `<svg class="icon-pause hidden" viewBox="0 0 24 24" aria-hidden="true"><path d="M7 5h4v14H7zM13 5h4v14h-4z"/></svg>`;
|
||||
const sparkIcon = `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2l1.8 6.2L20 10l-6.2 1.8L12 18l-1.8-6.2L4 10l6.2-1.8L12 2z"/></svg>`;
|
||||
|
||||
function setStatus(text, busy = false) {
|
||||
$("#status-text").textContent = text;
|
||||
$("#status").classList.toggle("is-busy", busy);
|
||||
}
|
||||
|
||||
function showToast(message) {
|
||||
const toast = $("#toast");
|
||||
toast.textContent = message;
|
||||
toast.classList.remove("hidden");
|
||||
clearTimeout(state.toastTimer);
|
||||
state.toastTimer = setTimeout(() => toast.classList.add("hidden"), 3200);
|
||||
}
|
||||
|
||||
function skeleton() {
|
||||
$("#grid").innerHTML = Array.from({ length: 9 })
|
||||
.map(
|
||||
() => `
|
||||
<article class="card skeleton-card">
|
||||
<div class="cover skeleton"></div>
|
||||
<div class="card-body">
|
||||
<div class="skeleton line wide"></div>
|
||||
<div class="skeleton line"></div>
|
||||
<div class="skeleton line short"></div>
|
||||
<div class="skeleton line reason-line"></div>
|
||||
</div>
|
||||
</article>`
|
||||
)
|
||||
.join("");
|
||||
$("#empty").classList.add("hidden");
|
||||
$("#error").classList.add("hidden");
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
$("#grid").innerHTML = "";
|
||||
$("#empty").classList.add("hidden");
|
||||
const error = $("#error");
|
||||
error.textContent = `${message} — check the server console, then hit Refresh.`;
|
||||
error.classList.remove("hidden");
|
||||
setStatus("error");
|
||||
}
|
||||
|
||||
async function loadFeed(refresh = false) {
|
||||
if (state.loading) return;
|
||||
state.loading = true;
|
||||
skeleton();
|
||||
setStatus(refresh ? "rebuilding feed" : "reading scrobbles", true);
|
||||
const refreshButton = $("#refresh");
|
||||
refreshButton.disabled = true;
|
||||
refreshButton.classList.add("is-loading");
|
||||
$("#days").disabled = true;
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/feed?days=${state.days}${refresh ? "&refresh=1" : ""}`,
|
||||
{ cache: "no-store" }
|
||||
);
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || "Could not build the feed");
|
||||
state.feed = data;
|
||||
state.filter = "all";
|
||||
history.replaceState(null, "", `?days=${state.days}`);
|
||||
render();
|
||||
setStatus("ready");
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
showError(error.message || "Could not load the feed");
|
||||
} finally {
|
||||
state.loading = false;
|
||||
refreshButton.disabled = false;
|
||||
refreshButton.classList.remove("is-loading");
|
||||
$("#days").disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function render() {
|
||||
const feed = state.feed;
|
||||
if (!feed) return;
|
||||
const stats = feed.stats || {};
|
||||
const days = feed.window?.days || state.days;
|
||||
$("#eyebrow").textContent = `LAST ${days} DAYS · NAVIDROME × LAST.FM`;
|
||||
$("#lede").innerHTML =
|
||||
`<strong>${stats.plays || 0}</strong> plays across ` +
|
||||
`<strong>${stats.artists || 0}</strong> artists — ` +
|
||||
`<strong>${stats.hours || 0}h</strong> of music. ` +
|
||||
`Here's what Last.fm thinks you'll love next.`;
|
||||
$("#stats").innerHTML = [
|
||||
[stats.plays || 0, "plays"],
|
||||
[stats.unique_tracks || 0, "tracks"],
|
||||
[stats.artists || 0, "artists"],
|
||||
[`${stats.hours || 0}h`, "listened"],
|
||||
]
|
||||
.map(
|
||||
([value, label]) => `
|
||||
<div class="stat">
|
||||
<strong>${esc(value)}</strong>
|
||||
<span>${esc(label)}</span>
|
||||
</div>`
|
||||
)
|
||||
.join("");
|
||||
updateTabCounts();
|
||||
renderCards();
|
||||
}
|
||||
|
||||
function tabCards() {
|
||||
const cards = state.feed?.cards || [];
|
||||
if (state.filter === "new") return cards.filter((card) => card.is_new_artist);
|
||||
if (state.filter === "known") return cards.filter((card) => !card.is_new_artist);
|
||||
if (state.filter === "playable") return cards.filter((card) => card.playable);
|
||||
return cards;
|
||||
}
|
||||
|
||||
function updateTabCounts() {
|
||||
const cards = state.feed?.cards || [];
|
||||
const counts = {
|
||||
all: cards.length,
|
||||
new: cards.filter((card) => card.is_new_artist).length,
|
||||
known: cards.filter((card) => !card.is_new_artist).length,
|
||||
playable: cards.filter((card) => card.playable).length,
|
||||
};
|
||||
$$("[data-count]").forEach((node) => {
|
||||
node.textContent = counts[node.dataset.count] ?? 0;
|
||||
});
|
||||
}
|
||||
|
||||
function cardMarkup(card, index) {
|
||||
const isAlbum = card.type === "album";
|
||||
const hue = hueFor(card.artist);
|
||||
const image = card.image
|
||||
? `<img src="${esc(card.image)}" alt="" loading="lazy" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" />`
|
||||
: "";
|
||||
const fallbackDisplay = card.image ? "none" : "flex";
|
||||
const subtitle = isAlbum
|
||||
? `${card.track_count || 0} tracks`
|
||||
: card.album || "";
|
||||
const album = `<p class="card-album">${esc(subtitle) || " "}</p>`;
|
||||
const source = isAlbum
|
||||
? `<span class="source-pill is-playable">Album · library</span>`
|
||||
: card.playable
|
||||
? `<span class="source-pill is-playable">In library</span>`
|
||||
: `<span class="source-pill">Last.fm</span>`;
|
||||
const badge = isAlbum ? "Album" : `${card.match_pct}% match`;
|
||||
const actionLabel = isAlbum
|
||||
? "Open album"
|
||||
: card.playable
|
||||
? "Play"
|
||||
: "Open on Last.fm";
|
||||
return `
|
||||
<article class="card ${isAlbum ? "is-album" : ""}" style="--delay:${Math.min(index, 14) * 26}ms; --h:${hue}" data-id="${esc(card.id)}">
|
||||
<div class="cover">
|
||||
${image}
|
||||
<div class="cover-fallback" style="display:${fallbackDisplay}">
|
||||
<span>${esc(initials(card.artist))}</span>
|
||||
</div>
|
||||
<div class="cover-shade"></div>
|
||||
<span class="match">${esc(badge)}</span>
|
||||
<button class="play-btn" type="button" data-action="play" data-id="${esc(card.id)}"
|
||||
aria-label="${actionLabel}: ${esc(card.title)} by ${esc(card.artist)}">
|
||||
${playIcon}${pauseIcon}
|
||||
</button>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<h3 title="${esc(card.title)}">${esc(card.title)}</h3>
|
||||
<p class="card-artist">${esc(card.artist)}</p>
|
||||
${album}
|
||||
<p class="reason">${sparkIcon}<span>${esc(card.reason)}</span></p>
|
||||
<div class="card-foot">
|
||||
${source}
|
||||
<span class="duration">${esc(formatDuration(card.duration))}</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>`;
|
||||
}
|
||||
|
||||
function renderCards() {
|
||||
const cards = tabCards();
|
||||
$("#grid").innerHTML = cards.map(cardMarkup).join("");
|
||||
$("#empty").classList.toggle("hidden", cards.length > 0);
|
||||
$("#error").classList.add("hidden");
|
||||
syncPlayingCards();
|
||||
}
|
||||
|
||||
function setFilter(filter) {
|
||||
state.filter = filter;
|
||||
$$(".tab").forEach((tab) => {
|
||||
const active = tab.dataset.filter === filter;
|
||||
tab.classList.toggle("is-active", active);
|
||||
tab.setAttribute("aria-selected", String(active));
|
||||
});
|
||||
renderCards();
|
||||
}
|
||||
|
||||
function cardById(id) {
|
||||
return (state.feed?.cards || []).find((card) => card.id === id);
|
||||
}
|
||||
|
||||
function syncPlayingCards() {
|
||||
const paused = state.audio.paused;
|
||||
$$(".card").forEach((card) => {
|
||||
const active = card.dataset.id === state.currentId;
|
||||
card.classList.toggle("is-current", active);
|
||||
card.classList.toggle("is-playing", active && !paused);
|
||||
const play = card.querySelector(".icon-play");
|
||||
const pause = card.querySelector(".icon-pause");
|
||||
if (play && pause) {
|
||||
play.classList.toggle("hidden", active && !paused);
|
||||
pause.classList.toggle("hidden", !(active && !paused));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function showPlayer(card) {
|
||||
const player = $("#player");
|
||||
player.classList.remove("hidden");
|
||||
$("#player-cover").innerHTML = card.image
|
||||
? `<img src="${esc(card.image)}" alt="" />`
|
||||
: `<span style="--h:${hueFor(card.artist)}">${esc(initials(card.artist))}</span>`;
|
||||
$("#player-title").textContent = card.title;
|
||||
$("#player-artist").textContent = card.artist;
|
||||
}
|
||||
|
||||
function setupAudio() {
|
||||
const audio = state.audio;
|
||||
audio.preload = "metadata";
|
||||
|
||||
audio.addEventListener("play", () => {
|
||||
$("#player-toggle .icon-play").classList.add("hidden");
|
||||
$("#player-toggle .icon-pause").classList.remove("hidden");
|
||||
syncPlayingCards();
|
||||
});
|
||||
audio.addEventListener("pause", () => {
|
||||
$("#player-toggle .icon-play").classList.remove("hidden");
|
||||
$("#player-toggle .icon-pause").classList.add("hidden");
|
||||
syncPlayingCards();
|
||||
});
|
||||
audio.addEventListener("ended", () => {
|
||||
state.currentId = null;
|
||||
syncPlayingCards();
|
||||
});
|
||||
audio.addEventListener("loadedmetadata", () => {
|
||||
$("#player-duration").textContent = formatClock(audio.duration);
|
||||
});
|
||||
audio.addEventListener("timeupdate", () => {
|
||||
const duration = audio.duration || 0;
|
||||
$("#player-elapsed").textContent = formatClock(audio.currentTime);
|
||||
if (duration) {
|
||||
$("#player-seek").value = String(Math.round((audio.currentTime / duration) * 1000));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function playById(id) {
|
||||
const card = cardById(id);
|
||||
if (!card) return;
|
||||
if (card.type === "album") {
|
||||
const target = card.navidrome_url || card.lastfm_url;
|
||||
showToast("Opening album in Navidrome");
|
||||
window.open(target, "_blank", "noopener,noreferrer");
|
||||
return;
|
||||
}
|
||||
if (!card.playable || !card.stream_url) {
|
||||
showToast("Not in your library — opening Last.fm");
|
||||
window.open(card.lastfm_url, "_blank", "noopener,noreferrer");
|
||||
return;
|
||||
}
|
||||
if (state.currentId === id) {
|
||||
if (state.audio.paused) state.audio.play().catch(() => {});
|
||||
else state.audio.pause();
|
||||
return;
|
||||
}
|
||||
state.currentId = id;
|
||||
state.audio.src = card.stream_url;
|
||||
showPlayer(card);
|
||||
state.audio.play().catch(() => {
|
||||
showToast("Could not start playback");
|
||||
});
|
||||
syncPlayingCards();
|
||||
}
|
||||
|
||||
function bind() {
|
||||
$("#tabs").addEventListener("click", (event) => {
|
||||
const tab = event.target.closest(".tab");
|
||||
if (tab) setFilter(tab.dataset.filter);
|
||||
});
|
||||
|
||||
$("#grid").addEventListener("click", (event) => {
|
||||
const button = event.target.closest('[data-action="play"]');
|
||||
if (button) {
|
||||
event.stopPropagation();
|
||||
playById(button.dataset.id);
|
||||
}
|
||||
});
|
||||
|
||||
$("#refresh").addEventListener("click", () => loadFeed(true));
|
||||
|
||||
$("#days").addEventListener("change", (event) => {
|
||||
state.days = Number(event.target.value);
|
||||
loadFeed();
|
||||
});
|
||||
|
||||
$("#player-toggle").addEventListener("click", () => {
|
||||
if (!state.currentId) return;
|
||||
if (state.audio.paused) state.audio.play().catch(() => {});
|
||||
else state.audio.pause();
|
||||
});
|
||||
|
||||
$("#player-seek").addEventListener("input", (event) => {
|
||||
const duration = state.audio.duration;
|
||||
if (!duration) return;
|
||||
state.audio.currentTime = (Number(event.target.value) / 1000) * duration;
|
||||
});
|
||||
|
||||
$("#player-close").addEventListener("click", () => {
|
||||
state.audio.pause();
|
||||
state.currentId = null;
|
||||
$("#player").classList.add("hidden");
|
||||
syncPlayingCards();
|
||||
});
|
||||
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") {
|
||||
state.audio.pause();
|
||||
$("#player").classList.add("hidden");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
const daysSelect = $("#days");
|
||||
daysSelect.value = String(state.days);
|
||||
if (!daysSelect.value) {
|
||||
state.days = 7;
|
||||
daysSelect.value = "7";
|
||||
}
|
||||
setupAudio();
|
||||
bind();
|
||||
loadFeed();
|
||||
}
|
||||
|
||||
init();
|
||||
Reference in new issue
Block a user