Core.js 30 KB

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