-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathUppy.js
1637 lines (1380 loc) · 46.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
/* eslint-disable max-classes-per-file */
/* global AggregateError */
import Translator from '@uppy/utils/lib/Translator'
import ee from 'namespace-emitter'
import { nanoid } from 'nanoid/non-secure'
import throttle from 'lodash/throttle.js'
import DefaultStore from '@uppy/store-default'
import getFileType from '@uppy/utils/lib/getFileType'
import getFileNameAndExtension from '@uppy/utils/lib/getFileNameAndExtension'
import { getSafeFileId } from '@uppy/utils/lib/generateFileID'
import supportsUploadProgress from './supportsUploadProgress.js'
import getFileName from './getFileName.js'
import { justErrorsLogger, debugLogger } from './loggers.js'
import {
Restricter,
defaultOptions as defaultRestrictionOptions,
RestrictionError,
} from './Restricter.js'
import packageJson from '../package.json'
import locale from './locale.js'
/**
* Uppy Core module.
* Manages plugins, state updates, acts as an event bus,
* adds/removes files and metadata.
*/
class Uppy {
static VERSION = packageJson.version
/** @type {Record<string, BasePlugin[]>} */
#plugins = Object.create(null)
#restricter
#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,
allowMultipleUploadBatches: true,
debug: false,
restrictions: defaultRestrictionOptions,
meta: {},
onBeforeFileAdded: (file, files) => !Object.hasOwn(files, file.id),
onBeforeUpload: (files) => files,
store: new 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}`)
this.i18nInit()
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.#restricter = new Restricter(() => this.opts, this.i18n)
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()
}
patchFilesState (filesWithNewState) {
const existingFilesState = this.getState().files
this.setState({
files: {
...existingFilesState,
...Object.fromEntries(Object.entries(filesWithNewState).map(([fileID, newFileState]) => ([
fileID,
{
...existingFilesState[fileID],
...newFileState,
},
]))),
},
})
}
/**
* 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.patchFilesState({ [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(newOpts)
})
}
// 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 => {
updatedFiles[fileID] = {
...files[fileID],
progress: {
...files[fileID].progress, ...defaultProgress,
},
}
})
this.setState({
files: updatedFiles,
totalProgress: 0,
allowNewUpload: true,
error: null,
recoveredState: null,
})
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)
}
getFilesByIds (ids) {
return ids.map((id) => this.getFile(id))
}
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),
}
}
/*
* @constructs
* @param { Error[] } errors
* @param { undefined } file
*/
/*
* @constructs
* @param { RestrictionError } error
*/
#informAndEmit (errors) {
for (const error of errors) {
const { file, isRestriction } = error
if (isRestriction) {
this.emit('restriction-failed', file, error)
} else {
this.emit('error', error)
}
this.log(error, 'warning')
}
const userFacingErrors = errors.filter((error) => error.isUserFacing)
// don't flood the user: only show the first 4 toasts
const maxNumToShow = 4
const firstErrors = userFacingErrors.slice(0, maxNumToShow)
const additionalErrors = userFacingErrors.slice(maxNumToShow)
firstErrors.forEach(({ message, details = '' }) => {
this.info({ message, details }, 'error', this.opts.infoTimeout)
})
if (additionalErrors.length > 0) {
this.info({ message: this.i18n('additionalRestrictionsFailed', { count: additionalErrors.length }) })
}
}
validateRestrictions (file, files = this.getFiles()) {
try {
this.#restricter.validate(files, [file])
} catch (err) {
return err
}
return null
}
#checkRequiredMetaFieldsOnFile (file) {
const { missingFields, error } = this.#restricter.getMissingRequiredMetaFields(file)
if (missingFields.length > 0) {
this.setFileState(file.id, { missingRequiredMetaFields: missingFields })
this.log(error.message)
this.emit('restriction-failed', file, error)
return false
}
return true
}
#checkRequiredMetaFields (files) {
let success = true
for (const file of Object.values(files)) {
if (!this.#checkRequiredMetaFieldsOnFile(file)) {
success = false
}
}
return success
}
#assertNewUploadAllowed (file) {
const { allowNewUpload } = this.getState()
if (allowNewUpload === false) {
const error = new RestrictionError(this.i18n('noMoreFilesAllowed'), { file })
this.#informAndEmit([error])
throw error
}
}
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.
*/
#transformFile (fileDescriptorOrFile) {
// Uppy expects files in { name, type, size, data } format.
// If the actual File object is passed from input[type=file] or drag-drop,
// we normalize it to match Uppy file object
const fileDescriptor = fileDescriptorOrFile instanceof File ? {
name: fileDescriptorOrFile.name,
type: fileDescriptorOrFile.type,
size: fileDescriptorOrFile.size,
data: fileDescriptorOrFile,
} : fileDescriptorOrFile
const fileType = getFileType(fileDescriptor)
const fileName = getFileName(fileType, fileDescriptor)
const fileExtension = getFileNameAndExtension(fileName).extension
const isRemote = Boolean(fileDescriptor.isRemote)
const id = getSafeFileId(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
return {
source: fileDescriptor.source || '',
id,
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,
}
}
// 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)
}
}
#checkAndUpdateFileState (filesToAdd) {
const { files: existingFiles } = this.getState()
// create a copy of the files object only once
const nextFilesState = { ...existingFiles }
const validFilesToAdd = []
const errors = []
for (const fileToAdd of filesToAdd) {
try {
let newFile = this.#transformFile(fileToAdd)
// If a file has been recovered (Golden Retriever), but we were unable to recover its data (probably too large),
// users are asked to re-select these half-recovered files and then this method will be called again.
// In order to keep the progress, meta and everthing else, we keep the existing file,
// but we replace `data`, and we remove `isGhost`, because the file is no longer a ghost now
if (existingFiles[newFile.id]?.isGhost) {
const { isGhost, ...existingFileState } = existingFiles[newFile.id]
newFile = {
...existingFileState,
data: fileToAdd.data,
}
this.log(`Replaced the blob in the restored ghost file: ${newFile.name}, ${newFile.id}`)
}
const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(newFile, nextFilesState)
if (!onBeforeFileAddedResult && this.checkIfFileAlreadyExists(newFile.id)) {
throw new RestrictionError(this.i18n('noDuplicates', { fileName: newFile.name }), { file: fileToAdd })
}
if (onBeforeFileAddedResult === false) {
// Don’t show UI info for this error, as it should be done by the developer
throw new RestrictionError('Cannot add the file because onBeforeFileAdded returned false.', { isUserFacing: false, file: fileToAdd })
} else if (typeof onBeforeFileAddedResult === 'object' && onBeforeFileAddedResult !== null) {
newFile = onBeforeFileAddedResult
}
this.#restricter.validateSingleFile(newFile)
// need to add it to the new local state immediately, so we can use the state to validate the next files too
nextFilesState[newFile.id] = newFile
validFilesToAdd.push(newFile)
} catch (err) {
errors.push(err)
}
}
try {
// need to run this separately because it's much more slow, so if we run it inside the for-loop it will be very slow
// when many files are added
this.#restricter.validateAggregateRestrictions(Object.values(existingFiles), validFilesToAdd)
} catch (err) {
errors.push(err)
// If we have any aggregate error, don't allow adding this batch
return {
nextFilesState: existingFiles,
validFilesToAdd: [],
errors,
}
}
return {
nextFilesState,
validFilesToAdd,
errors,
}
}
/**
* 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 { nextFilesState, validFilesToAdd, errors } = this.#checkAndUpdateFileState([file])
const restrictionErrors = errors.filter((error) => error.isRestriction)
this.#informAndEmit(restrictionErrors)
if (errors.length > 0) throw errors[0]
this.setState({ files: nextFilesState })
const [firstValidFileToAdd] = validFilesToAdd
this.emit('file-added', firstValidFileToAdd)
this.emit('files-added', validFilesToAdd)
this.log(`Added file: ${firstValidFileToAdd.name}, ${firstValidFileToAdd.id}, mime type: ${firstValidFileToAdd.type}`)
this.#startIfAutoProceed()
return firstValidFileToAdd.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()
const { nextFilesState, validFilesToAdd, errors } = this.#checkAndUpdateFileState(fileDescriptors)
const restrictionErrors = errors.filter((error) => error.isRestriction)
this.#informAndEmit(restrictionErrors)
const nonRestrictionErrors = errors.filter((error) => !error.isRestriction)
if (nonRestrictionErrors.length > 0) {
let message = 'Multiple errors occurred while adding files:\n'
nonRestrictionErrors.forEach((subError) => {
message += `\n * ${subError.message}`
})
this.info({
message: this.i18n('addBulkFilesFailed', { smart_count: nonRestrictionErrors.length }),
details: message,
}, 'error', this.opts.infoTimeout)
if (typeof AggregateError === 'function') {
throw new AggregateError(nonRestrictionErrors, message)
} else {
const err = new Error(message)
err.errors = nonRestrictionErrors
throw err
}
}
// OK, we haven't thrown an error, we can start updating state and emitting events now:
this.setState({ files: nextFilesState })
validFilesToAdd.forEach((file) => {
this.emit('file-added', file)
})
this.emit('files-added', validFilesToAdd)
if (validFilesToAdd.length > 5) {
this.log(`Added batch of ${validFilesToAdd.length} files`)
} else {
Object.values(validFilesToAdd).forEach((file) => {
this.log(`Added file: ${file.name}\n id: ${file.id}\n type: ${file.type}`)
})
}
if (validFilesToAdd.length > 0) {
this.#startIfAutoProceed()
}
}
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
}
const { capabilities } = this.getState()
if (newFileIDs.length !== currentUploads[uploadID].fileIDs.length
&& !capabilities.individualCancellation) {
throw new Error('individualCancellation is disabled')
}
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 ({ reason = 'user' } = {}) {
this.emit('cancel-all', { reason })
// Only remove existing uploads if user is canceling
if (reason === 'user') {
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)
}
logout () {
this.iteratePlugins(plugin => {
if (plugin.provider && plugin.provider.logout) {
plugin.provider.logout()
}
})
}
// ___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.
calculateProgress = throttle((file, data) => {
const fileInState = this.getFile(file?.id)
if (file == null || !fileInState) {
this.log(`Not setting progress for a file that has been removed: ${file?.id}`)
return
}
if (fileInState.progress.percentage === 100) {
this.log(`Not setting progress for a file that has been already uploaded: ${file.id}`)
return
}
// bytesTotal may be null or zero; in that case we can't divide by it
const canHavePercentage = Number.isFinite(data.bytesTotal) && data.bytesTotal > 0
this.setFileState(file.id, {
progress: {
...fileInState.progress,
bytesUploaded: data.bytesUploaded,
bytesTotal: data.bytesTotal,
percentage: canHavePercentage
? Math.round((data.bytesUploaded / data.bytesTotal) * 100)
: 0,
},
})
this.calculateTotalProgress()
}, 500, { leading: true, trailing: true })
calculateTotalProgress () {
// calculate total progress, using the number of files currently uploading,
// multiplied by 100 and the summ of individual progress of each file
const files = this.getFiles()
const inProgress = files.filter((file) => {
return file.progress.uploadStarted
|| file.progress.preprocess
|| file.progress.postprocess
})
if (inProgress.length === 0) {
this.emit('progress', 0)
this.setState({ totalProgress: 0 })
return
}
const sizedFiles = inProgress.filter((file) => file.progress.bytesTotal != null)
const unsizedFiles = inProgress.filter((file) => file.progress.bytesTotal == null)
if (sizedFiles.length === 0) {
const progressMax = inProgress.length * 100
const currentProgress = unsizedFiles.reduce((acc, file) => {
return acc + file.progress.percentage
}, 0)
const totalProgress = Math.round((currentProgress / progressMax) * 100)
this.setState({ totalProgress })
return
}
let totalSize = sizedFiles.reduce((acc, file) => {
return acc + file.progress.bytesTotal
}, 0)
const averageSize = totalSize / sizedFiles.length
totalSize += averageSize * unsizedFiles.length
let uploadedSize = 0
sizedFiles.forEach((file) => {
uploadedSize += file.progress.bytesUploaded
})
unsizedFiles.forEach((file) => {
uploadedSize += (averageSize * (file.progress.percentage || 0)) / 100
})
let totalProgress = totalSize === 0
? 0
: Math.round((uploadedSize / totalSize) * 100)
// hot fix, because:
// uploadedSize ended up larger than totalSize, resulting in 1325% total
if (totalProgress > 100) {
totalProgress = 100
}
this.setState({ totalProgress })
this.emit('progress', totalProgress)
}
/**
* Registers listeners for all global actions, like:
* `error`, `file-removed`, `upload-progress`
*/
#addListeners () {
/**
* @param {Error} error
* @param {object} [file]
* @param {object} [response]
*/
const errorHandler = (error, file, response) => {
let errorMsg = error.message || 'Unknown error'
if (error.details) {
errorMsg += ` ${error.details}`
}
this.setState({ error: errorMsg })
if (file != null && file.id in this.getState().files) {
this.setFileState(file.id, {
error: errorMsg,