janet-mastodon-bookmarks/media.janet

22 lines
661 B
Plaintext

(import httprequest :as r)
(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)