-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathUppy.ts
2317 lines (2007 loc) · 66.3 KB
/
Uppy.ts
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 type { h } from 'preact'
import Translator from '@uppy/utils/lib/Translator'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore untyped
import ee from 'namespace-emitter'
import { nanoid } from 'nanoid/non-secure'
import throttle from 'lodash/throttle.js'
import DefaultStore, { type Store } 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 type {
UppyFile,
Meta,
Body,
MinimalRequiredUppyFile,
} from '@uppy/utils/lib/UppyFile'
import type { CompanionFile } from '@uppy/utils/lib/CompanionFile'
import type {
CompanionClientProvider,
CompanionClientSearchProvider,
} from '@uppy/utils/lib/CompanionClientProvider'
import type {
FileProgressNotStarted,
FileProgressStarted,
} from '@uppy/utils/lib/FileProgress'
import type {
Locale,
I18n,
OptionalPluralizeLocale,
} from '@uppy/utils/lib/Translator'
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'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore We don't want TS to generate types for the package.json
import packageJson from '../package.json'
import locale from './locale.js'
import type BasePlugin from './BasePlugin.js'
import type { Restrictions, ValidateableFile } from './Restricter.js'
type Processor = (
fileIDs: string[],
uploadID: string,
) => Promise<unknown> | void
type LogLevel = 'info' | 'warning' | 'error' | 'success'
export type UnknownPlugin<
M extends Meta,
B extends Body,
PluginState extends Record<string, unknown> = Record<string, unknown>,
> = BasePlugin<any, M, B, PluginState>
/**
* ids are always `string`s, except the root folder's id can be `null`
*/
export type PartialTreeId = string | null
export type PartialTreeStatusFile = 'checked' | 'unchecked'
export type PartialTreeStatus = PartialTreeStatusFile | 'partial'
export type PartialTreeFile = {
type: 'file'
id: string
/**
* There exist two types of restrictions:
* - individual restrictions (`allowedFileTypes`, `minFileSize`, `maxFileSize`), and
* - aggregate restrictions (`maxNumberOfFiles`, `maxTotalFileSize`).
*
* `.restrictionError` reports whether this file passes individual restrictions.
*
*/
restrictionError: string | null
status: PartialTreeStatusFile
parentId: PartialTreeId
data: CompanionFile
}
export type PartialTreeFolderNode = {
type: 'folder'
id: string
/**
* Consider `(.nextPagePath, .cached)` a composite key that can represent 4 states:
* - `{ cached: true, nextPagePath: null }` - we fetched all pages in this folder
* - `{ cached: true, nextPagePath: 'smth' }` - we fetched 1st page, and there are still pages left to fetch in this folder
* - `{ cached: false, nextPagePath: null }` - we didn't fetch the 1st page in this folder
* - `{ cached: false, nextPagePath: 'someString' }` - ❌ CAN'T HAPPEN ❌
*/
cached: boolean
nextPagePath: PartialTreeId
status: PartialTreeStatus
parentId: PartialTreeId
data: CompanionFile
}
export type PartialTreeFolderRoot = {
type: 'root'
id: PartialTreeId
cached: boolean
nextPagePath: PartialTreeId
}
export type PartialTreeFolder = PartialTreeFolderNode | PartialTreeFolderRoot
/**
* PartialTree has the following structure.
*
* FolderRoot
* ┌─────┴─────┐
* FolderNode File
* ┌─────┴────┐
* File File
*
* Root folder is called `PartialTreeFolderRoot`,
* all other folders are called `PartialTreeFolderNode`, because they are "internal nodes".
*
* It's possible for `PartialTreeFolderNode` to be a leaf node if it doesn't contain any files.
*/
export type PartialTree = (PartialTreeFile | PartialTreeFolder)[]
export type UnknownProviderPluginState = {
authenticated: boolean | undefined
didFirstRender: boolean
searchString: string
loading: boolean | string
partialTree: PartialTree
currentFolderId: PartialTreeId
username: string | null
}
export interface AsyncStore {
getItem: (key: string) => Promise<string | null>
setItem: (key: string, value: string) => Promise<void>
removeItem: (key: string) => Promise<void>
}
/**
* This is a base for a provider that does not necessarily use the Companion-assisted OAuth2 flow
*/
export interface BaseProviderPlugin {
title: string
icon: () => h.JSX.Element
storage: AsyncStore
}
/*
* UnknownProviderPlugin can be any Companion plugin (such as Google Drive)
* that uses the Companion-assisted OAuth flow.
* As the plugins are passed around throughout Uppy we need a generic type for this.
* It may seems like duplication, but this type safe. Changing the type of `storage`
* will error in the `Provider` class of @uppy/companion-client and vice versa.
*
* Note that this is the *plugin* class, not a version of the `Provider` class.
* `Provider` does operate on Companion plugins with `uppy.getPlugin()`.
*/
export type UnknownProviderPlugin<
M extends Meta,
B extends Body,
> = UnknownPlugin<M, B, UnknownProviderPluginState> &
BaseProviderPlugin & {
rootFolderId: string | null
files: UppyFile<M, B>[]
provider: CompanionClientProvider
}
/*
* UnknownSearchProviderPlugin can be any search Companion plugin (such as Unsplash).
* As the plugins are passed around throughout Uppy we need a generic type for this.
* It may seems like duplication, but this type safe. Changing the type of `title`
* will error in the `SearchProvider` class of @uppy/companion-client and vice versa.
*
* Note that this is the *plugin* class, not a version of the `SearchProvider` class.
* `SearchProvider` does operate on Companion plugins with `uppy.getPlugin()`.
*/
export type UnknownSearchProviderPluginState = {
isInputMode: boolean
} & Pick<
UnknownProviderPluginState,
'loading' | 'searchString' | 'partialTree' | 'currentFolderId'
>
export type UnknownSearchProviderPlugin<
M extends Meta,
B extends Body,
> = UnknownPlugin<M, B, UnknownSearchProviderPluginState> &
BaseProviderPlugin & {
provider: CompanionClientSearchProvider
}
export interface UploadResult<M extends Meta, B extends Body> {
successful?: UppyFile<M, B>[]
failed?: UppyFile<M, B>[]
uploadID?: string
[key: string]: unknown
}
interface CurrentUpload<M extends Meta, B extends Body> {
fileIDs: string[]
step: number
result: UploadResult<M, B>
}
// TODO: can we use namespaces in other plugins to populate this?
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Plugins extends Record<string, Record<string, unknown> | undefined> {}
export interface State<M extends Meta, B extends Body>
extends Record<string, unknown> {
meta: M
capabilities: {
uploadProgress: boolean
individualCancellation: boolean
resumableUploads: boolean
isMobileDevice?: boolean
darkMode?: boolean
}
currentUploads: Record<string, CurrentUpload<M, B>>
allowNewUpload: boolean
recoveredState: null | Required<Pick<State<M, B>, 'files' | 'currentUploads'>>
error: string | null
files: {
[key: string]: UppyFile<M, B>
}
info: Array<{
isHidden?: boolean
type: LogLevel
message: string
details?: string | Record<string, string> | null
}>
plugins: Plugins
totalProgress: number
companion?: Record<string, string>
}
export interface UppyOptions<M extends Meta, B extends Body> {
id?: string
autoProceed?: boolean
/**
* @deprecated Use allowMultipleUploadBatches
*/
allowMultipleUploads?: boolean
allowMultipleUploadBatches?: boolean
logger?: typeof debugLogger
debug?: boolean
restrictions: Restrictions
meta?: M
onBeforeFileAdded?: (
currentFile: UppyFile<M, B>,
files: { [key: string]: UppyFile<M, B> },
) => UppyFile<M, B> | boolean | undefined
onBeforeUpload?: (files: {
[key: string]: UppyFile<M, B>
}) => { [key: string]: UppyFile<M, B> } | boolean
locale?: Locale
store?: Store<State<M, B>>
infoTimeout?: number
}
export interface UppyOptionsWithOptionalRestrictions<
M extends Meta,
B extends Body,
> extends Omit<UppyOptions<M, B>, 'restrictions'> {
restrictions?: Partial<Restrictions>
}
// The user facing type for UppyOptions used in uppy.setOptions()
type MinimalRequiredOptions<M extends Meta, B extends Body> = Partial<
Omit<UppyOptions<M, B>, 'locale' | 'meta' | 'restrictions'> & {
locale: OptionalPluralizeLocale
meta: Partial<M>
restrictions: Partial<Restrictions>
}
>
export type NonNullableUppyOptions<M extends Meta, B extends Body> = Required<
UppyOptions<M, B>
>
export interface _UppyEventMap<M extends Meta, B extends Body> {
'back-online': () => void
'cancel-all': () => void
complete: (result: UploadResult<M, B>) => void
error: (
error: { name: string; message: string; details?: string },
file?: UppyFile<M, B>,
response?: UppyFile<M, B>['response'],
) => void
'file-added': (file: UppyFile<M, B>) => void
'file-removed': (file: UppyFile<M, B>) => void
'files-added': (files: UppyFile<M, B>[]) => void
'info-hidden': () => void
'info-visible': () => void
'is-offline': () => void
'is-online': () => void
'pause-all': () => void
'plugin-added': (plugin: UnknownPlugin<any, any>) => void
'plugin-remove': (plugin: UnknownPlugin<any, any>) => void
'postprocess-complete': (
file: UppyFile<M, B> | undefined,
progress?: NonNullable<FileProgressStarted['preprocess']>,
) => void
'postprocess-progress': (
file: UppyFile<M, B> | undefined,
progress: NonNullable<FileProgressStarted['postprocess']>,
) => void
'preprocess-complete': (
file: UppyFile<M, B> | undefined,
progress?: NonNullable<FileProgressStarted['preprocess']>,
) => void
'preprocess-progress': (
file: UppyFile<M, B> | undefined,
progress: NonNullable<FileProgressStarted['preprocess']>,
) => void
progress: (progress: number) => void
restored: (pluginData: any) => void
'restore-confirmed': () => void
'restore-canceled': () => void
'restriction-failed': (file: UppyFile<M, B> | undefined, error: Error) => void
'resume-all': () => void
'retry-all': (files: UppyFile<M, B>[]) => void
'state-update': (
prevState: State<M, B>,
nextState: State<M, B>,
patch?: Partial<State<M, B>>,
) => void
upload: (uploadID: string, files: UppyFile<M, B>[]) => void
'upload-error': (
file: UppyFile<M, B> | undefined,
error: { name: string; message: string; details?: string },
response?:
| Omit<NonNullable<UppyFile<M, B>['response']>, 'uploadURL'>
| undefined,
) => void
'upload-pause': (file: UppyFile<M, B> | undefined, isPaused: boolean) => void
'upload-progress': (
file: UppyFile<M, B> | undefined,
progress: FileProgressStarted,
) => void
'upload-retry': (file: UppyFile<M, B>) => void
'upload-stalled': (
error: { message: string; details?: string },
files: UppyFile<M, B>[],
) => void
'upload-success': (
file: UppyFile<M, B> | undefined,
response: NonNullable<UppyFile<M, B>['response']>,
) => void
}
export interface UppyEventMap<M extends Meta, B extends Body>
extends _UppyEventMap<M, B> {
'upload-start': (files: UppyFile<M, B>[]) => void
}
/** `OmitFirstArg<typeof someArray>` is the type of the returned value of `someArray.slice(1)`. */
type OmitFirstArg<T> = T extends [any, ...infer U] ? U : never
const defaultUploadState = {
totalProgress: 0,
allowNewUpload: true,
error: null,
recoveredState: null,
}
/**
* Uppy Core module.
* Manages plugins, state updates, acts as an event bus,
* adds/removes files and metadata.
*/
export class Uppy<
M extends Meta = Meta,
B extends Body = Record<string, never>,
> {
static VERSION = packageJson.version
#plugins: Record<string, UnknownPlugin<M, B>[]> = Object.create(null)
#restricter
#storeUnsubscribe
#emitter = ee()
#preProcessors: Set<Processor> = new Set()
#uploaders: Set<Processor> = new Set()
#postProcessors: Set<Processor> = new Set()
defaultLocale: Locale
locale!: Locale
// The user optionally passes in options, but we set defaults for missing options.
// We consider all options present after the contructor has run.
opts: NonNullableUppyOptions<M, B>
store: NonNullableUppyOptions<M, B>['store']
// Warning: do not use this from a plugin, as it will cause the plugins' translations to be missing
i18n!: I18n
i18nArray!: Translator['translateArray']
scheduledAutoProceed: ReturnType<typeof setTimeout> | null = null
wasOffline = false
/**
* Instantiate Uppy
*/
constructor(opts?: UppyOptionsWithOptionalRestrictions<M, B>) {
this.defaultLocale = locale as any as Locale
const defaultOptions: UppyOptions<Record<string, unknown>, B> = {
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,
}
const merged = { ...defaultOptions, ...opts } as Omit<
NonNullableUppyOptions<M, B>,
'restrictions'
>
// Merge default options with the ones set by user,
// making sure to merge restrictions too
this.opts = {
...merged,
restrictions: {
...(defaultOptions.restrictions as 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${Uppy.VERSION}`)
this.i18nInit()
this.store = this.opts.store
this.setState({
...defaultUploadState,
plugins: {},
files: {},
currentUploads: {},
capabilities: {
uploadProgress: supportsUploadProgress(),
individualCancellation: true,
resumableUploads: false,
},
meta: { ...this.opts.meta },
info: [],
})
this.#restricter = new Restricter<M, B>(
() => 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') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore Mutating the global object for debug purposes
window[this.opts.id] = this
}
this.#addListeners()
}
emit<T extends keyof UppyEventMap<M, B>>(
event: T,
...args: Parameters<UppyEventMap<M, B>[T]>
): void {
this.#emitter.emit(event, ...args)
}
on<K extends keyof UppyEventMap<M, B>>(
event: K,
callback: UppyEventMap<M, B>[K],
): this {
this.#emitter.on(event, callback)
return this
}
once<K extends keyof UppyEventMap<M, B>>(
event: K,
callback: UppyEventMap<M, B>[K],
): this {
this.#emitter.once(event, callback)
return this
}
off<K extends keyof UppyEventMap<M, B>>(
event: K,
callback: UppyEventMap<M, B>[K],
): this {
this.#emitter.off(event, callback)
return this
}
/**
* Iterate on all plugins and run `update` on them.
* Called each time state changes.
*
*/
updateAll(state: Partial<State<M, B>>): void {
this.iteratePlugins((plugin: UnknownPlugin<M, B>) => {
plugin.update(state)
})
}
/**
* Updates state with a patch
*/
setState(patch?: Partial<State<M, B>>): void {
this.store.setState(patch)
}
/**
* Returns current state.
*/
getState(): State<M, B> {
return this.store.getState()
}
patchFilesState(filesWithNewState: {
[id: string]: Partial<UppyFile<M, B>>
}): void {
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: string, state: Partial<UppyFile<M, B>>): void {
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(): void {
const onMissingKey = (key: string): void =>
this.log(`Missing i18n string: ${key}`, 'error')
const translator = new Translator([this.defaultLocale, this.opts.locale], {
onMissingKey,
})
this.i18n = translator.translate.bind(translator)
this.i18nArray = translator.translateArray.bind(translator)
this.locale = translator.locale
}
setOptions(newOpts: MinimalRequiredOptions<M, B>): void {
this.opts = {
...this.opts,
...(newOpts as UppyOptions<M, B>),
restrictions: {
...this.opts.restrictions,
...(newOpts?.restrictions as 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(undefined) // so that UI re-renders with new options
}
resetProgress(): void {
const defaultProgress: Omit<FileProgressNotStarted, 'bytesTotal'> = {
percentage: 0,
bytesUploaded: false,
uploadComplete: false,
uploadStarted: null,
}
const files = { ...this.getState().files }
const updatedFiles: State<M, B>['files'] = Object.create(null)
Object.keys(files).forEach((fileID) => {
updatedFiles[fileID] = {
...files[fileID],
progress: {
...files[fileID].progress,
...defaultProgress,
},
// @ts-expect-error these typed are inserted
// into the namespace in their respective packages
// but core isn't ware of those
tus: undefined,
transloadit: undefined,
}
})
this.setState({ files: updatedFiles, ...defaultUploadState })
}
clear(): void {
const { capabilities, currentUploads } = this.getState()
if (
Object.keys(currentUploads).length > 0 &&
!capabilities.individualCancellation
) {
throw new Error(
'The installed uploader plugin does not allow removing files during an upload.',
)
}
this.setState({ ...defaultUploadState, files: {} })
}
addPreProcessor(fn: Processor): void {
this.#preProcessors.add(fn)
}
removePreProcessor(fn: Processor): boolean {
return this.#preProcessors.delete(fn)
}
addPostProcessor(fn: Processor): void {
this.#postProcessors.add(fn)
}
removePostProcessor(fn: Processor): boolean {
return this.#postProcessors.delete(fn)
}
addUploader(fn: Processor): void {
this.#uploaders.add(fn)
}
removeUploader(fn: Processor): boolean {
return this.#uploaders.delete(fn)
}
setMeta(data: Partial<M>): void {
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: string, data: State<M, B>['meta']): void {
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.
*/
getFile(fileID: string): UppyFile<M, B> {
return this.getState().files[fileID]
}
/**
* Get all files in an array.
*/
getFiles(): UppyFile<M, B>[] {
const { files } = this.getState()
return Object.values(files)
}
getFilesByIds(ids: string[]): UppyFile<M, B>[] {
return ids.map((id) => this.getFile(id))
}
getObjectOfFilesPerState(): {
newFiles: UppyFile<M, B>[]
startedFiles: UppyFile<M, B>[]
uploadStartedFiles: UppyFile<M, B>[]
pausedFiles: UppyFile<M, B>[]
completeFiles: UppyFile<M, B>[]
erroredFiles: UppyFile<M, B>[]
inProgressFiles: UppyFile<M, B>[]
inProgressNotPausedFiles: UppyFile<M, B>[]
processingFiles: UppyFile<M, B>[]
isUploadStarted: boolean
isAllComplete: boolean
isAllErrored: boolean
isAllPaused: boolean
isUploadInProgress: boolean
isSomeGhost: boolean
} {
const { files: filesObject, totalProgress, error } = this.getState()
const files = Object.values(filesObject)
const inProgressFiles: UppyFile<M, B>[] = []
const newFiles: UppyFile<M, B>[] = []
const startedFiles: UppyFile<M, B>[] = []
const uploadStartedFiles: UppyFile<M, B>[] = []
const pausedFiles: UppyFile<M, B>[] = []
const completeFiles: UppyFile<M, B>[] = []
const erroredFiles: UppyFile<M, B>[] = []
const inProgressNotPausedFiles: UppyFile<M, B>[] = []
const processingFiles: UppyFile<M, B>[] = []
for (const file of files) {
const { progress } = file
if (!progress.uploadComplete && progress.uploadStarted) {
inProgressFiles.push(file)
if (!file.isPaused) {
inProgressNotPausedFiles.push(file)
}
}
if (!progress.uploadStarted) {
newFiles.push(file)
}
if (
progress.uploadStarted ||
progress.preprocess ||
progress.postprocess
) {
startedFiles.push(file)
}
if (progress.uploadStarted) {
uploadStartedFiles.push(file)
}
if (file.isPaused) {
pausedFiles.push(file)
}
if (progress.uploadComplete) {
completeFiles.push(file)
}
if (file.error) {
erroredFiles.push(file)
}
if (progress.preprocess || progress.postprocess) {
processingFiles.push(file)
}
}
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),
}
}
#informAndEmit(
errors: {
name: string
message: string
isUserFacing?: boolean
details?: string
isRestriction?: boolean
file?: UppyFile<M, B>
}[],
): void {
for (const error of errors) {
if (error.isRestriction) {
this.emit(
'restriction-failed',
error.file,
error as RestrictionError<M, B>,
)
} else {
this.emit('error', error, error.file)
}
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: ValidateableFile<M, B>,
files: ValidateableFile<M, B>[] = this.getFiles(),
): RestrictionError<M, B> | null {
try {
this.#restricter.validate(files, [file])
} catch (err) {
return err as any
}
return null
}
validateSingleFile(file: ValidateableFile<M, B>): string | null {
try {
this.#restricter.validateSingleFile(file)
} catch (err) {
return err.message
}
return null
}
validateAggregateRestrictions(
files: ValidateableFile<M, B>[],
): string | null {
const existingFiles = this.getFiles()
try {
this.#restricter.validateAggregateRestrictions(existingFiles, files)
} catch (err) {
return err.message
}
return null
}
#checkRequiredMetaFieldsOnFile(file: UppyFile<M, B>): boolean {
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: State<M, B>['files']): boolean {
let success = true
for (const file of Object.values(files)) {
if (!this.#checkRequiredMetaFieldsOnFile(file)) {
success = false
}
}
return success
}
#assertNewUploadAllowed(file?: UppyFile<M, B>): void {
const { allowNewUpload } = this.getState()
if (allowNewUpload === false) {
const error = new RestrictionError<M, B>(
this.i18n('noMoreFilesAllowed'),
{
file,
},
)
this.#informAndEmit([error])
throw error
}
}
checkIfFileAlreadyExists(fileID: string): boolean {
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: File | UppyFile<M, B>): UppyFile<M, B> {
// 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 file = (
fileDescriptorOrFile instanceof File ?
{
name: fileDescriptorOrFile.name,
type: fileDescriptorOrFile.type,
size: fileDescriptorOrFile.size,
data: fileDescriptorOrFile,
}
: fileDescriptorOrFile) as UppyFile<M, B>
const fileType = getFileType(file)
const fileName = getFileName(fileType, file)
const fileExtension = getFileNameAndExtension(fileName).extension
const id = getSafeFileId(file, this.getID())
const meta = file.meta || {}
meta.name = fileName
meta.type = fileType
// `null` means the size is unknown.
const size =
Number.isFinite(file.data.size) ? file.data.size : (null as never)
return {
source: file.source || '',
id,
name: fileName,