Created
September 8, 2017 08:44
-
-
Save alphapapa/9df7093dc1ea83fbc4c8ef5d31b3bc57 to your computer and use it in GitHub Desktop.
Insert book information as an Org entry with author, title, etc. as properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require 'esxml-query) | |
(require 'org-web-tools) | |
(defun ap/amazon-book-data (url) | |
"Return plist of data for book at Amazon URL." | |
(cl-flet ((field (target-field list) | |
(cl-loop for li in list | |
for (field value) = (ignore-errors | |
(-let (((_ _ (_ _ field) value) li)) | |
(list field value))) | |
when (equal field target-field) | |
return (s-trim value)))) | |
(let* ((html (org-web-tools--get-url url)) | |
(tree (with-temp-buffer | |
(insert html) | |
(libxml-parse-html-region (point-min) (point-max)))) | |
(author (esxml-query "span.author a.contributorNameID *" tree)) | |
(title (esxml-query "div#booksTitle h1#title > span *" tree)) | |
(details (esxml-query-all "table#productDetailsTable ul li" tree)) | |
(date (s-replace "– " "" | |
(or | |
;; Printed book | |
(third (esxml-query-all "div#booksTitle h1#title span *" tree)) | |
;; Kindle | |
(field "Publication Date:" details)))) | |
(asin (field "ASIN:" details)) | |
(publisher (replace-regexp-in-string (rx " (" (1+ anything) ")") "" | |
(field "Publisher:" details))) | |
(isbn-10 (field "ISBN-10:" details)) | |
(isbn-13 (field "ISBN-13:" details))) | |
(list :author author :title title :asin asin :publisher publisher :date date | |
:isbn-10 isbn-10 :isbn-13 isbn-13)))) | |
(defun ap/org-insert-book-entry (&optional url) | |
"Insert Org entry for book at URL." | |
(interactive) | |
(cl-flet ((key-name (key) | |
(--> key | |
(symbol-name it) | |
(replace-regexp-in-string "^:" "" it) | |
(upcase it)))) | |
(when-let ((url (or url (org-web-tools--get-first-url))) | |
(data (ap/amazon-book-data url)) | |
(property-drawer (list 'property-drawer nil | |
(cl-loop for (key value) on data by #'cddr | |
for key = (key-name key) | |
when value | |
collect (list 'node-property (list :key key :value value))))) | |
(author (plist-get data :author)) | |
(title (plist-get data :title)) | |
(link (org-make-link-string url title)) | |
(heading (format "%s, %s" author link)) | |
(element (org-element-create 'headline (list :level 1 :title heading) | |
property-drawer)) | |
(string (org-element-interpret-data element))) | |
(kill-new string) | |
(save-excursion | |
(beginning-of-line) | |
(org-paste-subtree))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment