(use extras http-client progress-indicators filepath) (define *s* (make-string 2048)) (define o (open-output-file "/tmp/a.mp3")) (define (read/write filename length outport #!optional (bs (* 1024 2))) (let ((bar (make-progress-bar frame: (string-append filename ": [~a~a~a~a|~a]") width: 40 max: length))) (let loop ((size length)) (let* ((bytes (min bs size))) (if (zero? size) #t (let ((input (read-string! bytes *s*))) (if (> input 0) (begin (write-string *s* bytes outport) (advance-progress-bar! bar bytes)) (when (> bytes 0) (error "Missing ~a from input" (pretty-filesize bytes)))) (loop (- size bytes)))))) (finish-progress-bar! bar))) (define (filename-from-url u) (filepath:take-file-name u)) (define (get-file-port file) (file-open file (+ open/wronly open/creat))) (define (download-enclosure url length dest catcher) (let* ((filename (filename-from-url url)) (target-location (string-append dest "/" filename)) (temp-file (string-append target-location ".part")) (fd (get-file-port temp-file)) (outport (open-output-file* fd))) (if (equal? catcher 'curl) (unless (zero? (system (string-intersperse (list "curl" "-L" "-o" temp-file url)))) (printf "\tStill cannot download ~a~%" url) (file-close fd) (delete-file temp-file)) (condition-case (with-input-from-request url #f (if (zero? length) (begin (print "Downloading " filename) (print "This podcast has no valid length, using simple copy-port w/o output!") (lambda () (copy-port (current-input-port) outport))) (lambda () (read/write filename length outport)))) (e (exn net i/o) (printf "~%\tError while downloading ~a to ~a:~%\t~a~%" url filename ((condition-property-accessor 'exn 'message) e)) (printf "\tRetrying with curl...~%") (unless (zero? (system (string-intersperse (list "curl" "-L" "-o" temp-file url)))) (printf "\tStill cannot download ~a~%" url) (file-close fd) (delete-file temp-file))) (e (exn http unsupported-uri-scheme) (print "Cannot download " url " with http-client, shelling out to curl") (unless (zero? (system (string-intersperse (list "curl" "-L" "-o" temp-file url)))) (printf "\tUrl scheme ~a is not supported. Cannot download ~a~%" ((condition-property-accessor 'unsupported-uri-scheme 'uri-scheme) e) url) (file-close fd) (delete-file temp-file))))) (when (file-exists? temp-file) (print " done.") (rename-file temp-file target-location)))) (download-enclosure "http://localhost:8888/alternativlos-17.mp3" 89885440 "/tmp" #f)