From b28e56f99162e0a61bf95a6b4f0fc83aa41c2157 Mon Sep 17 00:00:00 2001 From: Bashy Date: Fri, 20 Nov 2026 23:18:15 +0200 Subject: [PATCH] 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 --- .env.example | 6 + src/nowplaying.js | 12 ++ src/routers/nowplaying.js | 28 +++++ src/streamelements.js | 75 +++++++++++ tools/nowplaying/feishin_nowplaying.py | 119 ++++++++++++++++++ .../nowplaying/heystreamer-nowplaying.service | 13 ++ 6 files changed, 253 insertions(+) create mode 100644 src/nowplaying.js create mode 100644 src/routers/nowplaying.js create mode 100644 src/streamelements.js create mode 100755 tools/nowplaying/feishin_nowplaying.py create mode 100644 tools/nowplaying/heystreamer-nowplaying.service diff --git a/.env.example b/.env.example index 1158885..a99ff3f 100644 --- a/.env.example +++ b/.env.example @@ -10,3 +10,9 @@ SECRET_KEY=change_this_to_a_random_string APP_BASE_URL=https://overlay.example.com DB_PATH=./heystreamer.db PORT=3000 + +# StreamElements tips (optional): dashboard -> avatar -> channel -> JWT token. Keep it secret. +SE_JWT= + +# Now playing (Feishin) helper: long random secret shared with tools/nowplaying (e.g. `openssl rand -hex 32`). +NOWPLAYING_KEY= diff --git a/src/nowplaying.js b/src/nowplaying.js new file mode 100644 index 0000000..7f51224 --- /dev/null +++ b/src/nowplaying.js @@ -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 }; diff --git a/src/routers/nowplaying.js b/src/routers/nowplaying.js new file mode 100644 index 0000000..6042a85 --- /dev/null +++ b/src/routers/nowplaying.js @@ -0,0 +1,28 @@ +const express = require('express'); +const crypto = require('crypto'); +const router = express.Router(); +const nowplaying = require('../nowplaying'); + +// POST /nowplaying (Authorization: Bearer ) 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; diff --git a/src/streamelements.js b/src/streamelements.js new file mode 100644 index 0000000..3315f5b --- /dev/null +++ b/src/streamelements.js @@ -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 }; diff --git a/tools/nowplaying/feishin_nowplaying.py b/tools/nowplaying/feishin_nowplaying.py new file mode 100755 index 0000000..35600a1 --- /dev/null +++ b/tools/nowplaying/feishin_nowplaying.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +""" +Feishin -> HeyStreamer "now playing". + +Watches Feishin over MPRIS (D-Bus) and POSTs {status, title, artist, album, length, cover} to +/nowplaying with "Authorization: Bearer ". + +The cover is fetched here on the LAN (Feishin's artUrl points at Navidrome and contains the +Subsonic login token) and sent as a small JPEG data URL, so no URL or credential leaves this PC. + +Config: ~/.config/heystreamer-nowplaying.env (HEYSTREAMER_URL=..., NOWPLAYING_KEY=...) +Run: python3 feishin_nowplaying.py (or the systemd user unit next to this file) +""" +import base64, io, json, os, sys, time, urllib.request +import gi +gi.require_version('Gio', '2.0') +from gi.repository import Gio, GLib + +BUS_NAME = 'org.mpris.MediaPlayer2.Feishin' +PATH, PLAYER_IF = '/org/mpris/MediaPlayer2', 'org.mpris.MediaPlayer2.Player' +HEARTBEAT_S = 30 + + +def load_config(): + cfg = dict(os.environ) + p = os.path.expanduser('~/.config/heystreamer-nowplaying.env') + if os.path.exists(p): + for line in open(p): + line = line.strip() + if line and not line.startswith('#') and '=' in line: + k, v = line.split('=', 1) + cfg.setdefault(k.strip(), v.strip().strip('"').strip("'")) + if not cfg.get('HEYSTREAMER_URL') or not cfg.get('NOWPLAYING_KEY'): + sys.exit('set HEYSTREAMER_URL and NOWPLAYING_KEY in ~/.config/heystreamer-nowplaying.env') + return cfg['HEYSTREAMER_URL'].rstrip('/'), cfg['NOWPLAYING_KEY'] + + +URL, KEY = load_config() +bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) +last_sent, cover_cache = None, {} + + +def prop(name): + try: + r = bus.call_sync(BUS_NAME, PATH, 'org.freedesktop.DBus.Properties', 'Get', + GLib.Variant('(ss)', (PLAYER_IF, name)), None, Gio.DBusCallFlags.NONE, 2000, None) + return r.unpack()[0] + except GLib.Error: + return None # Feishin not running + + +def cover_data(art_url): + """Fetch the cover on the LAN, shrink to 160 px JPEG, return a data URL (cached per URL).""" + if not art_url or not art_url.startswith(('http://', 'https://', 'file://')): + return None + if art_url in cover_cache: + return cover_cache[art_url] + try: + from PIL import Image + if art_url.startswith('file://'): + raw = open(urllib.request.url2pathname(art_url[7:]), 'rb').read() + else: + raw = urllib.request.urlopen(art_url, timeout=5).read() + im = Image.open(io.BytesIO(raw)).convert('RGB') + im.thumbnail((160, 160)) + buf = io.BytesIO(); im.save(buf, 'JPEG', quality=82) + data = 'data:image/jpeg;base64,' + base64.b64encode(buf.getvalue()).decode() + except Exception as e: + print('cover fetch failed:', type(e).__name__, flush=True) + data = None + cover_cache.clear(); cover_cache[art_url] = data + return data + + +def state(): + md, status = prop('Metadata'), prop('PlaybackStatus') + if not md or not status: + return {'status': 'Stopped', 'title': '', 'artist': '', 'album': '', 'length': None, 'cover': None} + artists = md.get('xesam:artist') or md.get('xesam:albumArtist') or [] + return { + 'status': status, + 'title': md.get('xesam:title') or '', + 'artist': ', '.join(artists) if isinstance(artists, list) else str(artists), + 'album': md.get('xesam:album') or '', + 'length': round(md['mpris:length'] / 1e6, 1) if md.get('mpris:length') else None, + 'cover': cover_data(md.get('mpris:artUrl')), + } + + +def send(force=False): + global last_sent + s = state() + sig = (s['status'], s['title'], s['artist']) + if not force and sig == last_sent: + return True + req = urllib.request.Request(URL + '/nowplaying', data=json.dumps(s).encode(), method='POST', + headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + KEY}) + try: + urllib.request.urlopen(req, timeout=8).read() + if sig != last_sent: + print(f"{s['status']}: {s['artist']} - {s['title']}", flush=True) + last_sent = sig + except Exception as e: + print('send failed:', type(e).__name__, getattr(e, 'code', ''), flush=True) + return True + + +def on_signal(*_): + GLib.timeout_add(150, lambda: send() and False) # let Feishin finish updating all properties + + +bus.signal_subscribe(BUS_NAME, 'org.freedesktop.DBus.Properties', 'PropertiesChanged', PATH, None, + Gio.DBusSignalFlags.NONE, on_signal) +bus.signal_subscribe('org.freedesktop.DBus', 'org.freedesktop.DBus', 'NameOwnerChanged', '/org/freedesktop/DBus', + BUS_NAME, Gio.DBusSignalFlags.NONE, on_signal) # Feishin started / quit +GLib.timeout_add_seconds(HEARTBEAT_S, lambda: send(force=True)) # overlay recovers after restarts +send(force=True) +print('watching Feishin ->', URL, flush=True) +GLib.MainLoop().run() diff --git a/tools/nowplaying/heystreamer-nowplaying.service b/tools/nowplaying/heystreamer-nowplaying.service new file mode 100644 index 0000000..3bf58c5 --- /dev/null +++ b/tools/nowplaying/heystreamer-nowplaying.service @@ -0,0 +1,13 @@ +# systemd user unit: copy to ~/.config/systemd/user/, then +# systemctl --user daemon-reload && systemctl --user enable --now heystreamer-nowplaying +[Unit] +Description=Feishin now-playing -> HeyStreamer overlay +After=graphical-session.target + +[Service] +ExecStart=/usr/bin/python3 %h/projects/heystreamer/tools/nowplaying/feishin_nowplaying.py +Restart=always +RestartSec=10 + +[Install] +WantedBy=default.target