From 20126bfad85a059912a2c372bd8e1239871c7b92 Mon Sep 17 00:00:00 2001 From: sostler Date: Wed, 17 Feb 2010 00:33:01 -0500 Subject: committing login-cookie hack to work on --- src/site.clj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/site.clj b/src/site.clj index dd7de80..2516d49 100755 --- a/src/site.clj +++ b/src/site.clj @@ -13,8 +13,9 @@ clojure.contrib.json.write clojure.contrib.sql compojure + utils cookie-login - utils)) + feed)) (def *run-flusher* true) (def *flusher-sleep-ms* 4000) -- cgit v1.2.3-70-g09d2 From 8a981f390c286cb9c5935290e7846df903148278 Mon Sep 17 00:00:00 2001 From: Scott Ostler Date: Mon, 22 Feb 2010 22:29:02 -0500 Subject: Avatar-uploading --- src/image_utils.clj | 3 ++ src/site.clj | 138 ++++++++++++++++++++++++++++++++++------------------ static/js/home.js | 3 +- static/js/pichat.js | 38 +++++++++++++-- template/profile.st | 8 +-- 5 files changed, 136 insertions(+), 54 deletions(-) create mode 100644 src/image_utils.clj (limited to 'src') diff --git a/src/image_utils.clj b/src/image_utils.clj new file mode 100644 index 0000000..638cd05 --- /dev/null +++ b/src/image_utils.clj @@ -0,0 +1,3 @@ +(ns image-utils + (:import javax.imageio.ImageIO)) + diff --git a/src/site.clj b/src/site.clj index c36f1ae..7b75b71 100755 --- a/src/site.clj +++ b/src/site.clj @@ -14,6 +14,7 @@ clojure.contrib.sql compojure cookie-login + image-utils )) (let [db-host "localhost" @@ -63,9 +64,11 @@ "http://localhost:8080")) (def *image-directory* "images") +(def *avatar-directory* "avatars") -; Create image directory if it doesn't exist. +; Create image directories if they don't exist. (.mkdir (new File *image-directory*)) +(.mkdir (new File *avatar-directory*)) ;; Utils @@ -333,41 +336,48 @@ ;; Profile (defn profile [session profile-nick offset] - (let [user-info (fetch-nick profile-nick)] - (if user-info - (let [nick (session :nick) - is-home (and nick (= nick profile-nick)) - has-avatar (non-empty-string? (user-info :avatar)) - offset (maybe-parse-int offset 0) - dump-offset (* offset *dumps-per-page*) - dumps (fetch-messages-by-nick profile-nick true dump-offset) - dump-count (count-messages-by-nick profile-nick true) - st (fetch-template "profile" session)] - (do - (.setAttribute st "is_home" is-home) - (doseq [a [:nick :avatar :contact :bio]] - (let [v (user-info a)] - (.setAttribute st (name a) - (if (non-empty-string? v) (escape-html v))))) - (.setAttribute st "dumps" - (to-array (map process-message-for-output dumps))) - (if (< (+ dump-offset *dumps-per-page*) dump-count) - (.setAttribute st "next" (inc offset))) - (if (not= offset 0) - (.setAttribute st "prev" (max (dec offset) 0))) + (if-let [user-info (fetch-nick profile-nick)] + (let [nick (session :nick) + is-home (and nick (= nick profile-nick)) + has-avatar (non-empty-string? (user-info :avatar)) + offset (maybe-parse-int offset 0) + dump-offset (* offset *dumps-per-page*) + dumps (fetch-messages-by-nick profile-nick true dump-offset) + dump-count (count-messages-by-nick profile-nick true) + st (fetch-template "profile" session)] + (do + (.setAttribute st "is_home" is-home) + (doseq [a [:nick :avatar :contact :bio]] + (let [v (user-info a)] + (.setAttribute st (name a) + (if (non-empty-string? v) (escape-html v))))) + (.setAttribute st "dumps" + (to-array (map process-message-for-output dumps))) + (if (< (+ dump-offset *dumps-per-page*) dump-count) + (.setAttribute st "next" (inc offset))) + (if (not= offset 0) + (.setAttribute st "prev" (max (dec offset) 0))) (.toString st))) - (resp-error "NO_USER")))) + (resp-error "NO_USER"))) + + +;; TODO: update chat w/ new avatar +(defn do-update-avatar [session params] + nil) + +(defn do-update-profile [user-id attr val] + (with-connection db + (update-values "users" ["user_id = ?" user-id] {attr val}))) (defn update-profile [session params] (let [user-id (session :user_id) attr (params :attr) val (params :val) attr-set #{"avatar" "contact" "bio"}] - (if (and user-id attr val + (if (and user-id attr val (contains? attr-set attr)) (do - (with-connection db - (update-values "users" ["user_id = ?" user-id] {attr val})) + (do-update-profile attr val) (if (= attr "avatar") [(session-assoc :avatar val) "OK"] "OK")) @@ -415,11 +425,12 @@ nick (session :nick) users (room :users)] (if nick - (if (contains? @users nick) - (alter users assoc-in [nick :last-seen] now) - (alter (room :users) assoc nick (user-struct-from-session session)))) - (resp-success (assoc (updates room since) - :timestamp now))))) + (if-let [user-info (@users nick)] + ; Incorporate avatar updates + (commute users assoc nick (merge user-info {:last-seen now + :avatar (user-info :avatar)})) + (commute (room :users) assoc nick (user-struct-from-session session)))) + (resp-success (assoc (updates room since) :timestamp now))))) (defn validated-refresh [session params] (let [room-key (params :room) @@ -525,32 +536,64 @@ ;; Upload +(def *avatar-dimensions* [50 50]) + +(defn is-image-file? [path] + true) + (defn format-filename [s] (let [spaceless (.replace s \space \-) subbed (re-gsub #"[^\w.-]" "" spaceless)] (str (System/currentTimeMillis) "-" subbed))) -(defn image-url-from-file [f] - (str-join "/" [*server-url* "images" (.getName f)])) +(defn image-url-from-file [d f] + (str-join "/" [*server-url* d (.getName f)])) + (defn do-upload [session image room] (let [filename (format-filename (:filename image)) dest (File. (rel-join *image-directory* filename)) - url (image-url-from-file dest) + url (image-url-from-file "images" dest) msg-id (msg-db (session :user_id) (room :room_id) url) - now (new Date) - msg (struct message-struct (session :nick) url now msg-id)] - (dosync - (add-message msg room)) - (copy (:tempfile image) dest) - [200 url])) + msg (struct message-struct (session :nick) url (new Date) msg-id)] + (do + (dosync + (add-message msg room)) + (copy (:tempfile image) dest) + (resp-success url)))) (defn upload [session params] (let [room-key (params :room) - nick (session :nick)] + nick (session :nick) + image (params :image)] (cond (not nick) [200 "NOT_LOGGED_IN"] + (not image) [200 "INVALID_REQUEST"] + (not (is-image-file? (image :filename))) [200 "INVALID_IMAGE"] (not (validate-room-access room-key session)) [200 "UNKNOWN_ROOM"] - :else (do-upload session (:image params) (@rooms room-key))))) + :else (do-upload session image (@rooms room-key))))) + +(defn copy-and-resize [image dest] + ; TODO: resize + (copy image dest)) + +;; NOTE -- Upload responses arent JSON-evaluated +(defn do-upload-avatar [session image] + (let [filename (format-filename (:filename image)) + dest (File. (rel-join *avatar-directory* filename)) + url (image-url-from-file "avatars" dest)] + (do + (copy-and-resize (:tempfile image) dest) + (do-update-profile (session :user_id) "avatar" url) + [(session-assoc :avatar url) + [200 url]]))) + +(defn upload-avatar [session params] + (let [image (params :image)] + (cond (not image) [200 "INVALID_REQUEST"] + (not (session :nick)) [200 "NOT_LOGGED_IN"] + (not (is-image-file? (image :filename))) [200 "INVALID_IMAGE"] + :else (do-upload-avatar session image)))) + ;; 404 (defn unknown-page [params] @@ -573,7 +616,8 @@ (defroutes static (GET "/static/*" (serve-static "static" (params :*))) - (GET "/images/*" (serve-static *image-directory* (params :*)))) + (GET "/images/*" (serve-static *image-directory* (params :*))) + (GET "/avatars/*" (serve-static *avatar-directory* (params :*)))) (defroutes pichat (GET "/" (no-cache (landing session))) @@ -605,7 +649,8 @@ (ANY "*" (unknown-page params))) (defroutes multipart - (POST "/upload" (upload session params))) + (POST "/upload/message" (upload session params)) + (POST "/upload/avatar" (upload-avatar session params))) ;; Add jpeg to list (def mimetypes @@ -647,7 +692,8 @@ (run-server {:port 8080} "/static/*" (servlet static) "/images/*" (servlet static) - "/upload" (servlet multipart) + "/avatars/*" (servlet static) + "/upload/*" (servlet multipart) "/*" (servlet pichat)) (send-off flusher flush!) \ No newline at end of file diff --git a/static/js/home.js b/static/js/home.js index b37bc8d..59d4c3d 100755 --- a/static/js/home.js +++ b/static/js/home.js @@ -145,14 +145,13 @@ function initBigHand(id){ } function login() { - //$('#passwordInput, #loginSubmit').blur(); var nick = $('#nickInput').val(); var password = $('#passwordInput').val(); var rememberme = $('#remembermeInput').attr('checked') ? 'yes' : ''; var hash = hex_sha1(nick + '$' + password + '$dumpfm'); var onSuccess = function(json) { - location.href = "/chat"; + location.href = location.href; }; var onError = function(resp, textStatus, errorThrown) { diff --git a/static/js/pichat.js b/static/js/pichat.js index d3da949..06c859d 100755 --- a/static/js/pichat.js +++ b/static/js/pichat.js @@ -225,7 +225,7 @@ function initProfile() { $('.logged-dump .content').each(function() { var t = $(this); t.html(buildMsgContent(t.text())); - }); + }); var onSubmit = function(attr, newVal, oldVal) { newVal = $.trim(newVal); @@ -260,6 +260,10 @@ function initProfile() { 'callbackShowErrors': false }; $('#contact.editable, #bio.editable').editInPlace(textareaOpts); + if ($('#upload').length > 0) { + setupUploadAvatar('upload'); + } + }; function initLog() { @@ -267,7 +271,6 @@ function initLog() { var t = $(this); t.html(buildMsgContent(t.text())); }); - } // TODO @@ -275,13 +278,42 @@ function favoriteImage() {}; function setupUpload(elementId, roomKey) { new AjaxUpload(elementId, { - action: '/upload', + action: '/upload/message', autoSubmit: true, name: 'image', data: { room: roomKey } }); } +function setupUploadAvatar(elementId) { + // NOTE: AjaxUpload responses aren't converted from JSON. + var onSubmit = function(file, error) { + $('#spinner').show(); + }; + var onComplete = function(file, resp) { + $('#spinner').hide(); + if (resp == 'INVALID_REQUEST') { + location.href = location.href; + } else if (resp == 'NOT_LOGGED_IN') { + location.href = location.href; + } else if (resp == 'INVALID_IMAGE') { + alert("Sorry, dump.fm can't deal with your image. Pick another :("); + return; + } + var s = ''; + $('#avatarPic').replaceWith(s).show(); + $('#avatar').text(resp); + }; + new AjaxUpload(elementId, { + action: '/upload/avatar', + autoSubmit: true, + name: 'image', + onSubmit: onSubmit, + onComplete: onComplete + }); +} + + // scrolling stuff // this code keeps the div scrolled to the bottom, but will also let the user scroll up, without jumping down diff --git a/template/profile.st b/template/profile.st index c3d77e2..071b888 100755 --- a/template/profile.st +++ b/template/profile.st @@ -5,8 +5,8 @@ + type="text/javascript"> + @@ -20,7 +20,7 @@ var text = jQuery(this).text(); jQuery(this).html(linkify(text)); }); - }); + }); @@ -51,6 +51,8 @@ $if(is_home)$
$avatar$
+ + $endif$ -- cgit v1.2.3-70-g09d2 From 223f95c03b41370219268d53fceb951808f780e6 Mon Sep 17 00:00:00 2001 From: sostler Date: Wed, 24 Feb 2010 08:02:59 -0500 Subject: Fixed cookie logins --- src/cookie_login.clj | 5 ++--- src/site.clj | 43 +++++++++++++++++++++++++++---------------- 2 files changed, 29 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/cookie_login.clj b/src/cookie_login.clj index e507876..8c948a6 100755 --- a/src/cookie_login.clj +++ b/src/cookie_login.clj @@ -38,7 +38,7 @@ "Middleware to support automatic cookie login. Must be placed after the with-session middleware. -Must be given three arguments: + Must be given three arguments: - process-login-token? Function to apply to request map to determine whether to process login token or not. If a false value is returned, @@ -56,8 +56,7 @@ Must be given three arguments: - *login-token-expiry* The number of milliseconds a login token is valid for. - Defaults to one week. -" + Defaults to one week." [handler process-login-token? token-maker token-reader] (let [login-token-key *login-token-key* login-token-expiry *login-token-expiry*] diff --git a/src/site.clj b/src/site.clj index a524a1c..b519f90 100755 --- a/src/site.clj +++ b/src/site.clj @@ -15,6 +15,7 @@ compojure utils cookie-login + session-sweeper feed)) (def *run-flusher* true) @@ -34,9 +35,7 @@ (def rooms (ref {})) (def flusher (agent nil)) -(defn flush! [x] - (when *run-flusher* - (send-off *agent* #'flush!)) +(defn flush-inactive-users! [x] (doseq [[rid room] @rooms] (dosync (let [users (room :users) @@ -44,9 +43,14 @@ alive? (fn [[n u]] (> (u :last-seen) (- now *user-timeout-ms*)))] (ref-set users (into {} (filter alive? @users)))))) - (. Thread (sleep *flusher-sleep-ms*)) + (Thread/sleep *flusher-sleep-ms*) + (when *run-flusher* + (send *agent* #'flush-inactive-users!)) x) +(defn start-user-flusher! [] + (send flusher flush-inactive-users!)) + ;; Configuration (def *server-url* @@ -244,9 +248,13 @@ (try [(aget x 0) (Long/parseLong (aget x 1)) (aget x 2)] (catch NumberFormatException _ nil)))) - (defn read-login-token [token] - nil) + (if-let [[nick expiry token-hash] (parse-login-token token)] + (if (>= expiry (System/currentTimeMillis)) + (let [db-info (fetch-nick nick) + computed-hash (sha1-hash (db-info :hash) expiry)] + (if (= token-hash computed-hash) + db-info))))) (defn make-login-token [{nick :nick hash :hash}] @@ -534,8 +542,7 @@ (defn serve-static [dir path] ; TODO: cache policy for other static files (js, css, etc.) (let [cache-header (if (re-find pic-regex path) - {:headers {"Cache-Control" - "post-check=3600,pre-check=43200"}} + {:headers {"Cache-Control" "max-age=604800,public"}} {})] [cache-header (serve-file dir path)])) @@ -613,11 +620,15 @@ (doseq [room-db (fetch-rooms)] (alter rooms assoc (room-db :key) (build-room-map-from-db room-db)))) - -(run-server {:port 8080} - "/static/*" (servlet static) - "/images/*" (servlet static) - "/upload" (servlet multipart) - "/*" (servlet pichat)) - -(send-off flusher flush!) + +(defn start-server + ([port] (run-server {:port port} + "/static/*" (servlet static) + "/images/*" (servlet static) + "/upload" (servlet multipart) + "/*" (servlet pichat))) + ([] (start-server 8080))) + +(start-server) +(start-user-flusher!) +(start-session-pruner!) \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 10e5c6b24b63e5a83922058d47380577808b8d3e Mon Sep 17 00:00:00 2001 From: Scott Ostler Date: Wed, 24 Feb 2010 08:04:03 -0500 Subject: Added avatar uploading, images to logs --- src/site.clj | 61 ++++++++++++++++++++++++++----------------------- static/js/home.js | 3 ++- static/js/pichat.js | 1 - template/log.st | 7 ++---- template/logged_dump.st | 1 + 5 files changed, 37 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/site.clj b/src/site.clj index 2936f13..4ffa3cf 100755 --- a/src/site.clj +++ b/src/site.clj @@ -123,6 +123,7 @@ (defn process-message-for-output [d] {"nick" (escape-html (d :nick)) + "avatar" (escape-html (d :avatar)) "message_id" (d :message_id) "created_on" (.format formatter (d :created_on)) "content" (escape-html (d :content))}) @@ -165,7 +166,7 @@ (defn fetch-messages-by-room ([room-id image-only] (fetch-messages-by-room room-id image-only 0)) ([room-id image-only offset] - (let [query (str "SELECT m.content, m.message_id, m.created_on, u.nick " + (let [query (str "SELECT m.content, m.message_id, m.created_on, u.nick, u.avatar " "FROM messages m, users u " "WHERE room_id = ? AND m.user_id = u.user_id " (if image-only "AND m.is_image = true " "") @@ -184,7 +185,7 @@ (defn fetch-messages-by-nick ([nick image-only] (fetch-messages-by-nick nick image-only 0)) ([nick image-only offset] - (let [query (str "SELECT m.content, m.created_on, u.nick " + (let [query (str "SELECT m.content, m.created_on, u.nick, u.avatar " "FROM messages m, users u, rooms r " "WHERE m.user_id = u.user_id AND u.nick = ? " "AND r.room_id = m.room_id AND r.admin_only = false " @@ -240,22 +241,25 @@ (defn parse-login-token [token] (let [x (.split token "\\%")] - (if (not (= (alength x) 3)) - nil) - (try [(aget x 0) (Long/parseLong (aget x 1)) (aget x 2)] - (catch NumberFormatException _ nil)))) - + (if (= (alength x) 3) + (try [(aget x 0) (Long/parseLong (aget x 1)) (aget x 2)] + (catch NumberFormatException _ nil))))) (defn read-login-token [token] - nil) + (if-let [[nick expiry token-hash] (parse-login-token token)] + (if (>= expiry (System/currentTimeMillis)) + (let [db-info (fetch-nick nick) + computed-hash (sha1-hash (db-info :hash) expiry)] + (if (= token-hash computed-hash) + (select-keys db-info [:user_id :nick :is_admin :avatar])))))) (defn make-login-token [{nick :nick hash :hash}] (let [expiration (ms-in-future *login-token-expiry*)] - (set-cookie *login-token-key* (encode-login-token nick - hash - expiration) - :expires (gmt-string (new Date expiration))))) + (set-cookie *login-token-key* + (encode-login-token nick hash expiration) + :expires + (gmt-string (new Date expiration))))) ;; Landing @@ -328,27 +332,26 @@ (resp-error "NO_USER"))) -;; TODO: update chat w/ new avatar -(defn do-update-avatar [session params] - nil) - -(defn do-update-profile [user-id attr val] +(defn update-user-db [user-id attr val] (with-connection db - (update-values "users" ["user_id = ?" user-id] {attr val}))) + (update-values "users" ["user_id = ?" user-id] {attr val}))) + +(defn download-avatar [session url] + (let [url false] + (update-user-db (session :user_id) "avatar" url) + (resp-success url))) (defn update-profile [session params] (let [user-id (session :user_id) attr (params :attr) val (params :val) attr-set #{"avatar" "contact" "bio"}] - (if (and user-id attr val - (contains? attr-set attr)) - (do - (do-update-profile attr val) - (if (= attr "avatar") - [(session-assoc :avatar val) "OK"] - "OK")) - (resp-error "BAD_REQUEST")))) + (cond (not user-id) (resp-error "MUST_LOGIN") + (not (and user-id attr val)) (resp-error "BAD_REQUEST") + (not (contains? attr-set attr)) (resp-error "BAD_REQUEST") + (= attr "avatar") (download-avatar session val) + :else (do (update-user-db user-id attr val) + (resp-success "OK"))))) ;; Chat @@ -395,7 +398,7 @@ (if-let [user-info (@users nick)] ; Incorporate avatar updates (commute users assoc nick (merge user-info {:last-seen now - :avatar (user-info :avatar)})) + :avatar (session :avatar)})) (commute (room :users) assoc nick (user-struct-from-session session)))) (resp-success (assoc (updates room since) :timestamp now))))) @@ -543,14 +546,14 @@ ; TODO: resize (copy image dest)) -;; NOTE -- Upload responses arent JSON-evaluated +;; N.B. -- Upload responses aren't JSON-evaluated (defn do-upload-avatar [session image] (let [filename (format-filename (:filename image)) dest (File. (rel-join *avatar-directory* filename)) url (image-url-from-file "avatars" dest)] (do (copy-and-resize (:tempfile image) dest) - (do-update-profile (session :user_id) "avatar" url) + (update-user-db (session :user_id) "avatar" url) [(session-assoc :avatar url) [200 url]]))) diff --git a/static/js/home.js b/static/js/home.js index 60b5d07..e9be833 100755 --- a/static/js/home.js +++ b/static/js/home.js @@ -152,7 +152,8 @@ function login() { var onSuccess = function(json) { location.href = location.href; if (typeof pageTracker !== 'undefined') { - pageTracker._setCustomVar(1, "logged-in", nick, + pageTracker._setCustomVar(1, "logged-in", nick); + } }; var onError = function(resp, textStatus, errorThrown) { diff --git a/static/js/pichat.js b/static/js/pichat.js index 566bd10..92d24a1 100755 --- a/static/js/pichat.js +++ b/static/js/pichat.js @@ -241,7 +241,6 @@ function initChat() { } function initProfile() { - jQuery(".linkify").each(function() { var text = jQuery(this).text(); jQuery(this).html(linkify(text)); diff --git a/template/log.st b/template/log.st index 0a12550..97eaa78 100755 --- a/template/log.st +++ b/template/log.st @@ -16,12 +16,9 @@
-
- -
+

-
$if(dumps)$ $dumps: { d | $logged_dump(dump=d)$ }$ @@ -31,7 +28,7 @@
$if(next)$ - + $endif$   diff --git a/template/logged_dump.st b/template/logged_dump.st index 86e23fc..01700b5 100755 --- a/template/logged_dump.st +++ b/template/logged_dump.st @@ -31,6 +31,7 @@ img{ }
+
$dump.created_on$ -- by $dump.nick$
$dump.content$

-- cgit v1.2.3-70-g09d2