UNPKG

57.5 kBJavaScriptView Raw
1function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
2
3function _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); } }
4
5function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
6
7function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
8
9function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
10
11function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
12
13function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
14
15function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
16
17function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
18
19function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
20
21var Translator = require('@uppy/utils/lib/Translator');
22
23var ee = require('namespace-emitter');
24
25var cuid = require('cuid');
26
27var throttle = require('lodash.throttle');
28
29var prettierBytes = require('@transloadit/prettier-bytes');
30
31var match = require('mime-match');
32
33var DefaultStore = require('@uppy/store-default');
34
35var getFileType = require('@uppy/utils/lib/getFileType');
36
37var getFileNameAndExtension = require('@uppy/utils/lib/getFileNameAndExtension');
38
39var generateFileID = require('@uppy/utils/lib/generateFileID');
40
41var supportsUploadProgress = require('./supportsUploadProgress');
42
43var _require = require('./loggers'),
44 justErrorsLogger = _require.justErrorsLogger,
45 debugLogger = _require.debugLogger;
46
47var Plugin = require('./Plugin'); // Exported from here.
48
49
50var RestrictionError = /*#__PURE__*/function (_Error) {
51 _inheritsLoose(RestrictionError, _Error);
52
53 function RestrictionError() {
54 var _this;
55
56 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
57 args[_key] = arguments[_key];
58 }
59
60 _this = _Error.call.apply(_Error, [this].concat(args)) || this;
61 _this.isRestriction = true;
62 return _this;
63 }
64
65 return RestrictionError;
66}( /*#__PURE__*/_wrapNativeSuper(Error));
67/**
68 * Uppy Core module.
69 * Manages plugins, state updates, acts as an event bus,
70 * adds/removes files and metadata.
71 */
72
73
74var Uppy = /*#__PURE__*/function () {
75 /**
76 * Instantiate Uppy
77 *
78 * @param {object} opts — Uppy options
79 */
80 function Uppy(opts) {
81 var _this2 = this;
82
83 this.defaultLocale = {
84 strings: {
85 addBulkFilesFailed: {
86 0: 'Failed to add %{smart_count} file due to an internal error',
87 1: 'Failed to add %{smart_count} files due to internal errors'
88 },
89 youCanOnlyUploadX: {
90 0: 'You can only upload %{smart_count} file',
91 1: 'You can only upload %{smart_count} files'
92 },
93 youHaveToAtLeastSelectX: {
94 0: 'You have to select at least %{smart_count} file',
95 1: 'You have to select at least %{smart_count} files'
96 },
97 // The default `exceedsSize2` string only combines the `exceedsSize` string (%{backwardsCompat}) with the size.
98 // Locales can override `exceedsSize2` to specify a different word order. This is for backwards compat with
99 // Uppy 1.9.x and below which did a naive concatenation of `exceedsSize2 + size` instead of using a locale-specific
100 // substitution.
101 // TODO: In 2.0 `exceedsSize2` should be removed in and `exceedsSize` updated to use substitution.
102 exceedsSize2: '%{backwardsCompat} %{size}',
103 exceedsSize: 'This file exceeds maximum allowed size of',
104 inferiorSize: 'This file is smaller than the allowed size of %{size}',
105 youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
106 noNewAlreadyUploading: 'Cannot add new files: already uploading',
107 noDuplicates: 'Cannot add the duplicate file \'%{fileName}\', it already exists',
108 companionError: 'Connection with Companion failed',
109 companionUnauthorizeHint: 'To unauthorize to your %{provider} account, please go to %{url}',
110 failedToUpload: 'Failed to upload %{file}',
111 noInternetConnection: 'No Internet connection',
112 connectedToInternet: 'Connected to the Internet',
113 // Strings for remote providers
114 noFilesFound: 'You have no files or folders here',
115 selectX: {
116 0: 'Select %{smart_count}',
117 1: 'Select %{smart_count}'
118 },
119 selectAllFilesFromFolderNamed: 'Select all files from folder %{name}',
120 unselectAllFilesFromFolderNamed: 'Unselect all files from folder %{name}',
121 selectFileNamed: 'Select file %{name}',
122 unselectFileNamed: 'Unselect file %{name}',
123 openFolderNamed: 'Open folder %{name}',
124 cancel: 'Cancel',
125 logOut: 'Log out',
126 filter: 'Filter',
127 resetFilter: 'Reset filter',
128 loading: 'Loading...',
129 authenticateWithTitle: 'Please authenticate with %{pluginName} to select files',
130 authenticateWith: 'Connect to %{pluginName}',
131 searchImages: 'Search for images',
132 enterTextToSearch: 'Enter text to search for images',
133 backToSearch: 'Back to Search',
134 emptyFolderAdded: 'No files were added from empty folder',
135 folderAdded: {
136 0: 'Added %{smart_count} file from %{folder}',
137 1: 'Added %{smart_count} files from %{folder}'
138 }
139 }
140 };
141 var defaultOptions = {
142 id: 'uppy',
143 autoProceed: false,
144 allowMultipleUploads: true,
145 debug: false,
146 restrictions: {
147 maxFileSize: null,
148 minFileSize: null,
149 maxTotalFileSize: null,
150 maxNumberOfFiles: null,
151 minNumberOfFiles: null,
152 allowedFileTypes: null
153 },
154 meta: {},
155 onBeforeFileAdded: function onBeforeFileAdded(currentFile, files) {
156 return currentFile;
157 },
158 onBeforeUpload: function onBeforeUpload(files) {
159 return files;
160 },
161 store: DefaultStore(),
162 logger: justErrorsLogger,
163 infoTimeout: 5000
164 }; // Merge default options with the ones set by user,
165 // making sure to merge restrictions too
166
167 this.opts = _extends({}, defaultOptions, opts, {
168 restrictions: _extends({}, defaultOptions.restrictions, opts && opts.restrictions)
169 }); // Support debug: true for backwards-compatability, unless logger is set in opts
170 // opts instead of this.opts to avoid comparing objects — we set logger: justErrorsLogger in defaultOptions
171
172 if (opts && opts.logger && opts.debug) {
173 this.log('You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.', 'warning');
174 } else if (opts && opts.debug) {
175 this.opts.logger = debugLogger;
176 }
177
178 this.log("Using Core v" + this.constructor.VERSION);
179
180 if (this.opts.restrictions.allowedFileTypes && this.opts.restrictions.allowedFileTypes !== null && !Array.isArray(this.opts.restrictions.allowedFileTypes)) {
181 throw new TypeError('`restrictions.allowedFileTypes` must be an array');
182 }
183
184 this.i18nInit(); // Container for different types of plugins
185
186 this.plugins = {};
187 this.getState = this.getState.bind(this);
188 this.getPlugin = this.getPlugin.bind(this);
189 this.setFileMeta = this.setFileMeta.bind(this);
190 this.setFileState = this.setFileState.bind(this);
191 this.log = this.log.bind(this);
192 this.info = this.info.bind(this);
193 this.hideInfo = this.hideInfo.bind(this);
194 this.addFile = this.addFile.bind(this);
195 this.removeFile = this.removeFile.bind(this);
196 this.pauseResume = this.pauseResume.bind(this);
197 this.validateRestrictions = this.validateRestrictions.bind(this); // ___Why throttle at 500ms?
198 // - We must throttle at >250ms for superfocus in Dashboard to work well (because animation takes 0.25s, and we want to wait for all animations to be over before refocusing).
199 // [Practical Check]: if thottle is at 100ms, then if you are uploading a file, and click 'ADD MORE FILES', - focus won't activate in Firefox.
200 // - We must throttle at around >500ms to avoid performance lags.
201 // [Practical Check] Firefox, try to upload a big file for a prolonged period of time. Laptop will start to heat up.
202
203 this._calculateProgress = throttle(this._calculateProgress.bind(this), 500, {
204 leading: true,
205 trailing: true
206 });
207 this.updateOnlineStatus = this.updateOnlineStatus.bind(this);
208 this.resetProgress = this.resetProgress.bind(this);
209 this.pauseAll = this.pauseAll.bind(this);
210 this.resumeAll = this.resumeAll.bind(this);
211 this.retryAll = this.retryAll.bind(this);
212 this.cancelAll = this.cancelAll.bind(this);
213 this.retryUpload = this.retryUpload.bind(this);
214 this.upload = this.upload.bind(this);
215 this.emitter = ee();
216 this.on = this.on.bind(this);
217 this.off = this.off.bind(this);
218 this.once = this.emitter.once.bind(this.emitter);
219 this.emit = this.emitter.emit.bind(this.emitter);
220 this.preProcessors = [];
221 this.uploaders = [];
222 this.postProcessors = [];
223 this.store = this.opts.store;
224 this.setState({
225 plugins: {},
226 files: {},
227 currentUploads: {},
228 allowNewUpload: true,
229 capabilities: {
230 uploadProgress: supportsUploadProgress(),
231 individualCancellation: true,
232 resumableUploads: false
233 },
234 totalProgress: 0,
235 meta: _extends({}, this.opts.meta),
236 info: {
237 isHidden: true,
238 type: 'info',
239 message: ''
240 }
241 });
242 this._storeUnsubscribe = this.store.subscribe(function (prevState, nextState, patch) {
243 _this2.emit('state-update', prevState, nextState, patch);
244
245 _this2.updateAll(nextState);
246 }); // Exposing uppy object on window for debugging and testing
247
248 if (this.opts.debug && typeof window !== 'undefined') {
249 window[this.opts.id] = this;
250 }
251
252 this._addListeners(); // Re-enable if we’ll need some capabilities on boot, like isMobileDevice
253 // this._setCapabilities()
254
255 } // _setCapabilities = () => {
256 // const capabilities = {
257 // isMobileDevice: isMobileDevice()
258 // }
259 // this.setState({
260 // ...this.getState().capabilities,
261 // capabilities
262 // })
263 // }
264
265
266 var _proto = Uppy.prototype;
267
268 _proto.on = function on(event, callback) {
269 this.emitter.on(event, callback);
270 return this;
271 };
272
273 _proto.off = function off(event, callback) {
274 this.emitter.off(event, callback);
275 return this;
276 }
277 /**
278 * Iterate on all plugins and run `update` on them.
279 * Called each time state changes.
280 *
281 */
282 ;
283
284 _proto.updateAll = function updateAll(state) {
285 this.iteratePlugins(function (plugin) {
286 plugin.update(state);
287 });
288 }
289 /**
290 * Updates state with a patch
291 *
292 * @param {object} patch {foo: 'bar'}
293 */
294 ;
295
296 _proto.setState = function setState(patch) {
297 this.store.setState(patch);
298 }
299 /**
300 * Returns current state.
301 *
302 * @returns {object}
303 */
304 ;
305
306 _proto.getState = function getState() {
307 return this.store.getState();
308 }
309 /**
310 * Back compat for when uppy.state is used instead of uppy.getState().
311 */
312 ;
313
314 /**
315 * Shorthand to set state for a specific file.
316 */
317 _proto.setFileState = function setFileState(fileID, state) {
318 var _extends2;
319
320 if (!this.getState().files[fileID]) {
321 throw new Error("Can\u2019t set state for " + fileID + " (the file could have been removed)");
322 }
323
324 this.setState({
325 files: _extends({}, this.getState().files, (_extends2 = {}, _extends2[fileID] = _extends({}, this.getState().files[fileID], state), _extends2))
326 });
327 };
328
329 _proto.i18nInit = function i18nInit() {
330 this.translator = new Translator([this.defaultLocale, this.opts.locale]);
331 this.locale = this.translator.locale;
332 this.i18n = this.translator.translate.bind(this.translator);
333 this.i18nArray = this.translator.translateArray.bind(this.translator);
334 };
335
336 _proto.setOptions = function setOptions(newOpts) {
337 this.opts = _extends({}, this.opts, newOpts, {
338 restrictions: _extends({}, this.opts.restrictions, newOpts && newOpts.restrictions)
339 });
340
341 if (newOpts.meta) {
342 this.setMeta(newOpts.meta);
343 }
344
345 this.i18nInit();
346
347 if (newOpts.locale) {
348 this.iteratePlugins(function (plugin) {
349 plugin.setOptions();
350 });
351 }
352
353 this.setState(); // so that UI re-renders with new options
354 };
355
356 _proto.resetProgress = function resetProgress() {
357 var defaultProgress = {
358 percentage: 0,
359 bytesUploaded: 0,
360 uploadComplete: false,
361 uploadStarted: null
362 };
363
364 var files = _extends({}, this.getState().files);
365
366 var updatedFiles = {};
367 Object.keys(files).forEach(function (fileID) {
368 var updatedFile = _extends({}, files[fileID]);
369
370 updatedFile.progress = _extends({}, updatedFile.progress, defaultProgress);
371 updatedFiles[fileID] = updatedFile;
372 });
373 this.setState({
374 files: updatedFiles,
375 totalProgress: 0
376 });
377 this.emit('reset-progress');
378 };
379
380 _proto.addPreProcessor = function addPreProcessor(fn) {
381 this.preProcessors.push(fn);
382 };
383
384 _proto.removePreProcessor = function removePreProcessor(fn) {
385 var i = this.preProcessors.indexOf(fn);
386
387 if (i !== -1) {
388 this.preProcessors.splice(i, 1);
389 }
390 };
391
392 _proto.addPostProcessor = function addPostProcessor(fn) {
393 this.postProcessors.push(fn);
394 };
395
396 _proto.removePostProcessor = function removePostProcessor(fn) {
397 var i = this.postProcessors.indexOf(fn);
398
399 if (i !== -1) {
400 this.postProcessors.splice(i, 1);
401 }
402 };
403
404 _proto.addUploader = function addUploader(fn) {
405 this.uploaders.push(fn);
406 };
407
408 _proto.removeUploader = function removeUploader(fn) {
409 var i = this.uploaders.indexOf(fn);
410
411 if (i !== -1) {
412 this.uploaders.splice(i, 1);
413 }
414 };
415
416 _proto.setMeta = function setMeta(data) {
417 var updatedMeta = _extends({}, this.getState().meta, data);
418
419 var updatedFiles = _extends({}, this.getState().files);
420
421 Object.keys(updatedFiles).forEach(function (fileID) {
422 updatedFiles[fileID] = _extends({}, updatedFiles[fileID], {
423 meta: _extends({}, updatedFiles[fileID].meta, data)
424 });
425 });
426 this.log('Adding metadata:');
427 this.log(data);
428 this.setState({
429 meta: updatedMeta,
430 files: updatedFiles
431 });
432 };
433
434 _proto.setFileMeta = function setFileMeta(fileID, data) {
435 var updatedFiles = _extends({}, this.getState().files);
436
437 if (!updatedFiles[fileID]) {
438 this.log('Was trying to set metadata for a file that has been removed: ', fileID);
439 return;
440 }
441
442 var newMeta = _extends({}, updatedFiles[fileID].meta, data);
443
444 updatedFiles[fileID] = _extends({}, updatedFiles[fileID], {
445 meta: newMeta
446 });
447 this.setState({
448 files: updatedFiles
449 });
450 }
451 /**
452 * Get a file object.
453 *
454 * @param {string} fileID The ID of the file object to return.
455 */
456 ;
457
458 _proto.getFile = function getFile(fileID) {
459 return this.getState().files[fileID];
460 }
461 /**
462 * Get all files in an array.
463 */
464 ;
465
466 _proto.getFiles = function getFiles() {
467 var _this$getState = this.getState(),
468 files = _this$getState.files;
469
470 return Object.keys(files).map(function (fileID) {
471 return files[fileID];
472 });
473 }
474 /**
475 * A public wrapper for _checkRestrictions — checks if a file passes a set of restrictions.
476 * For use in UI pluigins (like Providers), to disallow selecting files that won’t pass restrictions.
477 *
478 * @param {object} file object to check
479 * @param {Array} [files] array to check maxNumberOfFiles and maxTotalFileSize
480 * @returns {object} { result: true/false, reason: why file didn’t pass restrictions }
481 */
482 ;
483
484 _proto.validateRestrictions = function validateRestrictions(file, files) {
485 try {
486 this._checkRestrictions(file, files);
487
488 return {
489 result: true
490 };
491 } catch (err) {
492 return {
493 result: false,
494 reason: err.message
495 };
496 }
497 }
498 /**
499 * Check if file passes a set of restrictions set in options: maxFileSize, minFileSize,
500 * maxNumberOfFiles and allowedFileTypes.
501 *
502 * @param {object} file object to check
503 * @param {Array} [files] array to check maxNumberOfFiles and maxTotalFileSize
504 * @private
505 */
506 ;
507
508 _proto._checkRestrictions = function _checkRestrictions(file, files) {
509 if (files === void 0) {
510 files = this.getFiles();
511 }
512
513 var _this$opts$restrictio = this.opts.restrictions,
514 maxFileSize = _this$opts$restrictio.maxFileSize,
515 minFileSize = _this$opts$restrictio.minFileSize,
516 maxTotalFileSize = _this$opts$restrictio.maxTotalFileSize,
517 maxNumberOfFiles = _this$opts$restrictio.maxNumberOfFiles,
518 allowedFileTypes = _this$opts$restrictio.allowedFileTypes;
519
520 if (maxNumberOfFiles) {
521 if (files.length + 1 > maxNumberOfFiles) {
522 throw new RestrictionError("" + this.i18n('youCanOnlyUploadX', {
523 smart_count: maxNumberOfFiles
524 }));
525 }
526 }
527
528 if (allowedFileTypes) {
529 var isCorrectFileType = allowedFileTypes.some(function (type) {
530 // check if this is a mime-type
531 if (type.indexOf('/') > -1) {
532 if (!file.type) return false;
533 return match(file.type.replace(/;.*?$/, ''), type);
534 } // otherwise this is likely an extension
535
536
537 if (type[0] === '.' && file.extension) {
538 return file.extension.toLowerCase() === type.substr(1).toLowerCase();
539 }
540
541 return false;
542 });
543
544 if (!isCorrectFileType) {
545 var allowedFileTypesString = allowedFileTypes.join(', ');
546 throw new RestrictionError(this.i18n('youCanOnlyUploadFileTypes', {
547 types: allowedFileTypesString
548 }));
549 }
550 } // We can't check maxTotalFileSize if the size is unknown.
551
552
553 if (maxTotalFileSize && file.size != null) {
554 var totalFilesSize = 0;
555 totalFilesSize += file.size;
556 files.forEach(function (file) {
557 totalFilesSize += file.size;
558 });
559
560 if (totalFilesSize > maxTotalFileSize) {
561 throw new RestrictionError(this.i18n('exceedsSize2', {
562 backwardsCompat: this.i18n('exceedsSize'),
563 size: prettierBytes(maxTotalFileSize)
564 }));
565 }
566 } // We can't check maxFileSize if the size is unknown.
567
568
569 if (maxFileSize && file.size != null) {
570 if (file.size > maxFileSize) {
571 throw new RestrictionError(this.i18n('exceedsSize2', {
572 backwardsCompat: this.i18n('exceedsSize'),
573 size: prettierBytes(maxFileSize)
574 }));
575 }
576 } // We can't check minFileSize if the size is unknown.
577
578
579 if (minFileSize && file.size != null) {
580 if (file.size < minFileSize) {
581 throw new RestrictionError(this.i18n('inferiorSize', {
582 size: prettierBytes(minFileSize)
583 }));
584 }
585 }
586 }
587 /**
588 * Check if minNumberOfFiles restriction is reached before uploading.
589 *
590 * @private
591 */
592 ;
593
594 _proto._checkMinNumberOfFiles = function _checkMinNumberOfFiles(files) {
595 var minNumberOfFiles = this.opts.restrictions.minNumberOfFiles;
596
597 if (Object.keys(files).length < minNumberOfFiles) {
598 throw new RestrictionError("" + this.i18n('youHaveToAtLeastSelectX', {
599 smart_count: minNumberOfFiles
600 }));
601 }
602 }
603 /**
604 * Logs an error, sets Informer message, then throws the error.
605 * Emits a 'restriction-failed' event if it’s a restriction error
606 *
607 * @param {object | string} err — Error object or plain string message
608 * @param {object} [options]
609 * @param {boolean} [options.showInformer=true] — Sometimes developer might want to show Informer manually
610 * @param {object} [options.file=null] — File object used to emit the restriction error
611 * @param {boolean} [options.throwErr=true] — Errors shouldn’t be thrown, for example, in `upload-error` event
612 * @private
613 */
614 ;
615
616 _proto._showOrLogErrorAndThrow = function _showOrLogErrorAndThrow(err, _temp) {
617 var _ref = _temp === void 0 ? {} : _temp,
618 _ref$showInformer = _ref.showInformer,
619 showInformer = _ref$showInformer === void 0 ? true : _ref$showInformer,
620 _ref$file = _ref.file,
621 file = _ref$file === void 0 ? null : _ref$file,
622 _ref$throwErr = _ref.throwErr,
623 throwErr = _ref$throwErr === void 0 ? true : _ref$throwErr;
624
625 var message = typeof err === 'object' ? err.message : err;
626 var details = typeof err === 'object' && err.details ? err.details : ''; // Restriction errors should be logged, but not as errors,
627 // as they are expected and shown in the UI.
628
629 var logMessageWithDetails = message;
630
631 if (details) {
632 logMessageWithDetails += ' ' + details;
633 }
634
635 if (err.isRestriction) {
636 this.log(logMessageWithDetails);
637 this.emit('restriction-failed', file, err);
638 } else {
639 this.log(logMessageWithDetails, 'error');
640 } // Sometimes informer has to be shown manually by the developer,
641 // for example, in `onBeforeFileAdded`.
642
643
644 if (showInformer) {
645 this.info({
646 message: message,
647 details: details
648 }, 'error', this.opts.infoTimeout);
649 }
650
651 if (throwErr) {
652 throw typeof err === 'object' ? err : new Error(err);
653 }
654 };
655
656 _proto._assertNewUploadAllowed = function _assertNewUploadAllowed(file) {
657 var _this$getState2 = this.getState(),
658 allowNewUpload = _this$getState2.allowNewUpload;
659
660 if (allowNewUpload === false) {
661 this._showOrLogErrorAndThrow(new RestrictionError(this.i18n('noNewAlreadyUploading')), {
662 file: file
663 });
664 }
665 }
666 /**
667 * Create a file state object based on user-provided `addFile()` options.
668 *
669 * Note this is extremely side-effectful and should only be done when a file state object will be added to state immediately afterward!
670 *
671 * The `files` value is passed in because it may be updated by the caller without updating the store.
672 */
673 ;
674
675 _proto._checkAndCreateFileStateObject = function _checkAndCreateFileStateObject(files, file) {
676 var fileType = getFileType(file);
677 file.type = fileType;
678 var onBeforeFileAddedResult = this.opts.onBeforeFileAdded(file, files);
679
680 if (onBeforeFileAddedResult === false) {
681 // Don’t show UI info for this error, as it should be done by the developer
682 this._showOrLogErrorAndThrow(new RestrictionError('Cannot add the file because onBeforeFileAdded returned false.'), {
683 showInformer: false,
684 file: file
685 });
686 }
687
688 if (typeof onBeforeFileAddedResult === 'object' && onBeforeFileAddedResult) {
689 file = onBeforeFileAddedResult;
690 }
691
692 var fileName;
693
694 if (file.name) {
695 fileName = file.name;
696 } else if (fileType.split('/')[0] === 'image') {
697 fileName = fileType.split('/')[0] + '.' + fileType.split('/')[1];
698 } else {
699 fileName = 'noname';
700 }
701
702 var fileExtension = getFileNameAndExtension(fileName).extension;
703 var isRemote = file.isRemote || false;
704 var fileID = generateFileID(file);
705
706 if (files[fileID]) {
707 this._showOrLogErrorAndThrow(new RestrictionError(this.i18n('noDuplicates', {
708 fileName: fileName
709 })), {
710 file: file
711 });
712 }
713
714 var meta = file.meta || {};
715 meta.name = fileName;
716 meta.type = fileType; // `null` means the size is unknown.
717
718 var size = isFinite(file.data.size) ? file.data.size : null;
719 var newFile = {
720 source: file.source || '',
721 id: fileID,
722 name: fileName,
723 extension: fileExtension || '',
724 meta: _extends({}, this.getState().meta, meta),
725 type: fileType,
726 data: file.data,
727 progress: {
728 percentage: 0,
729 bytesUploaded: 0,
730 bytesTotal: size,
731 uploadComplete: false,
732 uploadStarted: null
733 },
734 size: size,
735 isRemote: isRemote,
736 remote: file.remote || '',
737 preview: file.preview
738 };
739
740 try {
741 this._checkRestrictions(newFile);
742 } catch (err) {
743 this._showOrLogErrorAndThrow(err, {
744 file: newFile
745 });
746 }
747
748 return newFile;
749 } // Schedule an upload if `autoProceed` is enabled.
750 ;
751
752 _proto._startIfAutoProceed = function _startIfAutoProceed() {
753 var _this3 = this;
754
755 if (this.opts.autoProceed && !this.scheduledAutoProceed) {
756 this.scheduledAutoProceed = setTimeout(function () {
757 _this3.scheduledAutoProceed = null;
758
759 _this3.upload().catch(function (err) {
760 if (!err.isRestriction) {
761 _this3.log(err.stack || err.message || err);
762 }
763 });
764 }, 4);
765 }
766 }
767 /**
768 * Add a new file to `state.files`. This will run `onBeforeFileAdded`,
769 * try to guess file type in a clever way, check file against restrictions,
770 * and start an upload if `autoProceed === true`.
771 *
772 * @param {object} file object to add
773 * @returns {string} id for the added file
774 */
775 ;
776
777 _proto.addFile = function addFile(file) {
778 var _extends3;
779
780 this._assertNewUploadAllowed(file);
781
782 var _this$getState3 = this.getState(),
783 files = _this$getState3.files;
784
785 var newFile = this._checkAndCreateFileStateObject(files, file);
786
787 this.setState({
788 files: _extends({}, files, (_extends3 = {}, _extends3[newFile.id] = newFile, _extends3))
789 });
790 this.emit('file-added', newFile);
791 this.log("Added file: " + newFile.name + ", " + newFile.id + ", mime type: " + newFile.type);
792
793 this._startIfAutoProceed();
794
795 return newFile.id;
796 }
797 /**
798 * Add multiple files to `state.files`. See the `addFile()` documentation.
799 *
800 * This cuts some corners for performance, so should typically only be used in cases where there may be a lot of files.
801 *
802 * If an error occurs while adding a file, it is logged and the user is notified. This is good for UI plugins, but not for programmatic use. Programmatic users should usually still use `addFile()` on individual files.
803 */
804 ;
805
806 _proto.addFiles = function addFiles(fileDescriptors) {
807 var _this4 = this;
808
809 this._assertNewUploadAllowed(); // create a copy of the files object only once
810
811
812 var files = _extends({}, this.getState().files);
813
814 var newFiles = [];
815 var errors = [];
816
817 for (var i = 0; i < fileDescriptors.length; i++) {
818 try {
819 var newFile = this._checkAndCreateFileStateObject(files, fileDescriptors[i]);
820
821 newFiles.push(newFile);
822 files[newFile.id] = newFile;
823 } catch (err) {
824 if (!err.isRestriction) {
825 errors.push(err);
826 }
827 }
828 }
829
830 this.setState({
831 files: files
832 });
833 newFiles.forEach(function (newFile) {
834 _this4.emit('file-added', newFile);
835 });
836
837 if (newFiles.length > 5) {
838 this.log("Added batch of " + newFiles.length + " files");
839 } else {
840 Object.keys(newFiles).forEach(function (fileID) {
841 _this4.log("Added file: " + newFiles[fileID].name + "\n id: " + newFiles[fileID].id + "\n type: " + newFiles[fileID].type);
842 });
843 }
844
845 if (newFiles.length > 0) {
846 this._startIfAutoProceed();
847 }
848
849 if (errors.length > 0) {
850 var message = 'Multiple errors occurred while adding files:\n';
851 errors.forEach(function (subError) {
852 message += "\n * " + subError.message;
853 });
854 this.info({
855 message: this.i18n('addBulkFilesFailed', {
856 smart_count: errors.length
857 }),
858 details: message
859 }, 'error', this.opts.infoTimeout);
860 var err = new Error(message);
861 err.errors = errors;
862 throw err;
863 }
864 };
865
866 _proto.removeFiles = function removeFiles(fileIDs, reason) {
867 var _this5 = this;
868
869 var _this$getState4 = this.getState(),
870 files = _this$getState4.files,
871 currentUploads = _this$getState4.currentUploads;
872
873 var updatedFiles = _extends({}, files);
874
875 var updatedUploads = _extends({}, currentUploads);
876
877 var removedFiles = Object.create(null);
878 fileIDs.forEach(function (fileID) {
879 if (files[fileID]) {
880 removedFiles[fileID] = files[fileID];
881 delete updatedFiles[fileID];
882 }
883 }); // Remove files from the `fileIDs` list in each upload.
884
885 function fileIsNotRemoved(uploadFileID) {
886 return removedFiles[uploadFileID] === undefined;
887 }
888
889 var uploadsToRemove = [];
890 Object.keys(updatedUploads).forEach(function (uploadID) {
891 var newFileIDs = currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved); // Remove the upload if no files are associated with it anymore.
892
893 if (newFileIDs.length === 0) {
894 uploadsToRemove.push(uploadID);
895 return;
896 }
897
898 updatedUploads[uploadID] = _extends({}, currentUploads[uploadID], {
899 fileIDs: newFileIDs
900 });
901 });
902 uploadsToRemove.forEach(function (uploadID) {
903 delete updatedUploads[uploadID];
904 });
905 var stateUpdate = {
906 currentUploads: updatedUploads,
907 files: updatedFiles
908 }; // If all files were removed - allow new uploads!
909
910 if (Object.keys(updatedFiles).length === 0) {
911 stateUpdate.allowNewUpload = true;
912 stateUpdate.error = null;
913 }
914
915 this.setState(stateUpdate);
916
917 this._calculateTotalProgress();
918
919 var removedFileIDs = Object.keys(removedFiles);
920 removedFileIDs.forEach(function (fileID) {
921 _this5.emit('file-removed', removedFiles[fileID], reason);
922 });
923
924 if (removedFileIDs.length > 5) {
925 this.log("Removed " + removedFileIDs.length + " files");
926 } else {
927 this.log("Removed files: " + removedFileIDs.join(', '));
928 }
929 };
930
931 _proto.removeFile = function removeFile(fileID, reason) {
932 if (reason === void 0) {
933 reason = null;
934 }
935
936 this.removeFiles([fileID], reason);
937 };
938
939 _proto.pauseResume = function pauseResume(fileID) {
940 if (!this.getState().capabilities.resumableUploads || this.getFile(fileID).uploadComplete) {
941 return;
942 }
943
944 var wasPaused = this.getFile(fileID).isPaused || false;
945 var isPaused = !wasPaused;
946 this.setFileState(fileID, {
947 isPaused: isPaused
948 });
949 this.emit('upload-pause', fileID, isPaused);
950 return isPaused;
951 };
952
953 _proto.pauseAll = function pauseAll() {
954 var updatedFiles = _extends({}, this.getState().files);
955
956 var inProgressUpdatedFiles = Object.keys(updatedFiles).filter(function (file) {
957 return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted;
958 });
959 inProgressUpdatedFiles.forEach(function (file) {
960 var updatedFile = _extends({}, updatedFiles[file], {
961 isPaused: true
962 });
963
964 updatedFiles[file] = updatedFile;
965 });
966 this.setState({
967 files: updatedFiles
968 });
969 this.emit('pause-all');
970 };
971
972 _proto.resumeAll = function resumeAll() {
973 var updatedFiles = _extends({}, this.getState().files);
974
975 var inProgressUpdatedFiles = Object.keys(updatedFiles).filter(function (file) {
976 return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted;
977 });
978 inProgressUpdatedFiles.forEach(function (file) {
979 var updatedFile = _extends({}, updatedFiles[file], {
980 isPaused: false,
981 error: null
982 });
983
984 updatedFiles[file] = updatedFile;
985 });
986 this.setState({
987 files: updatedFiles
988 });
989 this.emit('resume-all');
990 };
991
992 _proto.retryAll = function retryAll() {
993 var updatedFiles = _extends({}, this.getState().files);
994
995 var filesToRetry = Object.keys(updatedFiles).filter(function (file) {
996 return updatedFiles[file].error;
997 });
998 filesToRetry.forEach(function (file) {
999 var updatedFile = _extends({}, updatedFiles[file], {
1000 isPaused: false,
1001 error: null
1002 });
1003
1004 updatedFiles[file] = updatedFile;
1005 });
1006 this.setState({
1007 files: updatedFiles,
1008 error: null
1009 });
1010 this.emit('retry-all', filesToRetry);
1011
1012 if (filesToRetry.length === 0) {
1013 return Promise.resolve({
1014 successful: [],
1015 failed: []
1016 });
1017 }
1018
1019 var uploadID = this._createUpload(filesToRetry, {
1020 forceAllowNewUpload: true // create new upload even if allowNewUpload: false
1021
1022 });
1023
1024 return this._runUpload(uploadID);
1025 };
1026
1027 _proto.cancelAll = function cancelAll() {
1028 this.emit('cancel-all');
1029
1030 var _this$getState5 = this.getState(),
1031 files = _this$getState5.files;
1032
1033 var fileIDs = Object.keys(files);
1034
1035 if (fileIDs.length) {
1036 this.removeFiles(fileIDs, 'cancel-all');
1037 }
1038
1039 this.setState({
1040 totalProgress: 0,
1041 error: null
1042 });
1043 };
1044
1045 _proto.retryUpload = function retryUpload(fileID) {
1046 this.setFileState(fileID, {
1047 error: null,
1048 isPaused: false
1049 });
1050 this.emit('upload-retry', fileID);
1051
1052 var uploadID = this._createUpload([fileID], {
1053 forceAllowNewUpload: true // create new upload even if allowNewUpload: false
1054
1055 });
1056
1057 return this._runUpload(uploadID);
1058 };
1059
1060 _proto.reset = function reset() {
1061 this.cancelAll();
1062 };
1063
1064 _proto._calculateProgress = function _calculateProgress(file, data) {
1065 if (!this.getFile(file.id)) {
1066 this.log("Not setting progress for a file that has been removed: " + file.id);
1067 return;
1068 } // bytesTotal may be null or zero; in that case we can't divide by it
1069
1070
1071 var canHavePercentage = isFinite(data.bytesTotal) && data.bytesTotal > 0;
1072 this.setFileState(file.id, {
1073 progress: _extends({}, this.getFile(file.id).progress, {
1074 bytesUploaded: data.bytesUploaded,
1075 bytesTotal: data.bytesTotal,
1076 percentage: canHavePercentage // TODO(goto-bus-stop) flooring this should probably be the choice of the UI?
1077 // we get more accurate calculations if we don't round this at all.
1078 ? Math.round(data.bytesUploaded / data.bytesTotal * 100) : 0
1079 })
1080 });
1081
1082 this._calculateTotalProgress();
1083 };
1084
1085 _proto._calculateTotalProgress = function _calculateTotalProgress() {
1086 // calculate total progress, using the number of files currently uploading,
1087 // multiplied by 100 and the summ of individual progress of each file
1088 var files = this.getFiles();
1089 var inProgress = files.filter(function (file) {
1090 return file.progress.uploadStarted || file.progress.preprocess || file.progress.postprocess;
1091 });
1092
1093 if (inProgress.length === 0) {
1094 this.emit('progress', 0);
1095 this.setState({
1096 totalProgress: 0
1097 });
1098 return;
1099 }
1100
1101 var sizedFiles = inProgress.filter(function (file) {
1102 return file.progress.bytesTotal != null;
1103 });
1104 var unsizedFiles = inProgress.filter(function (file) {
1105 return file.progress.bytesTotal == null;
1106 });
1107
1108 if (sizedFiles.length === 0) {
1109 var progressMax = inProgress.length * 100;
1110 var currentProgress = unsizedFiles.reduce(function (acc, file) {
1111 return acc + file.progress.percentage;
1112 }, 0);
1113
1114 var _totalProgress = Math.round(currentProgress / progressMax * 100);
1115
1116 this.setState({
1117 totalProgress: _totalProgress
1118 });
1119 return;
1120 }
1121
1122 var totalSize = sizedFiles.reduce(function (acc, file) {
1123 return acc + file.progress.bytesTotal;
1124 }, 0);
1125 var averageSize = totalSize / sizedFiles.length;
1126 totalSize += averageSize * unsizedFiles.length;
1127 var uploadedSize = 0;
1128 sizedFiles.forEach(function (file) {
1129 uploadedSize += file.progress.bytesUploaded;
1130 });
1131 unsizedFiles.forEach(function (file) {
1132 uploadedSize += averageSize * (file.progress.percentage || 0) / 100;
1133 });
1134 var totalProgress = totalSize === 0 ? 0 : Math.round(uploadedSize / totalSize * 100); // hot fix, because:
1135 // uploadedSize ended up larger than totalSize, resulting in 1325% total
1136
1137 if (totalProgress > 100) {
1138 totalProgress = 100;
1139 }
1140
1141 this.setState({
1142 totalProgress: totalProgress
1143 });
1144 this.emit('progress', totalProgress);
1145 }
1146 /**
1147 * Registers listeners for all global actions, like:
1148 * `error`, `file-removed`, `upload-progress`
1149 */
1150 ;
1151
1152 _proto._addListeners = function _addListeners() {
1153 var _this6 = this;
1154
1155 this.on('error', function (error) {
1156 var errorMsg = 'Unknown error';
1157
1158 if (error.message) {
1159 errorMsg = error.message;
1160 }
1161
1162 if (error.details) {
1163 errorMsg += ' ' + error.details;
1164 }
1165
1166 _this6.setState({
1167 error: errorMsg
1168 });
1169 });
1170 this.on('upload-error', function (file, error, response) {
1171 var errorMsg = 'Unknown error';
1172
1173 if (error.message) {
1174 errorMsg = error.message;
1175 }
1176
1177 if (error.details) {
1178 errorMsg += ' ' + error.details;
1179 }
1180
1181 _this6.setFileState(file.id, {
1182 error: errorMsg,
1183 response: response
1184 });
1185
1186 _this6.setState({
1187 error: error.message
1188 });
1189
1190 if (typeof error === 'object' && error.message) {
1191 var newError = new Error(error.message);
1192 newError.details = error.message;
1193
1194 if (error.details) {
1195 newError.details += ' ' + error.details;
1196 }
1197
1198 newError.message = _this6.i18n('failedToUpload', {
1199 file: file.name
1200 });
1201
1202 _this6._showOrLogErrorAndThrow(newError, {
1203 throwErr: false
1204 });
1205 } else {
1206 _this6._showOrLogErrorAndThrow(error, {
1207 throwErr: false
1208 });
1209 }
1210 });
1211 this.on('upload', function () {
1212 _this6.setState({
1213 error: null
1214 });
1215 });
1216 this.on('upload-started', function (file, upload) {
1217 if (!_this6.getFile(file.id)) {
1218 _this6.log("Not setting progress for a file that has been removed: " + file.id);
1219
1220 return;
1221 }
1222
1223 _this6.setFileState(file.id, {
1224 progress: {
1225 uploadStarted: Date.now(),
1226 uploadComplete: false,
1227 percentage: 0,
1228 bytesUploaded: 0,
1229 bytesTotal: file.size
1230 }
1231 });
1232 });
1233 this.on('upload-progress', this._calculateProgress);
1234 this.on('upload-success', function (file, uploadResp) {
1235 if (!_this6.getFile(file.id)) {
1236 _this6.log("Not setting progress for a file that has been removed: " + file.id);
1237
1238 return;
1239 }
1240
1241 var currentProgress = _this6.getFile(file.id).progress;
1242
1243 _this6.setFileState(file.id, {
1244 progress: _extends({}, currentProgress, {
1245 postprocess: _this6.postProcessors.length > 0 ? {
1246 mode: 'indeterminate'
1247 } : null,
1248 uploadComplete: true,
1249 percentage: 100,
1250 bytesUploaded: currentProgress.bytesTotal
1251 }),
1252 response: uploadResp,
1253 uploadURL: uploadResp.uploadURL,
1254 isPaused: false
1255 });
1256
1257 _this6._calculateTotalProgress();
1258 });
1259 this.on('preprocess-progress', function (file, progress) {
1260 if (!_this6.getFile(file.id)) {
1261 _this6.log("Not setting progress for a file that has been removed: " + file.id);
1262
1263 return;
1264 }
1265
1266 _this6.setFileState(file.id, {
1267 progress: _extends({}, _this6.getFile(file.id).progress, {
1268 preprocess: progress
1269 })
1270 });
1271 });
1272 this.on('preprocess-complete', function (file) {
1273 if (!_this6.getFile(file.id)) {
1274 _this6.log("Not setting progress for a file that has been removed: " + file.id);
1275
1276 return;
1277 }
1278
1279 var files = _extends({}, _this6.getState().files);
1280
1281 files[file.id] = _extends({}, files[file.id], {
1282 progress: _extends({}, files[file.id].progress)
1283 });
1284 delete files[file.id].progress.preprocess;
1285
1286 _this6.setState({
1287 files: files
1288 });
1289 });
1290 this.on('postprocess-progress', function (file, progress) {
1291 if (!_this6.getFile(file.id)) {
1292 _this6.log("Not setting progress for a file that has been removed: " + file.id);
1293
1294 return;
1295 }
1296
1297 _this6.setFileState(file.id, {
1298 progress: _extends({}, _this6.getState().files[file.id].progress, {
1299 postprocess: progress
1300 })
1301 });
1302 });
1303 this.on('postprocess-complete', function (file) {
1304 if (!_this6.getFile(file.id)) {
1305 _this6.log("Not setting progress for a file that has been removed: " + file.id);
1306
1307 return;
1308 }
1309
1310 var files = _extends({}, _this6.getState().files);
1311
1312 files[file.id] = _extends({}, files[file.id], {
1313 progress: _extends({}, files[file.id].progress)
1314 });
1315 delete files[file.id].progress.postprocess; // TODO should we set some kind of `fullyComplete` property on the file object
1316 // so it's easier to see that the file is upload…fully complete…rather than
1317 // what we have to do now (`uploadComplete && !postprocess`)
1318
1319 _this6.setState({
1320 files: files
1321 });
1322 });
1323 this.on('restored', function () {
1324 // Files may have changed--ensure progress is still accurate.
1325 _this6._calculateTotalProgress();
1326 }); // show informer if offline
1327
1328 if (typeof window !== 'undefined' && window.addEventListener) {
1329 window.addEventListener('online', function () {
1330 return _this6.updateOnlineStatus();
1331 });
1332 window.addEventListener('offline', function () {
1333 return _this6.updateOnlineStatus();
1334 });
1335 setTimeout(function () {
1336 return _this6.updateOnlineStatus();
1337 }, 3000);
1338 }
1339 };
1340
1341 _proto.updateOnlineStatus = function updateOnlineStatus() {
1342 var online = typeof window.navigator.onLine !== 'undefined' ? window.navigator.onLine : true;
1343
1344 if (!online) {
1345 this.emit('is-offline');
1346 this.info(this.i18n('noInternetConnection'), 'error', 0);
1347 this.wasOffline = true;
1348 } else {
1349 this.emit('is-online');
1350
1351 if (this.wasOffline) {
1352 this.emit('back-online');
1353 this.info(this.i18n('connectedToInternet'), 'success', 3000);
1354 this.wasOffline = false;
1355 }
1356 }
1357 };
1358
1359 _proto.getID = function getID() {
1360 return this.opts.id;
1361 }
1362 /**
1363 * Registers a plugin with Core.
1364 *
1365 * @param {object} Plugin object
1366 * @param {object} [opts] object with options to be passed to Plugin
1367 * @returns {object} self for chaining
1368 */
1369 ;
1370
1371 _proto.use = function use(Plugin, opts) {
1372 if (typeof Plugin !== 'function') {
1373 var msg = "Expected a plugin class, but got " + (Plugin === null ? 'null' : typeof Plugin) + "." + ' Please verify that the plugin was imported and spelled correctly.';
1374 throw new TypeError(msg);
1375 } // Instantiate
1376
1377
1378 var plugin = new Plugin(this, opts);
1379 var pluginId = plugin.id;
1380 this.plugins[plugin.type] = this.plugins[plugin.type] || [];
1381
1382 if (!pluginId) {
1383 throw new Error('Your plugin must have an id');
1384 }
1385
1386 if (!plugin.type) {
1387 throw new Error('Your plugin must have a type');
1388 }
1389
1390 var existsPluginAlready = this.getPlugin(pluginId);
1391
1392 if (existsPluginAlready) {
1393 var _msg = "Already found a plugin named '" + existsPluginAlready.id + "'. " + ("Tried to use: '" + pluginId + "'.\n") + 'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.';
1394
1395 throw new Error(_msg);
1396 }
1397
1398 if (Plugin.VERSION) {
1399 this.log("Using " + pluginId + " v" + Plugin.VERSION);
1400 }
1401
1402 this.plugins[plugin.type].push(plugin);
1403 plugin.install();
1404 return this;
1405 }
1406 /**
1407 * Find one Plugin by name.
1408 *
1409 * @param {string} id plugin id
1410 * @returns {object|boolean}
1411 */
1412 ;
1413
1414 _proto.getPlugin = function getPlugin(id) {
1415 var foundPlugin = null;
1416 this.iteratePlugins(function (plugin) {
1417 if (plugin.id === id) {
1418 foundPlugin = plugin;
1419 return false;
1420 }
1421 });
1422 return foundPlugin;
1423 }
1424 /**
1425 * Iterate through all `use`d plugins.
1426 *
1427 * @param {Function} method that will be run on each plugin
1428 */
1429 ;
1430
1431 _proto.iteratePlugins = function iteratePlugins(method) {
1432 var _this7 = this;
1433
1434 Object.keys(this.plugins).forEach(function (pluginType) {
1435 _this7.plugins[pluginType].forEach(method);
1436 });
1437 }
1438 /**
1439 * Uninstall and remove a plugin.
1440 *
1441 * @param {object} instance The plugin instance to remove.
1442 */
1443 ;
1444
1445 _proto.removePlugin = function removePlugin(instance) {
1446 this.log("Removing plugin " + instance.id);
1447 this.emit('plugin-remove', instance);
1448
1449 if (instance.uninstall) {
1450 instance.uninstall();
1451 }
1452
1453 var list = this.plugins[instance.type].slice();
1454 var index = list.indexOf(instance);
1455
1456 if (index !== -1) {
1457 list.splice(index, 1);
1458 this.plugins[instance.type] = list;
1459 }
1460
1461 var updatedState = this.getState();
1462 delete updatedState.plugins[instance.id];
1463 this.setState(updatedState);
1464 }
1465 /**
1466 * Uninstall all plugins and close down this Uppy instance.
1467 */
1468 ;
1469
1470 _proto.close = function close() {
1471 var _this8 = this;
1472
1473 this.log("Closing Uppy instance " + this.opts.id + ": removing all files and uninstalling plugins");
1474 this.reset();
1475
1476 this._storeUnsubscribe();
1477
1478 this.iteratePlugins(function (plugin) {
1479 _this8.removePlugin(plugin);
1480 });
1481 }
1482 /**
1483 * Set info message in `state.info`, so that UI plugins like `Informer`
1484 * can display the message.
1485 *
1486 * @param {string | object} message Message to be displayed by the informer
1487 * @param {string} [type]
1488 * @param {number} [duration]
1489 */
1490 ;
1491
1492 _proto.info = function info(message, type, duration) {
1493 if (type === void 0) {
1494 type = 'info';
1495 }
1496
1497 if (duration === void 0) {
1498 duration = 3000;
1499 }
1500
1501 var isComplexMessage = typeof message === 'object';
1502 this.setState({
1503 info: {
1504 isHidden: false,
1505 type: type,
1506 message: isComplexMessage ? message.message : message,
1507 details: isComplexMessage ? message.details : null
1508 }
1509 });
1510 this.emit('info-visible');
1511 clearTimeout(this.infoTimeoutID);
1512
1513 if (duration === 0) {
1514 this.infoTimeoutID = undefined;
1515 return;
1516 } // hide the informer after `duration` milliseconds
1517
1518
1519 this.infoTimeoutID = setTimeout(this.hideInfo, duration);
1520 };
1521
1522 _proto.hideInfo = function hideInfo() {
1523 var newInfo = _extends({}, this.getState().info, {
1524 isHidden: true
1525 });
1526
1527 this.setState({
1528 info: newInfo
1529 });
1530 this.emit('info-hidden');
1531 }
1532 /**
1533 * Passes messages to a function, provided in `opts.logger`.
1534 * If `opts.logger: Uppy.debugLogger` or `opts.debug: true`, logs to the browser console.
1535 *
1536 * @param {string|object} message to log
1537 * @param {string} [type] optional `error` or `warning`
1538 */
1539 ;
1540
1541 _proto.log = function log(message, type) {
1542 var logger = this.opts.logger;
1543
1544 switch (type) {
1545 case 'error':
1546 logger.error(message);
1547 break;
1548
1549 case 'warning':
1550 logger.warn(message);
1551 break;
1552
1553 default:
1554 logger.debug(message);
1555 break;
1556 }
1557 }
1558 /**
1559 * Obsolete, event listeners are now added in the constructor.
1560 */
1561 ;
1562
1563 _proto.run = function run() {
1564 this.log('Calling run() is no longer necessary.', 'warning');
1565 return this;
1566 }
1567 /**
1568 * Restore an upload by its ID.
1569 */
1570 ;
1571
1572 _proto.restore = function restore(uploadID) {
1573 this.log("Core: attempting to restore upload \"" + uploadID + "\"");
1574
1575 if (!this.getState().currentUploads[uploadID]) {
1576 this._removeUpload(uploadID);
1577
1578 return Promise.reject(new Error('Nonexistent upload'));
1579 }
1580
1581 return this._runUpload(uploadID);
1582 }
1583 /**
1584 * Create an upload for a bunch of files.
1585 *
1586 * @param {Array<string>} fileIDs File IDs to include in this upload.
1587 * @returns {string} ID of this upload.
1588 */
1589 ;
1590
1591 _proto._createUpload = function _createUpload(fileIDs, opts) {
1592 var _extends4;
1593
1594 if (opts === void 0) {
1595 opts = {};
1596 }
1597
1598 var _opts = opts,
1599 _opts$forceAllowNewUp = _opts.forceAllowNewUpload,
1600 forceAllowNewUpload = _opts$forceAllowNewUp === void 0 ? false : _opts$forceAllowNewUp;
1601
1602 var _this$getState6 = this.getState(),
1603 allowNewUpload = _this$getState6.allowNewUpload,
1604 currentUploads = _this$getState6.currentUploads;
1605
1606 if (!allowNewUpload && !forceAllowNewUpload) {
1607 throw new Error('Cannot create a new upload: already uploading.');
1608 }
1609
1610 var uploadID = cuid();
1611 this.emit('upload', {
1612 id: uploadID,
1613 fileIDs: fileIDs
1614 });
1615 this.setState({
1616 allowNewUpload: this.opts.allowMultipleUploads !== false,
1617 currentUploads: _extends({}, currentUploads, (_extends4 = {}, _extends4[uploadID] = {
1618 fileIDs: fileIDs,
1619 step: 0,
1620 result: {}
1621 }, _extends4))
1622 });
1623 return uploadID;
1624 };
1625
1626 _proto._getUpload = function _getUpload(uploadID) {
1627 var _this$getState7 = this.getState(),
1628 currentUploads = _this$getState7.currentUploads;
1629
1630 return currentUploads[uploadID];
1631 }
1632 /**
1633 * Add data to an upload's result object.
1634 *
1635 * @param {string} uploadID The ID of the upload.
1636 * @param {object} data Data properties to add to the result object.
1637 */
1638 ;
1639
1640 _proto.addResultData = function addResultData(uploadID, data) {
1641 var _extends5;
1642
1643 if (!this._getUpload(uploadID)) {
1644 this.log("Not setting result for an upload that has been removed: " + uploadID);
1645 return;
1646 }
1647
1648 var currentUploads = this.getState().currentUploads;
1649
1650 var currentUpload = _extends({}, currentUploads[uploadID], {
1651 result: _extends({}, currentUploads[uploadID].result, data)
1652 });
1653
1654 this.setState({
1655 currentUploads: _extends({}, currentUploads, (_extends5 = {}, _extends5[uploadID] = currentUpload, _extends5))
1656 });
1657 }
1658 /**
1659 * Remove an upload, eg. if it has been canceled or completed.
1660 *
1661 * @param {string} uploadID The ID of the upload.
1662 */
1663 ;
1664
1665 _proto._removeUpload = function _removeUpload(uploadID) {
1666 var currentUploads = _extends({}, this.getState().currentUploads);
1667
1668 delete currentUploads[uploadID];
1669 this.setState({
1670 currentUploads: currentUploads
1671 });
1672 }
1673 /**
1674 * Run an upload. This picks up where it left off in case the upload is being restored.
1675 *
1676 * @private
1677 */
1678 ;
1679
1680 _proto._runUpload = function _runUpload(uploadID) {
1681 var _this9 = this;
1682
1683 var uploadData = this.getState().currentUploads[uploadID];
1684 var restoreStep = uploadData.step;
1685 var steps = [].concat(this.preProcessors, this.uploaders, this.postProcessors);
1686 var lastStep = Promise.resolve();
1687 steps.forEach(function (fn, step) {
1688 // Skip this step if we are restoring and have already completed this step before.
1689 if (step < restoreStep) {
1690 return;
1691 }
1692
1693 lastStep = lastStep.then(function () {
1694 var _extends6;
1695
1696 var _this9$getState = _this9.getState(),
1697 currentUploads = _this9$getState.currentUploads;
1698
1699 var currentUpload = currentUploads[uploadID];
1700
1701 if (!currentUpload) {
1702 return;
1703 }
1704
1705 var updatedUpload = _extends({}, currentUpload, {
1706 step: step
1707 });
1708
1709 _this9.setState({
1710 currentUploads: _extends({}, currentUploads, (_extends6 = {}, _extends6[uploadID] = updatedUpload, _extends6))
1711 }); // TODO give this the `updatedUpload` object as its only parameter maybe?
1712 // Otherwise when more metadata may be added to the upload this would keep getting more parameters
1713
1714
1715 return fn(updatedUpload.fileIDs, uploadID);
1716 }).then(function (result) {
1717 return null;
1718 });
1719 }); // Not returning the `catch`ed promise, because we still want to return a rejected
1720 // promise from this method if the upload failed.
1721
1722 lastStep.catch(function (err) {
1723 _this9.emit('error', err, uploadID);
1724
1725 _this9._removeUpload(uploadID);
1726 });
1727 return lastStep.then(function () {
1728 // Set result data.
1729 var _this9$getState2 = _this9.getState(),
1730 currentUploads = _this9$getState2.currentUploads;
1731
1732 var currentUpload = currentUploads[uploadID];
1733
1734 if (!currentUpload) {
1735 return;
1736 }
1737
1738 var files = currentUpload.fileIDs.map(function (fileID) {
1739 return _this9.getFile(fileID);
1740 });
1741 var successful = files.filter(function (file) {
1742 return !file.error;
1743 });
1744 var failed = files.filter(function (file) {
1745 return file.error;
1746 });
1747
1748 _this9.addResultData(uploadID, {
1749 successful: successful,
1750 failed: failed,
1751 uploadID: uploadID
1752 });
1753 }).then(function () {
1754 // Emit completion events.
1755 // This is in a separate function so that the `currentUploads` variable
1756 // always refers to the latest state. In the handler right above it refers
1757 // to an outdated object without the `.result` property.
1758 var _this9$getState3 = _this9.getState(),
1759 currentUploads = _this9$getState3.currentUploads;
1760
1761 if (!currentUploads[uploadID]) {
1762 return;
1763 }
1764
1765 var currentUpload = currentUploads[uploadID];
1766 var result = currentUpload.result;
1767
1768 _this9.emit('complete', result);
1769
1770 _this9._removeUpload(uploadID);
1771
1772 return result;
1773 }).then(function (result) {
1774 if (result == null) {
1775 _this9.log("Not setting result for an upload that has been removed: " + uploadID);
1776 }
1777
1778 return result;
1779 });
1780 }
1781 /**
1782 * Start an upload for all the files that are not currently being uploaded.
1783 *
1784 * @returns {Promise}
1785 */
1786 ;
1787
1788 _proto.upload = function upload() {
1789 var _this10 = this;
1790
1791 if (!this.plugins.uploader) {
1792 this.log('No uploader type plugins are used', 'warning');
1793 }
1794
1795 var files = this.getState().files;
1796 var onBeforeUploadResult = this.opts.onBeforeUpload(files);
1797
1798 if (onBeforeUploadResult === false) {
1799 return Promise.reject(new Error('Not starting the upload because onBeforeUpload returned false'));
1800 }
1801
1802 if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {
1803 files = onBeforeUploadResult; // Updating files in state, because uploader plugins receive file IDs,
1804 // and then fetch the actual file object from state
1805
1806 this.setState({
1807 files: files
1808 });
1809 }
1810
1811 return Promise.resolve().then(function () {
1812 return _this10._checkMinNumberOfFiles(files);
1813 }).catch(function (err) {
1814 _this10._showOrLogErrorAndThrow(err);
1815 }).then(function () {
1816 var _this10$getState = _this10.getState(),
1817 currentUploads = _this10$getState.currentUploads; // get a list of files that are currently assigned to uploads
1818
1819
1820 var currentlyUploadingFiles = Object.keys(currentUploads).reduce(function (prev, curr) {
1821 return prev.concat(currentUploads[curr].fileIDs);
1822 }, []);
1823 var waitingFileIDs = [];
1824 Object.keys(files).forEach(function (fileID) {
1825 var file = _this10.getFile(fileID); // if the file hasn't started uploading and hasn't already been assigned to an upload..
1826
1827
1828 if (!file.progress.uploadStarted && currentlyUploadingFiles.indexOf(fileID) === -1) {
1829 waitingFileIDs.push(file.id);
1830 }
1831 });
1832
1833 var uploadID = _this10._createUpload(waitingFileIDs);
1834
1835 return _this10._runUpload(uploadID);
1836 }).catch(function (err) {
1837 _this10._showOrLogErrorAndThrow(err, {
1838 showInformer: false
1839 });
1840 });
1841 };
1842
1843 _createClass(Uppy, [{
1844 key: "state",
1845 get: function get() {
1846 return this.getState();
1847 }
1848 }]);
1849
1850 return Uppy;
1851}();
1852
1853Uppy.VERSION = "1.14.0";
1854
1855module.exports = function (opts) {
1856 return new Uppy(opts);
1857}; // Expose class constructor.
1858
1859
1860module.exports.Uppy = Uppy;
1861module.exports.Plugin = Plugin;
1862module.exports.debugLogger = debugLogger;
\No newline at end of file