- Implement main.js for the master display functionality, including WebSocket connection, audio output management, and state handling. - Create style.css for the master display's visual design, ensuring a cohesive look and feel with a dark theme and responsive layout. - Integrate device management with a fallback for non-Electron environments, allowing users to select audio outputs. - Add features for managing favorites, including toggling favorites and filtering by genre. - Enhance user experience with a responsive favorites grid and drag-to-scroll functionality.
169 lines
6.3 KiB
JavaScript
169 lines
6.3 KiB
JavaScript
// Local cover-art storage for stations.
|
|
//
|
|
// Files live under <repo>/data/images/stations/<id>.<ext> and are served by
|
|
// express.static at /media/stations/<id>.<ext>. The DB tracks just the
|
|
// relative path in stations.image_path (e.g. "stations/12.jpg"), while
|
|
// stations.image_url keeps the original remote URL for refetch/debugging.
|
|
|
|
import { mkdirSync, existsSync, writeFileSync, readdirSync, unlinkSync, statSync } from 'node:fs';
|
|
import { resolve, join, dirname } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { getDb } from '../db/index.js';
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
const ROOT = resolve(__dirname, '..', '..', 'data', 'images');
|
|
const STATIONS_DIR = join(ROOT, 'stations');
|
|
// A browser-like UA is required by Wikimedia and several CDNs; an opaque
|
|
// UA like "OnlineRadioExplorer/0.1" gets HTTP 400/403 from upload.wikimedia.org.
|
|
// Override via env if you want to publish a contact URL.
|
|
const UA = process.env.IMAGE_FETCH_UA
|
|
|| 'Mozilla/5.0 (compatible; OnlineRadioExplorer/0.1; +https://github.com/marcoheine/onlineRadioExplorer)';
|
|
const FETCH_TIMEOUT_MS = 10_000;
|
|
const MAX_BYTES = 4 * 1024 * 1024; // 4 MB per image
|
|
|
|
const MIME_EXT = {
|
|
'image/jpeg': 'jpg',
|
|
'image/jpg': 'jpg',
|
|
'image/pjpeg': 'jpg',
|
|
'image/png': 'png',
|
|
'image/webp': 'webp',
|
|
'image/gif': 'gif',
|
|
'image/svg+xml': 'svg',
|
|
'image/x-icon': 'ico',
|
|
'image/vnd.microsoft.icon': 'ico'
|
|
};
|
|
|
|
export function ensureImageDirs() {
|
|
mkdirSync(STATIONS_DIR, { recursive: true });
|
|
}
|
|
|
|
export function getImageRoot() { return ROOT; }
|
|
|
|
// Strip any existing file for this station id (with any extension).
|
|
function removeExistingStationFile(id) {
|
|
if (!existsSync(STATIONS_DIR)) return;
|
|
const prefix = `${id}.`;
|
|
for (const f of readdirSync(STATIONS_DIR)) {
|
|
if (f.startsWith(prefix)) {
|
|
try { unlinkSync(join(STATIONS_DIR, f)); } catch { }
|
|
}
|
|
}
|
|
}
|
|
|
|
function extFromMime(mime) {
|
|
if (!mime) return null;
|
|
const base = mime.split(';')[0].trim().toLowerCase();
|
|
return MIME_EXT[base] || null;
|
|
}
|
|
|
|
function extFromMagic(buf) {
|
|
if (buf.length < 12) return null;
|
|
// PNG
|
|
if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4E && buf[3] === 0x47) return 'png';
|
|
// JPEG
|
|
if (buf[0] === 0xFF && buf[1] === 0xD8 && buf[2] === 0xFF) return 'jpg';
|
|
// GIF
|
|
if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46) return 'gif';
|
|
// WEBP: "RIFF...WEBP"
|
|
if (buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46
|
|
&& buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) return 'webp';
|
|
// SVG: starts with "<?xml" or "<svg"
|
|
const head = buf.slice(0, 256).toString('utf8').trimStart().toLowerCase();
|
|
if (head.startsWith('<?xml') || head.startsWith('<svg')) return 'svg';
|
|
// ICO
|
|
if (buf[0] === 0x00 && buf[1] === 0x00 && buf[2] === 0x01 && buf[3] === 0x00) return 'ico';
|
|
return null;
|
|
}
|
|
|
|
async function downloadToBuffer(url) {
|
|
const ctl = new AbortController();
|
|
const t = setTimeout(() => ctl.abort(), FETCH_TIMEOUT_MS);
|
|
try {
|
|
const res = await fetch(url, {
|
|
headers: { 'User-Agent': UA, 'Accept': 'image/*' },
|
|
redirect: 'follow',
|
|
signal: ctl.signal
|
|
});
|
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
const ct = res.headers.get('content-type') || '';
|
|
const reader = res.body?.getReader();
|
|
if (!reader) throw new Error('no body');
|
|
const chunks = [];
|
|
let received = 0;
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
received += value.length;
|
|
if (received > MAX_BYTES) { try { await reader.cancel(); } catch { } throw new Error('too large'); }
|
|
chunks.push(Buffer.from(value));
|
|
}
|
|
return { buffer: Buffer.concat(chunks), contentType: ct };
|
|
} finally { clearTimeout(t); }
|
|
}
|
|
|
|
/**
|
|
* Persist a buffer as the station's cover-art file and update the DB.
|
|
* Returns the relative path (e.g. "stations/12.jpg").
|
|
*/
|
|
export function saveStationImageFromBuffer(stationId, buf, mime, { source = 'upload' } = {}) {
|
|
ensureImageDirs();
|
|
// Reject obvious HTML responses (404 pages, SPA index, login walls) even
|
|
// when the upstream lies about the content-type.
|
|
const head = buf.slice(0, 512).toString('utf8').trimStart().toLowerCase();
|
|
if (head.startsWith('<!doctype html') || head.startsWith('<html')) {
|
|
throw new Error('response is HTML, not an image');
|
|
}
|
|
const ext = extFromMime(mime) || extFromMagic(buf);
|
|
if (!ext) throw new Error('unsupported image type');
|
|
removeExistingStationFile(stationId);
|
|
const fileName = `${stationId}.${ext}`;
|
|
writeFileSync(join(STATIONS_DIR, fileName), buf);
|
|
const rel = `stations/${fileName}`;
|
|
getDb().prepare(
|
|
"UPDATE stations SET image_path = ?, image_source = ?, updated_at = datetime('now') WHERE id = ?"
|
|
).run(rel, source, stationId);
|
|
return rel;
|
|
}
|
|
|
|
/**
|
|
* Download an image from a URL and store it locally for the station.
|
|
* Returns the relative path or null on failure.
|
|
*/
|
|
export async function saveStationImageFromUrl(stationId, url, { source = 'remote' } = {}) {
|
|
if (!url) return null;
|
|
let dl;
|
|
try {
|
|
dl = await downloadToBuffer(url);
|
|
} catch {
|
|
return null;
|
|
}
|
|
try {
|
|
return saveStationImageFromBuffer(stationId, dl.buffer, dl.contentType, { source });
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function deleteStationImage(stationId) {
|
|
removeExistingStationFile(stationId);
|
|
getDb().prepare(
|
|
"UPDATE stations SET image_path = NULL, image_source = NULL, updated_at = datetime('now') WHERE id = ?"
|
|
).run(stationId);
|
|
}
|
|
|
|
/** Public URL the kiosk should use. Local if cached, else the remote URL, else null. */
|
|
export function publicImageUrl({ image_path, image_url } = {}) {
|
|
if (image_path) return `/media/${image_path}`;
|
|
return image_url || null;
|
|
}
|
|
|
|
/** Total bytes used by the station-image cache (best effort). */
|
|
export function imageCacheStats() {
|
|
if (!existsSync(STATIONS_DIR)) return { files: 0, bytes: 0 };
|
|
let files = 0, bytes = 0;
|
|
for (const f of readdirSync(STATIONS_DIR)) {
|
|
try { bytes += statSync(join(STATIONS_DIR, f)).size; files++; } catch { }
|
|
}
|
|
return { files, bytes };
|
|
}
|