const activityProgressMap = new Map(); function formatTime(ms) { const totalSecs = Math.floor(ms / 1000); const hours = Math.floor(totalSecs / 3600); const mins = Math.floor((totalSecs % 3600) / 60); const secs = totalSecs % 60; return `${String(hours).padStart(1, "0")}:${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`; } function formatVerbose(ms) { const totalSecs = Math.floor(ms / 1000); const hours = Math.floor(totalSecs / 3600); const mins = Math.floor((totalSecs % 3600) / 60); const secs = totalSecs % 60; return `${hours}h ${mins}m ${secs}s`; } function updateElapsedAndProgress() { const now = Date.now(); for (const el of document.querySelectorAll(".activity-timestamp")) { const start = Number(el.dataset.start); if (!start) continue; const elapsed = now - start; const display = el.querySelector(".elapsed"); if (display) display.textContent = `(${formatVerbose(elapsed)} ago)`; } for (const bar of document.querySelectorAll(".progress-bar")) { const start = Number(bar.dataset.start); const end = Number(bar.dataset.end); if (!start || !end || end <= start) continue; const duration = end - start; const elapsed = Math.min(now - start, duration); const progress = Math.min( 100, Math.max(0, Math.floor((elapsed / duration) * 100)), ); const fill = bar.querySelector(".progress-fill"); if (fill) fill.style.width = `${progress}%`; } for (const label of document.querySelectorAll(".progress-time-labels")) { const start = Number(label.dataset.start); const end = Number(label.dataset.end); if (!start || !end || end <= start) continue; const isPaused = now > end; const current = isPaused ? end - start : Math.max(0, now - start); const total = end - start; const currentEl = label.querySelector(".progress-current"); const totalEl = label.querySelector(".progress-total"); const id = `${start}-${end}`; const last = activityProgressMap.get(id); if (isPaused || (last !== undefined && last === current)) { label.classList.add("paused"); } else { label.classList.remove("paused"); } activityProgressMap.set(id, current); if (currentEl) { currentEl.textContent = isPaused ? `Paused at ${formatTime(current)}` : formatTime(current); } if (totalEl) totalEl.textContent = formatTime(total); } } updateElapsedAndProgress(); setInterval(updateElapsedAndProgress, 1000); const head = document.querySelector("head"); const userId = head?.dataset.userId; let instanceUri = head?.dataset.instanceUri; let badgeURL = head?.dataset.badgeUrl; if (userId && instanceUri) { if (!instanceUri.startsWith("http")) { instanceUri = `https://${instanceUri}`; } const wsUri = instanceUri .replace(/^http:/, "ws:") .replace(/^https:/, "wss:") .replace(/\/$/, ""); const socket = new WebSocket(`${wsUri}/socket`); let heartbeatInterval = null; socket.addEventListener("open", () => {}); socket.addEventListener("message", (event) => { const payload = JSON.parse(event.data); if (payload.op === 1 && payload.d?.heartbeat_interval) { heartbeatInterval = setInterval(() => { socket.send(JSON.stringify({ op: 3 })); }, payload.d.heartbeat_interval); socket.send( JSON.stringify({ op: 2, d: { subscribe_to_id: userId, }, }), ); } if (payload.t === "INIT_STATE" || payload.t === "PRESENCE_UPDATE") { updatePresence(payload.d); requestAnimationFrame(() => updateElapsedAndProgress()); } }); socket.addEventListener("close", () => { if (heartbeatInterval) clearInterval(heartbeatInterval); }); } function resolveActivityImage(img, applicationId) { if (!img) return null; if (img.startsWith("mp:external/")) { return `https://media.discordapp.net/external/${img.slice("mp:external/".length)}`; } if (img.includes("/https/")) { const clean = img.split("/https/")[1]; return clean ? `https://${clean}` : null; } if (img.startsWith("spotify:")) { return `https://i.scdn.co/image/${img.split(":")[1]}`; } return `https://cdn.discordapp.com/app-assets/${applicationId}/${img}.png`; } function buildActivityHTML(activity) { const start = activity.timestamps?.start; const end = activity.timestamps?.end; const now = Date.now(); const elapsed = start ? now - start : 0; const total = start && end ? end - start : null; const progress = total && elapsed > 0 ? Math.min(100, Math.floor((elapsed / total) * 100)) : null; let art = null; let smallArt = null; if (activity.assets) { art = resolveActivityImage( activity.assets.large_image, activity.application_id, ); smallArt = resolveActivityImage( activity.assets.small_image, activity.application_id, ); } const activityTypeMap = { 0: "Playing", 1: "Streaming", 2: "Listening", 3: "Watching", 4: "Custom Status", 5: "Competing", }; const activityType = activity.name === "Spotify" ? "Listening to Spotify" : activity.name === "TIDAL" ? "Listening to TIDAL" : activityTypeMap[activity.type] || "Playing"; const activityTimestamp = start && progress === null ? `
Since: ${new Date(start).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", second: "2-digit", })}
` : ""; const activityButtons = activity.buttons && activity.buttons.length > 0 ? `
${activity.buttons .map((button, index) => { const label = typeof button === "string" ? button : button.label; let url = null; if (typeof button === "object" && button.url) { url = button.url; } else if (index === 0 && activity.url) { url = activity.url; } return url ? `${label}` : null; }) .filter(Boolean) .join("")}
` : ""; const progressBar = progress !== null ? `
${formatTime(elapsed)} ${formatTime(total)}
` : ""; const isMusic = activity.type === 2 || activity.type === 3; const primaryLine = isMusic ? activity.details : activity.name; const secondaryLine = isMusic ? activity.state : activity.details; const tertiaryLine = isMusic ? activity.assets?.large_text : activity.state; const activityArt = `
${``}
` return `
  • ${activityType} ${activityTimestamp}
    ${activityArt}
    ${primaryLine}
    ${secondaryLine ? `
    ${secondaryLine}
    ` : ""} ${tertiaryLine ? `
    ${tertiaryLine}
    ` : ""}
    ${activityButtons}
    ${progressBar}
  • `; } if (badgeURL && badgeURL !== "null" && userId) { if (!badgeURL.startsWith("http")) { badgeURL = `https://${badgeURL}`; } if (!badgeURL.endsWith("/")) { badgeURL += "/"; } async function loadBadges(userId, options = {}) { const { services = [], seperated = false, cache = true, targetId = "badges", } = options; const params = new URLSearchParams(); if (services.length) params.set("services", services.join(",")); if (seperated) params.set("seperated", "true"); if (!cache) params.set("cache", "false"); const url = `${badgeURL}${userId}?${params.toString()}`; const target = document.getElementById(targetId); if (!target) return; target.classList.add("hidden"); try { const res = await fetch(url); const json = await res.json(); if (!res.ok || !json.badges) { target.textContent = "Failed to load badges."; return; } const badges = Array.isArray(json.badges) ? json.badges : Object.values(json.badges).flat(); if (badges.length === 0) { target.innerHTML = ""; target.classList.add("hidden"); return; } target.innerHTML = ""; for (const badge of badges) { const img = document.createElement("img"); img.src = badge.badge; img.alt = badge.tooltip; img.title = badge.tooltip; img.className = "badge"; target.appendChild(img); } target.classList.remove("hidden"); } catch (err) { console.error(err); target.innerHTML = ""; target.classList.add("hidden"); } } loadBadges(userId, { services: [], seperated: false, cache: true, targetId: "badges", }); } function updatePresence(data) { const avatarWrapper = document.querySelector(".avatar-wrapper"); const statusIndicator = avatarWrapper?.querySelector(".status-indicator"); const mobileIcon = avatarWrapper?.querySelector(".platform-icon.mobile-only"); const userInfo = document.querySelector(".user-info"); const customStatus = userInfo?.querySelector(".custom-status"); const platform = { mobile: data.active_on_discord_mobile, web: data.active_on_discord_web, desktop: data.active_on_discord_desktop, }; let status = "offline"; if (data.activities.some((activity) => activity.type === 1)) { status = "streaming"; } else { status = data.discord_status; } if (statusIndicator) { statusIndicator.className = `status-indicator ${status}`; } if (platform.mobile && !mobileIcon) { avatarWrapper.innerHTML += ` `; } else if (!platform.mobile && mobileIcon) { mobileIcon.remove(); avatarWrapper.innerHTML += `
    `; } const custom = data.activities?.find((a) => a.type === 4); if (customStatus && custom) { let emojiHTML = ""; const emoji = custom.emoji; if (emoji?.id) { const emojiUrl = `https://cdn.discordapp.com/emojis/${emoji.id}.${emoji.animated ? "gif" : "png"}`; emojiHTML = `${emoji.name}`; } else if (emoji?.name) { emojiHTML = `${emoji.name} `; } customStatus.innerHTML = ` ${emojiHTML} ${custom.state ? `${custom.state}` : ""} `; } const filtered = data.activities ?.filter((a) => a.type !== 4) ?.sort((a, b) => { const priority = { 2: 0, 1: 1, 3: 2 }; // Listening, Streaming, Watching ? should i keep this const aPriority = priority[a.type] ?? 99; const bPriority = priority[b.type] ?? 99; return aPriority - bPriority; }); const activityList = document.querySelector(".activities"); const activitiesTitle = document.querySelector(".activity-header"); if (activityList && activitiesTitle) { if (filtered?.length) { activityList.innerHTML = filtered.map(buildActivityHTML).join(""); activitiesTitle.classList.remove("hidden"); } else { activityList.innerHTML = ""; activitiesTitle.classList.add("hidden"); } updateElapsedAndProgress(); getAllNoAsset(); } } async function getAllNoAsset() { const noAssetImages = document.querySelectorAll("img.activity-image.no-asset"); console.log("Images with .no-asset:", noAssetImages.length, noAssetImages); for (const img of noAssetImages) { const name = img.dataset.name; if (!name) continue; try { const res = await fetch(`/api/art/${encodeURIComponent(name)}`); if (!res.ok) continue; const { icon } = await res.json(); if (icon) { img.src = icon; img.classList.remove("no-asset"); img.parentElement.classList.remove("no-asset"); } } catch (err) { console.warn(`Failed to fetch fallback icon for "${name}"`, err); } } }