diff --git a/smart.json b/smart.json index c3a7d69..f791a23 100644 --- a/smart.json +++ b/smart.json @@ -3,7 +3,7 @@ "description": "User connection and status tracking for meteor", "homepage": "https://github.com/mizzao/meteor-user-status", "author": "Andrew Mao (http://www.andrewmao.net)", - "version": "0.1.1", + "version": "0.1.2", "git": "https://github.com/mizzao/meteor-user-status.git", "packages": {} } diff --git a/user_status_client.coffee b/user_status_client.coffee index 36dadf1..0b1a6f5 100644 --- a/user_status_client.coffee +++ b/user_status_client.coffee @@ -1,15 +1,3 @@ - -# Hook into original logout function -Meteor.__logout__ = Meteor.logout -Meteor.logout = (callback) -> - Meteor.users.update Meteor.userId(), - $set: {'profile.online': false} - Meteor.__logout__(callback) - -# Add online status when logged in or resuming Deps.autorun -> - return unless Meteor.userId() - Meteor.users.update Meteor.userId(), - $set: {'profile.online': true} - -Meteor.subscribe "statusWatcher" + Meteor.userId() # Re-subscribe whenever logging in our out + Meteor.subscribe "statusWatcher" diff --git a/user_status_server.coffee b/user_status_server.coffee index 7d9110b..6dd7021 100644 --- a/user_status_server.coffee +++ b/user_status_server.coffee @@ -1,22 +1,36 @@ this.UserSockets = new Meteor.Collection(null) -# Publication is guaranteed to be called once per connection -# trick as referenced in http://stackoverflow.com/q/10257958/586086 +# pub/sub trick as referenced in http://stackoverflow.com/q/10257958/586086 Meteor.publish "statusWatcher", -> id = @_session.userId - return unless id? + return unless @_session.socket? sockId = @_session.socket.id - # Add socket to open connections - Meteor.bindEnvironment -> - UserSockets.insert - userId: id + # Untrack connection on logout + unless id? + # TODO: this could be replaced with a findAndModify once it's supported on Collections + existing = UserSockets.findOne sockId: sockId - , (e) -> - Meteor._debug "Exception from connection add callback:", e + return unless existing? # Probably new session + + id = existing.userId + UserSockets.remove + sockId: sockId + + if UserSockets.find(userId: id).count() is 0 + Meteor.users.update id, + $set: {'profile.online': false} + return + + # Add socket to open connections + UserSockets.insert + userId: id + sockId: sockId + Meteor.users.update id, + $set: {'profile.online': true} # Remove socket on close - @_session.socket.on "close", Meteor.bindEnvironment( -> + @_session.socket.on "close", Meteor.bindEnvironment -> UserSockets.remove userId: id sockId: sockId @@ -24,7 +38,7 @@ Meteor.publish "statusWatcher", -> if UserSockets.find(userId: id).count() is 0 Meteor.users.update id, $set: {'profile.online': false} - , (e) -> Meteor._debug "Exception from connection close callback:", e - ) + + return