-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathapi.js
More file actions
231 lines (197 loc) · 6.71 KB
/
api.js
File metadata and controls
231 lines (197 loc) · 6.71 KB
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
const config = require('./config');
const form = require('form-urlencoded');
const Promise = require('es6-promise').Promise;
const sendRequest = (method, url, data, progress, token) => {
let xhr;
const requestPromise = new Promise((resolve) => {
const isFormData = global.FormData && (data instanceof FormData);
xhr = new XMLHttpRequest();
if (xhr.upload) {
xhr.upload.addEventListener('progress', progress);
}
xhr.open(method, url, true);
if (!isFormData) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
if (token) {
xhr.setRequestHeader('Authorization', `OAuth ${token}`);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
resolve({responseText: xhr.responseText, request: xhr});
}
};
xhr.send(data);
});
requestPromise.request = xhr;
return requestPromise;
};
/**
* Parses the public API's response and constructs error messages
* @param {String} responseText The API's raw response
* @param {XMLHttpRequest} xhr The original XMLHttpRequest
* @return {Object({json, error})} An object containing the response and a possible error
*/
const parseResponse = ({responseText, request}) => {
let error, json;
try {
json = JSON.parse(responseText);
} catch (e) {
}
if (!json) {
if (request) {
error = { message: `HTTP Error: ${request.status}` };
} else {
error = { message: 'Unknown error' };
}
} else if (json.errors) {
error = { message: '' };
if (json.errors[0] && json.errors[0].error_message) {
error = { message: json.errors[0].error_message };
}
}
if (error) {
error.status = request.status;
}
return { json, error };
};
/**
* Executes the public API request
* @param {String} method The HTTP method (GET, POST, PUT, DELETE)
* @param {String} url The resource's url
* @param {Object} data Data to send along with the request
* @param {Function=} progress upload progress handler
* @return {Promise}
*/
const sendAndFollow = (method, url, data, progress, token) => {
const requestPromise = sendRequest(method, url, data, progress, token);
const followPromise = requestPromise.then(({responseText, request}) => {
const response = parseResponse({responseText, request});
if (response.json && response.json.status === '302 - Found') {
return sendAndFollow('GET', response.json.location, null, token);
} else {
if (request.status !== 200 && response.error) {
throw response.error;
} else {
return response.json;
}
}
});
followPromise.request = requestPromise.request;
return followPromise;
};
const addParams = (params, additionalParams, isFormData) => {
Object.keys(additionalParams).forEach((key) => {
if (isFormData) {
params.append(key, additionalParams[key]);
} else {
params[key] = additionalParams[key];
}
});
};
module.exports = {
/**
* Executes the public API request
* @param {String} method HTTP method
* @param {String} path The resource's path
* @param {(Object|FormData)} params Parameters that will be sent
* @param {Function=} progress optional upload progress handler
* @return {Promise}
*/
request (method, path, params = {}, progress = () => {}) {
const oauthToken = config.get('oauth_token');
const clientId = config.get('client_id');
const additionalParams = {};
const isFormData = global.FormData && (params instanceof FormData);
let data, url;
additionalParams.format = 'json';
// in case not token has been issued yet, set the client_id
if (!oauthToken) {
additionalParams.client_id = clientId;
}
// add the additional params to the received params
addParams(params, additionalParams, isFormData);
// in case of POST, PUT, DELETE -> prepare data
if (method !== 'GET') {
data = isFormData ? params : form.encode(params);
params = { oauth_token: oauthToken };
}
// prepend `/` if not present
path = path[0] !== '/' ? `/${path}` : path;
// construct request url
url = `${config.get('baseURL')}${path}?${form.encode(params)}`;
return sendAndFollow(method, url, data, progress, oauthToken);
},
/**
* Fetches oEmbed information for the provided URL.
* Also embeds the response into an element if provided in options
* @param {String} trackUrl
* @param {Object} options
* @return {Promise}
*/
oEmbed (trackUrl, options = {}) {
// save element
const element = options.element;
delete options.element;
options.url = trackUrl;
// construct URL
const url = `https://soundcloud.com/oembed.json?${form.encode(options)}`;
// send the request and embed response into element if provided
return sendAndFollow('GET', url, null).then((oEmbed) => {
if (element && oEmbed.html) {
element.innerHTML = oEmbed.html;
}
return oEmbed;
});
},
/**
* Uploads a track to SoundCloud
* @param {Object} options The track's properties
* @param {String} title The track's title
* @param {Blob} file The track's data
* @param {Blob=} artwork_data The track's artwork
* @param {Function=} progress Progress callback
* @return {Promise}
*/
upload (options = {}) {
const file = options.asset_data || options.file;
const canMakeRequest = config.get('oauth_token') && options.title && file;
if (!canMakeRequest) {
return new Promise((resolve, reject) => {
reject({
status: 0,
error_message: 'oauth_token needs to be present and title and asset_data / file passed as parameters'
});
});
}
const properties = Object.keys(options);
const formData = new FormData();
// add all data to formdata
properties.forEach((property) => {
let value = options[property];
// `file` is used as short hand for `asset_data`
if (property === 'file') {
property = 'asset_data';
value = options['file'];
}
formData.append(`track[${property}]`, value);
});
return this.request('POST', '/tracks', formData, options.progress);
},
/**
* Resolves a SoundCloud url to a JSON representation of its entity
* @param {String} url The URL that should get resolved
* @return {Promise}
*/
resolve (url) {
return this.request('GET', '/resolve', {
url: url,
/*
* Tell the API not to serve a redirect. This is to get around
* CORS issues on Safari 7+, which likes to send pre-flight requests
* before following redirects, which has problems.
*/
_status_code_map: { 302: 200 }
});
}
};