diff --git a/CLAUDE.md b/CLAUDE.md index 36e7ef4..ae04fb0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -137,7 +137,15 @@ Chat (`?parts=chat`) is `public/chat/chat.css` + `public/chat/chat.js` (window.H ## TTS voices (/tts) -Builder page to make named TTS voices; redeems do not use them yet. +Builder page to make named TTS voices, used by redeem variations (Redeems page: "TTS: " per variation). +- Redeem with a TTS voice + viewer text: `redeems.addSpeech()` cleans the text (`tts.prepareViewerText`: links out, + repeats collapsed, cut to `settings.tts_max_chars` at a word, `settings.tts_blocklist` -> nothing read, note says + "(message removed)"), synthesizes " says: " (`tts_say_name`), and only then sends the alert with + `tts` (URL) + `tts_ms`. Shown as the big paper note (style `message`, caption "says:"). TTS on = the variation's + sound is not sent (the voice replaces it; the Redeems page greys the picker out). Synthesis errors: the note still shows, silent. +- Dashboard "Skip current alert" -> POST `/alerts/skip` -> WS `{type:'alert_skip'}` -> `PolaroidAlerts.skip()`. +- `tts_blocklist` never goes to overlay pages: they get `db.getOverlaySettings()` (render and settings_update). +- New columns on existing DBs are added by `db.migrate()` (`addColumn`, ALTER only when missing). - `src/tts.js`: `synth(config, text)` -> cached mp3 in `public/tts/.mp3` (gitignored, newest 300 kept). Config = up to 3 `layers` (engine `piper`|`espeak`, voice, speaker, speed, pitch in semitones, volume, delay ms) + `effects` {stadium, echo, crush, radio, robot, chorus, flanger, tremolo: 0..1}. `normalize()` clamps everything diff --git a/public/alerts/fx.js b/public/alerts/fx.js index 6a91e6a..3ed9dbf 100644 --- a/public/alerts/fx.js +++ b/public/alerts/fx.js @@ -2,7 +2,8 @@ Special redeem visuals, called by polaroid.js (shared queue). Each returns a Promise that resolves when done. FxAlert.giant(d, cur, snd) Gigantify Power-up: the viewer's emote grows huge, pulses while the sound plays FxAlert.rain(d, cur, snd) On-Screen Celebration Power-up: copies of the emote bounce around the screen - FxAlert.message(d, cur, snd) Highlight my message / Message Effect: big taped paper note with the message + FxAlert.message(d, cur, snd) Highlight my message / Message Effect / TTS redeems: big taped paper note with the message + (d.tts = spoken message URL, d.ttsMs = its length; TTS redeems come without a sound) d: { name (user), line, msg, emote (image URL or null) }; snd: { url, len, volume } cur: { anims, timer, audio } so reset/skip can stop it (anything with cancel() can go in anims). */ @@ -118,7 +119,14 @@ { delay:550, duration:Math.min(1600, 300 + 18 * text.length), easing:'ease-in-out' }); playSound(cur, snd); const read = 2000 + 70 * text.length; // time to read it - const exitAt = Math.max(650 + AFTER_ANIM, 650 + read, SOUND_LEAD + snd.len); + let exitAt = Math.max(650 + AFTER_ANIM, 650 + read, SOUND_LEAD + snd.len); + if (d.tts) { // TTS: after the intro sound, keep the note up until it is said + const ttsAt = SOUND_LEAD + (snd.url ? snd.len + 250 : 300); + const a = new Audio(d.tts); a.volume = snd.volume; + const t = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] TTS blocked:', err.message)); }, ttsAt); + cur.anims.push({ cancel: () => { clearTimeout(t); a.pause(); } }); // skip/reset stop the voice too + exitAt = Math.max(exitAt, ttsAt + (d.ttsMs || 4000) + 900); + } return done(cur, A(cur, el, [{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(140px) rotate(8deg)', opacity:0 }], { delay:exitAt, duration:500, easing:'ease-in' })); } diff --git a/public/alerts/polaroid.js b/public/alerts/polaroid.js index 55c2ed4..4917806 100644 --- a/public/alerts/polaroid.js +++ b/public/alerts/polaroid.js @@ -6,6 +6,7 @@ but never interrupts or drops a real one (it queues behind it). A real alert cuts off a test that is showing. window.PolaroidAlerts.reset() stop the current alert and clear the queue + window.PolaroidAlerts.skip() stop the current alert (e.g. a TTS message), carry on with the queue Alert shapes come from src/alerts.js: { type:'follow', user } @@ -127,7 +128,8 @@ return { cassette: true, style: e.style || 'cassette', emote: e.emote || null, sticker: rebase(e.art) || null, name: e.user || 'Someone', line: fill(e.caption || 'redeemed it! ♡'), msg: e.input, title: e.variation || e.reward, sub: e.reward, rarity: e.rarity, - sound: e.sound || null, volume: e.volume, soundOnly: e.polaroid === false }; + sound: e.sound || null, volume: e.volume, soundOnly: e.polaroid === false && !e.tts, + tts: e.tts ? rebase(e.tts) : null, ttsMs: e.tts_ms || 0 }; } case 'bits': { if (!(e.bits >= BITS_MIN)) return null; @@ -211,6 +213,13 @@ play({ ...alert, test: true }); // a real one on screen: wait } + // dashboard Skip button: cut what is on screen (sound/TTS too), then play the next queued alert + function skip() { + if (!current) return; + skipCurrent(); + setTimeout(() => { if (!busy) next(); }, GAP); + } + function reset() { gen++; queue.length = 0; @@ -362,6 +371,6 @@ .catch(() => {}); // cancelled by reset() } - window.PolaroidAlerts = { play, playTest, reset, describe }; + window.PolaroidAlerts = { play, playTest, reset, skip, describe }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload(); })(); diff --git a/public/chat/chat.css b/public/chat/chat.css index b8ad45c..c30f69d 100644 --- a/public/chat/chat.css +++ b/public/chat/chat.css @@ -2,16 +2,17 @@ The box sits under the webcam (Game scene: camera group at 1920,600, 640x360 on the 2560 canvas = 1440,450 480x270 on this 1920x1080 page). Newest message on top, slides out from under the camera, older ones are pushed down and dissolve at the bottom edge. - Move or resize it with Custom CSS in Settings, e.g. #chat { --chat-top: 60%; --chat-height: 37%; } */ + Per browser source: ?chat=left,top,width,height (px of the 1920x1080 page) and ?chatflow=up (newest at the bottom), + e.g. the Intermission panel: ?parts=chat&chat=130,640,700,360&chatflow=up. Default (no ?chat): under the camera, flowing down. */ #chat { - --chat-right: 2%; + --chat-left: 78%; --chat-top: 63%; /* 680px: just above the bottom of the camera ring, so messages come out from under it */ --chat-width: 20%; --chat-height: 34%; /* down to the bottom edge */ --ink: #3a2a20; --cream: #fffdf7; position: fixed; - right: var(--chat-right); + left: var(--chat-left); top: var(--chat-top); width: var(--chat-width); height: var(--chat-height); @@ -25,6 +26,16 @@ mask-image: linear-gradient(transparent 0, #000 30px, #000 calc(100% - 60px), transparent); } +/* up: like a normal chat, newest at the bottom, the oldest fade out at the top */ +#chat.up { + justify-content: flex-end; + padding: 14px 8px 8px; + -webkit-mask-image: linear-gradient(transparent 0, #000 50px); + mask-image: linear-gradient(transparent 0, #000 50px); +} +#chat.up .msg.in { animation-name: chat-in-up; } +@keyframes chat-in-up { from { opacity: 0; transform: translateY(24px) rotate(calc(var(--tilt, 0deg) * -3)) scale(.95); } } + #chat .msg { position: relative; flex: none; diff --git a/public/chat/chat.js b/public/chat/chat.js index 8cb5bd8..1582536 100644 --- a/public/chat/chat.js +++ b/public/chat/chat.js @@ -128,9 +128,10 @@ d.innerHTML = `${esc(name)}${r.html}`; d._n = ++seq; - // FLIP: remember where the others are, put the new one on top, then glide them down from the old spot + // FLIP: remember where the others are, add the new one (on top, or at the bottom for ?chatflow=up), + // then glide the others from their old spot const before = new Map([...box.children].map(m => [m, m.getBoundingClientRect().top])); - box.prepend(d); + if (box.classList.contains('up')) box.append(d); else box.prepend(d); before.forEach((top, m) => { const dy = top - m.getBoundingClientRect().top; if (dy && m.animate) m.animate([{ translate: `0 ${dy}px` }, { translate: '0 0' }], { duration: 320, easing: 'cubic-bezier(.2,.8,.3,1)' }); diff --git a/src/db.js b/src/db.js index fcc8ed6..5085287 100644 --- a/src/db.js +++ b/src/db.js @@ -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'); // " 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, diff --git a/src/redeems.js b/src/redeems.js index a92e8d4..a5734f0 100644 --- a/src/redeems.js +++ b/src/redeems.js @@ -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; } diff --git a/src/routers/alerts.js b/src/routers/alerts.js index 2f634e8..5946a74 100644 --- a/src/routers/alerts.js +++ b/src/routers/alerts.js @@ -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(); diff --git a/src/routers/overlay.js b/src/routers/overlay.js index 824d653..6c1421f 100644 --- a/src/routers/overlay.js +++ b/src/routers/overlay.js @@ -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; diff --git a/src/routers/redeems.js b/src/routers/redeems.js index 504acd0..93eb365 100644 --- a/src/routers/redeems.js +++ b/src/routers/redeems.js @@ -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); }); diff --git a/src/routers/settings.js b/src/routers/settings.js index 4dd2b84..63c2870 100644 --- a/src/routers/settings.js +++ b/src/routers/settings.js @@ -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'); diff --git a/src/tts.js b/src/tts.js index 2ece907..e20efc5 100644 --- a/src/tts.js +++ b/src/tts.js @@ -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 }; diff --git a/views/dashboard.ejs b/views/dashboard.ejs index 7e05b53..c630c52 100644 --- a/views/dashboard.ejs +++ b/views/dashboard.ejs @@ -11,11 +11,27 @@ <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=chat
Everything except chat (alerts, redeems, poll, Hype Train bar, raid send-off):
<%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=nochat
+ Chat somewhere else, e.g. in the Intermission panel (left,top,width,height in px of the 1920×1080 page; up = newest at the bottom):
+ <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=chat&chat=130,640,700,360&chatflow=up
Other combinations: hover for help · everything in one source: /overlay/<%= settings.overlay_id %> +
+ + +
+ +

Twitch connection

<% if (eventsubStatus.connected) { %> diff --git a/views/overlay.ejs b/views/overlay.ejs index b7469ba..694be44 100644 --- a/views/overlay.ejs +++ b/views/overlay.ejs @@ -67,7 +67,7 @@ - <% if (has('chat')) { %>

<% } %> + <% if (has('chat')) { %>
style="--chat-left:<%= chatBox.left %>px; --chat-top:<%= chatBox.top %>px; --chat-width:<%= chatBox.width %>px; --chat-height:<%= chatBox.height %>px;"<% } %>>
<% } %> <% if (has('alerts')) { %>
<% } %> @@ -161,6 +161,7 @@ // NOWPLAYING: if (msg.type === 'nowplaying') { if (PARTS.has('nowplaying')) NowPlaying.update(msg.np); 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 === 'alert_skip') { if (PARTS.has('alerts')) PolaroidAlerts.skip(); return; } if (!PARTS.has('alerts')) return; // alerts and legacy actions below if (msg.type === 'alert') { // test buttons: replace other test alerts at once, but never cut off a real alert diff --git a/views/redeems.ejs b/views/redeems.ejs index 3b5912f..6dc2aab 100644 --- a/views/redeems.ejs +++ b/views/redeems.ejs @@ -40,6 +40,7 @@ <% if (t.cost != null) { %><%= t.cost %> pts<% } %> <% if (t.missing) { %>not on Twitch anymore<% } %> <% if (t.live === false) { %>paused on Twitch<% } %> + <% if (t.variations.some(v => v.tts_voice_id)) { %>TTS<% } %> <%= t.variations.length ? `${on.length}/${t.variations.length} variation${t.variations.length === 1 ? '' : 's'} on` : 'no alert' %> @@ -72,6 +73,10 @@ <% for (const st of stickers) { %><% } %> + @@ -122,6 +127,17 @@ 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 + }); + // two-step delete, no browser dialog document.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => { const c = b.parentElement.querySelector('[data-del-confirm]'); diff --git a/views/settings.ejs b/views/settings.ejs index d54e29c..f653c79 100644 --- a/views/settings.ejs +++ b/views/settings.ejs @@ -58,6 +58,25 @@ e.g. 3600 = 1 hour of silence → max volume +

TTS redeems

+

For redeem variations with a TTS voice (set on the Redeems page; voices are made on the TTS page).

+
+ + +
+ +

Custom CSS / JS