Skip to content

Commit

Permalink
Implement getServerTime()
Browse files Browse the repository at this point in the history
  • Loading branch information
andronat committed Mar 30, 2020
1 parent 0b029a7 commit e31f5fd
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ class FirebaseWebRtcAdapter {
this.peers = {}; // id -> WebRtcPeer
this.occupants = {}; // id -> joinTimestamp

this.serverTimeRequests = 0;
this.timeOffsets = [];
this.avgTimeOffset = 0;

config = config || window.firebaseConfig;
this.firebase = firebase || window.firebase;

Expand Down Expand Up @@ -85,6 +89,8 @@ class FirebaseWebRtcAdapter {
var self = this;

this.initFirebase(function(id) {
self.updateTimeOffset();

self.localId = id;
var firebaseApp = self.firebaseApp;

Expand Down Expand Up @@ -252,6 +258,10 @@ class FirebaseWebRtcAdapter {
}
}

getMediaStream(clientId) {
return Promise.reject("Interface method not implemented: getMediaStream");
}

/*
* Privates
*/
Expand Down Expand Up @@ -381,6 +391,38 @@ class FirebaseWebRtcAdapter {
});
ref.onDisconnect().remove();
}

updateTimeOffset() {
return this.firebaseApp
.database()
.ref("/.info/serverTimeOffset")
.once("value")
.then(data => {
var timeOffset = data.val();

this.serverTimeRequests++;

if (this.serverTimeRequests <= 10) {
this.timeOffsets.push(timeOffset);
} else {
this.timeOffsets[this.serverTimeRequests % 10] = timeOffset;
}

this.avgTimeOffset =
this.timeOffsets.reduce((acc, offset) => (acc += offset), 0) /
this.timeOffsets.length;

if (this.serverTimeRequests > 10) {
setTimeout(() => this.updateTimeOffset(), 5 * 60 * 1000); // Sync clock every 5 minutes.
} else {
this.updateTimeOffset();
}
});
}

getServerTime() {
return new Date().getTime() + this.avgTimeOffset;
}
}

NAF.adapters.register("firebase", FirebaseWebRtcAdapter);
Expand Down

0 comments on commit e31f5fd

Please sign in to comment.