main
  1;;; my-empv-playlists.el --- Navidrome playlist actions for empv -*- lexical-binding: t; -*-
  2
  3(require 'cl-lib)
  4(require 'empv)
  5(require 'url-parse)
  6(require 'url-util)
  7
  8(defvar embark--run-after-command-functions)
  9
 10(defun my/empv-subsonic-embark-quit (orig prompt &optional on-quit)
 11  "Wrap ORIG's ON-QUIT for PROMPT so Embark can leave nested selectors."
 12  (funcall orig prompt
 13           (when on-quit
 14             (lambda ()
 15               ;; Embark queues its post-action work before quitting the
 16               ;; minibuffer.  Do not mistake that quit for back navigation.
 17               (unless (bound-and-true-p embark--run-after-command-functions)
 18                 (funcall on-quit))))))
 19
 20(advice-add 'empv--subsonic-result-handler :around #'my/empv-subsonic-embark-quit)
 21
 22(defun my/empv-playlist--song-ids (item)
 23  "Return the song IDs represented by Subsonic ITEM."
 24  (pcase (alist-get 'kind item)
 25    ('song (list (alist-get 'id item)))
 26    ('album (mapcar (lambda (song) (alist-get 'id song))
 27                    (alist-get 'results
 28                               (empv--subsonic-request "getAlbum.view" :id (alist-get 'id item)))))
 29    (_ (user-error "Select a song or album"))))
 30
 31(defun my/empv-playlist--queue-id (filename)
 32  "Return a Subsonic song ID from queue FILENAME, or nil."
 33  (when (stringp filename)
 34    (let* ((url (url-generic-parse-url (empv--clean-uri filename)))
 35           (base (url-generic-parse-url empv-subsonic-url))
 36           (path-and-query (split-string (or (url-filename url) "") "?"))
 37           (base-path (string-remove-suffix "/" (or (url-filename base) ""))))
 38      (when (and (equal (url-type url) (url-type base))
 39                 (equal (url-host url) (url-host base))
 40                 (equal (url-port url) (url-port base))
 41                 (equal (car path-and-query) (concat base-path "/rest/stream.view")))
 42        (cadr (assoc "id" (url-parse-query-string (or (cadr path-and-query) ""))))))))
 43
 44(defun my/empv-playlist--add (playlist-id ids)
 45  "Add IDS to PLAYLIST-ID in order, in bounded requests."
 46  (let ((added 0))
 47    (condition-case nil
 48        (while ids
 49          (let ((batch (seq-take ids 25)))
 50            (apply #'empv--subsonic-request "updatePlaylist.view"
 51                   :playlistId playlist-id
 52                   (cl-mapcan (lambda (id) (list :songIdToAdd id)) batch))
 53            (setq added (+ added (length batch))
 54                  ids (nthcdr (length batch) ids))))
 55      (error (user-error "Playlist update failed after %d tracks; playlist may be incomplete" added)))
 56    added))
 57
 58(defun my/empv-playlist--choose ()
 59  "Choose an owned writable playlist, or create one, and return its ID."
 60  (let* ((playlists (alist-get 'results (empv--subsonic-request "getPlaylists.view")))
 61         (candidates
 62          (cl-loop for playlist in playlists
 63                   when (and (equal (alist-get 'owner playlist) empv-subsonic-username)
 64                             (not (eq (alist-get 'readonly playlist) t)))
 65                   collect (cons (format "%s [%s]" (alist-get 'name playlist)
 66                                         (alist-get 'id playlist))
 67                                 (alist-get 'id playlist)))))
 68    (let* ((create "[Create new playlist]")
 69           (choice (completing-read "Add to playlist: " (cons create candidates) nil t)))
 70      (if (equal choice create)
 71          (let ((name (read-string "New playlist name: ")))
 72            (when (string-empty-p (string-trim name)) (user-error "Playlist name is empty"))
 73            (my/empv-playlist--create name))
 74        (cdr (assoc choice candidates))))))
 75
 76(defun my/empv-subsonic-add-to-playlist (item)
 77  "Add Subsonic song or album ITEM to a Navidrome playlist."
 78  (let ((ids (my/empv-playlist--song-ids item)))
 79    (unless (and ids (seq-every-p #'identity ids))
 80      (user-error "No valid songs found"))
 81    (let ((count (my/empv-playlist--add (my/empv-playlist--choose) ids)))
 82      (message "Added %d track(s) to playlist" count))))
 83
 84(defun my/empv-playlist--create (name)
 85  "Create a playlist named NAME and return its ID."
 86  ;; empv's response normalizer expects a createPlaylist object, but the
 87  ;; Subsonic endpoint returns a playlist object instead.
 88  (let* ((response (alist-get 'subsonic-response
 89                              (empv--request (empv--subsonic-build-url
 90                                              "createPlaylist.view" :name name))))
 91         (id (alist-get 'id (alist-get 'playlist response))))
 92    (unless (equal (alist-get 'status response) "ok")
 93      (user-error "Navidrome could not create the playlist"))
 94    (unless id (user-error "Playlist creation returned no ID"))
 95    id))
 96
 97(defun my/empv-save-queue-to-playlist (name)
 98  "Save the current mpv queue as a new Navidrome playlist called NAME."
 99  (interactive (list (read-string "New playlist name: ")))
100  (when (string-empty-p (string-trim name)) (user-error "Playlist name is empty"))
101  (unless (empv--running?) (user-error "empv is not running"))
102  (empv--let-properties '(playlist)
103    (let* ((ids (mapcar (lambda (item) (my/empv-playlist--queue-id (alist-get 'filename item)))
104                        .playlist))
105           (invalid (seq-count #'null ids)))
106      (cond
107       ((null ids) (message "Queue is empty; no playlist created"))
108       ((> invalid 0) (message "Queue contains %d non-Navidrome or unrecognized item(s); no playlist created" invalid))
109       (t
110        (let* ((id (my/empv-playlist--create name))
111               (count (my/empv-playlist--add id ids)))
112          (message "Created playlist '%s' with %d track(s)" name count)))))))
113
114(with-eval-after-load 'embark
115  (define-key empv-subsonic-item-action-map (kbd "a") #'my/empv-subsonic-add-to-playlist))
116
117(provide 'my-empv-playlists)
118;;; my-empv-playlists.el ends here