programming (and other) musings

Posts tagged "pages":

08 Jan 2021

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 "")
(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)

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))))

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))

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 ()
  (espotify-call-spotify-via-dbus "PlayPause"))

(defun espotify-next ()
  (espotify-call-spotify-via-dbus "Next"))

(defun espotify-previous ()
  (espotify-call-spotify-via-dbus "Previous"))

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 espotify-consult-by (type &optional filter)
  (let ((orderless-matching-styles '(orderless-literal)))
    (consult--read (espotify--search-generator type filter)
                   :prompt (format "Search %ss: " type)
                   :lookup 'espotify--consult-lookup
                   :category 'espotify-search-item
                   :history 'espotify-consult-history
                   :initial consult-async-default-split
                   :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:

(defun espotify--async-search (next type 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 have introduced the convention that we're only launching a search when the input string ends in "=", to avoid piling on HTTP requests, and also played a bit with Levenshtein distance, both via the function espotify-check-search-term:

(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-check-term (prev new)
  (when (not (string-blank-p new))
    (cond ((string-suffix-p espotify-search-suffix new)
           (substring new 0 (- (length new) (length espotify-search-suffix))))
          ((>= (string-distance prev new) espotify-search-threshold) new))))

In the consult case, a more natural choice for the search suffix is

(setq espotify-search-suffix consult-async-default-split)

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 espotify-consult-album (&optional filter)
  (espotify--maybe-play (espotify-consult-by 'album filter)))

And likewise for playlists, artists and combinations thereof:

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

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

(defun espotify-consult-playlist (&optional filter)
  (espotify--maybe-play (espotify-consult-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. These actions need access to the rich metadata attached to the candidate, and will therefore be defined as regular one-argument functions, rather than interactive commands (as is otherwise recommended for generic embark actions).

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

(defun espotify--show-info (candidate)
  "Show low-level info (an alist) about selection."
  (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--item candidate))
    (insert (pp-to-string item)))
  (goto-char (point-min))
  (read-only-mode 1))

(defun espotify--play-album (candidate)
  "Play album associated with selected item."
  (when-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--yank-url (candidate)
  "Add to kill ring the Spotify URL of this entry"
  (when-let (item (espotify--item candidate))
    (if-let (url (alist-get 'spotify (alist-get 'external_urls item)))
        (kill-new url)
      (message "No spotify URL for this candidate"))))

(embark-define-keymap espotify-item-keymap
  "Actions for Spotify search results"
  ("y" espotify--yank-url)
  ("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-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 espotify-counsel--search-by (type filter)
  (let ((current-term ""))
    (lambda (term)
      (when-let (term (espotify-check-term current-term term))
        (espotify-search-all (lambda (its)
                               (let ((cs (mapcar #'espotify--format-item its)))
                                 (ivy-update-candidates cs)))
                             (setq current-term term)

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-search-by (type filter)
  (ivy-read (format "Search %s: " type)
            (espotify-counsel--search-by type filter)
            :dynamic-collection t
            :action `(1 ("a" espotify-counsel--play-album "Play album")
                        ("p" espotify--maybe-play ,(format "Play %s" type)))))

and our collection of searching commands:

(defun espotify-counsel-album (&optional filter)
  (espotify-search-by 'album filter))

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

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

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

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.


(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!

Tags: emacs pages
23 Feb 2020

signel, a barebones signal chat on top of signal-cli

Unlike most chat systems in common use, Signal lacks a decent emacs client. All i could find was signal-msg, which is able only to send messages and has a readme that explicitly warns that its is not a chat application. Skimming over signal-msg's code i learnt about signal-cli, a java-based daemon that knows how to send and receive signal messages, and how to link to a nearby phone, or register new users. And playing with it i saw that it can output its activities formatted as JSON, and that offers (when run in daemon mode) a DBUS service that can be used to send messages.

Now, emacs knows how to run a process and capture its output handling it to a filter function, and comes equipped with a JSON parser and a set of built-in functions to talk to DBUS buses.

So how about writing a simple Signal chat app for emacs? Let's call it signel, and write it as a blog post in literate org-mode.

Starting a process

We are going to need a variable for our identity (telephone number), and a list of contact names (until i discover how to get them directly from signal-cli):

(require 'cl-lib)

(defvar signel-cli-user "+44744xxxxxx")
(defvar signel-contact-names '(("+447xxxxxxxx" . "john")
                               ("+346xxxxxxxx" . "anna")))

and a simple function to get a contact name given its telephone number:

(defun signel--contact-name (src)
  (or (alist-get src signel-contact-names nil nil #'string-equal) src))

We are also going to need the path for our signal-cli executable

(defvar signel-cli-exec "signal-cli")

Starting the signal-cli process is easy: make-process provides all the necessary bits. What we need is essentially calling

signal-cli -u +44744xxxxxx daemon --json

associating to the process a buffer selected by the function signel--proc-buffer . While we are at it, we'll write also little helpers for users of our API.

(defun signel--proc-buffer ()
  (get-buffer-create "*signal-cli*"))

(defun signel-signal-cli-buffer ()
  (get-buffer "*signal-cli*"))

(defun signel-signal-cli-process ()
  (when-let ((proc (get-buffer-process (signel-signal-cli-buffer))))
    (and (process-live-p proc) proc)))
(defun signel-start ()
  "Start the underlying signal-cli process if needed."
  (if (signel-signal-cli-process)
      (message "signal-cli is already running!")
    (let ((b (signel--proc-buffer)))
      (make-process :name "signal-cli"
                    :buffer b
                    :command `(,signel-cli-exec
                               "daemon" "--json")
                    :filter #'signel--filter)
      (message "Listening to signals!"))))

Parsing JSON

We've told emacs to handle any ouput of the process to the function signel--filter, which we're going to write next. This function will receive the process object and its latest output as a string representing a JSON object. Here's an example of the kind of outputs that signal-cli emits:

  "envelope": {
    "source": "+4473xxxxxxxx",
    "sourceDevice": 1,
    "relay": null,
    "timestamp": 1582396178696,
    "isReceipt": false,
    "dataMessage": {
      "timestamp": 1582396178696,
      "message": "Hello there!",
      "expiresInSeconds": 0,
      "attachments": [],
      "groupInfo": null
    "syncMessage": null,
    "callMessage": null,
    "receiptMessage": null

Everything seems to be always inside envelope, which contains objects for the possible messages received. In the example above, we're receiving a message from a source contact. We can also receive receipt messages, telling us whether our last message has been received or read; e.g.:

  "envelope": {
    "source": "+4473xxxxxxxx",
    "sourceDevice": 1,
    "relay": null,
    "timestamp": 1582397117584,
    "isReceipt": false,
    "dataMessage": null,
    "syncMessage": null,
    "callMessage": null,
    "receiptMessage": {
      "when": 1582397117584,
      "isDelivery": true,
      "isRead": false,
      "timestamps": [

A bit confusingly, that delivery notification has a receiptMessage, but its isReceipt flag is set to false. At other times, we get isReceipt but no receiptMessage:

  "envelope": {
    "source": "+346xxxxxxxx",
    "sourceDevice": 1,
    "relay": null,
    "timestamp": 1582476539281,
    "isReceipt": true,
    "dataMessage": null,
    "syncMessage": null,
    "callMessage": null,
    "receiptMessage": null

It is very easy to parse JSON in emacs and extract signal-cli's envelopes (and it's become faster in emacs 27, but the interface is a bit different):

(defun signel--parse-json (str)
  (if (> emacs-major-version 26)
      (json-parse-string str
                         :null-object nil
                         :false-object nil
                         :object-type 'alist
                         :array-type 'list)
    (json-read-from-string str)))

(defun signel--msg-contents (str)
  (alist-get 'envelope (ignore-errors (signel--parse-json str))))

Here i am being old-school and opting to receive JSON dicitionaries as alists (rather than hash maps, the default), and arrays as lists rather than vectors just because lisps are lisps for a reason. I'm also going to do some mild nil punning, hence the choice for null and false representations.

Once the contents of the envelope is extracted, it's trivial (and boring) to get into its components:

(defun signel--msg-source (msg) (alist-get 'source msg))

(defun signel--msg-data (msg)
  (alist-get 'message (alist-get 'dataMessage msg)))

(defun signel--msg-timestamp (msg)
  (if-let (msecs (alist-get 'timestamp msg))
      (format-time-string "%H:%M" (/ msecs 1000))

;; emacs 26 compat
(defun signel--not-false (x)
  (and (not (eq :json-false x)) x))

(defun signel--msg-receipt (msg)
  (alist-get 'receiptMessage msg))

(defun signel--msg-is-receipt (msg)
  (signel--not-false (alist-get 'isReceipt msg)))

(defun signel--msg-receipt-timestamp (msg)
  (when-let (msecs (alist-get 'when (signel--msg-receipt msg)))
    (format-time-string "%H:%M" (/ msecs 1000))))

(defun signel--msg-is-delivery (msg)
  (when-let ((receipt (signel--msg-receipt msg)))
    (signel--not-false (alist-get 'isDelivery msg))))

(defun signel--msg-is-read (msg)
  (when-let ((receipt (signel--msg-receipt msg)))
    (signel--not-false (alist-get 'isRead msg))))

A process output filter

We're almost ready to write our filter. It will:

  • For debugging purposes, insert the raw JSON string in the process buffer.
  • Parse the received JSON string and extract its envelope contents.
  • Check wether it has a source and either message data or a receipt timestamp.
  • Dispatch to a helper function that will insert the data or notification in a chat buffer.

Or, in elisp:

(defvar signel--line-buffer "")

(defun signel--filter (proc str)
  (signel--ordinary-insertion-filter proc str)
  (let ((str (concat signel--line-buffer str)))
    (if-let ((msg (signel--msg-contents str)))
        (let ((source (signel--msg-source msg))
              (stamp (signel--msg-timestamp msg))
              (data (signel--msg-data msg))
              (rec-stamp (signel--msg-receipt-timestamp msg)))
          (setq signel--line-buffer "")
          (when source
            (signel--update-chat-buffer source data stamp rec-stamp msg)))
      (setq signel--line-buffer
            (if (string-match-p ".*\n$" str) "" str)))))

We've had to take care of the case when the filter receives input that is not a complete JSON expression: in the case of signal-cli, that only happens when we haven't seen yet an end of line.

The function to insert the raw contents in the process buffer is surprisingly hard to get right, but the emacs manual spells out a reasonable implementation, which i just copied:

(defun signel--ordinary-insertion-filter (proc string)
  (when (and proc (buffer-live-p (process-buffer proc)))
    (with-current-buffer (process-buffer proc)
      (let ((moving (= (point) (process-mark proc))))
          ;; Insert the text, advancing the process marker.
          (goto-char (process-mark proc))
          (insert string)
          (set-marker (process-mark proc) (point)))
        (if moving (goto-char (process-mark proc)))))))

It's not an emacs app if it doesn't have a new mode

With that out of the way, we just have to insert our data in an appropriate buffer. We are going to associate a separate buffer to each source, using for that its name:

(defvar-local signel-user nil)

(defun signel--contact-buffer (source)
  (let* ((name (format "*%s" (signel--contact-name source)))
         (buffer (get-buffer name)))
    (unless buffer
      (setq buffer (get-buffer-create name))
      (with-current-buffer buffer
        (setq-local signel-user source)
        (insert signel-prompt)))

where, as is often the case in emacs, we are going to have a dedicated major mode for chat buffers, called signel-chat-mode. For now, let's keep it really simple (for the record, this is essentially a copy of what ERC does for its erc-mode):

(defvar signel-prompt ": ")

(define-derived-mode signel-chat-mode fundamental-mode "Signal"
  "Major mode for Signal chats."
  (when (boundp 'next-line-add-newlines)
    (set (make-local-variable 'next-line-add-newlines) nil))
  (setq line-move-ignore-invisible t)
  (set (make-local-variable 'paragraph-separate)
       (concat "\C-l\\|\\(^" (regexp-quote signel-prompt) "\\)"))
  (set (make-local-variable 'paragraph-start)
       (concat "\\(" (regexp-quote signel-prompt) "\\)"))
  (setq-local completion-ignore-case t))

Note how, in signel--contact-buffer, we're storing the user identity associated with the buffer (its source) in a buffer-local variable named signel-user that is set after enabling signel-chat-mode: order here matters because the major mode activation cleans up the values of any local variables previously set (i always forget that!).

And a customization group

We're going to need a couple of new faces for the different parts of inserted messages, so we'll take the chance to be tidy and introduce a customization group:

(defgroup signel nil "Signel")

(defface signel-contact '((t :weight bold))
  "Face for contact names."
  :group 'signel)

(defface signel-timestamp '((t :foreground "grey70"))
  "Face for timestamp names."
  :group 'signel)

(defface signel-notice '((t :inherit signel-timestamp))
  "Face for delivery notices."
  :group 'signel)

(defface signel-prompt '((t :weight bold))
  "Face for the input prompt marker."
  :group 'signel)

(defface signel-user '((t :foreground "orangered"))
  "Face for sent messages."
  :group 'signel)

(defface signel-notification '((t :foreground "burlywood"))
  "Face for notifications shown by tracking, when available."
  :group 'signel)

Displaying incoming messages

We have now almost all the ingredients to write signel--update-chat-buffer, the function that inserts the received message data into the chat buffer. Let's define a few little functions to format those parts:

(defun signel--contact (name)
  (propertize name 'face 'signel-contact))

(defun signel--timestamp (&rest p)
  (propertize (apply #'concat p) 'face 'signel-timestamp))

(defun signel--notice (notice)
  (propertize notice 'face 'signel-notice))

(defun signel--insert-prompt ()
  (let ((inhibit-read-only t)
        (p (point)))
    (insert signel-prompt)
    (set-text-properties p (- (point) 1)
                         '(face signel-prompt
                           read-only t front-sticky t rear-sticky t))))

(defun signel--delete-prompt ()
  (when (looking-at-p (regexp-quote signel-prompt))
    (let ((inhibit-read-only t))
      (delete-char (length signel-prompt)))))

(defun signel--delete-last-prompt ()
  (goto-char (point-max))
  (when (re-search-backward (concat "^" (regexp-quote signel-prompt)))

With that, we're finally ready to insert messages in our signel chat buffers:

(defcustom signel-report-deliveries nil
  "Whether to show message delivery notices."
  :group 'signel
  :type 'boolean)

(defcustom signel-report-read t
  "Whether to show message read notices."
  :group 'signel
  :type 'boolean)

(defun signel--prompt-and-notify ()
  (when (fboundp 'tracking-add-buffer)
    (tracking-add-buffer (current-buffer) '(signel-notification))))

(defun signel--needs-insert-p (data stamp rec-stamp msg)
  (or data
      (and (or rec-stamp stamp)
           (not (string= source signel-cli-user))
           (or signel-report-deliveries
               (and signel-report-read (signel--msg-is-read msg))))))

(defun signel--update-chat-buffer (source data stamp rec-stamp msg)
  (when (signel--needs-insert-p data stamp rec-stamp msg)
    (when-let ((b (signel--contact-buffer source)))
      (with-current-buffer b
        (if data
            (let ((p (point)))
              (insert (signel--timestamp "[" stamp "] ")
                      (signel--contact (signel--contact-name source))
              (fill-region p (point)))
          (let ((is-read (signel--msg-is-read msg)))
            (insert (signel--timestamp "*" (or rec-stamp stamp) "* ")
                    (signel--notice (if is-read "(read)" "(delivered)"))

There are some rough edges in the above implementation that must be polished should signel ever be released in the wild. For one, proper handling of timestamps and their formats. And of course notifications should be much more customizable (here i'm using Circe's tracking.el if available).

Sending messages: the DBUS interface

With that, we're going to receive and display messages and simple receipts, and i'm sure that we will feel the urge to answer some of them. As mentioned above, signal-cli let's us send messages via its DBUS interface. In a nutshell, if you want to send MESSAGETEXT to a RECIPIENT you'd invoke something like:

dbus-send --session --type=method_call \
          --dest="org.asamk.Signal" \
          /org/asamk/Signal \
          org.asamk.Signal.sendMessage \
          string:MESSAGETEXT array:string: string:RECIPIENT

That is, call the method sendMessage of the corresponding service interface with three arguments (the second one empty). Using emacs' dbus libray one can write the above as:

(defun signel--send-message (user msg)
  (dbus-call-method :session "org.asamk.Signal" "/org/asamk/Signal"
                    "org.asamk.Signal" "sendMessage"
                    :string msg
                    :string user))

The only complicated bit is being careful with the specification of the types of the method arguments: if one gets them wrong, DBUS will simply complain and say that the method is not defined, which was confusing me at first (but of course makes sense because DBUS allows overloading method names, so the full method spec must include its signature).

We want to read whatever our user writes after the last prompt and send it via the little helper above. Here's our interactive command for that:

(defun signel-send ()
  "Read text inserted in the current buffer after the last prompt and send it.

The recipient of the message is looked up in a local variable set
when the buffer was created."
  (goto-char (point-max))
  (let* ((p (point))
         (plen (length signel-prompt))
         (msg (buffer-substring (+ p plen) (point-max))))
    (signel--send-message signel-user msg)
    (insert (signel--timestamp (format-time-string "(%H:%M) ")))
    (fill-region p (point-max))
    (goto-char (point-max))
    (set-text-properties p (point) '(face signel-user))
    (insert "\n")

and we can bind it to the return key in signal chat buffers:

(define-key signel-chat-mode-map "\C-m" #'signel-send)

And we are going sometimes to want to talk to contacts that don't have yet said anything and have, therefore, no associated chat buffer:

(defun signel-query (contact)
  "Start a conversation with a signal contact."
  (interactive (list (completing-read "Signal to: "
                                      (mapcar #'cdr-safe signel-contact-names))))
  (let ((phone (alist-get contact
                          (cl-pairlis (mapcar #'cdr signel-contact-names)
                                      (mapcar #'car signel-contact-names))
                          nil nil #'string-equal)))
    (when (not phone)
      (error "Unknown contact %s" contact))
    (pop-to-buffer (signel--contact-buffer phone))))

There are of course lots of rough edges and missing functionality in this incipient signel, but it's already usable and a nice demonstration of how easy it is to get the ball rolling in this lisp machine of ours!

Tags: emacs pages
Other posts
Creative Commons License by jao is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.