(ns yenu.routes.admin (:require [yenu.layout :as layout] [compojure.core :refer [defroutes GET POST]] [ring.util.http-response :as response] [ring.util.response :refer [redirect]] [clojure.java.io :as io] [yenu.helpers.images :as images] [yenu.db.core :as db] [clojure.string :as str]) (:import [java.io File FileInputStream FileOutputStream])) (defn decoded-url-file [filepath] (java.net.URLDecoder/decode filepath "utf-8")) (defn upload-file [{:keys [tempfile size filename]}] (let [target-filepath (decoded-url-file (images/data-path "to-process" filename))] (try (with-open [in (new FileInputStream tempfile) out (new FileOutputStream target-filepath)] (let [src (.getChannel in) dst (.getChannel out)] (.transferFrom dst src 0 (.size src)) (.flush out)))) target-filepath)) (defn add-tag [image-id tag] (db/create-tag! {:tagname tag}) (let [{tag-id :id} (db/get-tag {:tagname tag})] (db/add-tag-to-image! {:imageid image-id :tagid tag-id}))) (defn add-image-to-database [filehash title description tags] (let [img (db/create-image! {:hash filehash :title title :description description}) image-id ((keyword "last_insert_rowid()") img) all-tags (str/split tags, #"(\s*,\s*|\s+)")] (run! #(add-tag image-id %) all-tags))) (defroutes admin-routes (GET "/upload" [] (layout/render "admin/upload.html")) (POST "/upload" [file title description tags] (-> (upload-file file) (images/process-image) (add-image-to-database title description tags)) (redirect "/")) (GET "/statistics" [] (layout/render "statistics.html")) (GET "/comments" [] (layout/render "comments.html")))