Add StreamElements tips and a Feishin now-playing helper (disabled)
- src/streamelements.js: StreamElements Astro websocket, channel.tips with SE_JWT. Only allowed + successful tips alert, deduped by id, follows reconnect tokens. Off unless SE_JWT is set. - tools/nowplaying/: PC helper that reads Feishin over MPRIS and posts title, artist and a small cover thumbnail to /nowplaying (Bearer NOWPLAYING_KEY). The cover is fetched on the LAN so the Navidrome token never leaves the PC. Endpoint and overlay widget are kept but switched off for now. - .env.example: SE_JWT, NOWPLAYING_KEY. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
553cc35b9e
commit
b28e56f991
6 changed files with 253 additions and 0 deletions
12
src/nowplaying.js
Normal file
12
src/nowplaying.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
// "Now playing" from the streamer's music player (Feishin via MPRIS), pushed by tools/nowplaying/feishin_nowplaying.py.
|
||||
// The helper sends only text + a small JPEG cover (data URL); no player/server URLs or credentials reach this app.
|
||||
let current = null; // { playing, title, artist, album, cover, length, updatedAt }
|
||||
|
||||
function set(np) {
|
||||
current = { ...np, updatedAt: Date.now() };
|
||||
require('./ws').broadcast({ type: 'nowplaying', np: current });
|
||||
return current;
|
||||
}
|
||||
function get() { return current; }
|
||||
|
||||
module.exports = { set, get };
|
||||
28
src/routers/nowplaying.js
Normal file
28
src/routers/nowplaying.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
const express = require('express');
|
||||
const crypto = require('crypto');
|
||||
const router = express.Router();
|
||||
const nowplaying = require('../nowplaying');
|
||||
|
||||
// POST /nowplaying (Authorization: Bearer <NOWPLAYING_KEY>) from the PC helper; no login session involved.
|
||||
const key = () => process.env.NOWPLAYING_KEY || '';
|
||||
function authorized(req) {
|
||||
const k = key(), got = (req.get('authorization') || '').replace(/^Bearer\s+/i, '');
|
||||
if (!k || !got) return false;
|
||||
const a = Buffer.from(k), b = Buffer.from(got);
|
||||
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
|
||||
|
||||
router.post('/', express.json({ limit: '300kb' }), (req, res) => {
|
||||
if (!authorized(req)) return res.status(401).json({ ok: false });
|
||||
const b = req.body || {};
|
||||
const cover = typeof b.cover === 'string' && /^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/.test(b.cover) && b.cover.length < 250000 ? b.cover : null;
|
||||
nowplaying.set({
|
||||
playing: b.status === 'Playing',
|
||||
title: str(b.title, 200), artist: str(b.artist, 200), album: str(b.album, 200),
|
||||
length: Number.isFinite(b.length) ? b.length : null, cover,
|
||||
});
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
75
src/streamelements.js
Normal file
75
src/streamelements.js
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// StreamElements tips via the Astro websocket (https://docs.streamelements.com/websockets).
|
||||
// Set SE_JWT in .env (StreamElements dashboard -> avatar -> channel -> copy JWT token). Unset = off.
|
||||
// Protocol: welcome -> subscribe {topic:'channel.tips', token, token_type:'jwt'} -> messages on topic channel.tips.
|
||||
// Server PINGs every 30 s (ws answers PONG automatically); a 'reconnect' message carries reconnect_token,
|
||||
// and connecting with ?reconnect_token= restores subscriptions without subscribing again.
|
||||
const { WebSocket } = require('ws');
|
||||
const alerts = require('./alerts');
|
||||
|
||||
const URL_BASE = process.env.SE_URL || 'wss://astro.streamelements.com';
|
||||
let ws = null, shouldRun = false, retryTimer = null, retryMs = 5000;
|
||||
const status = { enabled: false, connected: false, subscribed: false, error: null, lastTipAt: null };
|
||||
const seen = new Map(); // tip _id -> time, so a resent tip alerts only once
|
||||
|
||||
function start() {
|
||||
if (!process.env.SE_JWT) { console.log('[se] SE_JWT not set: StreamElements tips off'); return; }
|
||||
status.enabled = true; shouldRun = true;
|
||||
connect(URL_BASE, true);
|
||||
}
|
||||
|
||||
function stop() {
|
||||
shouldRun = false; clearTimeout(retryTimer);
|
||||
if (ws) { ws.removeAllListeners('close'); ws.close(); ws = null; }
|
||||
status.connected = status.subscribed = false;
|
||||
}
|
||||
|
||||
function connect(url, subscribe) {
|
||||
console.log(`[se] Connecting${subscribe ? '' : ' (reconnect token)'}...`);
|
||||
const sock = new WebSocket(url);
|
||||
sock.on('message', raw => { let m; try { m = JSON.parse(raw); } catch { return; } handle(sock, m, subscribe); });
|
||||
sock.on('close', (code) => {
|
||||
if (sock !== ws) return;
|
||||
status.connected = status.subscribed = false;
|
||||
console.log(`[se] Disconnected (${code})`);
|
||||
if (shouldRun) { clearTimeout(retryTimer); retryTimer = setTimeout(() => connect(URL_BASE, true), retryMs); retryMs = Math.min(retryMs * 2, 120000); }
|
||||
});
|
||||
sock.on('error', e => { status.error = e.message; console.error('[se] Error:', e.message); });
|
||||
const old = ws; ws = sock;
|
||||
if (old) { old.removeAllListeners('close'); old.close(); }
|
||||
}
|
||||
|
||||
function handle(sock, m, subscribe) {
|
||||
switch (m.type) {
|
||||
case 'welcome':
|
||||
status.connected = true; status.error = null; retryMs = 5000;
|
||||
if (subscribe) sock.send(JSON.stringify({ type: 'subscribe', nonce: 'tips-' + Date.now(),
|
||||
data: { topic: 'channel.tips', token: process.env.SE_JWT, token_type: 'jwt' } }));
|
||||
else status.subscribed = true;
|
||||
break;
|
||||
case 'response':
|
||||
if (m.error) { status.error = `${m.error}: ${m.data?.message || ''}`; console.error('[se] Subscribe failed:', status.error); }
|
||||
else { status.subscribed = true; console.log(`[se] Subscribed to ${m.data?.topic} (room ${m.data?.room})`); }
|
||||
break;
|
||||
case 'reconnect':
|
||||
if (m.data?.reconnect_token) connect(`${URL_BASE}/?reconnect_token=${encodeURIComponent(m.data.reconnect_token)}`, false);
|
||||
break;
|
||||
case 'message':
|
||||
if (m.topic === 'channel.tips') tip(m.data);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function tip(data) {
|
||||
if (!data?.donation) return;
|
||||
if (data.approved && data.approved !== 'allowed') { console.log(`[se] Tip ${data._id} not shown (approved: ${data.approved})`); return; }
|
||||
if (data.status && data.status !== 'success') return;
|
||||
const now = Date.now();
|
||||
for (const [id, t] of seen) if (now - t > 3600e3) seen.delete(id);
|
||||
if (data._id && seen.has(data._id)) return;
|
||||
if (data._id) seen.set(data._id, now);
|
||||
status.lastTipAt = new Date().toISOString();
|
||||
alerts.send(alerts.fromTip(data), data);
|
||||
}
|
||||
|
||||
function getStatus() { return { ...status }; }
|
||||
module.exports = { start, stop, getStatus };
|
||||
Loading…
Add table
Add a link
Reference in a new issue