Add Redeems: channel points, built-in rewards and bits Power-ups

- reward_variations (src/db.js in the wiring commit): each trigger has variations,
  one is picked at random weighted by rarity (Common 50 / Uncommon 25 / Rare 12 /
  Ultra Rare 3), like Twitch alert variations.
- /redeems page: rewards listed live from Twitch, plus Power-ups and built-in
  rewards; per variation name, rarity (with % chance), sound + volume, show cassette
  or sound only, caption, sticker, on/off, play/test/two-click delete.
- Special styles: Gigantify -> giant emote, Celebration -> bouncing emotes,
  Highlight my message / Message Effect -> big taped note.
- redeems-seed.json: first-run defaults rebuilt from the Twitch alert setup
  (96 variations, 21 triggers); only loaded when the table is empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-20 23:18:15 +02:00
parent 1766e37336
commit 553cc35b9e
4 changed files with 372 additions and 0 deletions

110
src/routers/redeems.js Normal file
View file

@ -0,0 +1,110 @@
const express = require('express');
const fs = require('fs');
const path = require('path');
const router = express.Router();
const db = require('../db');
const twitch = require('../twitch');
const redeems = require('../redeems');
const PUBLIC = path.join(__dirname, '../../public');
const listDir = (dir, re) => { try { return fs.readdirSync(path.join(PUBLIC, dir)).filter(f => re.test(f)).sort(); } catch { return []; } };
function soundOptions() {
const re = /\.(mp3|wav|ogg|m4a)$/i;
const lib = [
...listDir('alerts/sounds/redeems', re).map(f => ({ url: `/alerts/sounds/redeems/${f}`, label: `${f} (normalized)` })),
...listDir('alerts/sounds', re).map(f => ({ url: `/alerts/sounds/${f}`, label: f })),
];
const uploads = db.getAllMedia().filter(m => m.media_type === 'audio')
.map(m => ({ url: `/media/${m.filename}`, label: `${m.original_name} (uploaded)` }));
return [...lib, ...uploads];
}
// live list of the channel's custom rewards (title, cost, icon); null when Twitch is not reachable
async function twitchRewards() {
const u = twitch.getUser();
if (!u) return null;
try {
const res = await twitch.helix(`/channel_points/custom_rewards?broadcaster_id=${u.twitch_id}`);
if (!res.ok) return null;
return (await res.json()).data.map(r => ({
kind: 'reward', key: r.id, title: r.title, cost: r.cost, live: r.is_enabled,
image: r.image?.url_1x || r.default_image?.url_1x || null,
}));
} catch { return null; }
}
router.get('/', async (req, res) => {
const variations = db.getAllVariations();
const byTrigger = new Map();
for (const v of variations) {
const k = `${v.kind}|${v.key}`;
if (!byTrigger.has(k)) byTrigger.set(k, []);
byTrigger.get(k).push(v);
}
const fromTwitch = await twitchRewards();
const rewards = fromTwitch ? [...fromTwitch] : [];
// rewards that have variations but were not in the Twitch list (offline, or deleted on Twitch)
for (const v of variations) {
if (v.kind === 'reward' && !rewards.some(r => r.key === v.key)) {
rewards.push({ kind: 'reward', key: v.key, title: v.title, cost: null, missing: !!fromTwitch });
}
}
const uniq = (list) => list.filter((r, i) => list.findIndex(x => x.key === r.key) === i);
const groups = [
{ name: 'Channel point rewards', items: uniq(rewards).sort((a, b) => (a.cost ?? 1e9) - (b.cost ?? 1e9)) },
{ name: 'Bits Power-ups', items: Object.entries(redeems.POWER_UPS).map(([key, title]) => ({ kind: 'power_up', key, title })) },
{ name: 'Built-in channel point rewards', items: Object.entries(redeems.AUTO_REWARDS).map(([key, title]) => ({ kind: 'auto_reward', key, title })) },
];
for (const g of groups) for (const t of g.items) t.variations = byTrigger.get(`${t.kind}|${t.key}`) || [];
res.render('redeems', {
groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY,
sounds: soundOptions(),
stickers: [
...listDir('alerts/stickers', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/stickers/${f}`, label: f.replace(/\.\w+$/, '') })),
...listDir('alerts/art', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/art/${f}`, label: f.replace('_Contrast', '').replace(/\.\w+$/, '') })),
],
});
});
const back = (res, v) => res.redirect(`/redeems#t-${encodeURIComponent(`${v.kind}-${v.key}`)}`);
router.post('/variation', (req, res) => {
const { kind, key, title } = req.body;
if (!['reward', 'auto_reward', 'power_up'].includes(kind) || !key) return res.status(400).send('bad trigger');
const n = db.getVariationsFor(kind, key).length;
const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key) });
back(res, v);
});
router.post('/variation/:id', (req, res) => {
const v = db.getVariation(req.params.id);
if (!v) return res.status(404).send('not found');
const b = req.body;
const vol = parseFloat(b.volume);
db.updateVariation(v.id, {
name: (b.name || '').trim() || v.name,
rarity: redeems.RARITY[b.rarity] ? b.rarity : v.rarity,
sound: b.sound || '',
volume: isNaN(vol) ? v.volume : Math.max(0, Math.min(1, vol)),
polaroid: b.polaroid === 'on' ? 1 : 0,
caption: (b.caption || '').trim() || 'redeemed it! ♡',
art: b.art || '',
enabled: b.enabled === 'on' ? 1 : 0,
});
back(res, v);
});
router.post('/variation/:id/delete', (req, res) => {
const v = db.getVariation(req.params.id);
if (v) db.deleteVariation(v.id);
v ? back(res, v) : res.redirect('/redeems');
});
// tests send the alert to the overlay only (not logged)
router.post('/variation/:id/test', (req, res) => res.json({ ok: redeems.test({ id: req.params.id }) }));
router.post('/trigger/test', (req, res) => res.json({ ok: redeems.test({ kind: req.body.kind, key: req.body.key }) }));
module.exports = router;