随着时间的推移,存在着越来越错误的火球

firebase presence becomes more and more wrong over time

本文关键字:错误 越来越 火球 存在 时间      更新时间:2023-09-26

我根据他们的例子为firebase设置了一个简单的存在用户计数。问题是它依赖于删除断开连接时的计数。然而,firebase似乎每两个月就会关闭一次,并删除ondisconnect处理程序。这意味着随着时间的推移,计数会变得越来越错误。有什么办法解决这个问题吗?

ty.Presence = function() {
  this.rooms = {}
  this.presence = fb.child('presence')
  this.connectedRef = fb.child('.info/connected');
  if (!localStorage.fb_presence_id) {
    localStorage.fb_presence_id = Math.random().toString(36).slice(2)
  }
  this.browserID = localStorage.fb_presence_id
  var first = false   
}

ty.Presence.prototype.add = function(roomID, userobj) {
  var self = this
  var userListRef = this.presence.child(roomID)
  // Generate a reference to a new location for my user with push.
  var obj = {
    s: "on",
    id: this.browserID
  }
  if (userobj) {
    obj.u = {
      _id: userobj._id,
      n: userobj.username
    }
    if (userobj.a) {
      obj.u.a = userobj.a
    }
  }
  var myUserRef = userListRef.push(obj)
  this.rooms[roomID] = myUserRef
  this.connectedRef.on("value", function(isOnline) {
    if (isOnline.val()) {
      // If we lose our internet connection, we want ourselves removed from the list.
      myUserRef.onDisconnect().remove();
    }
  });
};
ty.Presence.prototype.count = function(roomID, cb) {
  var self = this
  var userListRef = this.presence.child(roomID)
  var count = 0
  function res () {
    var usersArr = _.pluck(users, 'id')
    usersArr = _.uniq(usersArr)
    count = usersArr.length
    if (cb) cb(count)
  }
  var users = {}
  userListRef.on("child_added", function(css) {
    users[css.name()] = css.val();
    res()
  });
  userListRef.on("child_removed", function(css) {
    delete users[css.name()]
    res()
  });
  cb(count)
};
ty.Presence.prototype.get = function(ref) {
  return this[ref]
};
ty.Presence.prototype.setGlobal = function(object) {
  var self = this
  _.each(this.rooms, function (myUserRef) {
    myUserRef.set(object)
  })
};
ty.Presence.prototype.remove = function(roomID) {
  if (this.rooms[roomID])
    this.rooms[roomID].remove();
};
ty.Presence.prototype.off = function(roomID) {
  var userListRef = this.presence.child(roomID)
  userListRef.off()
};

ty.presence = new ty.Presence()
ty.presence.add('all')

如果重新启动Firebase(例如,当新版本被实时推送时),onDisconnect处理程序可能会丢失。一种简单的方法是在存储记录时将时间戳作为优先级附加到记录。只要客户端保持在线,就让他偶尔更新时间戳。

setInterval(function() {
    connectedRef.setPriority(Date.now());   
}, 1000*60*60*4 /* every 4 hours */ );

因此,任何达到24小时的记录,显然都是孤儿。挑战可能由客户端(例如,当新客户端第一次收到列表时)或服务器进程(例如,node.js脚本使用setInterval()检查X之前的记录)进行。

presenceRef.endAt(Date.now()-24*60*60*1000 /* 24 hours ago */).remove();

当然不太理想,但这是我在应用程序中使用过的一种功能性解决方法。