Files
hermes-skillsharing/skills/smart-home/greysi-musik/scripts/greysi.py
T

353 lines
15 KiB
Python
Executable File

#!/usr/bin/env python3
"""Musik vom Mac per UPnP an GREYSI (Kodi, Kabel an der Anlage) schicken.
greysi play <suche|datei|ordner|url> lokal suchen (~/Music), sonst YouTube (yt-dlp), dann abspielen
greysi pause | resume | stop | status | vol <0-100>
... --auf wiim anderer Ausgang (greysi = Kodi an der Anlage, wiim = WiiM Mini); greysi ausgaenge
greysi suche <wörter> nur suchen (Mac-Musik + NAS addlove: Musik, music, Hörbücher)
greysi index Suchindex neu bauen (sonst automatisch nach 24 h)
Lokale Dateien liefert ein kleiner HTTP-Server auf diesem Mac aus (Port 8766, läuft im Hintergrund).
Läuft mit /usr/bin/python3 (Apple-signiert: darf ins Heimnetz, Homebrew-Python wurde dort schon blockiert).
"""
from __future__ import annotations
import html
import os
import re
import socket
import subprocess
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
# Ausgänge (UPnP-MediaRenderer). greysi = Kodi am Kabel zur Anlage; wiim = WiiM Mini „AddLove WiiM“.
OUTPUTS = {
"greysi": {"url": os.environ.get("GREYSI_UPNP", "http://192.168.178.80:1478/"), "tailnet": "100.64.0.6",
"name": "greysi", "words": ["greysi", "anlage", "kodi", "grey"]},
"wiim": {"url": os.environ.get("WIIM_UPNP", "http://192.168.178.88:49152/description.xml"), "tailnet": None,
"name": "WiiM", "words": ["wiim", "wim", "wii m", "wi m", "addlove"]},
}
TARGET = os.environ.get("MUSIK_ZIEL", "greysi")
def set_target(name: str) -> str:
"""Ausgang wählen (greysi | wiim). Unbekannt -> ValueError."""
global TARGET
key = name.strip().lower()
for k, o in OUTPUTS.items():
if key == k or key in o["words"]:
TARGET = k
return k
raise ValueError(f"unbekannter Ausgang {name!r}, bekannt: {', '.join(OUTPUTS)}")
def _renderer() -> tuple[str, str | None]:
o = OUTPUTS[TARGET]
return o["url"], o["tailnet"]
MUSIC = Path(os.environ.get("GREYSI_MUSIC", Path.home() / "Music/Music/Media.localized/Music"))
PORT = int(os.environ.get("GREYSI_PORT", "8766")) # 8765 belegt Hermes
STATE = Path.home() / ".cache/greysi"
# NAS mindvault-2: Freigabe addlove (Gast, nur lesen), wird bei Bedarf eingebunden
NAS_SHARE = os.environ.get("GREYSI_NAS", "//GUEST:@192.168.178.35/addlove")
NAS_DIRS = ["Musik", "music", "Hörbücher"]
INDEX_MAX_AGE_S = 24 * 3600
AUDIO = (".mp3", ".m4a", ".flac", ".wav", ".aac", ".ogg", ".opus", ".aiff")
import shutil # noqa: E402
# Mac: Homebrew; Android/Termux: `pip install yt-dlp` -> im PATH
YTDLP = shutil.which("yt-dlp") or "/opt/homebrew/bin/yt-dlp"
IS_MAC = sys.platform == "darwin"
# ---------------------------------------------------------------- UPnP
def _controls() -> tuple[str, dict[str, str]]:
base, fallback = _renderer()
try:
desc = urllib.request.urlopen(base, timeout=4).read().decode("utf-8", "replace")
except OSError:
if not fallback:
raise
base = re.sub(r"//[^:/]+", "//" + fallback, base)
desc = urllib.request.urlopen(base, timeout=4).read().decode("utf-8", "replace")
urls = {}
for st, ctl in re.findall(r"<serviceType>urn:schemas-upnp-org:service:(\w+):1</serviceType>.*?<controlURL>([^<]+)",
desc, re.S):
urls[st] = urllib.parse.urljoin(base, ctl)
return base, urls
def soap(service: str, action: str, args: dict | None = None) -> str:
_, urls = _controls()
body_args = "".join(f"<{k}>{html.escape(str(v))}</{k}>" for k, v in (args or {}).items())
st = f"urn:schemas-upnp-org:service:{service}:1"
env = ('<?xml version="1.0"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" '
's:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body>'
f'<u:{action} xmlns:u="{st}"><InstanceID>0</InstanceID>{body_args}</u:{action}></s:Body></s:Envelope>')
req = urllib.request.Request(urls[service], env.encode(), {
"Content-Type": 'text/xml; charset="utf-8"', "SOAPAction": f'"{st}#{action}"'})
try:
return urllib.request.urlopen(req, timeout=8).read().decode("utf-8", "replace")
except urllib.error.HTTPError as e:
raise SystemExit(f"UPnP {action} abgelehnt: {e.code} {e.read()[:300]!r}")
def didl(url: str, title: str) -> str:
mime = "audio/mpeg" if url.lower().endswith(".mp3") else "audio/*"
return ('<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" '
'xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/"><item id="1" parentID="0" restricted="1">'
f'<dc:title>{html.escape(title)}</dc:title><upnp:class>object.item.audioItem.musicTrack</upnp:class>'
f'<res protocolInfo="http-get:*:{mime}:*">{html.escape(url)}</res></item></DIDL-Lite>')
def send(url: str, title: str) -> None:
soap("AVTransport", "Stop") if _playing() else None
soap("AVTransport", "SetAVTransportURI", {"CurrentURI": url, "CurrentURIMetaData": didl(url, title)})
soap("AVTransport", "Play", {"Speed": 1})
def _playing() -> bool:
try:
return "PLAYING" in soap("AVTransport", "GetTransportInfo")
except SystemExit:
return False
# ---------------------------------------------------------------- HTTP für lokale Dateien
def my_ip() -> str:
host = urllib.parse.urlparse(_renderer()[0]).hostname or "192.168.178.80"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((host, 1478))
return s.getsockname()[0]
finally:
s.close()
def _ours() -> bool:
"""Antwortet auf PORT wirklich unser Server? (Marker-Datei; ein fremder Dienst auf dem Port fiel sonst nicht auf)"""
try:
return urllib.request.urlopen(f"http://127.0.0.1:{PORT}/.greysi", timeout=1).read() == b"greysi"
except OSError:
return False
def ensure_server() -> None:
STATE.mkdir(parents=True, exist_ok=True)
(STATE / "www" / ".greysi").write_bytes(b"greysi")
if _ours():
return
try:
socket.create_connection(("127.0.0.1", PORT), timeout=1).close()
raise SystemExit(f"Port {PORT} ist von einem anderen Programm belegt: GREYSI_PORT=<frei> setzen")
except OSError:
pass
log = open(STATE / "server.log", "ab")
subprocess.Popen(["/usr/bin/python3", "-m", "http.server", str(PORT), "--bind", "0.0.0.0", "--directory", str(STATE / "www")],
stdout=log, stderr=log, start_new_session=True)
for _ in range(25):
if _ours():
return
time.sleep(0.2)
raise SystemExit("HTTP-Server startet nicht, siehe ~/.cache/greysi/server.log")
def publish(files: list[Path]) -> str:
"""Dateien per Symlink freigeben; bei mehreren eine M3U-Playlist. Liefert die URL."""
www = STATE / "www"
www.mkdir(parents=True, exist_ok=True)
for old in www.iterdir():
if old.name != ".greysi":
old.unlink()
names = []
for i, f in enumerate(files):
name = f"{i:03d}{f.suffix.lower()}"
(www / name).symlink_to(f)
names.append(name)
ensure_server()
base = f"http://{my_ip()}:{PORT}/"
if len(names) == 1:
return base + names[0]
(www / "liste.m3u").write_text("#EXTM3U\n" + "".join(
f"#EXTINF:-1,{f.stem}\n{base}{n}\n" for f, n in zip(files, names)))
return base + "liste.m3u"
# ---------------------------------------------------------------- Suche
def nas_root() -> Path | None:
"""addlove-Freigabe schreibgeschützt unter ~/.cache/greysi/nas einbinden (schon eingebunden: nur prüfen)."""
mnt = STATE / "nas"
if not IS_MAC: # SMB-Einbindung nur auf dem Mac (mount_smbfs); Android spielt nur URLs/YouTube
return None
if (mnt / NAS_DIRS[0]).is_dir():
return mnt
for line in subprocess.run(["mount"], capture_output=True, text=True).stdout.splitlines():
m = re.match(r"//\S*@?192\.168\.178\.35/addlove on (.+?) \(", line)
if m and (Path(m.group(1)) / NAS_DIRS[0]).is_dir():
return Path(m.group(1))
mnt.mkdir(parents=True, exist_ok=True)
r = subprocess.run(["/sbin/mount_smbfs", "-o", "rdonly", NAS_SHARE, str(mnt)], capture_output=True, text=True,
timeout=30)
return mnt if r.returncode == 0 and (mnt / NAS_DIRS[0]).is_dir() else None
_building = {"thread": None}
def refresh_index_async() -> None:
"""Index im Hintergrund neu bauen (~2 min übers NAS), ohne einen Sprach-Turn warten zu lassen."""
import threading
t = _building["thread"]
if t is not None and t.is_alive():
return
def run():
(STATE / "index.txt").unlink(missing_ok=True)
_index()
_building["thread"] = threading.Thread(target=run, daemon=True)
_building["thread"].start()
def _index(build: bool = True) -> list[str]:
"""Alle Audio-Pfade (Mac-Musik + NAS), als Datei zwischengespeichert: das NAS per SMB zu durchlaufen dauert.
build=False (Sprachserver): veralteten Index trotzdem nutzen und im Hintergrund erneuern."""
idx = STATE / "index.txt"
if idx.exists() and time.time() - idx.stat().st_mtime < INDEX_MAX_AGE_S:
return idx.read_text().splitlines()
if not build:
refresh_index_async()
return idx.read_text().splitlines() if idx.exists() else []
roots = [MUSIC] + ([r / d for d in NAS_DIRS] if (r := nas_root()) else [])
paths = [str(p) for root in roots if root.is_dir() for p in root.rglob("*") if p.suffix.lower() in AUDIO]
STATE.mkdir(parents=True, exist_ok=True)
idx.write_text("\n".join(paths))
return paths
def local_search(q: str, build: bool = True) -> list[Path]:
"""Suche in Mac-Musik und NAS. NAS-Pfade brauchen die Einbindung: vor dem Abspielen sicherstellen."""
words = [w for w in re.split(r"\W+", q.lower()) if w]
if not words:
return []
hits = [Path(p) for p in _index(build) if all(w in p.lower().rsplit("/music/", 1)[-1] or w in Path(p).name.lower()
for w in words)]
if any(str(STATE / "nas") in str(h) for h in hits):
nas_root()
return sorted(hits)
def youtube(q_or_url: str) -> tuple[str, str]:
target = q_or_url if re.match(r"https?://", q_or_url) else f"ytsearch1:{q_or_url}"
out = subprocess.run([YTDLP, "-f", "bestaudio[ext=m4a]/bestaudio", "--no-playlist", "-g", "--get-title", target],
capture_output=True, text=True, timeout=60)
lines = [l for l in out.stdout.splitlines() if l.strip()]
if out.returncode or len(lines) < 2:
raise SystemExit("yt-dlp fand nichts: " + out.stderr[-300:])
return lines[-1], lines[0] # (direkte URL, Titel)
def play(arg: str) -> None:
p = Path(arg).expanduser()
if p.is_dir():
files = sorted(f for f in p.rglob("*") if f.suffix.lower() in AUDIO)
url, title = publish(files), p.name
elif p.is_file():
url, title = publish([p]), p.stem
elif re.match(r"https?://", arg) and not re.search(r"youtu|soundcloud|bandcamp|vimeo", arg):
url, title = arg, arg # Radiostream o. ä. direkt
elif not re.match(r"https?://", arg) and (files := local_search(arg)):
url, title = publish(files[:200]), f"{arg} ({len(files)} Titel)" if len(files) > 1 else files[0].stem
else:
url, title = youtube(arg)
send(url, title)
print(f"Spielt auf {OUTPUTS[TARGET]['name']}: {title}")
def track_title(p: Path) -> str:
"""Sprechbarer Titel aus dem Dateinamen: „04 - Adana Twins - Jumanji.mp3“ -> „Adana Twins - Jumanji“."""
t = re.sub(r"^\s*\d{1,3}\s*[-_.]?\s*", "", p.stem).replace("_", " ").strip()
return t or p.stem
def info() -> dict:
"""Zustand von GREYSI: state (PLAYING|PAUSED_PLAYBACK|STOPPED|...), title, position, duration, volume."""
t = soap("AVTransport", "GetTransportInfo")
m = html.unescape(soap("AVTransport", "GetPositionInfo"))
v = soap("RenderingControl", "GetVolume", {"Channel": "Master"})
g = lambda tag, s: (re.search(f"<{tag}>([^<]*)", s) or [None, ""])[1] # noqa: E731
title = re.search(r"<dc:title>([^<]*)", html.unescape(m))
vol = g("CurrentVolume", v)
return {"state": g("CurrentTransportState", t), "title": html.unescape(title.group(1)) if title else "",
"position": g("RelTime", m), "duration": g("TrackDuration", m),
"volume": int(vol) if vol.isdigit() else None}
def set_volume(n: int) -> int:
n = max(0, min(100, int(n)))
soap("RenderingControl", "SetVolume", {"Channel": "Master", "DesiredVolume": n})
return n
def play_files(files: list[Path], title: str) -> None:
if any(str(STATE / "nas") in str(f) for f in files):
nas_root()
send(publish(files[:200]), title)
def status() -> None:
t = soap("AVTransport", "GetTransportInfo")
m = soap("AVTransport", "GetPositionInfo")
v = soap("RenderingControl", "GetVolume", {"Channel": "Master"})
g = lambda tag, s: (re.search(f"<{tag}>([^<]*)", s) or [None, "?"])[1] # noqa: E731
title = re.search(r"dc:title&gt;([^&]*)", m) or re.search(r"<dc:title>([^<]*)", html.unescape(m))
print(f"Zustand: {g('CurrentTransportState', t)} | Titel: {title.group(1) if title else '-'} | "
f"Position: {g('RelTime', m)} / {g('TrackDuration', m)} | Lautstärke: {g('CurrentVolume', v)}")
def main(argv: list[str]) -> None:
if "--auf" in argv: # greysi play bonobo --auf wiim
i = argv.index("--auf")
set_target(argv[i + 1])
argv = argv[:i] + argv[i + 2:]
if not argv:
raise SystemExit(__doc__)
cmd, rest = argv[0], " ".join(argv[1:])
if cmd in ("index", "reindex"):
(STATE / "index.txt").unlink(missing_ok=True)
print(f"{len(_index())} Titel im Index (Mac + NAS)")
return
if cmd == "suche" and rest:
for h in local_search(rest)[:30]:
print(h)
return
if cmd == "play" and rest:
play(rest)
elif cmd == "pause":
soap("AVTransport", "Pause")
elif cmd in ("resume", "weiter"):
soap("AVTransport", "Play", {"Speed": 1})
elif cmd == "stop":
soap("AVTransport", "Stop")
elif cmd in ("vol", "volume", "lautstaerke") and rest.isdigit():
soap("RenderingControl", "SetVolume", {"Channel": "Master", "DesiredVolume": max(0, min(100, int(rest)))})
elif cmd == "status":
status()
elif cmd == "ausgaenge":
for k, o in OUTPUTS.items():
set_target(k)
try:
i = info()
print(f"{o['name']:7} {i['state']:16} {i['title'][:50]!r} Lautstärke {i['volume']}")
except Exception as e: # noqa: BLE001
print(f"{o['name']:7} nicht erreichbar ({type(e).__name__})")
return
else:
raise SystemExit(__doc__)
if cmd != "status":
time.sleep(1.5)
status()
if __name__ == "__main__":
main(sys.argv[1:])