mpd.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. """MPD connection on the GLib main loop.
  2. The connection sits in "idle", so changes arrive as events instead of being
  3. polled; a command first leaves idle, does its work and goes back. Only the
  4. handshake blocks: commands are pipelined and their responses handled as they
  5. arrive, so a slow server (a song opening from a sleeping NFS disk) never
  6. stalls the UI. Reconnects every 3 s.
  7. """
  8. import collections
  9. import socket
  10. from gi.repository import GLib
  11. from . import state as st
  12. CONNECT_TIMEOUT_S = 2.0
  13. # how long the server may sit on an answer before the connection is given up;
  14. # libmpdclient's default, as next/play wait until the new song is open
  15. RESPONSE_TIMEOUT_S = 30
  16. RECONNECT_S = 3
  17. IDLE_SUBSYSTEMS = "playlist player mixer options"
  18. PLAY, TOGGLE, STOP, NEXT, PREV, VOLUME_UP, VOLUME_DOWN, REFRESH = range(8)
  19. _COMMANDS = {
  20. PLAY: "play",
  21. TOGGLE: "pause",
  22. STOP: "stop",
  23. NEXT: "next",
  24. PREV: "previous",
  25. VOLUME_UP: "volume +1",
  26. VOLUME_DOWN: "volume -1",
  27. }
  28. class ConnectionLost(Exception):
  29. pass
  30. class ServerError(Exception):
  31. """ACK from the server: the command was refused, the session goes on"""
  32. def _ack_message(line):
  33. # ACK [error@command_listNum] {current_command} message_text
  34. brace = line.find("} ")
  35. return line[brace + 2:] if brace >= 0 else line
  36. def format_title(song):
  37. artist, title, name = song.get("artist"), song.get("title"), song.get("name")
  38. uri = song.get("file", "")
  39. if artist and title:
  40. return "%s - %s" % (artist, title)
  41. if title and name: # a stream announcing what it plays
  42. return "%s: %s" % (name, title)
  43. if title or name:
  44. return title or name
  45. slash = uri.rfind("/")
  46. if slash >= 0 and slash + 1 < len(uri) and "://" not in uri:
  47. return uri[slash + 1:]
  48. return uri
  49. class Connection(object):
  50. """Line protocol; any socket trouble raises ConnectionLost.
  51. The handshake reads blocking (with a timeout); afterwards read_lines() is
  52. called only when the socket is readable, so it never waits."""
  53. def __init__(self, host, port):
  54. if host.startswith("/"):
  55. self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  56. self.sock.settimeout(CONNECT_TIMEOUT_S)
  57. try:
  58. self.sock.connect(host)
  59. except (OSError, socket.timeout):
  60. self.sock.close()
  61. raise
  62. else:
  63. self.sock = socket.create_connection((host, port), CONNECT_TIMEOUT_S)
  64. self.sock.settimeout(CONNECT_TIMEOUT_S)
  65. self.buf = b""
  66. try:
  67. hello = self.read_line()
  68. except ConnectionLost:
  69. self.close()
  70. raise
  71. if not hello.startswith("OK MPD "):
  72. self.close()
  73. raise ConnectionLost("not an MPD server")
  74. def fileno(self):
  75. return self.sock.fileno()
  76. def close(self):
  77. try:
  78. self.sock.close()
  79. except OSError:
  80. pass
  81. def send(self, line):
  82. try:
  83. self.sock.sendall(line.encode("utf-8") + b"\n")
  84. except (OSError, socket.timeout) as e:
  85. raise ConnectionLost(str(e) or "write failed")
  86. def _recv(self):
  87. try:
  88. chunk = self.sock.recv(4096)
  89. except socket.timeout:
  90. raise ConnectionLost("timeout")
  91. except OSError as e:
  92. raise ConnectionLost(str(e))
  93. if not chunk:
  94. raise ConnectionLost("connection closed")
  95. self.buf += chunk
  96. def read_line(self):
  97. while b"\n" not in self.buf:
  98. self._recv()
  99. line, self.buf = self.buf.split(b"\n", 1)
  100. return line.decode("utf-8", "replace")
  101. def read_lines(self):
  102. """One read from a readable socket: the complete lines it finished"""
  103. self._recv()
  104. *lines, self.buf = self.buf.split(b"\n")
  105. return [line.decode("utf-8", "replace") for line in lines]
  106. class MpdClient(object):
  107. """changed() is called whenever state may have changed; log(text) notes events"""
  108. def __init__(self, host, port, state, changed, log):
  109. self.host, self.port = host, port
  110. self.state = state
  111. self.changed = changed
  112. self.log = log
  113. self.conn = None
  114. self.watch_id = 0
  115. self.timeout_id = 0
  116. self.was_connected = False
  117. # one handler per request sent and not yet answered, oldest first;
  118. # each gets the response's (key, value) pairs, or a ServerError
  119. self.pending = collections.deque()
  120. self.pairs = []
  121. self.idling = False # "idle" sent and no "noidle" after it yet
  122. # not directly: the owner must finish construction first
  123. self.retry_id = GLib.idle_add(self._try_connect)
  124. def close(self):
  125. for attr in ("watch_id", "retry_id", "timeout_id"):
  126. if getattr(self, attr):
  127. GLib.source_remove(getattr(self, attr))
  128. setattr(self, attr, 0)
  129. if self.conn:
  130. self.conn.close()
  131. self.conn = None
  132. # ---- connection ---------------------------------------------------------
  133. def _drop(self, why):
  134. for attr in ("watch_id", "timeout_id"):
  135. if getattr(self, attr):
  136. GLib.source_remove(getattr(self, attr))
  137. setattr(self, attr, 0)
  138. if self.conn:
  139. self.conn.close()
  140. self.conn = None
  141. self.pending.clear()
  142. self.pairs = []
  143. self.idling = False
  144. self.state.connected = False
  145. if self.was_connected and why:
  146. self.log("MPD: %s" % why)
  147. self.was_connected = False
  148. if not self.retry_id:
  149. self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect)
  150. self.changed()
  151. def _try_connect(self):
  152. self.retry_id = 0
  153. try:
  154. self.conn = Connection(self.host, self.port)
  155. except (OSError, socket.timeout, ConnectionLost):
  156. self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect)
  157. return False
  158. self.state.connected = True
  159. self.was_connected = True
  160. self.log("Połączono z MPD: %s" % self.host)
  161. self.watch_id = GLib.io_add_watch(
  162. self.conn.fileno(), GLib.PRIORITY_DEFAULT,
  163. GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, self._on_readable)
  164. try:
  165. self._queue_refresh()
  166. except ConnectionLost as e:
  167. self._drop(str(e))
  168. return False
  169. # ---- requests -----------------------------------------------------------
  170. def _send(self, line, handler):
  171. """Raises ConnectionLost"""
  172. self.conn.send(line)
  173. self.pending.append(handler)
  174. self._arm_timeout()
  175. def _arm_timeout(self):
  176. if self.timeout_id:
  177. GLib.source_remove(self.timeout_id)
  178. self.timeout_id = 0
  179. # only an answer to a command is owed; idle may wait forever
  180. if self.pending and not (self.idling and len(self.pending) == 1):
  181. self.timeout_id = GLib.timeout_add_seconds(RESPONSE_TIMEOUT_S,
  182. self._on_timeout)
  183. def _on_timeout(self):
  184. self.timeout_id = 0
  185. self._drop("timeout")
  186. return False
  187. def _leave_idle(self):
  188. # if the idle answer is already on its way the server ignores this,
  189. # so either way exactly one response comes back for the idle
  190. if self.idling:
  191. self.idling = False
  192. self.conn.send("noidle")
  193. def _enter_idle(self):
  194. self._send("idle " + IDLE_SUBSYSTEMS, self._on_idle)
  195. self.idling = True
  196. self._arm_timeout()
  197. def _queue_refresh(self):
  198. self._send("status", self._on_status)
  199. self._send("currentsong", self._on_song)
  200. def _on_readable(self, fd, cond):
  201. if cond & (GLib.IO_HUP | GLib.IO_ERR):
  202. self.watch_id = 0
  203. self._drop("connection closed")
  204. return False
  205. try:
  206. for line in self.conn.read_lines():
  207. self._on_line(line)
  208. if self.conn and not self.pending:
  209. self._enter_idle()
  210. except ConnectionLost as e:
  211. self._drop(str(e))
  212. return self.conn is not None
  213. def _on_line(self, line):
  214. if line == "OK":
  215. result = self.pairs
  216. elif line.startswith("ACK "):
  217. result = ServerError(_ack_message(line))
  218. else:
  219. key, sep, value = line.partition(": ")
  220. if sep:
  221. self.pairs.append((key, value))
  222. return
  223. self.pairs = []
  224. if not self.pending:
  225. raise ConnectionLost("unexpected response")
  226. handler = self.pending.popleft()
  227. self._arm_timeout()
  228. handler(result)
  229. # ---- responses ----------------------------------------------------------
  230. def _on_command(self, result):
  231. if isinstance(result, ServerError):
  232. self.log("MPD: %s" % result)
  233. def _on_idle(self, result):
  234. self.idling = False
  235. # left for a command: the refresh queued after it covers any change
  236. if not self.pending:
  237. self._queue_refresh()
  238. def _on_status(self, result):
  239. if isinstance(result, ServerError):
  240. self.log("MPD: %s" % result)
  241. return
  242. s = self.state
  243. status = dict(result)
  244. s.state = {"play": st.PLAY_PLAYING, "pause": st.PLAY_PAUSED,
  245. "stop": st.PLAY_STOPPED}.get(status.get("state"), st.PLAY_UNKNOWN)
  246. s.song_pos = _int(status.get("song"), -1)
  247. s.queue_len = _int(status.get("playlistlength"), 0)
  248. elapsed_s, total_s = 0.0, 0
  249. time_field = status.get("time", "")
  250. if ":" in time_field:
  251. a, b = time_field.split(":", 1)
  252. elapsed_s, total_s = _float(a, 0.0), _int(b, 0)
  253. if "elapsed" in status:
  254. elapsed_s = _float(status["elapsed"], elapsed_s)
  255. if not total_s and "duration" in status:
  256. total_s = int(_float(status["duration"], 0.0))
  257. s.elapsed_ms = int(elapsed_s * 1000)
  258. s.elapsed_stamp_ms = st.monotonic_ms()
  259. s.total_ms = total_s * 1000
  260. s.volume = _int(status.get("volume"), -1)
  261. s.repeat = status.get("repeat") == "1"
  262. s.random = status.get("random") == "1"
  263. def _on_song(self, result):
  264. s = self.state
  265. s.title = ""
  266. # as the firmware: a stopped player shows no title
  267. if not isinstance(result, ServerError) and s.state != st.PLAY_STOPPED:
  268. song = {}
  269. for key, value in result:
  270. song.setdefault(key.lower(), value) # first value of each tag
  271. if song:
  272. s.title = format_title(song)
  273. self.changed()
  274. def command(self, cmd):
  275. if not self.conn:
  276. self.log("Brak połączenia z MPD")
  277. return
  278. try:
  279. self._leave_idle()
  280. line = _COMMANDS.get(cmd)
  281. if line:
  282. self._send(line, self._on_command)
  283. self._queue_refresh()
  284. except ConnectionLost as e:
  285. self._drop(str(e))
  286. def _int(text, default):
  287. try:
  288. return int(text)
  289. except (TypeError, ValueError):
  290. return default
  291. def _float(text, default):
  292. try:
  293. return float(text)
  294. except (TypeError, ValueError):
  295. return default