const db = require('./db'); const ws = require('./ws'); const { isOnCooldown, setCooldown } = require('./cooldowns'); // replay: the overlay message that was shown for this event, stored so the dashboard can play it again function dispatchEvent(eventType, eventDetail = null, username = null, data = null, replay = null) { const actions = db.getMatchingActions(eventType, eventDetail); let fired = 0; for (const action of actions) { if (isOnCooldown(action.id, action.cooldown_seconds)) { console.log(`[dispatch] Action ${action.id} on cooldown — skipping`); continue; } let mediaUrl = null; if (action.media_file_id) { const media = db.getMediaFile(action.media_file_id); if (media) mediaUrl = `/media/${media.filename}`; } ws.broadcast({ event_type: eventType, action_type: action.action_type, media_url: mediaUrl, alert_text: action.alert_text, username, }); setCooldown(action.id); fired++; console.log(`[dispatch] Fired action ${action.id} (${action.name}) — event: ${eventType}, user: ${username}`); } // the log must never take the server down (a bad row once crashed it mid-stream) try { db.logActivity(eventType || 'unknown', eventDetail, username, data, fired, replay); } catch (e) { console.error(`[dispatch] activity log failed (${eventType}):`, e.message); } // per-viewer action statistics (chatlog.js) try { require('./chatlog').onAction(eventType, eventDetail, username, data, replay); } catch (e) { console.error(`[dispatch] action stats failed (${eventType}):`, e.message); } } module.exports = { dispatchEvent };