mpd.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. Commands are
  4. synchronous with a timeout, like libmpdclient's. Reconnects every 3 s.
  5. """
  6. import socket
  7. from gi.repository import GLib
  8. from . import state as st
  9. CONNECT_TIMEOUT_S = 2.0
  10. RECONNECT_S = 3
  11. IDLE_SUBSYSTEMS = "playlist player mixer options"
  12. PLAY, TOGGLE, STOP, NEXT, PREV, VOLUME_UP, VOLUME_DOWN, REFRESH = range(8)
  13. _COMMANDS = {
  14. PLAY: "play",
  15. TOGGLE: "pause",
  16. STOP: "stop",
  17. NEXT: "next",
  18. PREV: "previous",
  19. VOLUME_UP: "volume +1",
  20. VOLUME_DOWN: "volume -1",
  21. }
  22. class ConnectionLost(Exception):
  23. pass
  24. class ServerError(Exception):
  25. """ACK from the server: the command was refused, the session goes on"""
  26. def _ack_message(line):
  27. # ACK [error@command_listNum] {current_command} message_text
  28. brace = line.find("} ")
  29. return line[brace + 2:] if brace >= 0 else line
  30. def format_title(song):
  31. artist, title, name = song.get("artist"), song.get("title"), song.get("name")
  32. uri = song.get("file", "")
  33. if artist and title:
  34. return "%s - %s" % (artist, title)
  35. if title and name: # a stream announcing what it plays
  36. return "%s: %s" % (name, title)
  37. if title or name:
  38. return title or name
  39. slash = uri.rfind("/")
  40. if slash >= 0 and slash + 1 < len(uri) and "://" not in uri:
  41. return uri[slash + 1:]
  42. return uri
  43. class Connection(object):
  44. """Blocking line protocol; any socket trouble raises ConnectionLost"""
  45. def __init__(self, host, port):
  46. if host.startswith("/"):
  47. self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  48. self.sock.settimeout(CONNECT_TIMEOUT_S)
  49. try:
  50. self.sock.connect(host)
  51. except (OSError, socket.timeout):
  52. self.sock.close()
  53. raise
  54. else:
  55. self.sock = socket.create_connection((host, port), CONNECT_TIMEOUT_S)
  56. self.sock.settimeout(CONNECT_TIMEOUT_S)
  57. self.buf = b""
  58. try:
  59. hello = self.read_line()
  60. except ConnectionLost:
  61. self.close()
  62. raise
  63. if not hello.startswith("OK MPD "):
  64. self.close()
  65. raise ConnectionLost("not an MPD server")
  66. def fileno(self):
  67. return self.sock.fileno()
  68. def close(self):
  69. try:
  70. self.sock.close()
  71. except OSError:
  72. pass
  73. def send(self, line):
  74. try:
  75. self.sock.sendall(line.encode("utf-8") + b"\n")
  76. except (OSError, socket.timeout) as e:
  77. raise ConnectionLost(str(e) or "write failed")
  78. def read_line(self):
  79. while b"\n" not in self.buf:
  80. try:
  81. chunk = self.sock.recv(4096)
  82. except socket.timeout:
  83. raise ConnectionLost("timeout")
  84. except OSError as e:
  85. raise ConnectionLost(str(e))
  86. if not chunk:
  87. raise ConnectionLost("connection closed")
  88. self.buf += chunk
  89. line, self.buf = self.buf.split(b"\n", 1)
  90. return line.decode("utf-8", "replace")
  91. def read_response(self):
  92. """Lines up to OK, as (key, value) pairs; ACK raises ServerError"""
  93. pairs = []
  94. while True:
  95. line = self.read_line()
  96. if line == "OK":
  97. return pairs
  98. if line.startswith("ACK "):
  99. raise ServerError(_ack_message(line))
  100. key, sep, value = line.partition(": ")
  101. if sep:
  102. pairs.append((key, value))
  103. def command(self, line):
  104. self.send(line)
  105. return self.read_response()
  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.was_connected = False
  116. # not directly: the owner must finish construction first
  117. self.retry_id = GLib.idle_add(self._try_connect)
  118. def close(self):
  119. if self.watch_id:
  120. GLib.source_remove(self.watch_id)
  121. self.watch_id = 0
  122. if self.retry_id:
  123. GLib.source_remove(self.retry_id)
  124. self.retry_id = 0
  125. if self.conn:
  126. self.conn.close()
  127. self.conn = None
  128. # ---- connection ---------------------------------------------------------
  129. def _drop(self, why):
  130. if self.watch_id:
  131. GLib.source_remove(self.watch_id)
  132. self.watch_id = 0
  133. if self.conn:
  134. self.conn.close()
  135. self.conn = None
  136. self.state.connected = False
  137. if self.was_connected and why:
  138. self.log("MPD: %s" % why)
  139. self.was_connected = False
  140. if not self.retry_id:
  141. self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect)
  142. self.changed()
  143. def _try_connect(self):
  144. self.retry_id = 0
  145. try:
  146. self.conn = Connection(self.host, self.port)
  147. except (OSError, socket.timeout, ConnectionLost):
  148. self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect)
  149. return False
  150. self.state.connected = True
  151. self.was_connected = True
  152. self.log("Połączono z MPD: %s" % self.host)
  153. if self._run(self._refresh):
  154. self.watch_id = GLib.io_add_watch(
  155. self.conn.fileno(), GLib.PRIORITY_DEFAULT,
  156. GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, self._on_readable)
  157. self._enter_idle()
  158. return False
  159. def _run(self, fn, *args):
  160. """Call fn; True if the connection survived it"""
  161. try:
  162. fn(*args)
  163. except ServerError as e:
  164. self.log("MPD: %s" % e)
  165. except ConnectionLost as e:
  166. self._drop(str(e))
  167. return False
  168. return True
  169. def _enter_idle(self):
  170. if self.conn:
  171. try:
  172. self.conn.send("idle " + IDLE_SUBSYSTEMS)
  173. except ConnectionLost as e:
  174. self._drop(str(e))
  175. def _on_readable(self, fd, cond):
  176. if cond & (GLib.IO_HUP | GLib.IO_ERR):
  177. self.watch_id = 0
  178. self._drop("connection closed")
  179. return False
  180. # the idle response: "changed: ..." lines, then OK
  181. if not self._run(self.conn.read_response):
  182. return False # _drop() removed this watch
  183. if not self._run(self._refresh):
  184. return False
  185. self._enter_idle()
  186. return self.conn is not None
  187. # ---- state ----------------------------------------------------------------
  188. def _refresh(self):
  189. s = self.state
  190. status = dict(self.conn.command("status"))
  191. s.state = {"play": st.PLAY_PLAYING, "pause": st.PLAY_PAUSED,
  192. "stop": st.PLAY_STOPPED}.get(status.get("state"), st.PLAY_UNKNOWN)
  193. s.song_pos = _int(status.get("song"), -1)
  194. s.queue_len = _int(status.get("playlistlength"), 0)
  195. elapsed_s, total_s = 0.0, 0
  196. time_field = status.get("time", "")
  197. if ":" in time_field:
  198. a, b = time_field.split(":", 1)
  199. elapsed_s, total_s = _float(a, 0.0), _int(b, 0)
  200. if "elapsed" in status:
  201. elapsed_s = _float(status["elapsed"], elapsed_s)
  202. if not total_s and "duration" in status:
  203. total_s = int(_float(status["duration"], 0.0))
  204. s.elapsed_ms = int(elapsed_s * 1000)
  205. s.elapsed_stamp_ms = st.monotonic_ms()
  206. s.total_ms = total_s * 1000
  207. s.volume = _int(status.get("volume"), -1)
  208. s.repeat = status.get("repeat") == "1"
  209. s.random = status.get("random") == "1"
  210. s.title = ""
  211. # as the firmware: a stopped player shows no title
  212. if s.state != st.PLAY_STOPPED:
  213. song = {}
  214. for key, value in self.conn.command("currentsong"):
  215. song.setdefault(key.lower(), value) # first value of each tag
  216. if song:
  217. s.title = format_title(song)
  218. self.changed()
  219. def command(self, cmd):
  220. if not self.conn:
  221. self.log("Brak połączenia z MPD")
  222. return
  223. # leave idle; any event it reports is covered by the refresh below
  224. try:
  225. self.conn.send("noidle")
  226. self.conn.read_response()
  227. except ServerError:
  228. pass
  229. except ConnectionLost as e:
  230. self._drop(str(e))
  231. return
  232. line = _COMMANDS.get(cmd)
  233. if line and not self._run(self.conn.command, line):
  234. return
  235. if self._run(self._refresh):
  236. self._enter_idle()
  237. def _int(text, default):
  238. try:
  239. return int(text)
  240. except (TypeError, ValueError):
  241. return default
  242. def _float(text, default):
  243. try:
  244. return float(text)
  245. except (TypeError, ValueError):
  246. return default