Skip to content

Commit

Permalink
Add oauth timestamp fixing (using twitter server offset) to streaming…
Browse files Browse the repository at this point in the history
… api client
  • Loading branch information
ttezel committed May 2, 2016
1 parent a7cf9d6 commit 3b51215
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
config*.js
test.js
test.js
.DS_Store
33 changes: 33 additions & 0 deletions lib/streaming-api-connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ var STATUS_CODES_TO_ABORT_ON = require('./settings').STATUS_CODES_TO_ABORT_ON
var StreamingAPIConnection = function (reqOpts, twitOptions) {
this.reqOpts = reqOpts
this.twitOptions = twitOptions
this._twitter_time_minus_local_time_ms = 0
EventEmitter.call(this)
}

Expand Down Expand Up @@ -64,9 +65,11 @@ StreamingAPIConnection.prototype._startPersistentConnection = function () {
self._resetConnection();
self._setupParser();
self._resetStallAbortTimeout();
self._setOauthTimestamp();
self.request = request.post(this.reqOpts);
self.emit('connect', self.request);
self.request.on('response', function (response) {
self._updateOauthTimestampOffsetFromResponse(response)
// reset our reconnection attempt flag so next attempt goes through with 0 delay
// if we get a transport-level error
self._usedFirstReconnect = false;
Expand Down Expand Up @@ -322,4 +325,34 @@ StreamingAPIConnection.prototype._handleDisconnect = function (twitterMsg) {
this.stop();
}

/**
* Call whenever an http request is about to be made to update
* our local timestamp (used for Oauth) to be Twitter's server time.
*
*/
StreamingAPIConnection.prototype._setOauthTimestamp = function () {
var self = this;
if (self.reqOpts.oauth) {
var oauth_ts = Date.now() + self._twitter_time_minus_local_time_ms;
self.reqOpts.oauth.timestamp = Math.floor(oauth_ts/1000).toString();
}
}

/**
* Call whenever an http response is received from Twitter,
* to set our local timestamp offset from Twitter's server time.
* This is used to set the Oauth timestamp for our next http request
* to Twitter (by calling _setOauthTimestamp).
*
* @param {http.IncomingResponse} resp http response received from Twitter.
*/
StreamingAPIConnection.prototype._updateOauthTimestampOffsetFromResponse = function (resp) {
if (resp && resp.headers && resp.headers.date &&
new Date(resp.headers.date).toString() !== 'Invalid Date'
) {
var twitterTimeMs = new Date(resp.headers.date).getTime()
this._twitter_time_minus_local_time_ms = twitterTimeMs - Date.now();
}
}

module.exports = StreamingAPIConnection

0 comments on commit 3b51215

Please sign in to comment.