TTS redeems, skip button, per-source chat placement

- Redeem variations can have a TTS voice: the viewer's text is cleaned
  (links out, repeats collapsed, max length, blocked words -> not read),
  spoken as "<name> says: ..." and shown as the big paper note; the
  variation's sound is not played when TTS is on (picker greyed out)
- Settings: TTS max length, say-the-name, blocked words (never sent to
  overlay pages: db.getOverlaySettings)
- Dashboard "Skip current alert" -> /alerts/skip -> overlay skips it
- db.migrate()/addColumn: new columns on existing databases
- Chat: ?chat=left,top,width,height and ?chatflow=up per browser source
  (e.g. the Intermission panel); default unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-21 14:34:41 +02:00
parent b5a81bdb15
commit 4fda6060bf
16 changed files with 228 additions and 28 deletions

View file

@ -10,6 +10,7 @@ function init() {
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
createSchema();
migrate();
seedSettings();
seedVariations();
console.log(`[db] Initialised — path: ${DB_PATH}`);
@ -122,6 +123,21 @@ function createSchema() {
`);
}
// columns added after the first deploy: ALTER only when missing, so existing databases keep their data
function addColumn(table, col, def) {
if (!db.prepare(`PRAGMA table_info(${table})`).all().some(c => c.name === col)) {
db.exec(`ALTER TABLE ${table} ADD COLUMN ${col} ${def}`);
console.log(`[db] Added ${table}.${col}`);
}
}
function migrate() {
addColumn('reward_variations', 'tts_voice_id', 'INTEGER'); // tts_voices.id; NULL = no TTS
addColumn('settings', 'tts_max_chars', 'INTEGER DEFAULT 200'); // longer redeem text is cut
addColumn('settings', 'tts_blocklist', "TEXT DEFAULT ''"); // words/phrases, one per line or comma-separated
addColumn('settings', 'tts_say_name', 'INTEGER DEFAULT 1'); // "<name> says: ..." before the message
}
function seedSettings() {
const row = db.prepare('SELECT id FROM settings WHERE id = 1').get();
if (!row) {
@ -172,6 +188,12 @@ function getSettings() {
return db.prepare('SELECT * FROM settings WHERE id = 1').get();
}
// what overlay pages get: everything except server-only values (the overlay URL is public)
function getOverlaySettings() {
const { tts_blocklist, ...rest } = getSettings();
return rest;
}
function updateSettings(fields) {
const cols = Object.keys(fields).map(k => `${k} = @${k}`).join(', ');
db.prepare(`UPDATE settings SET ${cols} WHERE id = 1`).run(fields);
@ -241,7 +263,7 @@ function getMatchingActions(eventType, eventDetail) {
}
// Redeem variations
const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled'];
const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled', 'tts_voice_id'];
function getAllVariations() {
return db.prepare('SELECT * FROM reward_variations ORDER BY kind, title, id').all();
@ -297,7 +319,10 @@ function updateTtsVoice(id, name, config) {
}
function deleteTtsVoice(id) {
db.prepare('DELETE FROM tts_voices WHERE id = ?').run(id);
db.transaction(() => {
db.prepare('UPDATE reward_variations SET tts_voice_id = NULL WHERE tts_voice_id = ?').run(id);
db.prepare('DELETE FROM tts_voices WHERE id = ?').run(id);
})();
}
// Activity log
@ -321,7 +346,7 @@ function getActivityLog(limit = 50) {
module.exports = {
init,
upsertUser, getUserById, getPrimaryUser, updateUserTokens,
getSettings, updateSettings,
getSettings, getOverlaySettings, updateSettings,
getAllMedia, getMediaFile, createMedia, deleteMedia,
getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions,
getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation,

View file

@ -4,6 +4,7 @@
const db = require('./db');
const alerts = require('./alerts');
const dispatch = require('./dispatch');
const tts = require('./tts');
// 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
@ -37,7 +38,7 @@ const STYLE = {
'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 LINE = { emote: 'gigantified an emote!', emote_rain: 'is celebrating!', message: 'highlighted:', tts: 'says:' };
const emoteUrl = id => id ? `https://static-cdn.jtvnw.net/emoticons/v2/${encodeURIComponent(id)}/default/dark/3.0` : null;
function pick(variations) {
@ -49,16 +50,42 @@ function pick(variations) {
}
function toAlert(v, { user, input, emote }) {
const style = STYLE[`${v.kind}:${v.key}`] || 'cassette';
const spoken = !!(v.tts_voice_id && input); // TTS variations are shown as the big paper note
const style = spoken ? 'message' : (STYLE[`${v.kind}:${v.key}`] || 'cassette');
const line = spoken ? LINE.tts : LINE[style];
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),
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),
};
}
// TTS: clean the viewer's text, speak it with the variation's saved voice, attach { tts, tts_ms }.
// Never throws: on any problem the alert still goes out, just without speech.
async function addSpeech(v, alert) {
try {
const voice = db.getTtsVoice(v.tts_voice_id);
if (!voice || !alert.input) return;
const s = db.getSettings();
const { text, blocked } = tts.prepareViewerText(alert.input, { maxChars: s.tts_max_chars, blocklist: s.tts_blocklist });
if (blocked) {
console.log(`[tts] blocked message from ${alert.user}`);
alert.input = '(message removed)';
return;
}
alert.input = text; // the note shows what is read
if (!text) return;
const say = s.tts_say_name && alert.user ? `${alert.user} says: ${text}` : text;
const out = await tts.synth(voice.config, say);
alert.tts = out.url;
alert.tts_ms = out.durationMs;
} catch (e) {
console.warn(`[tts] ${alert.user}: ${e.message}`);
}
}
// legacy action event type for the actions system / activity log
const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up' };
@ -72,7 +99,8 @@ function handle(kind, key, title, { user, input, emote }, raw) {
return null;
}
const alert = toAlert(v, { user, input, emote });
alerts.send(alert, raw);
if (v.tts_voice_id && input) addSpeech(v, alert).then(() => alerts.send(alert, raw)); // speech first, then the alert
else alerts.send(alert, raw);
return alert;
}
@ -80,9 +108,12 @@ function handle(kind, key, title, { user, input, emote }, raw) {
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!'
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;
alerts.sendTestAlert(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 }); // 25 = Kappa
if (v.tts_voice_id) addSpeech(v, alert).then(() => alerts.sendTestAlert(alert));
else alerts.sendTestAlert(alert);
return true;
}

