Files
radio-explorer/server/media/images.js
Marco Mooren f6cdfd975c feat: integrate Electron for desktop application support
- Added Electron entry point in `electron/main.js` to run the Express server in-process and open the main application window.
- Updated `package.json` to include Electron dependencies and scripts for building and running the application.
- Refactored server startup logic into `server/start.js` for better modularity and to support both CLI and Electron usage.
- Implemented environment variable handling for database and image paths to accommodate Electron's packaging.
- Created a script `server/scripts/promote-morphix.js` to merge admin and morphix accounts into a single user.
- Adjusted image root path resolution in `server/media/images.js` to allow for environment variable overrides.
- Cleaned up `server/index.js` to delegate server initialization to the new `startServer` function.
2026-05-11 18:55:02 +02:00

173 lines
6.5 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));
// Where cover art lives. Overridable via env so Electron (packaged) can point
// it at app.getPath('userData')/data/images instead of the read-only asar dir.
const ROOT = process.env.ORADIO_IMAGE_ROOT
? resolve(process.env.ORADIO_IMAGE_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 };
}