Video Power-ups: Custom Power-ups, ?parts=video overlay, new redeems editor

- Custom Power-ups (bits) are redeem triggers: channel.custom_power_up_redemption.add
  -> redeems.handle('custom_power_up', ...) with the bits amount; listed live from
  Helix /bits/custom_power_ups on the Redeems page; labels/replay in Recent activity.
- Variations can show a video (reward_variations.video): style 'video' plays only on
  the opt-in ?parts=video overlay (public/alerts/video.js), full-screen, one at a time,
  with a yellow camcorder box ("TRIGGERED <name>", viewer, bits, POWER-UP) in the alert
  corner. Any source size; 2560x1440 like HUDFX gives sharper video.
- Redeems page rewritten as one editor: Display (Cassette / Sound only / Video),
  volume slider, sticker thumbnails, live % chances, one Save button + Ctrl+S
  (POST /redeems/save), tests/add/delete save first, unsaved edits kept as a browser
  draft with an inline restore bar (no dialogs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-22 16:10:56 +02:00
parent 19a0965eb2
commit b3caac7a31
11 changed files with 512 additions and 135 deletions

View file

@ -12,11 +12,11 @@ const RARITY = { common: 'Common', uncommon: 'Uncommon', rare: 'Rare', ultra_rar
const LABEL = {
follow: 'Follow', sub: 'Sub', gift_sub: 'Gift sub', bits: 'Bits', watch_streak: 'Watch streak',
raid: 'Raid in', raid_out: 'Raid out', hype_train: 'Hype Train', tip: 'Tip',
channel_points: 'Channel points', auto_reward: 'Built-in reward', power_up: 'Power-up',
channel_points: 'Channel points', auto_reward: 'Built-in reward', power_up: 'Power-up', custom_power_up: 'Custom Power-up',
poll_begin: 'Poll started', poll_end: 'Poll ended', command: 'Command',
};
const REDEEM_KIND = { channel_points: 'reward', auto_reward: 'auto_reward', power_up: 'power_up' };
const REDEEM_KIND = { channel_points: 'reward', auto_reward: 'auto_reward', power_up: 'power_up', custom_power_up: 'custom_power_up' };
function parse(json) { try { return json ? JSON.parse(json) : null; } catch { return null; } }
@ -27,6 +27,7 @@ function rewardTitle(type, raw, alert) {
if (type === 'channel_points') return raw?.reward?.title || null;
if (type === 'auto_reward') return AUTO_REWARDS[raw?.reward?.type] || raw?.reward?.type || null;
if (type === 'power_up') return POWER_UPS[raw?.power_up?.type] || raw?.power_up?.type || null;
if (type === 'custom_power_up') return raw?.custom_power_up?.title || null;
return null;
}
@ -43,10 +44,12 @@ function describe(log) {
if (raw?.reward?.cost) out.tags.push(`${raw.reward.cost} points`);
else if (raw?.reward?.channel_points) out.tags.push(`${raw.reward.channel_points} points`);
else if (raw?.bits) out.tags.push(`${raw.bits} bits`);
else if (raw?.custom_power_up?.bits) out.tags.push(`${raw.custom_power_up.bits} bits`);
if (a) {
if (a.variation && a.variation !== a.reward) out.tags.push(`played: ${a.variation}`);
if (a.rarity && a.rarity !== 'common') out.tags.push(RARITY[a.rarity] || a.rarity);
if (a.tts) out.tags.push('TTS');
if (a.video) out.tags.push('video');
}
out.message = a?.input || raw?.user_input || raw?.message?.text || null;
} else if (a) {
@ -111,7 +114,8 @@ async function replayMessage(log) {
const key = log.event_detail;
const input = raw.user_input || raw.message?.text || null;
const emote = raw.reward?.emote?.id || raw.power_up?.emote?.id || null;
const alert = await require('./redeems').rebuild(kind, key, { user: raw.user_name || raw.user_login || log.username, input, emote });
const bits = raw.custom_power_up?.bits ?? null;
const alert = await require('./redeems').rebuild(kind, key, { user: raw.user_name || raw.user_login || log.username, input, emote, bits });
return alert ? { type: 'alert', alert } : null;
}
if (log.event_type === 'raid_out') {

View file

@ -98,7 +98,7 @@ function createSchema() {
CREATE TABLE IF NOT EXISTS reward_variations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL, -- reward | auto_reward | power_up
kind TEXT NOT NULL, -- reward | auto_reward | power_up | custom_power_up
key TEXT NOT NULL, -- reward id / built-in reward type / power-up type
title TEXT NOT NULL, -- trigger name shown in the UI (last known)
name TEXT NOT NULL, -- variation name, shown on the polaroid
@ -141,7 +141,8 @@ function migrate() {
addColumn('activity_log', 'replay_json', 'TEXT');
addColumn('settings', 'hudfx_overlay_url', "TEXT DEFAULT ''");
addColumn('settings', 'chat_hidden_users', "TEXT DEFAULT 'bot_account, blerp, blerpbot, hudfx, hudfxbot, lumiastream'"); // never shown in the on-screen chat
addColumn('settings', 'chat_hide_commands', 'INTEGER DEFAULT 1'); // hide messages starting with ! // HUDFX browser source URL, embedded with ?ext=hudfx // the overlay message that was shown (dashboard Replay)
addColumn('settings', 'chat_hide_commands', 'INTEGER DEFAULT 1'); // hide messages starting with !
addColumn('reward_variations', 'video', "TEXT DEFAULT ''"); // URL of a video: full-screen on the ?parts=video overlay // HUDFX browser source URL, embedded with ?ext=hudfx // the overlay message that was shown (dashboard Replay)
}
// Put the starter TTS blocklist (src/tts-blocklist.txt) into the settings ONCE; after that it is the user's list
@ -282,7 +283,7 @@ function getMatchingActions(eventType, eventDetail) {
}
// Redeem variations
const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled', 'tts_voice_id'];
const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled', 'tts_voice_id', 'video'];
function getAllVariations() {
return db.prepare('SELECT * FROM reward_variations ORDER BY kind, title, id').all();

View file

@ -124,6 +124,8 @@ async function subscribeAll(sessionId) {
{ type: 'channel.follow', version: '2', condition: { broadcaster_user_id: b, moderator_user_id: b } },
// cheers AND bits Power-ups (message effect, celebration, gigantify); replaces channel.cheer
{ type: 'channel.bits.use', version: '1', condition: { broadcaster_user_id: b } },
// Custom Power-ups (bits, made on Twitch): redeem variations, e.g. full-screen videos
{ type: 'channel.custom_power_up_redemption.add', version: '1', condition: { broadcaster_user_id: b } },
// subs, resubs, gifts, community gifts, raids, with Prime/multi-month/recipient/message details
{ type: 'channel.chat.notification', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
{ type: 'channel.channel_points_custom_reward_redemption.add', version: '1', condition: { broadcaster_user_id: b } },
@ -207,6 +209,12 @@ function handleNotification(payload) {
if (alert) alerts.send(alert, event);
break;
}
case 'channel.custom_power_up_redemption.add': {
const p = event.custom_power_up || {};
if (p.id) redeems.handle('custom_power_up', p.id, p.title || 'Custom Power-up',
{ user: event.user_name || event.user_login, input: event.user_input || null, bits: p.bits ?? null }, event);
break;
}
case 'channel.raid':
if (event.from_broadcaster_user_id === broadcasterId) alerts.raidHappened(event).catch(e => console.error('[alerts] raid out:', e.message));
break;

View file

@ -31,6 +31,8 @@ const POWER_UPS = {
gigantify_an_emote: 'Power-up: Gigantify an Emote',
};
// Custom Power-ups (bits, made by the streamer on Twitch): kind 'custom_power_up', key = power-up id
// 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
@ -49,9 +51,10 @@ function pick(variations) {
return pool[pool.length - 1] || null;
}
function toAlert(v, { user, input, emote }) {
function toAlert(v, { user, input, emote, bits }) {
const spoken = !!(v.tts_voice_id && input); // TTS variations: envelope letter (fx.js envelope())
const style = spoken ? 'tts' : (STYLE[`${v.kind}:${v.key}`] || 'cassette');
// video variations play full-screen on the ?parts=video overlay (public/alerts/video.js)
const style = v.video ? 'video' : spoken ? 'tts' : (STYLE[`${v.kind}:${v.key}`] || 'cassette');
const line = spoken ? LINE.tts : LINE[style];
return {
type: 'redeem', kind: v.kind, key: v.key, style, vid: v.id, // vid: re-speak on replay if the mp3 was pruned
@ -60,6 +63,7 @@ function toAlert(v, { user, input, emote }) {
caption: style !== 'cassette' && v.caption === 'redeemed it! ♡' ? line : v.caption,
sound: spoken ? null : (v.sound || null), volume: v.volume, // TTS on: the voice replaces the sound
polaroid: !!v.polaroid, art: v.art || null, emote: emoteUrl(emote),
video: v.video || null, bits: bits ?? null,
};
}
@ -90,10 +94,10 @@ async function addSpeech(v, alert) {
}
// legacy action event type for the actions system / activity log
const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up' };
const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up', custom_power_up: 'custom_power_up' };
// A redemption arrived from Twitch.
function handle(kind, key, title, { user, input, emote }, raw) {
function handle(kind, key, title, { user, input, emote, bits }, raw) {
if (title) db.renameTrigger(kind, key, title);
const v = pick(db.getVariationsFor(kind, key));
if (!v) {
@ -101,19 +105,19 @@ function handle(kind, key, title, { user, input, emote }, raw) {
dispatch.dispatchEvent(LEGACY[kind], key, user, raw);
return null;
}
const alert = toAlert(v, { user, input, emote });
if (v.tts_voice_id && input) addSpeech(v, alert).then(() => alerts.send(alert, raw)); // speech first, then the alert
const alert = toAlert(v, { user, input, emote, bits });
if (v.tts_voice_id && input && !v.video) addSpeech(v, alert).then(() => alerts.send(alert, raw)); // speech first, then the alert
else alerts.send(alert, raw);
return alert;
}
// Dashboard Replay of an old activity row that has no stored alert: a fresh pick for the trigger,
// with the viewer's original name and text. Resolves to the alert, or null if nothing is configured.
async function rebuild(kind, key, { user, input, emote }) {
async function rebuild(kind, key, { user, input, emote, bits }) {
const v = pick(db.getVariationsFor(kind, key));
if (!v) return null;
const alert = toAlert(v, { user, input, emote });
if (v.tts_voice_id && input) await addSpeech(v, alert);
const alert = toAlert(v, { user, input, emote, bits });
if (v.tts_voice_id && input && !v.video) await addSpeech(v, alert);
return alert;
}
@ -132,10 +136,11 @@ function test({ id, kind, key }) {
const input = v.tts_voice_id ? 'Hydrate check! Also, nice shot, I was totally not camping that container.'
: ['send_highlighted_message', 'message_effect'].includes(v.key) ? 'this is what a highlighted message looks like on stream!'
: v.kind === 'reward' ? 'test input' : null;
const alert = toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null }); // 25 = Kappa
if (v.tts_voice_id) addSpeech(v, alert).then(() => alerts.sendTestAlert(alert));
const alert = toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null,
bits: v.kind === 'custom_power_up' ? 50 : null }); // 25 = Kappa
if (v.tts_voice_id && !v.video) addSpeech(v, alert).then(() => alerts.sendTestAlert(alert));
else alerts.sendTestAlert(alert);
return true;
}
module.exports = { RARITY, AUTO_REWARDS, POWER_UPS, STYLE, pick, handle, test, rebuild, respeak };
module.exports = { RARITY, AUTO_REWARDS, POWER_UPS, STYLE, LEGACY, pick, handle, test, rebuild, respeak };

View file

@ -13,12 +13,16 @@ const PARTS = ['chat', 'alerts', 'poll', 'hypebar', 'raid']; // 'nowplaying' i
// ?parts=chat,raid only those parts
// ?parts=nochat everything except chat (no<part>, several allowed: nochat,noraid)
// no ?parts / nothing valid: everything
// ?parts=video full-screen video redeems + their notification box (public/alerts/video.js).
// Opt-in only (never part of "everything"), so it lives in its own OBS source.
const OPT_IN = ['video'];
function partsFrom(q) {
if (!q) return PARTS;
const tokens = String(q).split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
const optIn = tokens.filter(t => OPT_IN.includes(t));
const excluded = tokens.filter(t => t.startsWith('no') && PARTS.includes(t.slice(2))).map(t => t.slice(2));
if (excluded.length) return PARTS.filter(p => !excluded.includes(p));
const asked = tokens.filter(p => PARTS.includes(p));
if (excluded.length) return [...PARTS.filter(p => !excluded.includes(p)), ...optIn];
const asked = tokens.filter(p => PARTS.includes(p) || OPT_IN.includes(p));
return asked.length ? asked : PARTS;
}

View file

@ -20,6 +20,31 @@ function soundOptions() {
return [...lib, ...uploads];
}
// videos for 'Video' variations: files in public/alerts/videos + videos uploaded on the Media page
function videoOptions() {
const lib = listDir('alerts/videos', /\.(webm|mp4|mov)$/i).map(f => ({ url: `/alerts/videos/${f}`, label: f }));
const uploads = db.getAllMedia().filter(m => m.media_type === 'video')
.map(m => ({ url: `/media/${m.filename}`, label: `${m.original_name} (uploaded)` }));
return [...lib, ...uploads];
}
// live list of the channel's Custom Power-ups (bits); null when Twitch is not reachable
let loggedPowerUps = false;
async function twitchPowerUps() {
const u = twitch.getUser();
if (!u) return null;
try {
const res = await twitch.helix(`/bits/custom_power_ups?broadcaster_id=${u.twitch_id}`);
if (!res.ok) { console.warn(`[redeems] custom power-ups: ${res.status} ${await res.text()}`); return null; }
const data = (await res.json()).data || [];
if (!loggedPowerUps) { loggedPowerUps = true; console.log(`[redeems] custom power-ups (first load): ${JSON.stringify(data).slice(0, 1500)}`); }
return data.map(p => ({
kind: 'custom_power_up', key: p.id, title: p.title, bits: p.bits ?? p.cost ?? null,
live: p.is_enabled ?? p.enabled ?? true, image: p.image?.url_1x || p.default_image?.url_1x || null,
}));
} catch (e) { console.warn('[redeems] custom power-ups:', e.message); return null; }
}
// live list of the channel's custom rewards (title, cost, icon); null when Twitch is not reachable
async function twitchRewards() {
const u = twitch.getUser();
@ -51,8 +76,17 @@ router.get('/', async (req, res) => {
rewards.push({ kind: 'reward', key: v.key, title: v.title, cost: null, missing: !!fromTwitch });
}
}
const fromTwitchPU = await twitchPowerUps();
const powerUps = fromTwitchPU ? [...fromTwitchPU] : [];
for (const v of variations) {
if (v.kind === 'custom_power_up' && !powerUps.some(p => p.key === v.key)) {
powerUps.push({ kind: 'custom_power_up', key: v.key, title: v.title, bits: null, missing: !!fromTwitchPU });
}
}
const uniq = (list) => list.filter((r, i) => list.findIndex(x => x.key === r.key) === i);
const groups = [
{ name: 'Custom Power-ups (bits)', id: 'custom-power-ups', items: uniq(powerUps).sort((a, b) => (a.bits ?? 1e9) - (b.bits ?? 1e9)),
empty: fromTwitchPU ? 'No Custom Power-ups yet: create them on Twitch (Creator Dashboard → Viewer Rewards → Power-ups).' : 'Could not load your Custom Power-ups from Twitch right now.' },
{ 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 })) },
@ -62,6 +96,7 @@ router.get('/', async (req, res) => {
res.render('redeems', {
groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY,
sounds: soundOptions(),
videos: videoOptions(),
ttsVoices: db.getAllTtsVoices(),
stickers: [
...listDir('alerts/stickers', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/stickers/${f}`, label: f.replace(/\.\w+$/, '') })),
@ -74,28 +109,50 @@ const back = (res, v) => res.redirect(`/redeems#t-${encodeURIComponent(`${v.kind
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');
if (!['reward', 'auto_reward', 'power_up', 'custom_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);
});
// one variation's fields from the editor. display: cassette | sound (sound only) | video
function cleanVariation(v, b) {
const vol = parseFloat(b.volume);
const display = ['cassette', 'sound', 'video'].includes(b.display) ? b.display : (v.video ? 'video' : v.polaroid ? 'cassette' : 'sound');
const videos = new Set(videoOptions().map(o => o.url));
const video = display === 'video' && videos.has(b.video) ? b.video : '';
const on = x => x === true || x === 'on' || x === 1 || x === '1';
return {
name: String(b.name || '').trim().slice(0, 80) || v.name,
rarity: redeems.RARITY[b.rarity] ? b.rarity : v.rarity,
sound: String(b.sound || ''),
volume: isNaN(vol) ? v.volume : Math.max(0, Math.min(1, vol)),
polaroid: display === 'cassette' ? 1 : 0,
video,
caption: String(b.caption || '').trim().slice(0, 120) || 'redeemed it! ♡',
art: String(b.art || ''),
enabled: on(b.enabled) ? 1 : 0,
tts_voice_id: db.getTtsVoice(parseInt(b.tts_voice_id, 10)) ? parseInt(b.tts_voice_id, 10) : null,
};
}
// Save all: { variations: [{ id, ...fields }] } from the editor (one Save button / Ctrl+S)
router.post('/save', express.json({ limit: '1mb' }), (req, res) => {
const list = Array.isArray(req.body?.variations) ? req.body.variations : [];
let saved = 0;
for (const b of list) {
const v = db.getVariation(parseInt(b.id, 10));
if (!v) continue;
db.updateVariation(v.id, cleanVariation(v, b));
saved++;
}
res.json({ ok: true, saved });
});
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,
tts_voice_id: db.getTtsVoice(parseInt(b.tts_voice_id, 10)) ? parseInt(b.tts_voice_id, 10) : null,
});
db.updateVariation(v.id, cleanVariation(v, req.body));
back(res, v);
});