saner checks and defaults for color and format behaviour combinations

This commit is contained in:
Gered 2014-03-30 18:44:56 -04:00
parent 2d13e8431c
commit a932983a72

View file

@ -7,27 +7,23 @@
[toascii.models.image :refer [convert-image get-image-by-url wrap-pre-tag]] [toascii.models.image :refer [convert-image get-image-by-url wrap-pre-tag]]
[toascii.util :refer [parse-int parse-boolean]])) [toascii.util :refer [parse-int parse-boolean]]))
(defn- color? [color]
(if (nil? color)
true
(parse-boolean color)))
(defresource render-image [{:keys [url width color format] :as params}] (defresource render-image [{:keys [url width color format] :as params}]
:media-type-available? :media-type-available?
(fn [ctx] (fn [ctx]
(if (color? color) (let [type (condp = format
{:representation {:media-type "text/html"}} "html" "text/html"
(let [type (condp = format "text" "text/plain"
"html" "text/html" "text/html")]
"text" "text/plain" {:representation {:media-type type}}))
"text/html")]
{:representation {:media-type type}})))
:malformed? :malformed?
(fn [_] (fn [ctx]
(cond (cond
(str/blank? url) {:error "Missing image url"} (str/blank? url) {:error "Missing image url"}
(and width (and width
(nil? (parse-int width))) {:error "Invalid image width."})) (nil? (parse-int width))) {:error "Invalid image width."}
(and (= "text" format)
(not (nil? color))
(parse-boolean color)) {:error "Cannot output colored plain text version of image."}))
:exists? :exists?
(fn [_] (fn [_]
(if-let [image (get-image-by-url url)] (if-let [image (get-image-by-url url)]
@ -36,10 +32,12 @@
:handle-ok :handle-ok
(fn [ctx] (fn [ctx]
(let [html? (= "text/html" (get-in ctx [:representation :media-type])) (let [html? (= "text/html" (get-in ctx [:representation :media-type]))
color? (or (and html? (nil? color))
(parse-boolean color))
output (convert-image output (convert-image
(:image ctx) (:image ctx)
(parse-int width) (parse-int width)
(color? color))] color?)]
(if html? (if html?
(wrap-pre-tag output) (wrap-pre-tag output)
output))) output)))