v0.60.0: cliairplay fallback; rounded playlist frame; empty art is a button on hover; no black in the art window

AirPlay: when LinTunes' own sender can't connect (or airplay_backend is
"cli"), Music Assistant's cliairplay is downloaded once, refused unless
its SHA-256 matches the pinned one, and streamed through.

The playlist list gets the panels' 8 px corners. The empty album-art panel
pops up as a plain button under the cursor and sinks darker while held.
The big art window keeps the art's shape after a resize and paints the
art to cover, so it never shows a background.
This commit is contained in:
2026-10-16 23:45:55 -07:00
parent efbee5c465
commit 293d253258
8 changed files with 1121 additions and 32 deletions
+20 -1
View File
@@ -198,6 +198,16 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
(right: previous/next style, wrapping) — hit-tested on release. No (right: previous/next style, wrapping) — hit-tested on release. No
double-click. Both big windows (visualizer, album art) close on a click double-click. Both big windows (visualizer, album art) close on a click
or Esc. or Esc.
The playlist list's frame is a `sidebar.RoundedFrame` (Round 91): the
panels' 8 px corners, painted *over* the list by a mouse-transparent
overlay (window color outside the curve, then Fusion's own frame line,
`frame_color`), since a mask would be jagged. The empty art panel is a
button (click = download art) that only looks like one under the
cursor: embossed in the Library button's face on hover, sunk and darker
while held. The big art window has **no background**: it is snapped
back to the art's shape after a resize (`art_window.reshaped`, the
dimension the user dragged leads) and paints the art to *cover*, so a
shape it can't take (maximized) crops a sliver instead of showing a bar.
The library search box filters the sidebar too (Round 89): The library search box filters the sidebar too (Round 89):
`LibraryView.search_changed` → `PlaylistTree.set_filter`, same rule as `LibraryView.search_changed` → `PlaylistTree.set_filter`, same rule as
the songs (every word, case-folded, in the name); a folder shows when its the songs (every word, case-folded, in the name); a folder shows when its
@@ -873,7 +883,16 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
the WiiM. `use_compat`: config.json's `airplay_protocol` "auto" = the the WiiM. `use_compat`: config.json's `airplay_protocol` "auto" = the
native sender for everything but Apple's own hardware (a HomePod is native sender for everything but Apple's own hardware (a HomePod is
AirPlay 2 only), "1" = native everywhere, "2" = pyatv's AirPlay 2; AirPlay 2 only), "1" = native everywhere, "2" = pyatv's AirPlay 2;
`airplay_latency_ms` overrides the 2 s. `airplay_debug` puts pyatv's and `airplay_latency_ms` overrides the 2 s. **cliairplay is the fallback**
(Round 91, trav's go-ahead): when the native sender can't connect, or
config.json's `airplay_backend` is `"cli"` (`"native"` = never fall
back), `cli.ensure_binary` downloads Music Assistant's pinned release
into `$XDG_DATA_HOME/lintunes/bin/` once and **refuses it unless its
SHA-256 matches** the one pinned in `cli.py` — then `CliAirPlaySink`
runs ffmpeg → cliairplay per stretch of playback (commands on a fifo,
`[STATUS]` lines back on stderr; `started at_unix_ms` / `playing
elapsed_ms` give the position). Bumping its version means new pinned
hashes from that release's SHA256SUMS. `airplay_debug` puts pyatv's and
`lintunes.airplay.raop`'s loggers at DEBUG (every RTSP request); every `lintunes.airplay.raop`'s loggers at DEBUG (every RTSP request); every
stream's start, first audio and outcome are logged at INFO under stream's start, first audio and outcome are logged at INFO under
`lintunes.airplay`, and the chosen sender in the control log. `lintunes.airplay`, and the chosen sender in the control log.
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux.""" """LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.59.0" __version__ = "0.60.0"
+217
View File
@@ -0,0 +1,217 @@
"""cliairplay: Music Assistant's AirPlay sender, run as a helper process.
pyatv's own stream is accepted by a WiiM (Linkplay) speaker — every request
answered 200, timing exchanged, volume set — and nothing comes out, in AirPlay
1 and 2 alike (Round 88). cliairplay, the same speaker, plays. So it streams
for LinTunes wherever it runs, and pyatv stays for discovery (and as the
fallback where the helper can't be had).
The binary is never committed or pip-installed: it is downloaded once, from
the release pinned here, and checked against the release's SHA-256 before it
is ever run (the yt-dlp/fpcalc "runtime tool" rule, minus the package
manager, since no distribution ships it). GPL-3.0, and run as a separate
process — LinTunes only talks to it: audio as raw PCM on stdin, commands on a
named pipe, `[STATUS]` lines back on stderr.
Everything here is pure or plain file/network I/O, no Qt.
"""
import contextlib
import hashlib
import os
import platform
import re
import secrets
import tempfile
import urllib.request
from pathlib import Path
VERSION = "0.5.4"
_RELEASE = ("https://github.com/music-assistant/airplay-cli/releases/download/"
f"v{VERSION}/")
# From the release's SHA256SUMS.
_SHA256 = {
"x86_64": "1ac56a15fb548f07a1dae94be16d4bea308420a0ec0cd04238023e44345fc1c9",
"aarch64": "1ce9160a8a9abb1b2263dfbf5ed59551dd1205b2336a024e9e33c903c201a310",
}
_ARCH_ALIASES = {"amd64": "x86_64", "arm64": "aarch64"}
DOWNLOAD_TIMEOUT_S = 60
class CliUnavailable(RuntimeError):
"""The helper can't be had here (platform, network, checksum)."""
def _arch() -> str | None:
if platform.system() != "Linux":
return None
machine = platform.machine().lower()
machine = _ARCH_ALIASES.get(machine, machine)
return machine if machine in _SHA256 else None
def binary_dir() -> Path:
"""Machine-local: a binary for this CPU, never the synced data dir."""
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser(
"~/.local/share")
return Path(base) / "lintunes" / "bin"
def binary_path() -> Path | None:
arch = _arch()
if arch is None:
return None
return binary_dir() / f"cliairplay-{VERSION}-{arch}"
def supported() -> bool:
return _arch() is not None
def installed() -> Path | None:
"""The verified binary, if it's already on disk."""
path = binary_path()
if path is not None and path.is_file() and os.access(path, os.X_OK):
return path
return None
def _sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def ensure_binary(fetch=None) -> Path:
"""The helper's path, downloading and verifying it first if needed.
Blocking (a few MB): callers run it off the GUI thread. `fetch(url)`
returns the bytes; it's injectable so tests never touch the network.
"""
path = installed()
if path is not None:
return path
arch = _arch()
if arch is None:
raise CliUnavailable(
f"no AirPlay helper for {platform.system()} {platform.machine()}")
fetch = fetch or _fetch
name = f"cliairplay-linux-{arch}"
try:
data = fetch(_RELEASE + name)
except Exception as e: # noqa: BLE001 — reported, not raised raw
raise CliUnavailable(f"couldn't download the AirPlay helper ({e})")
if _sha256(data) != _SHA256[arch]:
raise CliUnavailable("the downloaded AirPlay helper failed its checksum")
path = binary_path()
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".cliairplay-")
try:
with os.fdopen(fd, "wb") as out:
out.write(data)
os.chmod(tmp, 0o755)
os.replace(tmp, path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp)
raise
return path
def _fetch(url: str) -> bytes:
with urllib.request.urlopen(url, timeout=DOWNLOAD_TIMEOUT_S) as response:
return response.read()
# ---- the command line ----
# RAOP TXT keys the binary takes as their own flags (Music Assistant's set).
_RAOP_FLAGS = ("et", "md", "am", "pk", "pw", "cn")
def txt_blob(properties: dict) -> str:
"""The `_airplay._tcp` TXT as cliairplay's --txt: space-separated
key=value, skipping pairs with whitespace (the binary splits on spaces)."""
pairs = []
for key, value in (properties or {}).items():
if value is None:
continue
key, value = str(key), str(value)
if any(c.isspace() for c in key + value):
continue
pairs.append(f"{key}={value}")
return " ".join(pairs)
def protocol_arg(choice: str) -> str:
"""config.json's `airplay_protocol` → cliairplay's --protocol. "auto"
lets the binary pick from the TXT, as Music Assistant does."""
return {"1": "airplay2-compat", "2": "airplay2"}.get(choice, "auto")
def build_args(binary: str, host: str, port: int, raop: dict, airplay: dict,
pipe: str, volume: float, choice: str = "auto",
name: str = "") -> list[str]:
"""argv for one stream. `raop`/`airplay` are the TXT properties of the
device's _raop._tcp and _airplay._tcp services ({} when absent)."""
args = [binary, "--protocol", protocol_arg(choice),
"--dacp", secrets.token_hex(8).upper(),
"--activeremote", str(secrets.randbelow(2**32)),
"--cmdpipe", pipe,
"--samplerate", "44100", "--bitdepth", "16",
"--port", str(port),
"--volume", str(round(max(0.0, min(100.0, volume)))),
"--debug", "1"]
for key in _RAOP_FLAGS:
value = (raop or {}).get(key)
if value:
args += [f"--{key}", str(value)]
# Some receivers (the WiiM) advertise their AirPlay 2 feature bits only on
# _raop's `ft`; route selection reads them from --txt either way.
txt = dict(airplay or {})
if not (txt.get("features") or txt.get("ft")) and (raop or {}).get("ft"):
txt["ft"] = raop["ft"]
blob = txt_blob(txt)
if blob:
args += ["--txt", blob]
if name and airplay:
args += ["--name", name]
return args + [host]
# ---- what it says ----
_STATUS = re.compile(r"^\[STATUS\]\s+(\w+)\s*(.*)$")
_FIELD = re.compile(r'(\w+)=("([^"]*)"|\S+)')
def parse_status(line: str) -> tuple[str, dict] | None:
"""`[STATUS] playing elapsed_ms=1203` → ("playing", {"elapsed_ms": "1203"}).
Anything that isn't a status line is None."""
match = _STATUS.match(line.strip())
if match is None:
return None
fields = {}
for key, raw, quoted in _FIELD.findall(match.group(2)):
fields[key] = quoted if raw.startswith('"') else raw
return match.group(1), fields
def metadata_command(title: str, artist: str, album: str, duration_s: int,
artwork_file: str | None = None) -> str:
"""Now-playing for the receiver. Newlines would end a field early."""
def clean(value):
return " ".join(str(value or "").split())
lines = [f"TITLE={clean(title)}", f"ARTIST={clean(artist)}",
f"ALBUM={clean(album)}", f"DURATION={max(0, int(duration_s))}"]
if artwork_file:
lines.append(f"ARTWORKFILE={artwork_file}")
lines.append("ACTION=SENDMETA")
return "\n".join(lines) + "\n"
def start_command(at_unix_ms: int) -> str:
return f"START_UNIX_MS={int(at_unix_ms)}\nACTION=START\n"
def volume_command(percent: float) -> str:
return f"VOLUME={round(max(0.0, min(100.0, percent)))}\n"
+453
View File
@@ -0,0 +1,453 @@
"""The Player sink that plays through an AirPlay speaker via cliairplay.
Same contract as sink.AirPlaySink — one stream per stretch of playback, a
generation per stream so a replaced one can't advance the queue — but each
stream is two processes: ffmpeg decoding the song from the position (s16le
on its stdout) straight into cliairplay's stdin, and cliairplay talking to
the speaker. A daemon thread per stream owns both, writes the command pipe
and reads `[STATUS]` lines; what it learns comes back as Qt signals.
What the statuses mean (measured against shairport-sync, and the WiiM):
`connected` → send the now-playing and START; `started at_unix_ms=` is when
the first sample is *heard*, and `playing elapsed_ms=` (about once a second)
how far the listener is since then — so position needs no latency guess.
`eof` comes when the song has played out (stopping right then cut nothing),
and the binary then holds the session until told ACTION=STOP.
"""
import logging
import os
import shutil
import subprocess
import tempfile
import threading
import time
from PyQt6.QtCore import QTimer, pyqtSignal
from PyQt6.QtMultimedia import QAudio
from lintunes import tagging
from lintunes.airplay import cli
from lintunes.airplay.sink import (
DECODE_ERROR, DROPPED, FAILED, FINISHED, jpeg_artwork)
from lintunes.airplay.support import (
can_stream, ffmpeg_command, level_to_percent, unstreamable_reason)
from lintunes.player import PlaybackSink
log = logging.getLogger("lintunes.airplay")
CONNECT_TIMEOUT_S = 15.0
STOP_GRACE_S = 1.0
START_LEAD_MS = 300
def now_ms() -> int:
return int(time.time() * 1000)
class CliStream:
"""One song from one position, on its own thread. Never touches Qt:
`report(kind, fields)` and `ended(outcome, detail)` are called from the
thread and must be thread-safe (the sink passes signal emits)."""
def __init__(self, binary, target: dict, path: str, start_ms: int,
volume: float, metadata: str, report, ended, workdir: str):
self.binary = str(binary)
self.target = target
self.path = path
self.start_ms = start_ms
self.volume = volume
self.metadata = metadata
self._report = report
self._ended = ended
self._workdir = workdir
self._stop = threading.Event()
self._connected = threading.Event()
self._eof = threading.Event()
self._lock = threading.Lock()
self._pipe = None # the command pipe, once open
self._error = ""
self._last_line = ""
self.thread = threading.Thread(target=self._run, daemon=True,
name="airplay-stream")
def start(self):
self.thread.start()
def stop(self):
"""Ask the stream to end; returns at once (the thread tears down)."""
self._stop.set()
def send(self, command: str):
"""A command for the binary; dropped if the pipe isn't open yet."""
with self._lock:
if self._pipe is None:
return False
try:
os.write(self._pipe, command.encode())
return True
except OSError:
return False
# ---- the thread ----
def _run(self):
fifo = os.path.join(self._workdir, f"cmd-{id(self)}.pipe")
decoder = player = None
try:
os.mkfifo(fifo)
decoder = subprocess.Popen(
ffmpeg_command(self.path, self.start_ms, 44100, 2, 2,
big_endian=False),
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
t = self.target
player = subprocess.Popen(
cli.build_args(self.binary, t["host"], t["port"], t["raop"],
t["airplay"], fifo, self.volume,
t.get("choice", "auto"), t.get("name", "")),
stdin=decoder.stdout, stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE, text=True, errors="replace")
decoder.stdout.close() # the binary holds the only read end
reader = threading.Thread(target=self._read, args=(player,),
daemon=True)
reader.start()
outcome, detail = self._drive(player, decoder, fifo)
except Exception as e: # noqa: BLE001 — reported, never raised
outcome, detail = FAILED, str(e) or type(e).__name__
finally:
self._teardown(player, decoder, fifo)
self._ended(outcome, detail)
def _drive(self, player, decoder, fifo):
deadline = time.monotonic() + CONNECT_TIMEOUT_S
while not self._connected.wait(0.05):
if self._stop.is_set():
return None, ""
if player.poll() is not None:
return FAILED, self._error or self._last_line or "it closed"
if time.monotonic() > deadline:
return FAILED, "it didn't answer"
self._open_pipe(fifo, player)
if self.metadata:
self.send(self.metadata)
self.send(cli.start_command(now_ms() + START_LEAD_MS))
while not self._stop.is_set():
if self._eof.wait(0.1):
code = decoder.wait()
if code != 0 and not self._heard_any:
message = decoder.stderr.read().decode(
errors="replace").strip().splitlines()
return DECODE_ERROR, (message[-1] if message
else f"ffmpeg exited with {code}")
return FINISHED, ""
if player.poll() is not None:
return DROPPED, self._error or self._last_line
return None, ""
_heard_any = False
def _open_pipe(self, fifo, player):
"""The binary opens its end once connected; never block on it."""
while not self._stop.is_set() and player.poll() is None:
try:
fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK)
except OSError:
time.sleep(0.02)
continue
os.set_blocking(fd, True)
with self._lock:
self._pipe = fd
return
def _read(self, player):
for line in player.stderr:
line = line.rstrip()
if not line:
continue
parsed = cli.parse_status(line)
if parsed is None:
if "rror" in line:
self._last_line = line
continue
kind, fields = parsed
if kind == "connected":
self._connected.set()
elif kind == "eof":
self._eof.set()
elif kind == "playing":
self._heard_any = True
elif kind == "error":
self._error = fields.get("detail") or fields.get("code", "")
if kind in ("started", "playing", "connected", "error"):
self._report(kind, fields)
def _teardown(self, player, decoder, fifo):
if player is not None and player.poll() is None:
self.send("ACTION=STOP\n")
try:
player.wait(STOP_GRACE_S)
except subprocess.TimeoutExpired:
player.terminate()
try:
player.wait(STOP_GRACE_S)
except subprocess.TimeoutExpired:
player.kill()
if decoder is not None and decoder.poll() is None:
decoder.kill()
with self._lock:
fd, self._pipe = self._pipe, None
if fd is not None:
try:
os.close(fd)
except OSError:
pass
try:
os.unlink(fifo)
except OSError:
pass
class CliAirPlaySink(PlaybackSink):
"""Streams to an AirPlay receiver through cliairplay."""
provides_pcm = False
glyph = "airplay"
listen_src = "airplay"
POLL_MS = 250
VOLUME_COALESCE_MS = 120
STOP_TIMEOUT_S = 3.0
_status = pyqtSignal(int, str, object) # generation, kind, fields
_stream_ended = pyqtSignal(int, str, str) # generation, outcome, detail
stream_class = CliStream # tests swap in a fake
def __init__(self, binary, target: dict, name: str, parent=None):
super().__init__(parent)
self._binary = binary
self._target = dict(target, name=name)
self.name = name or "AirPlay"
self._workdir = tempfile.mkdtemp(prefix="lintunes-airplay-")
self._track = None
self._metadata = ""
self._stream: CliStream | None = None
self._generation = 0
self._playing = False
self._start_ms = 0
self._anchor_ms: int | None = None # unix ms when start_ms is heard
self._position_ms = 0
self._duration_ms = 0
self._percent = 0.0
self._first_logged = False
self._shutdown_done = False
self._dying = False
self._status.connect(self._on_status)
self._stream_ended.connect(self._on_stream_ended)
self._poll = QTimer(self)
self._poll.setInterval(self.POLL_MS)
self._poll.timeout.connect(self._on_poll)
self._volume_timer = QTimer(self)
self._volume_timer.setSingleShot(True)
self._volume_timer.setInterval(self.VOLUME_COALESCE_MS)
self._volume_timer.timeout.connect(self._flush_volume)
# ---- PlaybackSink ----
def can_play(self, track) -> bool:
return can_stream(track.location, track.kind)
def unplayable_reason(self, track) -> str:
return unstreamable_reason(track.location, track.kind)
def load(self, track, autoplay: bool, start_ms: int):
self._track = track
self._duration_ms = track.total_time or 0
self._metadata = cli.metadata_command(
track.name, track.artist, track.album, self._duration_ms // 1000,
self._artwork_file(track))
self.duration_changed.emit(self._duration_ms)
self._set_position(max(0, start_ms))
if autoplay:
self._start_stream(self._position_ms)
else:
self._halt_stream()
self._set_playing(False)
def _artwork_file(self, track) -> str | None:
try:
data = jpeg_artwork(tagging.read_embedded_artwork(track.location))
except Exception: # noqa: BLE001 — art is never worth a failure
return None
if not data:
return None
path = os.path.join(self._workdir, "cover.jpg")
try:
with open(path, "wb") as out:
out.write(data)
except OSError:
return None
return path
def play(self):
if self._track is None or self._playing:
return
self._start_stream(self._position_ms)
def pause(self):
self._freeze_position()
self._halt_stream()
self._set_playing(False)
def stop(self):
self._freeze_position()
self._halt_stream()
self._set_playing(False)
def seek(self, position_ms: int):
target = max(0, position_ms)
if self._playing:
self._start_stream(target)
else:
self._set_position(target)
def position_ms(self) -> int:
return self._position_ms
def duration_ms(self) -> int:
return self._duration_ms
def is_playing(self) -> bool:
return self._playing
def set_volume(self, level: float):
level = max(0.0, min(1.0, float(level)))
linear = QAudio.convertVolume(
level, QAudio.VolumeScale.LogarithmicVolumeScale,
QAudio.VolumeScale.LinearVolumeScale)
# cliairplay's 0–100 is pyatv's: linear across -30..0 dB.
self._percent = level_to_percent(linear)
self._volume_timer.start()
def shutdown(self):
if self._shutdown_done:
return
self._shutdown_done = True
self._poll.stop()
self._volume_timer.stop()
self._generation += 1
stream, self._stream = self._stream, None
if stream is not None:
stream.stop()
stream.thread.join(self.STOP_TIMEOUT_S)
shutil.rmtree(self._workdir, ignore_errors=True)
# ---- streams ----
def _start_stream(self, start_ms: int):
if self._shutdown_done or self._dying or self._track is None:
return
self._generation += 1
generation = self._generation
if self._stream is not None:
self._stream.stop()
log.info("stream %d: %s from %d ms (cliairplay)", generation,
self._track.name or self._track.location, start_ms)
self._start_ms = start_ms
self._anchor_ms = None
self._first_logged = False
self._stream = self.stream_class(
self._binary, self._target, self._track.location, start_ms,
self._percent, self._metadata,
lambda kind, fields: self._status.emit(generation, kind, fields),
lambda outcome, detail: self._stream_ended.emit(
generation, outcome or "", detail or ""),
self._workdir)
self._set_position(start_ms)
self._set_playing(True)
self._poll.start()
self._stream.start()
def _halt_stream(self):
self._generation += 1
self._poll.stop()
stream, self._stream = self._stream, None
if stream is not None:
stream.stop()
def _freeze_position(self):
if self._stream is not None:
self._set_position(self._heard())
def _heard(self) -> int:
if self._anchor_ms is None:
return self._start_ms
played = max(0, now_ms() - self._anchor_ms)
position = self._start_ms + played
if self._duration_ms:
position = min(position, self._duration_ms)
return position
def _on_status(self, generation: int, kind: str, fields: dict):
if generation != self._generation:
return
if kind == "started":
try:
self._anchor_ms = int(fields.get("at_unix_ms", 0)) or None
except ValueError:
self._anchor_ms = None
elif kind == "playing":
try:
self._anchor_ms = now_ms() - int(fields.get("elapsed_ms", 0))
except ValueError:
pass
if not self._first_logged:
self._first_logged = True
log.info("stream %d: playing", generation)
def _on_poll(self):
if self._stream is not None:
self._set_position(self._heard())
def _on_stream_ended(self, generation: int, outcome: str, detail: str):
if outcome:
log.info("stream %d ended: %s %s", generation, outcome, detail)
if (generation != self._generation or self._shutdown_done
or not outcome):
return
self._stream = None
self._poll.stop()
if outcome == FINISHED:
self._set_position(self._duration_ms or self._position_ms)
self._set_playing(False)
self.ended.emit()
elif outcome == DECODE_ERROR:
self._set_playing(False)
self.error.emit(f"it couldn't be decoded ({detail})")
elif outcome == DROPPED:
self._fail(f"{self.name} stopped playing — something else may "
"have taken it over.")
else:
self._fail(f"Lost {self.name} ({detail}).")
def _fail(self, reason: str):
if self._dying:
return
self._dying = True
self._poll.stop()
self.unavailable.emit(reason)
def _flush_volume(self):
if self._stream is not None:
self._stream.send(cli.volume_command(self._percent))
def _set_playing(self, playing: bool):
if playing != self._playing:
self._playing = playing
self.state_changed.emit(playing)
def _set_position(self, position_ms: int):
self._position_ms = position_ms
self.position_changed.emit(position_ms)
+53 -17
View File
@@ -121,19 +121,33 @@ class AirPlayController(QObject):
from lintunes.airplay.stream import install_shim from lintunes.airplay.stream import install_shim
install_shim() install_shim()
if compat and raop is not None: if compat and raop is not None:
# LinTunes' own RAOP sender (raop.py): what third-party speakers backend = str(config.get("airplay_backend") or "auto").lower()
# play. pyatv only found the device. if backend != "cli":
from lintunes.airplay.raop import ( try:
DEFAULT_LATENCY_MS, NativeDevice, RaopClient) return await self._connect_native(conf, device, raop,
latency = config.get("airplay_latency_ms") or DEFAULT_LATENCY_MS model, choice, config)
except (ConnectionError, OSError, asyncio.TimeoutError) as e:
native_error = str(e) or type(e).__name__
log_control("airplay", "native failed",
f"{device.name}: {native_error}")
if backend == "native":
raise
from lintunes.airplay import cli
if not cli.supported():
raise ConnectionError(
"LinTunes' AirPlay sender couldn't connect, and "
"cliairplay isn't available for this computer")
# Downloaded once, verified against its pinned SHA-256 before it
# ever runs (cli.ensure_binary); blocking, so off the loop.
binary = await loop.run_in_executor(None, cli.ensure_binary)
airplay = conf.get_service(Protocol.AirPlay)
log_control("airplay", "protocol", log_control("airplay", "protocol",
f"{device.name} ({model}): native RAOP, " f"{device.name} ({model}): cliairplay {cli.VERSION}")
f"{latency} ms buffer (airplay_protocol={choice})") return {"cli": binary, "target": {
native = NativeDevice(RaopClient( "host": str(conf.address), "port": raop.port,
str(conf.address), raop.port, dict(raop.properties), "raop": dict(raop.properties),
latency_ms=int(latency))) "airplay": dict(airplay.properties) if airplay else {},
await asyncio.wait_for(native.connect(), CONNECT_TIMEOUT_S) "choice": "auto"}}
return native
settings.protocols.raop.protocol_version = ( settings.protocols.raop.protocol_version = (
{"2": AirPlayVersion.V2}.get(choice, AirPlayVersion.Auto)) {"2": AirPlayVersion.V2}.get(choice, AirPlayVersion.Auto))
if raop is not None: if raop is not None:
@@ -146,18 +160,40 @@ class AirPlayController(QObject):
pyatv.connect(raop_only(conf), loop, storage=storage), pyatv.connect(raop_only(conf), loop, storage=storage),
CONNECT_TIMEOUT_S) CONNECT_TIMEOUT_S)
@staticmethod
async def _connect_native(conf, device, raop, model, choice, config):
"""LinTunes' own RAOP sender (raop.py): what third-party speakers
play. pyatv only found the device."""
import asyncio
from lintunes.airplay.raop import (
DEFAULT_LATENCY_MS, NativeDevice, RaopClient)
latency = config.get("airplay_latency_ms") or DEFAULT_LATENCY_MS
log_control("airplay", "protocol",
f"{device.name} ({model}): native RAOP, "
f"{latency} ms buffer (airplay_protocol={choice})")
native = NativeDevice(RaopClient(
str(conf.address), raop.port, dict(raop.properties),
latency_ms=int(latency)))
await asyncio.wait_for(native.connect(), CONNECT_TIMEOUT_S)
return native
def _on_connect_result(self, result: dict, attempt: int): def _on_connect_result(self, result: dict, attempt: int):
atv = result.get("atv")
via_cli = isinstance(atv, dict)
if attempt != self._attempt: if attempt != self._attempt:
atv = result.get("atv") if atv is not None and not via_cli:
if atv is not None:
self._loop.submit(self._close(atv)) self._loop.submit(self._close(atv))
return return
if "error" in result: if "error" in result:
self.failed.emit(f"Couldn't connect: {result['error']}") self.failed.emit(f"Couldn't connect: {result['error']}")
return return
from lintunes.airplay.sink import AirPlaySink if via_cli:
self._sink = AirPlaySink(result["atv"], self._loop, result["name"], from lintunes.airplay.cli_sink import CliAirPlaySink
self) self._sink = CliAirPlaySink(atv["cli"], atv["target"],
result["name"], self)
else:
from lintunes.airplay.sink import AirPlaySink
self._sink = AirPlaySink(atv, self._loop, result["name"], self)
# Deferred a turn, as in CastController: Player's own fallback slot # Deferred a turn, as in CastController: Player's own fallback slot
# disconnects this signal mid-emission. # disconnects this signal mid-emission.
self._sink.unavailable.connect( self._sink.unavailable.connect(
+73 -8
View File
@@ -1,5 +1,5 @@
from PyQt6.QtWidgets import QWidget, QApplication from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtCore import Qt, QSize from PyQt6.QtCore import Qt, QSize, QTimer
from PyQt6.QtGui import QPainter, QPixmap from PyQt6.QtGui import QPainter, QPixmap
# Height left free for the window's own title bar. On Wayland the frame size # Height left free for the window's own title bar. On Wayland the frame size
@@ -22,6 +22,31 @@ def fit_size(art: QSize, available: QSize,
return art.scaled(room, Qt.AspectRatioMode.KeepAspectRatio) return art.scaled(room, Qt.AspectRatioMode.KeepAspectRatio)
def reshaped(art: QSize, area: QSize, previous: QSize | None,
available: QSize | None = None) -> QSize:
"""The content size with the art's shape nearest ``area``.
The dimension that changed more since ``previous`` is the one the user
meant (dragging a side edge sets the width), and the other follows; the
result stays within ``available``.
"""
if art.isEmpty() or area.isEmpty():
return area
aspect = art.width() / art.height()
width_led = True
if previous is not None and not previous.isEmpty():
width_led = (abs(area.width() - previous.width()) / previous.width()
>= abs(area.height() - previous.height()) / previous.height())
if width_led:
size = QSize(area.width(), max(1, round(area.width() / aspect)))
else:
size = QSize(max(1, round(area.height() * aspect)), area.height())
if available is not None and not available.isEmpty() and (
size.width() > available.width() or size.height() > available.height()):
size = art.scaled(available, Qt.AspectRatioMode.KeepAspectRatio)
return size
def _aspect(pixmap: QPixmap | None) -> float | None: def _aspect(pixmap: QPixmap | None) -> float | None:
if pixmap is None or pixmap.isNull() or pixmap.height() == 0: if pixmap is None or pixmap.isNull() or pixmap.height() == 0:
return None return None
@@ -32,7 +57,14 @@ class ArtWindow(QWidget):
"""Non-modal window showing the current track's album art as large as """Non-modal window showing the current track's album art as large as
possible. Just an album art window — closing it has no side effects. possible. Just an album art window — closing it has no side effects.
A click anywhere on the art (or Esc) closes it, like the big A click anywhere on the art (or Esc) closes it, like the big
visualizer.""" visualizer.
Never any background: the window keeps the art's shape (a resize is
snapped back to it once the drag pauses), and the art is painted to
*cover* the area, so even mid-drag or when the window can't be
reshaped (maximized) there is a sliver cropped, never a bar."""
RESHAPE_DELAY_MS = 150
def __init__(self, parent=None): def __init__(self, parent=None):
super().__init__(parent, Qt.WindowType.Window) super().__init__(parent, Qt.WindowType.Window)
@@ -40,6 +72,11 @@ class ArtWindow(QWidget):
self.setMinimumSize(120, 120) self.setMinimumSize(120, 120)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)
self.setToolTip("Click to close") self.setToolTip("Click to close")
self._settled: QSize | None = None
self._reshape = QTimer(self)
self._reshape.setSingleShot(True)
self._reshape.setInterval(self.RESHAPE_DELAY_MS)
self._reshape.timeout.connect(self._snap_to_art)
def show_artwork(self, pixmap: QPixmap | None, title: str, screen=None): def show_artwork(self, pixmap: QPixmap | None, title: str, screen=None):
"""Open (or re-raise) the window, sized to the art on ``screen``.""" """Open (or re-raise) the window, sized to the art on ``screen``."""
@@ -57,7 +94,7 @@ class ArtWindow(QWidget):
self._pixmap = pixmap self._pixmap = pixmap
if reshape: if reshape:
# A track change brought a different shape of cover: re-fit, or # A track change brought a different shape of cover: re-fit, or
# the new art would sit between black bars. # the new art would be cropped.
self.fit_to_screen() self.fit_to_screen()
self.update() self.update()
@@ -71,20 +108,48 @@ class ArtWindow(QWidget):
size = fit_size(self._pixmap.size(), geo.size()) size = fit_size(self._pixmap.size(), geo.size())
# The app-drawn title bar (gui/titlebar.py) sits inside the window. # The app-drawn title bar (gui/titlebar.py) sits inside the window.
margins = self.contentsMargins() margins = self.contentsMargins()
self.resize(size.width(), size.height() + margins.top()) self._settled = size
self.resize(size.width() + margins.left() + margins.right(),
size.height() + margins.top() + margins.bottom())
# Wayland ignores move() (the compositor places the window); X11 # Wayland ignores move() (the compositor places the window); X11
# honors it. # honors it.
self.move(geo.x() + (geo.width() - size.width()) // 2, self.move(geo.x() + (geo.width() - size.width()) // 2,
geo.y() + (geo.height() - size.height()) // 2) geo.y() + (geo.height() - size.height()) // 2)
def resizeEvent(self, event):
super().resizeEvent(event)
self._reshape.start()
def _snap_to_art(self):
if (self._pixmap is None or self._pixmap.isNull()
or self.isMaximized() or self.isFullScreen()):
return
area = self.contentsRect().size()
screen = self.screen() or QApplication.primaryScreen()
room = None
if screen is not None:
geo = screen.availableGeometry().size()
margins = self.contentsMargins()
room = QSize(geo.width() - margins.left() - margins.right(),
geo.height() - margins.top() - margins.bottom())
size = reshaped(self._pixmap.size(), area, self._settled, room)
self._settled = size
if abs(size.width() - area.width()) > 1 or abs(
size.height() - area.height()) > 1:
margins = self.contentsMargins()
self.resize(size.width() + margins.left() + margins.right(),
size.height() + margins.top() + margins.bottom())
def paintEvent(self, event): def paintEvent(self, event):
painter = QPainter(self)
area = self.contentsRect()
painter.fillRect(area, Qt.GlobalColor.black)
if self._pixmap is None or self._pixmap.isNull(): if self._pixmap is None or self._pixmap.isNull():
return return
painter = QPainter(self)
area = self.contentsRect()
painter.setClipRect(area)
# Cover, not fit: the window has the art's shape, so this crops at
# most a rounding pixel — and never leaves a bar.
scaled = self._pixmap.scaled( scaled = self._pixmap.scaled(
area.size(), Qt.AspectRatioMode.KeepAspectRatio, area.size(), Qt.AspectRatioMode.KeepAspectRatioByExpanding,
Qt.TransformationMode.SmoothTransformation) Qt.TransformationMode.SmoothTransformation)
x = area.x() + (area.width() - scaled.width()) // 2 x = area.x() + (area.width() - scaled.width()) // 2
y = area.y() + (area.height() - scaled.height()) // 2 y = area.y() + (area.height() - scaled.height()) // 2
+102 -5
View File
@@ -5,7 +5,7 @@ from PyQt6.QtWidgets import (
QFrame, QFrame,
) )
from PyQt6.QtCore import Qt, QTimer, QPoint, QRectF, pyqtSignal from PyQt6.QtCore import Qt, QTimer, QPoint, QRectF, pyqtSignal
from PyQt6.QtGui import QBrush, QPainter, QPalette, QPixmap from PyQt6.QtGui import QBrush, QColor, QPainter, QPalette, QPixmap
from lintunes.models import PlaylistType from lintunes.models import PlaylistType
from lintunes import tagging, theme from lintunes import tagging, theme
@@ -77,18 +77,16 @@ class SidebarPanel(QWidget):
top.header_owner = self top.header_owner = self
# The playlists in their frame; the album art panel sits below it. # The playlists in their frame; the album art panel sits below it.
group = QFrame() group = RoundedFrame(NO_ART_RADIUS)
self._lists = QStackedWidget() self._lists = QStackedWidget()
self.tree = PlaylistTree(manager) self.tree = PlaylistTree(manager)
self._lists.addWidget(self.tree) self._lists.addWidget(self.tree)
self.friend_list = FriendPlaylistList() self.friend_list = FriendPlaylistList()
self._lists.addWidget(self.friend_list) self._lists.addWidget(self.friend_list)
group.setFrameShape(self.tree.frameShape())
group.setFrameShadow(self.tree.frameShadow())
for view in (self.tree, self.friend_list): for view in (self.tree, self.friend_list):
view.setFrameShape(QFrame.Shape.NoFrame) view.setFrameShape(QFrame.Shape.NoFrame)
inner = QVBoxLayout(group) inner = QVBoxLayout(group)
inner.setContentsMargins(0, 0, 0, 0) inner.setContentsMargins(1, 1, 1, 1)
inner.setSpacing(0) inner.setSpacing(0)
inner.addWidget(self._lists, stretch=1) inner.addWidget(self._lists, stretch=1)
self.art = SidebarArt(player) self.art = SidebarArt(player)
@@ -259,6 +257,58 @@ NO_ART_GAP = 6
NO_ART_RADIUS = 8 NO_ART_RADIUS = 8
def frame_color(palette) -> QColor:
"""Fusion's own frame line (its outline, lightened as PE_Frame does), so
a frame drawn here matches the ones the style draws."""
return palette.color(QPalette.ColorRole.Window).darker(140).lighter(108)
class RoundedFrame(QFrame):
"""A list's frame with rounded corners: the panels' radius, not Fusion's
square one. The list fills it edge to edge, so the corners are painted
*over* it by a mouse-transparent overlay — window color outside the
curve, then the frame line — which keeps them antialiased where a mask
would be jagged."""
def __init__(self, radius: float, parent=None):
super().__init__(parent)
self.setFrameShape(QFrame.Shape.NoFrame)
self._overlay = _FrameOverlay(self, radius)
def resizeEvent(self, event):
super().resizeEvent(event)
self._overlay.setGeometry(self.rect())
self._overlay.raise_()
def childEvent(self, event):
super().childEvent(event)
overlay = getattr(self, "_overlay", None)
if overlay is not None and event.added():
overlay.raise_()
class _FrameOverlay(QWidget):
def __init__(self, parent, radius: float):
super().__init__(parent)
self.radius = radius
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)
def paintEvent(self, event):
from PyQt6.QtGui import QPainterPath, QPen
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
curve = QPainterPath()
curve.addRoundedRect(rect, self.radius, self.radius)
outside = QPainterPath()
outside.addRect(QRectF(self.rect()))
painter.fillPath(outside.subtracted(curve),
self.palette().color(QPalette.ColorRole.Window))
painter.setPen(QPen(frame_color(self.palette()), 1))
painter.drawPath(curve)
class SidebarArt(QWidget): class SidebarArt(QWidget):
"""Square album art pinned to the sidebar bottom: a panel set into the """Square album art pinned to the sidebar bottom: a panel set into the
window below the playlist list's frame, like the visualizer, with the window below the playlist list's frame, like the visualizer, with the
@@ -275,6 +325,8 @@ class SidebarArt(QWidget):
self._pixmap: QPixmap | None = None self._pixmap: QPixmap | None = None
self._track = None self._track = None
self._art_window = ArtWindow() self._art_window = ArtWindow()
self._hovered = False
self._held = False
player.track_changed.connect(self.set_track) player.track_changed.connect(self.set_track)
def set_track(self, track): def set_track(self, track):
@@ -324,7 +376,39 @@ class SidebarArt(QWidget):
self._fit_height() self._fit_height()
super().resizeEvent(event) super().resizeEvent(event)
def _is_button(self) -> bool:
"""Empty with a track to fetch art for: the panel is a button (a
click downloads art), though it only looks like one under the
cursor."""
return self._track is not None and not self.has_art()
def enterEvent(self, event):
self._hovered = True
self.update()
super().enterEvent(event)
def leaveEvent(self, event):
self._hovered = False
self.update()
super().leaveEvent(event)
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self._held = True
self.update()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
# Held and dragged off: no longer pressed, as a button lets go.
inside = self.rect().contains(event.position().toPoint())
if inside != self._hovered:
self._hovered = inside
self.update()
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event): def mouseReleaseEvent(self, event):
self._held = False
self.update()
# A click is a release that lands on the art. Opening on press would # A click is a release that lands on the art. Opening on press would
# also fire when a drag merely starts here. # also fire when a drag merely starts here.
if (event.button() == Qt.MouseButton.LeftButton if (event.button() == Qt.MouseButton.LeftButton
@@ -344,6 +428,19 @@ class SidebarArt(QWidget):
painter = QPainter(self) painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing) painter.setRenderHint(QPainter.RenderHint.Antialiasing)
rect = QRectF(self.rect()).adjusted(0.5, NO_ART_GAP + 0.5, -0.5, -0.5) rect = QRectF(self.rect()).adjusted(0.5, NO_ART_GAP + 0.5, -0.5, -0.5)
if self._is_button() and self._hovered:
# Pops up as a plain button under the cursor (no glyph): the
# Library button's face, hover-darkened, and sunk while held.
face = self.palette().alternateBase().color()
if self._held:
theme.paint_deboss(painter, rect,
face.darker(theme.PRESSED_DARKER),
NO_ART_RADIUS, like=CONTROL_HEIGHT)
else:
theme.paint_emboss(painter, rect,
face.darker(theme.HOVER_DARKER),
NO_ART_RADIUS, like=CONTROL_HEIGHT)
return
theme.paint_deboss(painter, rect, theme.paint_deboss(painter, rect,
self.palette().alternateBase().color(), self.palette().alternateBase().color(),
NO_ART_RADIUS, like=CONTROL_HEIGHT) NO_ART_RADIUS, like=CONTROL_HEIGHT)
+202
View File
@@ -0,0 +1,202 @@
"""Round 91: the playlist frame's rounded corners, the empty art panel as a
button under the cursor, an art window with no background, and cliairplay
as the fallback AirPlay sender."""
import asyncio
import hashlib
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from PyQt6.QtCore import QEvent, QPointF, QSize, Qt
from PyQt6.QtGui import QColor, QEnterEvent, QMouseEvent, QPixmap
from PyQt6.QtWidgets import QLabel
from tests.test_round49 import _FakePlayer
# ---- the playlist frame ----
class TestRoundedFrame:
def test_corners_are_window_color_and_clicks_reach_the_list(self, qapp):
from lintunes.gui.sidebar import RoundedFrame, frame_color
frame = RoundedFrame(8)
inside = QLabel(frame)
inside.setAutoFillBackground(True)
palette = inside.palette()
palette.setColor(inside.backgroundRole(), QColor("red"))
inside.setPalette(palette)
inside.setGeometry(0, 0, 100, 100)
frame.resize(100, 100)
frame.show()
qapp.processEvents()
image = frame.grab().toImage()
window = frame.palette().color(frame.backgroundRole())
assert QColor(image.pixel(0, 0)) == QColor(window.name())
assert QColor(image.pixel(50, 50)) == QColor("red")
edge = QColor(image.pixel(50, 0))
assert abs(edge.red() - frame_color(frame.palette()).red()) < 12
assert frame._overlay.testAttribute(
Qt.WidgetAttribute.WA_TransparentForMouseEvents)
frame.close()
# ---- the empty art panel ----
def _event(kind, button=Qt.MouseButton.LeftButton, x=50, y=50):
return QMouseEvent(kind, QPointF(x, y), QPointF(x, y), button, button,
Qt.KeyboardModifier.NoModifier)
class TestEmptyArtButton:
def _art(self, track=True):
from lintunes.gui.sidebar import SidebarArt
art = SidebarArt(_FakePlayer())
art.resize(100, 106)
art._track = SimpleNamespace(track_id=1) if track else None
return art
def _middle(self, art):
return art.grab().toImage().pixelColor(50, 60)
def test_pops_up_on_hover_and_sinks_while_held(self, qapp):
art = self._art()
resting = self._middle(art)
art.enterEvent(QEnterEvent(QPointF(50, 50), QPointF(50, 50), QPointF(50, 50)))
hovered = self._middle(art)
art.mousePressEvent(_event(QEvent.Type.MouseButtonPress))
held = self._middle(art)
assert hovered != resting and held != hovered
assert held.lightness() < hovered.lightness()
art.mouseReleaseEvent(_event(QEvent.Type.MouseButtonRelease))
assert self._middle(art) == hovered
art.leaveEvent(QEvent(QEvent.Type.Leave))
assert self._middle(art) == resting
def test_no_track_or_real_art_is_never_a_button(self, qapp):
art = self._art(track=False)
resting = self._middle(art)
art.enterEvent(QEnterEvent(QPointF(50, 50), QPointF(50, 50), QPointF(50, 50)))
assert self._middle(art) == resting
assert not art._is_button()
art._track = SimpleNamespace(track_id=1)
art._pixmap = QPixmap(10, 10)
assert not art._is_button()
# ---- the big art window ----
class TestArtShape:
def test_the_dimension_that_moved_leads(self):
from lintunes.gui.art_window import reshaped
art = QSize(500, 500)
assert reshaped(art, QSize(700, 520), QSize(500, 500)) == QSize(700, 700)
assert reshaped(art, QSize(510, 300), QSize(500, 500)) == QSize(300, 300)
assert reshaped(QSize(200, 100), QSize(400, 400), None) == QSize(400, 200)
def test_stays_on_the_screen(self):
from lintunes.gui.art_window import reshaped
assert reshaped(QSize(500, 500), QSize(1500, 900), QSize(500, 500),
QSize(1920, 1000)) == QSize(1000, 1000)
def test_never_paints_a_background(self, qapp):
from lintunes.gui.art_window import ArtWindow
window = ArtWindow()
art = QPixmap(100, 100)
art.fill(QColor("red"))
window._pixmap = art
window.resize(300, 200) # the wrong shape, before the snap
image = window.grab().toImage()
for x, y in ((0, 0), (299, 199), (5, 100), (295, 100)):
assert image.pixelColor(x, y) == QColor("red")
# ---- cliairplay ----
class TestCliBinary:
def test_a_checksum_mismatch_is_never_installed(self, tmp_path, monkeypatch):
from lintunes.airplay import cli
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
monkeypatch.setattr(cli, "_arch", lambda: "x86_64")
with pytest.raises(cli.CliUnavailable):
cli.ensure_binary(fetch=lambda url: b"not the binary")
assert not any(tmp_path.rglob("cliairplay-*"))
def test_a_matching_download_is_installed_executable(self, tmp_path,
monkeypatch):
from lintunes.airplay import cli
data = b"pretend binary"
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
monkeypatch.setattr(cli, "_arch", lambda: "x86_64")
monkeypatch.setitem(cli._SHA256, "x86_64",
hashlib.sha256(data).hexdigest())
urls = []
path = cli.ensure_binary(fetch=lambda url: urls.append(url) or data)
assert path.read_bytes() == data and cli.installed() == path
assert urls == [cli._RELEASE + "cliairplay-linux-x86_64"]
assert cli.ensure_binary(fetch=lambda url: 1 / 0) == path # cached
def test_status_lines(self):
from lintunes.airplay import cli
assert cli.parse_status("[STATUS] playing elapsed_ms=1203") == (
"playing", {"elapsed_ms": "1203"})
assert cli.parse_status('[STATUS] error code=x detail="a b"') == (
"error", {"code": "x", "detail": "a b"})
assert cli.parse_status("[12:00] something") is None
def test_args_carry_the_raop_txt(self):
from lintunes.airplay import cli
args = cli.build_args("/bin/cli", "10.0.0.9", 7000,
{"et": "0,4", "md": "0,1,2", "ft": "0x1,0x2"},
{}, "/tmp/p", 50)
assert args[0] == "/bin/cli" and args[-1] == "10.0.0.9"
assert args[args.index("--et") + 1] == "0,4"
assert args[args.index("--txt") + 1] == "ft=0x1,0x2"
assert args[args.index("--volume") + 1] == "50"
class TestFallback:
def _controller(self):
from lintunes.airplay.controller import AirPlayController
controller = AirPlayController(MagicMock())
return controller
def _conf(self):
from pyatv.const import Protocol
raop = SimpleNamespace(port=7000, properties={"am": "WiiM"},
protocol=Protocol.RAOP)
conf = MagicMock(address="10.0.0.9")
conf.get_service = lambda p: raop if p == Protocol.RAOP else None
return conf
def _connect(self, controller, config, native):
from lintunes.airplay import cli, controller as module
device = SimpleNamespace(name="tiat", host="10.0.0.9", uuid="x")
with patch.object(module, "load_config", return_value=config), \
patch.object(type(controller), "_connect_native", native), \
patch.object(cli, "supported", return_value=True), \
patch.object(cli, "ensure_binary", return_value="/bin/cli"):
return asyncio.run(controller._connect(self._conf(), device))
def test_a_native_failure_falls_back_to_cliairplay(self, qapp):
async def native(*args):
raise ConnectionError("refused")
result = self._connect(self._controller(), {}, native)
assert result["cli"] == "/bin/cli"
assert result["target"]["host"] == "10.0.0.9"
assert result["target"]["port"] == 7000
def test_native_when_it_connects_and_cli_when_asked(self, qapp):
async def native(*args):
return "native device"
controller = self._controller()
assert self._connect(controller, {}, native) == "native device"
assert "cli" in self._connect(controller, {"airplay_backend": "cli"},
native)
def test_native_only_reports_the_failure(self, qapp):
async def native(*args):
raise ConnectionError("refused")
with pytest.raises(ConnectionError):
self._connect(self._controller(), {"airplay_backend": "native"},
native)