From e91a6f50a76ffc01c0f82bfba198b7e5bf204b2e Mon Sep 17 00:00:00 2001 From: gered Date: Sun, 30 Mar 2014 11:07:31 -0400 Subject: [PATCH] add image route support for the remaining parameters --- src/toascii/routes/api/image.clj | 34 +++++++++++++++++++++----------- src/toascii/util.clj | 17 ++++++++++++++++ 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/src/toascii/routes/api/image.clj b/src/toascii/routes/api/image.clj index 0575a9d..9806ce0 100644 --- a/src/toascii/routes/api/image.clj +++ b/src/toascii/routes/api/image.clj @@ -4,20 +4,32 @@ [liberator.core :refer [defresource]] [compojure.core :refer [ANY]] [toascii.route-utils :refer [register-routes]] - [toascii.models.image :refer [convert-image get-image-by-url]])) + [toascii.models.image :refer [convert-image get-image-by-url]] + [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}] :media-type-available? (fn [ctx] - (let [type (condp = format - "html" "text/html" - "text" "text/plain" - "text/html")] - {:representation {:media-type type}})) + (if (color? color) + {:representation {:media-type "text/html"}} + (let [type (condp = format + "html" "text/html" + "text" "text/plain" + "text/html")] + {:representation {:media-type type}}))) :malformed? (fn [_] (cond - (str/blank? url) {:error "Missing image url"})) + (str/blank? url) + {:error "Missing image url"} + + (and width (nil? (parse-int width))) + {:error "Invalid image width."})) :exists? (fn [_] (if-let [image (get-image-by-url url)] @@ -25,10 +37,10 @@ [false {:error "Image could not be loaded."}])) :handle-ok (fn [ctx] - (let [rendered (convert-image (:image ctx) true)] - (if (= "text/html" (get-in ctx [:representation :media-type])) - rendered - rendered))) + (convert-image + (:image ctx) + (parse-int width) + (color? color))) :handle-malformed (fn [ctx] (:error ctx)) diff --git a/src/toascii/util.clj b/src/toascii/util.clj index bd01099..6e12b16 100644 --- a/src/toascii/util.clj +++ b/src/toascii/util.clj @@ -59,3 +59,20 @@ (url/url) (encode-url-path-components) (URL.))) + +(defn parse-int [s] + (try + (Integer/parseInt s) + (catch Exception ex))) + +(defn parse-boolean [x] + (let [x (if (string? x) + (-> x (.toLowerCase) (.trim)) + x)] + (condp = x + "false" false + false false + "0" false + 0 false + nil false + true))) \ No newline at end of file