UNPKG

nebulab-dropbox

Version:
1,533 lines (1,352 loc) 125 kB
// Generated by CoffeeScript 1.7.1 (function() { var DbxClient, DbxEnvGlobal, DbxEnvRequire, DbxXhrArrayBufferView, DbxXhrCanSendForms, DbxXhrDoesPreflight, DbxXhrIeMode, DbxXhrRequest, DbxXhrSendArrayBufferView, DbxXhrWrapBlob, Dropbox, __hasProp = {}.hasOwnProperty, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; Dropbox = (function() { function Dropbox() { throw new Error("Not implemented. Did you mean to use Dropbox.Client?"); } return Dropbox; })(); Dropbox.Util = (function() { function Util() {} return Util; })(); Dropbox.Http = (function() { function Http() {} return Http; })(); Dropbox.File = (function() { function File() {} return File; })(); if (typeof global !== 'undefined' && typeof module !== 'undefined' && 'exports' in module) { DbxEnvGlobal = global; DbxEnvRequire = module.require.bind(module); module.exports = Dropbox; } else if (typeof window !== 'undefined' && typeof navigator !== 'undefined') { DbxEnvGlobal = window; DbxEnvRequire = null; if (window.Dropbox) { (function() { var name, value, _ref, _results; _ref = window.Dropbox; _results = []; for (name in _ref) { if (!__hasProp.call(_ref, name)) continue; value = _ref[name]; _results.push(Dropbox[name] = value); } return _results; })(); } window.Dropbox = Dropbox; } else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') { DbxEnvGlobal = self; DbxEnvRequire = self.importScripts.bind(self); self.Dropbox = Dropbox; } else { throw new Error('dropbox.js loaded in an unsupported JavaScript environment.'); } Dropbox.Env = (function() { function Env() {} Env.global = DbxEnvGlobal; Env.require = DbxEnvRequire; return Env; })(); Dropbox.Util.EventSource = (function() { function EventSource(options) { this._cancelable = options && options.cancelable; this._listeners = []; } EventSource.prototype.addListener = function(listener) { if (typeof listener !== 'function') { throw new TypeError('Invalid listener type; expected function'); } if (__indexOf.call(this._listeners, listener) < 0) { this._listeners.push(listener); } return this; }; EventSource.prototype.removeListener = function(listener) { var i, index, subscriber, _i, _len, _ref; if (this._listeners.indexOf) { index = this._listeners.indexOf(listener); if (index !== -1) { this._listeners.splice(index, 1); } } else { _ref = this._listeners; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { subscriber = _ref[i]; if (subscriber === listener) { this._listeners.splice(i, 1); break; } } } return this; }; EventSource.prototype.dispatch = function(event) { var listener, returnValue, _i, _len, _ref; _ref = this._listeners; for (_i = 0, _len = _ref.length; _i < _len; _i++) { listener = _ref[_i]; returnValue = listener(event); if (this._cancelable && (returnValue === false)) { return false; } } return true; }; return EventSource; })(); Dropbox.AccountInfo = (function() { AccountInfo.parse = function(accountInfo) { if (accountInfo && typeof accountInfo === 'object') { return new Dropbox.AccountInfo(accountInfo); } else { return accountInfo; } }; AccountInfo.prototype.name = null; AccountInfo.prototype.email = null; AccountInfo.prototype.countryCode = null; AccountInfo.prototype.uid = null; AccountInfo.prototype.referralUrl = null; AccountInfo.prototype.publicAppUrl = null; AccountInfo.prototype.quota = null; AccountInfo.prototype.usedQuota = null; AccountInfo.prototype.privateBytes = null; AccountInfo.prototype.sharedBytes = null; AccountInfo.prototype.json = function() { return this._json; }; function AccountInfo(accountInfo) { var lastIndex; this._json = accountInfo; this.name = accountInfo.display_name; this.email = accountInfo.email; this.countryCode = accountInfo.country || null; this.uid = accountInfo.uid.toString(); if (accountInfo.public_app_url) { this.publicAppUrl = accountInfo.public_app_url; lastIndex = this.publicAppUrl.length - 1; if (lastIndex >= 0 && this.publicAppUrl.substring(lastIndex) === '/') { this.publicAppUrl = this.publicAppUrl.substring(0, lastIndex); } } else { this.publicAppUrl = null; } this.referralUrl = accountInfo.referral_link; this.quota = accountInfo.quota_info.quota; this.privateBytes = accountInfo.quota_info.normal || 0; this.sharedBytes = accountInfo.quota_info.shared || 0; this.usedQuota = this.privateBytes + this.sharedBytes; } return AccountInfo; })(); Dropbox.ApiError = (function() { ApiError.prototype.status = null; ApiError.prototype.method = null; ApiError.prototype.url = null; ApiError.prototype.responseText = null; ApiError.prototype.response = null; ApiError.NETWORK_ERROR = 0; ApiError.NO_CONTENT = 304; ApiError.INVALID_PARAM = 400; ApiError.INVALID_TOKEN = 401; ApiError.OAUTH_ERROR = 403; ApiError.NOT_FOUND = 404; ApiError.INVALID_METHOD = 405; ApiError.NOT_ACCEPTABLE = 406; ApiError.CONFLICT = 409; ApiError.RATE_LIMITED = 429; ApiError.SERVER_ERROR = 503; ApiError.OVER_QUOTA = 507; function ApiError(xhr, method, url) { var text, xhrError; this.method = method; this.url = url; this.status = xhr.status; if (xhr.responseType) { try { text = xhr.response || xhr.responseText; } catch (_error) { xhrError = _error; try { text = xhr.responseText; } catch (_error) { xhrError = _error; text = null; } } } else { try { text = xhr.responseText; } catch (_error) { xhrError = _error; text = null; } } if (text) { try { this.responseText = text.toString(); this.response = JSON.parse(text); } catch (_error) { xhrError = _error; this.response = null; } } else { this.responseText = '(no response)'; this.response = null; } } ApiError.prototype.toString = function() { return "Dropbox API error " + this.status + " from " + this.method + " " + this.url + " :: " + this.responseText; }; ApiError.prototype.inspect = function() { return this.toString(); }; return ApiError; })(); Dropbox.AuthDriver = (function() { function AuthDriver() {} AuthDriver.prototype.authType = function() { return "code"; }; AuthDriver.prototype.url = function() { return "https://some.url"; }; AuthDriver.prototype.doAuthorize = function(authUrl, stateParam, client, callback) { return callback({ code: 'access-code' }); }; AuthDriver.prototype.getStateParam = function(client, callback) { return callback(Dropbox.Util.Oauth.randomAuthStateParam()); }; AuthDriver.prototype.resumeAuthorize = function(stateParam, client, callback) { return callback({ code: 'access-code' }); }; AuthDriver.prototype.onAuthStepChange = function(client, callback) { return callback(); }; AuthDriver.oauthQueryParams = ['access_token', 'expires_in', 'scope', 'token_type', 'code', 'error', 'error_description', 'error_uri', 'mac_key', 'mac_algorithm'].sort(); return AuthDriver; })(); Dropbox.AuthDriver.autoConfigure = function(client) { if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.id) { if (chrome.tabs && chrome.tabs.create) { client.authDriver(new Dropbox.AuthDriver.ChromeExtension()); } else { client.authDriver(new Dropbox.AuthDriver.ChromeApp()); } return; } if (typeof window !== 'undefined') { if (window.cordova) { client.authDriver(new Dropbox.AuthDriver.Cordova()); return; } if (window && window.navigator) { client.authDriver(new Dropbox.AuthDriver.Redirect()); } } }; Dropbox.AuthDriver.BrowserBase = (function() { function BrowserBase(options) { if (options) { this.rememberUser = 'rememberUser' in options ? options.rememberUser : true; this.scope = options.scope || 'default'; } else { this.rememberUser = true; this.scope = 'default'; } this.storageKey = null; this.storage = Dropbox.AuthDriver.BrowserBase.localStorage(); this.stateRe = /^[^#]+\#(.*&)?state=([^&]+)(&|$)/; } BrowserBase.prototype.authType = function() { return 'token'; }; BrowserBase.prototype.onAuthStepChange = function(client, callback) { this.setStorageKey(client); switch (client.authStep) { case Dropbox.Client.RESET: return this.loadCredentials((function(_this) { return function(credentials) { if (!credentials) { return callback(); } client.setCredentials(credentials); if (client.authStep !== Dropbox.Client.DONE) { return callback(); } if (!_this.rememberUser) { return _this.forgetCredentials(callback); } client.setCredentials(credentials); return callback(); }; })(this)); case Dropbox.Client.DONE: if (this.rememberUser) { return this.storeCredentials(client.credentials(), callback); } return this.forgetCredentials(callback); case Dropbox.Client.SIGNED_OUT: return this.forgetCredentials(callback); case Dropbox.Client.ERROR: return this.forgetCredentials(callback); default: callback(); return this; } }; BrowserBase.prototype.setStorageKey = function(client) { this.storageKey = "dropbox-auth:" + this.scope + ":" + (client.appHash()); return this; }; BrowserBase.prototype.storeCredentials = function(credentials, callback) { var jsonString, name, storageError, value; jsonString = JSON.stringify(credentials); try { this.storage.setItem(this.storageKey, jsonString); } catch (_error) { storageError = _error; name = encodeURIComponent(this.storageKey); value = encodeURIComponent(jsonString); document.cookie = "" + name + "=" + value + "; path=/"; } callback(); return this; }; BrowserBase.prototype.loadCredentials = function(callback) { var cookieRegexp, jsonError, jsonString, match, name, nameRegexp, storageError; try { jsonString = this.storage.getItem(this.storageKey); } catch (_error) { storageError = _error; jsonString = null; } if (jsonString === null) { name = encodeURIComponent(this.storageKey); nameRegexp = name.replace(/[.*+()]/g, '\\$&'); cookieRegexp = new RegExp("(^|(;\\s*))" + name + "=([^;]*)(;|$)"); if (match = cookieRegexp.exec(document.cookie)) { jsonString = decodeURIComponent(match[3]); } } if (!jsonString) { callback(null); return this; } try { callback(JSON.parse(jsonString)); } catch (_error) { jsonError = _error; callback(null); } return this; }; BrowserBase.prototype.forgetCredentials = function(callback) { var expires, name, storageError; try { this.storage.removeItem(this.storageKey); } catch (_error) { storageError = _error; name = encodeURIComponent(this.storageKey); expires = (new Date(0)).toGMTString(); document.cookie = "" + name + "={}; expires=" + expires + "; path=/"; } callback(); return this; }; BrowserBase.prototype.locationStateParam = function(url) { var location, match; location = url || Dropbox.AuthDriver.BrowserBase.currentLocation(); match = this.stateRe.exec(location); if (match) { return decodeURIComponent(match[2]); } return null; }; BrowserBase.prototype.replaceUrlBasename = function(url, basename) { var fragments, hashIndex, queryIndex; hashIndex = url.indexOf('#'); if (hashIndex !== -1) { url = url.substring(0, hashIndex); } queryIndex = url.indexOf('?'); if (queryIndex !== -1) { url = url.substring(0, queryIndex); } fragments = url.split('/'); fragments[fragments.length - 1] = basename; return fragments.join('/'); }; BrowserBase.localStorage = function() { var deprecationError; if (typeof window !== 'undefined') { try { return window.localStorage; } catch (_error) { deprecationError = _error; return null; } } else { return null; } }; BrowserBase.currentLocation = function() { return window.location.href; }; BrowserBase.cleanupLocation = function() { var hashIndex, pageUrl; if (window.history && window.history.replaceState) { pageUrl = this.currentLocation(); hashIndex = pageUrl.indexOf('#'); window.history.replaceState({}, document.title, pageUrl.substring(0, hashIndex)); } else { window.location.hash = ''; } }; return BrowserBase; })(); Dropbox.AuthDriver.Redirect = (function(_super) { __extends(Redirect, _super); function Redirect(options) { Redirect.__super__.constructor.call(this, options); this.receiverUrl = this.baseUrl(options); } Redirect.prototype.baseUrl = function(options) { var hashIndex, url; url = Dropbox.AuthDriver.BrowserBase.currentLocation(); if (options) { if (options.redirectUrl) { return options.redirectUrl; } if (options.redirectFile) { return this.replaceUrlBasename(url, options.redirectFile); } } hashIndex = url.indexOf('#'); if (hashIndex !== -1) { url = url.substring(0, hashIndex); } return url; }; Redirect.prototype.url = function() { return this.receiverUrl; }; Redirect.prototype.doAuthorize = function(authUrl, stateParam, client) { return this.storeCredentials(client.credentials(), function() { return window.location.assign(authUrl); }); }; Redirect.prototype.resumeAuthorize = function(stateParam, client, callback) { var pageUrl; if (this.locationStateParam() === stateParam) { pageUrl = Dropbox.AuthDriver.BrowserBase.currentLocation(); Dropbox.AuthDriver.BrowserBase.cleanupLocation(); return callback(Dropbox.Util.Oauth.queryParamsFromUrl(pageUrl)); } else { return this.forgetCredentials(function() { return callback({ error: 'Authorization error' }); }); } }; return Redirect; })(Dropbox.AuthDriver.BrowserBase); Dropbox.AuthDriver.Popup = (function(_super) { __extends(Popup, _super); function Popup(options) { Popup.__super__.constructor.call(this, options); this.receiverUrl = this.baseUrl(options); } Popup.prototype.url = function() { return this.receiverUrl; }; Popup.prototype.doAuthorize = function(authUrl, stateParam, client, callback) { this.listenForMessage(stateParam, callback); return this.openWindow(authUrl); }; Popup.prototype.baseUrl = function(options) { var url; url = Dropbox.AuthDriver.BrowserBase.currentLocation(); if (options) { if (options.receiverUrl) { return options.receiverUrl; } else if (options.receiverFile) { return this.replaceUrlBasename(url, options.receiverFile); } } return url; }; Popup.prototype.openWindow = function(url) { return window.open(url, '_dropboxOauthSigninWindow', this.popupWindowSpec(980, 700)); }; Popup.prototype.popupWindowSpec = function(popupWidth, popupHeight) { var height, popupLeft, popupTop, width, x0, y0, _ref, _ref1, _ref2, _ref3; x0 = (_ref = window.screenX) != null ? _ref : window.screenLeft; y0 = (_ref1 = window.screenY) != null ? _ref1 : window.screenTop; width = (_ref2 = window.outerWidth) != null ? _ref2 : document.documentElement.clientWidth; height = (_ref3 = window.outerHeight) != null ? _ref3 : document.documentElement.clientHeight; popupLeft = Math.round(x0 + (width - popupWidth) / 2); popupTop = Math.round(y0 + (height - popupHeight) / 2.5); if (popupLeft < x0) { popupLeft = x0; } if (popupTop < y0) { popupTop = y0; } return ("width=" + popupWidth + ",height=" + popupHeight + ",") + ("left=" + popupLeft + ",top=" + popupTop) + 'dialog=yes,dependent=yes,scrollbars=yes,location=yes'; }; Popup.prototype.listenForMessage = function(stateParam, callback) { var listener; listener = (function(_this) { return function(event) { var data, jsonError, oauthInfo; if (event.data) { data = event.data; } else { data = event; } try { oauthInfo = JSON.parse(data)._dropboxjs_oauth_info; } catch (_error) { jsonError = _error; return; } if (!oauthInfo) { return; } if (_this.locationStateParam(oauthInfo) === stateParam) { stateParam = false; window.removeEventListener('message', listener); Dropbox.AuthDriver.Popup.onMessage.removeListener(listener); return callback(Dropbox.Util.Oauth.queryParamsFromUrl(data)); } }; })(this); window.addEventListener('message', listener, false); return Dropbox.AuthDriver.Popup.onMessage.addListener(listener); }; Popup.locationOrigin = function(location) { var match; match = /^(file:\/\/[^\?\#]*)(\?|\#|$)/.exec(location); if (match) { return match[1]; } match = /^([^\:]+\:\/\/[^\/\?\#]*)(\/|\?|\#|$)/.exec(location); if (match) { return match[1]; } return location; }; Popup.oauthReceiver = function() { window.addEventListener('load', function() { var frameError, ieError, message, opener, pageOrigin, pageUrl; pageUrl = window.location.href; message = JSON.stringify({ _dropboxjs_oauth_info: pageUrl }); Dropbox.AuthDriver.BrowserBase.cleanupLocation(); opener = window.opener; if (window.parent !== window.top) { opener || (opener = window.parent); } if (opener) { try { pageOrigin = window.location.origin || locationOrigin(pageUrl); opener.postMessage(message, pageOrigin); window.close(); } catch (_error) { ieError = _error; } try { opener.Dropbox.AuthDriver.Popup.onMessage.dispatch(message); return window.close(); } catch (_error) { frameError = _error; } } }); }; Popup.onMessage = new Dropbox.Util.EventSource; return Popup; })(Dropbox.AuthDriver.BrowserBase); Dropbox.AuthDriver.ChromeBase = (function(_super) { __extends(ChromeBase, _super); function ChromeBase(options) { ChromeBase.__super__.constructor.call(this, options); this.storageKey = "dropbox_js_" + this.scope + "_credentials"; } ChromeBase.prototype.onAuthStepChange = function(client, callback) { switch (client.authStep) { case Dropbox.Client.RESET: return this.loadCredentials(function(credentials) { if (credentials) { client.setCredentials(credentials); } return callback(); }); case Dropbox.Client.DONE: return this.storeCredentials(client.credentials(), callback); case Dropbox.Client.SIGNED_OUT: return this.forgetCredentials(callback); case Dropbox.Client.ERROR: return this.forgetCredentials(callback); default: return callback(); } }; ChromeBase.prototype.url = function() { return this.receiverUrl; }; ChromeBase.prototype.storeCredentials = function(credentials, callback) { var items; items = {}; items[this.storageKey] = credentials; chrome.storage.local.set(items, callback); return this; }; ChromeBase.prototype.loadCredentials = function(callback) { chrome.storage.local.get(this.storageKey, (function(_this) { return function(items) { return callback(items[_this.storageKey] || null); }; })(this)); return this; }; ChromeBase.prototype.forgetCredentials = function(callback) { chrome.storage.local.remove(this.storageKey, callback); return this; }; return ChromeBase; })(Dropbox.AuthDriver.BrowserBase); Dropbox.AuthDriver.ChromeApp = (function(_super) { __extends(ChromeApp, _super); function ChromeApp(options) { ChromeApp.__super__.constructor.call(this, options); this.receiverUrl = "https://" + chrome.runtime.id + ".chromiumapp.org/"; } ChromeApp.prototype.doAuthorize = function(authUrl, stateParam, client, callback) { return chrome.identity.launchWebAuthFlow({ url: authUrl, interactive: true }, (function(_this) { return function(redirectUrl) { if (_this.locationStateParam(redirectUrl) === stateParam) { stateParam = false; return callback(Dropbox.Util.Oauth.queryParamsFromUrl(redirectUrl)); } }; })(this)); }; return ChromeApp; })(Dropbox.AuthDriver.ChromeBase); Dropbox.AuthDriver.ChromeExtension = (function(_super) { __extends(ChromeExtension, _super); function ChromeExtension(options) { var receiverPath; ChromeExtension.__super__.constructor.call(this, options); receiverPath = (options && options.receiverPath) || 'chrome_oauth_receiver.html'; this.receiverUrl = chrome.runtime.getURL(receiverPath); } ChromeExtension.prototype.doAuthorize = function(authUrl, stateParam, client, callback) { var listener, oauthTab; oauthTab = null; listener = (function(_this) { return function(message, sender) { var receiverHref; if (sender && sender.tab) { if (sender.tab.url.substring(0, _this.receiverUrl.length) !== _this.receiverUrl) { return; } } if (!message.dropbox_oauth_receiver_href) { return; } receiverHref = message.dropbox_oauth_receiver_href; if (_this.locationStateParam(receiverHref) === stateParam) { stateParam = false; if (oauthTab) { chrome.tabs.remove(oauthTab.id); } chrome.runtime.onMessage.removeListener(listener); return callback(Dropbox.Util.Oauth.queryParamsFromUrl(receiverHref)); } }; })(this); chrome.runtime.onMessage.addListener(listener); return chrome.tabs.create({ url: authUrl, active: true, pinned: false }, function(tab) { return oauthTab = tab; }); }; ChromeExtension.oauthReceiver = function() { return window.addEventListener('load', function() { var pageUrl; pageUrl = window.location.href; window.location.hash = ''; chrome.runtime.sendMessage({ dropbox_oauth_receiver_href: pageUrl }); if (window.close) { return window.close(); } }); }; return ChromeExtension; })(Dropbox.AuthDriver.ChromeBase); Dropbox.AuthDriver.Cordova = (function(_super) { __extends(Cordova, _super); function Cordova(options) { Cordova.__super__.constructor.call(this, options); } Cordova.prototype.url = function() { return 'https://www.dropbox.com/1/oauth2/redirect_receiver'; }; Cordova.prototype.doAuthorize = function(authUrl, stateParam, client, callback) { var authHost, browser, onEvent, promptPageLoaded, removed; browser = window.open(authUrl, '_blank', 'location=yes,closebuttoncaption=Cancel'); promptPageLoaded = false; authHost = /^[^/]*\/\/[^/]*\//.exec(authUrl)[0]; removed = false; onEvent = (function(_this) { return function(event) { if (event.url && _this.locationStateParam(event.url) === stateParam) { if (removed) { return; } browser.removeEventListener('loadstart', onEvent); browser.removeEventListener('loaderror', onEvent); browser.removeEventListener('loadstop', onEvent); browser.removeEventListener('exit', onEvent); removed = true; window.setTimeout((function() { return browser.close(); }), 10); callback(Dropbox.Util.Oauth.queryParamsFromUrl(event.url)); return; } if (event.type === 'exit') { if (removed) { return; } browser.removeEventListener('loadstart', onEvent); browser.removeEventListener('loaderror', onEvent); browser.removeEventListener('loadstop', onEvent); browser.removeEventListener('exit', onEvent); removed = true; callback(new AuthError('error=access_denied&error_description=User+closed+browser+window')); } }; })(this); browser.addEventListener('loadstart', onEvent); browser.addEventListener('loaderror', onEvent); browser.addEventListener('loadstop', onEvent); return browser.addEventListener('exit', onEvent); }; return Cordova; })(Dropbox.AuthDriver.BrowserBase); Dropbox.AuthDriver.NodeServer = (function() { function NodeServer(options) { this._port = (options != null ? options.port : void 0) || 8912; if (options != null ? options.tls : void 0) { this._tlsOptions = options.tls; if (typeof this._tlsOptions === 'string' || this._tlsOptions instanceof Buffer) { this._tlsOptions = { key: this._tlsOptions, cert: this._tlsOptions }; } } else { this._tlsOptions = null; } this._fs = Dropbox.Env.require('fs'); this._http = Dropbox.Env.require('http'); this._https = Dropbox.Env.require('https'); this._open = Dropbox.Env.require('open'); this._callbacks = {}; this._nodeUrl = Dropbox.Env.require('url'); this.createApp(); } NodeServer.prototype.authType = function() { return "code"; }; NodeServer.prototype.url = function() { var protocol; protocol = this._tlsOptions === null ? 'http' : 'https'; return "" + protocol + "://localhost:" + this._port + "/oauth_callback"; }; NodeServer.prototype.doAuthorize = function(authUrl, stateParam, client, callback) { this._callbacks[stateParam] = callback; return this.openBrowser(authUrl); }; NodeServer.prototype.openBrowser = function(url) { if (!url.match(/^https?:\/\//)) { throw new Error("Not a http/https URL: " + url); } if ('BROWSER' in process.env) { return this._open(url, process.env['BROWSER']); } else { return this._open(url); } }; NodeServer.prototype.createApp = function() { if (this._tlsOptions) { this._app = this._https.createServer(this._tlsOptions, (function(_this) { return function(request, response) { return _this.doRequest(request, response); }; })(this)); } else { this._app = this._http.createServer((function(_this) { return function(request, response) { return _this.doRequest(request, response); }; })(this)); } return this._app.listen(this._port); }; NodeServer.prototype.closeServer = function() { return this._app.close(); }; NodeServer.prototype.doRequest = function(request, response) { var data, stateParam, url; url = this._nodeUrl.parse(request.url, true); if (url.pathname === '/oauth_callback') { stateParam = url.query.state; if (this._callbacks[stateParam]) { this._callbacks[stateParam](url.query); delete this._callbacks[stateParam]; } } data = ''; request.on('data', function(dataFragment) { return data += dataFragment; }); return request.on('end', (function(_this) { return function() { return _this.closeBrowser(response); }; })(this)); }; NodeServer.prototype.closeBrowser = function(response) { var closeHtml; closeHtml = "<!doctype html>\n<script type=\"text/javascript\">window.close();</script>\n<p>Please close this window.</p>"; response.writeHead(200, { 'Content-Length': closeHtml.length, 'Content-Type': 'text/html' }); response.write(closeHtml); return response.end(); }; return NodeServer; })(); Dropbox.AuthError = (function() { AuthError.prototype.code = null; AuthError.prototype.description = null; AuthError.prototype.uri = null; AuthError.ACCESS_DENIED = 'access_denied'; AuthError.INVALID_REQUEST = 'invalid_request'; AuthError.UNAUTHORIZED_CLIENT = 'unauthorized_client'; AuthError.INVALID_GRANT = 'invalid_grant'; AuthError.INVALID_SCOPE = 'invalid_scope'; AuthError.UNSUPPORTED_GRANT_TYPE = 'unsupported_grant_type'; AuthError.UNSUPPORTED_RESPONSE_TYPE = 'unsupported_response_type'; AuthError.SERVER_ERROR = 'server_error'; AuthError.TEMPORARILY_UNAVAILABLE = 'temporarily_unavailable'; function AuthError(queryString) { var root; if (!queryString.error) { throw new Error("Not an OAuth 2.0 error: " + (JSON.stringify(queryString))); } if (typeof queryString.error === 'object' && queryString.error.error) { root = queryString.error; } else { root = queryString; } this.code = root.error; this.description = root.error_description || null; this.uri = root.error_uri || null; } AuthError.prototype.toString = function() { return "Dropbox OAuth error " + this.code + " :: " + this.description; }; AuthError.prototype.inspect = function() { return this.toString(); }; return AuthError; })(); Dropbox.Client = (function() { function Client(options) { this._serverRoot = options.server || this._defaultServerRoot(); if ('maxApiServer' in options) { this._maxApiServer = options.maxApiServer; } else { this._maxApiServer = this._defaultMaxApiServer(); } this._authServer = options.authServer || this._defaultAuthServer(); this._fileServer = options.fileServer || this._defaultFileServer(); this._downloadServer = options.downloadServer || this._defaultDownloadServer(); this._notifyServer = options.notifyServer || this._defaultNotifyServer(); this.onXhr = new Dropbox.Util.EventSource({ cancelable: true }); this.onError = new Dropbox.Util.EventSource; this.onAuthStepChange = new Dropbox.Util.EventSource; this._xhrOnErrorHandler = (function(_this) { return function(error, callback) { return _this._handleXhrError(error, callback); }; })(this); this._oauth = new Dropbox.Util.Oauth(options); this._uid = options.uid || null; this.authStep = this._oauth.step(); this._driver = null; this.authError = null; this._credentials = null; this.setupUrls(); } Client.prototype.onXhr = null; Client.prototype.onError = null; Client.prototype.onAuthStepChange = null; Client.prototype.authDriver = function(driver) { this._driver = driver; return this; }; Client.prototype.dropboxUid = function() { return this._uid; }; Client.prototype.credentials = function() { if (!this._credentials) { this._computeCredentials(); } return this._credentials; }; Client.prototype.authenticate = function(options, callback) { var interactive, oldAuthStep, _fsmErrorStep, _fsmNextStep, _fsmStep; if (!callback && typeof options === 'function') { callback = options; options = null; } if (options && 'interactive' in options) { interactive = options.interactive; } else { interactive = true; } if (!(this._driver || this.authStep === DbxClient.DONE)) { Dropbox.AuthDriver.autoConfigure(this); if (!this._driver) { throw new Error('OAuth driver auto-configuration failed. Call authDriver.'); } } if (this.authStep === DbxClient.ERROR) { throw new Error('Client got in an error state. Call reset() to reuse it!'); } _fsmNextStep = (function(_this) { return function() { _this.authStep = _this._oauth.step(); if (_this.authStep === DbxClient.ERROR) { _this.authError = _this._oauth.error(); } _this._credentials = null; _this.onAuthStepChange.dispatch(_this); return _fsmStep(); }; })(this); _fsmErrorStep = (function(_this) { return function() { _this.authStep = DbxClient.ERROR; _this._credentials = null; _this.onAuthStepChange.dispatch(_this); return _fsmStep(); }; })(this); oldAuthStep = null; _fsmStep = (function(_this) { return function() { var authUrl; if (oldAuthStep !== _this.authStep) { oldAuthStep = _this.authStep; if (_this._driver && _this._driver.onAuthStepChange) { _this._driver.onAuthStepChange(_this, _fsmStep); return; } } switch (_this.authStep) { case DbxClient.RESET: if (!interactive) { if (callback) { callback(null, _this); } return; } if (_this._driver.getStateParam) { _this._driver.getStateParam(function(stateParam) { if (_this.client.authStep === DbxClient.RESET) { _this._oauth.setAuthStateParam(stateParam); } return _fsmNextStep(); }); } _this._oauth.setAuthStateParam(Dropbox.Util.Oauth.randomAuthStateParam()); return _fsmNextStep(); case DbxClient.PARAM_SET: if (!interactive) { if (callback) { callback(null, _this); } return; } authUrl = _this.authorizeUrl(); return _this._driver.doAuthorize(authUrl, _this._oauth.authStateParam(), _this, function(queryParams) { _this._oauth.processRedirectParams(queryParams); if (queryParams.uid) { _this._uid = queryParams.uid; } return _fsmNextStep(); }); case DbxClient.PARAM_LOADED: if (!_this._driver.resumeAuthorize) { _this._oauth.setAuthStateParam(_this._oauth.authStateParam()); _fsmNextStep(); return; } return _this._driver.resumeAuthorize(_this._oauth.authStateParam(), _this, function(queryParams) { _this._oauth.processRedirectParams(queryParams); if (queryParams.uid) { _this._uid = queryParams.uid; } return _fsmNextStep(); }); case DbxClient.AUTHORIZED: return _this.getAccessToken(function(error, data) { if (error) { _this.authError = error; return _fsmErrorStep(); } else { _this._oauth.processRedirectParams(data); _this._uid = data.uid; return _fsmNextStep(); } }); case DbxClient.DONE: if (callback) { callback(null, _this); } break; case DbxClient.SIGNED_OUT: _this.authStep = DbxClient.RESET; _this.reset(); return _fsmStep(); case DbxClient.ERROR: if (callback) { callback(_this.authError, _this); } } }; })(this); _fsmStep(); return this; }; Client.prototype.isAuthenticated = function() { return this.authStep === DbxClient.DONE; }; Client.prototype.signOut = function(options, callback) { var stopOnXhrError, xhr; if (!callback && typeof options === 'function') { callback = options; options = null; } stopOnXhrError = options && options.mustInvalidate; if (this.authStep !== DbxClient.DONE) { throw new Error("This client doesn't have a user's token"); } xhr = new Dropbox.Util.Xhr('POST', this._urls.signOut); xhr.signWithOauth(this._oauth); return this._dispatchXhr(xhr, (function(_this) { return function(error) { if (error) { if (error.status === Dropbox.ApiError.INVALID_TOKEN) { error = null; } else if (stopOnXhrError) { if (callback) { callback(error); } return; } } _this.authStep = DbxClient.RESET; _this.reset(); _this.authStep = DbxClient.SIGNED_OUT; _this.onAuthStepChange.dispatch(_this); if (_this._driver && _this._driver.onAuthStepChange) { return _this._driver.onAuthStepChange(_this, function() { if (callback) { return callback(null); } }); } else { if (callback) { return callback(null); } } }; })(this)); }; Client.prototype.signOff = function(options, callback) { return this.signOut(options, callback); }; Client.prototype.getAccountInfo = function(options, callback) { var httpCache, xhr; if ((!callback) && (typeof options === 'function')) { callback = options; options = null; } httpCache = false; if (options && options.httpCache) { httpCache = true; } xhr = new Dropbox.Util.Xhr('GET', this._urls.accountInfo); xhr.signWithOauth(this._oauth, httpCache); return this._dispatchXhr(xhr, function(error, accountData) { return callback(error, Dropbox.AccountInfo.parse(accountData), accountData); }); }; Client.prototype.getUserInfo = function(options, callback) { return this.getAccountInfo(options, callback); }; Client.prototype.readFile = function(path, options, callback) { var httpCache, params, rangeEnd, rangeHeader, rangeStart, responseType, xhr; if ((!callback) && (typeof options === 'function')) { callback = options; options = null; } params = {}; responseType = 'text'; rangeHeader = null; httpCache = false; if (options) { if (options.versionTag) { params.rev = options.versionTag; } else if (options.rev) { params.rev = options.rev; } if (options.arrayBuffer) { responseType = 'arraybuffer'; } else if (options.blob) { responseType = 'blob'; } else if (options.buffer) { responseType = 'buffer'; } else if (options.binary) { responseType = 'b'; } if (options.length) { if (options.start != null) { rangeStart = options.start; rangeEnd = options.start + options.length - 1; } else { rangeStart = ''; rangeEnd = options.length; } rangeHeader = "bytes=" + rangeStart + "-" + rangeEnd; } else if (options.start != null) { rangeHeader = "bytes=" + options.start + "-"; } if (options.httpCache) { httpCache = true; } } xhr = new Dropbox.Util.Xhr('GET', "" + this._urls.getFile + "/" + (this._urlEncodePath(path))); xhr.setParams(params).signWithOauth(this._oauth, httpCache); xhr.setResponseType(responseType); if (rangeHeader) { if (rangeHeader) { xhr.setHeader('Range', rangeHeader); } xhr.reportResponseHeaders(); } return this._dispatchXhr(xhr, function(error, data, metadata, headers) { var rangeInfo; if (headers) { rangeInfo = Dropbox.Http.RangeInfo.parse(headers['content-range']); } else { rangeInfo = null; } return callback(error, data, Dropbox.File.Stat.parse(metadata), rangeInfo); }); }; Client.prototype.writeFile = function(path, data, options, callback) { var useForm; if ((!callback) && (typeof options === 'function')) { callback = options; options = null; } useForm = Dropbox.Util.Xhr.canSendForms && typeof data === 'object'; if (useForm) { return this._writeFileUsingForm(path, data, options, callback); } else { return this._writeFileUsingPut(path, data, options, callback); } }; Client.prototype._writeFileUsingForm = function(path, data, options, callback) { var fileName, params, slashIndex, xhr; slashIndex = path.lastIndexOf('/'); if (slashIndex === -1) { fileName = path; path = ''; } else { fileName = path.substring(slashIndex); path = path.substring(0, slashIndex); } params = { file: fileName }; if (options) { if (options.noOverwrite) { params.overwrite = 'false'; } if (options.lastVersionTag) { params.parent_rev = options.lastVersionTag; } else if (options.parentRev || options.parent_rev) { params.parent_rev = options.parentRev || options.parent_rev; } if (options.noAutorename) { params.autorename = 'false'; } } xhr = new Dropbox.Util.Xhr('POST', "" + this._urls.postFile + "/" + (this._urlEncodePath(path))); xhr.setParams(params).signWithOauth(this._oauth).setFileField('file', fileName, data, 'application/octet-stream'); delete params.file; return this._dispatchXhr(xhr, function(error, metadata) { if (callback) { return callback(error, Dropbox.File.Stat.parse(metadata)); } }); }; Client.prototype._writeFileUsingPut = function(path, data, options, callback) { var params, xhr; params = {}; if (options) { if (options.noOverwrite) { params.overwrite = 'false'; } if (options.lastVersionTag) { params.parent_rev = options.lastVersionTag; } else if (options.parentRev || options.parent_rev) { params.parent_rev = options.parentRev || options.parent_rev; } if (options.noAutorename) { params.autorename = 'false'; } } xhr = new Dropbox.Util.Xhr('POST', "" + this._urls.putFile + "/" + (this._urlEncodePath(path))); xhr.setBody(data).setParams(params).signWithOauth(this._oauth); return this._dispatchXhr(xhr, function(error, metadata) { if (callback) { return callback(error, Dropbox.File.Stat.parse(metadata)); } }); }; Client.prototype.resumableUploadStep = function(data, cursor, callback) { var params, xhr; if (cursor) { params = { offset: cursor.offset }; if (cursor.tag) { params.upload_id = cursor.tag; } } else { params = { offset: 0 }; } xhr = new Dropbox.Util.Xhr('POST', this._urls.chunkedUpload); xhr.setBody(data).setParams(params).signWithOauth(this._oauth); return this._dispatchXhr(xhr, function(error, cursor) { if (error && error.status === Dropbox.ApiError.INVALID_PARAM && error.response && error.response.upload_id && error.response.offset) { return callback(null, Dropbox.Http.UploadCursor.parse(error.response)); } else { return callback(error, Dropbox.Http.UploadCursor.parse(cursor)); } }); }; Client.prototype.resumableUploadFinish = function(path, cursor, options, callback) { var params, xhr; if ((!callback) && (typeof options === 'function')) { callback = options; options = null; } params = { upload_id: cursor.tag }; if (options) { if (options.lastVersionTag) { params.parent_rev = options.lastVersionTag; } else if (options.parentRev || options.parent_rev) { params.parent_rev = options.parentRev || options.parent_rev; } if (options.noOverwrite) { params.overwrite = 'false'; } } xhr = new Dropbox.Util.Xhr('POST', "" + this._urls.commitChunkedUpload + "/" + (this._urlEncodePath(path))); xhr.setParams(params).signWithOauth(this._oauth); return this._dispatchXhr(xhr, function(error, metadata) { if (callback) { return callback(error, Dropbox.File.Stat.parse(metadata)); } }); }; Client.prototype.stat = function(path, options, callback) { var httpCache, params, xhr; if ((!callback) && (typeof options === 'function')) { callback = options; options = null; } params = {}; httpCache = false; if (options) { if (options.versionTag) { params.rev = options.versionTag; } else if (options.rev) { params.rev = options.rev; } if (options.contentHash) { params.hash = options.contentHash; } else if (options.hash) { params.hash = options.hash; } if (options.removed || options.deleted) { params.include_deleted = 'true'; } if (options.readDir) { params.list = 'true'; if (options.readDir !== true) { params.file_limit = options.readDir.toString(); } } if (options.cacheHash) { params.hash = options.cacheHash; } if (options.httpCache) { httpCache = true; } } params.include_deleted || (params.include_deleted = 'false'); params.list || (params.lis