// Expects STEAM_API_KEY, STEAM_ID, XBL_TOKEN, JELLYFIN_URL, JELLYFIN_API_KEY, JELLYFIN_USER_ID, and IMOOD_EMAIL. // Uses the OpenXBL API, official Steam API, Jellyfin API, and imood API. const FETCH_TIMEOUT_MS = 10_000; const CORS_HEADERS = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Max-Age": "86400", }; const jsonResponse = (body, init = {}) => new Response(JSON.stringify(body), { ...init, headers: { "Content-Type": "application/json", "Cache-Control": "no-store", ...CORS_HEADERS, ...init.headers, }, }); const safeFetchText = async (label, url, options = {}) => { if (!url) return null; try { const response = await fetch(url, { ...options, signal: options.signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS), }); if (!response.ok) { console.error(`API Error (${label}): ${response.status} ${response.statusText}`); return null; } return await response.text(); } catch (error) { const reason = error?.name === "TimeoutError" ? "request timed out" : error?.message || "unknown error"; console.error(`Fetch Error (${label}):`, reason); return null; } }; const safeFetchJson = async (label, url, options = {}) => { const text = await safeFetchText(label, url, { ...options, headers: { Accept: "application/json", ...options.headers, }, }); if (text === null) return null; try { return JSON.parse(text); } catch (error) { console.error(`JSON Parse Error (${label}):`, error.message); return null; } }; const XML_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" }; const decodeXml = (value) => value .replace(//g, "$1") .replace(/&#x([0-9a-f]+);/gi, (_, hex) => { const codePoint = Number.parseInt(hex, 16); return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : ""; }) .replace(/&#(\d+);/g, (_, decimal) => { const codePoint = Number.parseInt(decimal, 10); return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : ""; }) .replace(/&(amp|lt|gt|quot|apos);/g, (_, entity) => XML_ENTITIES[entity]); const extractXml = (xml, tag) => { if (!xml) return null; const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)`, "i")); return match ? decodeXml(match[1]).trim() : null; }; const normaliseImoodMood = ({ base = null, personal = null, face = null, updatedAt = null } = {}) => ({ base: base || null, personal: personal ? personal.replace(/\r\n?/g, "\n") : null, face: Number.isInteger(face) ? face : null, updatedAt: updatedAt || null, }); const parseImoodXml = (xml) => { if (!xml || / { const timestamp = session.LastPlaybackCheckIn || session.LastActivityDate; const time = timestamp ? Date.parse(timestamp) : 0; return Number.isNaN(time) ? 0 : time; }; const normaliseUserId = (userId) => (typeof userId === "string" ? userId.replace(/-/g, "").toLowerCase() : null); const isDashboardTitle = (name) => typeof name === "string" && /^(home|xbox home|dashboard)$/i.test(name.trim()); export default { async fetch(request, env) { if (request.method === "OPTIONS") { return new Response(null, { headers: CORS_HEADERS }); } if (request.method !== "GET" && request.method !== "HEAD") { return new Response("Method Not Allowed", { status: 405, headers: { ...CORS_HEADERS, Allow: "GET, HEAD, OPTIONS" }, }); } const fetchImood = async () => { const email = env.IMOOD_EMAIL?.trim(); if (!email) return null; const emailUrl = `https://xml.imood.org/query.cgi?email=${encodeURIComponent(email)}`; return parseImoodXml(await safeFetchText("imood XML", emailUrl)); }; try { const xblUrl = env.XBL_TOKEN ? "https://api.xbl.io/v2/presence" : null; const steamUrl = env.STEAM_API_KEY && env.STEAM_ID ? `https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key=${encodeURIComponent(env.STEAM_API_KEY)}&steamids=${encodeURIComponent(env.STEAM_ID)}` : null; const jellyfinBase = env.JELLYFIN_URL?.replace(/\/+$/, ""); const jellyfinUrl = jellyfinBase && env.JELLYFIN_API_KEY && env.JELLYFIN_USER_ID ? `${jellyfinBase}/Sessions` : null; const [xboxData, steamData, jellyfinData, imood] = await Promise.all([ safeFetchJson("Xbox", xblUrl, { headers: { "X-Authorization": env.XBL_TOKEN } }), safeFetchJson("Steam", steamUrl), safeFetchJson("Jellyfin", jellyfinUrl, { headers: { "X-MediaBrowser-Token": env.JELLYFIN_API_KEY } }), fetchImood(), ]); // Parse Xbox let xboxOnline = false, xboxState = "Offline"; let xboxActiveTitle = null; let xboxLastSeen = null; let xboxDevices = []; if (xboxData?.content && typeof xboxData.content === "object") { const xboxContent = xboxData.content; xboxState = xboxContent.state || "Offline"; xboxOnline = xboxState === "Online"; const devices = Array.isArray(xboxContent.devices) ? xboxContent.devices : []; xboxDevices = devices; const titleCandidates = devices.flatMap((device) => { const titles = Array.isArray(device?.titles) ? device.titles : []; return titles.filter((title) => title?.name && !isDashboardTitle(title.name) && (!title.placement || title.placement === "Full")).map((title) => ({ title, device })); }); const active = titleCandidates.find(({ title }) => title.state === "Active") || titleCandidates[0]; if (active) { const { title, device } = active; xboxActiveTitle = { name: title.name, deviceType: device.type || null, state: title.state || null, lastModified: title.lastModified || null, richPresence: title.activity?.richPresence || null, }; } if (xboxContent.lastSeen?.titleName && !isDashboardTitle(xboxContent.lastSeen.titleName)) { xboxLastSeen = { titleName: xboxContent.lastSeen.titleName, deviceType: xboxContent.lastSeen.deviceType || null, timestamp: xboxContent.lastSeen.timestamp || null, }; } } // Parse Steam let steamOnline = false, steamSlug = "offline", steamGame = null; if (steamData?.response?.players?.[0]) { const player = steamData.response.players[0]; const personaState = Number(player.personastate); const steamSlugs = ["offline", "online", "busy", "away", "snooze", "looking_trade", "looking_play"]; steamSlug = steamSlugs[personaState] || "unknown"; steamOnline = [1, 5, 6].includes(personaState); steamGame = player.gameextrainfo || null; } // Parse Jellyfin let jellyfinActive = false, jellyfinPaused = false, jellyfinMedia = null; if (Array.isArray(jellyfinData)) { const jellyfinUserId = normaliseUserId(env.JELLYFIN_USER_ID); const sessionBelongsToUser = (session) => { if (!jellyfinUserId) return false; const additionalUsers = Array.isArray(session.AdditionalUsers) ? session.AdditionalUsers : []; const userIds = [session.UserId, ...additionalUsers.map((user) => user?.UserId)]; return userIds.some((userId) => normaliseUserId(userId) === jellyfinUserId); }; const activeSessions = jellyfinData.filter((session) => { const item = session?.NowPlayingItem; if (!item || !sessionBelongsToUser(session)) return false; const type = typeof item.Type === "string" ? item.Type.toLowerCase() : ""; return type === "episode" || type === "movie"; }); const activeSession = activeSessions.sort((a, b) => { // Prefer a playing session over an older paused one. const pausedOrder = Number(Boolean(a.PlayState?.IsPaused)) - Number(Boolean(b.PlayState?.IsPaused)); return pausedOrder || sessionActivityTime(b) - sessionActivityTime(a); })[0]; if (activeSession) { jellyfinActive = true; jellyfinPaused = Boolean(activeSession.PlayState?.IsPaused); const item = activeSession.NowPlayingItem; const isEpisode = item.Type.toLowerCase() === "episode"; jellyfinMedia = isEpisode ? { type: "tv", show: item.SeriesName || null, season: item.ParentIndexNumber ?? null, episode: item.IndexNumber ?? null, episodeName: item.Name || null, } : { type: "movie", title: item.Name || null, year: item.ProductionYear || null, }; } } const presenceData = { xbox: { online: xboxOnline, state: xboxState, devices: xboxDevices, activeTitle: xboxActiveTitle, lastSeen: xboxLastSeen, }, steam: { online: steamOnline, slug: steamSlug, game: steamGame }, jellyfin: { active: jellyfinActive, paused: jellyfinPaused, media: jellyfinMedia }, imood: imood || normaliseImoodMood(), updatedAt: new Date().toISOString(), }; return jsonResponse(presenceData); } catch (error) { console.error("Catastrophic Worker Error:", error.stack || error); return jsonResponse({ error: "Failed to assemble presence data" }, { status: 500 }); } }, };