Permalink
Browse files

[api] added `delta` and `stream`

  • Loading branch information...
1 parent a1dda26 commit d3409d8cd146ddd50c9a3dce0b89ede651d99460 @fent fent committed Mar 28, 2012
Showing with 75 additions and 1 deletion.
  1. +75 −1 lib/dropbox-node.js
View
@@ -2,6 +2,7 @@ var pathLib = require('path')
, querystring = require('querystring')
, escapePath = require('./util/escape-path')
, stringifyParams = require('./util/stringify-params')
+ , EventEmitter = require('events').EventEmitter
, OAuth = require('oauth').OAuth
, API_URI = 'https://api.dropbox.com/1'
, CONTENT_API_URI = 'https://api-content.dropbox.com/1';
@@ -267,7 +268,7 @@ DropboxClient.prototype.move = function(from_path, to_path, optargs, cb) {
// Searches a folder
// See https://www.dropbox.com/developers/reference/api#search
DropboxClient.prototype.search = function(path, query, optargs, cb) {
- if (typeof optargs == 'function') cb = optargs, optargs = {};
+ if (typeof optargs === 'function') cb = optargs, optargs = {};
this.oauth.get(API_URI + '/search/dropbox/' + path + '?' +
querystring.stringify({query: query})
, optargs.token || this.access_token
@@ -277,3 +278,76 @@ DropboxClient.prototype.search = function(path, query, optargs, cb) {
cb(null, JSON.parse(data));
});
}
+
+
+// Keep up with changes.
+// See https://www.dropbox.com/developers/reference/api#delta
+DropboxClient.prototype.delta = function(cursor, optargs, cb) {
+ var cursorType = typeof cursor;
+ if (cursorType === 'function') cb = cursor, optargs = {};
+ else if (typeof optargs === 'function') {
+ cb = optargs;
+ if (cursorType === 'object') {
+ optargs = cursor;
+ cursor = null;
+ } else {
+ optargs = {}
+ }
+ }
+
+ this.oauth.post(API_URI + '/delta' +
+ (cursor ?
+ '?' + querystring.stringify({cursor: cursor}) : '')
+ , optargs.token || this.access_token
+ , optargs.secret || this.access_token_secret
+ , ''
+ , function(err, data, res) {
+ if (err) return cb(err);
+ cb(null, JSON.parse(data));
+ });
+}
+
+
+// Continously stream changes through DropboxClient#delta
+DropboxClient.prototype.stream = function(cursor, optargs) {
+ optargs = optargs || {};
+ var ee = new EventEmitter();
+ var iid;
+ var self = this;
+
+ function getDelta() {
+ self.delta(cursor, optargs, function(err, data) {
+ if (err) { return ee.emit('error', err); }
+
+ // only emit changes if cursor was given
+ if (cursor) {
+ if (data.reset) {
+ ee.emit('reset');
+ }
+
+ for (var i = 0, len = data.entries.length; i < len; i++) {
+ var e = data.entries[i];
+ ee.emit('data', { path: e[0], metadata: e[1] });
+ }
+ }
+
+ cursor = data.cursor;
+ if (data.has_more) {
+ ee.resume();
+ }
+ });
+ }
+
+ ee.resume = function() {
+ getDelta();
+ clearInterval(iid);
+ iid = setInterval(getDelta, 300000); // 5 minutes
+ };
+ ee.resume();
+
+ ee.pause = function() {
+ clearInterval(iid);
+ };
+
+ return ee;
+}

0 comments on commit d3409d8

Please sign in to comment.