summaryrefslogtreecommitdiff
path: root/src/utils.clj
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils.clj')
-rwxr-xr-xsrc/utils.clj75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/utils.clj b/src/utils.clj
new file mode 100755
index 0000000..3ffd54b
--- /dev/null
+++ b/src/utils.clj
@@ -0,0 +1,75 @@
+(ns utils
+ (:import java.text.SimpleDateFormat
+ java.util.Date)
+ (:use clojure.contrib.json.write
+ clojure.contrib.sql))
+
+(let [db-host "localhost"
+ db-port 5432
+ db-name "dumpfm"]
+ (def db {:classname "org.postgresql.Driver"
+ :subprotocol "postgresql"
+ :subname (str "//" db-host ":" db-port "/" db-name)
+ :user "postgres"
+ :password "root"}))
+
+;; JSON responses
+
+(def yyyy-mm-dd-formatter (new SimpleDateFormat "yyyy-MM-dd"))
+
+(defmethod print-json Date
+ [d]
+ (print-json (.format yyyy-mm-dd-formatter d)))
+
+(defn resp-error [message]
+ {:status 400 :headers {} :body message})
+
+(defn resp-success [message]
+ {:status 200 :headers {} :body (json-str message)})
+
+;; Database
+
+(defn do-select [query]
+ (with-connection db
+ (with-query-results rs query
+ (doall rs))))
+
+(defn do-count [query]
+ ((first (with-connection db
+ (with-query-results rs query
+ (doall rs))))
+ :count))
+
+
+;; Stats
+
+(defn msg-stats [ts]
+ (let [qry (str "SELECT created_on::date, count(*) FROM messages "
+ "GROUP BY created_on::date "
+ "ORDER BY created_on::date")]
+ (do-select [qry])))
+
+(defn new-user-stats [ts]
+ (let [qry (str "SELECT created_on::date, count(*) FROM users "
+ "GROUP BY created_on::date "
+ "ORDER BY created_on::date")]
+ (do-select [qry])))
+
+(defn msgs-per-user-stats [ts]
+ true)
+
+(def *stat-map* {"msgs" msg-stats
+ "new users" new-user-stats
+ "msgs per user" msgs-per-user-stats})
+
+(defn stats [session params]
+ (let [stat (params :stat)
+ ts (params :timescale)]
+ (if-let [f (*stat-map* stat)]
+ (resp-success (f ts))
+ (resp-error "UNKNOWN STAT"))))
+
+(defn validated-stats [session params]
+ (if (session :is_admin)
+ (stats session params)
+ (resp-error "BAD_REQUEST"))) \ No newline at end of file