-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
carto-provider.js
407 lines (351 loc) · 11.6 KB
/
carto-provider.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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// Copyright (c) 2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import {OAuthApp} from '@carto/toolkit';
import Console from 'global/console';
import CartoIcon from './carto-icon';
import {Provider} from '@kepler.gl/cloud-providers';
import {createDataContainer} from '@kepler.gl/table';
import {formatCsv} from 'reducers';
const NAME = 'carto';
const DISPLAY_NAME = 'CARTO';
const NAMESPACE = 'keplergl';
const DOMAIN = 'carto.com';
const PRIVATE_STORAGE_ENABLED = true;
const SHARING_ENABLED = true;
export default class CartoProvider extends Provider {
constructor(clientId) {
super({name: NAME, displayName: DISPLAY_NAME, icon: CartoIcon});
this.clientId = clientId;
this.thumbnail = {width: 300, height: 200};
this.currentMap = null;
this._folderLink = `https://{user}.${DOMAIN}/dashboard/maps/external`;
// Initialize CARTO API
this._carto = new OAuthApp(
{
authorization: `https://${DOMAIN}/oauth2`,
scopes: 'schemas:c datasets:rw:*'
},
{
serverUrlTemplate: `https://{user}.${DOMAIN}/`,
namespace: NAMESPACE
}
);
this._carto.setClientID(clientId);
}
/**
* The CARTO toolkit library takes care of the login process.
*/
login(onCloudLoginSuccess) {
try {
this._carto.login().then(() => {
onCloudLoginSuccess && onCloudLoginSuccess(this.name);
});
} catch (error) {
this._manageErrors(error);
}
}
logout(onCloudLogoutSuccess) {
try {
this._carto.oauth.clear();
this._carto.oauth._carto.sync();
onCloudLogoutSuccess();
} catch (error) {
this._manageErrors(error);
}
}
isEnabled() {
return this.clientId !== null;
}
hasPrivateStorage() {
return PRIVATE_STORAGE_ENABLED;
}
hasSharingUrl() {
return SHARING_ENABLED;
}
async uploadMap({mapData = {}, options = {}}) {
try {
const {isPublic = true, overwrite = true} = options;
const {map: {config, datasets, info} = {}, thumbnail} = mapData;
const cartoDatasets = datasets.map(this._convertDataset);
const cs = await this._carto.getCustomStorage();
const {title, description} = info;
const name = title;
const thumbnailBase64 =
mapData && thumbnail ? await this._blobToBase64(mapData.thumbnail) : null;
let result;
if (overwrite) {
result = await cs.updateVisualization(
{
id: this.currentMap.id,
name,
description,
thumbnail: thumbnailBase64,
config: JSON.stringify(config),
isprivate: this.currentMap.isprivate
},
cartoDatasets
);
} else {
// TODO: Ask for changing current shared map generation because of being too oriented to file based clouds
// Check public name generation and replace
const regex = /(?:^keplergl_)([a-z0-9]+)(?:.json$)/;
const capturedName = name.match(regex);
const visName = capturedName ? `sharedmap_${capturedName[1]}` : name;
result = await cs.createVisualization(
{
name: visName,
description,
thumbnail: thumbnailBase64,
config: JSON.stringify(config),
isprivate: !isPublic
},
cartoDatasets,
true
);
}
if (result) {
this.currentMap = result;
}
return {
shareUrl: this._getMapPermalinkFromParams(
{
mapId: result.id,
owner: this._carto.username,
privateMap: !isPublic
},
true
),
folderLink: this._folderLink.replace('{user}', this._carto.username)
};
} catch (error) {
this._manageErrors(error);
}
}
/**
* Returns the access token. If it has expired returns null. The toolkit library loads it
* from localStorage automatically
*/
getAccessToken() {
let accessToken = null;
try {
accessToken = this._carto.oauth.expired ? null : this._carto.oauth.token;
} catch (error) {
this._manageErrors(error, false);
}
return accessToken;
}
getUserName() {
let username = null;
try {
username = this._carto.oauth.expired ? null : this._carto.username;
} catch (error) {
this._manageErrors(error, false);
}
return username;
}
/**
* The CARTO cloud provider polls the created window internally to parse the URL
* @param {*} location
*/
getAccessTokenFromLocation(location) {
return;
}
async downloadMap(queryParams) {
try {
const {owner: username, mapId, privateMap} = queryParams;
if (!username || !mapId) {
return;
}
let visualization;
if (privateMap.trim().toLowerCase() === 'true') {
await this._carto.login();
const currentUsername = this.getUserName();
if (currentUsername && currentUsername === username) {
const cs = await this._carto.getCustomStorage();
visualization = await cs.getVisualization(mapId);
}
} else {
visualization = await this._carto.PublicStorageReader.getVisualization(username, mapId);
}
if (!visualization) {
throw new Error(`Can't find map with ID: ${mapId}`);
}
// These are the options required for the action. For now, all datasets that come from CARTO are CSV
const datasets = visualization.datasets.map(dataset => {
const datasetId = dataset.name;
return {
info: {
id: datasetId,
label: datasetId,
description: dataset.description,
dataUrl: '',
configUrl: '',
panelDisabled: true
},
data: dataset.file
};
});
// const datasets = visualization.datasets.map(dataset => dataset.file);
this.currentMap = visualization.vis;
return {
map: {
datasets,
config: visualization.vis.config,
info: {title: visualization.vis.name, description: visualization.vis.description}
},
format: 'csv'
};
} catch (error) {
this._manageErrors(error);
}
}
async listMaps() {
// TODO: Implement pagination using {type='all', pageOffset=0, pageSize=-1}
try {
await this._carto.login();
const username = this.getUserName();
const cs = await this._carto.getCustomStorage();
const visualizations = await cs.getVisualizations();
let formattedVis = [];
// Format visualization object
for (const vis of visualizations) {
formattedVis.push({
id: vis.id,
title: vis.name,
description: vis.description,
privateMap: vis.isprivate,
thumbnail: vis.thumbnail === 'undefined' ? null : vis.thumbnail,
lastModification: new Date(Date.parse(vis.lastmodified)),
loadParams: {
owner: username,
mapId: vis.id,
privateMap: vis.isprivate.toString()
}
});
}
formattedVis = formattedVis.sort((a, b) => b.lastModification - a.lastModification);
return formattedVis;
} catch (error) {
this._manageErrors(error);
}
}
getShareUrl(fullUrl = false) {
return this.getMapUrl(fullUrl);
}
getMapUrl(fullUrl = true, mapParams = null) {
if (mapParams) {
return this._getMapPermalinkFromParams(mapParams, fullUrl);
} else if (this.currentMap) {
return this._getMapPermalinkFromParams(
{
mapId: this.currentMap.id,
owner: this.getUserName(),
privateMap: this.currentMap.isPrivate
},
fullUrl
);
}
}
getManagementUrl() {
return this._folderLink.replace('{user}', this._carto.username);
}
getCurrentVisualization() {
return this.currentMap
? {title: this.currentMap.name, description: this.currentMap.description}
: null;
}
// PRIVATE
_getMapPermalinkFromParams({mapId, owner, privateMap}, fullURL = true) {
const mapLink = this._composeURL({mapId, owner, privateMap});
return fullURL
? `${window.location.protocol}//${window.location.host}/${mapLink}`
: `/${mapLink}`;
}
_convertDataset({data: dataset}) {
const {allData, fields, id} = dataset;
const columns = fields.map(field => ({
name: field.name,
type: field.type
}));
const dataContainer = createDataContainer([...allData]);
const file = formatCsv(dataContainer, fields);
return {
name: id,
columns,
file
};
}
// eslint-disable-next-line complexity
_manageErrors(error, throwException = true) {
let message;
if (error && error.message) {
message = error.message;
switch (error.message) {
case 'No client ID has been specified':
Console.error('No ClientID set for CARTO provider');
break;
case 'Cannot set the client ID more than once':
Console.error('CARTO provider already initialized');
break;
case (error.message.match(/relation "[a-zA-Z0-9_]+" does not exist/) || {}).input:
Console.error('CARTO custom storage is not properly initialized');
message = 'Custom storage is not properly initialized';
break;
case (
error.message.match(/Failed to copy to keplergl_[a-zA-Z0-9_]+: Too many retries/) || {}
).input:
Console.error('CARTO Rate limit exceeded');
message =
"Failed to upload. You've exceeded the number of datasets allowed with your plan. Consider upgrading your plan.";
break;
case (error.message.match(/[a-zA-Z0-9_\s:]+: DB Quota exceeded/) || {}).input:
Console.error('CARTO DB Quota exceeded');
message =
"Failed to upload. You've exceeded your account's disk storage limit. Consider upgrading your plan.";
break;
default:
Console.error(`CARTO provider: ${message}`);
}
} else {
message = 'General error in CARTO provider';
Console.error(message);
}
// Use 'CARTO' as error code in order to show provider in notifications
if (throwException) {
throw new Error(message);
}
}
_composeURL({mapId, owner, privateMap}) {
return `demo/map/carto?mapId=${mapId}&owner=${owner}&privateMap=${privateMap}`;
}
_blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
if (!reader.error) {
resolve(reader.result);
} else {
reject(reader.error);
}
};
reader.readAsDataURL(blob);
});
}
}