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

35
public/alerts/video.css Normal file
View file

@ -0,0 +1,35 @@
/* Video redeems (?parts=video, see video.js): full-screen video + a camcorder notification box,
the HUDFX box's look in yellow, in the alert corner (85,110, 440px wide on 1920x1080; video.js zooms the box
to the page width, so a 2560x1440 source looks the same, only sharper). */
@import url('https://fonts.googleapis.com/css2?family=VT323&display=swap');
#vfx-video { position:fixed; inset:0; width:100vw; height:100vh; object-fit:contain; background:transparent;
visibility:hidden; pointer-events:none; z-index:40; }
#vfx-box {
--yellow:#eeb434; --pale:#ffe7a3; --screen:#241e12;
position:fixed; left:85px; top:110px; width:440px; box-sizing:border-box; z-index:41; visibility:hidden;
padding:46px 22px 26px; border:5px solid var(--yellow); border-radius:12px;
box-shadow:0 0 0 3px #15110a, 0 0 22px rgba(238,180,52,.55), 0 14px 26px rgba(0,0,0,.5);
background:
linear-gradient(#fff,#fff) 12px 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) 12px 12px / 4px 26px no-repeat,
linear-gradient(#fff,#fff) right 12px top 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) right 12px top 12px / 4px 26px no-repeat,
linear-gradient(#fff,#fff) left 12px bottom 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) left 12px bottom 12px / 4px 26px no-repeat,
linear-gradient(#fff,#fff) right 12px bottom 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) right 12px bottom 12px / 4px 26px no-repeat,
repeating-linear-gradient(0deg, rgba(255,255,255,.045) 0 2px, transparent 2px 4px),
radial-gradient(ellipse at 50% 45%, #43361a 0%, var(--screen) 70%) #241e12;
font-family:'VT323', monospace; color:#fff; text-align:center;
}
#vfx-box .rec { position:absolute; left:24px; top:16px; font-size:26px; color:#ff3b4e; text-shadow:0 0 6px rgba(255,59,78,.7);
animation:vfx-blink 1s steps(1) infinite; }
#vfx-box .tc { position:absolute; right:24px; top:16px; font-size:24px; opacity:.85; }
#vfx-box .title { font-size:36px; line-height:1; text-transform:uppercase; overflow-wrap:anywhere;
text-shadow:2px 0 rgba(255,59,120,.75), -2px 0 rgba(80,220,255,.75); }
#vfx-box .who { font-size:32px; line-height:1; margin-top:10px; color:var(--pale); text-transform:uppercase; overflow-wrap:anywhere;
text-shadow:2px 0 rgba(255,59,120,.6), -2px 0 rgba(80,220,255,.6); }
#vfx-box .amt { display:inline-block; margin-top:16px; padding:2px 16px; background:var(--yellow); color:#241e12; font-size:28px;
border-radius:4px; text-transform:uppercase; box-shadow:0 0 12px rgba(238,180,52,.7); }
#vfx-box .amt:empty { display:none; }
#vfx-box .brand { position:absolute; right:46px; bottom:14px; font:900 13px/1 'Nunito', sans-serif; letter-spacing:1.5px;
color:var(--yellow); opacity:.8; }
@keyframes vfx-blink { 0% { opacity:1; } 50% { opacity:0; } }

75
public/alerts/video.js Normal file
View file

@ -0,0 +1,75 @@
/*
Video redeems, for the ?parts=video overlay (an OBS source of its own, e.g. instead of HUDFX).
Any source size works; 2560x1440 like HUDFX gives sharper video. The box is laid out for 1920x1080 and
zoomed to the page width, so it always lands in the alert corner.
Redeem variations with a video (style 'video', see src/redeems.js) play here full-screen, one at a time,
with a camcorder notification box (video.css) while the video runs.
VideoFX.play(alert) queue it
VideoFX.playTest(alert) test: replaces a playing/queued test at once
VideoFX.skip() stop the current one, carry on with the queue
alert: { video, volume, user, reward, variation, bits, test }
*/
(() => {
const queue = [];
let cur = null, vid = null, box = null, tcTimer = null;
function els() {
if (vid) return;
vid = document.createElement('video'); vid.id = 'vfx-video'; vid.playsInline = true; document.body.appendChild(vid);
box = document.createElement('div'); box.id = 'vfx-box';
box.innerHTML = '<div class="rec">● REC</div><div class="tc"></div><div class="title"></div><div class="who"></div><div class="amt"></div><div class="brand">POWER-UP</div>';
document.body.appendChild(box);
fit(); addEventListener('resize', fit);
}
function fit() { if (box) box.style.zoom = innerWidth / 1920; }
const fmt = s => { s = Math.max(0, Math.floor(s)); return `▶ ${Math.floor(s / 3600)}:${String(Math.floor(s / 60) % 60).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`; };
function show(a) {
els();
const name = a.variation && a.variation !== a.reward ? a.variation : (a.reward || 'Power-up');
box.querySelector('.title').textContent = `Triggered ${name}`;
box.querySelector('.who').textContent = a.user || '';
box.querySelector('.amt').textContent = a.bits ? `◆ ${a.bits} bits ◆` : '';
box.querySelector('.tc').textContent = fmt(0);
box.style.visibility = 'visible';
box.animate([{ opacity: 0, transform: 'translateY(-12px)' }, { opacity: 1, transform: 'none' }], { duration: 400, easing: 'ease-out', fill: 'both' });
clearInterval(tcTimer); tcTimer = setInterval(() => { box.querySelector('.tc').textContent = fmt(vid.currentTime); }, 250);
}
function hideBox() {
clearInterval(tcTimer);
if (!box || box.style.visibility !== 'visible') return;
box.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 500, fill: 'both' }).finished
.then(() => { if (!cur) box.style.visibility = 'hidden'; }).catch(() => {});
}
function finish(a) {
if (cur !== a) return;
clearTimeout(a._guard);
vid.pause(); vid.removeAttribute('src'); vid.load(); vid.style.visibility = 'hidden';
cur = null;
hideBox();
setTimeout(next, 600);
}
function next() {
if (cur || !queue.length) return;
const a = cur = queue.shift();
show(a);
vid.src = a.video; vid.volume = Math.max(0, Math.min(1, a.volume ?? 0.8)); vid.currentTime = 0;
vid.style.visibility = 'visible';
vid.onended = () => finish(a);
vid.onerror = () => { console.warn('[video] could not play', a.video); setTimeout(() => finish(a), 2500); };
vid.play().catch(e => { console.warn('[video] play:', e.message); setTimeout(() => finish(a), 2500); });
a._guard = setTimeout(() => finish(a), 120000); // never block the queue on a broken/endless file
}
function play(a) { if (!a?.video) return; queue.push(a); next(); }
function playTest(a) {
if (!a?.video) return;
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1);
if (cur?.test) { queue.unshift({ ...a, test: true }); finish(cur); }
else play({ ...a, test: true });
}
function skip() { if (cur) finish(cur); }
window.VideoFX = { play, playTest, skip };
})();

View file

View file

@ -12,11 +12,11 @@ const RARITY = { common: 'Common', uncommon: 'Uncommon', rare: 'Rare', ultra_rar
const LABEL = { const LABEL = {
follow: 'Follow', sub: 'Sub', gift_sub: 'Gift sub', bits: 'Bits', watch_streak: 'Watch streak', 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', 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', 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; } } 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 === 'channel_points') return raw?.reward?.title || null;
if (type === 'auto_reward') return AUTO_REWARDS[raw?.reward?.type] || raw?.reward?.type || 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 === '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; return null;
} }
@ -43,10 +44,12 @@ function describe(log) {
if (raw?.reward?.cost) out.tags.push(`${raw.reward.cost} points`); 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?.reward?.channel_points) out.tags.push(`${raw.reward.channel_points} points`);
else if (raw?.bits) out.tags.push(`${raw.bits} bits`); 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) {
if (a.variation && a.variation !== a.reward) out.tags.push(`played: ${a.variation}`); 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.rarity && a.rarity !== 'common') out.tags.push(RARITY[a.rarity] || a.rarity);
if (a.tts) out.tags.push('TTS'); 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; out.message = a?.input || raw?.user_input || raw?.message?.text || null;
} else if (a) { } else if (a) {
@ -111,7 +114,8 @@ async function replayMessage(log) {
const key = log.event_detail; const key = log.event_detail;
const input = raw.user_input || raw.message?.text || null; const input = raw.user_input || raw.message?.text || null;
const emote = raw.reward?.emote?.id || raw.power_up?.emote?.id || 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; return alert ? { type: 'alert', alert } : null;
} }
if (log.event_type === 'raid_out') { if (log.event_type === 'raid_out') {

View file

@ -98,7 +98,7 @@ function createSchema() {
CREATE TABLE IF NOT EXISTS reward_variations ( CREATE TABLE IF NOT EXISTS reward_variations (
id INTEGER PRIMARY KEY AUTOINCREMENT, 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 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) title TEXT NOT NULL, -- trigger name shown in the UI (last known)
name TEXT NOT NULL, -- variation name, shown on the polaroid name TEXT NOT NULL, -- variation name, shown on the polaroid
@ -141,7 +141,8 @@ function migrate() {
addColumn('activity_log', 'replay_json', 'TEXT'); addColumn('activity_log', 'replay_json', 'TEXT');
addColumn('settings', 'hudfx_overlay_url', "TEXT DEFAULT ''"); 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_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 // 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 // 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() { function getAllVariations() {
return db.prepare('SELECT * FROM reward_variations ORDER BY kind, title, id').all(); 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 } }, { 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 // cheers AND bits Power-ups (message effect, celebration, gigantify); replaces channel.cheer
{ type: 'channel.bits.use', version: '1', condition: { broadcaster_user_id: b } }, { 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 // 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.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 } }, { 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); if (alert) alerts.send(alert, event);
break; 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': case 'channel.raid':
if (event.from_broadcaster_user_id === broadcasterId) alerts.raidHappened(event).catch(e => console.error('[alerts] raid out:', e.message)); if (event.from_broadcaster_user_id === broadcasterId) alerts.raidHappened(event).catch(e => console.error('[alerts] raid out:', e.message));
break; break;

View file

@ -31,6 +31,8 @@ const POWER_UPS = {
gigantify_an_emote: 'Power-up: Gigantify an Emote', 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) // how a trigger is drawn on the overlay (everything else: cassette tape)
const STYLE = { const STYLE = {
'power_up:gigantify_an_emote': 'emote', // the viewer's emote, giant 'power_up:gigantify_an_emote': 'emote', // the viewer's emote, giant
@ -49,9 +51,10 @@ function pick(variations) {
return pool[pool.length - 1] || null; 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 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]; const line = spoken ? LINE.tts : LINE[style];
return { return {
type: 'redeem', kind: v.kind, key: v.key, style, vid: v.id, // vid: re-speak on replay if the mp3 was pruned 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, 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 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), 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 // 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. // 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); if (title) db.renameTrigger(kind, key, title);
const v = pick(db.getVariationsFor(kind, key)); const v = pick(db.getVariationsFor(kind, key));
if (!v) { if (!v) {
@ -101,19 +105,19 @@ function handle(kind, key, title, { user, input, emote }, raw) {
dispatch.dispatchEvent(LEGACY[kind], key, user, raw); dispatch.dispatchEvent(LEGACY[kind], key, user, raw);
return null; return null;
} }
const alert = toAlert(v, { user, input, emote }); const alert = toAlert(v, { user, input, emote, bits });
if (v.tts_voice_id && input) addSpeech(v, alert).then(() => alerts.send(alert, raw)); // speech first, then the alert 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); else alerts.send(alert, raw);
return alert; return alert;
} }
// Dashboard Replay of an old activity row that has no stored alert: a fresh pick for the trigger, // 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. // 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)); const v = pick(db.getVariationsFor(kind, key));
if (!v) return null; if (!v) return null;
const alert = toAlert(v, { user, input, emote }); const alert = toAlert(v, { user, input, emote, bits });
if (v.tts_voice_id && input) await addSpeech(v, alert); if (v.tts_voice_id && input && !v.video) await addSpeech(v, alert);
return 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.' 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!' : ['send_highlighted_message', 'message_effect'].includes(v.key) ? 'this is what a highlighted message looks like on stream!'
: v.kind === 'reward' ? 'test input' : null; : v.kind === 'reward' ? 'test input' : null;
const alert = toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null }); // 25 = Kappa const alert = toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null,
if (v.tts_voice_id) addSpeech(v, alert).then(() => alerts.sendTestAlert(alert)); 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); else alerts.sendTestAlert(alert);
return true; 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=chat,raid only those parts
// ?parts=nochat everything except chat (no<part>, several allowed: nochat,noraid) // ?parts=nochat everything except chat (no<part>, several allowed: nochat,noraid)
// no ?parts / nothing valid: everything // 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) { function partsFrom(q) {
if (!q) return PARTS; if (!q) return PARTS;
const tokens = String(q).split(',').map(s => s.trim().toLowerCase()).filter(Boolean); 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)); 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)); if (excluded.length) return [...PARTS.filter(p => !excluded.includes(p)), ...optIn];
const asked = tokens.filter(p => PARTS.includes(p)); const asked = tokens.filter(p => PARTS.includes(p) || OPT_IN.includes(p));
return asked.length ? asked : PARTS; return asked.length ? asked : PARTS;
} }

View file

@ -20,6 +20,31 @@ function soundOptions() {
return [...lib, ...uploads]; 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 // live list of the channel's custom rewards (title, cost, icon); null when Twitch is not reachable
async function twitchRewards() { async function twitchRewards() {
const u = twitch.getUser(); 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 }); 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 uniq = (list) => list.filter((r, i) => list.findIndex(x => x.key === r.key) === i);
const groups = [ 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: '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: '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 })) }, { 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', { res.render('redeems', {
groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY, groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY,
sounds: soundOptions(), sounds: soundOptions(),
videos: videoOptions(),
ttsVoices: db.getAllTtsVoices(), ttsVoices: db.getAllTtsVoices(),
stickers: [ stickers: [
...listDir('alerts/stickers', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/stickers/${f}`, label: f.replace(/\.\w+$/, '') })), ...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) => { router.post('/variation', (req, res) => {
const { kind, key, title } = req.body; 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 n = db.getVariationsFor(kind, key).length;
const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key) }); const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key) });
back(res, v); 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) => { router.post('/variation/:id', (req, res) => {
const v = db.getVariation(req.params.id); const v = db.getVariation(req.params.id);
if (!v) return res.status(404).send('not found'); if (!v) return res.status(404).send('not found');
const b = req.body; db.updateVariation(v.id, cleanVariation(v, 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,
});
back(res, v); back(res, v);
}); });

View file

@ -14,6 +14,7 @@
<% if (has('poll')) { %><link rel="stylesheet" href="/alerts/poll.css?v=<%= boot %>"><% } %> <% if (has('poll')) { %><link rel="stylesheet" href="/alerts/poll.css?v=<%= boot %>"><% } %>
<% if (has('hypebar')) { %><link rel="stylesheet" href="/alerts/hypebar.css?v=<%= boot %>"><% } %> <% if (has('hypebar')) { %><link rel="stylesheet" href="/alerts/hypebar.css?v=<%= boot %>"><% } %>
<% if (has('raid')) { %><link rel="stylesheet" href="/alerts/raidcard.css?v=<%= boot %>"><% } %> <% if (has('raid')) { %><link rel="stylesheet" href="/alerts/raidcard.css?v=<%= boot %>"><% } %>
<% if (has('video')) { %><link rel="stylesheet" href="/alerts/video.css?v=<%= boot %>"><% } %>
<%# Now playing (Feishin) is switched off for now. To bring it back: add 'nowplaying' to PARTS in <%# Now playing (Feishin) is switched off for now. To bring it back: add 'nowplaying' to PARTS in
src/routers/overlay.js, uncomment the /nowplaying route in src/app.js and restore the NOWPLAYING lines here: src/routers/overlay.js, uncomment the /nowplaying route in src/app.js and restore the NOWPLAYING lines here:
<link rel="stylesheet" href="/alerts/nowplaying.css"> (inside an if (has('nowplaying'))) <link rel="stylesheet" href="/alerts/nowplaying.css"> (inside an if (has('nowplaying')))
@ -87,6 +88,7 @@
<% if (has('poll')) { %><script src="/alerts/poll.js?v=<%= boot %>"></script><% } %> <% if (has('poll')) { %><script src="/alerts/poll.js?v=<%= boot %>"></script><% } %>
<% if (has('hypebar')) { %><script src="/alerts/hypebar.js?v=<%= boot %>"></script><% } %> <% if (has('hypebar')) { %><script src="/alerts/hypebar.js?v=<%= boot %>"></script><% } %>
<% if (has('raid')) { %><script src="/alerts/raidcard.js?v=<%= boot %>"></script><% } %> <% if (has('raid')) { %><script src="/alerts/raidcard.js?v=<%= boot %>"></script><% } %>
<% if (has('video')) { %><script src="/alerts/video.js?v=<%= boot %>"></script><% } %>
<script> <script>
const S = <%- JSON.stringify(settings) %>; const S = <%- JSON.stringify(settings) %>;
window.S = S; // chat.js reads message_timeout / max_messages from here (settings_update keeps it current) window.S = S; // chat.js reads message_timeout / max_messages from here (settings_update keeps it current)
@ -173,7 +175,12 @@
// NOWPLAYING: if (msg.type === 'nowplaying') { if (PARTS.has('nowplaying')) NowPlaying.update(msg.np); return; } // NOWPLAYING: if (msg.type === 'nowplaying') { if (PARTS.has('nowplaying')) NowPlaying.update(msg.np); return; }
if (msg.type === 'nowplaying') return; if (msg.type === 'nowplaying') return;
if (msg.type === 'raid_card') { if (PARTS.has('raid')) RaidCard.update(msg.phase, msg.raid); return; } if (msg.type === 'raid_card') { if (PARTS.has('raid')) RaidCard.update(msg.phase, msg.raid); return; }
if (msg.type === 'alert_skip') { if (PARTS.has('alerts')) PolaroidAlerts.skip(); return; } if (msg.type === 'alert_skip') { if (PARTS.has('alerts')) PolaroidAlerts.skip(); if (PARTS.has('video')) VideoFX.skip(); return; }
// video redeems only play on the ?parts=video source
if (msg.type === 'alert' && msg.alert.style === 'video') {
if (PARTS.has('video')) msg.alert.test === true ? VideoFX.playTest(msg.alert) : VideoFX.play(msg.alert);
return;
}
if (!PARTS.has('alerts')) return; // alerts and legacy actions below if (!PARTS.has('alerts')) return; // alerts and legacy actions below
if (msg.type === 'alert') { if (msg.type === 'alert') {
// test buttons: replace other test alerts at once, but never cut off a real alert // test buttons: replace other test alerts at once, but never cut off a real alert

View file

@ -1,148 +1,329 @@
<style> <style>
.trig { border:1px solid var(--pico-muted-border-color); border-radius:10px; padding:.4rem .9rem; margin-bottom:.6rem; } /* save bar */
.savebar { position:sticky; top:0; z-index:20; display:flex; align-items:center; gap:.8rem; flex-wrap:wrap;
padding:.55rem .9rem; margin:0 0 1rem; border-radius:10px; background:var(--pico-card-background-color);
border:1px solid var(--pico-muted-border-color); box-shadow:0 4px 14px rgba(0,0,0,.25); }
.savebar .state { font-size:.9rem; }
.savebar .state.dirty { color:#e6b800; font-weight:600; }
.savebar .state.ok { color:#3fb950; }
.savebar .state.err { color:#f88; }
.savebar button { margin:0; width:auto; padding:.35rem 1.1rem; }
.savebar kbd { font-size:.7rem; }
.draftbar { display:flex; gap:.6rem; align-items:center; flex-wrap:wrap; padding:.5rem .9rem; margin:-.4rem 0 1rem;
border:1px dashed #e6b800; border-radius:10px; font-size:.9rem; }
.draftbar button { margin:0; width:auto; padding:.25rem .8rem; font-size:.85rem; }
/* triggers */
.group-h { margin:1.6rem 0 .6rem; }
.trig { border:1px solid var(--pico-muted-border-color); border-radius:12px; padding:.45rem .9rem; margin-bottom:.6rem; }
.trig[open] { padding-bottom:.8rem; }
.trig > summary { display:flex; align-items:center; gap:.6rem; flex-wrap:wrap; cursor:pointer; } .trig > summary { display:flex; align-items:center; gap:.6rem; flex-wrap:wrap; cursor:pointer; }
.trig > summary img { width:22px; height:22px; } .trig > summary img { width:24px; height:24px; border-radius:4px; }
.trig .meta { color:var(--pico-muted-color); font-size:.85rem; } .meta { color:var(--pico-muted-color); font-size:.85rem; }
.var { display:grid; grid-template-columns: 1.4fr 1fr 2fr .8fr; gap:.4rem .6rem; align-items:end; .pill { font-size:.75rem; padding:.05rem .5rem; border-radius:99px; border:1px solid var(--pico-muted-border-color); color:var(--pico-muted-color); }
padding:.6rem 0; border-top:1px dashed var(--pico-muted-border-color); } .pill.bits { border-color:#a970ff; color:#c9a8ff; }
.var label { font-size:.75rem; margin:0; color:var(--pico-muted-color); } .pill.pts { border-color:#3fb950; color:#7ee08f; }
.var input, .var select { margin:0; padding:.3rem .5rem; font-size:.85rem; height:auto; }
.var input[type=checkbox] { padding:0; }
.var .row2 { grid-column: 1 / -1; display:flex; gap:.6rem; flex-wrap:wrap; align-items:center; }
.var .row2 .grow { flex:1; min-width:220px; }
.var button { margin:0; padding:.25rem .7rem; font-size:.8rem; width:auto; }
.var.off { opacity:.55; }
.chance { font-size:.8rem; color:var(--pico-muted-color); }
.btn-sm { margin:0; padding:.25rem .7rem; font-size:.8rem; width:auto; } .btn-sm { margin:0; padding:.25rem .7rem; font-size:.8rem; width:auto; }
.danger { color:#f88; border-color:#f88; } .danger { color:#f88; border-color:#f88; }
.warn { color:#e6b800; } .warn { color:#e6b800; }
@media (max-width: 800px) { .var { grid-template-columns: 1fr 1fr; } }
/* variation cards */
.vcard { border:1px solid var(--pico-muted-border-color); border-left:4px solid var(--pico-muted-border-color);
border-radius:10px; padding:.6rem .8rem; margin:.6rem 0; }
.vcard.dirty { border-left-color:#e6b800; }
.vcard.off { opacity:.55; }
.vrow { display:flex; align-items:center; gap:.6rem; flex-wrap:wrap; }
.vrow + .vrow { margin-top:.55rem; }
.vcard input, .vcard select { margin:0; padding:.3rem .5rem; font-size:.85rem; height:auto; }
.vcard input[type=checkbox] { margin:0; }
.vcard input[type=range] { padding:0; width:110px; }
.vname { flex:1 1 180px; font-weight:600; }
.chance { font-size:.8rem; color:var(--pico-muted-color); min-width:5.5em; }
.field { display:flex; align-items:center; gap:.4rem; }
.field > span:first-child { font-size:.75rem; color:var(--pico-muted-color); }
.grow { flex:1 1 220px; }
.grow > input, .grow > select { width:100%; }
.seg { display:inline-flex; border:1px solid var(--pico-muted-border-color); border-radius:8px; overflow:hidden; }
.seg label { margin:0; padding:.25rem .8rem; font-size:.8rem; cursor:pointer; user-select:none; }
.seg input { display:none; }
.seg label:has(input:checked) { background:var(--pico-primary-background); color:var(--pico-primary-inverse); }
.thumb { width:34px; height:34px; object-fit:contain; }
.vol-out { font-size:.75rem; color:var(--pico-muted-color); width:2.6em; }
.preview { margin-top:.5rem; max-width:320px; border-radius:8px; background:#0006; }
[data-show] { display:none !important; }
.vcard[data-display="cassette"] [data-show~="cassette"],
.vcard[data-display="sound"] [data-show~="sound"],
.vcard[data-display="video"] [data-show~="video"] { display:flex !important; }
</style> </style>
<h2>Redeems</h2> <h2>Redeems</h2>
<p class="meta">
Each redeem plays <strong>one</strong> of its enabled variations, picked at random by rarity <div class="savebar">
(<% for (const [k, r] of Object.entries(rarity)) { %><%= r.label %> <%= r.weight %><% if (k !== 'ultra_rare') { %> · <% } %><% } %>, relative weights). <button type="button" id="save-all" title="Save every change on this page (Ctrl+S)">Save</button>
Sounds: built-in library, or upload more on the <a href="/media">Media</a> page. <span class="state ok" id="save-state">All saved</span>
<% if (!twitchOk) { %><br><span class="warn">Could not load your rewards from Twitch right now, so only rewards that already have variations are listed.</span><% } %> <span class="meta" style="margin-left:auto;" title="Each redeem plays ONE of its enabled variations, picked at random by rarity (relative weights). Sounds: built-in library or uploads on the Media page. Videos: uploads on the Media page (transparent WebM looks best); they play on the overlay URL with ?parts=video.">
</p> How it works ⓘ · <kbd>Ctrl</kbd>+<kbd>S</kbd> saves
</span>
</div>
<div class="draftbar" id="draftbar" hidden>
<span>Unsaved changes from <strong id="draft-when"></strong> were kept in this browser.</span>
<button type="button" id="draft-restore">Restore them</button>
<button type="button" class="outline" id="draft-discard">Discard</button>
</div>
<% if (!twitchOk) { %><p class="warn">Could not load your channel point rewards from Twitch right now, so only rewards that already have variations are listed.</p><% } %>
<% for (const g of groups) { %> <% for (const g of groups) { %>
<h3 style="margin-top:1.5rem;"><%= g.name %></h3> <h3 class="group-h" <%= g.id ? `id=${g.id}` : '' %>><%= g.name %></h3>
<% if (!g.items.length && g.empty) { %><p class="meta"><%= g.empty %></p><% } %>
<% for (const t of g.items) { <% for (const t of g.items) {
const on = t.variations.filter(v => v.enabled); 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}`; %> const anchor = `t-${t.kind}-${t.key}`; %>
<details class="trig" id="<%= anchor %>"> <details class="trig" id="<%= anchor %>" data-trigger>
<summary> <summary>
<% if (t.image) { %><img src="<%= t.image %>" alt=""><% } %> <% if (t.image) { %><img src="<%= t.image %>" alt=""><% } %>
<strong><%= t.title %></strong> <strong><%= t.title %></strong>
<% if (t.cost != null) { %><span class="meta"><%= t.cost %> pts</span><% } %> <% if (t.cost != null) { %><span class="pill pts"><%= t.cost %> pts</span><% } %>
<% if (t.bits != null) { %><span class="pill bits"><%= t.bits %> bits</span><% } %>
<% if (t.missing) { %><span class="badge badge-red">not on Twitch anymore</span><% } %> <% if (t.missing) { %><span class="badge badge-red">not on Twitch anymore</span><% } %>
<% if (t.live === false) { %><span class="badge badge-grey">paused on Twitch</span><% } %> <% if (t.live === false) { %><span class="badge badge-grey">paused on Twitch</span><% } %>
<% if (t.variations.some(v => v.tts_voice_id)) { %><span class="badge badge-green" title="At least one variation reads the viewer's text aloud">TTS</span><% } %> <% if (t.variations.some(v => v.video)) { %><span class="pill" title="At least one variation plays a full-screen video (?parts=video overlay)">video</span><% } %>
<span class="meta"> <% if (t.variations.some(v => v.tts_voice_id)) { %><span class="pill" title="At least one variation reads the viewer's text aloud">TTS</span><% } %>
<%= t.variations.length ? `${on.length}/${t.variations.length} variation${t.variations.length === 1 ? '' : 's'} on` : 'no alert' %> <span class="meta" data-count><%= t.variations.length ? `${on.length}/${t.variations.length} on` : 'no alert yet' %></span>
</span>
<% if (on.length) { %> <% if (on.length) { %>
<button type="button" class="outline btn-sm" data-test-trigger data-kind="<%= t.kind %>" data-key="<%= t.key %>">Test random</button> <button type="button" class="outline btn-sm" data-test-trigger data-kind="<%= t.kind %>" data-key="<%= t.key %>" title="Play a random enabled variation on the overlay (saves first)">Test random</button>
<% } %> <% } %>
</summary> </summary>
<% for (const v of t.variations) { %> <% for (const v of t.variations) {
<form method="POST" action="/redeems/variation/<%= v.id %>" class="var<%= v.enabled ? '' : ' off' %>"> const display = v.video ? 'video' : v.polaroid ? 'cassette' : 'sound'; %>
<div><label>Name (cassette label)</label><input name="name" value="<%= v.name %>" required></div> <div class="vcard<%= v.enabled ? '' : ' off' %>" data-id="<%= v.id %>" data-display="<%= display %>">
<div><label>Rarity</label> <div class="vrow">
<select name="rarity"> <input type="checkbox" role="switch" data-f="enabled" <%= v.enabled ? 'checked' : '' %> title="On: this variation can play">
<input class="vname" data-f="name" value="<%= v.name %>" title="Variation name (shown on the cassette / video box)">
<select data-f="rarity" style="width:auto;" title="Rarity: how often it is picked compared to the other enabled variations">
<% for (const [k, r] of Object.entries(rarity)) { %><option value="<%= k %>" <%= v.rarity === k ? 'selected' : '' %>><%= r.label %></option><% } %> <% for (const [k, r] of Object.entries(rarity)) { %><option value="<%= k %>" <%= v.rarity === k ? 'selected' : '' %>><%= r.label %></option><% } %>
</select> </select>
<% if (v.enabled && total) { %><span class="chance"><%= Math.round(100 * (rarity[v.rarity]?.weight || 1) / total) %>% chance</span><% } %> <span class="chance" data-chance></span>
<button type="button" class="outline btn-sm" data-test title="Show it on the overlay (saves first)">Test</button>
<button type="button" class="outline btn-sm danger" data-del title="Delete this variation">Delete</button>
<button type="button" class="btn-sm danger" data-del-confirm hidden>Really delete</button>
</div> </div>
<div><label>Sound</label>
<select name="sound" data-sound> <div class="vrow">
<span class="seg" title="Cassette: tape alert with sound. Sound only: just the sound. Video: full-screen video on the ?parts=video overlay">
<% for (const [val, lbl] of [['cassette', 'Cassette'], ['sound', 'Sound only'], ['video', 'Video']]) { %>
<label><input type="radio" name="display-<%= v.id %>" data-f="display" value="<%= val %>" <%= display === val ? 'checked' : '' %>><%= lbl %></label>
<% } %>
</span>
<span class="field" title="Volume of the sound / video">
<input type="range" min="0" max="1" step="0.05" data-f="volume" value="<%= v.volume %>"><span class="vol-out" data-vol></span>
</span>
</div>
<div class="vrow" data-show="cassette sound">
<span class="field grow"><select data-f="sound" title="Sound that plays (TTS on: the voice replaces it)">
<option value="">— silent —</option> <option value="">— silent —</option>
<% for (const s of sounds) { %><option value="<%= s.url %>" <%= v.sound === s.url ? 'selected' : '' %>><%= s.label %></option><% } %> <% for (const s of sounds) { %><option value="<%= s.url %>" <%= v.sound === s.url ? 'selected' : '' %>><%= s.label %></option><% } %>
</select> </select></span>
<button type="button" class="outline btn-sm" data-play-sound title="Play the sound here in the browser">▶</button>
</div> </div>
<div><label>Volume</label><input type="number" name="volume" min="0" max="1" step="0.05" value="<%= v.volume %>"></div>
<div class="row2"> <div class="vrow" data-show="cassette">
<label><input type="checkbox" name="enabled" <%= v.enabled ? 'checked' : '' %>> on</label> <span class="field"><img class="thumb" data-thumb alt="">
<label title="Off = only the sound plays, no cassette on screen (still waits its turn in the queue)"><input type="checkbox" name="polaroid" <%= v.polaroid ? 'checked' : '' %>> show cassette</label> <select data-f="art" style="width:auto;" title="Sticker in the cassette's corner">
<span class="grow"><input name="caption" value="<%= v.caption %>" title="Text after the viewer's name on the paper strip. {reward} = reward name, {variation} = this variation's name. The viewer's typed message is added automatically."></span> <option value="">headset Streamer</option>
<select name="art" style="width:auto;" title="Sticker in the cassette's corner"> <% for (const st of stickers) { %><option value="<%= st.url %>" <%= v.art === st.url ? 'selected' : '' %>><%= st.label %></option><% } %>
<option value="">sticker: headset Streamer</option> </select></span>
<% for (const st of stickers) { %><option value="<%= st.url %>" <%= v.art === st.url ? 'selected' : '' %>>sticker: <%= st.label %></option><% } %> <span class="field grow"><input data-f="caption" value="<%= v.caption %>" title="Text after the viewer's name on the paper strip. {reward} = reward name, {variation} = this variation's name. The viewer's typed message is added automatically."></span>
</select> <select data-f="tts_voice_id" style="width:auto;" title="Read the viewer's typed text aloud (voice from the TTS page), shown as a big paper note. The voice replaces the sound. The reward needs 'Require Viewer to Enter Text' on Twitch.">
<select name="tts_voice_id" data-tts style="width:auto;" title="Read the viewer's typed text aloud with a voice from the TTS page, shown as a big paper note. The voice replaces the sound. The reward needs 'Require Viewer to Enter Text' on Twitch.">
<option value="">TTS: off</option> <option value="">TTS: off</option>
<% for (const tv of ttsVoices) { %><option value="<%= tv.id %>" <%= v.tts_voice_id === tv.id ? 'selected' : '' %>>TTS: <%= tv.name %></option><% } %> <% for (const tv of ttsVoices) { %><option value="<%= tv.id %>" <%= v.tts_voice_id === tv.id ? 'selected' : '' %>>TTS: <%= tv.name %></option><% } %>
</select> </select>
<button type="button" class="outline btn-sm" data-play title="Play the sound here in the browser">▶</button>
<button type="submit" class="btn-sm">Save</button>
<button type="button" class="outline btn-sm" data-test-var="<%= v.id %>" title="Show it on the overlay">Test</button>
<button type="button" class="outline btn-sm danger" data-del>Delete</button>
<button type="submit" class="btn-sm danger" data-del-confirm formaction="/redeems/variation/<%= v.id %>/delete" hidden>Really delete</button>
</div> </div>
</form>
<div class="vrow" data-show="video">
<span class="field grow"><select data-f="video" title="Video file: uploads on the Media page (transparent WebM looks best)">
<option value="">— pick a video —</option>
<% for (const o of videos) { %><option value="<%= o.url %>" <%= v.video === o.url ? 'selected' : '' %>><%= o.label %></option><% } %>
</select></span>
<button type="button" class="outline btn-sm" data-play-video title="Preview the video here">▶</button>
<% if (!videos.length) { %><a href="/media" class="meta">upload a video on Media</a><% } %>
</div>
<video class="preview" data-preview hidden controls playsinline></video>
</div>
<% } %> <% } %>
<form method="POST" action="/redeems/variation" style="margin:.5rem 0 .3rem;"> <form method="POST" action="/redeems/variation" data-add style="margin:.6rem 0 0;">
<input type="hidden" name="kind" value="<%= t.kind %>"> <input type="hidden" name="kind" value="<%= t.kind %>">
<input type="hidden" name="key" value="<%= t.key %>"> <input type="hidden" name="key" value="<%= t.key %>">
<input type="hidden" name="title" value="<%= t.title %>"> <input type="hidden" name="title" value="<%= t.title %>">
<button type="submit" class="outline btn-sm">+ Add variation</button> <button type="submit" class="outline btn-sm" title="Add a variation (saves your changes first)">+ Add variation</button>
</form> </form>
</details> </details>
<% } %> <% } %>
<% } %> <% } %>
<p><small id="redeem-status"></small></p>
<script> <script>
(() => { (() => {
const status = document.getElementById('redeem-status'); const RARITY = <%- JSON.stringify(rarity) %>;
const say = t => { status.textContent = t; }; const DRAFT_KEY = 'redeemsDraft', OPEN_KEY = 'redeemsOpen';
// open the trigger we just edited const stateEl = document.getElementById('save-state');
if (location.hash) { const d = document.getElementById(decodeURIComponent(location.hash.slice(1))); if (d) d.open = true; } const dirty = new Set();
const cards = () => [...document.querySelectorAll('.vcard')];
const card = id => document.querySelector(`.vcard[data-id="${id}"]`);
const store = { get(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } },
set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} },
del(k) { try { localStorage.removeItem(k); } catch {} } };
let player = null; function state(text, cls) { stateEl.textContent = text; stateEl.className = 'state ' + cls; }
document.querySelectorAll('[data-play]').forEach(b => b.addEventListener('click', () => { function refreshState() { dirty.size ? state(`${dirty.size} unsaved change${dirty.size === 1 ? '' : 's'}`, 'dirty') : state('All saved', 'ok'); }
const url = b.closest('form').querySelector('[data-sound]').value;
if (player) player.pause();
if (!url) return say('No sound selected');
player = new Audio(url);
player.volume = parseFloat(b.closest('form').querySelector('[name=volume]').value) || 0.8;
player.play().catch(e => say('Could not play: ' + e.message));
}));
const post = async (url, body) => { // read one card's values
try { function collect(c) {
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) }); const o = { id: c.dataset.id };
say(r.ok ? 'Sent to overlay (save first if you changed something)' : `Failed (${r.status})`); c.querySelectorAll('[data-f]').forEach(el => {
} catch (e) { say('Failed: ' + e.message); } const f = el.dataset.f;
}; if (el.type === 'radio') { if (el.checked) o[f] = el.value; }
document.querySelectorAll('[data-test-var]').forEach(b => b.addEventListener('click', () => post(`/redeems/variation/${b.dataset.testVar}/test`))); else if (el.type === 'checkbox') o[f] = el.checked;
document.querySelectorAll('[data-test-trigger]').forEach(b => b.addEventListener('click', e => { else o[f] = el.value;
e.preventDefault(); // inside <summary>: do not toggle
post('/redeems/trigger/test', { kind: b.dataset.kind, key: b.dataset.key });
}));
// TTS on = no sound: grey out the sound picker (the server ignores it too)
document.querySelectorAll('[data-tts]').forEach(sel => {
const form = sel.closest('form'), snd = form.querySelector('[data-sound]');
const sync = () => {
snd.disabled = !!sel.value;
snd.title = sel.value ? 'TTS is on: the voice replaces the sound' : '';
};
sel.addEventListener('change', sync); sync();
form.addEventListener('submit', () => { snd.disabled = false; }); // still submit it, so turning TTS off brings the sound back
}); });
return o;
}
function apply(c, o) {
c.querySelectorAll('[data-f]').forEach(el => {
const f = el.dataset.f; if (!(f in o)) return;
if (el.type === 'radio') el.checked = el.value === o[f];
else if (el.type === 'checkbox') el.checked = !!o[f];
else el.value = o[f];
});
sync(c);
}
// two-step delete, no browser dialog // card look: display mode, off, volume, sticker thumbnail; chances for the whole trigger
document.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => { function sync(c) {
const c = b.parentElement.querySelector('[data-del-confirm]'); const o = collect(c);
b.hidden = true; c.hidden = false; c.dataset.display = o.display;
setTimeout(() => { b.hidden = false; c.hidden = true; }, 4000); c.classList.toggle('off', !o.enabled);
})); c.querySelector('[data-vol]').textContent = Math.round(o.volume * 100) + '%';
})(); const art = c.querySelector('[data-f="art"]'), th = c.querySelector('[data-thumb]');
th.src = art.value || '/alerts/stickers/default-sticker.png'; // cassette.js DEFAULT_STICKER
const snd = c.querySelector('[data-f="sound"]');
snd.disabled = !!o.tts_voice_id && o.display === 'cassette';
chances(c.closest('[data-trigger]'));
}
function chances(t) {
const cs = [...t.querySelectorAll('.vcard')].map(c => [c, collect(c)]);
const total = cs.filter(([, o]) => o.enabled).reduce((s, [, o]) => s + (RARITY[o.rarity]?.weight || 1), 0);
for (const [c, o] of cs) c.querySelector('[data-chance]').textContent = o.enabled && total ? Math.round(100 * (RARITY[o.rarity]?.weight || 1) / total) + '% chance' : 'off';
const n = cs.filter(([, o]) => o.enabled).length, el = t.querySelector('[data-count]');
if (el && cs.length) el.textContent = `${n}/${cs.length} on`;
}
function markDirty(c) {
dirty.add(c.dataset.id); c.classList.add('dirty');
const d = store.get(DRAFT_KEY) || { at: Date.now(), cards: {} };
d.at = Date.now(); d.cards[c.dataset.id] = collect(c); store.set(DRAFT_KEY, d);
refreshState();
}
cards().forEach(c => {
sync(c);
c.addEventListener('input', e => { if (e.target.dataset.f) { sync(c); markDirty(c); } });
c.addEventListener('change', e => { if (e.target.dataset.f) { sync(c); markDirty(c); } });
});
// --- save (button, Ctrl+S, and before anything that reloads the page) ---
let saving = null;
async function save() {
if (saving) return saving;
if (!dirty.size) return true;
const ids = [...dirty];
state('Saving…', 'dirty');
saving = (async () => {
try {
const r = await fetch('/redeems/save', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variations: ids.map(id => collect(card(id))) }) });
const j = await r.json().catch(() => ({}));
if (!r.ok || !j.ok) throw new Error(j.error || r.status);
ids.forEach(id => { dirty.delete(id); card(id)?.classList.remove('dirty'); });
if (!dirty.size) store.del(DRAFT_KEY);
state(`Saved ✓ ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`, 'ok');
return true;
} catch (e) { state('Save failed: ' + e.message + ' (your changes are kept)', 'err'); return false; }
finally { saving = null; }
})();
return saving;
}
document.getElementById('save-all').addEventListener('click', save);
document.addEventListener('keydown', e => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault(); save(); }
});
// add variation: save first, then the normal form post (reloads the page)
document.querySelectorAll('[data-add]').forEach(f => f.addEventListener('submit', async e => {
e.preventDefault(); if (await save()) { rememberOpen(f.closest('[data-trigger]').id, true); f.submit(); }
}));
// delete: two steps, no browser dialog; saves other changes first
document.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => {
const c = b.parentElement.querySelector('[data-del-confirm]');
b.hidden = true; c.hidden = false;
setTimeout(() => { b.hidden = false; c.hidden = true; }, 4000);
}));
document.querySelectorAll('[data-del-confirm]').forEach(b => b.addEventListener('click', async () => {
const c = b.closest('.vcard'); dirty.delete(c.dataset.id);
const d = store.get(DRAFT_KEY); if (d) { delete d.cards[c.dataset.id]; store.set(DRAFT_KEY, d); }
if (!(await save())) return;
const f = document.createElement('form'); f.method = 'POST'; f.action = `/redeems/variation/${c.dataset.id}/delete`;
document.body.appendChild(f); f.submit();
}));
// tests: save first so the overlay shows what you see
const post = async (url, body) => {
if (!(await save())) return;
try {
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
state(r.ok ? 'Sent to the overlay' : `Test failed (${r.status})`, r.ok ? 'ok' : 'err');
} catch (e) { state('Test failed: ' + e.message, 'err'); }
};
document.querySelectorAll('[data-test]').forEach(b => b.addEventListener('click', () => post(`/redeems/variation/${b.closest('.vcard').dataset.id}/test`)));
document.querySelectorAll('[data-test-trigger]').forEach(b => b.addEventListener('click', e => {
e.preventDefault(); post('/redeems/trigger/test', { kind: b.dataset.kind, key: b.dataset.key });
}));
// previews in the browser
let player = null;
document.querySelectorAll('[data-play-sound]').forEach(b => b.addEventListener('click', () => {
const c = b.closest('.vcard'), o = collect(c);
if (player) player.pause();
if (!o.sound) return state('No sound selected', 'err');
player = new Audio(o.sound); player.volume = parseFloat(o.volume) || 0.8;
player.play().catch(e => state('Could not play: ' + e.message, 'err'));
}));
document.querySelectorAll('[data-play-video]').forEach(b => b.addEventListener('click', () => {
const c = b.closest('.vcard'), o = collect(c), v = c.querySelector('[data-preview]');
if (!o.video) return state('No video selected', 'err');
if (!v.hidden && v.getAttribute('src') === o.video) { v.pause(); v.hidden = true; return; }
v.src = o.video; v.volume = parseFloat(o.volume) || 0.8; v.hidden = false; v.play().catch(() => {});
}));
// remember which triggers are open (survives the reload after add/delete)
function rememberOpen(id, open) { const s = new Set(store.get(OPEN_KEY) || []); open ? s.add(id) : s.delete(id); store.set(OPEN_KEY, [...s]); }
for (const id of store.get(OPEN_KEY) || []) { const d = document.getElementById(id); if (d) d.open = true; }
if (location.hash) { const d = document.getElementById(decodeURIComponent(location.hash.slice(1))); if (d) d.open = true; }
document.querySelectorAll('[data-trigger]').forEach(d => d.addEventListener('toggle', () => rememberOpen(d.id, d.open)));
// unsaved changes from a closed tab / crash: offer to restore (inline, no dialog)
const draft = store.get(DRAFT_KEY);
if (draft && draft.cards && Object.keys(draft.cards).some(id => card(id) && JSON.stringify(collect(card(id))) !== JSON.stringify(draft.cards[id]))) {
const bar = document.getElementById('draftbar');
document.getElementById('draft-when').textContent = new Date(draft.at).toLocaleString();
bar.hidden = false;
document.getElementById('draft-restore').onclick = () => {
for (const [id, o] of Object.entries(draft.cards)) { const c = card(id); if (c) { apply(c, o); markDirty(c); c.closest('[data-trigger]').open = true; } }
bar.hidden = true; state(`${dirty.size} restored change${dirty.size === 1 ? '' : 's'}: Save to keep them`, 'dirty');
};
document.getElementById('draft-discard').onclick = () => { store.del(DRAFT_KEY); bar.hidden = true; };
} else store.del(DRAFT_KEY);
})();
</script> </script>