heystreamer/views/overlay.ejs
Bashy d481fc4f69 Add polaroid alerts for follows, subs, gifts, streaks, raids and bits
Overlay
- public/alerts/polaroid.js + .css: animated polaroid (photo drops in, tape
  and heart stick on, caption writes in), randomized angles, per-event art,
  caption, tape colour, badge and sound, fanned photo stack for multi-month
  subs / community gifts / raids, and a queue so alerts never overlap.
- Bits: no alert under 5; sound tiers at 5/50/75/100/150/250.
- Watch streaks are read from chat (USERNOTICE viewermilestone) and reported
  to the server over the overlay WebSocket.

Server
- Subscribe to channel.chat.notification instead of channel.subscribe /
  subscription.message / subscription.gift / channel.raid: one event with
  Prime, months bought at once, gift recipient, resub message and community
  gift totals. Per-recipient gift notices of a gift bomb are skipped, so a
  bomb is one alert (was N+1). Needs the user:read:chat scope (log in again).
- src/alerts.js maps Twitch events to alerts, broadcasts them and still runs
  them through dispatch (activity log + existing actions).
- EventSub starts on boot from the stored login (alerts survive restarts),
  validates the token hourly and refreshes it on expiry or 401, follows
  session_reconnect without dropping events, and reconnects when keepalives
  stop.
- The overlay WebSocket only accepts chat_notice messages from connections
  that pass the overlay UUID; streak notices are deduped by message id.

Dashboard
- Twitch connection status and a test button per alert (POST /alerts/test/:key).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:57:36 +02:00

