const express = require('express'); const router = express.Router(); const alerts = require('../alerts'); const twitch = require('../twitch'); const ws = require('../ws'); // POST /alerts/test/:key: send a sample alert to every connected overlay (dashboard test buttons) router.post('/test/:key', (req, res) => { const ok = alerts.sendTest(req.params.key); res.status(ok ? 200 : 404).json({ ok }); }); // POST /alerts/skip: stop the alert on screen right now (e.g. a TTS message), the queue carries on router.post('/skip', (req, res) => { ws.broadcast({ type: 'alert_skip' }); console.log('[alerts] skip requested from the dashboard'); res.json({ ok: true }); }); // POST /alerts/raid/start {target}: start a raid on Twitch and show the send-off card until it happens router.post('/raid/start', async (req, res) => { const me = twitch.getUser(); const login = String(req.body.target || '').trim().replace(/^@/, '').toLowerCase(); if (!me) return res.status(400).json({ ok: false, error: 'not connected to Twitch' }); if (!/^[a-z0-9_]{2,25}$/.test(login)) return res.status(400).json({ ok: false, error: 'invalid channel name' }); try { const u = await twitch.helix(`/users?login=${encodeURIComponent(login)}`); const target = u.ok ? (await u.json()).data?.[0] : null; if (!target) return res.status(404).json({ ok: false, error: 'channel not found' }); const r = await twitch.helix(`/raids?from_broadcaster_id=${me.twitch_id}&to_broadcaster_id=${target.id}`, { method: 'POST' }); if (!r.ok) { const body = await r.json().catch(() => ({})); return res.status(r.status).json({ ok: false, error: body.message || `Twitch said ${r.status}` }); } let viewers = null; const s = await twitch.helix(`/streams?user_id=${me.twitch_id}`); if (s.ok) viewers = (await s.json()).data?.[0]?.viewer_count ?? null; alerts.raidStarted({ target: target.display_name, avatar: target.profile_image_url || null, viewers }); res.json({ ok: true, target: target.display_name, viewers }); } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); // POST /alerts/raid/cancel: cancel the pending raid on Twitch and remove the card router.post('/raid/cancel', async (req, res) => { const me = twitch.getUser(); if (!me) return res.status(400).json({ ok: false, error: 'not connected to Twitch' }); const r = await twitch.helix(`/raids?broadcaster_id=${me.twitch_id}`, { method: 'DELETE' }).catch(e => ({ ok: false, status: 500, e })); alerts.raidCancelled(); res.status(r.ok || r.status === 404 ? 200 : r.status).json({ ok: r.ok || r.status === 404 }); }); module.exports = router;