diff --git a/src/redeems-seed.json b/src/redeems-seed.json new file mode 100644 index 0000000..82af76e --- /dev/null +++ b/src/redeems-seed.json @@ -0,0 +1,41 @@ +{ + "_comment": "Example first-run defaults for the Redeems page: one silent variation per Twitch built-in reward / Power-up. A channel's own seed goes in src/redeems-seed.json (not in git; used instead of this file when present). Loaded only when the reward_variations table is empty; after that the dashboard is the source of truth. sound = URL under /public ('' = silent), art = cassette sticker URL ('' = the theme's default sticker).", + "variations": [ + { + "kind": "auto_reward", + "key": "send_highlighted_message", + "title": "Highlight my message", + "name": "Highlighted", + "rarity": "common", + "sound": "", + "art": "" + }, + { + "kind": "power_up", + "key": "message_effect", + "title": "Power-up: Message Effect", + "name": "Message effect", + "rarity": "common", + "sound": "", + "art": "" + }, + { + "kind": "power_up", + "key": "celebration", + "title": "Power-up: On-Screen Celebration", + "name": "Celebration", + "rarity": "common", + "sound": "", + "art": "" + }, + { + "kind": "power_up", + "key": "gigantify_an_emote", + "title": "Power-up: Gigantify an Emote", + "name": "Giant emote", + "rarity": "common", + "sound": "", + "art": "" + } + ] +} diff --git a/src/redeems.js b/src/redeems.js new file mode 100644 index 0000000..a92e8d4 --- /dev/null +++ b/src/redeems.js @@ -0,0 +1,89 @@ +// Channel point rewards, built-in channel point rewards and bits Power-ups. +// Each trigger (kind + key) has variations; one enabled variation is picked at random, +// weighted by rarity (like Twitch alert variations), and played as a polaroid or sound-only alert. +const db = require('./db'); +const alerts = require('./alerts'); +const dispatch = require('./dispatch'); + +// relative weight per rarity (Twitch does not publish its numbers; tune here). +// chance of a variation = its weight / sum of the weights of the trigger's ENABLED variations +const RARITY = { + common: { label: 'Common', weight: 50 }, + uncommon: { label: 'Uncommon', weight: 25 }, + rare: { label: 'Rare', weight: 12 }, + ultra_rare: { label: 'Ultra Rare', weight: 3 }, +}; + +// built-in (automatic) channel point rewards, channel.channel_points_automatic_reward_redemption.add v2 +const AUTO_REWARDS = { + send_highlighted_message: 'Highlight my message', + single_message_bypass_sub_mode: 'Send a message in sub-only mode', + random_sub_emote_unlock: 'Unlock a random sub emote', + chosen_sub_emote_unlock: 'Choose an emote to unlock', + chosen_modified_sub_emote_unlock: 'Modify a single emote', +}; + +// bits Power-ups, channel.bits.use with type = power_up +const POWER_UPS = { + message_effect: 'Power-up: Message Effect', + celebration: 'Power-up: On-Screen Celebration', + gigantify_an_emote: 'Power-up: Gigantify an Emote', +}; + +// how a trigger is drawn on the overlay (everything else: cassette tape) +const STYLE = { + 'power_up:gigantify_an_emote': 'emote', // the viewer's emote, giant + 'power_up:celebration': 'emote_rain', // copies of the emote bouncing around the screen + 'auto_reward:send_highlighted_message': 'message', // big taped paper note with the message + 'power_up:message_effect': 'message', // same as highlight +}; +const LINE = { emote: 'gigantified an emote!', emote_rain: 'is celebrating!', message: 'highlighted:' }; +const emoteUrl = id => id ? `https://static-cdn.jtvnw.net/emoticons/v2/${encodeURIComponent(id)}/default/dark/3.0` : null; + +function pick(variations) { + const pool = variations.filter(v => v.enabled); + const total = pool.reduce((s, v) => s + (RARITY[v.rarity]?.weight || 1), 0); + let r = Math.random() * total; + for (const v of pool) { r -= RARITY[v.rarity]?.weight || 1; if (r < 0) return v; } + return pool[pool.length - 1] || null; +} + +function toAlert(v, { user, input, emote }) { + const style = STYLE[`${v.kind}:${v.key}`] || 'cassette'; + return { + type: 'redeem', kind: v.kind, key: v.key, style, + user, reward: v.title, variation: v.name, rarity: v.rarity, input: input || null, + // special styles have their own wording unless the caption was customised + caption: style !== 'cassette' && v.caption === 'redeemed it! ♡' ? LINE[style] : v.caption, + sound: v.sound || null, volume: v.volume, polaroid: !!v.polaroid, art: v.art || null, emote: emoteUrl(emote), + }; +} + +// legacy action event type for the actions system / activity log +const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up' }; + +// A redemption arrived from Twitch. +function handle(kind, key, title, { user, input, emote }, raw) { + if (title) db.renameTrigger(kind, key, title); + const v = pick(db.getVariationsFor(kind, key)); + if (!v) { + // nothing configured (or all off): still log it and run legacy actions + dispatch.dispatchEvent(LEGACY[kind], key, user, raw); + return null; + } + const alert = toAlert(v, { user, input, emote }); + alerts.send(alert, raw); + return alert; +} + +// Dashboard test: one specific variation, or a random pick for the whole trigger. +function test({ id, kind, key }) { + const v = id ? db.getVariation(id) : pick(db.getVariationsFor(kind, key)); + if (!v) return false; + const input = ['send_highlighted_message', 'message_effect'].includes(v.key) ? 'this is what a highlighted message looks like on stream!' + : v.kind === 'reward' ? 'test input' : null; + alerts.sendTestAlert(toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null })); // 25 = Kappa + return true; +} + +module.exports = { RARITY, AUTO_REWARDS, POWER_UPS, STYLE, pick, handle, test }; diff --git a/src/routers/redeems.js b/src/routers/redeems.js new file mode 100644 index 0000000..504acd0 --- /dev/null +++ b/src/routers/redeems.js @@ -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; diff --git a/views/redeems.ejs b/views/redeems.ejs new file mode 100644 index 0000000..3b5912f --- /dev/null +++ b/views/redeems.ejs @@ -0,0 +1,132 @@ + + +

