-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachebusting.clj
80 lines (66 loc) · 2.52 KB
/
cachebusting.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
(ns page-renderer.cachebusting
(:require [clojure.java.io :as io]
[page-renderer.util :as u])
(:import (java.security MessageDigest DigestInputStream)))
(def ^:private default-mtime (System/currentTimeMillis))
(def ^:private default-hash (u/hexify (.getBytes (str default-mtime))))
(defn- try-get-mtime-for-a-file [web-asset-path]
(let [file (io/file (str "resources/public" web-asset-path))]
(if (.exists file)
(.lastModified file)
default-mtime)))
(defn hash-resource [r]
(let [md (MessageDigest/getInstance "MD5")]
(with-open [is (io/input-stream r)
dis (DigestInputStream. is md)]
(.readAllBytes dis)
(u/hexify (.digest md)))))
(defn mtime-or-default [web-asset-path]
(if-let [resource (io/resource (str "public" web-asset-path))]
(try
(.. resource openConnection getLastModified)
(catch Exception e
default-mtime))
(try-get-mtime-for-a-file web-asset-path)))
(def ^:dynamic hash-fn hash-resource)
(defn hash-or-default [res-path]
(let [relative? (not (re-find #"^\/" res-path))
resource (or (if relative?
(io/resource res-path)
(io/resource (str "public" res-path)))
(io/resource res-path))]
(if resource
(try
(hash-fn resource)
(catch Exception e
default-hash))
default-hash)))
(defn cache-bust-one [web-asset-path]
(if web-asset-path
(let []
(str web-asset-path
"?hash="
(hash-or-default web-asset-path)))))
(defn cache-bust [web-asset-path-or-coll]
(if (coll? web-asset-path-or-coll)
(map cache-bust-one web-asset-path-or-coll)
(cache-bust-one web-asset-path-or-coll)))
(defn cache-bust-assets [page-data]
(if (:skip-cachebusting? page-data)
page-data
(-> page-data
(u/update-if-present :twitter-image cache-bust-one)
(u/update-if-present :og-image cache-bust-one)
(u/update-if-present :favicon cache-bust-one)
(u/update-if-present :link-apple-icon cache-bust-one)
(u/update-if-present :link-apple-startup-image cache-bust-one)
(u/update-if-present :link-image-src cache-bust-one)
;
(u/update-if-present :script cache-bust)
(u/update-if-present :script-sync cache-bust)
(u/update-if-present :js-module cache-bust)
;
(u/update-if-present :stylesheet cache-bust)
(u/update-if-present :stylesheet-async cache-bust)
;
(u/update-if-present :manifest cache-bust-one))))