Emacs libraries and little utilities
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.

23 KiB

consulting spotify

(Note: you can tangle this file (e.g., with C-c C-v t inside Emacs) into three elisp libraries, espotify.el, espotify-consult.el, =espotify-embark. and espotify-counsel)

We have two kinds of interaction with Spotify: via its HTTP API to perform operations such as search, and via our local DBUS to talk to client players running in our computer, such as the official client, spotifyd or mopidy-spotify. Our goal is to obtain via the former a track or album identifier that we can send then to the latter to play, with emacs completion mechanisms (consult and friends in this case) providing the glue between both worlds.

Let's start with an umbrella customization group:

  ;;; espotify.el - spotify search and play -  -*- lexical-binding: t; -*-

  (defgroup espotify nil
    "Access to Spotify API and clients"
    :group 'multimedia)

Access to Spotify's API: authentication

I am stealing most of the ideas on how to establish authenticated connections to the Spotify API and performing queries from counsel-spotify, with many simplifications.

We start defining a couple of end-points:

  (defvar espotify-spotify-api-url "https://api.spotify.com/v1")
  (defvar espotify-spotify-api-authentication-url

And we're going to need as well a client id and secret for our application, which i am again defining as variables since i expect them to be set in some secure manner instead of via customize:

  (defvar espotify-client-id nil "Spotify application client ID.")
  (defvar espotify-client-secret nil "Spotify application client secret.")

To get valid values for them, one just needs to register a Spotify application. From them we can derive a base64-encoded credentials value:

  (defun espotify--basic-auth-credentials ()
    (let ((credential (concat espotify-client-id ":" espotify-client-secret)))
      (concat "Basic " (base64-encode-string credential t))))

The return value of the function above is to be used as the "Authorization" header of our requests to the authorization end-point, which is going to answer with an authorization token that we can then use to further requests. Let's define a function to wrap that operation:

  (defun espotify--with-auth-token (callback)
    (let ((url-request-method "POST")
          (url-request-data "&grant_type=client_credentials")
           `(("Content-Type" . "application/x-www-form-urlencoded")
             ("Authorization" . ,(espotify--basic-auth-credentials)))))
       (url-retrieve espotify-spotify-api-authentication-url
                     (lambda (_status)
                       (goto-char url-http-end-of-headers)
                       (funcall callback
                                (alist-get 'access_token (json-read)))))))

For instance:

   (lambda (token) (message "Your token is: %s" token)))

obtains an auth token and prints it as a message. Note that body is evaluated asynchronously by url-retrieve, so invocations to espotify-with-auth-token evaluate to the request's buffer and are usually discarded.

Search queries using the Spotify API

We are interested in performing a search for some term, of items of a given types (:track, :album, :artist, etc.), possibly with an additional filter. That's specified in a GET request's URL as constructed by this function:

  (defun espotify--make-search-url (term types &optional filter)
    (when (null types)
      (error "Must supply a non-empty list of types to search for"))
    (let ((term (url-encode-url term)))
      (format "%s/search?q=%s&type=%s&limit=50"
              (if filter (format "%s:%s" filter term) term)
              (mapconcat #'symbol-name types ","))))

For instance:

  (espotify--make-search-url "dream blue turtles" '(album))

If we have an authorisation token and a search URL in our hands, we can use them as in the following helper function, which will calls the given callback with the results of the query:

  (defun espotify--with-query-results (token url callback)
    (let ((url-request-extra-headers
           `(("Authorization" . ,(concat "Bearer " token)))))
      (url-retrieve url
                    (lambda (_status)
                      (goto-char url-http-end-of-headers)
                      (funcall callback
                               (let ((json-array-type 'list))
                                     (buffer-substring (point) (point-max))
                                   (decode-coding-string 'utf-8)

So we can combine this macro with espotify--with-auth-token in a single search function that takes a callback that will be applied to a given query, specified as a triple of term, types and filter:

  (defun espotify-get (callback url)
       (lambda (token)
         (espotify--with-query-results token url callback))))

  (defun espotify-search (callback term types &optional filter)
    (espotify-get callback (espotify--make-search-url term types filter)))

For instance:

  (defvar espotify-query-result nil)
  (espotify-search (lambda (res) (setq espotify-query-result res))
                   "dream blue turtles"
                   '(album artist))
  (sit-for 0)
  (mapcar 'car espotify-query-result)
albums artists

So Spotify is returning a results entry per type, which in turn, contains an items with the list of actual results. So let's provide an interface for a callback that takes as many lists of items as types it asks for:

  (defun espotify--type-items (res type)
    (alist-get 'items (alist-get (intern (format "%ss" type)) res)))

  (defun espotify-search* (callback term types &optional filter)
    (let* ((types (if (listp types) types (list types)))
           (cb (lambda (res)
                 (let ((its (mapcar (lambda (tp)
                                      (espotify--type-items res tp))
                   (apply callback its)))))
      (espotify-search cb term types filter)))

For example:

  (defvar espotify-query-result nil)
  (espotify-search* (lambda (al ar)
                      (message "Found %s albums, %s artists"
                               (length al) (length ar))
                      (setq espotify-query-result (cons al ar)))
                   "blue turtles"
                   '(album artist))
  (sit-for 0)
  (list (mapcar 'car (car (car espotify-query-result)))
        (mapcar 'car (car (cdr espotify-query-result))))
album_type artists available_markets external_urls href id images name release_date release_date_precision total_tracks type uri
external_urls followers genres href id images name popularity type uri

Another strategy would be to search for several types and pass to our callback the concatenation of all items:

  (defun espotify-search-all (callback term &optional types filter)
    (let ((types (or types '(album track artist playlist))))
      (espotify-search* (lambda (&rest items)
                          (funcall callback (apply 'append items)))

Listing user resources in the Spotify API

It is also possible to obtain lists of items of a given type for the current user, with a standard URL format:

  (defun espotify--make-user-url (type)
    (format "%s/me/%ss" espotify-spotify-api-url (symbol-name type)))

and we can then use espotify-get to offer access to our playlists, albums, etc.:

  (defun espotify-with-user-resources (callback type)
    (espotify-get (lambda (res) (funcall callback (alist-get 'items res)))
                  (espotify--make-user-url type)))

Sending commands to local players

Once we now the URI we want to play (that uri entry in our items), sending it to a local player via DBUS is fairly easy. Let's define a couple of customizable variables pointing to the service name and bus:

  (defcustom espotify-service-name "mopidy"
    "Name of the DBUS service used by the client we talk to.

  The official Spotify client uses `spotify', but one can also use
  alternative clients such as mopidy or spotifyd."
    :type 'string)

  (defcustom espotify-use-system-bus-p t
    "Whether to access the spotify client using the system DBUS.")

and then using the Emacs DBUS API to send methods to it is a breeze:

  (defun espotify-call-spotify-via-dbus (method &rest args)
    "Tell Spotify to execute METHOD with ARGS through DBUS."
    (apply #'dbus-call-method `(,(if espotify-use-system-bus-p :system :session)
                                ,(format "org.mpris.MediaPlayer2.%s"

  (defun espotify-play-uri (uri)
    (espotify-call-spotify-via-dbus "OpenUri" uri))

Search front-end using consult

I am exploring consult.el (and friends) to replace ivy/counsel, inspired in part by Protesilaos Stavrou's musings, and liking a lot what i see. Up till now, everything i had with counsel is supported, often in better ways, with one exception: completing search of spotify albums using counsel-spotify. So let's fix that by defining an asynchronous consult function that does precisely that!

The top-level command will have this form:

  ;;; espotify-consult.el - consult support -  -*- lexical-binding: t; -*-

  (require 'espotify)
  (require 'consult)

  (defvar espotify-consult-history nil)

  (defun consult-spotify-by (type &optional filter)
    (let ((orderless-matching-styles '(orderless-literal)))
      (consult--read (format "Search %ss: " type)
                     (espotify--search-generator type filter)
                     :lookup 'espotify--consult-lookup
                     :category 'espotify-search-item
                     :history 'espotify-consult-history
                     :initial "#"
                     :require-match t)))

where we can write an asynchronous generator of search results with the helper function:

  (defun espotify--search-generator (type filter)
    (thread-first (consult--async-sink)
      (consult--async-map #'espotify--format-item)
      (espotify--async-search type filter)

The above follows a generic consult pattern, where all functions are pre-defined for us except espotify--async-search, an asynchronous dispatcher closure that must generate and handle a list of candidates, responding to a set of action messages (init, reset, get, flush, etc.) 1 Here's its definition in our case:

  (defvar espotify-search-suffix "="
    "Suffix in the search string launching an actual Web query.")

  (defun espotify--async-search (next type filter)
    (lambda (action)
      (pcase action
        ((pred stringp)
         (when (string-suffix-p espotify-search-suffix action)
            (lambda (x)
              (funcall next 'flush)
              (funcall next x))
            (substring action 0 (- (length action)
                                   (length espotify-search-suffix)))
        (_ (funcall next action)))))

We have introduced the convention that we're only launching a search when the input string ends in "=", to avoid piling on HTTP requests.

When processing the results, we format them as a displayable string, while hiding in a property the URI that will allow us to play the item (and pass the formatter to consult-async--map, in espotify--search-generator above):

  (defun espotify--additional-info (x)
    (mapconcat 'identity
               (seq-filter 'identity
                           `(,(alist-get 'name (alist-get 'album x))
                             ,(alist-get 'name (car (alist-get 'artists x)))
                             ,(alist-get 'display_name (alist-get 'owner x))))
               ", "))

  (defun espotify--format-item (x)
    (propertize (format "%s%s"
                        (alist-get 'name x)
                        (if-let ((info (espotify--additional-info x)))
                            (format " (%s)" info)
                'espotify-item x))

  (defun espotify--item (cand)
    (get-text-property 0 'espotify-item cand))

  (defun espotify--uri (cand)
    (alist-get 'uri (espotify--item cand)))

and then we make sure that we access that original string when consult looks up for it using the :lookup function, which we can simply define as:

  (require 'seq)
  (defun espotify--consult-lookup (_input cands cand)
    (seq-find (lambda (x) (string= cand x)) cands))

With that, when we receive the final result from consult--read, we can play the selected URI right away:

  (defun espotify--maybe-play (cand)
    (when-let (uri (when cand (espotify--uri cand)))
      (espotify-play-uri uri)))

And here, finally, are our interactive command to search and play albums using consult:

  (defun consult-spotify-album (&optional filter)
    (espotify--maybe-play (consult-spotify-by 'album filter)))

And likewise for playlists, artists and combinations thereof:

   (defun consult-spotify-artist (&optional filter)
     (espotify--maybe-play (consult-spotify-by 'artist filter)))
   (defun consult-spotify-track (&optional filter)
     (espotify--maybe-play (consult-spotify-by 'track filter)))
   (defun consult-spotify-playlist (&optional filter)
     (espotify--maybe-play (consult-spotify-by 'playlist filter)))

Adding metadata to candidates using Marginalia

Let's add metadata fields to our candidates, so that packages like Marginalia can offer it to consult or selectrum.

  (defun espotify-marginalia-annotate (cand)
    (when-let (x (espotify--item cand))
       ((alist-get 'type x "") :face 'marginalia-mode :width 10)
       ((if-let (d (alist-get 'duration_ms x))
            (let ((secs (/ d 1000)))
              (format "%02d:%02d" (/ secs 60) (mod secs 60)))
       ((if-let (d (alist-get 'total_tracks x)) (format "%s tracks" d) "")
        :face 'marginalia-size :width 12)
       ((if-let (d (alist-get 'release_date (alist-get 'album x x)))
            (format "%s" d)
        :face 'marginalia-date :width 10))))

  (add-to-list 'marginalia-annotators-heavy
               '(espotify-search-item . espotify-marginalia-annotate))

Embark actions

In addition to the default action (play the URI in the selected candidate), we can use embark to define other operations. For instance, we could print the full item alist in its own buffer, or always look for an album to play:

  (require 'espotify-consult)
  (require 'embark)

  (defvar espotify--current-item nil)

  (defun espotify--show-info (name)
    "Show low-level info (an alist) about selection."
    (interactive "s")
    (pop-to-buffer (get-buffer-create "*espotify info*"))
    (read-only-mode -1)
    (delete-region (point-min) (point-max))
    (insert (propertize name 'face 'bold))
    (when espotify--current-item
      (insert (pp-to-string espotify--current-item)))
    (goto-char (point-min))
    (read-only-mode 1))

  (defun espotify--play-album (ignored)
    "Play album associated with selected item."
    (interactive "i")
    (if-let (album (if (string= "album"
                                (alist-get 'type espotify--current-item ""))
                     (alist-get 'album espotify--current-item)))
        (espotify-play-uri (alist-get 'uri album))
      (error "No album for %s" (alist-get 'nmae espotify--current-item))))

  (embark-define-keymap espotify-item-keymap
    "Actions for Spotify search results"
    ("a" espotify--play-album)
    ("h" espotify--show-info))

  (defun espotify--annotate-item (cand)
    (setq espotify--current-item (espotify--item cand))
    (cons 'espotify-search-item cand))

  (add-to-list 'embark-transformer-alist
               '(espotify-search-item . espotify--annotate-item))

  (add-to-list 'embark-keymap-alist
               '(espotify-search-item . espotify-item-keymap))

Search fronted using ivy

  ;;; counsel-espotify.el - counsel and spotify -  -*- lexical-binding: t; -*-
  (require 'espotify)
  (require 'ivy)

It is is also not too complicated to provide a counsel collection of functions. Here, we use ivy-read to access the completion interface, with the flag dynamic-collection set. Ivy will wait until we call ivy-candidate-updates with our items.

  (defun counsel-espotify--search-by (type filter)
    (lambda (term)
      (espotify-search-all (lambda (its)
                             (let ((cs (mapcar #'espotify--format-item its)))
                               (ivy-update-candidates cs)))

With that, we can define our generic completing read:

  (defun espotify-counsel--play-album (candidate)
    "Play album associated with selected item."
    (interactive "s")
    (let ((item (espotify--item candidate)))
      (if-let (album (if (string= "album" (alist-get 'type item ""))
                       (alist-get 'album item)))
          (espotify-play-uri (alist-get 'uri album))
        (error "No album for %s" (alist-get 'name item)))))

  (defun espotify--by (type filter)
    (ivy-read (format "Search %s: " type)
              (counsel-espotify--search-by type filter)
              :dynamic-collection t
              :action `(1 ("a" espotify-counsel--play-album "Play album")
                          ("p" espotify--maybe-play ,(format "Play %s" type)))))
  (defun counsel-spotify-album (&optional filter)
    (espotify--by 'album filter))

  (defun counsel-spotify-artist (&optional filter)
    (espotify--by 'artist filter))

  (defun counsel-spotify-track (&optional filter)
    (espotify--by 'track filter))

  (defun counsel-spotify-playlist (&optional filter)
    (espotify--by 'playlist filter))

Much simpler than consult, although it's true that we already had part of the job done. And we're missing some of the funcionality, like on-demand throttling. That part is not difficult to fix:

  (defun counsel-espotify--search-by (type filter)
    (lambda (term)
      (when (string-suffix-p "=" (or term ""))
        (espotify-search-all (lambda (its)
                               (let ((cs (mapcar #'espotify--format-item its)))
                                 (ivy-update-candidates cs)))


  (provide 'espotify)
  (provide 'espotify-consult)
  (provide 'espotify-embark)
  (provide 'espotify-counsel)



This is an elegant strategy i first learnt about in SICP, many, many years ago, and i must say that it is very charming to find it around in the wild!