nts.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. ;(function(){
  2. // NOTE: While the algorithm is P2P,
  3. // the current implementation is one sided,
  4. // only browsers self-modify, servers do not.
  5. // Need to fix this! Since WebRTC is now working.
  6. var env;
  7. if(typeof global !== "undefined"){ env = global }
  8. if(typeof window !== "undefined"){ var Gun = (env = window).Gun }
  9. else {
  10. if(typeof require !== "undefined"){ var Gun = require('./gun') }
  11. }
  12. Gun.on('opt', function(ctx){
  13. this.to.next(ctx);
  14. if(ctx.once){ return }
  15. ctx.on('in', function(at){
  16. if(!at.nts && !at.NTS){
  17. return this.to.next(at);
  18. }
  19. if(at['@']){
  20. (ask[at['@']]||noop)(at);
  21. return;
  22. }
  23. if(env.window){
  24. return this.to.next(at);
  25. }
  26. this.to.next({'@': at['#'], nts: Gun.time.is()});
  27. });
  28. var ask = {}, noop = function(){};
  29. if(!env.window){ return }
  30. Gun.state.drift = Gun.state.drift || 0;
  31. setTimeout(function ping(){
  32. var NTS = {}, ack = Gun.text.random(), msg = {'#': ack, nts: true, gun: ctx.gun};
  33. NTS.start = Gun.state();
  34. ask[ack] = function(at){
  35. NTS.end = Gun.state();
  36. Gun.obj.del(ask, ack);
  37. NTS.latency = (NTS.end - NTS.start)/2;
  38. if(!at.NTS){ return }
  39. NTS.calc = NTS.latency + at.NTS;
  40. Gun.state.drift -= (NTS.end - NTS.calc)/2;
  41. setTimeout(ping, 1000);
  42. }
  43. ctx.on('out', msg);
  44. }, 1);
  45. });
  46. // test by opening up examples/game/nts.html on devices that aren't NTP synced.
  47. }());