index.js 49 KB

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