"""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. Only the handshake blocks: commands are pipelined and their responses handled as they arrive, so a slow server (a song opening from a sleeping NFS disk) never stalls the UI. Reconnects every 3 s. """ import collections import socket from gi.repository import GLib from . import state as st CONNECT_TIMEOUT_S = 2.0 # how long the server may sit on an answer before the connection is given up; # libmpdclient's default, as next/play wait until the new song is open RESPONSE_TIMEOUT_S = 30 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): """Line protocol; any socket trouble raises ConnectionLost. The handshake reads blocking (with a timeout); afterwards read_lines() is called only when the socket is readable, so it never waits.""" 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 _recv(self): 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 def read_line(self): while b"\n" not in self.buf: self._recv() line, self.buf = self.buf.split(b"\n", 1) return line.decode("utf-8", "replace") def read_lines(self): """One read from a readable socket: the complete lines it finished""" self._recv() *lines, self.buf = self.buf.split(b"\n") return [line.decode("utf-8", "replace") for line in lines] 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.timeout_id = 0 self.was_connected = False # one handler per request sent and not yet answered, oldest first; # each gets the response's (key, value) pairs, or a ServerError self.pending = collections.deque() self.pairs = [] self.idling = False # "idle" sent and no "noidle" after it yet # not directly: the owner must finish construction first self.retry_id = GLib.idle_add(self._try_connect) def close(self): for attr in ("watch_id", "retry_id", "timeout_id"): if getattr(self, attr): GLib.source_remove(getattr(self, attr)) setattr(self, attr, 0) if self.conn: self.conn.close() self.conn = None # ---- connection --------------------------------------------------------- def _drop(self, why): for attr in ("watch_id", "timeout_id"): if getattr(self, attr): GLib.source_remove(getattr(self, attr)) setattr(self, attr, 0) if self.conn: self.conn.close() self.conn = None self.pending.clear() self.pairs = [] self.idling = False 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) 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) try: self._queue_refresh() except ConnectionLost as e: self._drop(str(e)) return False # ---- requests ----------------------------------------------------------- def _send(self, line, handler): """Raises ConnectionLost""" self.conn.send(line) self.pending.append(handler) self._arm_timeout() def _arm_timeout(self): if self.timeout_id: GLib.source_remove(self.timeout_id) self.timeout_id = 0 # only an answer to a command is owed; idle may wait forever if self.pending and not (self.idling and len(self.pending) == 1): self.timeout_id = GLib.timeout_add_seconds(RESPONSE_TIMEOUT_S, self._on_timeout) def _on_timeout(self): self.timeout_id = 0 self._drop("timeout") return False def _leave_idle(self): # if the idle answer is already on its way the server ignores this, # so either way exactly one response comes back for the idle if self.idling: self.idling = False self.conn.send("noidle") def _enter_idle(self): self._send("idle " + IDLE_SUBSYSTEMS, self._on_idle) self.idling = True self._arm_timeout() def _queue_refresh(self): self._send("status", self._on_status) self._send("currentsong", self._on_song) def _on_readable(self, fd, cond): if cond & (GLib.IO_HUP | GLib.IO_ERR): self.watch_id = 0 self._drop("connection closed") return False try: for line in self.conn.read_lines(): self._on_line(line) if self.conn and not self.pending: self._enter_idle() except ConnectionLost as e: self._drop(str(e)) return self.conn is not None def _on_line(self, line): if line == "OK": result = self.pairs elif line.startswith("ACK "): result = ServerError(_ack_message(line)) else: key, sep, value = line.partition(": ") if sep: self.pairs.append((key, value)) return self.pairs = [] if not self.pending: raise ConnectionLost("unexpected response") handler = self.pending.popleft() self._arm_timeout() handler(result) # ---- responses ---------------------------------------------------------- def _on_command(self, result): if isinstance(result, ServerError): self.log("MPD: %s" % result) def _on_idle(self, result): self.idling = False # left for a command: the refresh queued after it covers any change if not self.pending: self._queue_refresh() def _on_status(self, result): if isinstance(result, ServerError): self.log("MPD: %s" % result) return s = self.state status = dict(result) 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" def _on_song(self, result): s = self.state s.title = "" # as the firmware: a stopped player shows no title if not isinstance(result, ServerError) and s.state != st.PLAY_STOPPED: song = {} for key, value in result: 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 try: self._leave_idle() line = _COMMANDS.get(cmd) if line: self._send(line, self._on_command) self._queue_refresh() except ConnectionLost as e: self._drop(str(e)) 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