#!/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()