| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402 |
- """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, PLAY_POS, PLAYLIST = range(10)
- _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 _first_tags(pairs):
- song = {}
- for key, value in pairs:
- song.setdefault(key.lower(), value) # first value of each tag
- return song
- def queue_entry(song):
- duration = _float(song.get("duration"), -1.0)
- if duration < 0:
- duration = _float(song.get("time"), -1.0)
- artist, title = song.get("artist"), song.get("title")
- if not (artist and title):
- artist = title = None
- return st.QueueEntry(artist, title, format_title(song), int(duration))
- def parse_playlistinfo(pairs):
- """Songs as QueueEntry; each starts at its "file" line"""
- songs, cur = [], None
- for key, value in pairs:
- if key == "file":
- if cur is not None:
- songs.append(queue_entry(_first_tags(cur)))
- cur = []
- if cur is not None:
- cur.append((key, value))
- if cur is not None:
- songs.append(queue_entry(_first_tags(cur)))
- return songs
- 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
- self.want_playlist = False # keep state.playlist current
- # 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:
- if self.want_playlist:
- self._send("playlistinfo", self._on_playlist)
- 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:
- changed = () if isinstance(result, ServerError) else [v for k, v in result]
- if self.want_playlist and "playlist" in changed:
- self._send("playlistinfo", self._on_playlist)
- self._queue_refresh()
- def _on_playlist(self, result):
- if isinstance(result, ServerError):
- self.log("MPD: %s" % result)
- return
- if self.want_playlist:
- self.state.playlist = parse_playlistinfo(result)
- self.changed()
- 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 = _first_tags(result)
- if song:
- s.title = format_title(song)
- self.changed()
- def command(self, cmd, arg=None):
- """arg: the queue position for PLAY_POS"""
- if not self.conn:
- self.log("Brak połączenia z MPD")
- return
- try:
- self._leave_idle()
- if cmd == PLAYLIST:
- self._send("playlistinfo", self._on_playlist)
- else:
- line = "play %d" % arg if cmd == PLAY_POS else _COMMANDS.get(cmd)
- if line:
- self._send(line, self._on_command)
- self._queue_refresh()
- except ConnectionLost as e:
- self._drop(str(e))
- def follow_playlist(self, on):
- """While on, state.playlist is fetched now and kept current"""
- self.want_playlist = on
- self.state.playlist = None
- if on and self.conn:
- self.command(PLAYLIST)
- 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
|