1 | function _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 |
|
3 | 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); } }
|
4 |
|
5 | function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
|
6 |
|
7 | function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
|
8 |
|
9 | function _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 |
|
11 | function _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 |
|
13 | function _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 |
|
15 | function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
|
16 |
|
17 | function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
|
18 |
|
19 | function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
|
20 |
|
21 | var Translator = require('@uppy/utils/lib/Translator');
|
22 |
|
23 | var ee = require('namespace-emitter');
|
24 |
|
25 | var cuid = require('cuid');
|
26 |
|
27 | var throttle = require('lodash.throttle');
|
28 |
|
29 | var prettierBytes = require('@transloadit/prettier-bytes');
|
30 |
|
31 | var match = require('mime-match');
|
32 |
|
33 | var DefaultStore = require('@uppy/store-default');
|
34 |
|
35 | var getFileType = require('@uppy/utils/lib/getFileType');
|
36 |
|
37 | var getFileNameAndExtension = require('@uppy/utils/lib/getFileNameAndExtension');
|
38 |
|
39 | var generateFileID = require('@uppy/utils/lib/generateFileID');
|
40 |
|
41 | var supportsUploadProgress = require('./supportsUploadProgress');
|
42 |
|
43 | var _require = require('./loggers'),
|
44 | justErrorsLogger = _require.justErrorsLogger,
|
45 | debugLogger = _require.debugLogger;
|
46 |
|
47 | var Plugin = require('./Plugin');
|
48 |
|
49 |
|
50 | var RestrictionError = 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 | }( _wrapNativeSuper(Error));
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | var Uppy = function () {
|
75 | |
76 |
|
77 |
|
78 |
|
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 |
|
98 |
|
99 |
|
100 |
|
101 |
|
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 |
|
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 | };
|
165 |
|
166 |
|
167 | this.opts = _extends({}, defaultOptions, opts, {
|
168 | restrictions: _extends({}, defaultOptions.restrictions, opts && opts.restrictions)
|
169 | });
|
170 |
|
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();
|
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);
|
198 |
|
199 |
|
200 |
|
201 |
|
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 | });
|
247 |
|
248 | if (this.opts.debug && typeof window !== 'undefined') {
|
249 | window[this.opts.id] = this;
|
250 | }
|
251 |
|
252 | this._addListeners();
|
253 |
|
254 |
|
255 | }
|
256 |
|
257 |
|
258 |
|
259 |
|
260 |
|
261 |
|
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 |
|
279 |
|
280 |
|
281 |
|
282 | ;
|
283 |
|
284 | _proto.updateAll = function updateAll(state) {
|
285 | this.iteratePlugins(function (plugin) {
|
286 | plugin.update(state);
|
287 | });
|
288 | }
|
289 | |
290 |
|
291 |
|
292 |
|
293 |
|
294 | ;
|
295 |
|
296 | _proto.setState = function setState(patch) {
|
297 | this.store.setState(patch);
|
298 | }
|
299 | |
300 |
|
301 |
|
302 |
|
303 |
|
304 | ;
|
305 |
|
306 | _proto.getState = function getState() {
|
307 | return this.store.getState();
|
308 | }
|
309 | |
310 |
|
311 |
|
312 | ;
|
313 |
|
314 | |
315 |
|
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();
|
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 |
|
453 |
|
454 |
|
455 |
|
456 | ;
|
457 |
|
458 | _proto.getFile = function getFile(fileID) {
|
459 | return this.getState().files[fileID];
|
460 | }
|
461 | |
462 |
|
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 |
|
476 |
|
477 |
|
478 |
|
479 |
|
480 |
|
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 |
|
500 |
|
501 |
|
502 |
|
503 |
|
504 |
|
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 |
|
531 | if (type.indexOf('/') > -1) {
|
532 | if (!file.type) return false;
|
533 | return match(file.type.replace(/;.*?$/, ''), type);
|
534 | }
|
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 | }
|
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 | }
|
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 | }
|
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 |
|
589 |
|
590 |
|
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 |
|
605 |
|
606 |
|
607 |
|
608 |
|
609 |
|
610 |
|
611 |
|
612 |
|
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 : '';
|
627 |
|
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 | }
|
641 |
|
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 |
|
668 |
|
669 |
|
670 |
|
671 |
|
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 |
|
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;
|
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 | }
|
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 |
|
769 |
|
770 |
|
771 |
|
772 |
|
773 |
|
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 |
|
799 |
|
800 |
|
801 |
|
802 |
|
803 |
|
804 | ;
|
805 |
|
806 | _proto.addFiles = function addFiles(fileDescriptors) {
|
807 | var _this4 = this;
|
808 |
|
809 | this._assertNewUploadAllowed();
|
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 | });
|
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);
|
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 | };
|
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
|
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
|
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 | }
|
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
|
1077 |
|
1078 | ? Math.round(data.bytesUploaded / data.bytesTotal * 100) : 0
|
1079 | })
|
1080 | });
|
1081 |
|
1082 | this._calculateTotalProgress();
|
1083 | };
|
1084 |
|
1085 | _proto._calculateTotalProgress = function _calculateTotalProgress() {
|
1086 |
|
1087 |
|
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);
|
1135 |
|
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 |
|
1148 |
|
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;
|
1316 |
|
1317 |
|
1318 |
|
1319 | _this6.setState({
|
1320 | files: files
|
1321 | });
|
1322 | });
|
1323 | this.on('restored', function () {
|
1324 |
|
1325 | _this6._calculateTotalProgress();
|
1326 | });
|
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 |
|
1364 |
|
1365 |
|
1366 |
|
1367 |
|
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 | }
|
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 |
|
1408 |
|
1409 |
|
1410 |
|
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 |
|
1426 |
|
1427 |
|
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 |
|
1440 |
|
1441 |
|
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 |
|
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 |
|
1484 |
|
1485 |
|
1486 |
|
1487 |
|
1488 |
|
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 | }
|
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 |
|
1534 |
|
1535 |
|
1536 |
|
1537 |
|
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 |
|
1560 |
|
1561 | ;
|
1562 |
|
1563 | _proto.run = function run() {
|
1564 | this.log('Calling run() is no longer necessary.', 'warning');
|
1565 | return this;
|
1566 | }
|
1567 | |
1568 |
|
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 |
|
1585 |
|
1586 |
|
1587 |
|
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 |
|
1634 |
|
1635 |
|
1636 |
|
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 |
|
1660 |
|
1661 |
|
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 |
|
1675 |
|
1676 |
|
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 |
|
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 | });
|
1712 |
|
1713 |
|
1714 |
|
1715 | return fn(updatedUpload.fileIDs, uploadID);
|
1716 | }).then(function (result) {
|
1717 | return null;
|
1718 | });
|
1719 | });
|
1720 |
|
1721 |
|
1722 | lastStep.catch(function (err) {
|
1723 | _this9.emit('error', err, uploadID);
|
1724 |
|
1725 | _this9._removeUpload(uploadID);
|
1726 | });
|
1727 | return lastStep.then(function () {
|
1728 |
|
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 |
|
1755 |
|
1756 |
|
1757 |
|
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 |
|
1783 |
|
1784 |
|
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;
|
1804 |
|
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;
|
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);
|
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 |
|
1853 | Uppy.VERSION = "1.14.0";
|
1854 |
|
1855 | module.exports = function (opts) {
|
1856 | return new Uppy(opts);
|
1857 | };
|
1858 |
|
1859 |
|
1860 | module.exports.Uppy = Uppy;
|
1861 | module.exports.Plugin = Plugin;
|
1862 | module.exports.debugLogger = debugLogger; |
\ | No newline at end of file |