forked from acemtp/meteor-ping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathping.js
76 lines (60 loc) · 1.98 KB
/
ping.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
if (Meteor.isClient) {
Session.setDefault('uid', Random.id());
Session.setDefault('ping', 0);
Meteor.startup(function () {
Meteor.setInterval(function () {
var before = new Date().getTime();
var name = "";
if(Meteor.user() && Meteor.user().profile && Meteor.user().profile.name)
name = Meteor.user().profile.name;
Meteor.call('keepAlive', Session.get('uid'), Session.get('ping'), navigator.userAgent, name, function (error, result) {
var after = new Date().getTime();
if(error) console.log(error);
var ping = after - before;
Session.set("ping", ping)
//console.log("ping in ", ping);
//document.title = ping;
});
}, 1000);
});
Template.pings.pingsAlive = function () {
return Pings.find({alive: true}, {sort: {createdAt: -1}});
}
Template.pings.pingsDead = function () {
return Pings.find({alive: false}, {sort: {createdAt: -1}});
}
Template.ping.me = function () {
return Session.equals('uid', this._id);
}
Template.ping.meanPing = function () {
var tab = this.stats;
var res = 0;
_.each(tab, function(ping) {
res = res + ping;
});
return Math.floor(res / _.size(tab));
}
}
Pings = new Meteor.Collection("pings");
if (Meteor.isServer) {
Meteor.methods({
keepAlive: function (uid, ping, uagent, name) {
var p = Pings.findOne(uid);
if(p)
Pings.update(uid, {$set: {ping:ping, alive: true, updatedAt: new Date().getTime(), name: name}});
else
Pings.insert({_id: uid, alive: true, ping:ping, uagent: uagent, createdAt: new Date().getTime(), stats: [0,0,0,0,0,0,0,0,0,0], name: name });
Pings.update(uid, { $push: { "stats" : ping } } );
Pings.update(uid, { $pop: { "stats": -1 } } );
return true;
}
});
Meteor.setInterval(function () {
var now = (new Date()).getTime();
var before = (now - 5000);
Pings.find({updatedAt: {$lt: before}}).forEach(function (ping) {
//Pings.remove( ping._id );
Pings.update(ping._id, {$set : {alive : false}});
});
}, 1000*5);
}