|
|
@@ -1,9 +1,12 @@
|
|
|
"""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.
|
|
|
+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
|
|
|
@@ -11,6 +14,9 @@ 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"
|
|
|
|
|
|
@@ -57,7 +63,10 @@ def format_title(song):
|
|
|
|
|
|
|
|
|
class Connection(object):
|
|
|
- """Blocking line protocol; any socket trouble raises ConnectionLost"""
|
|
|
+ """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("/"):
|
|
|
@@ -96,36 +105,28 @@ class Connection(object):
|
|
|
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:
|
|
|
- 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
|
|
|
+ self._recv()
|
|
|
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()
|
|
|
+ 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):
|
|
|
@@ -138,17 +139,21 @@ class MpdClient(object):
|
|
|
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):
|
|
|
- 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
|
|
|
+ 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
|
|
|
@@ -156,12 +161,16 @@ class MpdClient(object):
|
|
|
# ---- connection ---------------------------------------------------------
|
|
|
|
|
|
def _drop(self, why):
|
|
|
- if self.watch_id:
|
|
|
- GLib.source_remove(self.watch_id)
|
|
|
- self.watch_id = 0
|
|
|
+ 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)
|
|
|
@@ -181,49 +190,102 @@ class MpdClient(object):
|
|
|
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"""
|
|
|
+ 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:
|
|
|
- fn(*args)
|
|
|
- except ServerError as e:
|
|
|
- self.log("MPD: %s" % e)
|
|
|
+ self._queue_refresh()
|
|
|
except ConnectionLost as e:
|
|
|
self._drop(str(e))
|
|
|
- return False
|
|
|
- return True
|
|
|
+ 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):
|
|
|
- if self.conn:
|
|
|
- try:
|
|
|
- self.conn.send("idle " + IDLE_SUBSYSTEMS)
|
|
|
- except ConnectionLost as e:
|
|
|
- self._drop(str(e))
|
|
|
+ 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
|
|
|
- # 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()
|
|
|
+ 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
|
|
|
|
|
|
- # ---- state ----------------------------------------------------------------
|
|
|
-
|
|
|
- def _refresh(self):
|
|
|
+ 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(self.conn.command("status"))
|
|
|
+ status = dict(result)
|
|
|
|
|
|
s.state = {"play": st.PLAY_PLAYING, "pause": st.PLAY_PAUSED,
|
|
|
"stop": st.PLAY_STOPPED}.get(status.get("state"), st.PLAY_UNKNOWN)
|
|
|
@@ -245,11 +307,13 @@ class MpdClient(object):
|
|
|
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 s.state != st.PLAY_STOPPED:
|
|
|
+ if not isinstance(result, ServerError) and s.state != st.PLAY_STOPPED:
|
|
|
song = {}
|
|
|
- for key, value in self.conn.command("currentsong"):
|
|
|
+ for key, value in result:
|
|
|
song.setdefault(key.lower(), value) # first value of each tag
|
|
|
if song:
|
|
|
s.title = format_title(song)
|
|
|
@@ -259,20 +323,14 @@ class MpdClient(object):
|
|
|
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
|
|
|
+ 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))
|
|
|
- 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):
|