index.js 35 KB

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