index.js 34 KB

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