Core.js 33 KB

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