|
| 1 | +(ns civitas.clay-main |
| 2 | + (:gen-class) |
| 3 | + (:require [clojure.java.io :as io] |
| 4 | + [clojure.string :as str] |
| 5 | + [ring.util.mime-type :as mime-type] |
| 6 | + [scicloj.clay.v2.main :as clay-main] |
| 7 | + [scicloj.clay.v2.server :as clay-server] |
| 8 | + [scicloj.clay.v2.server.state :as server-state]) |
| 9 | + (:import (java.io File))) |
| 10 | + |
| 11 | +(def default-preview-source |
| 12 | + "language_learning/vocabulary_estimation/bayes_theorem_simulations.clj") |
| 13 | + |
| 14 | +(def preview-root "temp") |
| 15 | +(def published-root "site/_site") |
| 16 | + |
| 17 | +(defn- regular-file-under [root uri] |
| 18 | + (when (and (string? uri) (str/starts-with? uri "/")) |
| 19 | + (let [root-file (.getCanonicalFile (io/file root)) |
| 20 | + file (.getCanonicalFile (io/file root-file (subs uri 1))) |
| 21 | + root-prefix (str (.getPath root-file) File/separator)] |
| 22 | + (when (and (str/starts-with? (.getPath file) root-prefix) |
| 23 | + (.isFile file)) |
| 24 | + file)))) |
| 25 | + |
| 26 | +(defn- current-preview-uri [] |
| 27 | + (let [{:keys [base-target-path full-target-path]} |
| 28 | + (:last-rendered-spec @server-state/*state)] |
| 29 | + (when (and base-target-path full-target-path) |
| 30 | + (str "/" (clay-server/relative-url-path base-target-path |
| 31 | + full-target-path))))) |
| 32 | + |
| 33 | +(defn preview-fallback-handler [{:keys [request-method uri]}] |
| 34 | + (let [preview-file (regular-file-under preview-root uri) |
| 35 | + linked-html? (and (str/ends-with? uri ".html") |
| 36 | + (not= uri (current-preview-uri)))] |
| 37 | + (when (and (= :get request-method) |
| 38 | + (or (nil? preview-file) linked-html?)) |
| 39 | + (when-let [file (regular-file-under published-root uri)] |
| 40 | + {:status 200 |
| 41 | + :headers {"Content-Type" |
| 42 | + (or (mime-type/ext-mime-type uri) |
| 43 | + "application/octet-stream")} |
| 44 | + :body (if (str/ends-with? uri ".html") |
| 45 | + (clay-server/wrap-html (slurp file) @server-state/*state) |
| 46 | + file)})))) |
| 47 | + |
| 48 | +(defn args-with-default-source [args] |
| 49 | + (if (seq args) |
| 50 | + args |
| 51 | + [default-preview-source])) |
| 52 | + |
| 53 | +(defn -main [& args] |
| 54 | + (clay-server/install-handler! #'preview-fallback-handler) |
| 55 | + (apply clay-main/-main (args-with-default-source args))) |
0 commit comments