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.

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