mpd.py 13 KB

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