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.

1193 lines
42KB

  1. ;;; libmpdel.el --- Communication with an MPD server -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2017-2020 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-playing-p ()
  456. "Return non-nil if player is playing, nil otherwise."
  457. (eq 'play (libmpdel-play-state)))
  458. (defun libmpdel-paused-p ()
  459. "Return non-nil if player is paused, nil otherwise."
  460. (eq 'pause (libmpdel-play-state)))
  461. (defun libmpdel-stopped-p ()
  462. "Return non-nil if player is stopped, nil otherwise."
  463. (eq 'stop (libmpdel-play-state)))
  464. (libmpdel--define-state current-song
  465. "An entity representing currently played song."
  466. (when (libmpdel--new-current-song-p new-value)
  467. (libmpdel-send-command
  468. "currentsong"
  469. (lambda (data)
  470. (setq libmpdel--current-song (and data (libmpdel--create-song-from-data data)))
  471. (run-hooks 'libmpdel-current-song-changed-hook)))))
  472. (defun libmpdel--new-current-song-p (song-id)
  473. "Return non-nil if SONG-ID differs from `libmpdel--current-song'."
  474. (let ((current-song-id (and libmpdel--current-song (libmpdel-song-id libmpdel--current-song))))
  475. (not (equal song-id current-song-id))))
  476. (libmpdel--define-state playlist-length
  477. "Number of songs in current playlist."
  478. (setq libmpdel--playlist-length (string-to-number new-value)))
  479. (libmpdel--define-state volume
  480. "Value is a string representing a number between 0 and 100."
  481. (setq libmpdel--volume new-value))
  482. (libmpdel--define-state random
  483. "Boolean indicating if songs are played randomly or in order."
  484. (setq libmpdel--random (string= new-value "1")))
  485. (libmpdel--define-state repeat
  486. "Boolean indicating if current playlist or song is repeated after it ends."
  487. (setq libmpdel--repeat (string= new-value "1")))
  488. (libmpdel--define-state single
  489. "Symbol indicating if current song is repeated `forever', only `once' or `never'."
  490. (setq libmpdel--single
  491. (cond
  492. ((string= new-value "oneshot") 'once)
  493. ((string= new-value "1") 'forever)
  494. (t 'never))))
  495. (defun libmpdel-time-to-string (time)
  496. "Return a string represeting TIME, a number in a string."
  497. (if (not time)
  498. "0"
  499. (let* ((time (string-to-number time))
  500. (seconds (mod time 60))
  501. (minutes (/ (- time seconds) 60)))
  502. (format "%02d:%02d" (truncate minutes) (truncate seconds)))))
  503. (defun libmpdel-completing-read (prompt entities &optional transformer)
  504. "PROMPT user to select one entity among ENTITIES.
  505. Transform each entity to a string with TRANSFORMER,
  506. `libmpdel-entity-name' if nil."
  507. (let* ((transformer (or transformer #'libmpdel-entity-name))
  508. (map (make-hash-table :test 'equal :size (length entities)))
  509. (entity-strings (mapcar (lambda (entity) (funcall transformer entity)) entities)))
  510. (cl-mapcar (lambda (entity entity-string)
  511. (puthash entity-string entity map))
  512. entities entity-strings)
  513. (let ((entity-string (completing-read prompt entity-strings nil t)))
  514. (gethash entity-string map))))
  515. (defun libmpdel-completing-read-entity (function prompt entity &optional transformer)
  516. "Call FUNCTION after prompting for an element of ENTITY.
  517. Pass PROMPT, the elements of ENTITY and TRANSFORMER to
  518. `libmpdel-completing-read'."
  519. (libmpdel-list
  520. entity
  521. (lambda (entities)
  522. (funcall function
  523. (libmpdel-completing-read prompt entities transformer)))))
  524. (defun libmpdel-funcall-on-stored-playlist (function)
  525. "Pass a stored playlist as parameter to FUNCTION.
  526. The user is asked to choose for a stored playlist first."
  527. (libmpdel-completing-read-entity
  528. function
  529. "Stored playlist: "
  530. 'stored-playlists))
  531. (defun libmpdel-current-playlist-add (entity)
  532. "Add ENTITY to a current playlist.
  533. ENTITY can also be a list of entities to add."
  534. (libmpdel-playlist-add entity 'current-playlist))
  535. (defun libmpdel-current-playlist-replace (entity)
  536. "Replace current playlist with ENTITY.
  537. ENTITY can also be a list of entities to replace with."
  538. (libmpdel-playlist-replace entity 'current-playlist))
  539. (defun libmpdel-stored-playlist-add (entity)
  540. "Add ENTITY to a stored playlist.
  541. The user is asked to choose for a stored playlist first.
  542. ENTITY can also be a list of entities to add."
  543. (libmpdel-funcall-on-stored-playlist
  544. (apply-partially #'libmpdel-playlist-add entity)))
  545. (defun libmpdel-stored-playlist-replace (entity)
  546. "Replace a stored playlist with ENTITY.
  547. The user is asked to choose for a stored playlist first.
  548. ENTITY can also be a list of entities to replace with."
  549. (libmpdel-funcall-on-stored-playlist
  550. (apply-partially #'libmpdel-playlist-replace entity)))
  551. (defun libmpdel-current-playlist-insert (entity)
  552. "Insert ENTITY after currently-played song and play it.
  553. ENTITY can also be a list of entities in which case all entities
  554. are added and the first one is played."
  555. (libmpdel-list-songs
  556. entity
  557. (lambda (songs)
  558. (libmpdel-send-commands
  559. (mapcar (lambda (song) (format "addid %S" (libmpdel-song-file song))) songs)
  560. (lambda (data)
  561. (let ((song-ids (mapcar (lambda (song-data) (cdr song-data)) data))
  562. ;; Add after current song if possible:
  563. (target-index (if (libmpdel-current-song) "-1" "0")))
  564. (libmpdel-send-commands
  565. ;; The reverse is important to get the songs in the same
  566. ;; order as in the selection:
  567. (mapcar
  568. (lambda (song-id) (format "moveid %s %s" song-id target-index))
  569. (reverse song-ids))
  570. (lambda (_) (libmpdel-send-command `("playid %s" ,(car song-ids)))))))))))
  571. (defun libmpdel-async-mapcar (list mapfn callback)
  572. "Apply MAPFN to each element of LIST and pass result to CALLBACK.
  573. MAPFN is a function taking 2 arguments: the element to map and a
  574. callback to call when the mapping is done."
  575. (if (not list)
  576. (funcall callback nil)
  577. (funcall ; transform the first element
  578. mapfn
  579. (car list)
  580. (lambda (first-mapped)
  581. (libmpdel-async-mapcar ; transform the rest
  582. (cdr list)
  583. mapfn
  584. (lambda (latter-elements)
  585. (funcall callback
  586. (cons first-mapped
  587. latter-elements))))))))
  588. (defun libmpdel-async-mapcan (list mapfn callback)
  589. "Apply MAPFN to each element of LIST.
  590. Concatenate the results and pass that to CALLBACK.
  591. MAPFN is a function taking 2 arguments: the element to map and a
  592. callback to call when the mapping is done."
  593. (libmpdel-async-mapcar
  594. list
  595. mapfn
  596. (lambda (groups)
  597. (funcall
  598. callback
  599. (apply #'cl-concatenate 'list groups)))))
  600. (defun libmpdel--get-profile-from-name (name)
  601. "Return an element of `libmpdel-profiles' matching NAME."
  602. (cl-find name libmpdel-profiles :test #'string= :key #'car))
  603. (defun libmpdel--select-profile ()
  604. "Ask the user to select a profile among `libmpdel-profiles' and return it."
  605. (unless (consp libmpdel-profiles)
  606. (user-error "Add profiles to `libmpdel-profiles'"))
  607. (if (= 1 (length libmpdel-profiles))
  608. (progn
  609. (message "Only 1 profile defined in `libmpdel-profiles'")
  610. (car libmpdel-profiles))
  611. (let* ((profile-names (mapcar #'car libmpdel-profiles))
  612. (profile-name (completing-read "Choose an MPD profile"
  613. profile-names nil t)))
  614. (libmpdel--get-profile-from-name profile-name))))
  615. ;;; Public functions
  616. (defun libmpdel-connected-p ()
  617. "Return non-nil if there is a connection to MPD server."
  618. (and libmpdel--connection
  619. (process-live-p (libmpdel--process))))
  620. (defun libmpdel-ensure-connection ()
  621. "Make sure there is an active connection to the MPD server."
  622. (unless (libmpdel-connected-p)
  623. (libmpdel--connect)))
  624. (defun libmpdel-disconnect ()
  625. "Close connection to the MPD server."
  626. (when (not (libmpdel-connected-p))
  627. (user-error "There is no connection to MPD"))
  628. (tq-close libmpdel--connection)
  629. (setq libmpdel--connection nil))
  630. (defun libmpdel-send-command (command &optional handler)
  631. "Send COMMAND to server and register HANDLER for the answer.
  632. If HANDLER is nil, ignore response."
  633. (libmpdel-ensure-connection)
  634. ;; if current command is IDLE, we have to cancel it. See
  635. ;; `mpdel-msghandlers' for more information.
  636. (when (eql (elt (car (last libmpdel--msghandlers)) 1) #'libmpdel--msghandler-idle)
  637. (libmpdel--raw-send-command "noidle"))
  638. (libmpdel--raw-send-command-with-handler command handler))
  639. (defun libmpdel-send-commands (commands &optional handler)
  640. "Send several COMMANDS at once and execute HANDLER once with result."
  641. (libmpdel-send-command
  642. (with-temp-buffer
  643. (insert "command_list_begin\n")
  644. (mapc (lambda (command) (insert command "\n")) commands)
  645. (insert "command_list_end")
  646. (buffer-substring-no-properties (point-min) (point-max)))
  647. handler))
  648. (defun libmpdel-entries (data key)
  649. "Collect DATA entries matching KEY."
  650. (mapcar #'cdr (cl-remove-if-not (apply-partially #'eq key) data :key #'car)))
  651. (defun libmpdel-sorted-entries (data key)
  652. "Sort and collect DATA entries matching KEY."
  653. (sort (libmpdel-entries data key) #'libmpdel--string<-ignore-case))
  654. (defun libmpdel-group-data (data)
  655. "Find repeating fields in DATA and group them."
  656. (when data
  657. (let ((first-key (caar data))
  658. result group)
  659. (mapc (lambda (key-value)
  660. (when (and
  661. (eq (car key-value) first-key)
  662. group)
  663. (push (reverse group) result)
  664. (setq group nil))
  665. (push key-value group))
  666. data)
  667. (push (reverse group) result)
  668. (reverse result))))
  669. (cl-defgeneric libmpdel-dired (entity)
  670. "Open `dired' on ENTITY.")
  671. (eval-when-compile
  672. (declare-function dired-jump "dired-x"))
  673. (cl-defmethod libmpdel-dired ((song libmpdel-song))
  674. "Open `dired' on SONG."
  675. (require 'dired-x)
  676. (dired-jump t (expand-file-name (libmpdel-song-file song) libmpdel-music-directory)))
  677. (defun libmpdel-equal (entity1 entity2)
  678. "Return non-nil if ENTITY1 and ENTITY2 represent the same entity."
  679. (equal (libmpdel-entity-id entity1) (libmpdel-entity-id entity2)))
  680. ;;; Helper queries
  681. (cl-defgeneric libmpdel-entity-to-criteria (entity)
  682. "Return search query matching all songs from ENTITY.")
  683. (cl-defmethod libmpdel-entity-to-criteria ((query string))
  684. "Return QUERY."
  685. query)
  686. (cl-defmethod libmpdel-entity-to-criteria ((artist libmpdel-artist))
  687. "Return search query matching all songs from ARTIST."
  688. (format "artist %S" (libmpdel-entity-name artist)))
  689. (cl-defmethod libmpdel-entity-to-criteria ((album libmpdel-album))
  690. "Return search query matching all songs from ALBUM."
  691. (format "%s album %S"
  692. (libmpdel-entity-to-criteria (libmpdel-artist album))
  693. (libmpdel-entity-name album)))
  694. (cl-defmethod libmpdel-entity-to-criteria ((song libmpdel-song))
  695. "Return search query matching SONG."
  696. (format "%s title %S"
  697. (libmpdel-entity-to-criteria (libmpdel-album song))
  698. (libmpdel-entity-name song)))
  699. (cl-defgeneric libmpdel-list (entity function)
  700. "Call FUNCTION with all children of ENTITY as parameter."
  701. (libmpdel-list-songs entity function))
  702. (cl-defmethod libmpdel-list ((_entity (eql artists)) function)
  703. "Call FUNCTION with all artists as parameter."
  704. (libmpdel-send-command
  705. "list artist"
  706. (lambda (data)
  707. (funcall function
  708. (mapcar
  709. (lambda (artist-name) (libmpdel--artist-create :name artist-name))
  710. (libmpdel-sorted-entries data 'Artist))))))
  711. (defvar libmpdel--unknown-artist
  712. (libmpdel--artist-create :name "")
  713. "An anonymous artist instance.")
  714. (cl-defmethod libmpdel-list ((_entity (eql albums)) function)
  715. "Call FUNCTION with all albums as parameter."
  716. (libmpdel-send-command
  717. "list album"
  718. (lambda (data)
  719. (funcall function
  720. (mapcar
  721. (lambda (album-name)
  722. (libmpdel--album-create :name album-name
  723. :artist libmpdel--unknown-artist))
  724. (libmpdel-sorted-entries data 'Album))))))
  725. (cl-defmethod libmpdel-list ((_entity (eql stored-playlists)) function)
  726. "Call FUNCTION with all stored playlists as parameter."
  727. (libmpdel-send-command
  728. "listplaylists"
  729. (lambda (data)
  730. (funcall function
  731. (mapcar
  732. (lambda (playlist-name) (libmpdel--stored-playlist-create :name playlist-name))
  733. (libmpdel-sorted-entries data 'playlist))))))
  734. (cl-defmethod libmpdel-list ((artist libmpdel-artist) function)
  735. "Call FUNCTION with all albums of ARTIST as parameter."
  736. (libmpdel-send-command
  737. `("list album %s" ,(libmpdel-entity-to-criteria artist))
  738. (lambda (data)
  739. (funcall function
  740. (mapcar
  741. (lambda (album-name) (libmpdel--album-create :name album-name :artist artist))
  742. (libmpdel-sorted-entries data 'Album))))))
  743. (cl-defgeneric libmpdel-list-songs (entity function)
  744. "Call FUNCTION with all songs of ENTITY."
  745. (libmpdel-send-command
  746. `("find %s" ,(libmpdel-entity-to-criteria entity))
  747. (lambda (data)
  748. (funcall function (libmpdel--create-songs-from-data data)))))
  749. (cl-defmethod libmpdel-list-songs ((stored-playlist libmpdel-stored-playlist) function)
  750. "Call FUNCTION with all songs of STORED-PLAYLIST."
  751. (libmpdel-send-command
  752. `("listplaylistinfo %S" ,(libmpdel-entity-name stored-playlist))
  753. (lambda (data)
  754. (funcall function (libmpdel--create-songs-from-data data)))))
  755. (cl-defmethod libmpdel-list-songs ((_ (eql current-playlist)) function)
  756. "Call FUNCTION with all songs of the current playlist."
  757. (libmpdel-send-command
  758. "playlistinfo"
  759. (lambda (data)
  760. (funcall function (libmpdel--create-songs-from-data data)))))
  761. (cl-defmethod libmpdel-list-songs ((search-criteria libmpdel-search-criteria) function)
  762. "Call FUNCTION with all songs matching SEARCH-CRITERIA."
  763. (libmpdel-send-command
  764. `("search %s %S"
  765. ,(libmpdel--search-criteria-type search-criteria)
  766. ,(libmpdel--search-criteria-what search-criteria))
  767. (lambda (data)
  768. (funcall function (libmpdel--create-songs-from-data data)))))
  769. (cl-defmethod libmpdel-list-songs ((filter libmpdel-filter) function)
  770. "Call FUNCTION with all songs matching FILTER."
  771. (libmpdel-send-command
  772. `("search %S" ,(libmpdel--filter-text filter))
  773. (lambda (data)
  774. (funcall function (libmpdel--create-songs-from-data data)))))
  775. (cl-defmethod libmpdel-list-songs ((song libmpdel-song) function)
  776. "Call FUNCTION with SONG."
  777. (funcall function (list song)))
  778. (cl-defmethod libmpdel-list-songs ((entities list) function)
  779. "Call FUNCTION with all songs in ENTITIES."
  780. (libmpdel-async-mapcan entities #'libmpdel-list-songs function))
  781. ;;; Playlist queries
  782. (cl-defgeneric libmpdel-playlist-add (entity playlist)
  783. "Add ENTITY to PLAYLIST.
  784. ENTITY can also be a list of entities to add.")
  785. (cl-defmethod libmpdel-playlist-add (entity (_ (eql current-playlist)))
  786. "Add ENTITY to the current playlist."
  787. (let ((id (libmpdel-entity-id entity)))
  788. (libmpdel-send-command
  789. (if (and (stringp id) (not (string-empty-p id)))
  790. `("addid %S" ,id)
  791. `("findadd %s" ,(libmpdel-entity-to-criteria entity))))))
  792. (cl-defmethod libmpdel-playlist-add (entity (stored-playlist libmpdel-stored-playlist))
  793. "Add ENTITY to STORED-PLAYLIST."
  794. (libmpdel-send-command
  795. `("searchaddpl %S %s"
  796. ,(libmpdel-entity-name stored-playlist)
  797. ,(libmpdel-entity-to-criteria entity))))
  798. (cl-defmethod libmpdel-playlist-add ((stored-playlist libmpdel-stored-playlist) (_ (eql current-playlist)))
  799. "Add content of STORED-PLAYLIST to the current playlist."
  800. (libmpdel-send-command `("load %S" ,(libmpdel-entity-name stored-playlist))))
  801. (cl-defmethod libmpdel-playlist-add ((entities list) playlist)
  802. "Add all ENTITIES to PLAYLIST."
  803. (mapcar (lambda (entity) (libmpdel-playlist-add entity playlist))
  804. entities))
  805. (defun libmpdel-playlist-replace (entity playlist)
  806. "Clear PLAYLIST and add ENTITY to it."
  807. (libmpdel-playlist-clear playlist)
  808. (libmpdel-playlist-add entity playlist))
  809. (cl-defgeneric libmpdel-playlist-clear (playlist)
  810. "Remove all songs from PLAYLIST.")
  811. (cl-defmethod libmpdel-playlist-clear ((_ (eql current-playlist)))
  812. "Remove all songs from the current playlist."
  813. (libmpdel-send-command "clear"))
  814. (cl-defmethod libmpdel-playlist-clear ((stored-playlist libmpdel-stored-playlist))
  815. "Remove all songs from STORED-PLAYLIST."
  816. (libmpdel-send-command `("playlistclear %S" ,(libmpdel-entity-name stored-playlist))))
  817. (cl-defgeneric libmpdel-playlist-delete (songs playlist)
  818. "Remove SONGS from PLAYLIST.")
  819. (cl-defmethod libmpdel-playlist-delete (songs (_ (eql current-playlist)))
  820. "Remove SONGS from the current playlist."
  821. (libmpdel-send-commands
  822. (mapcar (lambda (song) (format "deleteid %s" (libmpdel-song-id song)))
  823. songs)))
  824. (cl-defmethod libmpdel-playlist-delete (songs (stored-playlist libmpdel-stored-playlist))
  825. "Remove SONGS from STORED-PLAYLIST."
  826. (libmpdel-list
  827. stored-playlist
  828. (lambda (all-playlist-songs)
  829. (let ((song-positions (cl-sort (mapcar (lambda (song)
  830. (cl-position song all-playlist-songs :test #'equal))
  831. songs)
  832. #'>)))
  833. (libmpdel-send-commands
  834. (mapcar
  835. (lambda (song-position)
  836. (format "playlistdelete %S %s"
  837. (libmpdel-entity-name stored-playlist)
  838. song-position))
  839. song-positions))))))
  840. (defun libmpdel-playlist-move-up (songs)
  841. "Move up SONGS in current playlist."
  842. ;; We should move up from first in playlist to last
  843. (let* ((songs (cl-sort (cl-copy-seq songs) #'< :key #'libmpdel-song-position)))
  844. ;; Don't move up if first song is selected
  845. (unless (= (libmpdel-song-position (car songs)) 0)
  846. (libmpdel-send-commands
  847. (mapcar (lambda (song)
  848. (format "moveid %s %s" (libmpdel-song-id song) (1- (libmpdel-song-position song))))
  849. songs)))))
  850. (defun libmpdel-playlist-move-down (songs)
  851. "Move down SONGS in current playlist."
  852. ;; We should move down from last in playlist to first
  853. (let* ((songs (cl-sort (cl-copy-seq songs) #'> :key #'libmpdel-song-position)))
  854. ;; Don't move down if last song is selected
  855. (unless (= (libmpdel-song-position (car songs)) (1- libmpdel--playlist-length))
  856. (libmpdel-send-commands
  857. (mapcar (lambda (song)
  858. (format "moveid %s %s" (libmpdel-song-id song) (1+ (libmpdel-song-position song))))
  859. songs)))))
  860. (defun libmpdel-playlist-save (name)
  861. "Save current playlist as new stored playlist named NAME."
  862. (interactive (list (read-from-minibuffer "Enter a new playlist name: ")))
  863. (libmpdel-send-command
  864. `("save %S" ,name)
  865. (lambda (_data) (message "Current playlist saved to %S" name))))
  866. ;;; Playback queries
  867. ;;;###autoload
  868. (defun libmpdel-playback-set-volume (volume)
  869. "Set volume to VOLUME."
  870. (interactive (list
  871. (read-string (format "Current volume is %s. New volume [0-100]: "
  872. (libmpdel-volume)))))
  873. (libmpdel-send-command `("setvol %s" ,volume)))
  874. ;;;###autoload
  875. (defun libmpdel-playback-next ()
  876. "Play next song in the playlist."
  877. (interactive)
  878. (libmpdel-send-command "next"))
  879. ;;;###autoload
  880. (defun libmpdel-playback-previous ()
  881. "Play previous song in the playlist."
  882. (interactive)
  883. (libmpdel-send-command "previous"))
  884. ;;;###autoload
  885. (defun libmpdel-play ()
  886. "Start playing."
  887. (interactive)
  888. (libmpdel-send-command "play"))
  889. ;;;###autoload
  890. (defun libmpdel-stop ()
  891. "Stop playing. See also `libmpdel-playback-play-pause'."
  892. (interactive)
  893. (libmpdel-send-command "stop"))
  894. (defun libmpdel-play-song (song)
  895. "Start playing SONG."
  896. (let ((song-id (libmpdel-song-id song)))
  897. (if song-id
  898. (libmpdel-send-command `("playid %s" ,song-id))
  899. (libmpdel-current-playlist-insert song))))
  900. ;;;###autoload
  901. (defun libmpdel-playback-play-pause ()
  902. "Toggle between play and pause.
  903. See also `libmpdel-playback-stop'."
  904. (interactive)
  905. (libmpdel-send-command
  906. (cl-case libmpdel--play-state
  907. (play "pause 1")
  908. (pause "pause 0")
  909. (stop "play"))))
  910. ;;;###autoload
  911. (defun libmpdel-playback-seek (time &optional handler)
  912. "Seeks to the position TIME within the current song.
  913. TIME is a string indicating a number of seconds, fractions
  914. allowed. If prefixed by + or -, then the time is relative to
  915. the current playing position.
  916. If HANDLER is non-nil, execute it with no parameter when seek
  917. succeeds."
  918. (interactive (list (read-string "New position (e.g., 67, -23, +12): ")
  919. (lambda (_) (message "Seek done."))))
  920. (libmpdel-send-command
  921. `("seekcur %S" ,time)
  922. (when handler (lambda (_) (funcall handler)))))
  923. ;;;###autoload
  924. (defun libmpdel-playback-set-random ()
  925. "Set playback mode to random."
  926. (interactive)
  927. (libmpdel-send-command `("random 1")))
  928. ;;;###autoload
  929. (defun libmpdel-playback-unset-random ()
  930. "Set playback mode to sequential (not random)."
  931. (interactive)
  932. (libmpdel-send-command `("random 0")))
  933. ;;;###autoload
  934. (defun libmpdel-playback-set-repeat ()
  935. "Set playback mode to repeat."
  936. (interactive)
  937. (libmpdel-send-command `("repeat 1")))
  938. ;;;###autoload
  939. (defun libmpdel-playback-unset-repeat ()
  940. "Set playback mode to sequential (not repeat)."
  941. (interactive)
  942. (libmpdel-send-command `("repeat 0")))
  943. ;;;###autoload
  944. (defun libmpdel-playback-set-single-forever ()
  945. "Set playback single mode to forever.
  946. This will repeat the current song forever."
  947. (interactive)
  948. (libmpdel-send-command `("single 1")))
  949. ;;;###autoload
  950. (defun libmpdel-playback-set-single-never ()
  951. "Set playback single mode to never.
  952. This will not repeat the current song."
  953. (interactive)
  954. (libmpdel-send-command `("single 0")))
  955. ;;;###autoload
  956. (defun libmpdel-playback-set-single-once ()
  957. "Set playback single mode to once.
  958. This will repeat the current song only once and then keep playing
  959. the current playlist."
  960. (interactive)
  961. (libmpdel-send-command `("single oneshot")))
  962. ;;; Status queries
  963. (defun libmpdel-refresh-status ()
  964. "Ask the server for its current status."
  965. (libmpdel-send-command "status" #'libmpdel--msghandler-status))
  966. ;;; Database queries
  967. ;;;###autoload
  968. (defun libmpdel-database-update (&optional uri)
  969. "Update the music database for URI, everything if nil.
  970. Updates the music database: find new files, remove deleted files,
  971. update modified files.
  972. URI is a particular directory or song/file to update. If you do
  973. not specify it, everything is updated."
  974. (interactive "i")
  975. (libmpdel-send-command
  976. (if uri `("update %S" ,uri) "update")))
  977. (provide 'libmpdel)
  978. ;;; libmpdel.el ends here
  979. ;; Local Variables:
  980. ;; checkdoc-arguments-in-order-flag: nil
  981. ;; End: