Files
2026-09-11 21:59:35 +00:00

244 lines
11 KiB
Python

from __future__ import annotations
import ipaddress
import math
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any
from urllib.parse import urlparse
import soco
from requests.exceptions import Timeout as RequestsTimeout
from soco.data_structures import DidlAudioBroadcast, to_didl_string
class SonosError(RuntimeError):
"""Expected error while communicating with Sonos."""
class SonosNotFound(SonosError):
pass
class SonosTimeout(SonosError):
pass
class SonosService:
"""Sonos access with bounded network I/O and a briefly locked zone cache.
SoCo's request timeout bounds each HTTP/SOAP request. Calls run in the request
thread, except independent zone-status reads, which use a short-lived bounded
pool and are all joined before returning. No timed-out task is abandoned in a
shared executor, and no cache lock is held while doing network I/O.
"""
STATUS_WORKERS = 8
def __init__(self, discovery_timeout: float = 5.0, operation_timeout: float = 8.0):
for name, value in (("discovery_timeout", discovery_timeout), ("operation_timeout", operation_timeout)):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
raise ValueError(f"{name} muss eine positive endliche Zahl sein.")
self.discovery_timeout = discovery_timeout
self.operation_timeout = operation_timeout
# SoCo uses this for requests made by methods and property accessors that
# do not expose a timeout keyword themselves.
soco.config.REQUEST_TIMEOUT = operation_timeout
self._cache_lock = threading.Lock()
self._discovery_lock = threading.Lock()
self._zones: dict[str, Any] = {}
def close(self) -> None:
"""Kept for the application's lifecycle hook; no persistent pool exists."""
@staticmethod
def _uid(zone: Any) -> str:
return str(zone.uid)
@staticmethod
def _communication_error(exc: Exception) -> SonosError:
if isinstance(exc, (TimeoutError, RequestsTimeout)) or "timeout" in str(exc).lower() or "timed out" in str(exc).lower():
return SonosTimeout("Das Sonos-Gerät antwortet nicht rechtzeitig.")
return SonosError(f"Sonos-Kommunikation fehlgeschlagen: {exc}")
def _call(self, operation):
try:
return operation()
except (SonosError, ValueError):
raise
except Exception as exc:
raise self._communication_error(exc) from exc
def discover(self, refresh: bool = True) -> list[Any]:
with self._cache_lock:
cached = list(self._zones.values())
if refresh or not cached:
# Serialize actual SSDP scans, but never hold the cache lock during one.
with self._discovery_lock:
with self._cache_lock:
cached = list(self._zones.values())
if refresh or not cached:
found = self._call(lambda: soco.discover(timeout=self.discovery_timeout)) or set()
discovered = {self._uid(zone): zone for zone in found}
with self._cache_lock:
self._zones = discovered
cached = list(discovered.values())
return sorted(cached, key=lambda z: str(z.player_name).casefold())
def _zone(self, uid: str) -> Any:
self.discover(refresh=False)
with self._cache_lock:
zone = self._zones.get(uid)
if zone is None:
self.discover(refresh=True)
with self._cache_lock:
zone = self._zones.get(uid)
if zone is None:
raise SonosNotFound("Die gewählte Zone wurde nicht gefunden.")
return zone
@staticmethod
def _coordinator(zone: Any) -> Any:
try:
return zone.group.coordinator
except Exception:
return zone
def _zone_status(self, zone: Any) -> dict[str, Any]:
info = zone.get_current_transport_info()
track = zone.get_current_track_info()
group = zone.group
return {
"uid": self._uid(zone), "name": zone.player_name,
"ip": str(zone.ip_address), "volume": int(zone.volume),
"bass": int(zone.bass), "treble": int(zone.treble),
"loudness": bool(zone.loudness),
"state": info.get("current_transport_state", "UNKNOWN"),
"track": {
"title": track.get("title") or "", "artist": track.get("artist") or "",
"album": track.get("album") or "", "position": track.get("position") or "",
"duration": track.get("duration") or "",
},
"coordinatorUid": self._uid(group.coordinator),
"memberUids": [self._uid(member) for member in group.members],
}
def zones(self, refresh: bool = True) -> list[dict[str, Any]]:
zones = self.discover(refresh=refresh)
if not zones:
return []
results: dict[str, dict[str, Any]] = {}
# A slow/failing player consumes at most one worker and cannot prevent
# completed peers from being returned. SoCo bounds every worker's I/O.
with ThreadPoolExecutor(max_workers=min(len(zones), self.STATUS_WORKERS),
thread_name_prefix="sonos-status") as executor:
futures = {executor.submit(self._zone_status, zone): zone for zone in zones}
for future in as_completed(futures):
zone = futures[future]
try:
results[self._uid(zone)] = future.result()
except Exception as exc:
results[self._uid(zone)] = {
"uid": self._uid(zone), "name": str(zone.player_name),
"ip": str(zone.ip_address), "state": "UNAVAILABLE",
"volume": None, "bass": None, "treble": None, "loudness": None,
"track": {}, "coordinatorUid": self._uid(zone),
"memberUids": [self._uid(zone)], "error": str(self._communication_error(exc)),
}
return [results[self._uid(zone)] for zone in zones]
def transport(self, uid: str, action: str) -> None:
if action not in {"play", "pause", "stop"}:
raise ValueError("Unbekannte Wiedergabeaktion.")
zone = self._coordinator(self._zone(uid))
self._call(lambda: getattr(zone, action)())
def set_volume(self, uid: str, volume: int) -> None:
if isinstance(volume, bool) or not isinstance(volume, int) or not 0 <= volume <= 100:
raise ValueError("Die Lautstärke muss eine ganze Zahl zwischen 0 und 100 sein.")
zone = self._zone(uid)
self._call(lambda: setattr(zone, "volume", volume))
def set_eq(self, uid: str, control: str, value: Any) -> None:
if control in {"bass", "treble"}:
if isinstance(value, bool) or not isinstance(value, int) or not -10 <= value <= 10:
raise ValueError("Bass und Höhen müssen ganze Zahlen zwischen -10 und 10 sein.")
elif control == "loudness":
if not isinstance(value, bool):
raise ValueError("Loudness muss ein boolescher Wert sein.")
else:
raise ValueError("Unbekannter Equalizer-Regler.")
zone = self._zone(uid)
self._call(lambda: setattr(zone, control, value))
def group(self, coordinator_uid: str, member_uids: list[str]) -> None:
if not member_uids:
raise ValueError("Mindestens ein Gruppenmitglied ist erforderlich.")
if coordinator_uid in member_uids:
raise ValueError("Der Coordinator darf nicht zugleich Mitglied sein.")
if len(set(member_uids)) != len(member_uids):
raise ValueError("Gruppenmitglieder dürfen nicht doppelt vorkommen.")
coordinator = self._zone(coordinator_uid)
members = [self._zone(uid) for uid in member_uids]
for member in members:
self._call(lambda member=member: member.join(coordinator))
def ungroup(self, uid: str) -> None:
self._call(self._zone(uid).unjoin)
def favorites(self, uid: str) -> list[dict[str, Any]]:
zone = self._coordinator(self._zone(uid))
items = self._call(lambda: zone.music_library.get_sonos_favorites())
return [{"index": i, "title": getattr(item, "title", str(item))} for i, item in enumerate(items)]
def queue(self, uid: str) -> list[dict[str, Any]]:
zone = self._coordinator(self._zone(uid))
items = self._call(lambda: zone.get_queue())
return [{"index": i, "title": getattr(item, "title", ""),
"creator": getattr(item, "creator", "")} for i, item in enumerate(items)]
def play_queue(self, uid: str, index: int) -> None:
if isinstance(index, bool) or not isinstance(index, int) or index < 0:
raise ValueError("Der Queue-Index ist ungültig.")
zone = self._coordinator(self._zone(uid))
count = len(self._call(lambda: zone.get_queue()))
if index >= count:
raise ValueError("Der Queue-Eintrag existiert nicht.")
self._call(lambda: zone.play_from_queue(index))
def play_favorite(self, uid: str, index: int) -> None:
if isinstance(index, bool) or not isinstance(index, int) or index < 0:
raise ValueError("Der Favoriten-Index ist ungültig.")
zone = self._coordinator(self._zone(uid))
favorites = self._call(lambda: zone.music_library.get_sonos_favorites())
if index >= len(favorites):
raise ValueError("Der Favorit existiert nicht.")
favorite = favorites[index]
try:
item = favorite.reference
resource = item.resources[0]
except (AttributeError, IndexError, TypeError) as exc:
raise SonosError("Der Favorit enthält keine abspielbare Ressource.") from exc
if isinstance(item, DidlAudioBroadcast):
self._call(lambda: zone.play_uri(resource.uri, meta=to_didl_string(item)))
else:
# AddURIToQueue supports tracks, music-service items and expandable
# containers. It returns a 1-based queue position.
queue_number = self._call(lambda: zone.add_to_queue(item))
self._call(lambda: zone.play_from_queue(queue_number - 1))
def play_stream(self, uid: str, url: str) -> None:
if not isinstance(url, str) or len(url) > 2048:
raise ValueError("Die Stream-URL ist ungültig.")
parsed = urlparse(url)
if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password:
raise ValueError("Nur vollständige http/https-Stream-URLs ohne Zugangsdaten sind erlaubt.")
try:
ip = ipaddress.ip_address(parsed.hostname)
except ValueError:
ip = None
if ip is not None and (ip.is_unspecified or ip.is_multicast):
raise ValueError("Diese Stream-Adresse ist nicht erlaubt.")
zone = self._coordinator(self._zone(uid))
self._call(lambda: zone.play_uri(url, title="Web-Stream"))