mpd.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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, PLAY_POS, PLAYLIST = range(10)
  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 _first_tags(pairs):
  37. song = {}
  38. for key, value in pairs:
  39. song.setdefault(key.lower(), value) # first value of each tag
  40. return song
  41. def queue_entry(song):
  42. duration = _float(song.get("duration"), -1.0)
  43. if duration < 0:
  44. duration = _float(song.get("time"), -1.0)
  45. artist, title = song.get("artist"), song.get("title")
  46. if not (artist and title):
  47. artist = title = None
  48. return st.QueueEntry(artist, title, format_title(song), int(duration))
  49. def parse_playlistinfo(pairs):
  50. """Songs as QueueEntry; each starts at its "file" line"""
  51. songs, cur = [], None
  52. for key, value in pairs:
  53. if key == "file":
  54. if cur is not None:
  55. songs.append(queue_entry(_first_tags(cur)))
  56. cur = []
  57. if cur is not None:
  58. cur.append((key, value))
  59. if cur is not None:
  60. songs.append(queue_entry(_first_tags(cur)))
  61. return songs
  62. def format_title(song):
  63. artist, title, name = song.get("artist"), song.get("title"), song.get("name")
  64. uri = song.get("file", "")
  65. if artist and title:
  66. return "%s - %s" % (artist, title)
  67. if title and name: # a stream announcing what it plays
  68. return "%s: %s" % (name, title)
  69. if title or name:
  70. return title or name
  71. slash = uri.rfind("/")
  72. if slash >= 0 and slash + 1 < len(uri) and "://" not in uri:
  73. return uri[slash + 1:]
  74. return uri
  75. class Connection(object):
  76. """Line protocol; any socket trouble raises ConnectionLost.
  77. The handshake reads blocking (with a timeout); afterwards read_lines() is
  78. called only when the socket is readable, so it never waits."""
  79. def __init__(self, host, port):
  80. if host.startswith("/"):
  81. self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  82. self.sock.settimeout(CONNECT_TIMEOUT_S)
  83. try:
  84. self.sock.connect(host)
  85. except (OSError, socket.timeout):
  86. self.sock.close()
  87. raise
  88. else:
  89. self.sock = socket.create_connection((host, port), CONNECT_TIMEOUT_S)
  90. self.sock.settimeout(CONNECT_TIMEOUT_S)
  91. self.buf = b""
  92. try:
  93. hello = self.read_line()
  94. except ConnectionLost:
  95. self.close()
  96. raise
  97. if not hello.startswith("OK MPD "):
  98. self.close()
  99. raise ConnectionLost("not an MPD server")
  100. def fileno(self):
  101. return self.sock.fileno()
  102. def close(self):
  103. try:
  104. self.sock.close()
  105. except OSError:
  106. pass
  107. def send(self, line):
  108. try:
  109. self.sock.sendall(line.encode("utf-8") + b"\n")
  110. except (OSError, socket.timeout) as e:
  111. raise ConnectionLost(str(e) or "write failed")
  112. def _recv(self):
  113. try:
  114. chunk = self.sock.recv(4096)
  115. except socket.timeout:
  116. raise ConnectionLost("timeout")
  117. except OSError as e:
  118. raise ConnectionLost(str(e))
  119. if not chunk:
  120. raise ConnectionLost("connection closed")
  121. self.buf += chunk
  122. def read_line(self):
  123. while b"\n" not in self.buf:
  124. self._recv()
  125. line, self.buf = self.buf.split(b"\n", 1)
  126. return line.decode("utf-8", "replace")
  127. def read_lines(self):
  128. """One read from a readable socket: the complete lines it finished"""
  129. self._recv()
  130. *lines, self.buf = self.buf.split(b"\n")
  131. return [line.decode("utf-8", "replace") for line in lines]
  132. class MpdClient(object):
  133. """changed() is called whenever state may have changed; log(text) notes events"""
  134. def __init__(self, host, port, state, changed, log):
  135. self.host, self.port = host, port
  136. self.state = state
  137. self.changed = changed
  138. self.log = log
  139. self.conn = None
  140. self.watch_id = 0
  141. self.timeout_id = 0
  142. self.was_connected = False
  143. # one handler per request sent and not yet answered, oldest first;
  144. # each gets the response's (key, value) pairs, or a ServerError
  145. self.pending = collections.deque()
  146. self.pairs = []
  147. self.idling = False # "idle" sent and no "noidle" after it yet
  148. self.want_playlist = False # keep state.playlist current
  149. # not directly: the owner must finish construction first
  150. self.retry_id = GLib.idle_add(self._try_connect)
  151. def close(self):
  152. for attr in ("watch_id", "retry_id", "timeout_id"):
  153. if getattr(self, attr):
  154. GLib.source_remove(getattr(self, attr))
  155. setattr(self, attr, 0)
  156. if self.conn:
  157. self.conn.close()
  158. self.conn = None
  159. # ---- connection ---------------------------------------------------------
  160. def _drop(self, why):
  161. for attr in ("watch_id", "timeout_id"):
  162. if getattr(self, attr):
  163. GLib.source_remove(getattr(self, attr))
  164. setattr(self, attr, 0)
  165. if self.conn:
  166. self.conn.close()
  167. self.conn = None
  168. self.pending.clear()
  169. self.pairs = []
  170. self.idling = False
  171. self.state.connected = False
  172. if self.was_connected and why:
  173. self.log("MPD: %s" % why)
  174. self.was_connected = False
  175. if not self.retry_id:
  176. self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect)
  177. self.changed()
  178. def _try_connect(self):
  179. self.retry_id = 0
  180. try:
  181. self.conn = Connection(self.host, self.port)
  182. except (OSError, socket.timeout, ConnectionLost):
  183. self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect)
  184. return False
  185. self.state.connected = True
  186. self.was_connected = True
  187. self.log("Połączono z MPD: %s" % self.host)
  188. self.watch_id = GLib.io_add_watch(
  189. self.conn.fileno(), GLib.PRIORITY_DEFAULT,
  190. GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, self._on_readable)
  191. try:
  192. if self.want_playlist:
  193. self._send("playlistinfo", self._on_playlist)
  194. self._queue_refresh()
  195. except ConnectionLost as e:
  196. self._drop(str(e))
  197. return False
  198. # ---- requests -----------------------------------------------------------
  199. def _send(self, line, handler):
  200. """Raises ConnectionLost"""
  201. self.conn.send(line)
  202. self.pending.append(handler)
  203. self._arm_timeout()
  204. def _arm_timeout(self):
  205. if self.timeout_id:
  206. GLib.source_remove(self.timeout_id)
  207. self.timeout_id = 0
  208. # only an answer to a command is owed; idle may wait forever
  209. if self.pending and not (self.idling and len(self.pending) == 1):
  210. self.timeout_id = GLib.timeout_add_seconds(RESPONSE_TIMEOUT_S,
  211. self._on_timeout)
  212. def _on_timeout(self):
  213. self.timeout_id = 0
  214. self._drop("timeout")
  215. return False
  216. def _leave_idle(self):
  217. # if the idle answer is already on its way the server ignores this,
  218. # so either way exactly one response comes back for the idle
  219. if self.idling:
  220. self.idling = False
  221. self.conn.send("noidle")
  222. def _enter_idle(self):
  223. self._send("idle " + IDLE_SUBSYSTEMS, self._on_idle)
  224. self.idling = True
  225. self._arm_timeout()
  226. def _queue_refresh(self):
  227. self._send("status", self._on_status)
  228. self._send("currentsong", self._on_song)
  229. def _on_readable(self, fd, cond):
  230. if cond & (GLib.IO_HUP | GLib.IO_ERR):
  231. self.watch_id = 0
  232. self._drop("connection closed")
  233. return False
  234. try:
  235. for line in self.conn.read_lines():
  236. self._on_line(line)
  237. if self.conn and not self.pending:
  238. self._enter_idle()
  239. except ConnectionLost as e:
  240. self._drop(str(e))
  241. return self.conn is not None
  242. def _on_line(self, line):
  243. if line == "OK":
  244. result = self.pairs
  245. elif line.startswith("ACK "):
  246. result = ServerError(_ack_message(line))
  247. else:
  248. key, sep, value = line.partition(": ")
  249. if sep:
  250. self.pairs.append((key, value))
  251. return
  252. self.pairs = []
  253. if not self.pending:
  254. raise ConnectionLost("unexpected response")
  255. handler = self.pending.popleft()
  256. self._arm_timeout()
  257. handler(result)
  258. # ---- responses ----------------------------------------------------------
  259. def _on_command(self, result):
  260. if isinstance(result, ServerError):
  261. self.log("MPD: %s" % result)
  262. def _on_idle(self, result):
  263. self.idling = False
  264. # left for a command: the refresh queued after it covers any change
  265. if not self.pending:
  266. changed = () if isinstance(result, ServerError) else [v for k, v in result]
  267. if self.want_playlist and "playlist" in changed:
  268. self._send("playlistinfo", self._on_playlist)
  269. self._queue_refresh()
  270. def _on_playlist(self, result):
  271. if isinstance(result, ServerError):
  272. self.log("MPD: %s" % result)
  273. return
  274. if self.want_playlist:
  275. self.state.playlist = parse_playlistinfo(result)
  276. self.changed()
  277. def _on_status(self, result):
  278. if isinstance(result, ServerError):
  279. self.log("MPD: %s" % result)
  280. return
  281. s = self.state
  282. status = dict(result)
  283. s.state = {"play": st.PLAY_PLAYING, "pause": st.PLAY_PAUSED,
  284. "stop": st.PLAY_STOPPED}.get(status.get("state"), st.PLAY_UNKNOWN)
  285. s.song_pos = _int(status.get("song"), -1)
  286. s.queue_len = _int(status.get("playlistlength"), 0)
  287. elapsed_s, total_s = 0.0, 0
  288. time_field = status.get("time", "")
  289. if ":" in time_field:
  290. a, b = time_field.split(":", 1)
  291. elapsed_s, total_s = _float(a, 0.0), _int(b, 0)
  292. if "elapsed" in status:
  293. elapsed_s = _float(status["elapsed"], elapsed_s)
  294. if not total_s and "duration" in status:
  295. total_s = int(_float(status["duration"], 0.0))
  296. s.elapsed_ms = int(elapsed_s * 1000)
  297. s.elapsed_stamp_ms = st.monotonic_ms()
  298. s.total_ms = total_s * 1000
  299. s.volume = _int(status.get("volume"), -1)
  300. s.repeat = status.get("repeat") == "1"
  301. s.random = status.get("random") == "1"
  302. def _on_song(self, result):
  303. s = self.state
  304. s.title = ""
  305. # as the firmware: a stopped player shows no title
  306. if not isinstance(result, ServerError) and s.state != st.PLAY_STOPPED:
  307. song = _first_tags(result)
  308. if song:
  309. s.title = format_title(song)
  310. self.changed()
  311. def command(self, cmd, arg=None):
  312. """arg: the queue position for PLAY_POS"""
  313. if not self.conn:
  314. self.log("Brak połączenia z MPD")
  315. return
  316. try:
  317. self._leave_idle()
  318. if cmd == PLAYLIST:
  319. self._send("playlistinfo", self._on_playlist)
  320. else:
  321. line = "play %d" % arg if cmd == PLAY_POS else _COMMANDS.get(cmd)
  322. if line:
  323. self._send(line, self._on_command)
  324. self._queue_refresh()
  325. except ConnectionLost as e:
  326. self._drop(str(e))
  327. def follow_playlist(self, on):
  328. """While on, state.playlist is fetched now and kept current"""
  329. self.want_playlist = on
  330. self.state.playlist = None
  331. if on and self.conn:
  332. self.command(PLAYLIST)
  333. def _int(text, default):
  334. try:
  335. return int(text)
  336. except (TypeError, ValueError):
  337. return default
  338. def _float(text, default):
  339. try:
  340. return float(text)
  341. except (TypeError, ValueError):
  342. return default