Uppy.ts 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156
  1. /* eslint-disable max-classes-per-file */
  2. /* global AggregateError */
  3. import Translator from '@uppy/utils/lib/Translator'
  4. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5. // @ts-ignore untyped
  6. import ee from 'namespace-emitter'
  7. import { nanoid } from 'nanoid/non-secure'
  8. import throttle from 'lodash/throttle.js'
  9. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  10. // @ts-ignore store-default types not always available on that branch
  11. import DefaultStore from '@uppy/store-default'
  12. import getFileType from '@uppy/utils/lib/getFileType'
  13. import getFileNameAndExtension from '@uppy/utils/lib/getFileNameAndExtension'
  14. import { getSafeFileId } from '@uppy/utils/lib/generateFileID'
  15. import type { UppyFile, Meta, Body } from '@uppy/utils/lib/UppyFile'
  16. import type {
  17. FileProgressNotStarted,
  18. FileProgressStarted,
  19. } from '@uppy/utils/lib/FileProgress'
  20. import type {
  21. Locale,
  22. I18n,
  23. OptionalPluralizeLocale,
  24. } from '@uppy/utils/lib/Translator'
  25. import supportsUploadProgress from './supportsUploadProgress.ts'
  26. import getFileName from './getFileName.ts'
  27. import { justErrorsLogger, debugLogger } from './loggers.ts'
  28. import {
  29. Restricter,
  30. defaultOptions as defaultRestrictionOptions,
  31. RestrictionError,
  32. } from './Restricter.ts'
  33. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  34. // @ts-ignore We don't want TS to generate types for the package.json
  35. import packageJson from '../package.json'
  36. import locale from './locale.ts'
  37. import type BasePlugin from './BasePlugin.ts'
  38. import type UIPlugin from './UIPlugin.ts'
  39. import type { Restrictions } from './Restricter.ts'
  40. type Processor = (fileIDs: string[], uploadID: string) => Promise<void> | void
  41. type FileRemoveReason = 'user' | 'cancel-all'
  42. type LogLevel = 'info' | 'warning' | 'error' | 'success'
  43. type UnknownPlugin<M extends Meta, B extends Body> = InstanceType<
  44. typeof BasePlugin<any, M, B> | typeof UIPlugin<any, M, B>
  45. >
  46. type UnknownProviderPlugin<M extends Meta, B extends Body> = UnknownPlugin<
  47. M,
  48. B
  49. > & {
  50. provider: {
  51. logout: () => void
  52. }
  53. }
  54. // The user facing type for UppyFile used in uppy.addFile() and uppy.setOptions()
  55. export type MinimalRequiredUppyFile<M extends Meta, B extends Body> = Required<
  56. Pick<UppyFile<M, B>, 'name' | 'data' | 'type' | 'source'>
  57. > &
  58. Partial<
  59. Omit<UppyFile<M, B>, 'name' | 'data' | 'type' | 'source' | 'meta'>
  60. // We want to omit the 'meta' from UppyFile because of internal metadata
  61. // (see InternalMetadata in `UppyFile.ts`), as when adding a new file
  62. // that is not required.
  63. > & { meta?: M }
  64. interface UploadResult<M extends Meta, B extends Body> {
  65. successful?: UppyFile<M, B>[]
  66. failed?: UppyFile<M, B>[]
  67. uploadID?: string
  68. [key: string]: unknown
  69. }
  70. interface CurrentUpload<M extends Meta, B extends Body> {
  71. fileIDs: string[]
  72. step: number
  73. result: UploadResult<M, B>
  74. }
  75. // TODO: can we use namespaces in other plugins to populate this?
  76. // eslint-disable-next-line @typescript-eslint/no-empty-interface
  77. interface Plugins extends Record<string, Record<string, unknown> | undefined> {}
  78. export interface State<M extends Meta, B extends Body>
  79. extends Record<string, unknown> {
  80. meta: M
  81. capabilities: {
  82. uploadProgress: boolean
  83. individualCancellation: boolean
  84. resumableUploads: boolean
  85. }
  86. currentUploads: Record<string, CurrentUpload<M, B>>
  87. allowNewUpload: boolean
  88. recoveredState: null | State<M, B>
  89. error: string | null
  90. files: {
  91. [key: string]: UppyFile<M, B>
  92. }
  93. info: Array<{
  94. isHidden?: boolean
  95. type: LogLevel
  96. message: string
  97. details?: string | Record<string, string> | null
  98. }>
  99. plugins: Plugins
  100. totalProgress: number
  101. }
  102. export interface UppyOptions<M extends Meta, B extends Body> {
  103. id?: string
  104. autoProceed?: boolean
  105. /**
  106. * @deprecated Use allowMultipleUploadBatches
  107. */
  108. allowMultipleUploads?: boolean
  109. allowMultipleUploadBatches?: boolean
  110. logger?: typeof debugLogger
  111. debug?: boolean
  112. restrictions: Restrictions
  113. meta?: M
  114. onBeforeFileAdded?: (
  115. currentFile: UppyFile<M, B>,
  116. files: { [key: string]: UppyFile<M, B> },
  117. ) => UppyFile<M, B> | boolean | undefined
  118. onBeforeUpload?: (files: {
  119. [key: string]: UppyFile<M, B>
  120. }) => { [key: string]: UppyFile<M, B> } | boolean
  121. locale?: Locale
  122. // TODO: add <State<M, B>> when landing on `4.x`
  123. store?: DefaultStore
  124. infoTimeout?: number
  125. }
  126. export interface UppyOptionsWithOptionalRestrictions<
  127. M extends Meta,
  128. B extends Body,
  129. > extends Omit<UppyOptions<M, B>, 'restrictions'> {
  130. restrictions?: Partial<Restrictions>
  131. }
  132. // The user facing type for UppyOptions used in uppy.setOptions()
  133. type MinimalRequiredOptions<M extends Meta, B extends Body> = Partial<
  134. Omit<UppyOptions<M, B>, 'locale' | 'meta' | 'restrictions'> & {
  135. locale: OptionalPluralizeLocale
  136. meta: Partial<M>
  137. restrictions: Partial<Restrictions>
  138. }
  139. >
  140. export type NonNullableUppyOptions<M extends Meta, B extends Body> = Required<
  141. UppyOptions<M, B>
  142. >
  143. type GenericEventCallback = () => void
  144. type FileAddedCallback<M extends Meta, B extends Body> = (
  145. file: UppyFile<M, B>,
  146. ) => void
  147. type FilesAddedCallback<M extends Meta, B extends Body> = (
  148. files: UppyFile<M, B>[],
  149. ) => void
  150. type FileRemovedCallback<M extends Meta, B extends Body> = (
  151. file: UppyFile<M, B>,
  152. reason?: FileRemoveReason,
  153. ) => void
  154. type UploadCallback = (data: { id: string; fileIDs: string[] }) => void
  155. type ProgressCallback = (progress: number) => void
  156. type PreProcessProgressCallback<M extends Meta, B extends Body> = (
  157. file: UppyFile<M, B> | undefined,
  158. progress: NonNullable<FileProgressStarted['preprocess']>,
  159. ) => void
  160. type PostProcessProgressCallback<M extends Meta, B extends Body> = (
  161. file: UppyFile<M, B> | undefined,
  162. progress: NonNullable<FileProgressStarted['postprocess']>,
  163. ) => void
  164. type ProcessCompleteCallback<M extends Meta, B extends Body> = (
  165. file: UppyFile<M, B> | undefined,
  166. progress?: NonNullable<FileProgressStarted['preprocess']>,
  167. ) => void
  168. type UploadPauseCallback<M extends Meta, B extends Body> = (
  169. fileID: UppyFile<M, B>['id'] | undefined,
  170. isPaused: boolean,
  171. ) => void
  172. type UploadStartCallback<M extends Meta, B extends Body> = (
  173. files: UppyFile<M, B>[],
  174. ) => void
  175. type UploadStartedCallback<M extends Meta, B extends Body> = (
  176. file: UppyFile<M, B>,
  177. ) => void
  178. type UploadProgressCallback<M extends Meta, B extends Body> = (
  179. file: UppyFile<M, B> | undefined,
  180. progress: FileProgressStarted,
  181. ) => void
  182. type UploadSuccessCallback<M extends Meta, B extends Body> = (
  183. file: UppyFile<M, B> | undefined,
  184. response: NonNullable<UppyFile<M, B>['response']>,
  185. ) => void
  186. type UploadCompleteCallback<M extends Meta, B extends Body> = (
  187. result: UploadResult<M, B>,
  188. ) => void
  189. type ErrorCallback<M extends Meta, B extends Body> = (
  190. error: { message?: string; details?: string },
  191. file?: UppyFile<M, B>,
  192. response?: UppyFile<M, B>['response'],
  193. ) => void
  194. type UploadErrorCallback<M extends Meta, B extends Body> = (
  195. file: UppyFile<M, B> | undefined,
  196. error: { message: string; details?: string },
  197. response: UppyFile<M, B>['response'] | undefined,
  198. ) => void
  199. type UploadStalledCallback<M extends Meta, B extends Body> = (
  200. error: { message: string; details?: string },
  201. files: UppyFile<M, B>[],
  202. ) => void
  203. type UploadRetryCallback = (fileID: string) => void
  204. type RetryAllCallback = (fileIDs: string[]) => void
  205. type RestrictionFailedCallback<M extends Meta, B extends Body> = (
  206. file: UppyFile<M, B> | undefined,
  207. error: Error,
  208. ) => void
  209. type StateUpdateCallback<M extends Meta, B extends Body> = (
  210. prevState: State<M, B>,
  211. nextState: State<M, B>,
  212. patch?: Partial<State<M, B>>,
  213. ) => void
  214. type CancelAllCallback = (reason: { reason?: FileRemoveReason }) => void
  215. type PluginCallback = (plugin: UnknownPlugin<any, any>) => void
  216. export interface _UppyEventMap<M extends Meta, B extends Body> {
  217. 'back-online': GenericEventCallback
  218. 'cancel-all': CancelAllCallback
  219. complete: UploadCompleteCallback<M, B>
  220. error: ErrorCallback<M, B>
  221. 'file-added': FileAddedCallback<M, B>
  222. 'file-removed': FileRemovedCallback<M, B>
  223. 'files-added': FilesAddedCallback<M, B>
  224. 'info-hidden': GenericEventCallback
  225. 'info-visible': GenericEventCallback
  226. 'is-offline': GenericEventCallback
  227. 'is-online': GenericEventCallback
  228. 'pause-all': GenericEventCallback
  229. 'plugin-added': PluginCallback
  230. 'plugin-remove': PluginCallback
  231. 'postprocess-complete': ProcessCompleteCallback<M, B>
  232. 'postprocess-progress': PostProcessProgressCallback<M, B>
  233. 'preprocess-complete': ProcessCompleteCallback<M, B>
  234. 'preprocess-progress': PreProcessProgressCallback<M, B>
  235. progress: ProgressCallback
  236. 'reset-progress': GenericEventCallback
  237. restored: GenericEventCallback
  238. 'restore-confirmed': GenericEventCallback
  239. 'restriction-failed': RestrictionFailedCallback<M, B>
  240. 'resume-all': GenericEventCallback
  241. 'retry-all': RetryAllCallback
  242. 'state-update': StateUpdateCallback<M, B>
  243. upload: UploadCallback
  244. 'upload-error': UploadErrorCallback<M, B>
  245. 'upload-pause': UploadPauseCallback<M, B>
  246. 'upload-progress': UploadProgressCallback<M, B>
  247. 'upload-retry': UploadRetryCallback
  248. 'upload-stalled': UploadStalledCallback<M, B>
  249. 'upload-success': UploadSuccessCallback<M, B>
  250. }
  251. /** @deprecated */
  252. export interface DeprecatedUppyEventMap<M extends Meta, B extends Body> {
  253. 'upload-start': UploadStartCallback<M, B>
  254. 'upload-started': UploadStartedCallback<M, B>
  255. }
  256. export interface UppyEventMap<M extends Meta, B extends Body>
  257. extends _UppyEventMap<M, B>,
  258. DeprecatedUppyEventMap<M, B> {}
  259. const defaultUploadState = {
  260. totalProgress: 0,
  261. allowNewUpload: true,
  262. error: null,
  263. recoveredState: null,
  264. }
  265. /**
  266. * Uppy Core module.
  267. * Manages plugins, state updates, acts as an event bus,
  268. * adds/removes files and metadata.
  269. */
  270. export class Uppy<M extends Meta, B extends Body> {
  271. static VERSION = packageJson.version
  272. #plugins: Record<string, UnknownPlugin<M, B>[]> = Object.create(null)
  273. #restricter
  274. #storeUnsubscribe
  275. #emitter = ee()
  276. #preProcessors: Set<Processor> = new Set()
  277. #uploaders: Set<Processor> = new Set()
  278. #postProcessors: Set<Processor> = new Set()
  279. defaultLocale: Locale
  280. locale: Locale
  281. // The user optionally passes in options, but we set defaults for missing options.
  282. // We consider all options present after the contructor has run.
  283. opts: NonNullableUppyOptions<M, B>
  284. store: NonNullableUppyOptions<M, B>['store']
  285. i18n: I18n
  286. i18nArray: Translator['translateArray']
  287. scheduledAutoProceed: ReturnType<typeof setTimeout> | null = null
  288. wasOffline = false
  289. /**
  290. * Instantiate Uppy
  291. */
  292. constructor(opts?: UppyOptionsWithOptionalRestrictions<M, B>) {
  293. this.defaultLocale = locale as any as Locale
  294. const defaultOptions: UppyOptions<Record<string, unknown>, B> = {
  295. id: 'uppy',
  296. autoProceed: false,
  297. allowMultipleUploadBatches: true,
  298. debug: false,
  299. restrictions: defaultRestrictionOptions,
  300. meta: {},
  301. onBeforeFileAdded: (file, files) => !Object.hasOwn(files, file.id),
  302. onBeforeUpload: (files) => files,
  303. store: new DefaultStore(),
  304. logger: justErrorsLogger,
  305. infoTimeout: 5000,
  306. }
  307. const merged = { ...defaultOptions, ...opts } as Omit<
  308. NonNullableUppyOptions<M, B>,
  309. 'restrictions'
  310. >
  311. // Merge default options with the ones set by user,
  312. // making sure to merge restrictions too
  313. this.opts = {
  314. ...merged,
  315. restrictions: {
  316. ...(defaultOptions.restrictions as Restrictions),
  317. ...(opts && opts.restrictions),
  318. },
  319. }
  320. // Support debug: true for backwards-compatability, unless logger is set in opts
  321. // opts instead of this.opts to avoid comparing objects — we set logger: justErrorsLogger in defaultOptions
  322. if (opts && opts.logger && opts.debug) {
  323. this.log(
  324. '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`.',
  325. 'warning',
  326. )
  327. } else if (opts && opts.debug) {
  328. this.opts.logger = debugLogger
  329. }
  330. this.log(`Using Core v${Uppy.VERSION}`)
  331. this.i18nInit()
  332. this.store = this.opts.store
  333. this.setState({
  334. ...defaultUploadState,
  335. plugins: {},
  336. files: {},
  337. currentUploads: {},
  338. capabilities: {
  339. uploadProgress: supportsUploadProgress(),
  340. individualCancellation: true,
  341. resumableUploads: false,
  342. },
  343. meta: { ...this.opts.meta },
  344. info: [],
  345. })
  346. this.#restricter = new Restricter<M, B>(() => this.opts, this.i18n)
  347. this.#storeUnsubscribe = this.store.subscribe(
  348. // eslint-disable-next-line
  349. // @ts-ignore Store is incorrectly typed
  350. (prevState, nextState, patch) => {
  351. // eslint-disable-next-line
  352. // @ts-ignore Store is incorrectly typed
  353. this.emit('state-update', prevState, nextState, patch)
  354. this.updateAll(nextState)
  355. },
  356. )
  357. // Exposing uppy object on window for debugging and testing
  358. if (this.opts.debug && typeof window !== 'undefined') {
  359. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  360. // @ts-ignore Mutating the global object for debug purposes
  361. window[this.opts.id] = this
  362. }
  363. this.#addListeners()
  364. }
  365. emit<T extends keyof UppyEventMap<M, B>>(
  366. event: T,
  367. ...args: Parameters<UppyEventMap<M, B>[T]>
  368. ): void {
  369. this.#emitter.emit(event, ...args)
  370. }
  371. /** @deprecated */
  372. on<K extends keyof DeprecatedUppyEventMap<M, B>>(
  373. event: K,
  374. callback: DeprecatedUppyEventMap<M, B>[K],
  375. ): this
  376. on<K extends keyof _UppyEventMap<M, B>>(
  377. event: K,
  378. callback: _UppyEventMap<M, B>[K],
  379. ): this
  380. on<K extends keyof UppyEventMap<M, B>>(
  381. event: K,
  382. callback: UppyEventMap<M, B>[K],
  383. ): this {
  384. this.#emitter.on(event, callback)
  385. return this
  386. }
  387. once<K extends keyof UppyEventMap<M, B>>(
  388. event: K,
  389. callback: UppyEventMap<M, B>[K],
  390. ): this {
  391. this.#emitter.once(event, callback)
  392. return this
  393. }
  394. off<K extends keyof UppyEventMap<M, B>>(
  395. event: K,
  396. callback: UppyEventMap<M, B>[K],
  397. ): this {
  398. this.#emitter.off(event, callback)
  399. return this
  400. }
  401. /**
  402. * Iterate on all plugins and run `update` on them.
  403. * Called each time state changes.
  404. *
  405. */
  406. updateAll(state: Partial<State<M, B>>): void {
  407. this.iteratePlugins((plugin: UnknownPlugin<M, B>) => {
  408. plugin.update(state)
  409. })
  410. }
  411. /**
  412. * Updates state with a patch
  413. */
  414. setState(patch?: Partial<State<M, B>>): void {
  415. // eslint-disable-next-line
  416. // @ts-ignore Store is incorrectly typed
  417. this.store.setState(patch)
  418. }
  419. /**
  420. * Returns current state.
  421. */
  422. getState(): State<M, B> {
  423. // eslint-disable-next-line
  424. // @ts-ignore Store is incorrectly typed
  425. return this.store.getState()
  426. }
  427. patchFilesState(filesWithNewState: {
  428. [id: string]: Partial<UppyFile<M, B>>
  429. }): void {
  430. const existingFilesState = this.getState().files
  431. this.setState({
  432. files: {
  433. ...existingFilesState,
  434. ...Object.fromEntries(
  435. Object.entries(filesWithNewState).map(([fileID, newFileState]) => [
  436. fileID,
  437. {
  438. ...existingFilesState[fileID],
  439. ...newFileState,
  440. },
  441. ]),
  442. ),
  443. },
  444. })
  445. }
  446. /**
  447. * Shorthand to set state for a specific file.
  448. */
  449. setFileState(fileID: string, state: Partial<UppyFile<M, B>>): void {
  450. if (!this.getState().files[fileID]) {
  451. throw new Error(
  452. `Can’t set state for ${fileID} (the file could have been removed)`,
  453. )
  454. }
  455. this.patchFilesState({ [fileID]: state })
  456. }
  457. i18nInit(): void {
  458. const onMissingKey = (key: string): void =>
  459. this.log(`Missing i18n string: ${key}`, 'error')
  460. const translator = new Translator([this.defaultLocale, this.opts.locale], {
  461. onMissingKey,
  462. })
  463. this.i18n = translator.translate.bind(translator)
  464. this.i18nArray = translator.translateArray.bind(translator)
  465. this.locale = translator.locale
  466. }
  467. setOptions(newOpts: MinimalRequiredOptions<M, B>): void {
  468. this.opts = {
  469. ...this.opts,
  470. ...(newOpts as UppyOptions<M, B>),
  471. restrictions: {
  472. ...this.opts.restrictions,
  473. ...(newOpts?.restrictions as Restrictions),
  474. },
  475. }
  476. if (newOpts.meta) {
  477. this.setMeta(newOpts.meta)
  478. }
  479. this.i18nInit()
  480. if (newOpts.locale) {
  481. this.iteratePlugins((plugin) => {
  482. plugin.setOptions(newOpts)
  483. })
  484. }
  485. // Note: this is not the preact `setState`, it's an internal function that has the same name.
  486. this.setState(undefined) // so that UI re-renders with new options
  487. }
  488. // todo next major: remove
  489. resetProgress(): void {
  490. const defaultProgress: Omit<FileProgressNotStarted, 'bytesTotal'> = {
  491. percentage: 0,
  492. bytesUploaded: 0,
  493. uploadComplete: false,
  494. uploadStarted: null,
  495. }
  496. const files = { ...this.getState().files }
  497. const updatedFiles: State<M, B>['files'] = {}
  498. Object.keys(files).forEach((fileID) => {
  499. updatedFiles[fileID] = {
  500. ...files[fileID],
  501. progress: {
  502. ...files[fileID].progress,
  503. ...defaultProgress,
  504. },
  505. }
  506. })
  507. this.setState({ files: updatedFiles, ...defaultUploadState })
  508. this.emit('reset-progress')
  509. }
  510. // @todo next major: rename to `clear()`, make it also cancel ongoing uploads
  511. // or throw and say you need to cancel manually
  512. protected clearUploadedFiles(): void {
  513. this.setState({ ...defaultUploadState, files: {} })
  514. }
  515. addPreProcessor(fn: Processor): void {
  516. this.#preProcessors.add(fn)
  517. }
  518. removePreProcessor(fn: Processor): boolean {
  519. return this.#preProcessors.delete(fn)
  520. }
  521. addPostProcessor(fn: Processor): void {
  522. this.#postProcessors.add(fn)
  523. }
  524. removePostProcessor(fn: Processor): boolean {
  525. return this.#postProcessors.delete(fn)
  526. }
  527. addUploader(fn: Processor): void {
  528. this.#uploaders.add(fn)
  529. }
  530. removeUploader(fn: Processor): boolean {
  531. return this.#uploaders.delete(fn)
  532. }
  533. setMeta(data: Partial<M>): void {
  534. const updatedMeta = { ...this.getState().meta, ...data }
  535. const updatedFiles = { ...this.getState().files }
  536. Object.keys(updatedFiles).forEach((fileID) => {
  537. updatedFiles[fileID] = {
  538. ...updatedFiles[fileID],
  539. meta: { ...updatedFiles[fileID].meta, ...data },
  540. }
  541. })
  542. this.log('Adding metadata:')
  543. this.log(data)
  544. this.setState({
  545. meta: updatedMeta,
  546. files: updatedFiles,
  547. })
  548. }
  549. setFileMeta(fileID: string, data: State<M, B>['meta']): void {
  550. const updatedFiles = { ...this.getState().files }
  551. if (!updatedFiles[fileID]) {
  552. this.log(
  553. 'Was trying to set metadata for a file that has been removed: ',
  554. fileID,
  555. )
  556. return
  557. }
  558. const newMeta = { ...updatedFiles[fileID].meta, ...data }
  559. updatedFiles[fileID] = { ...updatedFiles[fileID], meta: newMeta }
  560. this.setState({ files: updatedFiles })
  561. }
  562. /**
  563. * Get a file object.
  564. */
  565. getFile(fileID: string): UppyFile<M, B> {
  566. return this.getState().files[fileID]
  567. }
  568. /**
  569. * Get all files in an array.
  570. */
  571. getFiles(): UppyFile<M, B>[] {
  572. const { files } = this.getState()
  573. return Object.values(files)
  574. }
  575. getFilesByIds(ids: string[]): UppyFile<M, B>[] {
  576. return ids.map((id) => this.getFile(id))
  577. }
  578. // TODO: remove or refactor this method. It's very inefficient
  579. getObjectOfFilesPerState(): {
  580. newFiles: UppyFile<M, B>[]
  581. startedFiles: UppyFile<M, B>[]
  582. uploadStartedFiles: UppyFile<M, B>[]
  583. pausedFiles: UppyFile<M, B>[]
  584. completeFiles: UppyFile<M, B>[]
  585. erroredFiles: UppyFile<M, B>[]
  586. inProgressFiles: UppyFile<M, B>[]
  587. inProgressNotPausedFiles: UppyFile<M, B>[]
  588. processingFiles: UppyFile<M, B>[]
  589. isUploadStarted: boolean
  590. isAllComplete: boolean
  591. isAllErrored: boolean
  592. isAllPaused: boolean
  593. isUploadInProgress: boolean
  594. isSomeGhost: boolean
  595. } {
  596. const { files: filesObject, totalProgress, error } = this.getState()
  597. const files = Object.values(filesObject)
  598. const inProgressFiles = files.filter(
  599. ({ progress }) => !progress.uploadComplete && progress.uploadStarted,
  600. )
  601. const newFiles = files.filter((file) => !file.progress.uploadStarted)
  602. const startedFiles = files.filter(
  603. (file) =>
  604. file.progress.uploadStarted ||
  605. file.progress.preprocess ||
  606. file.progress.postprocess,
  607. )
  608. const uploadStartedFiles = files.filter(
  609. (file) => file.progress.uploadStarted,
  610. )
  611. const pausedFiles = files.filter((file) => file.isPaused)
  612. const completeFiles = files.filter((file) => file.progress.uploadComplete)
  613. const erroredFiles = files.filter((file) => file.error)
  614. const inProgressNotPausedFiles = inProgressFiles.filter(
  615. (file) => !file.isPaused,
  616. )
  617. const processingFiles = files.filter(
  618. (file) => file.progress.preprocess || file.progress.postprocess,
  619. )
  620. return {
  621. newFiles,
  622. startedFiles,
  623. uploadStartedFiles,
  624. pausedFiles,
  625. completeFiles,
  626. erroredFiles,
  627. inProgressFiles,
  628. inProgressNotPausedFiles,
  629. processingFiles,
  630. isUploadStarted: uploadStartedFiles.length > 0,
  631. isAllComplete:
  632. totalProgress === 100 &&
  633. completeFiles.length === files.length &&
  634. processingFiles.length === 0,
  635. isAllErrored: !!error && erroredFiles.length === files.length,
  636. isAllPaused:
  637. inProgressFiles.length !== 0 &&
  638. pausedFiles.length === inProgressFiles.length,
  639. isUploadInProgress: inProgressFiles.length > 0,
  640. isSomeGhost: files.some((file) => file.isGhost),
  641. }
  642. }
  643. #informAndEmit(
  644. errors: {
  645. message: string
  646. isUserFacing?: boolean
  647. details?: string
  648. isRestriction?: boolean
  649. file?: UppyFile<M, B>
  650. }[],
  651. ): void {
  652. for (const error of errors) {
  653. if (error.isRestriction) {
  654. this.emit(
  655. 'restriction-failed',
  656. error.file,
  657. error as RestrictionError<M, B>,
  658. )
  659. } else {
  660. this.emit('error', error, error.file)
  661. }
  662. this.log(error, 'warning')
  663. }
  664. const userFacingErrors = errors.filter((error) => error.isUserFacing)
  665. // don't flood the user: only show the first 4 toasts
  666. const maxNumToShow = 4
  667. const firstErrors = userFacingErrors.slice(0, maxNumToShow)
  668. const additionalErrors = userFacingErrors.slice(maxNumToShow)
  669. firstErrors.forEach(({ message, details = '' }) => {
  670. this.info({ message, details }, 'error', this.opts.infoTimeout)
  671. })
  672. if (additionalErrors.length > 0) {
  673. this.info({
  674. message: this.i18n('additionalRestrictionsFailed', {
  675. count: additionalErrors.length,
  676. }),
  677. })
  678. }
  679. }
  680. validateRestrictions(
  681. file: UppyFile<M, B>,
  682. files = this.getFiles(),
  683. ): RestrictionError<M, B> | null {
  684. try {
  685. this.#restricter.validate(files, [file])
  686. } catch (err) {
  687. return err
  688. }
  689. return null
  690. }
  691. #checkRequiredMetaFieldsOnFile(file: UppyFile<M, B>): boolean {
  692. const { missingFields, error } =
  693. this.#restricter.getMissingRequiredMetaFields(file)
  694. if (missingFields.length > 0) {
  695. this.setFileState(file.id, { missingRequiredMetaFields: missingFields })
  696. this.log(error.message)
  697. this.emit('restriction-failed', file, error)
  698. return false
  699. }
  700. return true
  701. }
  702. #checkRequiredMetaFields(files: State<M, B>['files']): boolean {
  703. let success = true
  704. for (const file of Object.values(files)) {
  705. if (!this.#checkRequiredMetaFieldsOnFile(file)) {
  706. success = false
  707. }
  708. }
  709. return success
  710. }
  711. #assertNewUploadAllowed(file?: UppyFile<M, B>): void {
  712. const { allowNewUpload } = this.getState()
  713. if (allowNewUpload === false) {
  714. const error = new RestrictionError(this.i18n('noMoreFilesAllowed'), {
  715. file,
  716. })
  717. this.#informAndEmit([error])
  718. throw error
  719. }
  720. }
  721. checkIfFileAlreadyExists(fileID: string): boolean {
  722. const { files } = this.getState()
  723. if (files[fileID] && !files[fileID].isGhost) {
  724. return true
  725. }
  726. return false
  727. }
  728. /**
  729. * Create a file state object based on user-provided `addFile()` options.
  730. */
  731. #transformFile(fileDescriptorOrFile: File | UppyFile<M, B>): UppyFile<M, B> {
  732. // Uppy expects files in { name, type, size, data } format.
  733. // If the actual File object is passed from input[type=file] or drag-drop,
  734. // we normalize it to match Uppy file object
  735. const file = (
  736. fileDescriptorOrFile instanceof File
  737. ? {
  738. name: fileDescriptorOrFile.name,
  739. type: fileDescriptorOrFile.type,
  740. size: fileDescriptorOrFile.size,
  741. data: fileDescriptorOrFile,
  742. }
  743. : fileDescriptorOrFile
  744. ) as UppyFile<M, B>
  745. const fileType = getFileType(file)
  746. const fileName = getFileName(fileType, file)
  747. const fileExtension = getFileNameAndExtension(fileName).extension
  748. const id = getSafeFileId(file)
  749. const meta = file.meta || {}
  750. meta.name = fileName
  751. meta.type = fileType
  752. // `null` means the size is unknown.
  753. const size = Number.isFinite(file.data.size) ? file.data.size : null
  754. return {
  755. source: file.source || '',
  756. id,
  757. name: fileName,
  758. extension: fileExtension || '',
  759. meta: {
  760. ...this.getState().meta,
  761. ...meta,
  762. },
  763. type: fileType,
  764. data: file.data,
  765. progress: {
  766. percentage: 0,
  767. bytesUploaded: 0,
  768. bytesTotal: size,
  769. uploadComplete: false,
  770. uploadStarted: null,
  771. } as FileProgressNotStarted,
  772. size,
  773. isGhost: false,
  774. isRemote: file.isRemote || false,
  775. // TODO: this should not be a string
  776. // @ts-expect-error wrong
  777. remote: file.remote || '',
  778. preview: file.preview,
  779. }
  780. }
  781. // Schedule an upload if `autoProceed` is enabled.
  782. #startIfAutoProceed(): void {
  783. if (this.opts.autoProceed && !this.scheduledAutoProceed) {
  784. this.scheduledAutoProceed = setTimeout(() => {
  785. this.scheduledAutoProceed = null
  786. this.upload().catch((err) => {
  787. if (!err.isRestriction) {
  788. this.log(err.stack || err.message || err)
  789. }
  790. })
  791. }, 4)
  792. }
  793. }
  794. #checkAndUpdateFileState(filesToAdd: UppyFile<M, B>[]): {
  795. nextFilesState: State<M, B>['files']
  796. validFilesToAdd: UppyFile<M, B>[]
  797. errors: RestrictionError<M, B>[]
  798. } {
  799. const { files: existingFiles } = this.getState()
  800. // create a copy of the files object only once
  801. const nextFilesState = { ...existingFiles }
  802. const validFilesToAdd: UppyFile<M, B>[] = []
  803. const errors: RestrictionError<M, B>[] = []
  804. for (const fileToAdd of filesToAdd) {
  805. try {
  806. let newFile = this.#transformFile(fileToAdd)
  807. // If a file has been recovered (Golden Retriever), but we were unable to recover its data (probably too large),
  808. // users are asked to re-select these half-recovered files and then this method will be called again.
  809. // In order to keep the progress, meta and everything else, we keep the existing file,
  810. // but we replace `data`, and we remove `isGhost`, because the file is no longer a ghost now
  811. const isGhost = existingFiles[newFile.id]?.isGhost
  812. if (isGhost) {
  813. const existingFileState = existingFiles[newFile.id]
  814. newFile = {
  815. ...existingFileState,
  816. isGhost: false,
  817. data: fileToAdd.data,
  818. }
  819. this.log(
  820. `Replaced the blob in the restored ghost file: ${newFile.name}, ${newFile.id}`,
  821. )
  822. }
  823. const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(
  824. newFile,
  825. nextFilesState,
  826. )
  827. if (
  828. !onBeforeFileAddedResult &&
  829. this.checkIfFileAlreadyExists(newFile.id)
  830. ) {
  831. throw new RestrictionError(
  832. this.i18n('noDuplicates', { fileName: newFile.name }),
  833. { file: fileToAdd },
  834. )
  835. }
  836. // Pass through reselected files from Golden Retriever
  837. if (onBeforeFileAddedResult === false && !isGhost) {
  838. // Don’t show UI info for this error, as it should be done by the developer
  839. throw new RestrictionError(
  840. 'Cannot add the file because onBeforeFileAdded returned false.',
  841. { isUserFacing: false, file: fileToAdd },
  842. )
  843. } else if (
  844. typeof onBeforeFileAddedResult === 'object' &&
  845. onBeforeFileAddedResult !== null
  846. ) {
  847. newFile = onBeforeFileAddedResult
  848. }
  849. this.#restricter.validateSingleFile(newFile)
  850. // need to add it to the new local state immediately, so we can use the state to validate the next files too
  851. nextFilesState[newFile.id] = newFile
  852. validFilesToAdd.push(newFile)
  853. } catch (err) {
  854. errors.push(err)
  855. }
  856. }
  857. try {
  858. // 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
  859. // when many files are added
  860. this.#restricter.validateAggregateRestrictions(
  861. Object.values(existingFiles),
  862. validFilesToAdd,
  863. )
  864. } catch (err) {
  865. errors.push(err)
  866. // If we have any aggregate error, don't allow adding this batch
  867. return {
  868. nextFilesState: existingFiles,
  869. validFilesToAdd: [],
  870. errors,
  871. }
  872. }
  873. return {
  874. nextFilesState,
  875. validFilesToAdd,
  876. errors,
  877. }
  878. }
  879. /**
  880. * Add a new file to `state.files`. This will run `onBeforeFileAdded`,
  881. * try to guess file type in a clever way, check file against restrictions,
  882. * and start an upload if `autoProceed === true`.
  883. */
  884. addFile(file: File | MinimalRequiredUppyFile<M, B>): UppyFile<M, B>['id'] {
  885. this.#assertNewUploadAllowed(file as UppyFile<M, B>)
  886. const { nextFilesState, validFilesToAdd, errors } =
  887. this.#checkAndUpdateFileState([file as UppyFile<M, B>])
  888. const restrictionErrors = errors.filter((error) => error.isRestriction)
  889. this.#informAndEmit(restrictionErrors)
  890. if (errors.length > 0) throw errors[0]
  891. this.setState({ files: nextFilesState })
  892. const [firstValidFileToAdd] = validFilesToAdd
  893. this.emit('file-added', firstValidFileToAdd)
  894. this.emit('files-added', validFilesToAdd)
  895. this.log(
  896. `Added file: ${firstValidFileToAdd.name}, ${firstValidFileToAdd.id}, mime type: ${firstValidFileToAdd.type}`,
  897. )
  898. this.#startIfAutoProceed()
  899. return firstValidFileToAdd.id
  900. }
  901. /**
  902. * Add multiple files to `state.files`. See the `addFile()` documentation.
  903. *
  904. * If an error occurs while adding a file, it is logged and the user is notified.
  905. * This is good for UI plugins, but not for programmatic use.
  906. * Programmatic users should usually still use `addFile()` on individual files.
  907. */
  908. addFiles(fileDescriptors: MinimalRequiredUppyFile<M, B>[]): void {
  909. this.#assertNewUploadAllowed()
  910. const { nextFilesState, validFilesToAdd, errors } =
  911. this.#checkAndUpdateFileState(fileDescriptors as UppyFile<M, B>[])
  912. const restrictionErrors = errors.filter((error) => error.isRestriction)
  913. this.#informAndEmit(restrictionErrors)
  914. const nonRestrictionErrors = errors.filter((error) => !error.isRestriction)
  915. if (nonRestrictionErrors.length > 0) {
  916. let message = 'Multiple errors occurred while adding files:\n'
  917. nonRestrictionErrors.forEach((subError) => {
  918. message += `\n * ${subError.message}`
  919. })
  920. this.info(
  921. {
  922. message: this.i18n('addBulkFilesFailed', {
  923. smart_count: nonRestrictionErrors.length,
  924. }),
  925. details: message,
  926. },
  927. 'error',
  928. this.opts.infoTimeout,
  929. )
  930. if (typeof AggregateError === 'function') {
  931. throw new AggregateError(nonRestrictionErrors, message)
  932. } else {
  933. const err = new Error(message)
  934. // @ts-expect-error fallback when AggregateError is not available
  935. err.errors = nonRestrictionErrors
  936. throw err
  937. }
  938. }
  939. // OK, we haven't thrown an error, we can start updating state and emitting events now:
  940. this.setState({ files: nextFilesState })
  941. validFilesToAdd.forEach((file) => {
  942. this.emit('file-added', file)
  943. })
  944. this.emit('files-added', validFilesToAdd)
  945. if (validFilesToAdd.length > 5) {
  946. this.log(`Added batch of ${validFilesToAdd.length} files`)
  947. } else {
  948. Object.values(validFilesToAdd).forEach((file) => {
  949. this.log(
  950. `Added file: ${file.name}\n id: ${file.id}\n type: ${file.type}`,
  951. )
  952. })
  953. }
  954. if (validFilesToAdd.length > 0) {
  955. this.#startIfAutoProceed()
  956. }
  957. }
  958. removeFiles(fileIDs: string[], reason?: FileRemoveReason): void {
  959. const { files, currentUploads } = this.getState()
  960. const updatedFiles = { ...files }
  961. const updatedUploads = { ...currentUploads }
  962. const removedFiles = Object.create(null)
  963. fileIDs.forEach((fileID) => {
  964. if (files[fileID]) {
  965. removedFiles[fileID] = files[fileID]
  966. delete updatedFiles[fileID]
  967. }
  968. })
  969. // Remove files from the `fileIDs` list in each upload.
  970. function fileIsNotRemoved(uploadFileID: string): boolean {
  971. return removedFiles[uploadFileID] === undefined
  972. }
  973. Object.keys(updatedUploads).forEach((uploadID) => {
  974. const newFileIDs =
  975. currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved)
  976. // Remove the upload if no files are associated with it anymore.
  977. if (newFileIDs.length === 0) {
  978. delete updatedUploads[uploadID]
  979. return
  980. }
  981. const { capabilities } = this.getState()
  982. if (
  983. newFileIDs.length !== currentUploads[uploadID].fileIDs.length &&
  984. !capabilities.individualCancellation
  985. ) {
  986. throw new Error('individualCancellation is disabled')
  987. }
  988. updatedUploads[uploadID] = {
  989. ...currentUploads[uploadID],
  990. fileIDs: newFileIDs,
  991. }
  992. })
  993. const stateUpdate: Partial<State<M, B>> = {
  994. currentUploads: updatedUploads,
  995. files: updatedFiles,
  996. }
  997. // If all files were removed - allow new uploads,
  998. // and clear recoveredState
  999. if (Object.keys(updatedFiles).length === 0) {
  1000. stateUpdate.allowNewUpload = true
  1001. stateUpdate.error = null
  1002. stateUpdate.recoveredState = null
  1003. }
  1004. this.setState(stateUpdate)
  1005. this.calculateTotalProgress()
  1006. const removedFileIDs = Object.keys(removedFiles)
  1007. removedFileIDs.forEach((fileID) => {
  1008. this.emit('file-removed', removedFiles[fileID], reason)
  1009. })
  1010. if (removedFileIDs.length > 5) {
  1011. this.log(`Removed ${removedFileIDs.length} files`)
  1012. } else {
  1013. this.log(`Removed files: ${removedFileIDs.join(', ')}`)
  1014. }
  1015. }
  1016. removeFile(fileID: string, reason?: FileRemoveReason): void {
  1017. this.removeFiles([fileID], reason)
  1018. }
  1019. pauseResume(fileID: string): boolean | undefined {
  1020. if (
  1021. !this.getState().capabilities.resumableUploads ||
  1022. this.getFile(fileID).progress.uploadComplete
  1023. ) {
  1024. return undefined
  1025. }
  1026. const wasPaused = this.getFile(fileID).isPaused || false
  1027. const isPaused = !wasPaused
  1028. this.setFileState(fileID, {
  1029. isPaused,
  1030. })
  1031. this.emit('upload-pause', fileID, isPaused)
  1032. return isPaused
  1033. }
  1034. pauseAll(): void {
  1035. const updatedFiles = { ...this.getState().files }
  1036. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  1037. return (
  1038. !updatedFiles[file].progress.uploadComplete &&
  1039. updatedFiles[file].progress.uploadStarted
  1040. )
  1041. })
  1042. inProgressUpdatedFiles.forEach((file) => {
  1043. const updatedFile = { ...updatedFiles[file], isPaused: true }
  1044. updatedFiles[file] = updatedFile
  1045. })
  1046. this.setState({ files: updatedFiles })
  1047. this.emit('pause-all')
  1048. }
  1049. resumeAll(): void {
  1050. const updatedFiles = { ...this.getState().files }
  1051. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  1052. return (
  1053. !updatedFiles[file].progress.uploadComplete &&
  1054. updatedFiles[file].progress.uploadStarted
  1055. )
  1056. })
  1057. inProgressUpdatedFiles.forEach((file) => {
  1058. const updatedFile = {
  1059. ...updatedFiles[file],
  1060. isPaused: false,
  1061. error: null,
  1062. }
  1063. updatedFiles[file] = updatedFile
  1064. })
  1065. this.setState({ files: updatedFiles })
  1066. this.emit('resume-all')
  1067. }
  1068. retryAll(): Promise<UploadResult<M, B> | undefined> {
  1069. const updatedFiles = { ...this.getState().files }
  1070. const filesToRetry = Object.keys(updatedFiles).filter((file) => {
  1071. return updatedFiles[file].error
  1072. })
  1073. filesToRetry.forEach((file) => {
  1074. const updatedFile = {
  1075. ...updatedFiles[file],
  1076. isPaused: false,
  1077. error: null,
  1078. }
  1079. updatedFiles[file] = updatedFile
  1080. })
  1081. this.setState({
  1082. files: updatedFiles,
  1083. error: null,
  1084. })
  1085. this.emit('retry-all', filesToRetry)
  1086. if (filesToRetry.length === 0) {
  1087. return Promise.resolve({
  1088. successful: [],
  1089. failed: [],
  1090. })
  1091. }
  1092. const uploadID = this.#createUpload(filesToRetry, {
  1093. forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
  1094. })
  1095. return this.#runUpload(uploadID)
  1096. }
  1097. cancelAll({ reason = 'user' }: { reason?: FileRemoveReason } = {}): void {
  1098. this.emit('cancel-all', { reason })
  1099. // Only remove existing uploads if user is canceling
  1100. if (reason === 'user') {
  1101. const { files } = this.getState()
  1102. const fileIDs = Object.keys(files)
  1103. if (fileIDs.length) {
  1104. this.removeFiles(fileIDs, 'cancel-all')
  1105. }
  1106. this.setState(defaultUploadState)
  1107. // todo should we call this.emit('reset-progress') like we do for resetProgress?
  1108. }
  1109. }
  1110. retryUpload(fileID: string): Promise<UploadResult<M, B> | undefined> {
  1111. this.setFileState(fileID, {
  1112. error: null,
  1113. isPaused: false,
  1114. })
  1115. this.emit('upload-retry', fileID)
  1116. const uploadID = this.#createUpload([fileID], {
  1117. forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
  1118. })
  1119. return this.#runUpload(uploadID)
  1120. }
  1121. logout(): void {
  1122. this.iteratePlugins((plugin) => {
  1123. ;(plugin as UnknownProviderPlugin<M, B>).provider?.logout?.()
  1124. })
  1125. }
  1126. // ___Why throttle at 500ms?
  1127. // - We must throttle at >250ms for superfocus in Dashboard to work well
  1128. // (because animation takes 0.25s, and we want to wait for all animations to be over before refocusing).
  1129. // [Practical Check]: if thottle is at 100ms, then if you are uploading a file,
  1130. // and click 'ADD MORE FILES', - focus won't activate in Firefox.
  1131. // - We must throttle at around >500ms to avoid performance lags.
  1132. // [Practical Check] Firefox, try to upload a big file for a prolonged period of time. Laptop will start to heat up.
  1133. calculateProgress = throttle(
  1134. (file, data) => {
  1135. const fileInState = this.getFile(file?.id)
  1136. if (file == null || !fileInState) {
  1137. this.log(
  1138. `Not setting progress for a file that has been removed: ${file?.id}`,
  1139. )
  1140. return
  1141. }
  1142. if (fileInState.progress.percentage === 100) {
  1143. this.log(
  1144. `Not setting progress for a file that has been already uploaded: ${file.id}`,
  1145. )
  1146. return
  1147. }
  1148. // bytesTotal may be null or zero; in that case we can't divide by it
  1149. const canHavePercentage =
  1150. Number.isFinite(data.bytesTotal) && data.bytesTotal > 0
  1151. this.setFileState(file.id, {
  1152. progress: {
  1153. ...fileInState.progress,
  1154. bytesUploaded: data.bytesUploaded,
  1155. bytesTotal: data.bytesTotal,
  1156. percentage: canHavePercentage
  1157. ? Math.round((data.bytesUploaded / data.bytesTotal) * 100)
  1158. : 0,
  1159. },
  1160. })
  1161. this.calculateTotalProgress()
  1162. },
  1163. 500,
  1164. { leading: true, trailing: true },
  1165. )
  1166. calculateTotalProgress(): void {
  1167. // calculate total progress, using the number of files currently uploading,
  1168. // multiplied by 100 and the summ of individual progress of each file
  1169. const files = this.getFiles()
  1170. const inProgress = files.filter((file) => {
  1171. return (
  1172. file.progress.uploadStarted ||
  1173. file.progress.preprocess ||
  1174. file.progress.postprocess
  1175. )
  1176. })
  1177. if (inProgress.length === 0) {
  1178. this.emit('progress', 0)
  1179. this.setState({ totalProgress: 0 })
  1180. return
  1181. }
  1182. const sizedFiles = inProgress.filter(
  1183. (file) => file.progress.bytesTotal != null,
  1184. )
  1185. const unsizedFiles = inProgress.filter(
  1186. (file) => file.progress.bytesTotal == null,
  1187. )
  1188. if (sizedFiles.length === 0) {
  1189. const progressMax = inProgress.length * 100
  1190. const currentProgress = unsizedFiles.reduce((acc, file) => {
  1191. return acc + file.progress.percentage
  1192. }, 0)
  1193. const totalProgress = Math.round((currentProgress / progressMax) * 100)
  1194. this.setState({ totalProgress })
  1195. return
  1196. }
  1197. let totalSize = sizedFiles.reduce((acc, file) => {
  1198. return (acc + (file.progress.bytesTotal ?? 0)) as number
  1199. }, 0)
  1200. const averageSize = totalSize / sizedFiles.length
  1201. totalSize += averageSize * unsizedFiles.length
  1202. let uploadedSize = 0
  1203. sizedFiles.forEach((file) => {
  1204. uploadedSize += file.progress.bytesUploaded as number
  1205. })
  1206. unsizedFiles.forEach((file) => {
  1207. uploadedSize += (averageSize * (file.progress.percentage || 0)) / 100
  1208. })
  1209. let totalProgress =
  1210. totalSize === 0 ? 0 : Math.round((uploadedSize / totalSize) * 100)
  1211. // hot fix, because:
  1212. // uploadedSize ended up larger than totalSize, resulting in 1325% total
  1213. if (totalProgress > 100) {
  1214. totalProgress = 100
  1215. }
  1216. this.setState({ totalProgress })
  1217. this.emit('progress', totalProgress)
  1218. }
  1219. /**
  1220. * Registers listeners for all global actions, like:
  1221. * `error`, `file-removed`, `upload-progress`
  1222. */
  1223. #addListeners(): void {
  1224. // Type inference only works for inline functions so we have to type it again
  1225. const errorHandler: UppyEventMap<M, B>['error'] = (
  1226. error,
  1227. file,
  1228. response,
  1229. ) => {
  1230. let errorMsg = error.message || 'Unknown error'
  1231. if (error.details) {
  1232. errorMsg += ` ${error.details}`
  1233. }
  1234. this.setState({ error: errorMsg })
  1235. if (file != null && file.id in this.getState().files) {
  1236. this.setFileState(file.id, {
  1237. error: errorMsg,
  1238. response,
  1239. })
  1240. }
  1241. }
  1242. this.on('error', errorHandler)
  1243. this.on('upload-error', (file, error, response) => {
  1244. errorHandler(error, file, response)
  1245. if (typeof error === 'object' && error.message) {
  1246. this.log(error.message, 'error')
  1247. const newError = new Error(
  1248. this.i18n('failedToUpload', { file: file?.name ?? '' }),
  1249. ) as any // we may want a new custom error here
  1250. newError.isUserFacing = true // todo maybe don't do this with all errors?
  1251. newError.details = error.message
  1252. if (error.details) {
  1253. newError.details += ` ${error.details}`
  1254. }
  1255. this.#informAndEmit([newError])
  1256. } else {
  1257. this.#informAndEmit([error])
  1258. }
  1259. })
  1260. let uploadStalledWarningRecentlyEmitted: ReturnType<
  1261. typeof setTimeout
  1262. > | null = null
  1263. this.on('upload-stalled', (error, files) => {
  1264. const { message } = error
  1265. const details = files.map((file) => file.meta.name).join(', ')
  1266. if (!uploadStalledWarningRecentlyEmitted) {
  1267. this.info({ message, details }, 'warning', this.opts.infoTimeout)
  1268. uploadStalledWarningRecentlyEmitted = setTimeout(() => {
  1269. uploadStalledWarningRecentlyEmitted = null
  1270. }, this.opts.infoTimeout)
  1271. }
  1272. this.log(`${message} ${details}`.trim(), 'warning')
  1273. })
  1274. this.on('upload', () => {
  1275. this.setState({ error: null })
  1276. })
  1277. const onUploadStarted = (files: UppyFile<M, B>[]): void => {
  1278. const filesFiltered = files.filter((file) => {
  1279. const exists = file != null && this.getFile(file.id)
  1280. if (!exists)
  1281. this.log(
  1282. `Not setting progress for a file that has been removed: ${file?.id}`,
  1283. )
  1284. return exists
  1285. })
  1286. const filesState = Object.fromEntries(
  1287. filesFiltered.map((file) => [
  1288. file.id,
  1289. {
  1290. progress: {
  1291. progress: 0,
  1292. uploadStarted: Date.now(),
  1293. uploadComplete: false,
  1294. percentage: 0,
  1295. bytesUploaded: 0,
  1296. bytesTotal: file.size,
  1297. } as FileProgressStarted,
  1298. },
  1299. ]),
  1300. )
  1301. this.patchFilesState(filesState)
  1302. }
  1303. this.on('upload-start', (files) => {
  1304. files.forEach((file: UppyFile<M, B>) => {
  1305. // todo backward compat, remove this event in a next major
  1306. this.emit('upload-started', file)
  1307. })
  1308. onUploadStarted(files)
  1309. })
  1310. this.on('upload-progress', this.calculateProgress)
  1311. this.on('upload-success', (file, uploadResp) => {
  1312. if (file == null || !this.getFile(file.id)) {
  1313. this.log(
  1314. `Not setting progress for a file that has been removed: ${file?.id}`,
  1315. )
  1316. return
  1317. }
  1318. const currentProgress = this.getFile(file.id).progress
  1319. this.setFileState(file.id, {
  1320. progress: {
  1321. ...currentProgress,
  1322. postprocess:
  1323. this.#postProcessors.size > 0
  1324. ? {
  1325. mode: 'indeterminate',
  1326. }
  1327. : undefined,
  1328. uploadComplete: true,
  1329. percentage: 100,
  1330. bytesUploaded: currentProgress.bytesTotal,
  1331. } as FileProgressStarted,
  1332. response: uploadResp,
  1333. uploadURL: uploadResp.uploadURL,
  1334. isPaused: false,
  1335. })
  1336. // Remote providers sometimes don't tell us the file size,
  1337. // but we can know how many bytes we uploaded once the upload is complete.
  1338. if (file.size == null) {
  1339. this.setFileState(file.id, {
  1340. size: uploadResp.bytesUploaded || currentProgress.bytesTotal,
  1341. })
  1342. }
  1343. this.calculateTotalProgress()
  1344. })
  1345. this.on('preprocess-progress', (file, progress) => {
  1346. if (file == null || !this.getFile(file.id)) {
  1347. this.log(
  1348. `Not setting progress for a file that has been removed: ${file?.id}`,
  1349. )
  1350. return
  1351. }
  1352. this.setFileState(file.id, {
  1353. progress: { ...this.getFile(file.id).progress, preprocess: progress },
  1354. })
  1355. })
  1356. this.on('preprocess-complete', (file) => {
  1357. if (file == null || !this.getFile(file.id)) {
  1358. this.log(
  1359. `Not setting progress for a file that has been removed: ${file?.id}`,
  1360. )
  1361. return
  1362. }
  1363. const files = { ...this.getState().files }
  1364. files[file.id] = {
  1365. ...files[file.id],
  1366. progress: { ...files[file.id].progress },
  1367. }
  1368. delete files[file.id].progress.preprocess
  1369. this.setState({ files })
  1370. })
  1371. this.on('postprocess-progress', (file, progress) => {
  1372. if (file == null || !this.getFile(file.id)) {
  1373. this.log(
  1374. `Not setting progress for a file that has been removed: ${file?.id}`,
  1375. )
  1376. return
  1377. }
  1378. this.setFileState(file.id, {
  1379. progress: {
  1380. ...this.getState().files[file.id].progress,
  1381. postprocess: progress,
  1382. },
  1383. })
  1384. })
  1385. this.on('postprocess-complete', (file) => {
  1386. if (file == null || !this.getFile(file.id)) {
  1387. this.log(
  1388. `Not setting progress for a file that has been removed: ${file?.id}`,
  1389. )
  1390. return
  1391. }
  1392. const files = {
  1393. ...this.getState().files,
  1394. }
  1395. files[file.id] = {
  1396. ...files[file.id],
  1397. progress: {
  1398. ...files[file.id].progress,
  1399. },
  1400. }
  1401. delete files[file.id].progress.postprocess
  1402. this.setState({ files })
  1403. })
  1404. this.on('restored', () => {
  1405. // Files may have changed--ensure progress is still accurate.
  1406. this.calculateTotalProgress()
  1407. })
  1408. // @ts-expect-error should fix itself when dashboard it typed (also this doesn't belong here)
  1409. this.on('dashboard:file-edit-complete', (file) => {
  1410. if (file) {
  1411. this.#checkRequiredMetaFieldsOnFile(file)
  1412. }
  1413. })
  1414. // show informer if offline
  1415. if (typeof window !== 'undefined' && window.addEventListener) {
  1416. window.addEventListener('online', this.#updateOnlineStatus)
  1417. window.addEventListener('offline', this.#updateOnlineStatus)
  1418. setTimeout(this.#updateOnlineStatus, 3000)
  1419. }
  1420. }
  1421. updateOnlineStatus(): void {
  1422. const online = window.navigator.onLine ?? true
  1423. if (!online) {
  1424. this.emit('is-offline')
  1425. this.info(this.i18n('noInternetConnection'), 'error', 0)
  1426. this.wasOffline = true
  1427. } else {
  1428. this.emit('is-online')
  1429. if (this.wasOffline) {
  1430. this.emit('back-online')
  1431. this.info(this.i18n('connectedToInternet'), 'success', 3000)
  1432. this.wasOffline = false
  1433. }
  1434. }
  1435. }
  1436. #updateOnlineStatus = this.updateOnlineStatus.bind(this)
  1437. getID(): UppyOptions<M, B>['id'] {
  1438. return this.opts.id
  1439. }
  1440. /**
  1441. * Registers a plugin with Core.
  1442. */
  1443. use<T extends typeof BasePlugin<any, M, B>>(
  1444. Plugin: T,
  1445. opts?: ConstructorParameters<T>[1],
  1446. ): this {
  1447. if (typeof Plugin !== 'function') {
  1448. const msg =
  1449. `Expected a plugin class, but got ${
  1450. Plugin === null ? 'null' : typeof Plugin
  1451. }.` +
  1452. ' Please verify that the plugin was imported and spelled correctly.'
  1453. throw new TypeError(msg)
  1454. }
  1455. // Instantiate
  1456. const plugin = new Plugin(this, opts)
  1457. const pluginId = plugin.id
  1458. if (!pluginId) {
  1459. throw new Error('Your plugin must have an id')
  1460. }
  1461. if (!plugin.type) {
  1462. throw new Error('Your plugin must have a type')
  1463. }
  1464. const existsPluginAlready = this.getPlugin(pluginId)
  1465. if (existsPluginAlready) {
  1466. const msg =
  1467. `Already found a plugin named '${existsPluginAlready.id}'. ` +
  1468. `Tried to use: '${pluginId}'.\n` +
  1469. 'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.'
  1470. throw new Error(msg)
  1471. }
  1472. // @ts-expect-error does exist
  1473. if (Plugin.VERSION) {
  1474. // @ts-expect-error does exist
  1475. this.log(`Using ${pluginId} v${Plugin.VERSION}`)
  1476. }
  1477. if (plugin.type in this.#plugins) {
  1478. this.#plugins[plugin.type].push(plugin)
  1479. } else {
  1480. this.#plugins[plugin.type] = [plugin]
  1481. }
  1482. plugin.install()
  1483. this.emit('plugin-added', plugin)
  1484. return this
  1485. }
  1486. /**
  1487. * Find one Plugin by name.
  1488. */
  1489. getPlugin(id: string): UnknownPlugin<M, B> | undefined {
  1490. for (const plugins of Object.values(this.#plugins)) {
  1491. const foundPlugin = plugins.find((plugin) => plugin.id === id)
  1492. if (foundPlugin != null) return foundPlugin
  1493. }
  1494. return undefined
  1495. }
  1496. private [Symbol.for('uppy test: getPlugins')](
  1497. type: string,
  1498. ): UnknownPlugin<M, B>[] {
  1499. return this.#plugins[type]
  1500. }
  1501. /**
  1502. * Iterate through all `use`d plugins.
  1503. *
  1504. */
  1505. iteratePlugins(method: (plugin: UnknownPlugin<M, B>) => void): void {
  1506. Object.values(this.#plugins).flat(1).forEach(method)
  1507. }
  1508. /**
  1509. * Uninstall and remove a plugin.
  1510. *
  1511. * @param {object} instance The plugin instance to remove.
  1512. */
  1513. removePlugin(instance: UnknownPlugin<M, B>): void {
  1514. this.log(`Removing plugin ${instance.id}`)
  1515. this.emit('plugin-remove', instance)
  1516. if (instance.uninstall) {
  1517. instance.uninstall()
  1518. }
  1519. const list = this.#plugins[instance.type]
  1520. // list.indexOf failed here, because Vue3 converted the plugin instance
  1521. // to a Proxy object, which failed the strict comparison test:
  1522. // obj !== objProxy
  1523. const index = list.findIndex((item) => item.id === instance.id)
  1524. if (index !== -1) {
  1525. list.splice(index, 1)
  1526. }
  1527. const state = this.getState()
  1528. const updatedState = {
  1529. plugins: {
  1530. ...state.plugins,
  1531. [instance.id]: undefined,
  1532. },
  1533. }
  1534. this.setState(updatedState)
  1535. }
  1536. /**
  1537. * Uninstall all plugins and close down this Uppy instance.
  1538. */
  1539. // @todo next major: rename to `destroy`.
  1540. // Cancel local uploads, cancel remote uploads, DON'T cancel assemblies
  1541. // document that if you do want to cancel assemblies, you need to call smth manually.
  1542. // Potentially remove reason, as it’s confusing, just come up with a default behaviour.
  1543. close({ reason }: { reason?: FileRemoveReason } | undefined = {}): void {
  1544. this.log(
  1545. `Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`,
  1546. )
  1547. this.cancelAll({ reason })
  1548. this.#storeUnsubscribe()
  1549. this.iteratePlugins((plugin) => {
  1550. this.removePlugin(plugin)
  1551. })
  1552. if (typeof window !== 'undefined' && window.removeEventListener) {
  1553. window.removeEventListener('online', this.#updateOnlineStatus)
  1554. window.removeEventListener('offline', this.#updateOnlineStatus)
  1555. }
  1556. }
  1557. hideInfo(): void {
  1558. const { info } = this.getState()
  1559. this.setState({ info: info.slice(1) })
  1560. this.emit('info-hidden')
  1561. }
  1562. /**
  1563. * Set info message in `state.info`, so that UI plugins like `Informer`
  1564. * can display the message.
  1565. */
  1566. info(
  1567. message:
  1568. | string
  1569. | { message: string; details?: string | Record<string, string> },
  1570. type: LogLevel = 'info',
  1571. duration = 3000,
  1572. ): void {
  1573. const isComplexMessage = typeof message === 'object'
  1574. this.setState({
  1575. info: [
  1576. ...this.getState().info,
  1577. {
  1578. type,
  1579. message: isComplexMessage ? message.message : message,
  1580. details: isComplexMessage ? message.details : null,
  1581. },
  1582. ],
  1583. })
  1584. setTimeout(() => this.hideInfo(), duration)
  1585. this.emit('info-visible')
  1586. }
  1587. /**
  1588. * Passes messages to a function, provided in `opts.logger`.
  1589. * If `opts.logger: Uppy.debugLogger` or `opts.debug: true`, logs to the browser console.
  1590. */
  1591. log(message: string | Record<string, unknown> | Error, type?: string): void {
  1592. const { logger } = this.opts
  1593. switch (type) {
  1594. case 'error':
  1595. logger.error(message)
  1596. break
  1597. case 'warning':
  1598. logger.warn(message)
  1599. break
  1600. default:
  1601. logger.debug(message)
  1602. break
  1603. }
  1604. }
  1605. // We need to store request clients by a unique ID, so we can share RequestClient instances across files
  1606. // this allows us to do rate limiting and synchronous operations like refreshing provider tokens
  1607. // example: refreshing tokens: if each file has their own requestclient,
  1608. // we don't have any way to synchronize all requests in order to
  1609. // - block all requests
  1610. // - refresh the token
  1611. // - unblock all requests and allow them to run with a the new access token
  1612. // back when we had a requestclient per file, once an access token expired,
  1613. // all 6 files would go ahead and refresh the token at the same time
  1614. // (calling /refresh-token up to 6 times), which will probably fail for some providers
  1615. #requestClientById = new Map<string, unknown>()
  1616. registerRequestClient(id: string, client: unknown): void {
  1617. this.#requestClientById.set(id, client)
  1618. }
  1619. /** @protected */
  1620. getRequestClientForFile(file: UppyFile<M, B>): unknown {
  1621. if (!file.remote)
  1622. throw new Error(
  1623. `Tried to get RequestClient for a non-remote file ${file.id}`,
  1624. )
  1625. const requestClient = this.#requestClientById.get(
  1626. file.remote.requestClientId,
  1627. )
  1628. if (requestClient == null)
  1629. throw new Error(
  1630. `requestClientId "${file.remote.requestClientId}" not registered for file "${file.id}"`,
  1631. )
  1632. return requestClient
  1633. }
  1634. /**
  1635. * Restore an upload by its ID.
  1636. */
  1637. restore(uploadID: string): Promise<UploadResult<M, B> | undefined> {
  1638. this.log(`Core: attempting to restore upload "${uploadID}"`)
  1639. if (!this.getState().currentUploads[uploadID]) {
  1640. this.#removeUpload(uploadID)
  1641. return Promise.reject(new Error('Nonexistent upload'))
  1642. }
  1643. return this.#runUpload(uploadID)
  1644. }
  1645. /**
  1646. * Create an upload for a bunch of files.
  1647. *
  1648. */
  1649. #createUpload(
  1650. fileIDs: string[],
  1651. opts: { forceAllowNewUpload?: boolean } = {},
  1652. ): string {
  1653. // uppy.retryAll sets this to true — when retrying we want to ignore `allowNewUpload: false`
  1654. const { forceAllowNewUpload = false } = opts
  1655. const { allowNewUpload, currentUploads } = this.getState()
  1656. if (!allowNewUpload && !forceAllowNewUpload) {
  1657. throw new Error('Cannot create a new upload: already uploading.')
  1658. }
  1659. const uploadID = nanoid()
  1660. this.emit('upload', {
  1661. id: uploadID,
  1662. fileIDs,
  1663. })
  1664. this.setState({
  1665. allowNewUpload:
  1666. this.opts.allowMultipleUploadBatches !== false &&
  1667. this.opts.allowMultipleUploads !== false,
  1668. currentUploads: {
  1669. ...currentUploads,
  1670. [uploadID]: {
  1671. fileIDs,
  1672. step: 0,
  1673. result: {},
  1674. },
  1675. },
  1676. })
  1677. return uploadID
  1678. }
  1679. private [Symbol.for('uppy test: createUpload')](...args: any[]): string {
  1680. // @ts-expect-error https://github.com/microsoft/TypeScript/issues/47595
  1681. return this.#createUpload(...args)
  1682. }
  1683. #getUpload(uploadID: string): CurrentUpload<M, B> {
  1684. const { currentUploads } = this.getState()
  1685. return currentUploads[uploadID]
  1686. }
  1687. /**
  1688. * Add data to an upload's result object.
  1689. */
  1690. addResultData(uploadID: string, data: CurrentUpload<M, B>['result']): void {
  1691. if (!this.#getUpload(uploadID)) {
  1692. this.log(
  1693. `Not setting result for an upload that has been removed: ${uploadID}`,
  1694. )
  1695. return
  1696. }
  1697. const { currentUploads } = this.getState()
  1698. const currentUpload = {
  1699. ...currentUploads[uploadID],
  1700. result: { ...currentUploads[uploadID].result, ...data },
  1701. }
  1702. this.setState({
  1703. currentUploads: { ...currentUploads, [uploadID]: currentUpload },
  1704. })
  1705. }
  1706. /**
  1707. * Remove an upload, eg. if it has been canceled or completed.
  1708. *
  1709. */
  1710. #removeUpload(uploadID: string): void {
  1711. const currentUploads = { ...this.getState().currentUploads }
  1712. delete currentUploads[uploadID]
  1713. this.setState({
  1714. currentUploads,
  1715. })
  1716. }
  1717. /**
  1718. * Run an upload. This picks up where it left off in case the upload is being restored.
  1719. */
  1720. async #runUpload(uploadID: string): Promise<UploadResult<M, B> | undefined> {
  1721. const getCurrentUpload = (): CurrentUpload<M, B> => {
  1722. const { currentUploads } = this.getState()
  1723. return currentUploads[uploadID]
  1724. }
  1725. let currentUpload = getCurrentUpload()
  1726. const steps = [
  1727. ...this.#preProcessors,
  1728. ...this.#uploaders,
  1729. ...this.#postProcessors,
  1730. ]
  1731. try {
  1732. for (let step = currentUpload.step || 0; step < steps.length; step++) {
  1733. if (!currentUpload) {
  1734. break
  1735. }
  1736. const fn = steps[step]
  1737. this.setState({
  1738. currentUploads: {
  1739. ...this.getState().currentUploads,
  1740. [uploadID]: {
  1741. ...currentUpload,
  1742. step,
  1743. },
  1744. },
  1745. })
  1746. const { fileIDs } = currentUpload
  1747. // TODO give this the `updatedUpload` object as its only parameter maybe?
  1748. // Otherwise when more metadata may be added to the upload this would keep getting more parameters
  1749. await fn(fileIDs, uploadID)
  1750. // Update currentUpload value in case it was modified asynchronously.
  1751. currentUpload = getCurrentUpload()
  1752. }
  1753. } catch (err) {
  1754. this.#removeUpload(uploadID)
  1755. throw err
  1756. }
  1757. // Set result data.
  1758. if (currentUpload) {
  1759. // Mark postprocessing step as complete if necessary; this addresses a case where we might get
  1760. // stuck in the postprocessing UI while the upload is fully complete.
  1761. // If the postprocessing steps do not do any work, they may not emit postprocessing events at
  1762. // all, and never mark the postprocessing as complete. This is fine on its own but we
  1763. // introduced code in the @uppy/core upload-success handler to prepare postprocessing progress
  1764. // state if any postprocessors are registered. That is to avoid a "flash of completed state"
  1765. // before the postprocessing plugins can emit events.
  1766. //
  1767. // So, just in case an upload with postprocessing plugins *has* completed *without* emitting
  1768. // postprocessing completion, we do it instead.
  1769. currentUpload.fileIDs.forEach((fileID) => {
  1770. const file = this.getFile(fileID)
  1771. if (file && file.progress.postprocess) {
  1772. this.emit('postprocess-complete', file)
  1773. }
  1774. })
  1775. const files = currentUpload.fileIDs.map((fileID) => this.getFile(fileID))
  1776. const successful = files.filter((file) => !file.error)
  1777. const failed = files.filter((file) => file.error)
  1778. this.addResultData(uploadID, { successful, failed, uploadID })
  1779. // Update currentUpload value in case it was modified asynchronously.
  1780. currentUpload = getCurrentUpload()
  1781. }
  1782. // Emit completion events.
  1783. // This is in a separate function so that the `currentUploads` variable
  1784. // always refers to the latest state. In the handler right above it refers
  1785. // to an outdated object without the `.result` property.
  1786. let result
  1787. if (currentUpload) {
  1788. result = currentUpload.result
  1789. this.emit('complete', result)
  1790. this.#removeUpload(uploadID)
  1791. }
  1792. if (result == null) {
  1793. this.log(
  1794. `Not setting result for an upload that has been removed: ${uploadID}`,
  1795. )
  1796. }
  1797. return result
  1798. }
  1799. /**
  1800. * Start an upload for all the files that are not currently being uploaded.
  1801. */
  1802. upload(): Promise<NonNullable<UploadResult<M, B>> | undefined> {
  1803. if (!this.#plugins.uploader?.length) {
  1804. this.log('No uploader type plugins are used', 'warning')
  1805. }
  1806. let { files } = this.getState()
  1807. const onBeforeUploadResult = this.opts.onBeforeUpload(files)
  1808. if (onBeforeUploadResult === false) {
  1809. return Promise.reject(
  1810. new Error(
  1811. 'Not starting the upload because onBeforeUpload returned false',
  1812. ),
  1813. )
  1814. }
  1815. if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {
  1816. files = onBeforeUploadResult
  1817. // Updating files in state, because uploader plugins receive file IDs,
  1818. // and then fetch the actual file object from state
  1819. this.setState({
  1820. files,
  1821. })
  1822. }
  1823. return Promise.resolve()
  1824. .then(() => this.#restricter.validateMinNumberOfFiles(files))
  1825. .catch((err) => {
  1826. this.#informAndEmit([err])
  1827. throw err
  1828. })
  1829. .then(() => {
  1830. if (!this.#checkRequiredMetaFields(files)) {
  1831. throw new RestrictionError(this.i18n('missingRequiredMetaField'))
  1832. }
  1833. })
  1834. .catch((err) => {
  1835. // Doing this in a separate catch because we already emited and logged
  1836. // all the errors in `checkRequiredMetaFields` so we only throw a generic
  1837. // missing fields error here.
  1838. throw err
  1839. })
  1840. .then(() => {
  1841. const { currentUploads } = this.getState()
  1842. // get a list of files that are currently assigned to uploads
  1843. const currentlyUploadingFiles = Object.values(currentUploads).flatMap(
  1844. (curr) => curr.fileIDs,
  1845. )
  1846. const waitingFileIDs: string[] = []
  1847. Object.keys(files).forEach((fileID) => {
  1848. const file = this.getFile(fileID)
  1849. // if the file hasn't started uploading and hasn't already been assigned to an upload..
  1850. if (
  1851. !file.progress.uploadStarted &&
  1852. currentlyUploadingFiles.indexOf(fileID) === -1
  1853. ) {
  1854. waitingFileIDs.push(file.id)
  1855. }
  1856. })
  1857. const uploadID = this.#createUpload(waitingFileIDs)
  1858. return this.#runUpload(uploadID)
  1859. })
  1860. .catch((err) => {
  1861. this.emit('error', err)
  1862. this.log(err, 'error')
  1863. throw err
  1864. })
  1865. }
  1866. }
  1867. export default Uppy