janet-mastodon-bookmarks/utils.janet

51 lines
1.6 KiB
Plaintext

(import httprequest :as r)
(def exists? (fn [path]
"Returns whether a file exists at the specified path."
(def f (file/open path :r))
(if f (do (file/close f) true) false)))
(defn get-image [url folder &named headers opts]
"Download an image from a URL and save it to a file. Returns the path to the saved file."
(default headers {})
(default opts {})
(def filename (array/pop (string/split "/" url)))
(def fullpath (string folder filename))
# Check if the file already exists
(def existing (file/open fullpath :r))
(if existing (file/close existing))
(if (not existing)
(do
(print (string "Downloading " url))
(def response (r/get url headers opts))
(def fout (file/open fullpath :w))
(file/write fout (response :body))
(file/close fout)))
filename)
(defn get-link [response rel]
"Gets the link with the specified relation from the response.
e.g. (get-link response \"next\")"
# Get the links from the headers
(def link-header ((response :headers) "Link"))
(if (= link-header nil) (break nil))
(def links (string/split "," link-header))
# Find the link with the specified relation
(def link (find |(not= (string/find rel $) nil) links))
# Extract the url from the link string (as an array of 1 element)
(if link (do
(def url (peg/match ~(sequence (any " ") "<" (capture (some (if-not ">" 1))) ">") link))
(if url (in url 0) nil))))
(defn array-shift [arr]
"Removes the first element from the array."
(if (empty? arr) (break nil))
(def head (in arr 0))
(array/remove arr 0)
head)