forked from transloadit/uppy
/
Uppy.js
1704 lines (1458 loc) · 48.8 KB
/
Uppy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global AggregateError */
'use strict'
const Translator = require('@uppy/utils/lib/Translator')
const ee = require('namespace-emitter')
const { nanoid } = require('nanoid/non-secure')
const throttle = require('lodash.throttle')
const prettierBytes = require('@transloadit/prettier-bytes')
const match = require('mime-match')
const DefaultStore = require('@uppy/store-default')
const getFileType = require('@uppy/utils/lib/getFileType')
const getFileNameAndExtension = require('@uppy/utils/lib/getFileNameAndExtension')
const generateFileID = require('@uppy/utils/lib/generateFileID')
const supportsUploadProgress = require('./supportsUploadProgress')
const getFileName = require('./getFileName')
const { justErrorsLogger, debugLogger } = require('./loggers')
const locale = require('./locale')
// Exported from here.
class RestrictionError extends Error {
constructor (...args) {
super(...args)
this.isRestriction = true
}
}
if (typeof AggregateError === 'undefined') {
// eslint-disable-next-line no-global-assign
globalThis.AggregateError = class AggregateError extends Error {
constructor (errors, message) {
super(message)
this.errors = errors
}
}
}
class AggregateRestrictionError extends AggregateError {
constructor (...args) {
super(...args)
this.isRestriction = true
}
}
/**
* Uppy Core module.
* Manages plugins, state updates, acts as an event bus,
* adds/removes files and metadata.
*/
class Uppy {
// eslint-disable-next-line global-require
static VERSION = require('../package.json').version
/** @type {Record<string, BasePlugin[]>} */
#plugins = Object.create(null)
#storeUnsubscribe
#emitter = ee()
#preProcessors = new Set()
#uploaders = new Set()
#postProcessors = new Set()
/**
* Instantiate Uppy
*
* @param {object} opts — Uppy options
*/
constructor (opts) {
this.defaultLocale = locale
const defaultOptions = {
id: 'uppy',
autoProceed: false,
/**
* @deprecated The method should not be used
*/
allowMultipleUploads: true,
allowMultipleUploadBatches: true,
debug: false,
restrictions: {
maxFileSize: null,
minFileSize: null,
maxTotalFileSize: null,
maxNumberOfFiles: null,
minNumberOfFiles: null,
allowedFileTypes: null,
requiredMetaFields: [],
},
meta: {},
onBeforeFileAdded: (currentFile) => currentFile,
onBeforeUpload: (files) => files,
store: DefaultStore(),
logger: justErrorsLogger,
infoTimeout: 5000,
}
// Merge default options with the ones set by user,
// making sure to merge restrictions too
this.opts = {
...defaultOptions,
...opts,
restrictions: {
...defaultOptions.restrictions,
...(opts && opts.restrictions),
},
}
// Support debug: true for backwards-compatability, unless logger is set in opts
// opts instead of this.opts to avoid comparing objects — we set logger: justErrorsLogger in defaultOptions
if (opts && opts.logger && opts.debug) {
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')
} else if (opts && opts.debug) {
this.opts.logger = debugLogger
}
this.log(`Using Core v${this.constructor.VERSION}`)
if (this.opts.restrictions.allowedFileTypes
&& this.opts.restrictions.allowedFileTypes !== null
&& !Array.isArray(this.opts.restrictions.allowedFileTypes)) {
throw new TypeError('`restrictions.allowedFileTypes` must be an array')
}
this.i18nInit()
// ___Why throttle at 500ms?
// - 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).
// [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.
// - We must throttle at around >500ms to avoid performance lags.
// [Practical Check] Firefox, try to upload a big file for a prolonged period of time. Laptop will start to heat up.
this.calculateProgress = throttle(this.calculateProgress.bind(this), 500, { leading: true, trailing: true })
this.store = this.opts.store
this.setState({
plugins: {},
files: {},
currentUploads: {},
allowNewUpload: true,
capabilities: {
uploadProgress: supportsUploadProgress(),
individualCancellation: true,
resumableUploads: false,
},
totalProgress: 0,
meta: { ...this.opts.meta },
info: [],
recoveredState: null,
})
this.#storeUnsubscribe = this.store.subscribe((prevState, nextState, patch) => {
this.emit('state-update', prevState, nextState, patch)
this.updateAll(nextState)
})
// Exposing uppy object on window for debugging and testing
if (this.opts.debug && typeof window !== 'undefined') {
window[this.opts.id] = this
}
this.#addListeners()
}
emit (event, ...args) {
this.#emitter.emit(event, ...args)
}
on (event, callback) {
this.#emitter.on(event, callback)
return this
}
once (event, callback) {
this.#emitter.once(event, callback)
return this
}
off (event, callback) {
this.#emitter.off(event, callback)
return this
}
/**
* Iterate on all plugins and run `update` on them.
* Called each time state changes.
*
*/
updateAll (state) {
this.iteratePlugins(plugin => {
plugin.update(state)
})
}
/**
* Updates state with a patch
*
* @param {object} patch {foo: 'bar'}
*/
setState (patch) {
this.store.setState(patch)
}
/**
* Returns current state.
*
* @returns {object}
*/
getState () {
return this.store.getState()
}
/**
* Back compat for when uppy.state is used instead of uppy.getState().
*
* @deprecated
*/
get state () {
// Here, state is a non-enumerable property.
return this.getState()
}
/**
* Shorthand to set state for a specific file.
*/
setFileState (fileID, state) {
if (!this.getState().files[fileID]) {
throw new Error(`Can’t set state for ${fileID} (the file could have been removed)`)
}
this.setState({
files: { ...this.getState().files, [fileID]: { ...this.getState().files[fileID], ...state } },
})
}
i18nInit () {
const translator = new Translator([this.defaultLocale, this.opts.locale])
this.i18n = translator.translate.bind(translator)
this.i18nArray = translator.translateArray.bind(translator)
this.locale = translator.locale
}
setOptions (newOpts) {
this.opts = {
...this.opts,
...newOpts,
restrictions: {
...this.opts.restrictions,
...(newOpts && newOpts.restrictions),
},
}
if (newOpts.meta) {
this.setMeta(newOpts.meta)
}
this.i18nInit()
if (newOpts.locale) {
this.iteratePlugins((plugin) => {
plugin.setOptions()
})
}
// Note: this is not the preact `setState`, it's an internal function that has the same name.
this.setState() // so that UI re-renders with new options
}
resetProgress () {
const defaultProgress = {
percentage: 0,
bytesUploaded: 0,
uploadComplete: false,
uploadStarted: null,
}
const files = { ...this.getState().files }
const updatedFiles = {}
Object.keys(files).forEach(fileID => {
const updatedFile = { ...files[fileID] }
updatedFile.progress = { ...updatedFile.progress, ...defaultProgress }
updatedFiles[fileID] = updatedFile
})
this.setState({
files: updatedFiles,
totalProgress: 0,
})
this.emit('reset-progress')
}
addPreProcessor (fn) {
this.#preProcessors.add(fn)
}
removePreProcessor (fn) {
return this.#preProcessors.delete(fn)
}
addPostProcessor (fn) {
this.#postProcessors.add(fn)
}
removePostProcessor (fn) {
return this.#postProcessors.delete(fn)
}
addUploader (fn) {
this.#uploaders.add(fn)
}
removeUploader (fn) {
return this.#uploaders.delete(fn)
}
setMeta (data) {
const updatedMeta = { ...this.getState().meta, ...data }
const updatedFiles = { ...this.getState().files }
Object.keys(updatedFiles).forEach((fileID) => {
updatedFiles[fileID] = { ...updatedFiles[fileID], meta: { ...updatedFiles[fileID].meta, ...data } }
})
this.log('Adding metadata:')
this.log(data)
this.setState({
meta: updatedMeta,
files: updatedFiles,
})
}
setFileMeta (fileID, data) {
const updatedFiles = { ...this.getState().files }
if (!updatedFiles[fileID]) {
this.log('Was trying to set metadata for a file that has been removed: ', fileID)
return
}
const newMeta = { ...updatedFiles[fileID].meta, ...data }
updatedFiles[fileID] = { ...updatedFiles[fileID], meta: newMeta }
this.setState({ files: updatedFiles })
}
/**
* Get a file object.
*
* @param {string} fileID The ID of the file object to return.
*/
getFile (fileID) {
return this.getState().files[fileID]
}
/**
* Get all files in an array.
*/
getFiles () {
const { files } = this.getState()
return Object.values(files)
}
getObjectOfFilesPerState () {
const { files: filesObject, totalProgress, error } = this.getState()
const files = Object.values(filesObject)
const inProgressFiles = files.filter(({ progress }) => !progress.uploadComplete && progress.uploadStarted)
const newFiles = files.filter((file) => !file.progress.uploadStarted)
const startedFiles = files.filter(
file => file.progress.uploadStarted || file.progress.preprocess || file.progress.postprocess,
)
const uploadStartedFiles = files.filter((file) => file.progress.uploadStarted)
const pausedFiles = files.filter((file) => file.isPaused)
const completeFiles = files.filter((file) => file.progress.uploadComplete)
const erroredFiles = files.filter((file) => file.error)
const inProgressNotPausedFiles = inProgressFiles.filter((file) => !file.isPaused)
const processingFiles = files.filter((file) => file.progress.preprocess || file.progress.postprocess)
return {
newFiles,
startedFiles,
uploadStartedFiles,
pausedFiles,
completeFiles,
erroredFiles,
inProgressFiles,
inProgressNotPausedFiles,
processingFiles,
isUploadStarted: uploadStartedFiles.length > 0,
isAllComplete: totalProgress === 100
&& completeFiles.length === files.length
&& processingFiles.length === 0,
isAllErrored: !!error && erroredFiles.length === files.length,
isAllPaused: inProgressFiles.length !== 0 && pausedFiles.length === inProgressFiles.length,
isUploadInProgress: inProgressFiles.length > 0,
isSomeGhost: files.some(file => file.isGhost),
}
}
/**
* A public wrapper for _checkRestrictions — checks if a file passes a set of restrictions.
* For use in UI pluigins (like Providers), to disallow selecting files that won’t pass restrictions.
*
* @param {object} file object to check
* @param {Array} [files] array to check maxNumberOfFiles and maxTotalFileSize
* @returns {object} { result: true/false, reason: why file didn’t pass restrictions }
*/
validateRestrictions (file, files) {
try {
this.#checkRestrictions(file, files)
return {
result: true,
}
} catch (err) {
return {
result: false,
reason: err.message,
}
}
}
/**
* Check if file passes a set of restrictions set in options: maxFileSize, minFileSize,
* maxNumberOfFiles and allowedFileTypes.
*
* @param {object} file object to check
* @param {Array} [files] array to check maxNumberOfFiles and maxTotalFileSize
* @private
*/
#checkRestrictions (file, files = this.getFiles()) {
const { maxFileSize, minFileSize, maxTotalFileSize, maxNumberOfFiles, allowedFileTypes } = this.opts.restrictions
if (maxNumberOfFiles) {
if (files.length + 1 > maxNumberOfFiles) {
throw new RestrictionError(`${this.i18n('youCanOnlyUploadX', { smart_count: maxNumberOfFiles })}`)
}
}
if (allowedFileTypes) {
const isCorrectFileType = allowedFileTypes.some((type) => {
// check if this is a mime-type
if (type.indexOf('/') > -1) {
if (!file.type) return false
return match(file.type.replace(/;.*?$/, ''), type)
}
// otherwise this is likely an extension
if (type[0] === '.' && file.extension) {
return file.extension.toLowerCase() === type.substr(1).toLowerCase()
}
return false
})
if (!isCorrectFileType) {
const allowedFileTypesString = allowedFileTypes.join(', ')
throw new RestrictionError(this.i18n('youCanOnlyUploadFileTypes', { types: allowedFileTypesString }))
}
}
// We can't check maxTotalFileSize if the size is unknown.
if (maxTotalFileSize && file.size != null) {
let totalFilesSize = 0
totalFilesSize += file.size
files.forEach((f) => {
totalFilesSize += f.size
})
if (totalFilesSize > maxTotalFileSize) {
throw new RestrictionError(this.i18n('exceedsSize', {
size: prettierBytes(maxTotalFileSize),
file: file.name,
}))
}
}
// We can't check maxFileSize if the size is unknown.
if (maxFileSize && file.size != null) {
if (file.size > maxFileSize) {
throw new RestrictionError(this.i18n('exceedsSize', {
size: prettierBytes(maxFileSize),
file: file.name,
}))
}
}
// We can't check minFileSize if the size is unknown.
if (minFileSize && file.size != null) {
if (file.size < minFileSize) {
throw new RestrictionError(this.i18n('inferiorSize', {
size: prettierBytes(minFileSize),
}))
}
}
}
/**
* Check if minNumberOfFiles restriction is reached before uploading.
*
* @private
*/
#checkMinNumberOfFiles (files) {
const { minNumberOfFiles } = this.opts.restrictions
if (Object.keys(files).length < minNumberOfFiles) {
throw new RestrictionError(`${this.i18n('youHaveToAtLeastSelectX', { smart_count: minNumberOfFiles })}`)
}
}
/**
* Check if requiredMetaField restriction is met for a specific file.
*
*/
#checkRequiredMetaFieldsOnFile (file) {
const { requiredMetaFields } = this.opts.restrictions
const { hasOwnProperty } = Object.prototype
const errors = []
const missingFields = []
for (let i = 0; i < requiredMetaFields.length; i++) {
if (!hasOwnProperty.call(file.meta, requiredMetaFields[i]) || file.meta[requiredMetaFields[i]] === '') {
const err = new RestrictionError(`${this.i18n('missingRequiredMetaFieldOnFile', { fileName: file.name })}`)
errors.push(err)
missingFields.push(requiredMetaFields[i])
this.#showOrLogErrorAndThrow(err, { file, showInformer: false, throwErr: false })
}
}
this.setFileState(file.id, { missingRequiredMetaFields: missingFields })
return errors
}
/**
* Check if requiredMetaField restriction is met before uploading.
*
*/
#checkRequiredMetaFields (files) {
const errors = Object.keys(files).flatMap((fileID) => {
const file = this.getFile(fileID)
return this.#checkRequiredMetaFieldsOnFile(file)
})
if (errors.length) {
throw new AggregateRestrictionError(errors, `${this.i18n('missingRequiredMetaField')}`)
}
}
/**
* Logs an error, sets Informer message, then throws the error.
* Emits a 'restriction-failed' event if it’s a restriction error
*
* @param {object | string} err — Error object or plain string message
* @param {object} [options]
* @param {boolean} [options.showInformer=true] — Sometimes developer might want to show Informer manually
* @param {object} [options.file=null] — File object used to emit the restriction error
* @param {boolean} [options.throwErr=true] — Errors shouldn’t be thrown, for example, in `upload-error` event
* @private
*/
#showOrLogErrorAndThrow (err, { showInformer = true, file = null, throwErr = true } = {}) {
const message = typeof err === 'object' ? err.message : err
const details = (typeof err === 'object' && err.details) ? err.details : ''
// Restriction errors should be logged, but not as errors,
// as they are expected and shown in the UI.
let logMessageWithDetails = message
if (details) {
logMessageWithDetails += ` ${details}`
}
if (err.isRestriction) {
this.log(logMessageWithDetails)
this.emit('restriction-failed', file, err)
} else {
this.log(logMessageWithDetails, 'error')
}
// Sometimes informer has to be shown manually by the developer,
// for example, in `onBeforeFileAdded`.
if (showInformer) {
this.info({ message, details }, 'error', this.opts.infoTimeout)
}
if (throwErr) {
throw (typeof err === 'object' ? err : new Error(err))
}
}
#assertNewUploadAllowed (file) {
const { allowNewUpload } = this.getState()
if (allowNewUpload === false) {
this.#showOrLogErrorAndThrow(new RestrictionError(this.i18n('noMoreFilesAllowed')), { file })
}
}
checkIfFileAlreadyExists (fileID) {
const { files } = this.getState()
if (files[fileID] && !files[fileID].isGhost) {
return true
}
return false
}
/**
* Create a file state object based on user-provided `addFile()` options.
*
* Note this is extremely side-effectful and should only be done when a file state object
* will be added to state immediately afterward!
*
* The `files` value is passed in because it may be updated by the caller without updating the store.
*/
#checkAndCreateFileStateObject (files, fileDescriptor) {
const fileType = getFileType(fileDescriptor)
const fileName = getFileName(fileType, fileDescriptor)
const fileExtension = getFileNameAndExtension(fileName).extension
const isRemote = Boolean(fileDescriptor.isRemote)
const fileID = generateFileID({
...fileDescriptor,
type: fileType,
})
if (this.checkIfFileAlreadyExists(fileID)) {
const error = new RestrictionError(this.i18n('noDuplicates', { fileName }))
this.#showOrLogErrorAndThrow(error, { file: fileDescriptor })
}
const meta = fileDescriptor.meta || {}
meta.name = fileName
meta.type = fileType
// `null` means the size is unknown.
const size = Number.isFinite(fileDescriptor.data.size) ? fileDescriptor.data.size : null
let newFile = {
source: fileDescriptor.source || '',
id: fileID,
name: fileName,
extension: fileExtension || '',
meta: {
...this.getState().meta,
...meta,
},
type: fileType,
data: fileDescriptor.data,
progress: {
percentage: 0,
bytesUploaded: 0,
bytesTotal: size,
uploadComplete: false,
uploadStarted: null,
},
size,
isRemote,
remote: fileDescriptor.remote || '',
preview: fileDescriptor.preview,
}
const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(newFile, files)
if (onBeforeFileAddedResult === false) {
// Don’t show UI info for this error, as it should be done by the developer
this.#showOrLogErrorAndThrow(new RestrictionError('Cannot add the file because onBeforeFileAdded returned false.'), { showInformer: false, fileDescriptor })
} else if (typeof onBeforeFileAddedResult === 'object' && onBeforeFileAddedResult !== null) {
newFile = onBeforeFileAddedResult
}
try {
const filesArray = Object.keys(files).map(i => files[i])
this.#checkRestrictions(newFile, filesArray)
} catch (err) {
this.#showOrLogErrorAndThrow(err, { file: newFile })
}
return newFile
}
// Schedule an upload if `autoProceed` is enabled.
#startIfAutoProceed () {
if (this.opts.autoProceed && !this.scheduledAutoProceed) {
this.scheduledAutoProceed = setTimeout(() => {
this.scheduledAutoProceed = null
this.upload().catch((err) => {
if (!err.isRestriction) {
this.log(err.stack || err.message || err)
}
})
}, 4)
}
}
/**
* Add a new file to `state.files`. This will run `onBeforeFileAdded`,
* try to guess file type in a clever way, check file against restrictions,
* and start an upload if `autoProceed === true`.
*
* @param {object} file object to add
* @returns {string} id for the added file
*/
addFile (file) {
this.#assertNewUploadAllowed(file)
const { files } = this.getState()
let newFile = this.#checkAndCreateFileStateObject(files, file)
// Users are asked to re-select recovered files without data,
// and to keep the progress, meta and everthing else, we only replace said data
if (files[newFile.id] && files[newFile.id].isGhost) {
newFile = {
...files[newFile.id],
data: file.data,
isGhost: false,
}
this.log(`Replaced the blob in the restored ghost file: ${newFile.name}, ${newFile.id}`)
}
this.setState({
files: {
...files,
[newFile.id]: newFile,
},
})
this.emit('file-added', newFile)
this.emit('files-added', [newFile])
this.log(`Added file: ${newFile.name}, ${newFile.id}, mime type: ${newFile.type}`)
this.#startIfAutoProceed()
return newFile.id
}
/**
* Add multiple files to `state.files`. See the `addFile()` documentation.
*
* 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.
*/
addFiles (fileDescriptors) {
this.#assertNewUploadAllowed()
// create a copy of the files object only once
const files = { ...this.getState().files }
const newFiles = []
const errors = []
for (let i = 0; i < fileDescriptors.length; i++) {
try {
let newFile = this.#checkAndCreateFileStateObject(files, fileDescriptors[i])
// Users are asked to re-select recovered files without data,
// and to keep the progress, meta and everthing else, we only replace said data
if (files[newFile.id] && files[newFile.id].isGhost) {
newFile = {
...files[newFile.id],
data: fileDescriptors[i].data,
isGhost: false,
}
this.log(`Replaced blob in a ghost file: ${newFile.name}, ${newFile.id}`)
}
files[newFile.id] = newFile
newFiles.push(newFile)
} catch (err) {
if (!err.isRestriction) {
errors.push(err)
}
}
}
this.setState({ files })
newFiles.forEach((newFile) => {
this.emit('file-added', newFile)
})
this.emit('files-added', newFiles)
if (newFiles.length > 5) {
this.log(`Added batch of ${newFiles.length} files`)
} else {
Object.keys(newFiles).forEach(fileID => {
this.log(`Added file: ${newFiles[fileID].name}\n id: ${newFiles[fileID].id}\n type: ${newFiles[fileID].type}`)
})
}
if (newFiles.length > 0) {
this.#startIfAutoProceed()
}
if (errors.length > 0) {
let message = 'Multiple errors occurred while adding files:\n'
errors.forEach((subError) => {
message += `\n * ${subError.message}`
})
this.info({
message: this.i18n('addBulkFilesFailed', { smart_count: errors.length }),
details: message,
}, 'error', this.opts.infoTimeout)
if (typeof AggregateError === 'function') {
throw new AggregateError(errors, message)
} else {
const err = new Error(message)
err.errors = errors
throw err
}
}
}
removeFiles (fileIDs, reason) {
const { files, currentUploads } = this.getState()
const updatedFiles = { ...files }
const updatedUploads = { ...currentUploads }
const removedFiles = Object.create(null)
fileIDs.forEach((fileID) => {
if (files[fileID]) {
removedFiles[fileID] = files[fileID]
delete updatedFiles[fileID]
}
})
// Remove files from the `fileIDs` list in each upload.
function fileIsNotRemoved (uploadFileID) {
return removedFiles[uploadFileID] === undefined
}
Object.keys(updatedUploads).forEach((uploadID) => {
const newFileIDs = currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved)
// Remove the upload if no files are associated with it anymore.
if (newFileIDs.length === 0) {
delete updatedUploads[uploadID]
return
}
updatedUploads[uploadID] = {
...currentUploads[uploadID],
fileIDs: newFileIDs,
}
})
const stateUpdate = {
currentUploads: updatedUploads,
files: updatedFiles,
}
// If all files were removed - allow new uploads,
// and clear recoveredState
if (Object.keys(updatedFiles).length === 0) {
stateUpdate.allowNewUpload = true
stateUpdate.error = null
stateUpdate.recoveredState = null
}
this.setState(stateUpdate)
this.calculateTotalProgress()
const removedFileIDs = Object.keys(removedFiles)
removedFileIDs.forEach((fileID) => {
this.emit('file-removed', removedFiles[fileID], reason)
})
if (removedFileIDs.length > 5) {
this.log(`Removed ${removedFileIDs.length} files`)
} else {
this.log(`Removed files: ${removedFileIDs.join(', ')}`)
}
}
removeFile (fileID, reason = null) {
this.removeFiles([fileID], reason)
}
pauseResume (fileID) {
if (!this.getState().capabilities.resumableUploads
|| this.getFile(fileID).uploadComplete) {
return undefined
}
const wasPaused = this.getFile(fileID).isPaused || false
const isPaused = !wasPaused
this.setFileState(fileID, {
isPaused,
})
this.emit('upload-pause', fileID, isPaused)
return isPaused
}
pauseAll () {
const updatedFiles = { ...this.getState().files }
const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
return !updatedFiles[file].progress.uploadComplete
&& updatedFiles[file].progress.uploadStarted
})
inProgressUpdatedFiles.forEach((file) => {
const updatedFile = { ...updatedFiles[file], isPaused: true }
updatedFiles[file] = updatedFile
})
this.setState({ files: updatedFiles })
this.emit('pause-all')
}
resumeAll () {
const updatedFiles = { ...this.getState().files }
const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
return !updatedFiles[file].progress.uploadComplete
&& updatedFiles[file].progress.uploadStarted
})
inProgressUpdatedFiles.forEach((file) => {
const updatedFile = {
...updatedFiles[file],
isPaused: false,
error: null,
}
updatedFiles[file] = updatedFile
})
this.setState({ files: updatedFiles })
this.emit('resume-all')
}
retryAll () {
const updatedFiles = { ...this.getState().files }
const filesToRetry = Object.keys(updatedFiles).filter(file => {
return updatedFiles[file].error
})
filesToRetry.forEach((file) => {
const updatedFile = {
...updatedFiles[file],
isPaused: false,
error: null,
}
updatedFiles[file] = updatedFile
})
this.setState({
files: updatedFiles,
error: null,
})
this.emit('retry-all', filesToRetry)
if (filesToRetry.length === 0) {
return Promise.resolve({
successful: [],
failed: [],
})
}
const uploadID = this.#createUpload(filesToRetry, {
forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
})
return this.#runUpload(uploadID)
}
cancelAll () {
this.emit('cancel-all')
const { files } = this.getState()
const fileIDs = Object.keys(files)
if (fileIDs.length) {
this.removeFiles(fileIDs, 'cancel-all')
}
this.setState({
totalProgress: 0,
error: null,
recoveredState: null,
})
}
retryUpload (fileID) {
this.setFileState(fileID, {
error: null,
isPaused: false,
})
this.emit('upload-retry', fileID)
const uploadID = this.#createUpload([fileID], {
forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
})
return this.#runUpload(uploadID)
}
reset () {
this.cancelAll()
}
logout () {
this.iteratePlugins(plugin => {
if (plugin.provider && plugin.provider.logout) {
plugin.provider.logout()
}
})