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.

1110 lines
39KB

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