Interacting with spotify API and players inside emacs
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.
jao ea6d6021e5
wee refactoring (espotify-candidate-url)
1 year ago
.gitignore Initial commit 2 years ago
LICENSE Initial commit 2 years ago
consult-spotify.el consult-spotify: fix for input history specification 1 year ago
espotify.el wee refactoring (espotify-candidate-url) 1 year ago
ivy-spotify.el ivy-spotify: typos 2 years ago wee refactoring (espotify-candidate-url) 1 year ago

consulting spotify

Note: you can tangle this file (e.g., with C-c C-v t inside Emacs) into three elisp packages, namely espotify.el, consult-spotify.el, and ivy-spotify.el.

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:

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

Access to Spotify's REST APIs


We start defining a couple of end-points:

  (defvar espotify-spotify-api-url
    "End-point to access Spotify's REST API.")

  (defvar espotify-spotify-api-authentication-url
    "End-point to access Spotify's authentication tokens.")

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:

  (defcustom espotify-client-id ""
    "Spotify application client ID."
    :type 'string)

  (defcustom espotify-client-secret ""
    "Spotify application client secret."
    :type 'string)

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

  (defun espotify--basic-auth-credentials ()
    "Get credentials."
    (unless (and (> (length espotify-client-id) 0)
                 (> (length espotify-client-secret) 0))
      (user-error "Invalid Spotify credentials: please set `%s' and `%s'"
                  "espotify-client-id" "espotify-client-secret"))
    (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:

  (defvar url-http-end-of-headers)

  (defun espotify--with-auth-token (callback)
    "Use CALLBACK with a token."
    (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

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)
    "Use TERM, TYPES and FILTER to create a URL."
    (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)
    "Call CALLBACK with the results of browsing URL with TOKEN."
    (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)
    "Perform a GET query to URL, receiving its results with CALLBACK."
       (lambda (token)
         (espotify--with-query-results token url callback))))

  (defun espotify-search (callback term types &optional filter)
    "Perform a search query for TERM, receiving its results with CALLBACK.

  The types of resource we want is given by TYPES, and we can add an additional
  query 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)
    "Auxiliary function for RES and TYPE."
    (alist-get 'items (alist-get (intern (format "%ss" type)) res)))

  (defun espotify-search* (callback term types &optional filter)
    "Like `espotify-search', but CALLBACK receives lists of items types.
     TERM FILTER TYPES for checkdoc compliance."
    (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)
    "Like `espotify-search', but CALLBACK receives a single list of results.
     TERM, FILTER to make checkdoc happy."
    (let ((types (or types '(album track artist playlist))))
      (espotify-search* (lambda (&rest items)
                          (funcall callback (apply #'append items)))

Formatting and comparing search results

Search results as completion candidates

As we've seen in the previous section, our search callbacks will receive search results as alists, which we've been calling items, describing their properties. In completion functions manipulating those items we'll need ways of representing them as completion candidates, i.e., as strings with metadata attached as text properties. Thus, it's useful to define in our generic library a function, espotify-format-item to create such as string, as well as an accessor to the associated metadata:

  (defun espotify--additional-item-info (item)
    "Helper creating a string description of ITEM's metadata."
    (let ((names (mapcar (lambda (a) (alist-get 'name a))
                         (cons (alist-get 'album item)
                               (alist-get 'artists item))))
          (dname (alist-get 'display_name (alist-get 'owner item))))
      (mapconcat 'identity
                 (seq-filter #'identity (append names (list dname)))
                 ", ")))

  (defun espotify-format-item (item)
    "Format the search result ITEM as a string with additional metadata.
  The metadata will be accessible via `espotify-candidate-metadata'."
    (propertize (format "%s%s"
                        (alist-get 'name item)
                        (if-let ((info (espotify--additional-item-info item)))
                            (format " (%s)" info)
                'espotify-item item))

  (defun espotify-candidate-metadata (cand)
    "Extract from CAND (as returned by `espotify-format-item') its metadata."
    (get-text-property 0 'espotify-item cand))

Comparing search terms

Since our API involves HTTP calls using user terms that are going to be completed, we need a criterion to decide whether to launch one of those queries. An idea is to compare the current search term with the previous one and act only when it differs sufficiently. We will also introduce the convention that we're launching a search when the input string ends in "=".

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

  (defvar espotify-search-threshold 8
    "Threshold to automatically launch an actual Web query.")

  (defun espotify--distance (a b)
    "Distance between strings A and B."
    (if (fboundp 'string-distance)
        (string-distance a b)
      (abs (- (length a) (length b)))))

  (defun espotify-check-term (prev new)
    "Compare search terms PREV and NEW return the one we should search, if any."
    (when (not (string-blank-p new))
      (cond ((string-suffix-p espotify-search-suffix new)
             (substring new 0 (- (length new)
                                 (length espotify-search-suffix))))
            ((>= (espotify--distance prev new) espotify-search-threshold) new))))

Sending commands to local Spotify players

Once we now the URI we want to play (that uri entry in our candidates), 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."
    :type 'boolean)

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

  (defun espotify--dbus-call (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-with-dbus (uri)
    "Play the given URI using a DBUS connection."
    (espotify--dbus-call "OpenUri" uri))

  (defvar espotify-play-uri-function #'espotify-play-uri-with-dbus)

  (defun espotify-play-uri (uri)
    "Use a DBUS call to play a URI denoting a resource."
    (funcall espotify-play-uri-function uri))

For cases where it isn't a breeze (e.g., because our MPRIs connection is not up to it) we've added the additional flexibility of specifiying an alternative URI playing function.

We can also define a helper function that will play the URI associated to a formatted candidate, when present:

  (defun espotify-play-candidate (cand)
   "If CAND is a formatted item string and it has a URL, play it."
   (when-let (uri (alist-get 'uri (espotify-candidate-metadata cand)))
     (espotify-play-uri uri)))

Although we're not going to use them explicitly below, we can define a couple more commands that may come in handy:

 (defun espotify-play-pause ()
   "Toggle default Spotify player via DBUS."
   (espotify--dbus-call "PlayPause"))

 (defun espotify-next ()
   "Tell default Spotify player to play next track via DBUS."
   (espotify--dbus-call "Next"))

 (defun espotify-previous ()
   "Tell default Spotify player to play previous track via DBUS."
   (espotify--dbus-call "Previous"))

Other actions on search results

In addition to the default action (play the URI in the selected candidate), we can define other actions on completion candidates. For instance, we could print the full item alist in its own buffer, or always look for an underlying album to play. These actions just need to access the rich metadata attached to the candidate, and will be defined as regular one-argument functions.

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

  (defun espotify-play-candidate-album (candidate)
    "Play album associated with selected CANDIDATE."
    (when-let (item (espotify-candidate-metadata 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-candidate-url (candidate)
    "Retrieve the spotify URL for the given CANDIDATE."
    (when-let (item (espotify-candidate-metadata candidate))
      (alist-get 'spotify (alist-get 'external_urls item))))

  (defun espotify-yank-candidate-url (candidate)
    "Add to kill ring the Spotify URL of this CANDIDATE."
    (if-let (url (espotify-candidate-url candidate))
        (kill-new url)
      (message "No spotify URL for this candidate")))

You can use these actions in your programs. For instance, if you use embark, we could associate them with a new espotify-search-item target with:

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

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

Search front-end using consult

Anatomy of a consult async generator

To define a new asynchronous consult command, one wants to use consult--read, passing to it a function that generates our dynamic list of completion candidates. Our top-level consult ommand will thus have this form:

  (defvar consult-spotify-history nil)

  (defun consult-spotify-by (type &optional filter)
    "Consult spotify by TYPE with FILTER."
    (consult--read (consult-spotify--search-generator type filter)
                   :prompt (format "Search %ss: " type)
                   :lookup #'consult--lookup-member
                   :category 'spotify-search-item
                   :history '(:input consult-spotify-history)
                   :initial (consult--async-split-initial "")
                   :require-match t))

where we can write an asynchronous generator of search results as a pipeline of closures that successively create and massage completion candidates. In our case, that pipeline might look like this:

  (defun consult-spotify--search-generator (type filter)
    "Generate an async search closure for TYPE and FILTER."
    (thread-first (consult--async-sink)
      (consult--async-map #'espotify-format-item)
      (consult-spotify--async-search type filter)

The above follows a generic consult pattern, where consult-spotify--async-search must be an asynchronous dispatcher closure that must generate and handle a list of result items, which are in turn formated as candidates by espotify-format-item. The rest are helpers already provided by consult:

  • consult--async-split: splits the input string, one part for async, one part for filtering
  • consult--async-throttle: throttles the user input
  • consult--async-refresh-immediate: refreshes when candidates are pushed
  • consult--async-sink: collects the candidates and refreshes

Consult offers also a few more closure generators that we haven't used (yet):

  • consult--async-map: transform candidates
  • consult--async-refresh-timer: refreshes, when candidates are pushed, throttles with a timer
  • consult--async-filter: filter candidates
  • consult--async-process, a source generator handy when your candidates come from the output of executing a local process

Candidates generator for espotify searches

Back to our candidates generator. It must be a function that takes a continuation closure (the async after you in the pipeline) and returns an action dispatcher, that is, a function takiing that action as its single argument (possibly passing its results, or simply delegating, to the next handler in the pipeline). So our dispatcher generator is going to look something like this template, where we display all possible actions to be dispatched:

  (defun espotify--async-search (next-async ...)
    ;; return a dispatcher for new actions
    (lambda (action)
      (pcase action
        ((pred stringp) ...) ;; if the action is a string, it's the user input
        ((pred listp) ...)   ;; if a list, candidates to be appended
        ('setup ...)
        ('destroy ...)
        ('flush ..)
        ('get ...))))

For each action, we must decide whether to handle it ourselves or simply pass it to next-async, or maybe both. Or we could ask next-async to perform new actions for us. In our case, we only care about generating a list of tracks when given a query string that ends on a marker character (or any other criteria), and making sure it reaches the top level. Thus, our async has only work to do when it receives a string. Here's how it works:

  (defun consult-spotify--async-search (next type filter)
    "Async search with NEXT, TYPE and FILTER."
    (let ((current ""))
      (lambda (action)
        (pcase action
          ((pred stringp)
           (when-let (term (espotify-check-term current action))
             (setq current term)
              (lambda (x)
                (funcall next 'flush)
                (funcall next x))
          (_ (funcall next action))))))

We're using espotify-check-term to decide when the new term to search is going to trigger a new search, ignoring it otherwise.

Note that we made sure that we access our formatted candidate string when consult looks up for it using the stock :lookup function consult--lookup-member.

User level commands

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

  (defun consult-spotify-album ()
    "Query spotify for an album using consult."
    (espotify-play-candidate (consult-spotify-by 'album)))

And likewise for playlists, artists and combinations thereof:

  (defun consult-spotify-artist ()
    "Query spotify for an artist using consult."
    (espotify-play-candidate (consult-spotify-by 'artist)))

  (defun consult-spotify-track ()
    "Query spotify for a track using consult."
    (espotify-play-candidate (consult-spotify-by 'track)))

  (defun consult-spotify-playlist ()
    "Query spotify for a track using consult."
    (espotify-play-candidate (consult-spotify-by 'playlist)))

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.

  (with-eval-after-load "marginalia"
    (defun consult-spotify--annotate (cand)
      "Compute marginalia fields for candidate CAND."
      (when-let (x (espotify-candidate-metadata 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-annotator-registry
                 '(spotify-search-item consult-spotify--annotate)))

Search front-end using ivy

If you are an ivy/counsel user, you don't need any of the above: counsel-spotify implements similar functionality. But i found instructive to figure out how our espotify can be used to reimplement it. It's pretty simple.

We will 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, or return a non-empty list (from previous attempts).

  (defun ivy-spotify--search-by (type)
    "Perform an asynchronous spotify search, for resources of the given TYPE."
    (let ((current-term "")
      (lambda (term)
        (when-let (term (espotify-check-term current-term term))
           (lambda (its)
             (let ((cs (mapcar #'espotify-format-item its)))
               (ivy-update-candidates (setq candidates cs))))
           (setq current-term term)
        (or candidates 0))))

where we've also used a function to ensure any open connections get closed before launching new ones:

  (defun ivy-spotify--unwind ()
    "Delete any open spotify connections."
    (dolist (name '("" ""))
      (when-let (p (get-process name))
        (delete-process p))))

Admittedly, that's a tad clumsy: one could conceivably have other connections to spotify open when launching our searches, and the unwind above would kill those instead, but i don't see that as a use case happening often enough to be worth of the time and complexity a really robust alternative would entail.

With that, we can define our generic completing read:

  (defun ivy-spotify--play-album (candidate)
    "Play album associated with selected CANDIDATE."
    (let ((item (espotify-candidate-metadata candidate)))
      (if-let (album (if (string= "album" (alist-get 'type item ""))
                       (alist-get 'album item)))
          (espotify-play-uri (alist-get 'uri album))
        (message "No album found for '%s'" (alist-get 'name item)))))

  (defvar ivy-spotify-search-history nil
    "History for spotify searches.")

  (defun ivy-spotify-search-by (type)
    "Search spotify resources of the given TYPE using ivy."
    (ivy-read (format "Search %s: " type)
              (ivy-spotify--search-by type)
              :dynamic-collection t
              :unwind #'ivy-spotify--unwind
              :history 'ivy-spotify-search-history
              :caller (make-symbol (format "ivy-spotify-%s" type))
              :action `(1 ("p" espotify-play-candidate ,(format "Play %s" type))
                          ("a" ivy-spotify--play-album "Play album")
                          ("i" espotify-show-candidate-info "Show info"))))

and our collection of searching commands:

  (defun ivy-spotify-album ()
    "Query spotify for an album using ivy."
    (ivy-spotify-search-by 'album))

  (defun ivy-spotify-artist ()
    "Query spotify for an artist using ivy."
    (ivy-spotify-search-by 'artist))

  (defun ivy-spotify-track ()
    "Query spotify for a track using ivy."
    (ivy-spotify-search-by 'track))

  (defun ivy-spotify-playlist ()
    "Query spotify for a playlist using ivy."
    (ivy-spotify-search-by 'playlist))

Simpler than our initial consult, although it's true that we already had part of the job done. The nice "split search" that counsult offers out of the box, though, is much more difficult to get.



  ;;; espotify.el --- Spotify access library  -*- lexical-binding: t; -*-

  ;; Package-Requires: ((emacs "26.1"))


  ;;; Commentary:

  ;; This package provides generic utilities to access Spotify and
  ;; use its query APIs, as well as controlling local players via
  ;; their dbus interface.  Although they can be used in other
  ;; programs, the functions in this package were originally
  ;; intended for consult-spotify and ivy-spotify.

  ;;; Code:

  (require 'dbus)



  (provide 'espotify)
  ;;; espotify.el ends here


  ;;; consult-spotify.el --- Spotify queries using consult  -*- lexical-binding: t; -*-

  ;; Package-Requires: ((emacs "26.1") (consult "0.8") (espotify "0.1"))


  ;;; Commentary:

  ;; This package provides functions to interactively query
  ;; Spotify using consult.  Its main entry points are the
  ;; commands `consult-spotify-album', `consult-spotify-artist',
  ;; `consult-spotify-playlist' and `consult-spotify-track'.
  ;; This package is implemeted using the espotify library.

  ;;; Code:

  (require 'seq)
  (require 'subr-x)
  (require 'espotify)
  (require 'consult)


  (provide 'consult-spotify)
  ;;; consult-spotify.el ends here


  ;;; ivy-spotify.el --- Search spotify with ivy  -*- lexical-binding: t; -*-

  ;; Package-Requires: ((emacs "26.1") (espotify "0.1") (ivy "0.13.1"))


  ;;; Commentary:

  ;; This package provides an ivy-based completion interface to
  ;; spotify's search API, analogous to counsel-spotify, using the
  ;; smaller espotify library.  The following interactive commands
  ;; are defined:
  ;;  - `ivy-spotify-album'
  ;;  - `ivy-spotify-artist'
  ;;  - `ivy-spotify-track'
  ;;  - `ivy-spotify-playlist'
  ;; A completing prompt will appear upon invoking it, and when
  ;; the input varies significantly or you end your input with `='
  ;; a web search will be triggered.  Several ivy actions (play,
  ;; play album, show candidate info) are available.

  ;;; Code:

  (require 'espotify)
  (require 'ivy)


  (provide 'ivy-spotify)
  ;;; ivy-spotify.el ends here

Spofity app blurb

  ;; For espotify to work, you need to set valid values for
  ;; `espotify-client-id' and `espotify-client-secret'.  To get
  ;; valid values for them, one just needs to register a spotify
  ;; application at

  ;; All .el files have been automatically generated from the literate program


  ;; Author: Jose A Ortega Ruiz <>
  ;; Maintainer: Jose A Ortega Ruiz
  ;; Keywords: multimedia
  ;; License: GPL-3.0-or-later
  ;; Version: 0.1
  ;; Homepage:


  ;; Copyright (C) 2021  Jose A Ortega Ruiz

  ;; This program is free software; you can redistribute it and/or modify
  ;; it under the terms of the GNU General Public License as published by
  ;; the Free Software Foundation, either version 3 of the License, or
  ;; (at your option) any later version.

  ;; This program is distributed in the hope that it will be useful,
  ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  ;; GNU General Public License for more details.

  ;; You should have received a copy of the GNU General Public License
  ;; along with this program.  If not, see <>.


Protesilaos Stavrou's musings on completion frameworks prompted me to explore the selectrum/consult/marginalia/embark quadrivium.

The code above benefited quite a bit from Daniel Mendler's and Antolin Omar Camarena's comments, and i discussed a bit its evolution and other possibilities offered by the consult API in this blog post.

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.