index.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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 getTimeStamp = require('@uppy/utils/lib/getTimeStamp')
  12. const Plugin = require('./Plugin') // Exported from here.
  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. companionError: 'Connection with Companion 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: false,
  54. allowMultipleUploads: true,
  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. // i18n
  72. this.translator = new Translator([ defaultLocale, this.opts.locale ])
  73. this.locale = this.translator.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. allowNewUpload: true,
  110. capabilities: {
  111. resumableUploads: false
  112. },
  113. totalProgress: 0,
  114. meta: { ...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, allowNewUpload } = 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. if (allowNewUpload === false) {
  342. onError(new Error('Cannot add new files: already uploading.'))
  343. }
  344. const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(file, files)
  345. if (onBeforeFileAddedResult === false) {
  346. this.log('Not adding file because onBeforeFileAdded returned false')
  347. return
  348. }
  349. if (typeof onBeforeFileAddedResult === 'object' && onBeforeFileAddedResult) {
  350. // warning after the change in 0.24
  351. if (onBeforeFileAddedResult.then) {
  352. throw new TypeError('onBeforeFileAdded() returned a Promise, but this is no longer supported. It must be synchronous.')
  353. }
  354. file = onBeforeFileAddedResult
  355. }
  356. const fileType = getFileType(file)
  357. let fileName
  358. if (file.name) {
  359. fileName = file.name
  360. } else if (fileType.split('/')[0] === 'image') {
  361. fileName = fileType.split('/')[0] + '.' + fileType.split('/')[1]
  362. } else {
  363. fileName = 'noname'
  364. }
  365. const fileExtension = getFileNameAndExtension(fileName).extension
  366. const isRemote = file.isRemote || false
  367. const fileID = generateFileID(file)
  368. const meta = file.meta || {}
  369. meta.name = fileName
  370. meta.type = fileType
  371. const newFile = {
  372. source: file.source || '',
  373. id: fileID,
  374. name: fileName,
  375. extension: fileExtension || '',
  376. meta: Object.assign({}, this.getState().meta, meta),
  377. type: fileType,
  378. data: file.data,
  379. progress: {
  380. percentage: 0,
  381. bytesUploaded: 0,
  382. bytesTotal: file.data.size || 0,
  383. uploadComplete: false,
  384. uploadStarted: false
  385. },
  386. size: file.data.size || 0,
  387. isRemote: isRemote,
  388. remote: file.remote || '',
  389. preview: file.preview
  390. }
  391. try {
  392. this._checkRestrictions(newFile)
  393. } catch (err) {
  394. onError(err)
  395. }
  396. this.setState({
  397. files: Object.assign({}, files, {
  398. [fileID]: newFile
  399. })
  400. })
  401. this.emit('file-added', newFile)
  402. this.log(`Added file: ${fileName}, ${fileID}, mime type: ${fileType}`)
  403. if (this.opts.autoProceed && !this.scheduledAutoProceed) {
  404. this.scheduledAutoProceed = setTimeout(() => {
  405. this.scheduledAutoProceed = null
  406. this.upload().catch((err) => {
  407. console.error(err.stack || err.message || err)
  408. })
  409. }, 4)
  410. }
  411. }
  412. removeFile (fileID) {
  413. const { files, currentUploads } = this.getState()
  414. const updatedFiles = Object.assign({}, files)
  415. const removedFile = updatedFiles[fileID]
  416. delete updatedFiles[fileID]
  417. // Remove this file from its `currentUpload`.
  418. const updatedUploads = Object.assign({}, currentUploads)
  419. const removeUploads = []
  420. Object.keys(updatedUploads).forEach((uploadID) => {
  421. const newFileIDs = currentUploads[uploadID].fileIDs.filter((uploadFileID) => uploadFileID !== fileID)
  422. // Remove the upload if no files are associated with it anymore.
  423. if (newFileIDs.length === 0) {
  424. removeUploads.push(uploadID)
  425. return
  426. }
  427. updatedUploads[uploadID] = Object.assign({}, currentUploads[uploadID], {
  428. fileIDs: newFileIDs
  429. })
  430. })
  431. this.setState({
  432. currentUploads: updatedUploads,
  433. files: updatedFiles
  434. })
  435. removeUploads.forEach((uploadID) => {
  436. this._removeUpload(uploadID)
  437. })
  438. this._calculateTotalProgress()
  439. this.emit('file-removed', removedFile)
  440. this.log(`File removed: ${removedFile.id}`)
  441. }
  442. pauseResume (fileID) {
  443. if (!this.getState().capabilities.resumableUploads ||
  444. this.getFile(fileID).uploadComplete) {
  445. return
  446. }
  447. const wasPaused = this.getFile(fileID).isPaused || false
  448. const isPaused = !wasPaused
  449. this.setFileState(fileID, {
  450. isPaused: isPaused
  451. })
  452. this.emit('upload-pause', fileID, isPaused)
  453. return isPaused
  454. }
  455. pauseAll () {
  456. const updatedFiles = Object.assign({}, this.getState().files)
  457. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  458. return !updatedFiles[file].progress.uploadComplete &&
  459. updatedFiles[file].progress.uploadStarted
  460. })
  461. inProgressUpdatedFiles.forEach((file) => {
  462. const updatedFile = Object.assign({}, updatedFiles[file], {
  463. isPaused: true
  464. })
  465. updatedFiles[file] = updatedFile
  466. })
  467. this.setState({files: updatedFiles})
  468. this.emit('pause-all')
  469. }
  470. resumeAll () {
  471. const updatedFiles = Object.assign({}, this.getState().files)
  472. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  473. return !updatedFiles[file].progress.uploadComplete &&
  474. updatedFiles[file].progress.uploadStarted
  475. })
  476. inProgressUpdatedFiles.forEach((file) => {
  477. const updatedFile = Object.assign({}, updatedFiles[file], {
  478. isPaused: false,
  479. error: null
  480. })
  481. updatedFiles[file] = updatedFile
  482. })
  483. this.setState({files: updatedFiles})
  484. this.emit('resume-all')
  485. }
  486. retryAll () {
  487. const updatedFiles = Object.assign({}, this.getState().files)
  488. const filesToRetry = Object.keys(updatedFiles).filter(file => {
  489. return updatedFiles[file].error
  490. })
  491. filesToRetry.forEach((file) => {
  492. const updatedFile = Object.assign({}, updatedFiles[file], {
  493. isPaused: false,
  494. error: null
  495. })
  496. updatedFiles[file] = updatedFile
  497. })
  498. this.setState({
  499. files: updatedFiles,
  500. error: null
  501. })
  502. this.emit('retry-all', filesToRetry)
  503. const uploadID = this._createUpload(filesToRetry)
  504. return this._runUpload(uploadID)
  505. }
  506. cancelAll () {
  507. this.emit('cancel-all')
  508. const files = Object.keys(this.getState().files)
  509. files.forEach((fileID) => {
  510. this.removeFile(fileID)
  511. })
  512. this.setState({
  513. allowNewUpload: true,
  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' && window.addEventListener) {
  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} id plugin id
  738. * @return {object | boolean}
  739. */
  740. getPlugin (id) {
  741. let foundPlugin = null
  742. this.iteratePlugins((plugin) => {
  743. if (plugin.id === id) {
  744. foundPlugin = plugin
  745. return false
  746. }
  747. })
  748. return foundPlugin
  749. }
  750. /**
  751. * Iterate through all `use`d plugins.
  752. *
  753. * @param {function} method that will be run on each plugin
  754. */
  755. iteratePlugins (method) {
  756. Object.keys(this.plugins).forEach(pluginType => {
  757. this.plugins[pluginType].forEach(method)
  758. })
  759. }
  760. /**
  761. * Uninstall and remove a plugin.
  762. *
  763. * @param {object} instance The plugin instance to remove.
  764. */
  765. removePlugin (instance) {
  766. this.log(`Removing plugin ${instance.id}`)
  767. this.emit('plugin-remove', instance)
  768. if (instance.uninstall) {
  769. instance.uninstall()
  770. }
  771. const list = this.plugins[instance.type].slice()
  772. const index = list.indexOf(instance)
  773. if (index !== -1) {
  774. list.splice(index, 1)
  775. this.plugins[instance.type] = list
  776. }
  777. const updatedState = this.getState()
  778. delete updatedState.plugins[instance.id]
  779. this.setState(updatedState)
  780. }
  781. /**
  782. * Uninstall all plugins and close down this Uppy instance.
  783. */
  784. close () {
  785. this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`)
  786. this.reset()
  787. this._storeUnsubscribe()
  788. this.iteratePlugins((plugin) => {
  789. this.removePlugin(plugin)
  790. })
  791. }
  792. /**
  793. * Set info message in `state.info`, so that UI plugins like `Informer`
  794. * can display the message.
  795. *
  796. * @param {string | object} message Message to be displayed by the informer
  797. * @param {string} [type]
  798. * @param {number} [duration]
  799. */
  800. info (message, type = 'info', duration = 3000) {
  801. const isComplexMessage = typeof message === 'object'
  802. this.setState({
  803. info: {
  804. isHidden: false,
  805. type: type,
  806. message: isComplexMessage ? message.message : message,
  807. details: isComplexMessage ? message.details : null
  808. }
  809. })
  810. this.emit('info-visible')
  811. clearTimeout(this.infoTimeoutID)
  812. if (duration === 0) {
  813. this.infoTimeoutID = undefined
  814. return
  815. }
  816. // hide the informer after `duration` milliseconds
  817. this.infoTimeoutID = setTimeout(this.hideInfo, duration)
  818. }
  819. hideInfo () {
  820. const newInfo = Object.assign({}, this.getState().info, {
  821. isHidden: true
  822. })
  823. this.setState({
  824. info: newInfo
  825. })
  826. this.emit('info-hidden')
  827. }
  828. /**
  829. * Logs stuff to console, only if `debug` is set to true. Silent in production.
  830. *
  831. * @param {String|Object} msg to log
  832. * @param {String} [type] optional `error` or `warning`
  833. */
  834. log (msg, type) {
  835. if (!this.opts.debug) {
  836. return
  837. }
  838. let message = `[Uppy] [${getTimeStamp()}] ${msg}`
  839. window['uppyLog'] = window['uppyLog'] + '\n' + 'DEBUG LOG: ' + msg
  840. if (type === 'error') {
  841. console.error(message)
  842. return
  843. }
  844. if (type === 'warning') {
  845. console.warn(message)
  846. return
  847. }
  848. if (msg === `${msg}`) {
  849. console.log(message)
  850. } else {
  851. message = `[Uppy] [${getTimeStamp()}]`
  852. console.log(message)
  853. console.dir(msg)
  854. }
  855. }
  856. /**
  857. * Obsolete, event listeners are now added in the constructor.
  858. */
  859. run () {
  860. this.log('Calling run() is no longer necessary.', 'warning')
  861. return this
  862. }
  863. /**
  864. * Restore an upload by its ID.
  865. */
  866. restore (uploadID) {
  867. this.log(`Core: attempting to restore upload "${uploadID}"`)
  868. if (!this.getState().currentUploads[uploadID]) {
  869. this._removeUpload(uploadID)
  870. return Promise.reject(new Error('Nonexistent upload'))
  871. }
  872. return this._runUpload(uploadID)
  873. }
  874. /**
  875. * Create an upload for a bunch of files.
  876. *
  877. * @param {Array<string>} fileIDs File IDs to include in this upload.
  878. * @return {string} ID of this upload.
  879. */
  880. _createUpload (fileIDs) {
  881. const { allowNewUpload, currentUploads } = this.getState()
  882. if (!allowNewUpload) {
  883. throw new Error('Cannot create a new upload: already uploading.')
  884. }
  885. const uploadID = cuid()
  886. this.emit('upload', {
  887. id: uploadID,
  888. fileIDs: fileIDs
  889. })
  890. this.setState({
  891. allowNewUpload: this.opts.allowMultipleUploads !== false,
  892. currentUploads: {
  893. ...currentUploads,
  894. [uploadID]: {
  895. fileIDs: fileIDs,
  896. step: 0,
  897. result: {}
  898. }
  899. }
  900. })
  901. return uploadID
  902. }
  903. _getUpload (uploadID) {
  904. const { currentUploads } = this.getState()
  905. return currentUploads[uploadID]
  906. }
  907. /**
  908. * Add data to an upload's result object.
  909. *
  910. * @param {string} uploadID The ID of the upload.
  911. * @param {object} data Data properties to add to the result object.
  912. */
  913. addResultData (uploadID, data) {
  914. if (!this._getUpload(uploadID)) {
  915. this.log(`Not setting result for an upload that has been removed: ${uploadID}`)
  916. return
  917. }
  918. const currentUploads = this.getState().currentUploads
  919. const currentUpload = Object.assign({}, currentUploads[uploadID], {
  920. result: Object.assign({}, currentUploads[uploadID].result, data)
  921. })
  922. this.setState({
  923. currentUploads: Object.assign({}, currentUploads, {
  924. [uploadID]: currentUpload
  925. })
  926. })
  927. }
  928. /**
  929. * Remove an upload, eg. if it has been canceled or completed.
  930. *
  931. * @param {string} uploadID The ID of the upload.
  932. */
  933. _removeUpload (uploadID) {
  934. const currentUploads = Object.assign({}, this.getState().currentUploads)
  935. delete currentUploads[uploadID]
  936. this.setState({
  937. currentUploads: currentUploads
  938. })
  939. }
  940. /**
  941. * Run an upload. This picks up where it left off in case the upload is being restored.
  942. *
  943. * @private
  944. */
  945. _runUpload (uploadID) {
  946. const uploadData = this.getState().currentUploads[uploadID]
  947. const restoreStep = uploadData.step
  948. const steps = [
  949. ...this.preProcessors,
  950. ...this.uploaders,
  951. ...this.postProcessors
  952. ]
  953. let lastStep = Promise.resolve()
  954. steps.forEach((fn, step) => {
  955. // Skip this step if we are restoring and have already completed this step before.
  956. if (step < restoreStep) {
  957. return
  958. }
  959. lastStep = lastStep.then(() => {
  960. const { currentUploads } = this.getState()
  961. const currentUpload = {
  962. ...currentUploads[uploadID],
  963. step: step
  964. }
  965. this.setState({
  966. currentUploads: {
  967. ...currentUploads,
  968. [uploadID]: currentUpload
  969. }
  970. })
  971. // TODO give this the `currentUpload` object as its only parameter maybe?
  972. // Otherwise when more metadata may be added to the upload this would keep getting more parameters
  973. return fn(currentUpload.fileIDs, uploadID)
  974. }).then((result) => {
  975. return null
  976. })
  977. })
  978. // Not returning the `catch`ed promise, because we still want to return a rejected
  979. // promise from this method if the upload failed.
  980. lastStep.catch((err) => {
  981. this.emit('error', err, uploadID)
  982. this._removeUpload(uploadID)
  983. })
  984. return lastStep.then(() => {
  985. // Set result data.
  986. const { currentUploads } = this.getState()
  987. const currentUpload = currentUploads[uploadID]
  988. if (!currentUpload) {
  989. this.log(`Not setting result for an upload that has been removed: ${uploadID}`)
  990. return
  991. }
  992. const files = currentUpload.fileIDs
  993. .map((fileID) => this.getFile(fileID))
  994. const successful = files.filter((file) => !file.error)
  995. const failed = files.filter((file) => file.error)
  996. this.addResultData(uploadID, { successful, failed, uploadID })
  997. }).then(() => {
  998. // Emit completion events.
  999. // This is in a separate function so that the `currentUploads` variable
  1000. // always refers to the latest state. In the handler right above it refers
  1001. // to an outdated object without the `.result` property.
  1002. const { currentUploads } = this.getState()
  1003. const currentUpload = currentUploads[uploadID]
  1004. const result = currentUpload.result
  1005. this.emit('complete', result)
  1006. this._removeUpload(uploadID)
  1007. return result
  1008. })
  1009. }
  1010. /**
  1011. * Start an upload for all the files that are not currently being uploaded.
  1012. *
  1013. * @return {Promise}
  1014. */
  1015. upload () {
  1016. if (!this.plugins.uploader) {
  1017. this.log('No uploader type plugins are used', 'warning')
  1018. }
  1019. let files = this.getState().files
  1020. const onBeforeUploadResult = this.opts.onBeforeUpload(files)
  1021. if (onBeforeUploadResult === false) {
  1022. return Promise.reject(new Error('Not starting the upload because onBeforeUpload returned false'))
  1023. }
  1024. if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {
  1025. // warning after the change in 0.24
  1026. if (onBeforeUploadResult.then) {
  1027. throw new TypeError('onBeforeUpload() returned a Promise, but this is no longer supported. It must be synchronous.')
  1028. }
  1029. files = onBeforeUploadResult
  1030. }
  1031. return Promise.resolve()
  1032. .then(() => this._checkMinNumberOfFiles(files))
  1033. .then(() => {
  1034. const { currentUploads } = this.getState()
  1035. // get a list of files that are currently assigned to uploads
  1036. const currentlyUploadingFiles = Object.keys(currentUploads).reduce((prev, curr) => prev.concat(currentUploads[curr].fileIDs), [])
  1037. const waitingFileIDs = []
  1038. Object.keys(files).forEach((fileID) => {
  1039. const file = this.getFile(fileID)
  1040. // if the file hasn't started uploading and hasn't already been assigned to an upload..
  1041. if ((!file.progress.uploadStarted) && (currentlyUploadingFiles.indexOf(fileID) === -1)) {
  1042. waitingFileIDs.push(file.id)
  1043. }
  1044. })
  1045. const uploadID = this._createUpload(waitingFileIDs)
  1046. return this._runUpload(uploadID)
  1047. })
  1048. .catch((err) => {
  1049. const message = typeof err === 'object' ? err.message : err
  1050. const details = typeof err === 'object' ? err.details : null
  1051. this.log(`${message} ${details}`)
  1052. this.info({ message: message, details: details }, 'error', 4000)
  1053. return Promise.reject(typeof err === 'object' ? err : new Error(err))
  1054. })
  1055. }
  1056. }
  1057. module.exports = function (opts) {
  1058. return new Uppy(opts)
  1059. }
  1060. // Expose class constructor.
  1061. module.exports.Uppy = Uppy
  1062. module.exports.Plugin = Plugin