Emacs library to communicate with Music Player Daemon (MPD, https://www.musicpd.org/), a flexible, powerful, server-side application for playing music.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1175 lines
41KB

  1. ;;; libmpdel.el --- Communication with an MPD server -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2017-2018 Damien Cassou
  3. ;; Author: Damien Cassou <damien@cassou.me>
  4. ;; Keywords: multimedia
  5. ;; Url: https://gitlab.petton.fr/mpdel/libmpdel
  6. ;; Package-requires: ((emacs "25.1"))
  7. ;; Version: 1.2.0
  8. ;; This program is free software; you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; This program is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; The package libmpdel is an Emacs library client to communicate with
  20. ;; Music Player Daemon (MPD), a flexible, powerful, server-side
  21. ;; application for playing music. For a user interface, please check
  22. ;; the mpdel project instead (which depends on this one).
  23. ;;; Code:
  24. (require 'time-stamp)
  25. (require 'tq)
  26. (require 'cl-lib)
  27. (require 'subr-x)
  28. ;;; Customization
  29. (defgroup libmpdel nil
  30. "Communication with an MPD server."
  31. :group 'comm)
  32. (defcustom libmpdel-hostname "localhost"
  33. "MPD server location to connect to. Also see `libmpdel-port'."
  34. :type 'string)
  35. (defcustom libmpdel-port 6600
  36. "MPD server port to connect to. Also see `libmpdel-hostname'."
  37. :type 'integer)
  38. (defcustom libmpdel-profiles (list (list "Local server" libmpdel-hostname libmpdel-port))
  39. "List of (HOST . PORT) when using several MPD servers."
  40. :type '(repeat (list
  41. :tag "Profile"
  42. :value ("Local server" "localhost" 6600)
  43. (string :tag "name")
  44. (string :tag "host")
  45. (integer :tag "port"))))
  46. (defcustom libmpdel-music-directory "~/Music"
  47. "MPD `music_directory' variable's value.
  48. This is used to map MPD's music files to the filesystem."
  49. :type 'directory)
  50. (defcustom libmpdel-current-playlist-changed-hook nil
  51. "Functions to call when the current playlist is modified."
  52. :type 'hook
  53. :group 'libmpdel)
  54. (defcustom libmpdel-stored-playlist-changed-hook nil
  55. "Functions to call when a stored playlist is modified."
  56. :type 'hook
  57. :group 'libmpdel)
  58. (defcustom libmpdel-player-changed-hook nil
  59. "Functions to call when the player status changes.
  60. This includes starting, stopping and seeking music."
  61. :type 'hook
  62. :group 'libmpdel)
  63. (defcustom libmpdel-current-song-changed-hook nil
  64. "Functions to call when the current song changes.
  65. See `libmpdel-current-song-id'."
  66. :type 'hook
  67. :group 'libmpdel)
  68. ;;; Global private variables
  69. (defvar libmpdel--connection nil
  70. "Current connection to the MPD server.
  71. The logs of this connection are accessible in the *mpd* buffer.")
  72. (defconst libmpdel--response-regexp
  73. (rx line-start
  74. (or
  75. (and "OK" (? " MPD " (one-or-more not-newline)))
  76. (and "ACK ["
  77. (one-or-more (any digit)) "@" (one-or-more (any digit))
  78. "] " (one-or-more not-newline)))
  79. "\n")
  80. "Regexp matching the responses sent by the MPD server.")
  81. (defconst libmpdel--msgfield-regexp
  82. (rx line-start
  83. (group (+? (not (any ?:))))
  84. ": "
  85. (group (* not-newline))
  86. line-end)
  87. "Regexp matching a line consisting of a key and a value.
  88. The key is stored in group 1 and the value in group 2.")
  89. (defvar libmpdel--msghandlers nil
  90. "Current commands sent to the server.
  91. Each element in the list is of the form (COMMAND HANDLER BUFFER).
  92. COMMAND is the query sent to the server. Even though this
  93. information is not necessary, it is useful to better understand
  94. the log.
  95. HANDLER is a function executed when the answers to COMMAND comes
  96. back. The function must accept one parameter (usually named
  97. MESSAGE) that will contain the answer.
  98. BUFFER is a buffer that was active when COMMAND was sent. This
  99. buffer is made active again while executing HANDLER.
  100. An invariant of this MPD client is that there is always an IDLE
  101. command sent to the server (and its corresponding handler in this
  102. variable). This means our client is always registered to
  103. notifications in the server. When we want to send a command to
  104. the server (for example to change the current song), we always
  105. have to (1) cancel the IDLE first (with a \"noidle\"
  106. command), (2) send the command we want, and (3) send the IDLE
  107. command again. Cancelling the current \"idle\" command is done
  108. in `mpdel-send-command'. Sending \"idle\" again is done in the
  109. handler for \"idle\" that will be triggered when the empty answer
  110. for the cancelled \"idle\" arrives.
  111. Because MPD answers in the order the commands are sent, we know
  112. that the first handler is the one to execute when we receive a
  113. message from the server.")
  114. ;;; Data structures
  115. (cl-defstruct (libmpdel-artist
  116. (:constructor libmpdel--artist-create)
  117. (:conc-name libmpdel--artist-))
  118. (name nil :read-only t))
  119. (cl-defstruct (libmpdel-album
  120. (:constructor libmpdel--album-create)
  121. (:conc-name libmpdel--album-))
  122. (name nil :read-only t)
  123. (artist nil :read-only t))
  124. (cl-defstruct (libmpdel-song
  125. (:constructor libmpdel--song-create)
  126. (:conc-name libmpdel--song-))
  127. (name nil :read-only t)
  128. (track nil :read-only t)
  129. (file nil :read-only t)
  130. (album nil :read-only t)
  131. (disc nil :read-only t)
  132. (date nil :read-only t)
  133. (id nil :read-only t)
  134. (pos nil :read-only t))
  135. (cl-defstruct (libmpdel-stored-playlist
  136. (:constructor libmpdel--stored-playlist-create)
  137. (:conc-name libmpdel--stored-playlist-))
  138. (name nil :read-only t))
  139. (cl-defstruct (libmpdel-search-criteria
  140. (:constructor libmpdel-search-criteria-create)
  141. (:conc-name libmpdel--search-criteria-))
  142. (type nil :read-only t)
  143. (what nil :read-only t))
  144. (cl-defstruct (libmpdel-filter
  145. (:constructor libmpdel-filter-create)
  146. (:conc-name libmpdel--filter-))
  147. (text nil :read-only t))
  148. (defun libmpdel-artist-name (entity)
  149. "Return artist name of ENTITY."
  150. (libmpdel--artist-name (libmpdel-artist entity)))
  151. (cl-defgeneric libmpdel-artist (entity)
  152. "Return artist of ENTITY.")
  153. (cl-defmethod libmpdel-artist ((artist libmpdel-artist))
  154. "Return ARTIST."
  155. artist)
  156. (cl-defmethod libmpdel-artist ((album libmpdel-album))
  157. "Return the ALBUM's artist."
  158. (libmpdel--album-artist album))
  159. (cl-defmethod libmpdel-artist ((song libmpdel-song))
  160. "Return the SONG's artist."
  161. (libmpdel-artist (libmpdel--song-album song)))
  162. (defun libmpdel-album-name (entity)
  163. "Return album name of ENTITY."
  164. (libmpdel--album-name (libmpdel-album entity)))
  165. (cl-defgeneric libmpdel-album (entity)
  166. "Return album of ENTITY.")
  167. (cl-defmethod libmpdel-album ((album libmpdel-album))
  168. "Return ALBUM."
  169. album)
  170. (cl-defmethod libmpdel-album ((song libmpdel-song))
  171. "Return SONG's album."
  172. (libmpdel--song-album song))
  173. (cl-defgeneric libmpdel-entity-name (entity)
  174. "Return basename of ENTITY.")
  175. (cl-defmethod libmpdel-entity-name ((artist libmpdel-artist))
  176. "Return ARTIST's name."
  177. (libmpdel--artist-name artist))
  178. (cl-defmethod libmpdel-entity-name ((album libmpdel-album))
  179. "Return ALBUM's name."
  180. (libmpdel--album-name album))
  181. (cl-defmethod libmpdel-entity-name ((song libmpdel-song))
  182. "Return SONG's name."
  183. (libmpdel--song-name song))
  184. (cl-defmethod libmpdel-entity-name ((_entity (eql stored-playlists)))
  185. "Return a string describing the `stored-playlists' entity."
  186. "Stored playlists")
  187. (cl-defmethod libmpdel-entity-name ((_entity (eql artists)))
  188. "Return a string describing the `artists' entity."
  189. "All artists")
  190. (cl-defmethod libmpdel-entity-name ((_entity (eql albums)))
  191. "Return a string describing the `albums' entity."
  192. "All albums")
  193. (cl-defmethod libmpdel-entity-name ((_entity (eql current-playlist)))
  194. "Return a string describing the `current-playlist' entity."
  195. "Current playlist")
  196. (cl-defmethod libmpdel-entity-name ((stored-playlist libmpdel-stored-playlist))
  197. "Return STORED-PLAYLIST's name."
  198. (libmpdel--stored-playlist-name stored-playlist))
  199. (cl-defmethod libmpdel-entity-name ((search-criteria libmpdel-search-criteria))
  200. "Return a string representing SEARCH-CRITERIA."
  201. (format "search %s: \"%s\""
  202. (libmpdel--search-criteria-type search-criteria)
  203. (libmpdel--search-criteria-what search-criteria)))
  204. (cl-defmethod libmpdel-entity-name ((filter libmpdel-filter))
  205. "Return a string representing FILTER."
  206. (format "filter %s" (libmpdel--filter-text filter)))
  207. (cl-defgeneric libmpdel-entity-parent (_entity)
  208. "Return parent of ENTITY, nil if none."
  209. nil)
  210. (cl-defmethod libmpdel-entity-parent ((song libmpdel-song))
  211. "Return SONG's album."
  212. (libmpdel-album song))
  213. (cl-defmethod libmpdel-entity-parent ((album libmpdel-album))
  214. "Return ALBUM's artist."
  215. (libmpdel-artist album))
  216. (cl-defmethod libmpdel-entity-parent ((_artist libmpdel-artist))
  217. "Return the `artists' entity."
  218. 'artists)
  219. (cl-defmethod libmpdel-entity-parent ((_stored-playlist libmpdel-stored-playlist))
  220. "Return the `stored-playlists' entity."
  221. 'stored-playlists)
  222. (cl-defgeneric libmpdel-entity-id (entity)
  223. "Return an identifier string for ENTITY."
  224. entity)
  225. (cl-defmethod libmpdel-entity-id ((song libmpdel-song))
  226. "Return the SONG's filename."
  227. ;; Override of default implementation to ignore changing ids and
  228. ;; position.
  229. (libmpdel--song-file song))
  230. (defun libmpdel-song-file (song)
  231. "Return the filename of SONG."
  232. (libmpdel--song-file song))
  233. (defun libmpdel-song-track (song)
  234. "Return the track number of SONG within its album."
  235. (or (libmpdel--song-track song) ""))
  236. (defun libmpdel-entity-date (song)
  237. "Return the date of SONG."
  238. (or (libmpdel--song-date song) ""))
  239. (defun libmpdel-song-disc (song)
  240. "Return the disc number of SONG within its album."
  241. (or (libmpdel--song-disc song) ""))
  242. (defun libmpdel-song-id (song)
  243. "Return SONG id within the current playlist, nil if none."
  244. (libmpdel--song-id song))
  245. (defun libmpdel-song-position (song)
  246. "Return position of SONG in playlist, nil if not in playlist."
  247. (let ((pos (libmpdel--song-pos song)))
  248. (when (and (stringp pos) (not (string= pos "")))
  249. (string-to-number pos))))
  250. (defun libmpdel--create-song-from-data (song-data)
  251. "Return a song from SONG-DATA, a server's response."
  252. (libmpdel--song-create
  253. :name (cdr (assq 'Title song-data))
  254. :track (cdr (assq 'Track song-data))
  255. :file (cdr (assq 'file song-data))
  256. :album (libmpdel--album-create
  257. :name (cdr (assq 'Album song-data))
  258. :artist (libmpdel--artist-create :name (cdr (assq 'Artist song-data))))
  259. :date (cdr (assq 'Date song-data))
  260. :disc (cdr (assq 'Disc song-data))
  261. :id (cdr (assq 'Id song-data))
  262. :pos (cdr (assq 'Pos song-data))))
  263. (defun libmpdel--create-songs-from-data (data)
  264. "Return a list of songs from DATA, a server's response."
  265. (mapcar #'libmpdel--create-song-from-data (libmpdel-group-data data)))
  266. (defun libmpdel-current-playlist-p (entity)
  267. "Return non-nil if ENTITY is the current playlist."
  268. (eq entity 'current-playlist))
  269. ;;; Helper functions
  270. (defun libmpdel--process ()
  271. "Return the process communicating with the MPD server."
  272. (tq-process libmpdel--connection))
  273. (defun libmpdel--process-buffer ()
  274. "Return the buffer associated with the connection process."
  275. (process-buffer (libmpdel--process)))
  276. (defun libmpdel--connect ()
  277. "Create a new connection with the MPD server."
  278. ;; The *mpd* buffer will contain all the communication logs
  279. (when (libmpdel-connected-p)
  280. (user-error "A connection is already opened"))
  281. (with-current-buffer (get-buffer-create "*mpd*")
  282. (setq-local buffer-read-only t)
  283. (let ((inhibit-read-only t))
  284. (erase-buffer)))
  285. (setq libmpdel--connection (tq-create (open-network-stream
  286. "mpd" "*mpd*"
  287. libmpdel-hostname
  288. libmpdel-port
  289. :type 'plain)))
  290. (set-process-coding-system (libmpdel--process) 'utf-8-unix 'utf-8-unix)
  291. (set-process-query-on-exit-flag (libmpdel--process) nil)
  292. ;; Take care of the initial welcome message from server that we
  293. ;; don't ask for:
  294. (setq libmpdel--msghandlers '(("welcome" libmpdel--msghandler-ignore nil)))
  295. (tq-queue-add libmpdel--connection nil libmpdel--response-regexp nil #'libmpdel--message-filter)
  296. (libmpdel-refresh-status)
  297. ;; As an invariant of the MPD client, there is always an "idle"
  298. ;; command sent to the server. This acts like a registration to the
  299. ;; server's notifications. See `libmpdel--msghandlers' for more
  300. ;; information.
  301. (libmpdel--raw-send-command-with-handler "idle" #'libmpdel--msghandler-idle))
  302. ;;;###autoload
  303. (defun libmpdel-connect-profile (profile)
  304. "Connect to MPD server defined in PROFILE.
  305. Interactively, let the user choose PROFILE from `libmpdel-profiles'.
  306. If a connection already exists, terminate it first."
  307. (interactive (list (libmpdel--select-profile)))
  308. (let* ((libmpdel-hostname (cl-second profile))
  309. (libmpdel-port (cl-third profile)))
  310. (when (libmpdel-connected-p)
  311. (libmpdel-disconnect))
  312. (libmpdel--connect)))
  313. (defun libmpdel--raw-send-command (command)
  314. "Send COMMAND, a string, to the server and log that."
  315. (libmpdel--log command "->")
  316. (tq-enqueue
  317. libmpdel--connection
  318. (format "%s\n" command)
  319. libmpdel--response-regexp
  320. nil
  321. #'libmpdel--message-filter))
  322. (defun libmpdel--raw-send-command-with-handler (command &optional handler)
  323. "Send COMMAND to MPD server and set HANDLER for the response.
  324. If HANDLER is nil, response will be ignored.
  325. If command is a string, send that. Otherwise, it must be a list
  326. that will be passed to `format' before being sent."
  327. (let ((command (if (listp command)
  328. (apply #'format command)
  329. command)))
  330. (setq libmpdel--msghandlers
  331. (append libmpdel--msghandlers
  332. `((,command
  333. ,(or handler #'libmpdel--msghandler-ignore)
  334. ,(current-buffer)))))
  335. (libmpdel--raw-send-command command)))
  336. (defun libmpdel--message-filter (_ message)
  337. "Take care of the MESSAGE sent by the server.
  338. The first parameter is ignored. MESSAGE contains a string
  339. representing the answer from the server."
  340. ;; Because errors in handlers are not raised by Emacs, we log them.
  341. (condition-case-unless-debug error
  342. (progn
  343. ;; because answers arrive in the same order we sent the
  344. ;; commands, we are sure that the first handler is the one to
  345. ;; use.
  346. (cl-destructuring-bind (command handler buffer) (pop libmpdel--msghandlers)
  347. (libmpdel--log (format "\"%s\" (as answer to \"%s\")" message command)
  348. "<-")
  349. ;; if answer is a ACK, then there was a problem. We log it as such.
  350. (if (string= (substring message 0 3) "ACK")
  351. (libmpdel--log "ACK message" "ko")
  352. (with-current-buffer (if (buffer-live-p buffer) buffer (current-buffer))
  353. (funcall handler (libmpdel--extract-data message))))))
  354. (error (libmpdel--log error "ko"))))
  355. (defun libmpdel--log (string type-string)
  356. "Add STRING at end of *mpd* buffer.
  357. TYPE-STRING is a two-letter string classifying the kind of
  358. message to log."
  359. (with-current-buffer (libmpdel--process-buffer)
  360. (let ((inhibit-read-only t)
  361. (moving (= (point) (process-mark (libmpdel--process)))))
  362. (save-excursion
  363. ;; Insert the text, advancing the process marker.
  364. (goto-char (process-mark (libmpdel--process)))
  365. (insert "-------------------------\n")
  366. (insert (format "%s [%s] %s\n" type-string (time-stamp-string) string))
  367. (set-marker (process-mark (libmpdel--process)) (point)))
  368. (if moving (goto-char (process-mark (libmpdel--process)))))))
  369. (defun libmpdel--msghandler-idle (data)
  370. "Handler for the response DATA to the \"idle\" command.
  371. This handler is responsible for sending another \"idle\"
  372. command."
  373. ;; Because "idle" only informs about what changed (e.g., "the
  374. ;; playback state changed") without telling the new state (e.g.,
  375. ;; "the player is now stopped"), we have to ask for the details:
  376. (when data
  377. (libmpdel-refresh-status))
  378. ;; Each time an "idle" is finished, we start a new one:
  379. (libmpdel--raw-send-command-with-handler "idle" #'libmpdel--msghandler-idle)
  380. (mapc (lambda (changed-subsystem)
  381. (cl-case (intern (cdr changed-subsystem))
  382. ;; At this point, libmpdel has only been informed that
  383. ;; something changed (e.g., "the current playlist has been
  384. ;; changed"). We don't have the details (e.g., "the
  385. ;; current playlist contains these songs"). As a result,
  386. ;; hook functions will have to fetch the details by
  387. ;; themselves if they need to. On the contrary, for hook
  388. ;; functions requiring libmpdel to have new data, use
  389. ;; `libmpdel--msghandler-status'.
  390. (playlist (run-hooks 'libmpdel-current-playlist-changed-hook))
  391. (stored_playlist (run-hooks 'libmpdel-stored-playlist-changed-hook))))
  392. data))
  393. (defun libmpdel--msghandler-status (data)
  394. "Handler for the response DATA to the \"status\" command."
  395. (dolist (status-pair data)
  396. (let ((status-key (car status-pair))
  397. (status-value (cdr status-pair)))
  398. (cl-case status-key
  399. (state (libmpdel--set-play-state status-value))
  400. (songid (libmpdel--set-current-song status-value))
  401. (playlistlength (libmpdel--set-playlist-length status-value))
  402. (volume (libmpdel--set-volume status-value))
  403. (random (libmpdel--set-random status-value))
  404. (repeat (libmpdel--set-repeat status-value))
  405. (single (libmpdel--set-single status-value)))))
  406. ;; When no song is being played, 'songid is not in DATA. If that's
  407. ;; the case, we have to set current song to nil:
  408. (unless (cl-member 'songid data :key #'car)
  409. (libmpdel--set-current-song nil)))
  410. (defun libmpdel--msghandler-ignore (_)
  411. "No handler was associated to last response."
  412. ;; nothing to do
  413. nil)
  414. (defun libmpdel--extract-data (message)
  415. "Return MESSAGE."
  416. (save-match-data
  417. (with-temp-buffer
  418. (insert message)
  419. (let ((end-of-message (point-at-bol))
  420. (data nil))
  421. (goto-char (point-min))
  422. (while (re-search-forward libmpdel--msgfield-regexp end-of-message t)
  423. (push (cons (intern (match-string 1)) (match-string 2)) data))
  424. (reverse data)))))
  425. (defun libmpdel--string<-ignore-case (str1 str2)
  426. "Compare the contents of STR1 and STR2, ignoring case."
  427. (let ((comp (compare-strings str1 nil nil str2 nil nil t)))
  428. (or (eq comp t) (< comp 0))))
  429. (defmacro libmpdel--define-state (name value-desc &rest set-body)
  430. "Generate code to set and get state for NAME.
  431. Name is a symbol (e.g., `volume' or `play-state') naming the
  432. state to generate code for.
  433. VALUE-DESC is a string describing the kind of value accepted for
  434. this state.
  435. SET-BODY is a list of forms to put in the generated setter
  436. function. During executiong of SET-BODY, a variable NEW-VALUE is
  437. bound containing the value to set."
  438. (declare (indent 1))
  439. `(progn
  440. (defvar ,(intern (format "libmpdel--%s" name)) nil
  441. ,(format "Current %s of MPD server.\n%s" name value-desc))
  442. (defun ,(intern (format "libmpdel--set-%s" name)) (new-value)
  443. ,(format "Save NEW-VALUE as current %s.\n%s" name value-desc)
  444. ,@set-body)
  445. (defun ,(intern (format "libmpdel-%s" name)) ()
  446. ,(format "Return current value of %s.\n%s" name value-desc)
  447. ,(intern (format "libmpdel--%s" name)))))
  448. (libmpdel--define-state play-state
  449. "Value is `play', `pause' or `stop'."
  450. (let ((new-state (intern new-value))
  451. (old-state libmpdel--play-state))
  452. (unless (equal old-state new-state)
  453. (setq libmpdel--play-state new-state)
  454. (run-hooks 'libmpdel-player-changed-hook))))
  455. (defun libmpdel-stopped-p ()
  456. "Return non-nil if player is stopped, nil otherwise."
  457. (eq 'stop (libmpdel-play-state)))
  458. (libmpdel--define-state current-song
  459. "An entity representing currently played song."
  460. (when (libmpdel--new-current-song-p new-value)
  461. (libmpdel-send-command
  462. "currentsong"
  463. (lambda (data)
  464. (setq libmpdel--current-song (and data (libmpdel--create-song-from-data data)))
  465. (run-hooks 'libmpdel-current-song-changed-hook)))))
  466. (defun libmpdel--new-current-song-p (song-id)
  467. "Return non-nil if SONG-ID differs from `libmpdel--current-song'."
  468. (let ((current-song-id (and libmpdel--current-song (libmpdel-song-id libmpdel--current-song))))
  469. (not (equal song-id current-song-id))))
  470. (libmpdel--define-state playlist-length
  471. "Number of songs in current playlist."
  472. (setq libmpdel--playlist-length (string-to-number new-value)))
  473. (libmpdel--define-state volume
  474. "Value is a string representing a number between 0 and 100."
  475. (setq libmpdel--volume new-value))
  476. (libmpdel--define-state random
  477. "Boolean indicating if songs are played randomly or in order."
  478. (setq libmpdel--random (string= new-value "1")))
  479. (libmpdel--define-state repeat
  480. "Boolean indicating if current playlist or song is repeated after it ends."
  481. (setq libmpdel--repeat (string= new-value "1")))
  482. (libmpdel--define-state single
  483. "Symbol indicating if current song is repeated `forever', only `once' or `never'."
  484. (setq libmpdel--single
  485. (cond
  486. ((string= new-value "oneshot") 'once)
  487. ((string= new-value "1") 'forever)
  488. (t 'never))))
  489. (defun libmpdel-time-to-string (time)
  490. "Return a string represeting TIME, a number in a string."
  491. (if (not time)
  492. "0"
  493. (let* ((time (string-to-number time))
  494. (seconds (mod time 60))
  495. (minutes (/ (- time seconds) 60)))
  496. (format "%02d:%02d" (truncate minutes) (truncate seconds)))))
  497. (defun libmpdel-completing-read (prompt entities &optional transformer)
  498. "PROMPT user to select one entity among ENTITIES.
  499. Transform each entity to a string with TRANSFORMER,
  500. `libmpdel-entity-name' if nil."
  501. (let* ((transformer (or transformer #'libmpdel-entity-name))
  502. (map (make-hash-table :test 'equal :size (length entities)))
  503. (entity-strings (mapcar (lambda (entity) (funcall transformer entity)) entities)))
  504. (cl-mapcar (lambda (entity entity-string)
  505. (puthash entity-string entity map))
  506. entities entity-strings)
  507. (let ((entity-string (completing-read prompt entity-strings nil t)))
  508. (gethash entity-string map))))
  509. (defun libmpdel-completing-read-entity (function prompt entity &optional transformer)
  510. "Call FUNCTION after prompting for an element of ENTITY.
  511. Pass PROMPT, the elements of ENTITY and TRANSFORMER to
  512. `libmpdel-completing-read'."
  513. (libmpdel-list
  514. entity
  515. (lambda (entities)
  516. (funcall function
  517. (libmpdel-completing-read prompt entities transformer)))))
  518. (defun libmpdel-funcall-on-stored-playlist (function)
  519. "Pass a stored playlist as parameter to FUNCTION.
  520. The user is asked to choose for a stored playlist first."
  521. (libmpdel-completing-read-entity
  522. function
  523. "Stored playlist: "
  524. 'stored-playlists))
  525. (defun libmpdel-current-playlist-add (entity)
  526. "Add ENTITY to a current playlist.
  527. ENTITY can also be a list of entities to add."
  528. (libmpdel-playlist-add entity 'current-playlist))
  529. (defun libmpdel-current-playlist-replace (entity)
  530. "Replace current playlist with ENTITY.
  531. ENTITY can also be a list of entities to replace with."
  532. (libmpdel-playlist-replace entity 'current-playlist))
  533. (defun libmpdel-stored-playlist-add (entity)
  534. "Add ENTITY to a stored playlist.
  535. The user is asked to choose for a stored playlist first.
  536. ENTITY can also be a list of entities to add."
  537. (libmpdel-funcall-on-stored-playlist
  538. (apply-partially #'libmpdel-playlist-add entity)))
  539. (defun libmpdel-stored-playlist-replace (entity)
  540. "Replace a stored playlist with ENTITY.
  541. The user is asked to choose for a stored playlist first.
  542. ENTITY can also be a list of entities to replace with."
  543. (libmpdel-funcall-on-stored-playlist
  544. (apply-partially #'libmpdel-playlist-replace entity)))
  545. (defun libmpdel-current-playlist-insert (entity)
  546. "Insert ENTITY after currently-played song and play it.
  547. ENTITY can also be a list of entities in which case all entities
  548. are added and the first one is played."
  549. (libmpdel-list-songs
  550. entity
  551. (lambda (songs)
  552. (libmpdel-send-commands
  553. (mapcar (lambda (song) (format "addid %S" (libmpdel-song-file song))) songs)
  554. (lambda (data)
  555. (let ((song-ids (mapcar (lambda (song-data) (cdr song-data)) data))
  556. ;; Add after current song if possible:
  557. (target-index (if (libmpdel-current-song) "-1" "0")))
  558. (libmpdel-send-commands
  559. ;; The reverse is important to get the songs in the same
  560. ;; order as in the selection:
  561. (mapcar
  562. (lambda (song-id) (format "moveid %s %s" song-id target-index))
  563. (reverse song-ids))
  564. (lambda (_) (libmpdel-send-command `("playid %s" ,(car song-ids)))))))))))
  565. (defun libmpdel-async-mapcar (list mapfn callback)
  566. "Apply MAPFN to each element of LIST and pass result to CALLBACK.
  567. MAPFN is a function taking 2 arguments: the element to map and a
  568. callback to call when the mapping is done."
  569. (if (not list)
  570. (funcall callback nil)
  571. (funcall ; transform the first element
  572. mapfn
  573. (car list)
  574. (lambda (first-mapped)
  575. (libmpdel-async-mapcar ; transform the rest
  576. (cdr list)
  577. mapfn
  578. (lambda (latter-elements)
  579. (funcall callback
  580. (cons first-mapped
  581. latter-elements))))))))
  582. (defun libmpdel-async-mapcan (list mapfn callback)
  583. "Apply MAPFN to each element of LIST.
  584. Concatenate the results and pass that to CALLBACK.
  585. MAPFN is a function taking 2 arguments: the element to map and a
  586. callback to call when the mapping is done."
  587. (libmpdel-async-mapcar
  588. list
  589. mapfn
  590. (lambda (groups)
  591. (funcall
  592. callback
  593. (apply #'cl-concatenate 'list groups)))))
  594. (defun libmpdel--get-profile-from-name (name)
  595. "Return an element of `libmpdel-profiles' matching NAME."
  596. (cl-find name libmpdel-profiles :test #'string= :key #'car))
  597. (defun libmpdel--select-profile ()
  598. "Ask the user to select a profile among `libmpdel-profiles' and return it."
  599. (unless (consp libmpdel-profiles)
  600. (user-error "Add profiles to `libmpdel-profiles'"))
  601. (if (= 1 (length libmpdel-profiles))
  602. (progn
  603. (message "Only 1 profile defined in `libmpdel-profiles'")
  604. (car libmpdel-profiles))
  605. (let* ((profile-names (mapcar #'car libmpdel-profiles))
  606. (profile-name (completing-read "Choose an MPD profile"
  607. profile-names nil t)))
  608. (libmpdel--get-profile-from-name profile-name))))
  609. ;;; Public functions
  610. (defun libmpdel-connected-p ()
  611. "Return non-nil if there is a connection to MPD server."
  612. (and libmpdel--connection
  613. (process-live-p (libmpdel--process))))
  614. (defun libmpdel-ensure-connection ()
  615. "Make sure there is an active connection to the MPD server."
  616. (unless (libmpdel-connected-p)
  617. (libmpdel--connect)))
  618. (defun libmpdel-disconnect ()
  619. "Close connection to the MPD server."
  620. (when (not (libmpdel-connected-p))
  621. (user-error "There is no connection to MPD"))
  622. (tq-close libmpdel--connection)
  623. (setq libmpdel--connection nil))
  624. (defun libmpdel-send-command (command &optional handler)
  625. "Send COMMAND to server and register HANDLER for the answer.
  626. If HANDLER is nil, ignore response."
  627. (libmpdel-ensure-connection)
  628. ;; if current command is IDLE, we have to cancel it. See
  629. ;; `mpdel-msghandlers' for more information.
  630. (when (eql (elt (car (last libmpdel--msghandlers)) 1) #'libmpdel--msghandler-idle)
  631. (libmpdel--raw-send-command "noidle"))
  632. (libmpdel--raw-send-command-with-handler command handler))
  633. (defun libmpdel-send-commands (commands &optional handler)
  634. "Send several COMMANDS at once and execute HANDLER once with result."
  635. (libmpdel-send-command
  636. (with-temp-buffer
  637. (insert "command_list_begin\n")
  638. (mapc (lambda (command) (insert command "\n")) commands)
  639. (insert "command_list_end")
  640. (buffer-substring-no-properties (point-min) (point-max)))
  641. handler))
  642. (defun libmpdel-entries (data key)
  643. "Collect DATA entries matching KEY."
  644. (mapcar #'cdr (cl-remove-if-not (apply-partially #'eq key) data :key #'car)))
  645. (defun libmpdel-sorted-entries (data key)
  646. "Sort and collect DATA entries matching KEY."
  647. (sort (libmpdel-entries data key) #'libmpdel--string<-ignore-case))
  648. (defun libmpdel-group-data (data)
  649. "Find repeating fields in DATA and group them."
  650. (when data
  651. (let ((first-key (caar data))
  652. result group)
  653. (mapc (lambda (key-value)
  654. (when (and
  655. (eq (car key-value) first-key)
  656. group)
  657. (push (reverse group) result)
  658. (setq group nil))
  659. (push key-value group))
  660. data)
  661. (push (reverse group) result)
  662. (reverse result))))
  663. (cl-defgeneric libmpdel-dired (entity)
  664. "Open `dired' on ENTITY.")
  665. (eval-when-compile
  666. (declare-function dired-jump "dired-x"))
  667. (cl-defmethod libmpdel-dired ((song libmpdel-song))
  668. "Open `dired' on SONG."
  669. (require 'dired-x)
  670. (dired-jump t (expand-file-name (libmpdel-song-file song) libmpdel-music-directory)))
  671. (defun libmpdel-equal (entity1 entity2)
  672. "Return non-nil if ENTITY1 and ENTITY2 represent the same entity."
  673. (equal (libmpdel-entity-id entity1) (libmpdel-entity-id entity2)))
  674. ;;; Helper queries
  675. (cl-defgeneric libmpdel-entity-to-criteria (entity)
  676. "Return search query matching all songs from ENTITY.")
  677. (cl-defmethod libmpdel-entity-to-criteria ((query string))
  678. "Return QUERY."
  679. query)
  680. (cl-defmethod libmpdel-entity-to-criteria ((artist libmpdel-artist))
  681. "Return search query matching all songs from ARTIST."
  682. (format "artist %S" (libmpdel-entity-name artist)))
  683. (cl-defmethod libmpdel-entity-to-criteria ((album libmpdel-album))
  684. "Return search query matching all songs from ALBUM."
  685. (format "%s album %S"
  686. (libmpdel-entity-to-criteria (libmpdel-artist album))
  687. (libmpdel-entity-name album)))
  688. (cl-defmethod libmpdel-entity-to-criteria ((song libmpdel-song))
  689. "Return search query matching SONG."
  690. (format "%s title %S"
  691. (libmpdel-entity-to-criteria (libmpdel-album song))
  692. (libmpdel-entity-name song)))
  693. (cl-defgeneric libmpdel-list (entity function)
  694. "Call FUNCTION with all children of ENTITY as parameter."
  695. (libmpdel-list-songs entity function))
  696. (cl-defmethod libmpdel-list ((_entity (eql artists)) function)
  697. "Call FUNCTION with all artists as parameter."
  698. (libmpdel-send-command
  699. "list artist"
  700. (lambda (data)
  701. (funcall function
  702. (mapcar
  703. (lambda (artist-name) (libmpdel--artist-create :name artist-name))
  704. (libmpdel-sorted-entries data 'Artist))))))
  705. (cl-defmethod libmpdel-list ((_entity (eql albums)) function)
  706. "Call FUNCTION with all artists as parameter."
  707. (libmpdel-list
  708. 'artists
  709. (lambda (artists) (libmpdel-async-mapcan artists #'libmpdel-list function))))
  710. (cl-defmethod libmpdel-list ((_entity (eql stored-playlists)) function)
  711. "Call FUNCTION with all stored playlists as parameter."
  712. (libmpdel-send-command
  713. "listplaylists"
  714. (lambda (data)
  715. (funcall function
  716. (mapcar
  717. (lambda (playlist-name) (libmpdel--stored-playlist-create :name playlist-name))
  718. (libmpdel-sorted-entries data 'playlist))))))
  719. (cl-defmethod libmpdel-list ((artist libmpdel-artist) function)
  720. "Call FUNCTION with all albums of ARTIST as parameter."
  721. (libmpdel-send-command
  722. `("list album %s" ,(libmpdel-entity-to-criteria artist))
  723. (lambda (data)
  724. (funcall function
  725. (mapcar
  726. (lambda (album-name) (libmpdel--album-create :name album-name :artist artist))
  727. (libmpdel-sorted-entries data 'Album))))))
  728. (cl-defgeneric libmpdel-list-songs (entity function)
  729. "Call FUNCTION with all songs of ENTITY."
  730. (libmpdel-send-command
  731. `("find %s" ,(libmpdel-entity-to-criteria entity))
  732. (lambda (data)
  733. (funcall function (libmpdel--create-songs-from-data data)))))
  734. (cl-defmethod libmpdel-list-songs ((stored-playlist libmpdel-stored-playlist) function)
  735. "Call FUNCTION with all songs of STORED-PLAYLIST."
  736. (libmpdel-send-command
  737. `("listplaylistinfo %S" ,(libmpdel-entity-name stored-playlist))
  738. (lambda (data)
  739. (funcall function (libmpdel--create-songs-from-data data)))))
  740. (cl-defmethod libmpdel-list-songs ((_ (eql current-playlist)) function)
  741. "Call FUNCTION with all songs of the current playlist."
  742. (libmpdel-send-command
  743. "playlistinfo"
  744. (lambda (data)
  745. (funcall function (libmpdel--create-songs-from-data data)))))
  746. (cl-defmethod libmpdel-list-songs ((search-criteria libmpdel-search-criteria) function)
  747. "Call FUNCTION with all songs matching SEARCH-CRITERIA."
  748. (libmpdel-send-command
  749. `("search %s %S"
  750. ,(libmpdel--search-criteria-type search-criteria)
  751. ,(libmpdel--search-criteria-what search-criteria))
  752. (lambda (data)
  753. (funcall function (libmpdel--create-songs-from-data data)))))
  754. (cl-defmethod libmpdel-list-songs ((filter libmpdel-filter) function)
  755. "Call FUNCTION with all songs matching FILTER."
  756. (libmpdel-send-command
  757. `("search %S" ,(libmpdel--filter-text filter))
  758. (lambda (data)
  759. (funcall function (libmpdel--create-songs-from-data data)))))
  760. (cl-defmethod libmpdel-list-songs ((song libmpdel-song) function)
  761. "Call FUNCTION with SONG."
  762. (funcall function (list song)))
  763. (cl-defmethod libmpdel-list-songs ((entities list) function)
  764. "Call FUNCTION with all songs in ENTITIES."
  765. (libmpdel-async-mapcan entities #'libmpdel-list-songs function))
  766. ;;; Playlist queries
  767. (cl-defgeneric libmpdel-playlist-add (entity playlist)
  768. "Add ENTITY to PLAYLIST.
  769. ENTITY can also be a list of entities to add.")
  770. (cl-defmethod libmpdel-playlist-add (entity (_ (eql current-playlist)))
  771. "Add ENTITY to the current playlist."
  772. (let ((id (libmpdel-entity-id entity)))
  773. (libmpdel-send-command
  774. (if (and (stringp id) (not (string-empty-p id)))
  775. `("addid %S" ,id)
  776. `("findadd %s" ,(libmpdel-entity-to-criteria entity))))))
  777. (cl-defmethod libmpdel-playlist-add (entity (stored-playlist libmpdel-stored-playlist))
  778. "Add ENTITY to STORED-PLAYLIST."
  779. (libmpdel-send-command
  780. `("searchaddpl %S %s"
  781. ,(libmpdel-entity-name stored-playlist)
  782. ,(libmpdel-entity-to-criteria entity))))
  783. (cl-defmethod libmpdel-playlist-add ((stored-playlist libmpdel-stored-playlist) (_ (eql current-playlist)))
  784. "Add content of STORED-PLAYLIST to the current playlist."
  785. (libmpdel-send-command `("load %S" ,(libmpdel-entity-name stored-playlist))))
  786. (cl-defmethod libmpdel-playlist-add ((entities list) playlist)
  787. "Add all ENTITIES to PLAYLIST."
  788. (mapcar (lambda (entity) (libmpdel-playlist-add entity playlist))
  789. entities))
  790. (defun libmpdel-playlist-replace (entity playlist)
  791. "Clear PLAYLIST and add ENTITY to it."
  792. (libmpdel-playlist-clear playlist)
  793. (libmpdel-playlist-add entity playlist))
  794. (cl-defgeneric libmpdel-playlist-clear (playlist)
  795. "Remove all songs from PLAYLIST.")
  796. (cl-defmethod libmpdel-playlist-clear ((_ (eql current-playlist)))
  797. "Remove all songs from the current playlist."
  798. (libmpdel-send-command "clear"))
  799. (cl-defmethod libmpdel-playlist-clear ((stored-playlist libmpdel-stored-playlist))
  800. "Remove all songs from STORED-PLAYLIST."
  801. (libmpdel-send-command `("playlistclear %S" ,(libmpdel-entity-name stored-playlist))))
  802. (cl-defgeneric libmpdel-playlist-delete (songs playlist)
  803. "Remove SONGS from PLAYLIST.")
  804. (cl-defmethod libmpdel-playlist-delete (songs (_ (eql current-playlist)))
  805. "Remove SONGS from the current playlist."
  806. (libmpdel-send-commands
  807. (mapcar (lambda (song) (format "deleteid %s" (libmpdel-song-id song)))
  808. songs)))
  809. (cl-defmethod libmpdel-playlist-delete (songs (stored-playlist libmpdel-stored-playlist))
  810. "Remove SONGS from STORED-PLAYLIST."
  811. (libmpdel-list
  812. stored-playlist
  813. (lambda (all-playlist-songs)
  814. (let ((song-positions (cl-sort (mapcar (lambda (song)
  815. (cl-position song all-playlist-songs :test #'equal))
  816. songs)
  817. #'>)))
  818. (libmpdel-send-commands
  819. (mapcar
  820. (lambda (song-position)
  821. (format "playlistdelete %S %s"
  822. (libmpdel-entity-name stored-playlist)
  823. song-position))
  824. song-positions))))))
  825. (defun libmpdel-playlist-move-up (songs)
  826. "Move up SONGS in current playlist."
  827. ;; We should move up from first in playlist to last
  828. (let* ((songs (cl-sort (cl-copy-seq songs) #'< :key #'libmpdel-song-position)))
  829. ;; Don't move up if first song is selected
  830. (unless (= (libmpdel-song-position (car songs)) 0)
  831. (libmpdel-send-commands
  832. (mapcar (lambda (song)
  833. (format "moveid %s %s" (libmpdel-song-id song) (1- (libmpdel-song-position song))))
  834. songs)))))
  835. (defun libmpdel-playlist-move-down (songs)
  836. "Move down SONGS in current playlist."
  837. ;; We should move down from last in playlist to first
  838. (let* ((songs (cl-sort (cl-copy-seq songs) #'> :key #'libmpdel-song-position)))
  839. ;; Don't move down if last song is selected
  840. (unless (= (libmpdel-song-position (car songs)) (1- libmpdel--playlist-length))
  841. (libmpdel-send-commands
  842. (mapcar (lambda (song)
  843. (format "moveid %s %s" (libmpdel-song-id song) (1+ (libmpdel-song-position song))))
  844. songs)))))
  845. (defun libmpdel-playlist-save (name)
  846. "Save current playlist as new stored playlist named NAME."
  847. (interactive (list (read-from-minibuffer "Enter a new playlist name: ")))
  848. (libmpdel-send-command
  849. `("save %S" ,name)
  850. (lambda (_data) (message "Current playlist saved to %S" name))))
  851. ;;; Playback queries
  852. ;;;###autoload
  853. (defun libmpdel-playback-set-volume (volume)
  854. "Set volume to VOLUME."
  855. (interactive (list
  856. (read-string (format "Current volume is %s. New volume [0-100]: "
  857. (libmpdel-volume)))))
  858. (libmpdel-send-command `("setvol %s" ,volume)))
  859. ;;;###autoload
  860. (defun libmpdel-playback-next ()
  861. "Play next song in the playlist."
  862. (interactive)
  863. (libmpdel-send-command "next"))
  864. ;;;###autoload
  865. (defun libmpdel-playback-previous ()
  866. "Play previous song in the playlist."
  867. (interactive)
  868. (libmpdel-send-command "previous"))
  869. ;;;###autoload
  870. (defun libmpdel-play ()
  871. "Start playing."
  872. (interactive)
  873. (libmpdel-send-command "play"))
  874. ;;;###autoload
  875. (defun libmpdel-stop ()
  876. "Stop playing. See also `libmpdel-playback-play-pause'."
  877. (interactive)
  878. (libmpdel-send-command "stop"))
  879. (defun libmpdel-play-song (song)
  880. "Start playing SONG."
  881. (let ((song-id (libmpdel-song-id song)))
  882. (if song-id
  883. (libmpdel-send-command `("playid %s" ,song-id))
  884. (libmpdel-current-playlist-insert song))))
  885. ;;;###autoload
  886. (defun libmpdel-playback-play-pause ()
  887. "Toggle between play and pause.
  888. See also `libmpdel-playback-stop'."
  889. (interactive)
  890. (libmpdel-send-command
  891. (cl-case libmpdel--play-state
  892. (play "pause 1")
  893. (pause "pause 0")
  894. (stop "play"))))
  895. ;;;###autoload
  896. (defun libmpdel-playback-seek (time &optional handler)
  897. "Seeks to the position TIME within the current song.
  898. TIME is a string indicating a number of seconds, fractions
  899. allowed. If prefixed by + or -, then the time is relative to
  900. the current playing position.
  901. If HANDLER is non-nil, execute it with no parameter when seek
  902. succeeds."
  903. (interactive (list (read-string "New position (e.g., 67, -23, +12): ")
  904. (lambda (_) (message "Seek done."))))
  905. (libmpdel-send-command
  906. `("seekcur %S" ,time)
  907. (when handler (lambda (_) (funcall handler)))))
  908. ;;;###autoload
  909. (defun libmpdel-playback-set-random ()
  910. "Set playback mode to random."
  911. (interactive)
  912. (libmpdel-send-command `("random 1")))
  913. ;;;###autoload
  914. (defun libmpdel-playback-unset-random ()
  915. "Set playback mode to sequential (not random)."
  916. (interactive)
  917. (libmpdel-send-command `("random 0")))
  918. ;;;###autoload
  919. (defun libmpdel-playback-set-repeat ()
  920. "Set playback mode to repeat."
  921. (interactive)
  922. (libmpdel-send-command `("repeat 1")))
  923. ;;;###autoload
  924. (defun libmpdel-playback-unset-repeat ()
  925. "Set playback mode to sequential (not repeat)."
  926. (interactive)
  927. (libmpdel-send-command `("repeat 0")))
  928. ;;;###autoload
  929. (defun libmpdel-playback-set-single-forever ()
  930. "Set playback single mode to forever.
  931. This will repeat the current song forever."
  932. (interactive)
  933. (libmpdel-send-command `("single 1")))
  934. ;;;###autoload
  935. (defun libmpdel-playback-set-single-never ()
  936. "Set playback single mode to never.
  937. This will not repeat the current song."
  938. (interactive)
  939. (libmpdel-send-command `("single 0")))
  940. ;;;###autoload
  941. (defun libmpdel-playback-set-single-once ()
  942. "Set playback single mode to once.
  943. This will repeat the current song only once and then keep playing
  944. the current playlist."
  945. (interactive)
  946. (libmpdel-send-command `("single oneshot")))
  947. ;;; Status queries
  948. (defun libmpdel-refresh-status ()
  949. "Ask the server for its current status."
  950. (libmpdel-send-command "status" #'libmpdel--msghandler-status))
  951. ;;; Database queries
  952. ;;;###autoload
  953. (defun libmpdel-database-update (&optional uri)
  954. "Update the music database for URI, everything if nil.
  955. Updates the music database: find new files, remove deleted files,
  956. update modified files.
  957. URI is a particular directory or song/file to update. If you do
  958. not specify it, everything is updated."
  959. (interactive "i")
  960. (libmpdel-send-command
  961. (if uri `("update %S" ,uri) "update")))
  962. (provide 'libmpdel)
  963. ;;; libmpdel.el ends here
  964. ;; Local Variables:
  965. ;; checkdoc-arguments-in-order-flag: nil
  966. ;; End: