Skip to content

Instantly share code, notes, and snippets.

@lucassouza1
Forked from anonymous/gist:4383179
Created December 27, 2012 12:32
Show Gist options
  • Save lucassouza1/4388030 to your computer and use it in GitHub Desktop.
Save lucassouza1/4388030 to your computer and use it in GitHub Desktop.
(:use [ring.util.codec :only [url-encode]])
(def utmac "MO-XXXXXXXX-X") ;; Use MO instead of UA
(defn- new-uuid []
(java.util.UUID/randomUUID))
(defn md5
"Generate a md5 checksum for the given string"
[token]
(let [hash-bytes
(doto (java.security.MessageDigest/getInstance "MD5")
(.reset)
(.update (.getBytes token)))]
(.toString
(new java.math.BigInteger 1 (.digest hash-bytes)) ; Positive and the size of the number
16)))
(defn- visitor-id
[]
(let [message (str "Java" (new-uuid))
md5-string (md5 message)]
(str "0x" (subs md5-string 0 16))))
(defn- make-query-string [m]
(->> (for [[k v] m]
(str (url-encode k) "=" (url-encode (str v))))
(interpose "&")
(apply str)))
(defn make-ga-url [utmp ip]
(let [gif-url "http://www.google-analytics.com/__utm.gif?"
url-map (atom {})
add-key (fn [k v]
(swap! url-map assoc (name k) v))]
(add-key :utmac )
(add-key :utmn (rand-int 0x7fffffff))
(add-key :utmr "-")
(add-key :utmp utmp)
(add-key :utmdebug 1)
(add-key :guid "ON")
(add-key :utmwv "4.4sh")
(add-key :utmcc "__utma=999.999.999.999.999.1")
(add-key :utmvid (visitor-id))
(add-key :utmip ip)
(str gif-url (make-query-string @url-map))))
(defn wrap-ga
[handler]
(fn [request]
(let [utmp (str (:uri request) "?" (:query-string request))
ip (:remote-addr request)
url (make-ga-url utmp ip)]
(slurp url)
(handler request))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment