index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /**
  2. * This plugin is currently a A Big Hack™! The core reason for that is how this plugin
  3. * interacts with Uppy's current pipeline design. The pipeline can handle files in steps,
  4. * including preprocessing, uploading, and postprocessing steps. This plugin initially
  5. * was designed to do its work in a preprocessing step, and let XHRUpload deal with the
  6. * actual file upload as an uploading step. However, Uppy runs steps on all files at once,
  7. * sequentially: first, all files go through a preprocessing step, then, once they are all
  8. * done, they go through the uploading step.
  9. *
  10. * For S3, this causes severely broken behaviour when users upload many files. The
  11. * preprocessing step will request S3 upload URLs that are valid for a short time only,
  12. * but it has to do this for _all_ files, which can take a long time if there are hundreds
  13. * or even thousands of files. By the time the uploader step starts, the first URLs may
  14. * already have expired. If not, the uploading might take such a long time that later URLs
  15. * will expire before some files can be uploaded.
  16. *
  17. * The long-term solution to this problem is to change the upload pipeline so that files
  18. * can be sent to the next step individually. That requires a breaking change, so it is
  19. * planned for some future Uppy version.
  20. *
  21. * In the mean time, this plugin is stuck with a hackier approach: the necessary parts
  22. * of the XHRUpload implementation were copied into this plugin, as the MiniXHRUpload
  23. * class, and this plugin calls into it immediately once it receives an upload URL.
  24. * This isn't as nicely modular as we'd like and requires us to maintain two copies of
  25. * the XHRUpload code, but at least it's not horrifically broken :)
  26. */
  27. const { BasePlugin } = require('@uppy/core')
  28. const Translator = require('@uppy/utils/lib/Translator')
  29. const { RateLimitedQueue, internalRateLimitedQueue } = require('@uppy/utils/lib/RateLimitedQueue')
  30. const settle = require('@uppy/utils/lib/settle')
  31. const hasProperty = require('@uppy/utils/lib/hasProperty')
  32. const { RequestClient } = require('@uppy/companion-client')
  33. const qsStringify = require('qs-stringify')
  34. const MiniXHRUpload = require('./MiniXHRUpload')
  35. const isXml = require('./isXml')
  36. function resolveUrl (origin, link) {
  37. return new URL(link, origin || undefined).toString()
  38. }
  39. /**
  40. * Get the contents of a named tag in an XML source string.
  41. *
  42. * @param {string} source - The XML source string.
  43. * @param {string} tagName - The name of the tag.
  44. * @returns {string} The contents of the tag, or the empty string if the tag does not exist.
  45. */
  46. function getXmlValue (source, tagName) {
  47. const start = source.indexOf(`<${tagName}>`)
  48. const end = source.indexOf(`</${tagName}>`, start)
  49. return start !== -1 && end !== -1
  50. ? source.slice(start + tagName.length + 2, end)
  51. : ''
  52. }
  53. function assertServerError (res) {
  54. if (res && res.error) {
  55. const error = new Error(res.message)
  56. Object.assign(error, res.error)
  57. throw error
  58. }
  59. return res
  60. }
  61. // warning deduplication flag: see `getResponseData()` XHRUpload option definition
  62. let warnedSuccessActionStatus = false
  63. module.exports = class AwsS3 extends BasePlugin {
  64. static VERSION = require('../package.json').version
  65. constructor (uppy, opts) {
  66. super(uppy, opts)
  67. this.type = 'uploader'
  68. this.id = this.opts.id || 'AwsS3'
  69. this.title = 'AWS S3'
  70. this.defaultLocale = {
  71. strings: {
  72. timedOut: 'Upload stalled for %{seconds} seconds, aborting.',
  73. },
  74. }
  75. const defaultOptions = {
  76. timeout: 30 * 1000,
  77. limit: 0,
  78. metaFields: [], // have to opt in
  79. getUploadParameters: this.getUploadParameters.bind(this),
  80. }
  81. this.opts = { ...defaultOptions, ...opts }
  82. this.i18nInit()
  83. this.client = new RequestClient(uppy, opts)
  84. this.handleUpload = this.handleUpload.bind(this)
  85. this.requests = new RateLimitedQueue(this.opts.limit)
  86. }
  87. setOptions (newOpts) {
  88. super.setOptions(newOpts)
  89. this.i18nInit()
  90. }
  91. i18nInit () {
  92. this.translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale])
  93. this.i18n = this.translator.translate.bind(this.translator)
  94. this.setPluginState() // so that UI re-renders and we see the updated locale
  95. }
  96. getUploadParameters (file) {
  97. if (!this.opts.companionUrl) {
  98. throw new Error('Expected a `companionUrl` option containing a Companion address.')
  99. }
  100. const filename = file.meta.name
  101. const { type } = file.meta
  102. const metadata = {}
  103. this.opts.metaFields.forEach((key) => {
  104. if (file.meta[key] != null) {
  105. metadata[key] = file.meta[key].toString()
  106. }
  107. })
  108. const query = qsStringify({ filename, type, metadata })
  109. return this.client.get(`s3/params?${query}`)
  110. .then(assertServerError)
  111. }
  112. validateParameters (file, params) {
  113. const valid = typeof params === 'object' && params
  114. && typeof params.url === 'string'
  115. && (typeof params.fields === 'object' || params.fields == null)
  116. if (!valid) {
  117. const err = new TypeError(`AwsS3: got incorrect result from 'getUploadParameters()' for file '${file.name}', expected an object '{ url, method, fields, headers }' but got '${JSON.stringify(params)}' instead.\nSee https://uppy.io/docs/aws-s3/#getUploadParameters-file for more on the expected format.`)
  118. console.error(err)
  119. throw err
  120. }
  121. const methodIsValid = params.method == null || /^(put|post)$/i.test(params.method)
  122. if (!methodIsValid) {
  123. const err = new TypeError(`AwsS3: got incorrect method from 'getUploadParameters()' for file '${file.name}', expected 'put' or 'post' but got '${params.method}' instead.\nSee https://uppy.io/docs/aws-s3/#getUploadParameters-file for more on the expected format.`)
  124. console.error(err)
  125. throw err
  126. }
  127. }
  128. handleUpload (fileIDs) {
  129. /**
  130. * keep track of `getUploadParameters()` responses
  131. * so we can cancel the calls individually using just a file ID
  132. *
  133. * @type {object.<string, Promise>}
  134. */
  135. const paramsPromises = Object.create(null)
  136. function onremove (file) {
  137. const { id } = file
  138. if (hasProperty(paramsPromises, id)) {
  139. paramsPromises[id].abort()
  140. }
  141. }
  142. this.uppy.on('file-removed', onremove)
  143. fileIDs.forEach((id) => {
  144. const file = this.uppy.getFile(id)
  145. this.uppy.emit('upload-started', file)
  146. })
  147. const getUploadParameters = this.requests.wrapPromiseFunction((file) => {
  148. return this.opts.getUploadParameters(file)
  149. })
  150. const numberOfFiles = fileIDs.length
  151. return settle(fileIDs.map((id, index) => {
  152. paramsPromises[id] = getUploadParameters(this.uppy.getFile(id))
  153. return paramsPromises[id].then((params) => {
  154. delete paramsPromises[id]
  155. const file = this.uppy.getFile(id)
  156. this.validateParameters(file, params)
  157. const {
  158. method = 'post',
  159. url,
  160. fields,
  161. headers,
  162. } = params
  163. const xhrOpts = {
  164. method,
  165. formData: method.toLowerCase() === 'post',
  166. endpoint: url,
  167. metaFields: fields ? Object.keys(fields) : [],
  168. }
  169. if (headers) {
  170. xhrOpts.headers = headers
  171. }
  172. this.uppy.setFileState(file.id, {
  173. meta: { ...file.meta, ...fields },
  174. xhrUpload: xhrOpts,
  175. })
  176. return this._uploader.uploadFile(file.id, index, numberOfFiles)
  177. }).catch((error) => {
  178. delete paramsPromises[id]
  179. const file = this.uppy.getFile(id)
  180. this.uppy.emit('upload-error', file, error)
  181. })
  182. })).then((settled) => {
  183. // cleanup.
  184. this.uppy.off('file-removed', onremove)
  185. return settled
  186. })
  187. }
  188. install () {
  189. const { uppy } = this
  190. this.uppy.addUploader(this.handleUpload)
  191. // Get the response data from a successful XMLHttpRequest instance.
  192. // `content` is the S3 response as a string.
  193. // `xhr` is the XMLHttpRequest instance.
  194. function defaultGetResponseData (content, xhr) {
  195. const opts = this
  196. // If no response, we've hopefully done a PUT request to the file
  197. // in the bucket on its full URL.
  198. if (!isXml(content, xhr)) {
  199. if (opts.method.toUpperCase() === 'POST') {
  200. if (!warnedSuccessActionStatus) {
  201. uppy.log('[AwsS3] No response data found, make sure to set the success_action_status AWS SDK option to 201. See https://uppy.io/docs/aws-s3/#POST-Uploads', 'warning')
  202. warnedSuccessActionStatus = true
  203. }
  204. // The responseURL won't contain the object key. Give up.
  205. return { location: null }
  206. }
  207. // responseURL is not available in older browsers.
  208. if (!xhr.responseURL) {
  209. return { location: null }
  210. }
  211. // Trim the query string because it's going to be a bunch of presign
  212. // parameters for a PUT request—doing a GET request with those will
  213. // always result in an error
  214. return { location: xhr.responseURL.replace(/\?.*$/, '') }
  215. }
  216. return {
  217. // Some S3 alternatives do not reply with an absolute URL.
  218. // Eg DigitalOcean Spaces uses /$bucketName/xyz
  219. location: resolveUrl(xhr.responseURL, getXmlValue(content, 'Location')),
  220. bucket: getXmlValue(content, 'Bucket'),
  221. key: getXmlValue(content, 'Key'),
  222. etag: getXmlValue(content, 'ETag'),
  223. }
  224. }
  225. // Get the error data from a failed XMLHttpRequest instance.
  226. // `content` is the S3 response as a string.
  227. // `xhr` is the XMLHttpRequest instance.
  228. function defaultGetResponseError (content, xhr) {
  229. // If no response, we don't have a specific error message, use the default.
  230. if (!isXml(content, xhr)) {
  231. return
  232. }
  233. const error = getXmlValue(content, 'Message')
  234. return new Error(error)
  235. }
  236. const xhrOptions = {
  237. fieldName: 'file',
  238. responseUrlFieldName: 'location',
  239. timeout: this.opts.timeout,
  240. // Share the rate limiting queue with XHRUpload.
  241. [internalRateLimitedQueue]: this.requests,
  242. responseType: 'text',
  243. getResponseData: this.opts.getResponseData || defaultGetResponseData,
  244. getResponseError: defaultGetResponseError,
  245. }
  246. // Only for MiniXHRUpload, remove once we can depend on XHRUpload directly again
  247. xhrOptions.i18n = this.i18n
  248. // Revert to `this.uppy.use(XHRUpload)` once the big comment block at the top of
  249. // this file is solved
  250. this._uploader = new MiniXHRUpload(this.uppy, xhrOptions)
  251. }
  252. uninstall () {
  253. this.uppy.removeUploader(this.handleUpload)
  254. }
  255. }