"""MPD connection on the GLib main loop. The connection sits in "idle", so changes arrive as events instead of being polled; a command first leaves idle, does its work and goes back. Commands are synchronous with a timeout, like libmpdclient's. Reconnects every 3 s. """ import socket from gi.repository import GLib from . import state as st CONNECT_TIMEOUT_S = 2.0 RECONNECT_S = 3 IDLE_SUBSYSTEMS = "playlist player mixer options" PLAY, TOGGLE, STOP, NEXT, PREV, VOLUME_UP, VOLUME_DOWN, REFRESH = range(8) _COMMANDS = { PLAY: "play", TOGGLE: "pause", STOP: "stop", NEXT: "next", PREV: "previous", VOLUME_UP: "volume +1", VOLUME_DOWN: "volume -1", } class ConnectionLost(Exception): pass class ServerError(Exception): """ACK from the server: the command was refused, the session goes on""" def _ack_message(line): # ACK [error@command_listNum] {current_command} message_text brace = line.find("} ") return line[brace + 2:] if brace >= 0 else line def format_title(song): artist, title, name = song.get("artist"), song.get("title"), song.get("name") uri = song.get("file", "") if artist and title: return "%s - %s" % (artist, title) if title and name: # a stream announcing what it plays return "%s: %s" % (name, title) if title or name: return title or name slash = uri.rfind("/") if slash >= 0 and slash + 1 < len(uri) and "://" not in uri: return uri[slash + 1:] return uri class Connection(object): """Blocking line protocol; any socket trouble raises ConnectionLost""" def __init__(self, host, port): if host.startswith("/"): self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.settimeout(CONNECT_TIMEOUT_S) try: self.sock.connect(host) except (OSError, socket.timeout): self.sock.close() raise else: self.sock = socket.create_connection((host, port), CONNECT_TIMEOUT_S) self.sock.settimeout(CONNECT_TIMEOUT_S) self.buf = b"" try: hello = self.read_line() except ConnectionLost: self.close() raise if not hello.startswith("OK MPD "): self.close() raise ConnectionLost("not an MPD server") def fileno(self): return self.sock.fileno() def close(self): try: self.sock.close() except OSError: pass def send(self, line): try: self.sock.sendall(line.encode("utf-8") + b"\n") except (OSError, socket.timeout) as e: raise ConnectionLost(str(e) or "write failed") def read_line(self): while b"\n" not in self.buf: try: chunk = self.sock.recv(4096) except socket.timeout: raise ConnectionLost("timeout") except OSError as e: raise ConnectionLost(str(e)) if not chunk: raise ConnectionLost("connection closed") self.buf += chunk line, self.buf = self.buf.split(b"\n", 1) return line.decode("utf-8", "replace") def read_response(self): """Lines up to OK, as (key, value) pairs; ACK raises ServerError""" pairs = [] while True: line = self.read_line() if line == "OK": return pairs if line.startswith("ACK "): raise ServerError(_ack_message(line)) key, sep, value = line.partition(": ") if sep: pairs.append((key, value)) def command(self, line): self.send(line) return self.read_response() class MpdClient(object): """changed() is called whenever state may have changed; log(text) notes events""" def __init__(self, host, port, state, changed, log): self.host, self.port = host, port self.state = state self.changed = changed self.log = log self.conn = None self.watch_id = 0 self.was_connected = False # not directly: the owner must finish construction first self.retry_id = GLib.idle_add(self._try_connect) def close(self): if self.watch_id: GLib.source_remove(self.watch_id) self.watch_id = 0 if self.retry_id: GLib.source_remove(self.retry_id) self.retry_id = 0 if self.conn: self.conn.close() self.conn = None # ---- connection --------------------------------------------------------- def _drop(self, why): if self.watch_id: GLib.source_remove(self.watch_id) self.watch_id = 0 if self.conn: self.conn.close() self.conn = None self.state.connected = False if self.was_connected and why: self.log("MPD: %s" % why) self.was_connected = False if not self.retry_id: self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect) self.changed() def _try_connect(self): self.retry_id = 0 try: self.conn = Connection(self.host, self.port) except (OSError, socket.timeout, ConnectionLost): self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect) return False self.state.connected = True self.was_connected = True self.log("Połączono z MPD: %s" % self.host) if self._run(self._refresh): self.watch_id = GLib.io_add_watch( self.conn.fileno(), GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, self._on_readable) self._enter_idle() return False def _run(self, fn, *args): """Call fn; True if the connection survived it""" try: fn(*args) except ServerError as e: self.log("MPD: %s" % e) except ConnectionLost as e: self._drop(str(e)) return False return True def _enter_idle(self): if self.conn: try: self.conn.send("idle " + IDLE_SUBSYSTEMS) except ConnectionLost as e: self._drop(str(e)) def _on_readable(self, fd, cond): if cond & (GLib.IO_HUP | GLib.IO_ERR): self.watch_id = 0 self._drop("connection closed") return False # the idle response: "changed: ..." lines, then OK if not self._run(self.conn.read_response): return False # _drop() removed this watch if not self._run(self._refresh): return False self._enter_idle() return self.conn is not None # ---- state ---------------------------------------------------------------- def _refresh(self): s = self.state status = dict(self.conn.command("status")) s.state = {"play": st.PLAY_PLAYING, "pause": st.PLAY_PAUSED, "stop": st.PLAY_STOPPED}.get(status.get("state"), st.PLAY_UNKNOWN) s.song_pos = _int(status.get("song"), -1) s.queue_len = _int(status.get("playlistlength"), 0) elapsed_s, total_s = 0.0, 0 time_field = status.get("time", "") if ":" in time_field: a, b = time_field.split(":", 1) elapsed_s, total_s = _float(a, 0.0), _int(b, 0) if "elapsed" in status: elapsed_s = _float(status["elapsed"], elapsed_s) if not total_s and "duration" in status: total_s = int(_float(status["duration"], 0.0)) s.elapsed_ms = int(elapsed_s * 1000) s.elapsed_stamp_ms = st.monotonic_ms() s.total_ms = total_s * 1000 s.volume = _int(status.get("volume"), -1) s.repeat = status.get("repeat") == "1" s.random = status.get("random") == "1" s.title = "" # as the firmware: a stopped player shows no title if s.state != st.PLAY_STOPPED: song = {} for key, value in self.conn.command("currentsong"): song.setdefault(key.lower(), value) # first value of each tag if song: s.title = format_title(song) self.changed() def command(self, cmd): if not self.conn: self.log("Brak połączenia z MPD") return # leave idle; any event it reports is covered by the refresh below try: self.conn.send("noidle") self.conn.read_response() except ServerError: pass except ConnectionLost as e: self._drop(str(e)) return line = _COMMANDS.get(cmd) if line and not self._run(self.conn.command, line): return if self._run(self._refresh): self._enter_idle() def _int(text, default): try: return int(text) except (TypeError, ValueError): return default def _float(text, default): try: return float(text) except (TypeError, ValueError): return default