Uppy.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640
  1. /* eslint-disable max-classes-per-file */
  2. /* global AggregateError */
  3. import Translator from '@uppy/utils/lib/Translator'
  4. import ee from 'namespace-emitter'
  5. import { nanoid } from 'nanoid/non-secure'
  6. import throttle from 'lodash/throttle.js'
  7. import DefaultStore from '@uppy/store-default'
  8. import getFileType from '@uppy/utils/lib/getFileType'
  9. import getFileNameAndExtension from '@uppy/utils/lib/getFileNameAndExtension'
  10. import { getSafeFileId } from '@uppy/utils/lib/generateFileID'
  11. import supportsUploadProgress from './supportsUploadProgress.js'
  12. import getFileName from './getFileName.js'
  13. import { justErrorsLogger, debugLogger } from './loggers.js'
  14. import {
  15. Restricter,
  16. defaultOptions as defaultRestrictionOptions,
  17. RestrictionError,
  18. } from './Restricter.js'
  19. import packageJson from '../package.json'
  20. import locale from './locale.js'
  21. const getDefaultUploadState = () => ({
  22. totalProgress: 0,
  23. allowNewUpload: true,
  24. error: null,
  25. recoveredState: null,
  26. });
  27. /**
  28. * Uppy Core module.
  29. * Manages plugins, state updates, acts as an event bus,
  30. * adds/removes files and metadata.
  31. */
  32. class Uppy {
  33. static VERSION = packageJson.version
  34. /** @type {Record<string, BasePlugin[]>} */
  35. #plugins = Object.create(null)
  36. #restricter
  37. #storeUnsubscribe
  38. #emitter = ee()
  39. #preProcessors = new Set()
  40. #uploaders = new Set()
  41. #postProcessors = new Set()
  42. /**
  43. * Instantiate Uppy
  44. *
  45. * @param {object} opts — Uppy options
  46. */
  47. constructor (opts) {
  48. this.defaultLocale = locale
  49. const defaultOptions = {
  50. id: 'uppy',
  51. autoProceed: false,
  52. allowMultipleUploadBatches: true,
  53. debug: false,
  54. restrictions: defaultRestrictionOptions,
  55. meta: {},
  56. onBeforeFileAdded: (file, files) => !Object.hasOwn(files, file.id),
  57. onBeforeUpload: (files) => files,
  58. store: new DefaultStore(),
  59. logger: justErrorsLogger,
  60. infoTimeout: 5000,
  61. }
  62. // Merge default options with the ones set by user,
  63. // making sure to merge restrictions too
  64. this.opts = {
  65. ...defaultOptions,
  66. ...opts,
  67. restrictions: {
  68. ...defaultOptions.restrictions,
  69. ...(opts && opts.restrictions),
  70. },
  71. }
  72. // Support debug: true for backwards-compatability, unless logger is set in opts
  73. // opts instead of this.opts to avoid comparing objects — we set logger: justErrorsLogger in defaultOptions
  74. if (opts && opts.logger && opts.debug) {
  75. this.log('You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.', 'warning')
  76. } else if (opts && opts.debug) {
  77. this.opts.logger = debugLogger
  78. }
  79. this.log(`Using Core v${this.constructor.VERSION}`)
  80. this.i18nInit()
  81. this.store = this.opts.store
  82. this.setState({
  83. ...getDefaultUploadState(),
  84. plugins: {},
  85. files: {},
  86. currentUploads: {},
  87. capabilities: {
  88. uploadProgress: supportsUploadProgress(),
  89. individualCancellation: true,
  90. resumableUploads: false,
  91. },
  92. meta: { ...this.opts.meta },
  93. info: [],
  94. })
  95. this.#restricter = new Restricter(() => this.opts, this.i18n)
  96. this.#storeUnsubscribe = this.store.subscribe((prevState, nextState, patch) => {
  97. this.emit('state-update', prevState, nextState, patch)
  98. this.updateAll(nextState)
  99. })
  100. // Exposing uppy object on window for debugging and testing
  101. if (this.opts.debug && typeof window !== 'undefined') {
  102. window[this.opts.id] = this
  103. }
  104. this.#addListeners()
  105. }
  106. emit (event, ...args) {
  107. this.#emitter.emit(event, ...args)
  108. }
  109. on (event, callback) {
  110. this.#emitter.on(event, callback)
  111. return this
  112. }
  113. once (event, callback) {
  114. this.#emitter.once(event, callback)
  115. return this
  116. }
  117. off (event, callback) {
  118. this.#emitter.off(event, callback)
  119. return this
  120. }
  121. /**
  122. * Iterate on all plugins and run `update` on them.
  123. * Called each time state changes.
  124. *
  125. */
  126. updateAll (state) {
  127. this.iteratePlugins(plugin => {
  128. plugin.update(state)
  129. })
  130. }
  131. /**
  132. * Updates state with a patch
  133. *
  134. * @param {object} patch {foo: 'bar'}
  135. */
  136. setState (patch) {
  137. this.store.setState(patch)
  138. }
  139. /**
  140. * Returns current state.
  141. *
  142. * @returns {object}
  143. */
  144. getState () {
  145. return this.store.getState()
  146. }
  147. patchFilesState (filesWithNewState) {
  148. const existingFilesState = this.getState().files
  149. this.setState({
  150. files: {
  151. ...existingFilesState,
  152. ...Object.fromEntries(Object.entries(filesWithNewState).map(([fileID, newFileState]) => ([
  153. fileID,
  154. {
  155. ...existingFilesState[fileID],
  156. ...newFileState,
  157. },
  158. ]))),
  159. },
  160. })
  161. }
  162. /**
  163. * Shorthand to set state for a specific file.
  164. */
  165. setFileState (fileID, state) {
  166. if (!this.getState().files[fileID]) {
  167. throw new Error(`Can’t set state for ${fileID} (the file could have been removed)`)
  168. }
  169. this.patchFilesState({ [fileID]: state })
  170. }
  171. i18nInit () {
  172. const translator = new Translator([this.defaultLocale, this.opts.locale])
  173. this.i18n = translator.translate.bind(translator)
  174. this.i18nArray = translator.translateArray.bind(translator)
  175. this.locale = translator.locale
  176. }
  177. setOptions (newOpts) {
  178. this.opts = {
  179. ...this.opts,
  180. ...newOpts,
  181. restrictions: {
  182. ...this.opts.restrictions,
  183. ...(newOpts && newOpts.restrictions),
  184. },
  185. }
  186. if (newOpts.meta) {
  187. this.setMeta(newOpts.meta)
  188. }
  189. this.i18nInit()
  190. if (newOpts.locale) {
  191. this.iteratePlugins((plugin) => {
  192. plugin.setOptions(newOpts)
  193. })
  194. }
  195. // Note: this is not the preact `setState`, it's an internal function that has the same name.
  196. this.setState() // so that UI re-renders with new options
  197. }
  198. // todo next major: rename to something better? (it doesn't just reset progress)
  199. resetProgress () {
  200. const defaultProgress = {
  201. percentage: 0,
  202. bytesUploaded: 0,
  203. uploadComplete: false,
  204. uploadStarted: null,
  205. }
  206. const files = { ...this.getState().files }
  207. const updatedFiles = {}
  208. Object.keys(files).forEach(fileID => {
  209. updatedFiles[fileID] = {
  210. ...files[fileID],
  211. progress: {
  212. ...files[fileID].progress, ...defaultProgress,
  213. },
  214. }
  215. })
  216. this.setState({ files: updatedFiles, ...getDefaultUploadState() })
  217. this.emit('reset-progress')
  218. }
  219. /** @protected */
  220. clearUploadedFiles () {
  221. this.setState({ ...getDefaultUploadState(), files: {} })
  222. }
  223. addPreProcessor (fn) {
  224. this.#preProcessors.add(fn)
  225. }
  226. removePreProcessor (fn) {
  227. return this.#preProcessors.delete(fn)
  228. }
  229. addPostProcessor (fn) {
  230. this.#postProcessors.add(fn)
  231. }
  232. removePostProcessor (fn) {
  233. return this.#postProcessors.delete(fn)
  234. }
  235. addUploader (fn) {
  236. this.#uploaders.add(fn)
  237. }
  238. removeUploader (fn) {
  239. return this.#uploaders.delete(fn)
  240. }
  241. setMeta (data) {
  242. const updatedMeta = { ...this.getState().meta, ...data }
  243. const updatedFiles = { ...this.getState().files }
  244. Object.keys(updatedFiles).forEach((fileID) => {
  245. updatedFiles[fileID] = { ...updatedFiles[fileID], meta: { ...updatedFiles[fileID].meta, ...data } }
  246. })
  247. this.log('Adding metadata:')
  248. this.log(data)
  249. this.setState({
  250. meta: updatedMeta,
  251. files: updatedFiles,
  252. })
  253. }
  254. setFileMeta (fileID, data) {
  255. const updatedFiles = { ...this.getState().files }
  256. if (!updatedFiles[fileID]) {
  257. this.log('Was trying to set metadata for a file that has been removed: ', fileID)
  258. return
  259. }
  260. const newMeta = { ...updatedFiles[fileID].meta, ...data }
  261. updatedFiles[fileID] = { ...updatedFiles[fileID], meta: newMeta }
  262. this.setState({ files: updatedFiles })
  263. }
  264. /**
  265. * Get a file object.
  266. *
  267. * @param {string} fileID The ID of the file object to return.
  268. */
  269. getFile (fileID) {
  270. return this.getState().files[fileID]
  271. }
  272. /**
  273. * Get all files in an array.
  274. */
  275. getFiles () {
  276. const { files } = this.getState()
  277. return Object.values(files)
  278. }
  279. getFilesByIds (ids) {
  280. return ids.map((id) => this.getFile(id))
  281. }
  282. getObjectOfFilesPerState () {
  283. const { files: filesObject, totalProgress, error } = this.getState()
  284. const files = Object.values(filesObject)
  285. const inProgressFiles = files.filter(({ progress }) => !progress.uploadComplete && progress.uploadStarted)
  286. const newFiles = files.filter((file) => !file.progress.uploadStarted)
  287. const startedFiles = files.filter(
  288. file => file.progress.uploadStarted || file.progress.preprocess || file.progress.postprocess,
  289. )
  290. const uploadStartedFiles = files.filter((file) => file.progress.uploadStarted)
  291. const pausedFiles = files.filter((file) => file.isPaused)
  292. const completeFiles = files.filter((file) => file.progress.uploadComplete)
  293. const erroredFiles = files.filter((file) => file.error)
  294. const inProgressNotPausedFiles = inProgressFiles.filter((file) => !file.isPaused)
  295. const processingFiles = files.filter((file) => file.progress.preprocess || file.progress.postprocess)
  296. return {
  297. newFiles,
  298. startedFiles,
  299. uploadStartedFiles,
  300. pausedFiles,
  301. completeFiles,
  302. erroredFiles,
  303. inProgressFiles,
  304. inProgressNotPausedFiles,
  305. processingFiles,
  306. isUploadStarted: uploadStartedFiles.length > 0,
  307. isAllComplete: totalProgress === 100
  308. && completeFiles.length === files.length
  309. && processingFiles.length === 0,
  310. isAllErrored: !!error && erroredFiles.length === files.length,
  311. isAllPaused: inProgressFiles.length !== 0 && pausedFiles.length === inProgressFiles.length,
  312. isUploadInProgress: inProgressFiles.length > 0,
  313. isSomeGhost: files.some(file => file.isGhost),
  314. }
  315. }
  316. /*
  317. * @constructs
  318. * @param { Error[] } errors
  319. * @param { undefined } file
  320. */
  321. /*
  322. * @constructs
  323. * @param { RestrictionError } error
  324. */
  325. #informAndEmit (errors) {
  326. for (const error of errors) {
  327. const { file, isRestriction } = error
  328. if (isRestriction) {
  329. this.emit('restriction-failed', file, error)
  330. } else {
  331. this.emit('error', error)
  332. }
  333. this.log(error, 'warning')
  334. }
  335. const userFacingErrors = errors.filter((error) => error.isUserFacing)
  336. // don't flood the user: only show the first 4 toasts
  337. const maxNumToShow = 4
  338. const firstErrors = userFacingErrors.slice(0, maxNumToShow)
  339. const additionalErrors = userFacingErrors.slice(maxNumToShow)
  340. firstErrors.forEach(({ message, details = '' }) => {
  341. this.info({ message, details }, 'error', this.opts.infoTimeout)
  342. })
  343. if (additionalErrors.length > 0) {
  344. this.info({ message: this.i18n('additionalRestrictionsFailed', { count: additionalErrors.length }) })
  345. }
  346. }
  347. validateRestrictions (file, files = this.getFiles()) {
  348. try {
  349. this.#restricter.validate(files, [file])
  350. } catch (err) {
  351. return err
  352. }
  353. return null
  354. }
  355. #checkRequiredMetaFieldsOnFile (file) {
  356. const { missingFields, error } = this.#restricter.getMissingRequiredMetaFields(file)
  357. if (missingFields.length > 0) {
  358. this.setFileState(file.id, { missingRequiredMetaFields: missingFields })
  359. this.log(error.message)
  360. this.emit('restriction-failed', file, error)
  361. return false
  362. }
  363. return true
  364. }
  365. #checkRequiredMetaFields (files) {
  366. let success = true
  367. for (const file of Object.values(files)) {
  368. if (!this.#checkRequiredMetaFieldsOnFile(file)) {
  369. success = false
  370. }
  371. }
  372. return success
  373. }
  374. #assertNewUploadAllowed (file) {
  375. const { allowNewUpload } = this.getState()
  376. if (allowNewUpload === false) {
  377. const error = new RestrictionError(this.i18n('noMoreFilesAllowed'), { file })
  378. this.#informAndEmit([error])
  379. throw error
  380. }
  381. }
  382. checkIfFileAlreadyExists (fileID) {
  383. const { files } = this.getState()
  384. if (files[fileID] && !files[fileID].isGhost) {
  385. return true
  386. }
  387. return false
  388. }
  389. /**
  390. * Create a file state object based on user-provided `addFile()` options.
  391. */
  392. #transformFile (fileDescriptorOrFile) {
  393. // Uppy expects files in { name, type, size, data } format.
  394. // If the actual File object is passed from input[type=file] or drag-drop,
  395. // we normalize it to match Uppy file object
  396. const fileDescriptor = fileDescriptorOrFile instanceof File ? {
  397. name: fileDescriptorOrFile.name,
  398. type: fileDescriptorOrFile.type,
  399. size: fileDescriptorOrFile.size,
  400. data: fileDescriptorOrFile,
  401. } : fileDescriptorOrFile
  402. const fileType = getFileType(fileDescriptor)
  403. const fileName = getFileName(fileType, fileDescriptor)
  404. const fileExtension = getFileNameAndExtension(fileName).extension
  405. const isRemote = Boolean(fileDescriptor.isRemote)
  406. const id = getSafeFileId(fileDescriptor)
  407. const meta = fileDescriptor.meta || {}
  408. meta.name = fileName
  409. meta.type = fileType
  410. // `null` means the size is unknown.
  411. const size = Number.isFinite(fileDescriptor.data.size) ? fileDescriptor.data.size : null
  412. return {
  413. source: fileDescriptor.source || '',
  414. id,
  415. name: fileName,
  416. extension: fileExtension || '',
  417. meta: {
  418. ...this.getState().meta,
  419. ...meta,
  420. },
  421. type: fileType,
  422. data: fileDescriptor.data,
  423. progress: {
  424. percentage: 0,
  425. bytesUploaded: 0,
  426. bytesTotal: size,
  427. uploadComplete: false,
  428. uploadStarted: null,
  429. },
  430. size,
  431. isRemote,
  432. remote: fileDescriptor.remote || '',
  433. preview: fileDescriptor.preview,
  434. }
  435. }
  436. // Schedule an upload if `autoProceed` is enabled.
  437. #startIfAutoProceed () {
  438. if (this.opts.autoProceed && !this.scheduledAutoProceed) {
  439. this.scheduledAutoProceed = setTimeout(() => {
  440. this.scheduledAutoProceed = null
  441. this.upload().catch((err) => {
  442. if (!err.isRestriction) {
  443. this.log(err.stack || err.message || err)
  444. }
  445. })
  446. }, 4)
  447. }
  448. }
  449. #checkAndUpdateFileState (filesToAdd) {
  450. const { files: existingFiles } = this.getState()
  451. // create a copy of the files object only once
  452. const nextFilesState = { ...existingFiles }
  453. const validFilesToAdd = []
  454. const errors = []
  455. for (const fileToAdd of filesToAdd) {
  456. try {
  457. let newFile = this.#transformFile(fileToAdd)
  458. // If a file has been recovered (Golden Retriever), but we were unable to recover its data (probably too large),
  459. // users are asked to re-select these half-recovered files and then this method will be called again.
  460. // In order to keep the progress, meta and everthing else, we keep the existing file,
  461. // but we replace `data`, and we remove `isGhost`, because the file is no longer a ghost now
  462. if (existingFiles[newFile.id]?.isGhost) {
  463. const { isGhost, ...existingFileState } = existingFiles[newFile.id]
  464. newFile = {
  465. ...existingFileState,
  466. data: fileToAdd.data,
  467. }
  468. this.log(`Replaced the blob in the restored ghost file: ${newFile.name}, ${newFile.id}`)
  469. }
  470. const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(newFile, nextFilesState)
  471. if (!onBeforeFileAddedResult && this.checkIfFileAlreadyExists(newFile.id)) {
  472. throw new RestrictionError(this.i18n('noDuplicates', { fileName: newFile.name }), { file: fileToAdd })
  473. }
  474. if (onBeforeFileAddedResult === false) {
  475. // Don’t show UI info for this error, as it should be done by the developer
  476. throw new RestrictionError('Cannot add the file because onBeforeFileAdded returned false.', { isUserFacing: false, file: fileToAdd })
  477. } else if (typeof onBeforeFileAddedResult === 'object' && onBeforeFileAddedResult !== null) {
  478. newFile = onBeforeFileAddedResult
  479. }
  480. this.#restricter.validateSingleFile(newFile)
  481. // need to add it to the new local state immediately, so we can use the state to validate the next files too
  482. nextFilesState[newFile.id] = newFile
  483. validFilesToAdd.push(newFile)
  484. } catch (err) {
  485. errors.push(err)
  486. }
  487. }
  488. try {
  489. // 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
  490. // when many files are added
  491. this.#restricter.validateAggregateRestrictions(Object.values(existingFiles), validFilesToAdd)
  492. } catch (err) {
  493. errors.push(err)
  494. // If we have any aggregate error, don't allow adding this batch
  495. return {
  496. nextFilesState: existingFiles,
  497. validFilesToAdd: [],
  498. errors,
  499. }
  500. }
  501. return {
  502. nextFilesState,
  503. validFilesToAdd,
  504. errors,
  505. }
  506. }
  507. /**
  508. * Add a new file to `state.files`. This will run `onBeforeFileAdded`,
  509. * try to guess file type in a clever way, check file against restrictions,
  510. * and start an upload if `autoProceed === true`.
  511. *
  512. * @param {object} file object to add
  513. * @returns {string} id for the added file
  514. */
  515. addFile (file) {
  516. this.#assertNewUploadAllowed(file)
  517. const { nextFilesState, validFilesToAdd, errors } = this.#checkAndUpdateFileState([file])
  518. const restrictionErrors = errors.filter((error) => error.isRestriction)
  519. this.#informAndEmit(restrictionErrors)
  520. if (errors.length > 0) throw errors[0]
  521. this.setState({ files: nextFilesState })
  522. const [firstValidFileToAdd] = validFilesToAdd
  523. this.emit('file-added', firstValidFileToAdd)
  524. this.emit('files-added', validFilesToAdd)
  525. this.log(`Added file: ${firstValidFileToAdd.name}, ${firstValidFileToAdd.id}, mime type: ${firstValidFileToAdd.type}`)
  526. this.#startIfAutoProceed()
  527. return firstValidFileToAdd.id
  528. }
  529. /**
  530. * Add multiple files to `state.files`. See the `addFile()` documentation.
  531. *
  532. * If an error occurs while adding a file, it is logged and the user is notified.
  533. * This is good for UI plugins, but not for programmatic use.
  534. * Programmatic users should usually still use `addFile()` on individual files.
  535. */
  536. addFiles (fileDescriptors) {
  537. this.#assertNewUploadAllowed()
  538. const { nextFilesState, validFilesToAdd, errors } = this.#checkAndUpdateFileState(fileDescriptors)
  539. const restrictionErrors = errors.filter((error) => error.isRestriction)
  540. this.#informAndEmit(restrictionErrors)
  541. const nonRestrictionErrors = errors.filter((error) => !error.isRestriction)
  542. if (nonRestrictionErrors.length > 0) {
  543. let message = 'Multiple errors occurred while adding files:\n'
  544. nonRestrictionErrors.forEach((subError) => {
  545. message += `\n * ${subError.message}`
  546. })
  547. this.info({
  548. message: this.i18n('addBulkFilesFailed', { smart_count: nonRestrictionErrors.length }),
  549. details: message,
  550. }, 'error', this.opts.infoTimeout)
  551. if (typeof AggregateError === 'function') {
  552. throw new AggregateError(nonRestrictionErrors, message)
  553. } else {
  554. const err = new Error(message)
  555. err.errors = nonRestrictionErrors
  556. throw err
  557. }
  558. }
  559. // OK, we haven't thrown an error, we can start updating state and emitting events now:
  560. this.setState({ files: nextFilesState })
  561. validFilesToAdd.forEach((file) => {
  562. this.emit('file-added', file)
  563. })
  564. this.emit('files-added', validFilesToAdd)
  565. if (validFilesToAdd.length > 5) {
  566. this.log(`Added batch of ${validFilesToAdd.length} files`)
  567. } else {
  568. Object.values(validFilesToAdd).forEach((file) => {
  569. this.log(`Added file: ${file.name}\n id: ${file.id}\n type: ${file.type}`)
  570. })
  571. }
  572. if (validFilesToAdd.length > 0) {
  573. this.#startIfAutoProceed()
  574. }
  575. }
  576. removeFiles (fileIDs, reason) {
  577. const { files, currentUploads } = this.getState()
  578. const updatedFiles = { ...files }
  579. const updatedUploads = { ...currentUploads }
  580. const removedFiles = Object.create(null)
  581. fileIDs.forEach((fileID) => {
  582. if (files[fileID]) {
  583. removedFiles[fileID] = files[fileID]
  584. delete updatedFiles[fileID]
  585. }
  586. })
  587. // Remove files from the `fileIDs` list in each upload.
  588. function fileIsNotRemoved (uploadFileID) {
  589. return removedFiles[uploadFileID] === undefined
  590. }
  591. Object.keys(updatedUploads).forEach((uploadID) => {
  592. const newFileIDs = currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved)
  593. // Remove the upload if no files are associated with it anymore.
  594. if (newFileIDs.length === 0) {
  595. delete updatedUploads[uploadID]
  596. return
  597. }
  598. const { capabilities } = this.getState()
  599. if (newFileIDs.length !== currentUploads[uploadID].fileIDs.length
  600. && !capabilities.individualCancellation) {
  601. throw new Error('individualCancellation is disabled')
  602. }
  603. updatedUploads[uploadID] = {
  604. ...currentUploads[uploadID],
  605. fileIDs: newFileIDs,
  606. }
  607. })
  608. const stateUpdate = {
  609. currentUploads: updatedUploads,
  610. files: updatedFiles,
  611. }
  612. // If all files were removed - allow new uploads,
  613. // and clear recoveredState
  614. if (Object.keys(updatedFiles).length === 0) {
  615. stateUpdate.allowNewUpload = true
  616. stateUpdate.error = null
  617. stateUpdate.recoveredState = null
  618. }
  619. this.setState(stateUpdate)
  620. this.calculateTotalProgress()
  621. const removedFileIDs = Object.keys(removedFiles)
  622. removedFileIDs.forEach((fileID) => {
  623. this.emit('file-removed', removedFiles[fileID], reason)
  624. })
  625. if (removedFileIDs.length > 5) {
  626. this.log(`Removed ${removedFileIDs.length} files`)
  627. } else {
  628. this.log(`Removed files: ${removedFileIDs.join(', ')}`)
  629. }
  630. }
  631. removeFile (fileID, reason = null) {
  632. this.removeFiles([fileID], reason)
  633. }
  634. pauseResume (fileID) {
  635. if (!this.getState().capabilities.resumableUploads
  636. || this.getFile(fileID).uploadComplete) {
  637. return undefined
  638. }
  639. const wasPaused = this.getFile(fileID).isPaused || false
  640. const isPaused = !wasPaused
  641. this.setFileState(fileID, {
  642. isPaused,
  643. })
  644. this.emit('upload-pause', fileID, isPaused)
  645. return isPaused
  646. }
  647. pauseAll () {
  648. const updatedFiles = { ...this.getState().files }
  649. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  650. return !updatedFiles[file].progress.uploadComplete
  651. && updatedFiles[file].progress.uploadStarted
  652. })
  653. inProgressUpdatedFiles.forEach((file) => {
  654. const updatedFile = { ...updatedFiles[file], isPaused: true }
  655. updatedFiles[file] = updatedFile
  656. })
  657. this.setState({ files: updatedFiles })
  658. this.emit('pause-all')
  659. }
  660. resumeAll () {
  661. const updatedFiles = { ...this.getState().files }
  662. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  663. return !updatedFiles[file].progress.uploadComplete
  664. && updatedFiles[file].progress.uploadStarted
  665. })
  666. inProgressUpdatedFiles.forEach((file) => {
  667. const updatedFile = {
  668. ...updatedFiles[file],
  669. isPaused: false,
  670. error: null,
  671. }
  672. updatedFiles[file] = updatedFile
  673. })
  674. this.setState({ files: updatedFiles })
  675. this.emit('resume-all')
  676. }
  677. retryAll () {
  678. const updatedFiles = { ...this.getState().files }
  679. const filesToRetry = Object.keys(updatedFiles).filter(file => {
  680. return updatedFiles[file].error
  681. })
  682. filesToRetry.forEach((file) => {
  683. const updatedFile = {
  684. ...updatedFiles[file],
  685. isPaused: false,
  686. error: null,
  687. }
  688. updatedFiles[file] = updatedFile
  689. })
  690. this.setState({
  691. files: updatedFiles,
  692. error: null,
  693. })
  694. this.emit('retry-all', filesToRetry)
  695. if (filesToRetry.length === 0) {
  696. return Promise.resolve({
  697. successful: [],
  698. failed: [],
  699. })
  700. }
  701. const uploadID = this.#createUpload(filesToRetry, {
  702. forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
  703. })
  704. return this.#runUpload(uploadID)
  705. }
  706. cancelAll ({ reason = 'user' } = {}) {
  707. this.emit('cancel-all', { reason })
  708. // Only remove existing uploads if user is canceling
  709. if (reason === 'user') {
  710. const { files } = this.getState()
  711. const fileIDs = Object.keys(files)
  712. if (fileIDs.length) {
  713. this.removeFiles(fileIDs, 'cancel-all')
  714. }
  715. this.setState(getDefaultUploadState())
  716. // todo should we call this.emit('reset-progress') like we do for resetProgress?
  717. }
  718. }
  719. retryUpload (fileID) {
  720. this.setFileState(fileID, {
  721. error: null,
  722. isPaused: false,
  723. })
  724. this.emit('upload-retry', fileID)
  725. const uploadID = this.#createUpload([fileID], {
  726. forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
  727. })
  728. return this.#runUpload(uploadID)
  729. }
  730. logout () {
  731. this.iteratePlugins(plugin => {
  732. if (plugin.provider && plugin.provider.logout) {
  733. plugin.provider.logout()
  734. }
  735. })
  736. }
  737. // ___Why throttle at 500ms?
  738. // - We must throttle at >250ms for superfocus in Dashboard to work well
  739. // (because animation takes 0.25s, and we want to wait for all animations to be over before refocusing).
  740. // [Practical Check]: if thottle is at 100ms, then if you are uploading a file,
  741. // and click 'ADD MORE FILES', - focus won't activate in Firefox.
  742. // - We must throttle at around >500ms to avoid performance lags.
  743. // [Practical Check] Firefox, try to upload a big file for a prolonged period of time. Laptop will start to heat up.
  744. calculateProgress = throttle((file, data) => {
  745. const fileInState = this.getFile(file?.id)
  746. if (file == null || !fileInState) {
  747. this.log(`Not setting progress for a file that has been removed: ${file?.id}`)
  748. return
  749. }
  750. if (fileInState.progress.percentage === 100) {
  751. this.log(`Not setting progress for a file that has been already uploaded: ${file.id}`)
  752. return
  753. }
  754. // bytesTotal may be null or zero; in that case we can't divide by it
  755. const canHavePercentage = Number.isFinite(data.bytesTotal) && data.bytesTotal > 0
  756. this.setFileState(file.id, {
  757. progress: {
  758. ...fileInState.progress,
  759. bytesUploaded: data.bytesUploaded,
  760. bytesTotal: data.bytesTotal,
  761. percentage: canHavePercentage
  762. ? Math.round((data.bytesUploaded / data.bytesTotal) * 100)
  763. : 0,
  764. },
  765. })
  766. this.calculateTotalProgress()
  767. }, 500, { leading: true, trailing: true })
  768. calculateTotalProgress () {
  769. // calculate total progress, using the number of files currently uploading,
  770. // multiplied by 100 and the summ of individual progress of each file
  771. const files = this.getFiles()
  772. const inProgress = files.filter((file) => {
  773. return file.progress.uploadStarted
  774. || file.progress.preprocess
  775. || file.progress.postprocess
  776. })
  777. if (inProgress.length === 0) {
  778. this.emit('progress', 0)
  779. this.setState({ totalProgress: 0 })
  780. return
  781. }
  782. const sizedFiles = inProgress.filter((file) => file.progress.bytesTotal != null)
  783. const unsizedFiles = inProgress.filter((file) => file.progress.bytesTotal == null)
  784. if (sizedFiles.length === 0) {
  785. const progressMax = inProgress.length * 100
  786. const currentProgress = unsizedFiles.reduce((acc, file) => {
  787. return acc + file.progress.percentage
  788. }, 0)
  789. const totalProgress = Math.round((currentProgress / progressMax) * 100)
  790. this.setState({ totalProgress })
  791. return
  792. }
  793. let totalSize = sizedFiles.reduce((acc, file) => {
  794. return acc + file.progress.bytesTotal
  795. }, 0)
  796. const averageSize = totalSize / sizedFiles.length
  797. totalSize += averageSize * unsizedFiles.length
  798. let uploadedSize = 0
  799. sizedFiles.forEach((file) => {
  800. uploadedSize += file.progress.bytesUploaded
  801. })
  802. unsizedFiles.forEach((file) => {
  803. uploadedSize += (averageSize * (file.progress.percentage || 0)) / 100
  804. })
  805. let totalProgress = totalSize === 0
  806. ? 0
  807. : Math.round((uploadedSize / totalSize) * 100)
  808. // hot fix, because:
  809. // uploadedSize ended up larger than totalSize, resulting in 1325% total
  810. if (totalProgress > 100) {
  811. totalProgress = 100
  812. }
  813. this.setState({ totalProgress })
  814. this.emit('progress', totalProgress)
  815. }
  816. /**
  817. * Registers listeners for all global actions, like:
  818. * `error`, `file-removed`, `upload-progress`
  819. */
  820. #addListeners () {
  821. /**
  822. * @param {Error} error
  823. * @param {object} [file]
  824. * @param {object} [response]
  825. */
  826. const errorHandler = (error, file, response) => {
  827. let errorMsg = error.message || 'Unknown error'
  828. if (error.details) {
  829. errorMsg += ` ${error.details}`
  830. }
  831. this.setState({ error: errorMsg })
  832. if (file != null && file.id in this.getState().files) {
  833. this.setFileState(file.id, {
  834. error: errorMsg,
  835. response,
  836. })
  837. }
  838. }
  839. this.on('error', errorHandler)
  840. this.on('upload-error', (file, error, response) => {
  841. errorHandler(error, file, response)
  842. if (typeof error === 'object' && error.message) {
  843. this.log(error.message, 'error')
  844. const newError = new Error(this.i18n('failedToUpload', { file: file?.name }))
  845. newError.isUserFacing = true // todo maybe don't do this with all errors?
  846. newError.details = error.message
  847. if (error.details) {
  848. newError.details += ` ${error.details}`
  849. }
  850. this.#informAndEmit([newError])
  851. } else {
  852. this.#informAndEmit([error])
  853. }
  854. })
  855. let uploadStalledWarningRecentlyEmitted
  856. this.on('upload-stalled', (error, files) => {
  857. const { message } = error
  858. const details = files.map(file => file.meta.name).join(', ')
  859. if (!uploadStalledWarningRecentlyEmitted) {
  860. this.info({ message, details }, 'warning', this.opts.infoTimeout)
  861. uploadStalledWarningRecentlyEmitted = setTimeout(() => {
  862. uploadStalledWarningRecentlyEmitted = null
  863. }, this.opts.infoTimeout)
  864. }
  865. this.log(`${message} ${details}`.trim(), 'warning')
  866. })
  867. this.on('upload', () => {
  868. this.setState({ error: null })
  869. })
  870. const onUploadStarted = (files) => {
  871. const filesFiltered = files.filter((file) => {
  872. const exists = (file != null && this.getFile(file.id))
  873. if (!exists) this.log(`Not setting progress for a file that has been removed: ${file?.id}`)
  874. return exists
  875. })
  876. const filesState = Object.fromEntries(filesFiltered.map((file) => ([
  877. file.id,
  878. {
  879. progress: {
  880. uploadStarted: Date.now(),
  881. uploadComplete: false,
  882. percentage: 0,
  883. bytesUploaded: 0,
  884. bytesTotal: file.size,
  885. },
  886. },
  887. ])))
  888. this.patchFilesState(filesState)
  889. }
  890. this.on('upload-start', (files) => {
  891. files.forEach((file) => {
  892. // todo backward compat, remove this event in a next major
  893. this.emit('upload-started', file)
  894. })
  895. onUploadStarted(files)
  896. })
  897. this.on('upload-progress', this.calculateProgress)
  898. this.on('upload-success', (file, uploadResp) => {
  899. if (file == null || !this.getFile(file.id)) {
  900. this.log(`Not setting progress for a file that has been removed: ${file?.id}`)
  901. return
  902. }
  903. const currentProgress = this.getFile(file.id).progress
  904. this.setFileState(file.id, {
  905. progress: {
  906. ...currentProgress,
  907. postprocess: this.#postProcessors.size > 0 ? {
  908. mode: 'indeterminate',
  909. } : null,
  910. uploadComplete: true,
  911. percentage: 100,
  912. bytesUploaded: currentProgress.bytesTotal,
  913. },
  914. response: uploadResp,
  915. uploadURL: uploadResp.uploadURL,
  916. isPaused: false,
  917. })
  918. // Remote providers sometimes don't tell us the file size,
  919. // but we can know how many bytes we uploaded once the upload is complete.
  920. if (file.size == null) {
  921. this.setFileState(file.id, {
  922. size: uploadResp.bytesUploaded || currentProgress.bytesTotal,
  923. })
  924. }
  925. this.calculateTotalProgress()
  926. })
  927. this.on('preprocess-progress', (file, progress) => {
  928. if (file == null || !this.getFile(file.id)) {
  929. this.log(`Not setting progress for a file that has been removed: ${file?.id}`)
  930. return
  931. }
  932. this.setFileState(file.id, {
  933. progress: { ...this.getFile(file.id).progress, preprocess: progress },
  934. })
  935. })
  936. this.on('preprocess-complete', (file) => {
  937. if (file == null || !this.getFile(file.id)) {
  938. this.log(`Not setting progress for a file that has been removed: ${file?.id}`)
  939. return
  940. }
  941. const files = { ...this.getState().files }
  942. files[file.id] = { ...files[file.id], progress: { ...files[file.id].progress } }
  943. delete files[file.id].progress.preprocess
  944. this.setState({ files })
  945. })
  946. this.on('postprocess-progress', (file, progress) => {
  947. if (file == null || !this.getFile(file.id)) {
  948. this.log(`Not setting progress for a file that has been removed: ${file?.id}`)
  949. return
  950. }
  951. this.setFileState(file.id, {
  952. progress: { ...this.getState().files[file.id].progress, postprocess: progress },
  953. })
  954. })
  955. this.on('postprocess-complete', (file) => {
  956. if (file == null || !this.getFile(file.id)) {
  957. this.log(`Not setting progress for a file that has been removed: ${file?.id}`)
  958. return
  959. }
  960. const files = {
  961. ...this.getState().files,
  962. }
  963. files[file.id] = {
  964. ...files[file.id],
  965. progress: {
  966. ...files[file.id].progress,
  967. },
  968. }
  969. delete files[file.id].progress.postprocess
  970. this.setState({ files })
  971. })
  972. this.on('restored', () => {
  973. // Files may have changed--ensure progress is still accurate.
  974. this.calculateTotalProgress()
  975. })
  976. this.on('dashboard:file-edit-complete', (file) => {
  977. if (file) {
  978. this.#checkRequiredMetaFieldsOnFile(file)
  979. }
  980. })
  981. // show informer if offline
  982. if (typeof window !== 'undefined' && window.addEventListener) {
  983. window.addEventListener('online', this.#updateOnlineStatus)
  984. window.addEventListener('offline', this.#updateOnlineStatus)
  985. setTimeout(this.#updateOnlineStatus, 3000)
  986. }
  987. }
  988. updateOnlineStatus () {
  989. const online = typeof window.navigator.onLine !== 'undefined'
  990. ? window.navigator.onLine
  991. : true
  992. if (!online) {
  993. this.emit('is-offline')
  994. this.info(this.i18n('noInternetConnection'), 'error', 0)
  995. this.wasOffline = true
  996. } else {
  997. this.emit('is-online')
  998. if (this.wasOffline) {
  999. this.emit('back-online')
  1000. this.info(this.i18n('connectedToInternet'), 'success', 3000)
  1001. this.wasOffline = false
  1002. }
  1003. }
  1004. }
  1005. #updateOnlineStatus = this.updateOnlineStatus.bind(this)
  1006. getID () {
  1007. return this.opts.id
  1008. }
  1009. /**
  1010. * Registers a plugin with Core.
  1011. *
  1012. * @param {object} Plugin object
  1013. * @param {object} [opts] object with options to be passed to Plugin
  1014. * @returns {object} self for chaining
  1015. */
  1016. // eslint-disable-next-line no-shadow
  1017. use (Plugin, opts) {
  1018. if (typeof Plugin !== 'function') {
  1019. const msg = `Expected a plugin class, but got ${Plugin === null ? 'null' : typeof Plugin}.`
  1020. + ' Please verify that the plugin was imported and spelled correctly.'
  1021. throw new TypeError(msg)
  1022. }
  1023. // Instantiate
  1024. const plugin = new Plugin(this, opts)
  1025. const pluginId = plugin.id
  1026. if (!pluginId) {
  1027. throw new Error('Your plugin must have an id')
  1028. }
  1029. if (!plugin.type) {
  1030. throw new Error('Your plugin must have a type')
  1031. }
  1032. const existsPluginAlready = this.getPlugin(pluginId)
  1033. if (existsPluginAlready) {
  1034. const msg = `Already found a plugin named '${existsPluginAlready.id}'. `
  1035. + `Tried to use: '${pluginId}'.\n`
  1036. + 'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.'
  1037. throw new Error(msg)
  1038. }
  1039. if (Plugin.VERSION) {
  1040. this.log(`Using ${pluginId} v${Plugin.VERSION}`)
  1041. }
  1042. if (plugin.type in this.#plugins) {
  1043. this.#plugins[plugin.type].push(plugin)
  1044. } else {
  1045. this.#plugins[plugin.type] = [plugin]
  1046. }
  1047. plugin.install()
  1048. this.emit('plugin-added', plugin)
  1049. return this
  1050. }
  1051. /**
  1052. * Find one Plugin by name.
  1053. *
  1054. * @param {string} id plugin id
  1055. * @returns {BasePlugin|undefined}
  1056. */
  1057. getPlugin (id) {
  1058. for (const plugins of Object.values(this.#plugins)) {
  1059. const foundPlugin = plugins.find(plugin => plugin.id === id)
  1060. if (foundPlugin != null) return foundPlugin
  1061. }
  1062. return undefined
  1063. }
  1064. [Symbol.for('uppy test: getPlugins')] (type) {
  1065. return this.#plugins[type]
  1066. }
  1067. /**
  1068. * Iterate through all `use`d plugins.
  1069. *
  1070. * @param {Function} method that will be run on each plugin
  1071. */
  1072. iteratePlugins (method) {
  1073. Object.values(this.#plugins).flat(1).forEach(method)
  1074. }
  1075. /**
  1076. * Uninstall and remove a plugin.
  1077. *
  1078. * @param {object} instance The plugin instance to remove.
  1079. */
  1080. removePlugin (instance) {
  1081. this.log(`Removing plugin ${instance.id}`)
  1082. this.emit('plugin-remove', instance)
  1083. if (instance.uninstall) {
  1084. instance.uninstall()
  1085. }
  1086. const list = this.#plugins[instance.type]
  1087. // list.indexOf failed here, because Vue3 converted the plugin instance
  1088. // to a Proxy object, which failed the strict comparison test:
  1089. // obj !== objProxy
  1090. const index = list.findIndex(item => item.id === instance.id)
  1091. if (index !== -1) {
  1092. list.splice(index, 1)
  1093. }
  1094. const state = this.getState()
  1095. const updatedState = {
  1096. plugins: {
  1097. ...state.plugins,
  1098. [instance.id]: undefined,
  1099. },
  1100. }
  1101. this.setState(updatedState)
  1102. }
  1103. /**
  1104. * Uninstall all plugins and close down this Uppy instance.
  1105. */
  1106. close ({ reason } = {}) {
  1107. this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`)
  1108. this.cancelAll({ reason })
  1109. this.#storeUnsubscribe()
  1110. this.iteratePlugins((plugin) => {
  1111. this.removePlugin(plugin)
  1112. })
  1113. if (typeof window !== 'undefined' && window.removeEventListener) {
  1114. window.removeEventListener('online', this.#updateOnlineStatus)
  1115. window.removeEventListener('offline', this.#updateOnlineStatus)
  1116. }
  1117. }
  1118. hideInfo () {
  1119. const { info } = this.getState()
  1120. this.setState({ info: info.slice(1) })
  1121. this.emit('info-hidden')
  1122. }
  1123. /**
  1124. * Set info message in `state.info`, so that UI plugins like `Informer`
  1125. * can display the message.
  1126. *
  1127. * @param {string | object} message Message to be displayed by the informer
  1128. * @param {string} [type]
  1129. * @param {number} [duration]
  1130. */
  1131. info (message, type = 'info', duration = 3000) {
  1132. const isComplexMessage = typeof message === 'object'
  1133. this.setState({
  1134. info: [
  1135. ...this.getState().info,
  1136. {
  1137. type,
  1138. message: isComplexMessage ? message.message : message,
  1139. details: isComplexMessage ? message.details : null,
  1140. },
  1141. ],
  1142. })
  1143. setTimeout(() => this.hideInfo(), duration)
  1144. this.emit('info-visible')
  1145. }
  1146. /**
  1147. * Passes messages to a function, provided in `opts.logger`.
  1148. * If `opts.logger: Uppy.debugLogger` or `opts.debug: true`, logs to the browser console.
  1149. *
  1150. * @param {string|object} message to log
  1151. * @param {string} [type] optional `error` or `warning`
  1152. */
  1153. log (message, type) {
  1154. const { logger } = this.opts
  1155. switch (type) {
  1156. case 'error': logger.error(message); break
  1157. case 'warning': logger.warn(message); break
  1158. default: logger.debug(message); break
  1159. }
  1160. }
  1161. /**
  1162. * Restore an upload by its ID.
  1163. */
  1164. restore (uploadID) {
  1165. this.log(`Core: attempting to restore upload "${uploadID}"`)
  1166. if (!this.getState().currentUploads[uploadID]) {
  1167. this.#removeUpload(uploadID)
  1168. return Promise.reject(new Error('Nonexistent upload'))
  1169. }
  1170. return this.#runUpload(uploadID)
  1171. }
  1172. /**
  1173. * Create an upload for a bunch of files.
  1174. *
  1175. * @param {Array<string>} fileIDs File IDs to include in this upload.
  1176. * @returns {string} ID of this upload.
  1177. */
  1178. #createUpload (fileIDs, opts = {}) {
  1179. // uppy.retryAll sets this to true — when retrying we want to ignore `allowNewUpload: false`
  1180. const { forceAllowNewUpload = false } = opts
  1181. const { allowNewUpload, currentUploads } = this.getState()
  1182. if (!allowNewUpload && !forceAllowNewUpload) {
  1183. throw new Error('Cannot create a new upload: already uploading.')
  1184. }
  1185. const uploadID = nanoid()
  1186. this.emit('upload', {
  1187. id: uploadID,
  1188. fileIDs,
  1189. })
  1190. this.setState({
  1191. allowNewUpload: this.opts.allowMultipleUploadBatches !== false && this.opts.allowMultipleUploads !== false,
  1192. currentUploads: {
  1193. ...currentUploads,
  1194. [uploadID]: {
  1195. fileIDs,
  1196. step: 0,
  1197. result: {},
  1198. },
  1199. },
  1200. })
  1201. return uploadID
  1202. }
  1203. [Symbol.for('uppy test: createUpload')] (...args) { return this.#createUpload(...args) }
  1204. #getUpload (uploadID) {
  1205. const { currentUploads } = this.getState()
  1206. return currentUploads[uploadID]
  1207. }
  1208. /**
  1209. * Add data to an upload's result object.
  1210. *
  1211. * @param {string} uploadID The ID of the upload.
  1212. * @param {object} data Data properties to add to the result object.
  1213. */
  1214. addResultData (uploadID, data) {
  1215. if (!this.#getUpload(uploadID)) {
  1216. this.log(`Not setting result for an upload that has been removed: ${uploadID}`)
  1217. return
  1218. }
  1219. const { currentUploads } = this.getState()
  1220. const currentUpload = { ...currentUploads[uploadID], result: { ...currentUploads[uploadID].result, ...data } }
  1221. this.setState({
  1222. currentUploads: { ...currentUploads, [uploadID]: currentUpload },
  1223. })
  1224. }
  1225. /**
  1226. * Remove an upload, eg. if it has been canceled or completed.
  1227. *
  1228. * @param {string} uploadID The ID of the upload.
  1229. */
  1230. #removeUpload (uploadID) {
  1231. const currentUploads = { ...this.getState().currentUploads }
  1232. delete currentUploads[uploadID]
  1233. this.setState({
  1234. currentUploads,
  1235. })
  1236. }
  1237. /**
  1238. * Run an upload. This picks up where it left off in case the upload is being restored.
  1239. *
  1240. * @private
  1241. */
  1242. async #runUpload (uploadID) {
  1243. const getCurrentUpload = () => {
  1244. const { currentUploads } = this.getState()
  1245. return currentUploads[uploadID]
  1246. }
  1247. let currentUpload = getCurrentUpload()
  1248. const steps = [
  1249. ...this.#preProcessors,
  1250. ...this.#uploaders,
  1251. ...this.#postProcessors,
  1252. ]
  1253. try {
  1254. for (let step = currentUpload.step || 0; step < steps.length; step++) {
  1255. if (!currentUpload) {
  1256. break
  1257. }
  1258. const fn = steps[step]
  1259. this.setState({
  1260. currentUploads: {
  1261. ...this.getState().currentUploads,
  1262. [uploadID]: {
  1263. ...currentUpload,
  1264. step,
  1265. },
  1266. },
  1267. })
  1268. const { fileIDs } = currentUpload
  1269. // TODO give this the `updatedUpload` object as its only parameter maybe?
  1270. // Otherwise when more metadata may be added to the upload this would keep getting more parameters
  1271. await fn(fileIDs, uploadID)
  1272. // Update currentUpload value in case it was modified asynchronously.
  1273. currentUpload = getCurrentUpload()
  1274. }
  1275. } catch (err) {
  1276. this.#removeUpload(uploadID)
  1277. throw err
  1278. }
  1279. // Set result data.
  1280. if (currentUpload) {
  1281. // Mark postprocessing step as complete if necessary; this addresses a case where we might get
  1282. // stuck in the postprocessing UI while the upload is fully complete.
  1283. // If the postprocessing steps do not do any work, they may not emit postprocessing events at
  1284. // all, and never mark the postprocessing as complete. This is fine on its own but we
  1285. // introduced code in the @uppy/core upload-success handler to prepare postprocessing progress
  1286. // state if any postprocessors are registered. That is to avoid a "flash of completed state"
  1287. // before the postprocessing plugins can emit events.
  1288. //
  1289. // So, just in case an upload with postprocessing plugins *has* completed *without* emitting
  1290. // postprocessing completion, we do it instead.
  1291. currentUpload.fileIDs.forEach((fileID) => {
  1292. const file = this.getFile(fileID)
  1293. if (file && file.progress.postprocess) {
  1294. this.emit('postprocess-complete', file)
  1295. }
  1296. })
  1297. const files = currentUpload.fileIDs.map((fileID) => this.getFile(fileID))
  1298. const successful = files.filter((file) => !file.error)
  1299. const failed = files.filter((file) => file.error)
  1300. await this.addResultData(uploadID, { successful, failed, uploadID })
  1301. // Update currentUpload value in case it was modified asynchronously.
  1302. currentUpload = getCurrentUpload()
  1303. }
  1304. // Emit completion events.
  1305. // This is in a separate function so that the `currentUploads` variable
  1306. // always refers to the latest state. In the handler right above it refers
  1307. // to an outdated object without the `.result` property.
  1308. let result
  1309. if (currentUpload) {
  1310. result = currentUpload.result
  1311. this.emit('complete', result)
  1312. this.#removeUpload(uploadID)
  1313. }
  1314. if (result == null) {
  1315. this.log(`Not setting result for an upload that has been removed: ${uploadID}`)
  1316. }
  1317. return result
  1318. }
  1319. /**
  1320. * Start an upload for all the files that are not currently being uploaded.
  1321. *
  1322. * @returns {Promise}
  1323. */
  1324. upload () {
  1325. if (!this.#plugins.uploader?.length) {
  1326. this.log('No uploader type plugins are used', 'warning')
  1327. }
  1328. let { files } = this.getState()
  1329. const onBeforeUploadResult = this.opts.onBeforeUpload(files)
  1330. if (onBeforeUploadResult === false) {
  1331. return Promise.reject(new Error('Not starting the upload because onBeforeUpload returned false'))
  1332. }
  1333. if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {
  1334. files = onBeforeUploadResult
  1335. // Updating files in state, because uploader plugins receive file IDs,
  1336. // and then fetch the actual file object from state
  1337. this.setState({
  1338. files,
  1339. })
  1340. }
  1341. return Promise.resolve()
  1342. .then(() => this.#restricter.validateMinNumberOfFiles(files))
  1343. .catch((err) => {
  1344. this.#informAndEmit([err])
  1345. throw err
  1346. })
  1347. .then(() => {
  1348. if (!this.#checkRequiredMetaFields(files)) {
  1349. throw new RestrictionError(this.i18n('missingRequiredMetaField'))
  1350. }
  1351. })
  1352. .catch((err) => {
  1353. // Doing this in a separate catch because we already emited and logged
  1354. // all the errors in `checkRequiredMetaFields` so we only throw a generic
  1355. // missing fields error here.
  1356. throw err
  1357. })
  1358. .then(() => {
  1359. const { currentUploads } = this.getState()
  1360. // get a list of files that are currently assigned to uploads
  1361. const currentlyUploadingFiles = Object.values(currentUploads).flatMap(curr => curr.fileIDs)
  1362. const waitingFileIDs = []
  1363. Object.keys(files).forEach((fileID) => {
  1364. const file = this.getFile(fileID)
  1365. // if the file hasn't started uploading and hasn't already been assigned to an upload..
  1366. if ((!file.progress.uploadStarted) && (currentlyUploadingFiles.indexOf(fileID) === -1)) {
  1367. waitingFileIDs.push(file.id)
  1368. }
  1369. })
  1370. const uploadID = this.#createUpload(waitingFileIDs)
  1371. return this.#runUpload(uploadID)
  1372. })
  1373. .catch((err) => {
  1374. this.emit('error', err)
  1375. this.log(err, 'error')
  1376. throw err
  1377. })
  1378. }
  1379. }
  1380. export default Uppy