File size: 8,872 Bytes
fdcb5fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = undefined;

var _constants = require("./constants.js");

var _routes = require("../lib/routes.js");

var _auth = require("./auth.js");

var _utils = require("./utils.js");

var _response = require("./response.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var b64 = typeof btoa === 'undefined' ? function (str) {
  return Buffer.from(str).toString('base64');
} : btoa;
/**
 * @class Dropbox
 * @classdesc The Dropbox SDK class that provides methods to read, write and
 * create files or folders in a user or team's Dropbox.
 * @arg {Object} options
 * @arg {Function} [options.fetch] - fetch library for making requests.
 * @arg {String} [options.selectUser] - Select user is only used for team functionality.
 * It specifies which user the team access token should be acting as.
 * @arg {String} [options.pathRoot] - root path to access other namespaces
 * Use to access team folders for example
 * @arg {String} [options.selectAdmin] - Select admin is only used by team functionality.
 * It specifies which team admin the team access token should be acting as.
 * @arg {DropboxAuth} [options.auth] - The DropboxAuth object used to authenticate requests.
 * If this is set, the remaining parameters will be ignored.
 * @arg {String} [options.accessToken] - An access token for making authenticated
 * requests.
 * @arg {Date} [options.accessTokenExpiresAt] - Date of the current access token's
 * expiration (if available)
 * @arg {String} [options.refreshToken] - A refresh token for retrieving access tokens
 * @arg {String} [options.clientId] - The client id for your app. Used to create
 * authentication URL.
 * @arg {String} [options.clientSecret] - The client secret for your app. Used to create
 * authentication URL and refresh access tokens.
 * @arg {String} [options.domain] - A custom domain to use when making api requests. This
 * should only be used for testing as scaffolding to avoid making network requests.
 * @arg {String} [options.domainDelimiter] - A custom delimiter to use when separating domain from
 * subdomain. This should only be used for testing as scaffolding.
 * @arg {Object} [options.customHeaders] - An object (in the form of header: value) designed to set
 * custom headers to use during a request.
 */

