Core.js 34 KB

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