From 495c113792f78c767b1b329cc4817be3132c2f5b Mon Sep 17 00:00:00 2001 From: Simon Cambier Date: Sun, 23 Jun 2024 10:23:18 +0200 Subject: [PATCH] Better download function --- main.janet | 21 +++------------------ media.janet | 6 +++--- 2 files changed, 6 insertions(+), 21 deletions(-) diff --git a/main.janet b/main.janet index 8ef0c9b..023bd54 100644 --- a/main.janet +++ b/main.janet @@ -1,5 +1,6 @@ (import httprequest :as r) (import spork/json :as json) +(import ./media :as media) (def apptoken "REDACTED") (def urls @["https://hachyderm.io/api/v1/bookmarks"]) @@ -37,24 +38,8 @@ (def media (item "media_attachments")) (each m media (def url (m "url")) - (def filename (array/pop (string/split "/" url))) - (def fullpath (string save-path "attachments/" filename)) - - (array/push files filename) - - # Check if the file already exists - (def existing (file/open fullpath :r)) - (if existing (file/close existing)) - - # If it doesn't exist, download it - (if (not existing) - (do - (print (string "Downloading " url)) - (def response - (r/get url {"Authorization" (string "Bearer " apptoken)} {})) - (def fout (file/open fullpath :w)) - (file/write fout (response :body)) - (file/close fout)))) + (def folder (string save-path "attachments/")) + (array/push files (string "attachments/" (media/get-image url folder)))) files) diff --git a/media.janet b/media.janet index 5c3f520..a813a58 100644 --- a/media.janet +++ b/media.janet @@ -1,12 +1,12 @@ (import httprequest :as r) -(defn get-image [url path &named headers opts] +(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 path filename)) + (def fullpath (string folder filename)) # Check if the file already exists (def existing (file/open fullpath :r)) @@ -18,4 +18,4 @@ (def fout (file/open fullpath :w)) (file/write fout (response :body)) (file/close fout))) - fullpath) + filename)