var Dropbox = /*#__PURE__*/function () {
  function Dropbox(options) {
    _classCallCheck(this, Dropbox);

    options = options || {};

    if (options.auth) {
      this.auth = options.auth;
    } else {
      this.auth = new _auth["default"](options);
    }

    this.fetch = options.fetch || this.auth.fetch;
    this.selectUser = options.selectUser;
    this.selectAdmin = options.selectAdmin;
    this.pathRoot = options.pathRoot;
    this.domain = options.domain || this.auth.domain;
    this.domainDelimiter = options.domainDelimiter || this.auth.domainDelimiter;
    this.customHeaders = options.customHeaders || this.auth.customHeaders;
    Object.assign(this, _routes.routes);
  }

  _createClass(Dropbox, [{
    key: "request",
    value: function request(path, args, auth, host, style) {
      // scope is provided after "style", but unused in requests, so it's not in parameters
      switch (style) {
        case _constants.RPC:
          return this.rpcRequest(path, args, auth, host);

        case _constants.DOWNLOAD:
          return this.downloadRequest(path, args, auth, host);

        case _constants.UPLOAD:
          return this.uploadRequest(path, args, auth, host);

        default:
          throw new Error("Invalid request style: ".concat(style));
      }
    }
  }, {
    key: "rpcRequest",
    value: function rpcRequest(path, body, auth, host) {
      var _this = this;

      return this.auth.checkAndRefreshAccessToken().then(function () {
        var fetchOptions = {
          method: 'POST',
          body: body ? JSON.stringify(body) : null,
          headers: {}
        };

        if (body) {
          fetchOptions.headers['Content-Type'] = 'application/json';
        }

        _this.setAuthHeaders(auth, fetchOptions);

        _this.setCommonHeaders(fetchOptions);

        return fetchOptions;
      }).then(function (fetchOptions) {
        return _this.fetch((0, _utils.baseApiUrl)(host, _this.domain, _this.domainDelimiter) + path, fetchOptions);
      }).then(function (res) {
        return (0, _response.parseResponse)(res);
      });
    }
  }, {
    key: "downloadRequest",
    value: function downloadRequest(path, args, auth, host) {
      var _this2 = this;

      return this.auth.checkAndRefreshAccessToken().then(function () {
        var fetchOptions = {
          method: 'POST',
          headers: {
            'Dropbox-API-Arg': (0, _utils.httpHeaderSafeJson)(args)
          }
        };

        _this2.setAuthHeaders(auth, fetchOptions);

        _this2.setCommonHeaders(fetchOptions);

        return fetchOptions;
      }).then(function (fetchOptions) {
        return _this2.fetch((0, _utils.baseApiUrl)(host, _this2.domain, _this2.domainDelimiter) + path, fetchOptions);
      }).then(function (res) {
        return (0, _response.parseDownloadResponse)(res);
      });
    }
  }, {
    key: "uploadRequest",
    value: function uploadRequest(path, args, auth, host) {
      var _this3 = this;

      return this.auth.checkAndRefreshAccessToken().then(function () {
        var contents = args.contents;
        delete args.contents;
        var fetchOptions = {
          body: contents,
          method: 'POST',
          headers: {
            'Content-Type': 'application/octet-stream',
            'Dropbox-API-Arg': (0, _utils.httpHeaderSafeJson)(args)
          }
        };

        _this3.setAuthHeaders(auth, fetchOptions);

        _this3.setCommonHeaders(fetchOptions);

        return fetchOptions;
      }).then(function (fetchOptions) {
        return _this3.fetch((0, _utils.baseApiUrl)(host, _this3.domain, _this3.domainDelimiter) + path, fetchOptions);
      }).then(function (res) {
        return (0, _response.parseResponse)(res);
      });
    }
  }, {
    key: "setAuthHeaders",
    value: function setAuthHeaders(auth, fetchOptions) {
      // checks for multiauth and assigns auth based on priority to create header in switch case
      if (auth.split(',').length > 1) {
        var authTypes = auth.replace(' ', '').split(',');

        if (authTypes.includes(_constants.USER_AUTH) && this.auth.getAccessToken()) {
          auth = _constants.USER_AUTH;
        } else if (authTypes.includes(_constants.TEAM_AUTH) && this.auth.getAccessToken()) {
          auth = _constants.TEAM_AUTH;
        } else if (authTypes.includes(_constants.APP_AUTH)) {
          auth = _constants.APP_AUTH;
        }
      }

      switch (auth) {
        case _constants.APP_AUTH:
          if (this.auth.clientId && this.auth.clientSecret) {
            var authHeader = b64("".concat(this.auth.clientId, ":").concat(this.auth.clientSecret));
            fetchOptions.headers.Authorization = "Basic ".concat(authHeader);
          }

          break;

        case _constants.TEAM_AUTH:
        case _constants.USER_AUTH:
          if (this.auth.getAccessToken()) {
            fetchOptions.headers.Authorization = "Bearer ".concat(this.auth.getAccessToken());
          }

          break;

        case _constants.NO_AUTH:
        case _constants.COOKIE:
          break;

        default:
          throw new Error("Unhandled auth type: ".concat(auth));
      }
    }
  }, {
    key: "setCommonHeaders",
    value: function setCommonHeaders(options) {
      var _this4 = this;

      if (this.selectUser) {
        options.headers['Dropbox-API-Select-User'] = this.selectUser;
      }

      if (this.selectAdmin) {
        options.headers['Dropbox-API-Select-Admin'] = this.selectAdmin;
      }

      if (this.pathRoot) {
        options.headers['Dropbox-API-Path-Root'] = this.pathRoot;
      }

      if (this.customHeaders) {
        var headerKeys = Object.keys(this.customHeaders);
        headerKeys.forEach(function (header) {
          options.headers[header] = _this4.customHeaders[header];
        });
      }
    }
  }]);

  return Dropbox;
}();

exports["default"] = Dropbox;