-
Notifications
You must be signed in to change notification settings - Fork 351
/
dropbox.js
182 lines (161 loc) · 5.71 KB
/
dropbox.js
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
import {
UPLOAD,
DOWNLOAD,
RPC,
APP_AUTH,
TEAM_AUTH,
USER_AUTH,
NO_AUTH,
} from './constants.js';
import { routes } from '../lib/routes.js';
import DropboxAuth from './auth.js';
import { getBaseURL, httpHeaderSafeJson } from './utils.js';
import { parseDownloadResponse, parseResponse } from './response.js';
let fetch;
if (typeof window !== 'undefined') {
fetch = window.fetch.bind(window);
} else {
fetch = require('node-fetch'); // eslint-disable-line global-require
}
const b64 = typeof btoa === 'undefined'
? (str) => 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.
*/
export default class Dropbox {
constructor(options) {
options = options || {};
if (options.auth) {
this.auth = options.auth;
} else {
this.auth = new DropboxAuth(options);
}
this.fetch = options.fetch || fetch;
this.selectUser = options.selectUser;
this.selectAdmin = options.selectAdmin;
this.pathRoot = options.pathRoot;
Object.assign(this, routes);
}
request(path, args, auth, host, style) {
switch (style) {
case RPC:
return this.rpcRequest(path, args, auth, host);
case DOWNLOAD:
return this.downloadRequest(path, args, auth, host);
case UPLOAD:
return this.uploadRequest(path, args, auth, host);
default:
throw new Error(`Invalid request style: ${style}`);
}
}
rpcRequest(path, body, auth, host) {
return this.auth.checkAndRefreshAccessToken()
.then(() => {
const fetchOptions = {
method: 'POST',
body: (body) ? JSON.stringify(body) : null,
headers: {},
};
if (body) {
fetchOptions.headers['Content-Type'] = 'application/json';
}
let authHeader;
switch (auth) {
case APP_AUTH:
if (!this.auth.clientId || !this.auth.clientSecret) {
throw new Error('A client id and secret is required for this function');
}
authHeader = b64(`${this.auth.clientId}:${this.auth.clientSecret}`);
fetchOptions.headers.Authorization = `Basic ${authHeader}`;
break;
case TEAM_AUTH:
case USER_AUTH:
fetchOptions.headers.Authorization = `Bearer ${this.auth.getAccessToken()}`;
break;
case NO_AUTH:
break;
default:
throw new Error(`Unhandled auth type: ${auth}`);
}
this.setCommonHeaders(fetchOptions);
return fetchOptions;
})
.then((fetchOptions) => this.fetch(getBaseURL(host) + path, fetchOptions))
.then((res) => parseResponse(res));
}
downloadRequest(path, args, auth, host) {
return this.auth.checkAndRefreshAccessToken()
.then(() => {
if (auth !== USER_AUTH) {
throw new Error(`Unexpected auth type: ${auth}`);
}
const fetchOptions = {
method: 'POST',
headers: {
Authorization: `Bearer ${this.auth.getAccessToken()}`,
'Dropbox-API-Arg': httpHeaderSafeJson(args),
},
};
this.setCommonHeaders(fetchOptions);
return fetchOptions;
})
.then((fetchOptions) => fetch(getBaseURL(host) + path, fetchOptions))
.then((res) => parseDownloadResponse(res));
}
uploadRequest(path, args, auth, host) {
return this.auth.checkAndRefreshAccessToken()
.then(() => {
if (auth !== USER_AUTH) {
throw new Error(`Unexpected auth type: ${auth}`);
}
const { contents } = args;
delete args.contents;
const fetchOptions = {
body: contents,
method: 'POST',
headers: {
Authorization: `Bearer ${this.auth.getAccessToken()}`,
'Content-Type': 'application/octet-stream',
'Dropbox-API-Arg': httpHeaderSafeJson(args),
},
};
this.setCommonHeaders(fetchOptions);
return fetchOptions;
})
.then((fetchOptions) => this.fetch(getBaseURL(host) + path, fetchOptions))
.then((res) => parseResponse(res));
}
setCommonHeaders(options) {
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;
}
}
}