Files
EpicNext-Cms/src/lib/services/radio.ts
T
openhands e5ec3c1f06
CI / check (push) Successful in 27s
CI / release (push) Skipped
CI / deploy (push) Successful in 57s
perf: optimize CMS queries, caching, and asset delivery
Database:
- Add missing indexes (users.credits, users_currency(type,amount),
  users_settings.respects_received, camera_web.timestamp,
  messenger_offline.user_id) via migrations 0020/0021
- Use partial .select() everywhere instead of SELECT * (tickets, users,
  rooms, audit logs, catalog tree, polls, radio, password reset)
- Add queryPrepared/queryPreparedOne (server-side prepared statements)
  and switch the login check to a prepared statement; drop dead
  cache options from the pool config
- Raise total_users/total_rooms COUNT(*) cache TTL to 5m

Caching:
- Consolidate the three cache helpers (cached, redisCache, cachedQuery)
  into a single memory-first implementation backed by Redis
- invalidateKey now clears the in-process cache as well as Redis
- Cache homepage sections, news list, and leaderboard tabs; share one
  news_list cache key between homepage and news archive
- siteSettings: in-process cache with TTL so repeated getters no longer
  pay a Redis round-trip per call
- Share a 10s poll cache across all radio SSE connections
- Normalize timestamps after cache reads (Redis JSON round-trip)

Assets:
- Enable AVIF/WebP via images.formats and remove unoptimized from news
  covers and the homepage hero (149KB jpg) with proper sizes/priority
- Support ?format=webp|avif|png in the /imaging proxy via sharp

Other:
- Fix pnpm supply-chain minimumReleaseAge failures by excluding the
  freshly-published packages (next 16.3.1, hookform resolvers 5.8.0,
  resend 6.20.0)
- Remove unused before/after fields from housekeeping AuditEntry
2026-08-14 11:20:37 +02:00

130 lines
4.0 KiB
TypeScript

import { siteSettings } from "@/lib/services/site-settings";
/**
* Best-effort radio stream helpers, shared by the public API and the jobs
* worker. They poll the now-playing / listeners endpoints configured in
* website_settings (AzureCast / Icecast / Shoutcast all differ), parsing the
* common shapes. Everything fails soft (returns null) on error/missing config.
*/
// Block SSRF — only allow http/https to public IPs (no private/loopback/link-local).
const PRIVATE_IP_RE =
/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.0\.0\.0|::1|fe80:|fc00:|fd00:|localhost)/i;
function isSafeUrl(url: string): boolean {
try {
const u = new URL(url);
if (u.protocol !== "http:" && u.protocol !== "https:") return false;
if (PRIVATE_IP_RE.test(u.hostname)) return false;
return true;
} catch {
return false;
}
}
export interface NowPlaying {
title: string;
artist: string | null;
}
// Shared in-process poll cache: every connected SSE client (players, widgets)
// would otherwise hit the radio API once per 10s each. With one cache entry per
// endpoint, N connections cost 1 request per interval regardless of N.
const POLL_CACHE_TTL_MS = 10_000;
const pollCache = new Map<string, { data: unknown; expiresAt: number }>();
async function cachedFetchJson(url: string, ms = 4000): Promise<unknown> {
const now = Date.now();
const hit = pollCache.get(url);
if (hit && hit.expiresAt > now) return hit.data;
const data = await fetchJson(url, ms);
pollCache.set(url, { data, expiresAt: now + POLL_CACHE_TTL_MS });
return data;
}
async function fetchJson(url: string, ms = 4000): Promise<unknown> {
if (!isSafeUrl(url)) return null;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const res = await fetch(url, {
signal: controller.signal,
cache: "no-store",
});
const text = await res.text();
try {
return JSON.parse(text);
} catch {
return text; // plain-text "Artist - Title" (Shoutcast/Icecast metadata)
}
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
function parseNowPlaying(d: unknown): NowPlaying | null {
if (!d) return null;
// AzureCast: { now_playing: { song: { title, artist } } }
const azure = (
d as {
now_playing?: {
song?: { title?: string; artist?: string; text?: string };
};
}
).now_playing?.song;
if (azure?.title || azure?.text) {
return {
title: azure.title ?? azure.text ?? "",
artist: azure.artist ?? null,
};
}
// Generic JSON: { title, artist } or { songtitle }
const generic = d as { title?: string; artist?: string; songtitle?: string };
if (generic.title)
return { title: generic.title, artist: generic.artist ?? null };
if (generic.songtitle) {
const [a, t] = generic.songtitle.split(" - ");
return t
? { title: t.trim(), artist: a.trim() }
: { title: generic.songtitle, artist: null };
}
// Plain text "Artist - Title"
if (typeof d === "string" && d.trim()) {
const parts = d.split(" - ");
return parts.length > 1
? { title: parts.slice(1).join(" - ").trim(), artist: parts[0].trim() }
: { title: d.trim(), artist: null };
}
return null;
}
export async function fetchNowPlaying(): Promise<NowPlaying | null> {
const url = (await siteSettings.get("radio_now_playing_api_url", "")) ?? "";
if (!url) return null;
return parseNowPlaying(await cachedFetchJson(url));
}
export async function fetchListeners(): Promise<number | null> {
const url = (await siteSettings.get("radio_listeners_api_url", "")) ?? "";
if (!url) return null;
const d = await cachedFetchJson(url);
if (d == null) return null;
const obj = d as { listeners?: unknown; current_listeners?: unknown };
const raw =
typeof d === "number"
? d
: (obj.listeners ??
obj.current_listeners ??
(typeof d === "string" ? Number(d) : null));
const n = Number(
typeof raw === "object" &&
raw &&
"total" in (raw as Record<string, unknown>)
? (raw as { total: unknown }).total
: raw,
);
return Number.isFinite(n) ? n : null;
}