index.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. const Translator = require('@uppy/utils/lib/Translator')
  2. const ee = require('namespace-emitter')
  3. const cuid = require('cuid')
  4. // const throttle = require('lodash.throttle')
  5. const prettyBytes = require('prettier-bytes')
  6. const match = require('mime-match')
  7. const DefaultStore = require('@uppy/store-default')
  8. const getFileType = require('@uppy/utils/lib/getFileType')
  9. const getFileNameAndExtension = require('@uppy/utils/lib/getFileNameAndExtension')
  10. const generateFileID = require('@uppy/utils/lib/generateFileID')
  11. const getTimeStamp = require('@uppy/utils/lib/getTimeStamp')
  12. const supportsUploadProgress = require('./supportsUploadProgress')
  13. const Plugin = require('./Plugin') // Exported from here.
  14. /**
  15. * Uppy Core module.
  16. * Manages plugins, state updates, acts as an event bus,
  17. * adds/removes files and metadata.
  18. */
  19. class Uppy {
  20. /**
  21. * Instantiate Uppy
  22. * @param {object} opts — Uppy options
  23. */
  24. constructor (opts) {
  25. this.defaultLocale = {
  26. strings: {
  27. youCanOnlyUploadX: {
  28. 0: 'You can only upload %{smart_count} file',
  29. 1: 'You can only upload %{smart_count} files',
  30. 2: 'You can only upload %{smart_count} files'
  31. },
  32. youHaveToAtLeastSelectX: {
  33. 0: 'You have to select at least %{smart_count} file',
  34. 1: 'You have to select at least %{smart_count} files',
  35. 2: 'You have to select at least %{smart_count} files'
  36. },
  37. exceedsSize: 'This file exceeds maximum allowed size of',
  38. youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
  39. companionError: 'Connection with Companion failed',
  40. companionAuthError: 'Authorization required',
  41. failedToUpload: 'Failed to upload %{file}',
  42. noInternetConnection: 'No Internet connection',
  43. connectedToInternet: 'Connected to the Internet',
  44. // Strings for remote providers
  45. noFilesFound: 'You have no files or folders here',
  46. selectXFiles: {
  47. 0: 'Select %{smart_count} file',
  48. 1: 'Select %{smart_count} files',
  49. 2: 'Select %{smart_count} files'
  50. },
  51. cancel: 'Cancel',
  52. logOut: 'Log out',
  53. filter: 'Filter',
  54. resetFilter: 'Reset filter',
  55. loading: 'Loading...',
  56. authenticateWithTitle: 'Please authenticate with %{pluginName} to select files',
  57. authenticateWith: 'Connect to %{pluginName}'
  58. }
  59. }
  60. // set default options
  61. const defaultOptions = {
  62. id: 'uppy',
  63. autoProceed: false,
  64. allowMultipleUploads: true,
  65. debug: false,
  66. restrictions: {
  67. maxFileSize: null,
  68. maxNumberOfFiles: null,
  69. minNumberOfFiles: null,
  70. allowedFileTypes: null
  71. },
  72. meta: {},
  73. onBeforeFileAdded: (currentFile, files) => currentFile,
  74. onBeforeUpload: (files) => files,
  75. store: DefaultStore()
  76. }
  77. // Merge default options with the ones set by user
  78. this.opts = Object.assign({}, defaultOptions, opts)
  79. this.opts.restrictions = Object.assign({}, defaultOptions.restrictions, this.opts.restrictions)
  80. // i18n
  81. this.translator = new Translator([ this.defaultLocale, this.opts.locale ])
  82. this.locale = this.translator.locale
  83. this.i18n = this.translator.translate.bind(this.translator)
  84. this.i18nArray = this.translator.translateArray.bind(this.translator)
  85. // Container for different types of plugins
  86. this.plugins = {}
  87. this.getState = this.getState.bind(this)
  88. this.getPlugin = this.getPlugin.bind(this)
  89. this.setFileMeta = this.setFileMeta.bind(this)
  90. this.setFileState = this.setFileState.bind(this)
  91. this.log = this.log.bind(this)
  92. this.info = this.info.bind(this)
  93. this.hideInfo = this.hideInfo.bind(this)
  94. this.addFile = this.addFile.bind(this)
  95. this.removeFile = this.removeFile.bind(this)
  96. this.pauseResume = this.pauseResume.bind(this)
  97. this._calculateProgress = this._calculateProgress.bind(this)
  98. this.updateOnlineStatus = this.updateOnlineStatus.bind(this)
  99. this.resetProgress = this.resetProgress.bind(this)
  100. this.pauseAll = this.pauseAll.bind(this)
  101. this.resumeAll = this.resumeAll.bind(this)
  102. this.retryAll = this.retryAll.bind(this)
  103. this.cancelAll = this.cancelAll.bind(this)
  104. this.retryUpload = this.retryUpload.bind(this)
  105. this.upload = this.upload.bind(this)
  106. this.emitter = ee()
  107. this.on = this.on.bind(this)
  108. this.off = this.off.bind(this)
  109. this.once = this.emitter.once.bind(this.emitter)
  110. this.emit = this.emitter.emit.bind(this.emitter)
  111. this.preProcessors = []
  112. this.uploaders = []
  113. this.postProcessors = []
  114. this.store = this.opts.store
  115. this.setState({
  116. plugins: {},
  117. files: {},
  118. currentUploads: {},
  119. allowNewUpload: true,
  120. capabilities: {
  121. uploadProgress: supportsUploadProgress(),
  122. individualCancellation: true,
  123. resumableUploads: false
  124. },
  125. totalProgress: 0,
  126. meta: { ...this.opts.meta },
  127. info: {
  128. isHidden: true,
  129. type: 'info',
  130. message: ''
  131. }
  132. })
  133. this._storeUnsubscribe = this.store.subscribe((prevState, nextState, patch) => {
  134. this.emit('state-update', prevState, nextState, patch)
  135. this.updateAll(nextState)
  136. })
  137. // for debugging and testing
  138. // this.updateNum = 0
  139. if (this.opts.debug && typeof window !== 'undefined') {
  140. window['uppyLog'] = ''
  141. window[this.opts.id] = this
  142. }
  143. this._addListeners()
  144. }
  145. on (event, callback) {
  146. this.emitter.on(event, callback)
  147. return this
  148. }
  149. off (event, callback) {
  150. this.emitter.off(event, callback)
  151. return this
  152. }
  153. /**
  154. * Iterate on all plugins and run `update` on them.
  155. * Called each time state changes.
  156. *
  157. */
  158. updateAll (state) {
  159. this.iteratePlugins(plugin => {
  160. plugin.update(state)
  161. })
  162. }
  163. /**
  164. * Updates state with a patch
  165. *
  166. * @param {object} patch {foo: 'bar'}
  167. */
  168. setState (patch) {
  169. this.store.setState(patch)
  170. }
  171. /**
  172. * Returns current state.
  173. * @return {object}
  174. */
  175. getState () {
  176. return this.store.getState()
  177. }
  178. /**
  179. * Back compat for when uppy.state is used instead of uppy.getState().
  180. */
  181. get state () {
  182. return this.getState()
  183. }
  184. /**
  185. * Shorthand to set state for a specific file.
  186. */
  187. setFileState (fileID, state) {
  188. if (!this.getState().files[fileID]) {
  189. throw new Error(`Can’t set state for ${fileID} (the file could have been removed)`)
  190. }
  191. this.setState({
  192. files: Object.assign({}, this.getState().files, {
  193. [fileID]: Object.assign({}, this.getState().files[fileID], state)
  194. })
  195. })
  196. }
  197. resetProgress () {
  198. const defaultProgress = {
  199. percentage: 0,
  200. bytesUploaded: 0,
  201. uploadComplete: false,
  202. uploadStarted: null
  203. }
  204. const files = Object.assign({}, this.getState().files)
  205. const updatedFiles = {}
  206. Object.keys(files).forEach(fileID => {
  207. const updatedFile = Object.assign({}, files[fileID])
  208. updatedFile.progress = Object.assign({}, updatedFile.progress, defaultProgress)
  209. updatedFiles[fileID] = updatedFile
  210. })
  211. this.setState({
  212. files: updatedFiles,
  213. totalProgress: 0
  214. })
  215. // TODO Document on the website
  216. this.emit('reset-progress')
  217. }
  218. addPreProcessor (fn) {
  219. this.preProcessors.push(fn)
  220. }
  221. removePreProcessor (fn) {
  222. const i = this.preProcessors.indexOf(fn)
  223. if (i !== -1) {
  224. this.preProcessors.splice(i, 1)
  225. }
  226. }
  227. addPostProcessor (fn) {
  228. this.postProcessors.push(fn)
  229. }
  230. removePostProcessor (fn) {
  231. const i = this.postProcessors.indexOf(fn)
  232. if (i !== -1) {
  233. this.postProcessors.splice(i, 1)
  234. }
  235. }
  236. addUploader (fn) {
  237. this.uploaders.push(fn)
  238. }
  239. removeUploader (fn) {
  240. const i = this.uploaders.indexOf(fn)
  241. if (i !== -1) {
  242. this.uploaders.splice(i, 1)
  243. }
  244. }
  245. setMeta (data) {
  246. const updatedMeta = Object.assign({}, this.getState().meta, data)
  247. const updatedFiles = Object.assign({}, this.getState().files)
  248. Object.keys(updatedFiles).forEach((fileID) => {
  249. updatedFiles[fileID] = Object.assign({}, updatedFiles[fileID], {
  250. meta: Object.assign({}, updatedFiles[fileID].meta, data)
  251. })
  252. })
  253. this.log('Adding metadata:')
  254. this.log(data)
  255. this.setState({
  256. meta: updatedMeta,
  257. files: updatedFiles
  258. })
  259. }
  260. setFileMeta (fileID, data) {
  261. const updatedFiles = Object.assign({}, this.getState().files)
  262. if (!updatedFiles[fileID]) {
  263. this.log('Was trying to set metadata for a file that’s not with us anymore: ', fileID)
  264. return
  265. }
  266. const newMeta = Object.assign({}, updatedFiles[fileID].meta, data)
  267. updatedFiles[fileID] = Object.assign({}, updatedFiles[fileID], {
  268. meta: newMeta
  269. })
  270. this.setState({ files: updatedFiles })
  271. }
  272. /**
  273. * Get a file object.
  274. *
  275. * @param {string} fileID The ID of the file object to return.
  276. */
  277. getFile (fileID) {
  278. return this.getState().files[fileID]
  279. }
  280. /**
  281. * Get all files in an array.
  282. */
  283. getFiles () {
  284. const { files } = this.getState()
  285. return Object.keys(files).map((fileID) => files[fileID])
  286. }
  287. /**
  288. * Check if minNumberOfFiles restriction is reached before uploading.
  289. *
  290. * @private
  291. */
  292. _checkMinNumberOfFiles (files) {
  293. const { minNumberOfFiles } = this.opts.restrictions
  294. if (Object.keys(files).length < minNumberOfFiles) {
  295. throw new Error(`${this.i18n('youHaveToAtLeastSelectX', { smart_count: minNumberOfFiles })}`)
  296. }
  297. }
  298. /**
  299. * Check if file passes a set of restrictions set in options: maxFileSize,
  300. * maxNumberOfFiles and allowedFileTypes.
  301. *
  302. * @param {object} file object to check
  303. * @private
  304. */
  305. _checkRestrictions (file) {
  306. const { maxFileSize, maxNumberOfFiles, allowedFileTypes } = this.opts.restrictions
  307. if (maxNumberOfFiles) {
  308. if (Object.keys(this.getState().files).length + 1 > maxNumberOfFiles) {
  309. throw new Error(`${this.i18n('youCanOnlyUploadX', { smart_count: maxNumberOfFiles })}`)
  310. }
  311. }
  312. if (allowedFileTypes) {
  313. const isCorrectFileType = allowedFileTypes.some((type) => {
  314. // if (!file.type) return false
  315. // is this is a mime-type
  316. if (type.indexOf('/') > -1) {
  317. if (!file.type) return false
  318. return match(file.type, type)
  319. }
  320. // otherwise this is likely an extension
  321. if (type[0] === '.') {
  322. return file.extension.toLowerCase() === type.substr(1).toLowerCase()
  323. }
  324. return false
  325. })
  326. if (!isCorrectFileType) {
  327. const allowedFileTypesString = allowedFileTypes.join(', ')
  328. throw new Error(this.i18n('youCanOnlyUploadFileTypes', { types: allowedFileTypesString }))
  329. }
  330. }
  331. // We can't check maxFileSize if the size is unknown.
  332. if (maxFileSize && file.data.size != null) {
  333. if (file.data.size > maxFileSize) {
  334. throw new Error(`${this.i18n('exceedsSize')} ${prettyBytes(maxFileSize)}`)
  335. }
  336. }
  337. }
  338. /**
  339. * Add a new file to `state.files`. This will run `onBeforeFileAdded`,
  340. * try to guess file type in a clever way, check file against restrictions,
  341. * and start an upload if `autoProceed === true`.
  342. *
  343. * @param {object} file object to add
  344. */
  345. addFile (file) {
  346. const { files, allowNewUpload } = this.getState()
  347. const onError = (msg) => {
  348. const err = typeof msg === 'object' ? msg : new Error(msg)
  349. this.log(err.message)
  350. this.info(err.message, 'error', 5000)
  351. throw err
  352. }
  353. if (allowNewUpload === false) {
  354. onError(new Error('Cannot add new files: already uploading.'))
  355. }
  356. const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(file, files)
  357. if (onBeforeFileAddedResult === false) {
  358. this.log('Not adding file because onBeforeFileAdded returned false')
  359. return
  360. }
  361. if (typeof onBeforeFileAddedResult === 'object' && onBeforeFileAddedResult) {
  362. // warning after the change in 0.24
  363. if (onBeforeFileAddedResult.then) {
  364. throw new TypeError('onBeforeFileAdded() returned a Promise, but this is no longer supported. It must be synchronous.')
  365. }
  366. file = onBeforeFileAddedResult
  367. }
  368. const fileType = getFileType(file)
  369. let fileName
  370. if (file.name) {
  371. fileName = file.name
  372. } else if (fileType.split('/')[0] === 'image') {
  373. fileName = fileType.split('/')[0] + '.' + fileType.split('/')[1]
  374. } else {
  375. fileName = 'noname'
  376. }
  377. const fileExtension = getFileNameAndExtension(fileName).extension
  378. const isRemote = file.isRemote || false
  379. const fileID = generateFileID(file)
  380. const meta = file.meta || {}
  381. meta.name = fileName
  382. meta.type = fileType
  383. // `null` means the size is unknown.
  384. const size = isFinite(file.data.size) ? file.data.size : null
  385. const newFile = {
  386. source: file.source || '',
  387. id: fileID,
  388. name: fileName,
  389. extension: fileExtension || '',
  390. meta: Object.assign({}, this.getState().meta, meta),
  391. type: fileType,
  392. data: file.data,
  393. progress: {
  394. percentage: 0,
  395. bytesUploaded: 0,
  396. bytesTotal: size,
  397. uploadComplete: false,
  398. uploadStarted: null
  399. },
  400. size: size,
  401. isRemote: isRemote,
  402. remote: file.remote || '',
  403. preview: file.preview
  404. }
  405. try {
  406. this._checkRestrictions(newFile)
  407. } catch (err) {
  408. this.emit('restriction-failed', newFile, err)
  409. onError(err)
  410. }
  411. this.setState({
  412. files: Object.assign({}, files, {
  413. [fileID]: newFile
  414. })
  415. })
  416. this.emit('file-added', newFile)
  417. this.log(`Added file: ${fileName}, ${fileID}, mime type: ${fileType}`)
  418. if (this.opts.autoProceed && !this.scheduledAutoProceed) {
  419. this.scheduledAutoProceed = setTimeout(() => {
  420. this.scheduledAutoProceed = null
  421. this.upload().catch((err) => {
  422. console.error(err.stack || err.message || err)
  423. })
  424. }, 4)
  425. }
  426. }
  427. removeFile (fileID) {
  428. const { files, currentUploads } = this.getState()
  429. const updatedFiles = Object.assign({}, files)
  430. const removedFile = updatedFiles[fileID]
  431. delete updatedFiles[fileID]
  432. // Remove this file from its `currentUpload`.
  433. const updatedUploads = Object.assign({}, currentUploads)
  434. const removeUploads = []
  435. Object.keys(updatedUploads).forEach((uploadID) => {
  436. const newFileIDs = currentUploads[uploadID].fileIDs.filter((uploadFileID) => uploadFileID !== fileID)
  437. // Remove the upload if no files are associated with it anymore.
  438. if (newFileIDs.length === 0) {
  439. removeUploads.push(uploadID)
  440. return
  441. }
  442. updatedUploads[uploadID] = Object.assign({}, currentUploads[uploadID], {
  443. fileIDs: newFileIDs
  444. })
  445. })
  446. this.setState({
  447. currentUploads: updatedUploads,
  448. files: updatedFiles
  449. })
  450. removeUploads.forEach((uploadID) => {
  451. this._removeUpload(uploadID)
  452. })
  453. this._calculateTotalProgress()
  454. this.emit('file-removed', removedFile)
  455. this.log(`File removed: ${removedFile.id}`)
  456. }
  457. pauseResume (fileID) {
  458. if (!this.getState().capabilities.resumableUploads ||
  459. this.getFile(fileID).uploadComplete) {
  460. return
  461. }
  462. const wasPaused = this.getFile(fileID).isPaused || false
  463. const isPaused = !wasPaused
  464. this.setFileState(fileID, {
  465. isPaused: isPaused
  466. })
  467. this.emit('upload-pause', fileID, isPaused)
  468. return isPaused
  469. }
  470. pauseAll () {
  471. const updatedFiles = Object.assign({}, this.getState().files)
  472. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  473. return !updatedFiles[file].progress.uploadComplete &&
  474. updatedFiles[file].progress.uploadStarted
  475. })
  476. inProgressUpdatedFiles.forEach((file) => {
  477. const updatedFile = Object.assign({}, updatedFiles[file], {
  478. isPaused: true
  479. })
  480. updatedFiles[file] = updatedFile
  481. })
  482. this.setState({ files: updatedFiles })
  483. this.emit('pause-all')
  484. }
  485. resumeAll () {
  486. const updatedFiles = Object.assign({}, this.getState().files)
  487. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  488. return !updatedFiles[file].progress.uploadComplete &&
  489. updatedFiles[file].progress.uploadStarted
  490. })
  491. inProgressUpdatedFiles.forEach((file) => {
  492. const updatedFile = Object.assign({}, updatedFiles[file], {
  493. isPaused: false,
  494. error: null
  495. })
  496. updatedFiles[file] = updatedFile
  497. })
  498. this.setState({ files: updatedFiles })
  499. this.emit('resume-all')
  500. }
  501. retryAll () {
  502. const updatedFiles = Object.assign({}, this.getState().files)
  503. const filesToRetry = Object.keys(updatedFiles).filter(file => {
  504. return updatedFiles[file].error
  505. })
  506. filesToRetry.forEach((file) => {
  507. const updatedFile = Object.assign({}, updatedFiles[file], {
  508. isPaused: false,
  509. error: null
  510. })
  511. updatedFiles[file] = updatedFile
  512. })
  513. this.setState({
  514. files: updatedFiles,
  515. error: null
  516. })
  517. this.emit('retry-all', filesToRetry)
  518. const uploadID = this._createUpload(filesToRetry)
  519. return this._runUpload(uploadID)
  520. }
  521. cancelAll () {
  522. this.emit('cancel-all')
  523. const files = Object.keys(this.getState().files)
  524. files.forEach((fileID) => {
  525. this.removeFile(fileID)
  526. })
  527. this.setState({
  528. allowNewUpload: true,
  529. totalProgress: 0,
  530. error: null
  531. })
  532. }
  533. retryUpload (fileID) {
  534. const updatedFiles = Object.assign({}, this.getState().files)
  535. const updatedFile = Object.assign({}, updatedFiles[fileID],
  536. { error: null, isPaused: false }
  537. )
  538. updatedFiles[fileID] = updatedFile
  539. this.setState({
  540. files: updatedFiles
  541. })
  542. this.emit('upload-retry', fileID)
  543. const uploadID = this._createUpload([ fileID ])
  544. return this._runUpload(uploadID)
  545. }
  546. reset () {
  547. this.cancelAll()
  548. }
  549. _calculateProgress (file, data) {
  550. if (!this.getFile(file.id)) {
  551. this.log(`Not setting progress for a file that has been removed: ${file.id}`)
  552. return
  553. }
  554. // bytesTotal may be null or zero; in that case we can't divide by it
  555. const canHavePercentage = isFinite(data.bytesTotal) && data.bytesTotal > 0
  556. this.setFileState(file.id, {
  557. progress: Object.assign({}, this.getFile(file.id).progress, {
  558. bytesUploaded: data.bytesUploaded,
  559. bytesTotal: data.bytesTotal,
  560. percentage: canHavePercentage
  561. // TODO(goto-bus-stop) flooring this should probably be the choice of the UI?
  562. // we get more accurate calculations if we don't round this at all.
  563. ? Math.floor(data.bytesUploaded / data.bytesTotal * 100)
  564. : 0
  565. })
  566. })
  567. this._calculateTotalProgress()
  568. }
  569. _calculateTotalProgress () {
  570. // calculate total progress, using the number of files currently uploading,
  571. // multiplied by 100 and the summ of individual progress of each file
  572. const files = this.getFiles()
  573. const inProgress = files.filter((file) => {
  574. return file.progress.uploadStarted
  575. })
  576. if (inProgress.length === 0) {
  577. this.emit('progress', 0)
  578. this.setState({ totalProgress: 0 })
  579. return
  580. }
  581. const sizedFiles = inProgress.filter((file) => file.progress.bytesTotal != null)
  582. const unsizedFiles = inProgress.filter((file) => file.progress.bytesTotal == null)
  583. if (sizedFiles.length === 0) {
  584. const progressMax = inProgress.length
  585. const currentProgress = unsizedFiles.reduce((acc, file) => {
  586. return acc + file.progress.percentage
  587. }, 0)
  588. const totalProgress = Math.round(currentProgress / progressMax * 100)
  589. this.setState({ totalProgress })
  590. return
  591. }
  592. let totalSize = sizedFiles.reduce((acc, file) => {
  593. return acc + file.progress.bytesTotal
  594. }, 0)
  595. const averageSize = totalSize / sizedFiles.length
  596. totalSize += averageSize * unsizedFiles.length
  597. let uploadedSize = 0
  598. sizedFiles.forEach((file) => {
  599. uploadedSize += file.progress.bytesUploaded
  600. })
  601. unsizedFiles.forEach((file) => {
  602. uploadedSize += averageSize * (file.progress.percentage || 0)
  603. })
  604. let totalProgress = totalSize === 0
  605. ? 0
  606. : Math.round(uploadedSize / totalSize * 100)
  607. // hot fix, because:
  608. // uploadedSize ended up larger than totalSize, resulting in 1325% total
  609. if (totalProgress > 100) {
  610. totalProgress = 100
  611. }
  612. this.setState({ totalProgress })
  613. this.emit('progress', totalProgress)
  614. }
  615. /**
  616. * Registers listeners for all global actions, like:
  617. * `error`, `file-removed`, `upload-progress`
  618. */
  619. _addListeners () {
  620. this.on('error', (error) => {
  621. this.setState({ error: error.message })
  622. })
  623. this.on('upload-error', (file, error, response) => {
  624. this.setFileState(file.id, {
  625. error: error.message,
  626. response
  627. })
  628. this.setState({ error: error.message })
  629. let message = this.i18n('failedToUpload', { file: file.name })
  630. if (typeof error === 'object' && error.message) {
  631. message = { message: message, details: error.message }
  632. }
  633. this.info(message, 'error', 5000)
  634. })
  635. this.on('upload', () => {
  636. this.setState({ error: null })
  637. })
  638. this.on('upload-started', (file, upload) => {
  639. if (!this.getFile(file.id)) {
  640. this.log(`Not setting progress for a file that has been removed: ${file.id}`)
  641. return
  642. }
  643. this.setFileState(file.id, {
  644. progress: {
  645. uploadStarted: Date.now(),
  646. uploadComplete: false,
  647. percentage: 0,
  648. bytesUploaded: 0,
  649. bytesTotal: file.size
  650. }
  651. })
  652. })
  653. // upload progress events can occur frequently, especially when you have a good
  654. // connection to the remote server. Therefore, we are throtteling them to
  655. // prevent accessive function calls.
  656. // see also: https://github.com/tus/tus-js-client/commit/9940f27b2361fd7e10ba58b09b60d82422183bbb
  657. // const _throttledCalculateProgress = throttle(this._calculateProgress, 100, { leading: true, trailing: true })
  658. this.on('upload-progress', this._calculateProgress)
  659. this.on('upload-success', (file, uploadResp) => {
  660. const currentProgress = this.getFile(file.id).progress
  661. this.setFileState(file.id, {
  662. progress: Object.assign({}, currentProgress, {
  663. uploadComplete: true,
  664. percentage: 100,
  665. bytesUploaded: currentProgress.bytesTotal
  666. }),
  667. response: uploadResp,
  668. uploadURL: uploadResp.uploadURL,
  669. isPaused: false
  670. })
  671. this._calculateTotalProgress()
  672. })
  673. this.on('preprocess-progress', (file, progress) => {
  674. if (!this.getFile(file.id)) {
  675. this.log(`Not setting progress for a file that has been removed: ${file.id}`)
  676. return
  677. }
  678. this.setFileState(file.id, {
  679. progress: Object.assign({}, this.getFile(file.id).progress, {
  680. preprocess: progress
  681. })
  682. })
  683. })
  684. this.on('preprocess-complete', (file) => {
  685. if (!this.getFile(file.id)) {
  686. this.log(`Not setting progress for a file that has been removed: ${file.id}`)
  687. return
  688. }
  689. const files = Object.assign({}, this.getState().files)
  690. files[file.id] = Object.assign({}, files[file.id], {
  691. progress: Object.assign({}, files[file.id].progress)
  692. })
  693. delete files[file.id].progress.preprocess
  694. this.setState({ files: files })
  695. })
  696. this.on('postprocess-progress', (file, progress) => {
  697. if (!this.getFile(file.id)) {
  698. this.log(`Not setting progress for a file that has been removed: ${file.id}`)
  699. return
  700. }
  701. this.setFileState(file.id, {
  702. progress: Object.assign({}, this.getState().files[file.id].progress, {
  703. postprocess: progress
  704. })
  705. })
  706. })
  707. this.on('postprocess-complete', (file) => {
  708. if (!this.getFile(file.id)) {
  709. this.log(`Not setting progress for a file that has been removed: ${file.id}`)
  710. return
  711. }
  712. const files = Object.assign({}, this.getState().files)
  713. files[file.id] = Object.assign({}, files[file.id], {
  714. progress: Object.assign({}, files[file.id].progress)
  715. })
  716. delete files[file.id].progress.postprocess
  717. // TODO should we set some kind of `fullyComplete` property on the file object
  718. // so it's easier to see that the file is upload…fully complete…rather than
  719. // what we have to do now (`uploadComplete && !postprocess`)
  720. this.setState({ files: files })
  721. })
  722. this.on('restored', () => {
  723. // Files may have changed--ensure progress is still accurate.
  724. this._calculateTotalProgress()
  725. })
  726. // show informer if offline
  727. if (typeof window !== 'undefined' && window.addEventListener) {
  728. window.addEventListener('online', () => this.updateOnlineStatus())
  729. window.addEventListener('offline', () => this.updateOnlineStatus())
  730. setTimeout(() => this.updateOnlineStatus(), 3000)
  731. }
  732. }
  733. updateOnlineStatus () {
  734. const online =
  735. typeof window.navigator.onLine !== 'undefined'
  736. ? window.navigator.onLine
  737. : true
  738. if (!online) {
  739. this.emit('is-offline')
  740. this.info(this.i18n('noInternetConnection'), 'error', 0)
  741. this.wasOffline = true
  742. } else {
  743. this.emit('is-online')
  744. if (this.wasOffline) {
  745. this.emit('back-online')
  746. this.info(this.i18n('connectedToInternet'), 'success', 3000)
  747. this.wasOffline = false
  748. }
  749. }
  750. }
  751. getID () {
  752. return this.opts.id
  753. }
  754. /**
  755. * Registers a plugin with Core.
  756. *
  757. * @param {object} Plugin object
  758. * @param {object} [opts] object with options to be passed to Plugin
  759. * @return {Object} self for chaining
  760. */
  761. use (Plugin, opts) {
  762. if (typeof Plugin !== 'function') {
  763. let msg = `Expected a plugin class, but got ${Plugin === null ? 'null' : typeof Plugin}.` +
  764. ' Please verify that the plugin was imported and spelled correctly.'
  765. throw new TypeError(msg)
  766. }
  767. // Instantiate
  768. const plugin = new Plugin(this, opts)
  769. const pluginId = plugin.id
  770. this.plugins[plugin.type] = this.plugins[plugin.type] || []
  771. if (!pluginId) {
  772. throw new Error('Your plugin must have an id')
  773. }
  774. if (!plugin.type) {
  775. throw new Error('Your plugin must have a type')
  776. }
  777. let existsPluginAlready = this.getPlugin(pluginId)
  778. if (existsPluginAlready) {
  779. let msg = `Already found a plugin named '${existsPluginAlready.id}'. ` +
  780. `Tried to use: '${pluginId}'.\n` +
  781. `Uppy plugins must have unique 'id' options. See https://uppy.io/docs/plugins/#id.`
  782. throw new Error(msg)
  783. }
  784. this.plugins[plugin.type].push(plugin)
  785. plugin.install()
  786. return this
  787. }
  788. /**
  789. * Find one Plugin by name.
  790. *
  791. * @param {string} id plugin id
  792. * @return {object | boolean}
  793. */
  794. getPlugin (id) {
  795. let foundPlugin = null
  796. this.iteratePlugins((plugin) => {
  797. if (plugin.id === id) {
  798. foundPlugin = plugin
  799. return false
  800. }
  801. })
  802. return foundPlugin
  803. }
  804. /**
  805. * Iterate through all `use`d plugins.
  806. *
  807. * @param {function} method that will be run on each plugin
  808. */
  809. iteratePlugins (method) {
  810. Object.keys(this.plugins).forEach(pluginType => {
  811. this.plugins[pluginType].forEach(method)
  812. })
  813. }
  814. /**
  815. * Uninstall and remove a plugin.
  816. *
  817. * @param {object} instance The plugin instance to remove.
  818. */
  819. removePlugin (instance) {
  820. this.log(`Removing plugin ${instance.id}`)
  821. this.emit('plugin-remove', instance)
  822. if (instance.uninstall) {
  823. instance.uninstall()
  824. }
  825. const list = this.plugins[instance.type].slice()
  826. const index = list.indexOf(instance)
  827. if (index !== -1) {
  828. list.splice(index, 1)
  829. this.plugins[instance.type] = list
  830. }
  831. const updatedState = this.getState()
  832. delete updatedState.plugins[instance.id]
  833. this.setState(updatedState)
  834. }
  835. /**
  836. * Uninstall all plugins and close down this Uppy instance.
  837. */
  838. close () {
  839. this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`)
  840. this.reset()
  841. this._storeUnsubscribe()
  842. this.iteratePlugins((plugin) => {
  843. this.removePlugin(plugin)
  844. })
  845. }
  846. /**
  847. * Set info message in `state.info`, so that UI plugins like `Informer`
  848. * can display the message.
  849. *
  850. * @param {string | object} message Message to be displayed by the informer
  851. * @param {string} [type]
  852. * @param {number} [duration]
  853. */
  854. info (message, type = 'info', duration = 3000) {
  855. const isComplexMessage = typeof message === 'object'
  856. this.setState({
  857. info: {
  858. isHidden: false,
  859. type: type,
  860. message: isComplexMessage ? message.message : message,
  861. details: isComplexMessage ? message.details : null
  862. }
  863. })
  864. this.emit('info-visible')
  865. clearTimeout(this.infoTimeoutID)
  866. if (duration === 0) {
  867. this.infoTimeoutID = undefined
  868. return
  869. }
  870. // hide the informer after `duration` milliseconds
  871. this.infoTimeoutID = setTimeout(this.hideInfo, duration)
  872. }
  873. hideInfo () {
  874. const newInfo = Object.assign({}, this.getState().info, {
  875. isHidden: true
  876. })
  877. this.setState({
  878. info: newInfo
  879. })
  880. this.emit('info-hidden')
  881. }
  882. /**
  883. * Logs stuff to console, only if `debug` is set to true. Silent in production.
  884. *
  885. * @param {String|Object} message to log
  886. * @param {String} [type] optional `error` or `warning`
  887. */
  888. log (message, type) {
  889. if (!this.opts.debug) {
  890. return
  891. }
  892. const prefix = `[Uppy] [${getTimeStamp()}]`
  893. if (type === 'error') {
  894. console.error(prefix, message)
  895. return
  896. }
  897. if (type === 'warning') {
  898. console.warn(prefix, message)
  899. return
  900. }
  901. console.log(prefix, message)
  902. }
  903. /**
  904. * Obsolete, event listeners are now added in the constructor.
  905. */
  906. run () {
  907. this.log('Calling run() is no longer necessary.', 'warning')
  908. return this
  909. }
  910. /**
  911. * Restore an upload by its ID.
  912. */
  913. restore (uploadID) {
  914. this.log(`Core: attempting to restore upload "${uploadID}"`)
  915. if (!this.getState().currentUploads[uploadID]) {
  916. this._removeUpload(uploadID)
  917. return Promise.reject(new Error('Nonexistent upload'))
  918. }
  919. return this._runUpload(uploadID)
  920. }
  921. /**
  922. * Create an upload for a bunch of files.
  923. *
  924. * @param {Array<string>} fileIDs File IDs to include in this upload.
  925. * @return {string} ID of this upload.
  926. */
  927. _createUpload (fileIDs) {
  928. const { allowNewUpload, currentUploads } = this.getState()
  929. if (!allowNewUpload) {
  930. throw new Error('Cannot create a new upload: already uploading.')
  931. }
  932. const uploadID = cuid()
  933. this.emit('upload', {
  934. id: uploadID,
  935. fileIDs: fileIDs
  936. })
  937. this.setState({
  938. allowNewUpload: this.opts.allowMultipleUploads !== false,
  939. currentUploads: {
  940. ...currentUploads,
  941. [uploadID]: {
  942. fileIDs: fileIDs,
  943. step: 0,
  944. result: {}
  945. }
  946. }
  947. })
  948. return uploadID
  949. }
  950. _getUpload (uploadID) {
  951. const { currentUploads } = this.getState()
  952. return currentUploads[uploadID]
  953. }
  954. /**
  955. * Add data to an upload's result object.
  956. *
  957. * @param {string} uploadID The ID of the upload.
  958. * @param {object} data Data properties to add to the result object.
  959. */
  960. addResultData (uploadID, data) {
  961. if (!this._getUpload(uploadID)) {
  962. this.log(`Not setting result for an upload that has been removed: ${uploadID}`)
  963. return
  964. }
  965. const currentUploads = this.getState().currentUploads
  966. const currentUpload = Object.assign({}, currentUploads[uploadID], {
  967. result: Object.assign({}, currentUploads[uploadID].result, data)
  968. })
  969. this.setState({
  970. currentUploads: Object.assign({}, currentUploads, {
  971. [uploadID]: currentUpload
  972. })
  973. })
  974. }
  975. /**
  976. * Remove an upload, eg. if it has been canceled or completed.
  977. *
  978. * @param {string} uploadID The ID of the upload.
  979. */
  980. _removeUpload (uploadID) {
  981. const currentUploads = Object.assign({}, this.getState().currentUploads)
  982. delete currentUploads[uploadID]
  983. this.setState({
  984. currentUploads: currentUploads
  985. })
  986. }
  987. /**
  988. * Run an upload. This picks up where it left off in case the upload is being restored.
  989. *
  990. * @private
  991. */
  992. _runUpload (uploadID) {
  993. const uploadData = this.getState().currentUploads[uploadID]
  994. const restoreStep = uploadData.step
  995. const steps = [
  996. ...this.preProcessors,
  997. ...this.uploaders,
  998. ...this.postProcessors
  999. ]
  1000. let lastStep = Promise.resolve()
  1001. steps.forEach((fn, step) => {
  1002. // Skip this step if we are restoring and have already completed this step before.
  1003. if (step < restoreStep) {
  1004. return
  1005. }
  1006. lastStep = lastStep.then(() => {
  1007. const { currentUploads } = this.getState()
  1008. const currentUpload = Object.assign({}, currentUploads[uploadID], {
  1009. step: step
  1010. })
  1011. this.setState({
  1012. currentUploads: Object.assign({}, currentUploads, {
  1013. [uploadID]: currentUpload
  1014. })
  1015. })
  1016. // TODO give this the `currentUpload` object as its only parameter maybe?
  1017. // Otherwise when more metadata may be added to the upload this would keep getting more parameters
  1018. return fn(currentUpload.fileIDs, uploadID)
  1019. }).then((result) => {
  1020. return null
  1021. })
  1022. })
  1023. // Not returning the `catch`ed promise, because we still want to return a rejected
  1024. // promise from this method if the upload failed.
  1025. lastStep.catch((err) => {
  1026. this.emit('error', err, uploadID)
  1027. this._removeUpload(uploadID)
  1028. })
  1029. return lastStep.then(() => {
  1030. // Set result data.
  1031. const { currentUploads } = this.getState()
  1032. const currentUpload = currentUploads[uploadID]
  1033. if (!currentUpload) {
  1034. return
  1035. }
  1036. const files = currentUpload.fileIDs
  1037. .map((fileID) => this.getFile(fileID))
  1038. const successful = files.filter((file) => !file.error)
  1039. const failed = files.filter((file) => file.error)
  1040. this.addResultData(uploadID, { successful, failed, uploadID })
  1041. }).then(() => {
  1042. // Emit completion events.
  1043. // This is in a separate function so that the `currentUploads` variable
  1044. // always refers to the latest state. In the handler right above it refers
  1045. // to an outdated object without the `.result` property.
  1046. const { currentUploads } = this.getState()
  1047. if (!currentUploads[uploadID]) {
  1048. return
  1049. }
  1050. const currentUpload = currentUploads[uploadID]
  1051. const result = currentUpload.result
  1052. this.emit('complete', result)
  1053. this._removeUpload(uploadID)
  1054. return result
  1055. }).then((result) => {
  1056. if (result == null) {
  1057. this.log(`Not setting result for an upload that has been removed: ${uploadID}`)
  1058. }
  1059. return result
  1060. })
  1061. }
  1062. /**
  1063. * Start an upload for all the files that are not currently being uploaded.
  1064. *
  1065. * @return {Promise}
  1066. */
  1067. upload () {
  1068. if (!this.plugins.uploader) {
  1069. this.log('No uploader type plugins are used', 'warning')
  1070. }
  1071. let files = this.getState().files
  1072. const onBeforeUploadResult = this.opts.onBeforeUpload(files)
  1073. if (onBeforeUploadResult === false) {
  1074. return Promise.reject(new Error('Not starting the upload because onBeforeUpload returned false'))
  1075. }
  1076. if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {
  1077. // warning after the change in 0.24
  1078. if (onBeforeUploadResult.then) {
  1079. throw new TypeError('onBeforeUpload() returned a Promise, but this is no longer supported. It must be synchronous.')
  1080. }
  1081. files = onBeforeUploadResult
  1082. }
  1083. return Promise.resolve()
  1084. .then(() => this._checkMinNumberOfFiles(files))
  1085. .then(() => {
  1086. const { currentUploads } = this.getState()
  1087. // get a list of files that are currently assigned to uploads
  1088. const currentlyUploadingFiles = Object.keys(currentUploads).reduce((prev, curr) => prev.concat(currentUploads[curr].fileIDs), [])
  1089. const waitingFileIDs = []
  1090. Object.keys(files).forEach((fileID) => {
  1091. const file = this.getFile(fileID)
  1092. // if the file hasn't started uploading and hasn't already been assigned to an upload..
  1093. if ((!file.progress.uploadStarted) && (currentlyUploadingFiles.indexOf(fileID) === -1)) {
  1094. waitingFileIDs.push(file.id)
  1095. }
  1096. })
  1097. const uploadID = this._createUpload(waitingFileIDs)
  1098. return this._runUpload(uploadID)
  1099. })
  1100. .catch((err) => {
  1101. const message = typeof err === 'object' ? err.message : err
  1102. const details = typeof err === 'object' ? err.details : null
  1103. this.log(`${message} ${details}`)
  1104. this.info({ message: message, details: details }, 'error', 4000)
  1105. return Promise.reject(typeof err === 'object' ? err : new Error(err))
  1106. })
  1107. }
  1108. }
  1109. module.exports = function (opts) {
  1110. return new Uppy(opts)
  1111. }
  1112. // Expose class constructor.
  1113. module.exports.Uppy = Uppy
  1114. module.exports.Plugin = Plugin