|
var http = require('http'); |
|
var querystring = require('querystring'); |
|
|
|
function FriendFeedRealtime (args) { |
|
args || (args = {}); |
|
var that = this; |
|
('username remote_key request on_entry on_error').split(' ') |
|
.forEach(function (key) { |
|
(key in args) && (that[key] = args[key]); |
|
}); |
|
this.request || (this.request = '/feed/home'); |
|
this.on_error || (this.on_error = function (err) { |
|
console.error(err); process.exit(1); |
|
}); |
|
this.on_entry || (this.on_entry = function (res) { |
|
console.log("%s: %s", res.from.name, res.body); |
|
}); |
|
|
|
this.long_poll({updates: 1}); |
|
} |
|
|
|
(function (fp) { |
|
fp.api = function (opt) { |
|
var _api = { |
|
port: 80 |
|
, host: 'friendfeed-api.com' |
|
, path: [ ('/v2/updates' + this.request) |
|
, querystring.stringify(opt) ].join('?') |
|
}; |
|
|
|
this.username && this.remote_key && |
|
(_api.auth = [ this.username, this.remote_key ].join(':')); |
|
|
|
// if (this['set-cookies']) { |
|
// _api.headers['cookie'] = this['set-cookies']; |
|
// } |
|
|
|
return _api; |
|
}; |
|
fp.long_poll = function (opt) { |
|
var that = this; |
|
var _data = ''; |
|
var req = http.get(this.api(opt), function (res) { |
|
req = null; |
|
/^2/.test(res.statusCode) || |
|
that.on_error({message: "response status: "+ res.statusCode}); |
|
|
|
// if (res.headers['set-cookie']) { |
|
// that['set-cookie'] = res.headers['set-cookie']; |
|
// } |
|
|
|
res.setEncoding('utf8'); |
|
res.on('data', function (chunk) { _data += chunk }); |
|
res.on('end', function () { |
|
var data; |
|
try { |
|
data = JSON.parse(_data); |
|
} catch (e) { that.on_error(e) } |
|
|
|
data.errorCode && that.on_error(data.errorCode); |
|
|
|
data.entries.forEach(function (entry) { |
|
that.on_entry(entry); |
|
}); |
|
|
|
data.realtime && that.long_poll({cursor: data.realtime.cursor}); |
|
}); |
|
}); |
|
req.on('error', this.on_error); |
|
req.end(); |
|
}; |
|
})(FriendFeedRealtime.prototype); |
|
|
|
module.exports = FriendFeedRealtime; |
|
module.exports.version = '0.0.0-alpha'; |