Uppy.js 44 KB

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