Core.js 32 KB

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