Uppy.ts 65 KB

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