Core.js 31 KB

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