Redeems

+

+ Each redeem plays one of its enabled variations, picked at random by rarity + (<% for (const [k, r] of Object.entries(rarity)) { %><%= r.label %> <%= r.weight %><% if (k !== 'ultra_rare') { %> · <% } %><% } %>, relative weights). + Sounds: built-in library, or upload more on the Media page. + <% if (!twitchOk) { %>
Could not load your rewards from Twitch right now, so only rewards that already have variations are listed.<% } %> +

+ +<% for (const g of groups) { %> +

<%= g.name %>

+ <% for (const t of g.items) { + const on = t.variations.filter(v => v.enabled); + const total = on.reduce((s, v) => s + (rarity[v.rarity]?.weight || 1), 0); + const anchor = `t-${t.kind}-${t.key}`; %> +
+ + <% if (t.image) { %><% } %> + <%= t.title %> + <% if (t.cost != null) { %><%= t.cost %> pts<% } %> + <% if (t.missing) { %>not on Twitch anymore<% } %> + <% if (t.live === false) { %>paused on Twitch<% } %> + + <%= t.variations.length ? `${on.length}/${t.variations.length} variation${t.variations.length === 1 ? '' : 's'} on` : 'no alert' %> + + <% if (on.length) { %> + + <% } %> + + + <% for (const v of t.variations) { %> +
+
+
+ + <% if (v.enabled && total) { %><%= Math.round(100 * (rarity[v.rarity]?.weight || 1) / total) %>% chance<% } %> +
+
+ +
+
+
+ + + + + + + + + +
+
+ <% } %> + +
+ + + + +
+
+ <% } %> +<% } %> + +

+ +