読み書きプログラミング

日常のプログラミングで気づいたことを綴っています

サインインユーザーの現在閲覧ページモニタ

前回に続いて、サインインしてるユーザーの閲覧状態をモニタするコードです。

苦労したところは、サーバー側を更新した時のイベントです。明示的なAPIはないので、リアクティブなMeteor.status()を使いました。

# (C) 2015 ICHIKAWA, Yuji (New 3 Rs)
###
Iron Router current page monitoring
Usage:
1. publish connections property of user to use in client side.
2. connections property includes sessionId-path pairs
###

"use strict"

connections = {} # connectionId: userId

Router.onAfterAction ->
    if Meteor.isClient and @ready() and (userId = Meteor.userId())?
        Meteor.call 'current-page', @location.get().path
    return

if Meteor.isClient
    reconnect = false
    Meteor.autorun ->
        if Meteor.status().connected
            if reconnect and Meteor.userId()?
                Meteor.call 'current-page', Iron.Location.get().path
        else
            reconnect = true

if Meteor.isServer
    Meteor.methods
        'current-page': (path) ->
            unless @userId?
                return
            check path, String

            connections[@connection.id] = @userId
            set = {}
            set["connections.#{@connection.id}"] = path
            Meteor.users.update @userId, $set: set
            return

    Meteor.onConnection (handle) ->
        handle.onClose ->
            unset = {}
            unset["connections.#{handle.id}"] = ''
            Meteor.users.update connections[handle.id], $unset: unset
            delete connections[handle.id]
            return
        return

    Meteor.startup ->
        Meteor.users.find().forEach (user) ->
            Meteor.users.update user._id, $unset:
                status: ''
                connections: ''