2023-10-11 Posting to Oddµ from Emacs

Emacs people probably don't care about Oddµ, but I need to write down how to use the `url` package to post stuff. There are so many things I usually forget. For example: You need to provide "Content-Type" and encode appropriately. If you forget, nothing gets saved.

Also interesting: How to use `url-basic-auth`.

I found a lot of this in the sources of `mediawiki.el`, so thanks to Mark A. Hershberger and friends!

(add-hook 'markdown-mode-hook 'asc:markdown-init)

(defun asc:markdown-init ()
  (local-set-key (kbd "C-c C-c C-p") 'asc:markdown-publish))

(defun asc:markdown-publish (name add-changes)
  "Publish the page on my blog."
  (interactive
   (list (read-string "Name of the page: "
                      (string-replace ".md" "" (buffer-name)))
         (y-or-n-p "Add to list of changes: ")))
  (let* ((url (concat "https://alexschroeder.ch/save/" name))
         (url-request-method "POST")
         (url-request-coding-system 'utf-8)
         (url-request-extra-headers
          '(("Content-Type" . "application/x-www-form-urlencoded; charset=utf-8")
            ("Connection" . "close")))
         (url-request-data
          (mm-url-encode-www-form-urlencoded
           `(("body" . ,(buffer-substring-no-properties (point-min) (point-max)))
             ("notify" . ,(if add-changes "on" ""))))))
    (when (url-basic-auth url)
      (add-to-list 'url-request-extra-headers
                   (cons "Authorization" (url-basic-auth url))))
    (url-retrieve url (lambda (status &rest ignore)
                        (let ((kill-this-buffer (current-buffer)))
                          (if (and (integerp status) (not (< status 300)))
                              (error "Oh no: %d 😱" status)
                            (message "No idea if this worked")))))))

​#Emacs ​#Oddµ

(I suspect that the name should be percent-encoded before being concatenated with the base URL, but until now all my page names have been 100% ASCII…)

Next: Writing pages offline, some of the time.

Writing pages offline, some of the time