226 lines
7.9 KiB
Text

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Caveat:wght@700&display=swap">
<link rel="stylesheet" href="/alerts/polaroid.css">
<style>
:root {
--chat-left: <%= overlayLayout.chat_left %>%;
--chat-top: <%= overlayLayout.chat_top %>%;
--chat-width: <%= overlayLayout.chat_width %>%;
--chat-height: <%= overlayLayout.chat_height %>%;
--chat-font-size: <%= overlayLayout.chat_font_size %>px;
--chat-font-family: <%= overlayLayout.chat_font_family %>;
--chat-bg-opacity: <%= overlayLayout.chat_bg_opacity %>;
--chat-text-color: <%= overlayLayout.chat_text_color %>;
--chat-border-radius: <%= overlayLayout.chat_border_radius %>px;
--alert-left: <%= overlayLayout.alert_left %>%;
--alert-top: <%= overlayLayout.alert_top %>%;
--alert-font-size: <%= overlayLayout.alert_font_size %>px;
--alert-bg-opacity: <%= overlayLayout.alert_bg_opacity %>;
--alert-text-color: <%= overlayLayout.alert_text_color %>;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: transparent; overflow: hidden; width: 1920px; height: 1080px; }
#chat {
position: fixed;
left: var(--chat-left);
top: var(--chat-top);
width: var(--chat-width);
max-height: var(--chat-height);
overflow: hidden;
display: flex;
flex-direction: column;
gap: 4px;
font-family: var(--chat-font-family);
font-size: var(--chat-font-size);
color: var(--chat-text-color);
}
.chat-msg {
background: rgba(0, 0, 0, var(--chat-bg-opacity));
border-radius: var(--chat-border-radius);
padding: 5px 10px;
word-break: break-word;
animation: fadeIn 0.25s ease;
transition: opacity 0.5s ease;
}
.chat-msg .username { font-weight: 700; margin-right: 4px; }
#alert-box {
position: fixed;
left: var(--alert-left);
top: var(--alert-top);
transform: translate(-50%, -50%);
font-family: var(--chat-font-family);
font-size: var(--alert-font-size);
color: var(--alert-text-color);
background: rgba(0, 0, 0, var(--alert-bg-opacity));
border-radius: 12px;
padding: 16px 28px;
text-align: center;
display: none;
}
#alert-video {
position: fixed;
left: var(--alert-left);
top: var(--alert-top);
transform: translate(-50%, -50%);
max-width: 640px;
max-height: 480px;
border-radius: 12px;
display: none;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
<%- settings.custom_css %>
</style>
</head>
<body>
<div id="chat"></div>
<div id="alert-box"></div>
<video id="alert-video" autoplay></video>
<script src="/vendor/tmi.min.js"></script>
<script src="/alerts/polaroid.js"></script>
<script>
const S = <%- JSON.stringify(settings) %>;
const chat = document.getElementById('chat');
const alertBox = document.getElementById('alert-box');
const alertVideo = document.getElementById('alert-video');
let lastMsgTime = 0;
// --- Chat via tmi.js ---
if (S.channel) {
const client = new tmi.Client({ channels: [S.channel] });
client.connect().catch(console.error);
// Watch streaks only exist as a chat USERNOTICE (msg-id=viewermilestone).
// Report them to the server, which logs them and sends the alert back to every overlay.
client.on('raw_message', (_copy, m) => {
const t = m.tags || {};
if (m.command !== 'USERNOTICE' || t['msg-id'] !== 'viewermilestone' || t['msg-param-category'] !== 'watch-streak') return;
sendUp({ type: 'chat_notice', kind: 'watch_streak', id: t.id,
user: t['display-name'] || t.login, streak: t['msg-param-value'] });
});
client.on('message', (channel, tags, message) => {
const now = Date.now();
const silence = (now - lastMsgTime) / 1000;
console.log(`[gap] silence=${silence.toFixed(1)}s threshold=${S.gap_audio_min_silence}s enabled=${S.gap_audio_enabled} url=${!!S.gap_audio_url} lastMsg=${lastMsgTime>0}`);
if (S.gap_audio_enabled && S.gap_audio_url && lastMsgTime > 0 && silence >= S.gap_audio_min_silence) {
const t = Math.min(
(silence - S.gap_audio_min_silence) / Math.max(S.gap_audio_loud_after - S.gap_audio_min_silence, 1),
1
);
const vol = S.gap_audio_min_volume + t * (S.gap_audio_max_volume - S.gap_audio_min_volume);
console.log(`[gap] PLAY — t=${t.toFixed(2)} vol=${vol.toFixed(2)} min=${S.gap_audio_min_volume} max=${S.gap_audio_max_volume}`);
playAudio(S.gap_audio_url, vol);
}
lastMsgTime = now;
addMessage(tags['display-name'] || tags.username, tags.color || '#b4a0d4', message);
});
}
function addMessage(username, color, text) {
const div = document.createElement('div');
div.className = 'chat-msg';
div.innerHTML = `<span class="username" style="color:${esc(color)}">${esc(username)}</span>: ${esc(text)}`;
chat.appendChild(div);
while (chat.children.length > S.max_messages) chat.removeChild(chat.firstChild);
if (S.message_timeout > 0) {
setTimeout(() => {
div.style.opacity = '0';
setTimeout(() => div.remove(), 500);
}, S.message_timeout * 1000);
}
}
// --- Alert WebSocket ---
// ?overlay=<id> marks this page as the real overlay, so the server accepts chat_notice messages from it
let ws = null;
const pending = [];
function sendUp(obj) {
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(obj));
else pending.push(obj);
}
function connectWS() {
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
ws = new WebSocket(`${proto}://${location.host}/ws/overlay?overlay=${encodeURIComponent(S.overlay_id)}`);
ws.onopen = () => { while (pending.length) ws.send(JSON.stringify(pending.shift())); };
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
if (msg.type === 'settings_update') {
Object.assign(S, msg.settings);
return;
}
if (msg.type === 'alert') {
// test alerts replace whatever is showing (fast checking); real ones queue
if (msg.alert.test === true) PolaroidAlerts.reset();
PolaroidAlerts.play(msg.alert);
return;
}
document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg }));
handleAction(msg);
};
ws.onclose = () => setTimeout(connectWS, 3000);
}
connectWS();
function handleAction(msg) {
if (msg.action_type === 'sound' && msg.media_url) {
playAudio(msg.media_url, 1.0);
} else if (msg.action_type === 'video' && msg.media_url) {
showVideo(msg.media_url);
} else if (msg.action_type === 'alert') {
showAlert(msg.alert_text || '', msg.username);
}
}
function playAudio(url, volume) {
const a = new Audio(url);
a.volume = Math.max(0, Math.min(1, volume));
a.play().catch(() => {});
}
function showAlert(text, username) {
alertBox.textContent = text.replace('{username}', username || '');
alertBox.style.display = 'block';
setTimeout(() => { alertBox.style.display = 'none'; }, 5000);
}
function showVideo(url) {
alertVideo.src = url;
alertVideo.style.display = 'block';
alertVideo.play();
alertVideo.onended = () => {
alertVideo.style.display = 'none';
alertVideo.src = '';
};
}
function esc(str) {
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
<%- settings.custom_js %>
</script>
</body>
</html>