grub-fork/src-clj/grub/core.clj

60 lines
1.9 KiB
Clojure
Raw Normal View History

2013-07-24 17:39:02 +00:00
(ns grub.core
(:require [ring.middleware.reload :as reload]
[compojure.core :refer [defroutes GET POST]]
[compojure.handler :as handler]
2013-07-24 18:38:14 +00:00
[compojure.route :as route]
[org.httpkit.server :as httpkit]
2013-07-24 18:38:14 +00:00
[hiccup
[page :refer [html5]]
[page :refer [include-js include-css]]]
[clojure.core.async :as async :refer [<! >! >!! chan go close! timeout]]))
2013-07-24 18:38:14 +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-08-04 18:15:56 +00:00
(include-css "/css/bootstrap.css")
(include-css "/css/styles.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
(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?
(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]
(httpkit/run-server app {:port 3000}))