View file

@ -2,6 +2,7 @@ const express = require('express');
const router = express.Router();
const alerts = require('../alerts');
const twitch = require('../twitch');
const ws = require('../ws');
// POST /alerts/test/:key: send a sample alert to every connected overlay (dashboard test buttons)
router.post('/test/:key', (req, res) => {
@ -9,6 +10,13 @@ router.post('/test/:key', (req, res) => {
res.status(ok ? 200 : 404).json({ ok });
});
// POST /alerts/skip: stop the alert on screen right now (e.g. a TTS message), the queue carries on
router.post('/skip', (req, res) => {
ws.broadcast({ type: 'alert_skip' });
console.log('[alerts] skip requested from the dashboard');
res.json({ ok: true });
});
// POST /alerts/raid/start {target}: start a raid on Twitch and show the send-off card until it happens
router.post('/raid/start', async (req, res) => {
const me = twitch.getUser();

View file

@ -18,10 +18,21 @@ function partsFrom(q) {
return asked.length ? asked : PARTS;
}
// ?chat=left,top,width,height chat box in px of the 1920x1080 page (e.g. Intermission panel: 130,640,700,360)
// ?chatflow=up|down up = newest at the bottom (normal chat); down (default) = newest on top, under the camera
function chatBoxFrom(q) {
const n = String(q || '').split(',').map(Number);
if (n.length !== 4 || n.some(x => !isFinite(x))) return null;
const [l, t, w, h] = n;
if (w < 50 || h < 50 || l < -1920 || t < -1080 || l > 1920 || t > 1080 || w > 1920 || h > 1080) return null;
return { left: Math.round(l), top: Math.round(t), width: Math.round(w), height: Math.round(h) };
}
router.get('/:uuid', (req, res) => {
const settings = db.getSettings();
const settings = db.getOverlaySettings();
if (req.params.uuid !== settings.overlay_id) return res.status(404).send('Overlay not found');
res.render('overlay', { layout: false, settings, parts: partsFrom(req.query.parts) });
res.render('overlay', { layout: false, settings, parts: partsFrom(req.query.parts),
chatBox: chatBoxFrom(req.query.chat), chatFlow: req.query.chatflow === 'up' ? 'up' : 'down' });
});
module.exports = router;

View file

@ -62,6 +62,7 @@ router.get('/', async (req, res) => {
res.render('redeems', {
groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY,
sounds: soundOptions(),
ttsVoices: db.getAllTtsVoices(),
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+$/, '') })),
@ -93,6 +94,7 @@ router.post('/variation/:id', (req, res) => {
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);
});

View file

@ -25,12 +25,15 @@ router.post('/', (req, res) => {
gap_audio_min_volume: flt(b.gap_audio_min_volume, 0.2),
gap_audio_max_volume: flt(b.gap_audio_max_volume, 1.0),
gap_audio_loud_after: int(b.gap_audio_loud_after, 3600),
tts_max_chars: Math.max(20, Math.min(300, int(b.tts_max_chars, 200))),
tts_say_name: b.tts_say_name === 'on' ? 1 : 0,
tts_blocklist: String(b.tts_blocklist || '').slice(0, 20000),
custom_css: b.custom_css || '',
custom_js: b.custom_js || '',
});
// Push updated settings to all connected overlays so they don't need a page reload
ws.broadcast({ type: 'settings_update', settings: db.getSettings() });
ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() });
console.log(`[settings] Saved — channel: ${b.channel}, gap_audio: ${b.gap_audio_enabled === 'on'}`);
res.redirect('/settings');

View file

@ -83,6 +83,32 @@ function cleanText(text) {
return String(text || '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_CHARS);
}
// ---------- viewer text (redeems) ----------
// Returns { text, blocked }. blocked = a blocklist word was found: do not read anything.
const LEET = { 0: 'o', 1: 'i', 3: 'e', 4: 'a', 5: 's', 7: 't', '@': 'a', $: 's', '!': 'i' };
function parseBlocklist(list) {
return String(list || '').split(/[\n,]/).map(w => w.trim().toLowerCase()).filter(Boolean);
}
function prepareViewerText(input, { maxChars = 200, blocklist = '' } = {}) {
let t = cleanText(input)
.replace(/\b(?:https?:\/\/|www\.)\S+/gi, ' ') // links
.replace(/\b[\w-]+(?:\.[\w-]+)*\.(?:com|net|org|gg|tv|io|ru|xyz|ly|me|co|app|link|sk|ro|de|uk|info|site|shop)\b\S*/gi, ' ')
.replace(/(\S)\1{3,}/g, '$1$1$1') // aaaaaaa -> aaa
.replace(/\b(\w+)(?:\s+\1\b){2,}/gi, '$1 $1') // lol lol lol lol -> lol lol
.replace(/\s+/g, ' ').trim();
const max = Math.max(20, Math.min(MAX_CHARS, maxChars | 0 || 200));
if (t.length > max) t = t.slice(0, max).replace(/\s+\S*$/, '') + '…';
const plain = t.toLowerCase().replace(/[013457@$!]/g, c => LEET[c] || c);
const words = ' ' + plain.replace(/[^a-z0-9\u00c0-\u024f]+/g, ' ') + ' ';
const squashed = plain.replace(/[^a-z\u00c0-\u024f]+/g, '');
const blocked = parseBlocklist(blocklist).some(w => {
const ww = w.replace(/[013457@$!]/g, c => LEET[c] || c);
return ww.length >= 4 ? squashed.includes(ww.replace(/[^a-z\u00c0-\u024f]+/g, '')) // longer words: also when spaced out
: words.includes(' ' + ww.replace(/[^a-z0-9\u00c0-\u024f]+/g, ' ').trim() + ' ');
});
return { text: t, blocked };
}
// ---------- worker ----------
let proc = null, outBuf = '', nextId = 1;
const pending = new Map();
@ -150,6 +176,11 @@ function layerFilter(l, i) {
return `[${i}:a]${f.join(',')}[l${i}]`;
}
function durationMs(file) {
return new Promise(resolve => execFile('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file],
{ timeout: 10000 }, (err, out) => resolve(err ? 0 : Math.round(parseFloat(out) * 1000) || 0)));
}
function prune() {
try {
const files = fs.readdirSync(OUT_DIR).filter(f => f.endsWith('.mp3'))
@ -158,7 +189,7 @@ function prune() {
} catch (e) { console.warn('[tts] prune:', e.message); }
}
// Returns { url, file, cached, ms }. Same config + text = same file (cached).
// Returns { url, file, cached, ms, durationMs }. Same config + text = same file (cached).
async function synth(configIn, textIn) {
const config = normalize(configIn);
const text = cleanText(textIn);
@ -166,7 +197,7 @@ async function synth(configIn, textIn) {
const hash = crypto.createHash('sha1').update(JSON.stringify([config, text])).digest('hex').slice(0, 20);
const file = path.join(OUT_DIR, `${hash}.mp3`);
const url = `/tts/${hash}.mp3`;
if (fs.existsSync(file)) return { url, file, cached: true, ms: 0 };
if (fs.existsSync(file)) return { url, file, cached: true, ms: 0, durationMs: await durationMs(file) };
const t0 = Date.now();
fs.mkdirSync(TMP_DIR, { recursive: true });
@ -191,7 +222,7 @@ async function synth(configIn, textIn) {
for (const w of wavs) fs.rm(w, { force: true }, () => {});
}
prune();
return { url, file, cached: false, ms: Date.now() - t0 };
return { url, file, cached: false, ms: Date.now() - t0, durationMs: await durationMs(file) };
}
module.exports = { voices, synth, normalize, cleanText, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS };
module.exports = { voices, synth, normalize, cleanText, prepareViewerText, parseBlocklist, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS };