Advertisement
Guest User

Untitled

a guest
Feb 13th, 2020
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 1.82 KB | None | 0 0
  1. #lang racket
  2.  
  3. (require net/http-client json net/url racket/port web-server/private/timer racket/file racket/bytes file/md5)
  4.  
  5. (define server (getenv "SERVER"))
  6. (define token (getenv "ACCESS_TOKEN"))
  7. (define safebooru "safebooru.donmai.us")
  8. (define limit "20")
  9. (define page (number->string (random 1 350)))
  10. (define tags "mario_(series)")
  11. (define pos (random 20))
  12. (define CRLF "\r\n")
  13. (define boundary (bytes->string/utf-8 (md5 (number->string (current-seconds)))))
  14.  
  15. (define (search-safebooru)
  16.   (define-values (status header response)(http-sendrecv safebooru (string-append "/posts.json?limit=" limit "&page=" page "&tags="tags ) #:ssl? #t))
  17.   (define posts (read-json response))
  18.  (list-ref posts pos))
  19.  
  20. (define (download-image)
  21.   (define post (search-safebooru))
  22.   (define url (hash-ref post 'file_url))
  23.   (define md5 (hash-ref post 'md5))
  24.   (define file-ext (hash-ref post 'file_ext))
  25.   (define filename (string-append md5 "." file-ext))
  26.   (define boundary-line (string-append "--" boundary CRLF))
  27.  
  28.   (call-with-output-file filename
  29.     (lambda (in) (display (port->bytes (get-pure-port (string->url url)))in))
  30.     #:exists 'replace)
  31.  
  32.   (bytes-append
  33.    (string->bytes/utf-8
  34.     (string-append
  35.      boundary-line
  36.      "Content-Disposition: form-data; name=\"file\";"
  37.      (format "Content-Type: image/~a" (if (eq? file-ext "jpg") "jpeg" "png")) CRLF))
  38.    (file->bytes filename)
  39.    (string->bytes/utf-8 (string-append CRLF "--" boundary "--" CRLF))))
  40.  
  41. (define (upload-image)
  42.   (define-values (status headers response)
  43.     (http-sendrecv server (string-append "/api/v1/media") #:ssl? #t #:method #"POST"  #:headers (list (string-append "Content-Type: multipart/form-data; boundary=" boundary)(string-append "Authorization: Bearer " token))  #:data (download-image)))
  44.   (displayln (read-json response))
  45.   (displayln status))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement