Uploader.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. const fs = require('fs')
  2. const path = require('path')
  3. const tus = require('tus-js-client')
  4. const uuid = require('uuid')
  5. const createTailReadStream = require('@uppy/fs-tail-stream')
  6. const emitter = require('./emitter')
  7. const request = require('request')
  8. const serializeError = require('serialize-error')
  9. const { jsonStringify, hasMatch } = require('./helpers/utils')
  10. const logger = require('./logger')
  11. const validator = require('validator')
  12. const headerSanitize = require('./header-blacklist')
  13. const PROTOCOLS = Object.freeze({
  14. multipart: 'multipart',
  15. s3Multipart: 's3-multipart',
  16. tus: 'tus'
  17. })
  18. class Uploader {
  19. /**
  20. * Uploads file to destination based on the supplied protocol (tus, s3-multipart, multipart)
  21. * For tus uploads, the deferredLength option is enabled, because file size value can be unreliable
  22. * for some providers (Instagram particularly)
  23. *
  24. * @typedef {object} UploaderOptions
  25. * @property {string} endpoint
  26. * @property {string=} uploadUrl
  27. * @property {string} protocol
  28. * @property {number} size
  29. * @property {string=} fieldname
  30. * @property {string} pathPrefix
  31. * @property {string=} path
  32. * @property {any=} s3
  33. * @property {any} metadata
  34. * @property {any} uppyOptions
  35. * @property {any=} storage
  36. * @property {any=} headers
  37. *
  38. * @param {UploaderOptions} options
  39. */
  40. constructor (options) {
  41. if (!this.validateOptions(options)) {
  42. logger.debug(this._errRespMessage, 'uploader.validator.fail')
  43. return
  44. }
  45. this.options = options
  46. this.token = uuid.v4()
  47. this.options.path = `${this.options.pathPrefix}/${Uploader.FILE_NAME_PREFIX}-${this.token}`
  48. this.streamsEnded = false
  49. this.duplexStream = null
  50. // @TODO disabling parallel uploads and downloads for now
  51. // if (this.options.protocol === PROTOCOLS.tus) {
  52. // this.duplexStream = new stream.PassThrough()
  53. // .on('error', (err) => logger.error(`${this.shortToken} ${err}`, 'uploader.duplex.error'))
  54. // }
  55. this.writeStream = fs.createWriteStream(this.options.path, { mode: 0o666 }) // no executable files
  56. .on('error', (err) => logger.error(`${this.shortToken} ${err}`, 'uploader.write.error'))
  57. /** @type {number} */
  58. this.emittedProgress = 0
  59. this.storage = options.storage
  60. this._paused = false
  61. if (this.options.protocol === PROTOCOLS.tus) {
  62. emitter().on(`pause:${this.token}`, () => {
  63. this._paused = true
  64. if (this.tus) {
  65. this.tus.abort()
  66. }
  67. })
  68. emitter().on(`resume:${this.token}`, () => {
  69. this._paused = false
  70. if (this.tus) {
  71. this.tus.start()
  72. }
  73. })
  74. }
  75. }
  76. /**
  77. * the number of bytes written into the streams
  78. */
  79. get bytesWritten () {
  80. return this.writeStream.bytesWritten
  81. }
  82. /**
  83. * Validate the options passed down to the uplaoder
  84. *
  85. * @param {UploaderOptions} options
  86. * @returns {boolean}
  87. */
  88. validateOptions (options) {
  89. // s3 uploads don't require upload destination
  90. // validation, because the destination is determined
  91. // by the server's s3 config
  92. if (options.protocol === PROTOCOLS.s3Multipart) {
  93. return true
  94. }
  95. if (!options.endpoint && !options.uploadUrl) {
  96. this._errRespMessage = 'No destination specified'
  97. return false
  98. }
  99. const validatorOpts = { require_protocol: true, require_tld: !options.uppyOptions.debug }
  100. return [options.endpoint, options.uploadUrl].every((url) => {
  101. if (url && !validator.isURL(url, validatorOpts)) {
  102. this._errRespMessage = 'Invalid destination url'
  103. return false
  104. }
  105. const allowedUrls = options.uppyOptions.uploadUrls
  106. if (allowedUrls && url && !hasMatch(url, allowedUrls)) {
  107. this._errRespMessage = 'upload destination does not match any allowed destinations'
  108. return false
  109. }
  110. return true
  111. })
  112. }
  113. hasError () {
  114. return this._errRespMessage != null
  115. }
  116. /**
  117. * returns a substring of the token
  118. */
  119. get shortToken () {
  120. return this.token.substring(0, 8)
  121. }
  122. /**
  123. *
  124. * @param {function} callback
  125. */
  126. onSocketReady (callback) {
  127. emitter().once(`connection:${this.token}`, () => callback())
  128. logger.debug(`${this.shortToken} waiting for connection`, 'uploader.socket.wait')
  129. }
  130. cleanUp () {
  131. fs.unlink(this.options.path, (err) => {
  132. if (err) {
  133. logger.error(`cleanup failed for: ${this.options.path} err: ${err}`, 'uploader.cleanup.error')
  134. }
  135. })
  136. emitter().removeAllListeners(`pause:${this.token}`)
  137. emitter().removeAllListeners(`resume:${this.token}`)
  138. }
  139. /**
  140. *
  141. * @param {Buffer | Buffer[]} chunk
  142. */
  143. handleChunk (chunk) {
  144. // @todo a default protocol should not be set. We should ensure that the user specifies her protocol.
  145. const protocol = this.options.protocol || PROTOCOLS.multipart
  146. // The download has completed; close the file and start an upload if necessary.
  147. if (chunk === null) {
  148. this.writeStream.on('finish', () => {
  149. this.streamsEnded = true
  150. if (this.options.endpoint && protocol === PROTOCOLS.multipart) {
  151. this.uploadMultipart()
  152. }
  153. if (protocol === PROTOCOLS.tus && !this.tus) {
  154. return this.uploadTus()
  155. }
  156. })
  157. return this.endStreams()
  158. }
  159. this.writeStream.write(chunk, () => {
  160. logger.debug(`${this.shortToken} ${this.bytesWritten} bytes`, 'uploader.download.progress')
  161. if (protocol === PROTOCOLS.multipart || protocol === PROTOCOLS.tus) {
  162. return this.emitIllusiveProgress()
  163. }
  164. if (protocol === PROTOCOLS.s3Multipart && !this.s3Upload) {
  165. return this.uploadS3()
  166. }
  167. // @TODO disabling parallel uploads and downloads for now
  168. // if (!this.options.endpoint) return
  169. // if (protocol === PROTOCOLS.tus && !this.tus) {
  170. // return this.uploadTus()
  171. // }
  172. })
  173. }
  174. /**
  175. * @param {Buffer | Buffer[]} chunk
  176. * @param {function} cb
  177. */
  178. writeToStreams (chunk, cb) {
  179. const done = []
  180. const doneLength = this.duplexStream ? 2 : 1
  181. const onDone = () => {
  182. done.push(true)
  183. if (done.length >= doneLength) {
  184. cb()
  185. }
  186. }
  187. this.writeStream.write(chunk, onDone)
  188. if (this.duplexStream) {
  189. this.duplexStream.write(chunk, onDone)
  190. }
  191. }
  192. endStreams () {
  193. this.writeStream.end()
  194. if (this.duplexStream) {
  195. this.duplexStream.end()
  196. }
  197. }
  198. getResponse () {
  199. if (this._errRespMessage) {
  200. return { body: this._errRespMessage, status: 400 }
  201. }
  202. return { body: { token: this.token }, status: 200 }
  203. }
  204. /**
  205. * @typedef {{action: string, payload: object}} State
  206. * @param {State} state
  207. */
  208. saveState (state) {
  209. if (!this.storage) return
  210. this.storage.set(`${Uploader.STORAGE_PREFIX}:${this.token}`, jsonStringify(state))
  211. }
  212. /**
  213. * This method emits upload progress but also creates an "upload progress" illusion
  214. * for the waiting period while only download is happening. Hence, it combines both
  215. * download and upload into an upload progress.
  216. * @see emitProgress
  217. * @param {number=} bytesUploaded the bytes actually Uploaded so far
  218. */
  219. emitIllusiveProgress (bytesUploaded) {
  220. if (this._paused) {
  221. return
  222. }
  223. let bytesTotal = this.streamsEnded ? this.bytesWritten : this.options.size
  224. if (!this.streamsEnded) {
  225. bytesTotal = Math.max(bytesTotal, this.bytesWritten)
  226. }
  227. bytesUploaded = bytesUploaded || 0
  228. // for a 10MB file, 10MB of download will account for 5MB upload progress
  229. // and 10MB of actual upload will account for the other 5MB upload progress.
  230. const illusiveBytesUploaded = (this.bytesWritten / 2) + (bytesUploaded / 2)
  231. logger.debug(
  232. `${this.shortToken} ${bytesUploaded} ${illusiveBytesUploaded} ${bytesTotal}`,
  233. 'uploader.illusive.progress'
  234. )
  235. this.emitProgress(illusiveBytesUploaded, bytesTotal)
  236. }
  237. /**
  238. *
  239. * @param {number} bytesUploaded
  240. * @param {number | null} bytesTotal
  241. */
  242. emitProgress (bytesUploaded, bytesTotal) {
  243. bytesTotal = bytesTotal || this.options.size
  244. if (this.tus && this.tus.options.uploadLengthDeferred && this.streamsEnded) {
  245. bytesTotal = this.bytesWritten
  246. }
  247. const percentage = (bytesUploaded / bytesTotal * 100)
  248. const formatPercentage = percentage.toFixed(2)
  249. logger.debug(
  250. `${this.shortToken} ${bytesUploaded} ${bytesTotal} ${formatPercentage}%`,
  251. 'uploader.upload.progress'
  252. )
  253. const dataToEmit = {
  254. action: 'progress',
  255. payload: { progress: formatPercentage, bytesUploaded, bytesTotal }
  256. }
  257. this.saveState(dataToEmit)
  258. // avoid flooding the client with progress events.
  259. const roundedPercentage = Math.floor(percentage)
  260. if (this.emittedProgress !== roundedPercentage) {
  261. this.emittedProgress = roundedPercentage
  262. emitter().emit(this.token, dataToEmit)
  263. }
  264. }
  265. /**
  266. *
  267. * @param {string} url
  268. * @param {object} extraData
  269. */
  270. emitSuccess (url, extraData = {}) {
  271. const emitData = {
  272. action: 'success',
  273. payload: Object.assign(extraData, { complete: true, url })
  274. }
  275. this.saveState(emitData)
  276. emitter().emit(this.token, emitData)
  277. }
  278. /**
  279. *
  280. * @param {Error} err
  281. * @param {object=} extraData
  282. */
  283. emitError (err, extraData = {}) {
  284. const dataToEmit = {
  285. action: 'error',
  286. // TODO: consider removing the stack property
  287. payload: Object.assign(extraData, { error: serializeError(err) })
  288. }
  289. this.saveState(dataToEmit)
  290. emitter().emit(this.token, dataToEmit)
  291. }
  292. /**
  293. * start the tus upload
  294. */
  295. uploadTus () {
  296. const fname = path.basename(this.options.path)
  297. const ftype = this.options.metadata.type
  298. const metadata = Object.assign({ filename: fname, filetype: ftype }, this.options.metadata || {})
  299. const file = fs.createReadStream(this.options.path)
  300. const uploader = this
  301. // @ts-ignore
  302. this.tus = new tus.Upload(file, {
  303. endpoint: this.options.endpoint,
  304. uploadUrl: this.options.uploadUrl,
  305. // @ts-ignore
  306. uploadLengthDeferred: false,
  307. resume: true,
  308. retryDelays: [0, 1000, 3000, 5000],
  309. uploadSize: this.bytesWritten,
  310. metadata,
  311. /**
  312. *
  313. * @param {Error} error
  314. */
  315. onError (error) {
  316. logger.error(error, 'uploader.tus.error')
  317. uploader.emitError(error)
  318. },
  319. /**
  320. *
  321. * @param {number} bytesUploaded
  322. * @param {number} bytesTotal
  323. */
  324. onProgress (bytesUploaded, bytesTotal) {
  325. uploader.emitIllusiveProgress(bytesUploaded)
  326. },
  327. onSuccess () {
  328. uploader.emitSuccess(uploader.tus.url)
  329. uploader.cleanUp()
  330. }
  331. })
  332. if (!this._paused) {
  333. this.tus.start()
  334. }
  335. }
  336. uploadMultipart () {
  337. const file = fs.createReadStream(this.options.path)
  338. // upload progress
  339. let bytesUploaded = 0
  340. file.on('data', (data) => {
  341. bytesUploaded += data.length
  342. this.emitIllusiveProgress(bytesUploaded)
  343. })
  344. const formData = Object.assign(
  345. {},
  346. this.options.metadata,
  347. { [this.options.fieldname]: file }
  348. )
  349. const headers = headerSanitize(this.options.headers)
  350. request.post({ url: this.options.endpoint, headers, formData, encoding: null }, (error, response, body) => {
  351. if (error) {
  352. logger.error(error, 'upload.multipart.error')
  353. this.emitError(error)
  354. return
  355. }
  356. const headers = response.headers
  357. // remove browser forbidden headers
  358. delete headers['set-cookie']
  359. delete headers['set-cookie2']
  360. const respObj = {
  361. responseText: body.toString(),
  362. status: response.statusCode,
  363. statusText: response.statusMessage,
  364. headers
  365. }
  366. if (response.statusCode >= 400) {
  367. logger.error(`upload failed with status: ${response.statusCode}`, 'upload.multipart.error')
  368. this.emitError(new Error(response.statusMessage), respObj)
  369. } else if (bytesUploaded !== this.bytesWritten && bytesUploaded !== this.options.size) {
  370. const errMsg = `uploaded only ${bytesUploaded} of ${this.bytesWritten} with status: ${response.statusCode}`
  371. logger.error(errMsg, 'upload.multipart.mismatch.error')
  372. this.emitError(new Error(errMsg))
  373. } else {
  374. this.emitSuccess(null, { response: respObj })
  375. }
  376. this.cleanUp()
  377. })
  378. }
  379. /**
  380. * Upload the file to S3 while it is still being downloaded.
  381. */
  382. uploadS3 () {
  383. const file = createTailReadStream(this.options.path, {
  384. tail: true
  385. })
  386. this.writeStream.on('finish', () => {
  387. file.close()
  388. })
  389. return this._uploadS3(file)
  390. }
  391. /**
  392. * Upload a stream to S3.
  393. */
  394. _uploadS3 (stream) {
  395. if (!this.options.s3) {
  396. this.emitError(new Error('The S3 client is not configured on this companion instance.'))
  397. return
  398. }
  399. const filename = this.options.metadata.filename || path.basename(this.options.path)
  400. const { client, options } = this.options.s3
  401. const upload = client.upload({
  402. Bucket: options.bucket,
  403. Key: options.getKey(null, filename),
  404. ACL: options.acl,
  405. ContentType: this.options.metadata.type,
  406. Body: stream
  407. })
  408. this.s3Upload = upload
  409. upload.on('httpUploadProgress', ({ loaded, total }) => {
  410. this.emitProgress(loaded, total)
  411. })
  412. upload.send((error, data) => {
  413. this.s3Upload = null
  414. if (error) {
  415. this.emitError(error)
  416. } else {
  417. this.emitSuccess(null, {
  418. response: {
  419. responseText: JSON.stringify(data),
  420. headers: {
  421. 'content-type': 'application/json'
  422. }
  423. }
  424. })
  425. }
  426. this.cleanUp()
  427. })
  428. }
  429. }
  430. Uploader.FILE_NAME_PREFIX = 'uppy-file'
  431. Uploader.STORAGE_PREFIX = 'companion'
  432. module.exports = Uploader