2013-07-24 17:39:02 +00:00
|
|
|
(ns grub.core
|
|
|
|
(:require [ring.middleware.reload :as reload]
|
2013-07-28 06:24:01 +00:00
|
|
|
[compojure.core :refer [defroutes GET POST]]
|
|
|
|
[compojure.handler :as handler]
|
2013-07-24 18:38:14 +00:00
|
|
|
[compojure.route :as route]
|
2013-07-28 06:24:01 +00:00
|
|
|
[org.httpkit.server :as httpkit]
|
2013-07-24 18:38:14 +00:00
|
|
|
[hiccup
|
|
|
|
[page :refer [html5]]
|
2013-07-28 06:24:01 +00:00
|
|
|
[page :refer [include-js include-css]]]
|
|
|
|
[clojure.core.async :as async :refer [<! >! >!! chan go close! timeout]]))
|
2013-07-24 18:38:14 +00:00
|
|
|
|
2013-07-28 06:24:01 +00:00
|
|
|
(def out-channels (atom []))
|
|
|
|
(def channel-id-count (atom 0))
|
|
|
|
|
|
|
|
(defn push-grub-to-others [grub my-channel-id]
|
|
|
|
(let [other-channels (fn [] (filter #(not (= (:id %) my-channel-id)) @out-channels))]
|
|
|
|
(go (doseq [{ch :channel} (other-channels)]
|
|
|
|
(>! ch grub)))))
|
|
|
|
|
|
|
|
(defn push-new-grubs-to-client [c ws-channel]
|
|
|
|
(go (while true
|
|
|
|
(let [grub (<! c)]
|
|
|
|
(httpkit/send! ws-channel grub)))))
|
|
|
|
|
|
|
|
(defn websocket-handler [request]
|
|
|
|
(httpkit/with-channel request ws-channel
|
|
|
|
(let [channel-id (swap! channel-id-count inc)
|
|
|
|
c (chan)]
|
|
|
|
(swap! out-channels conj {:id channel-id :channel c})
|
|
|
|
(println "channel connected:" (.toString ws-channel))
|
|
|
|
(httpkit/on-receive ws-channel #(push-grub-to-others % channel-id))
|
|
|
|
(push-new-grubs-to-client c ws-channel))))
|
|
|
|
|
2013-07-24 18:38:14 +00:00
|
|
|
(defn index-page []
|
|
|
|
(html5
|
2013-07-24 19:43:26 +00:00
|
|
|
[:head
|
|
|
|
[:title "Grub"]
|
|
|
|
[:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
|
2013-07-27 15:54:15 +00:00
|
|
|
(include-css "/css/bootstrap.css")]
|
2013-07-24 18:38:14 +00:00
|
|
|
[:body
|
2013-07-24 19:43:26 +00:00
|
|
|
(include-js "http://code.jquery.com/jquery.js")
|
|
|
|
(include-js "/js/bootstrap.js")
|
|
|
|
(include-js "/js/main.js")]))
|
2013-07-24 18:38:14 +00:00
|
|
|
|
|
|
|
(defroutes routes
|
2013-07-28 06:24:01 +00:00
|
|
|
(GET "/ws" [] websocket-handler)
|
2013-07-24 18:38:14 +00:00
|
|
|
(GET "/" [] (index-page))
|
|
|
|
(route/files "/")
|
|
|
|
(route/not-found "<p>Page not found.</p>"))
|
2013-07-24 17:39:02 +00:00
|
|
|
|
2013-07-24 18:38:14 +00:00
|
|
|
(def app
|
|
|
|
(let [dev? true]
|
|
|
|
(if dev?
|
2013-07-28 06:24:01 +00:00
|
|
|
(reload/wrap-reload (handler/site #'routes))
|
|
|
|
(handler/site routes))))
|
2013-07-24 17:39:02 +00:00
|
|
|
|
2013-07-24 18:38:14 +00:00
|
|
|
(defn -main [& args]
|
2013-07-28 06:24:01 +00:00
|
|
|
(httpkit/run-server app {:port 3000}))
|