forked from strophe/strophejs-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Feature: Added plugin for synchronising client time with the server
- Loading branch information
Theo Cushion
committed
Nov 28, 2010
1 parent
9d971eb
commit f8465cc
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
//= require <strophe> | ||
|
||
/* serverdate plugin | ||
** | ||
** This plugin syncs a local clock to the servers using the response header | ||
** on the BOSH connection | ||
** | ||
*/ | ||
|
||
var ServerDate = function(){ | ||
if( arguments.length === 0 ){ | ||
return new Date( new Date().valueOf() + ServerDate.skew ); | ||
} | ||
else if ( arguments.length === 1 ){ | ||
// Covers case where a string is passed in | ||
return new Date( arguments[0] ); | ||
} | ||
else { | ||
return new Date( Date.UTC.apply( null, arguments ) + ((new Date()).getTimezoneOffset() * 60000) ); | ||
} | ||
}; | ||
ServerDate.parse = Date.parse; | ||
ServerDate.UTC = Date.UTC; | ||
ServerDate.now = function(){ return (new ServerDate()).valueOf(); }; | ||
ServerDate.skew = 0; | ||
|
||
Strophe.addConnectionPlugin('serverdate', { | ||
init: function(connection){ | ||
Strophe.Request.prototype._newXHR = function () { | ||
var xhr = null; | ||
if (window.XMLHttpRequest) { | ||
xhr = new XMLHttpRequest(); | ||
if (xhr.overrideMimeType) { | ||
xhr.overrideMimeType("text/xml"); | ||
} | ||
} else if (window.ActiveXObject) { | ||
xhr = new ActiveXObject("Microsoft.XMLHTTP"); | ||
} | ||
|
||
var handler = this.func.prependArg(this); | ||
|
||
xhr.onreadystatechange = function(){ | ||
if(this.readyState == 2){ | ||
var header = this.getResponseHeader('Date'); | ||
var server_date = new Date(header); | ||
if ( header && server_date != 'Invalid Date' ){ | ||
system_date = new Date(); | ||
skew_ms = server_date - system_date; | ||
ServerDate.skew = skew_ms; | ||
} | ||
} | ||
handler(); | ||
}; | ||
|
||
return xhr; | ||
}; | ||
} | ||
}); |