index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 breakig change, so it is
  19. * planned for Uppy v2.
  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. // If global `URL` constructor is available, use it
  28. const URL_ = typeof URL === 'function' ? URL : require('url-parse')
  29. const { BasePlugin } = require('@uppy/core')
  30. const Translator = require('@uppy/utils/lib/Translator')
  31. const RateLimitedQueue = require('@uppy/utils/lib/RateLimitedQueue')
  32. const settle = require('@uppy/utils/lib/settle')
  33. const hasProperty = require('@uppy/utils/lib/hasProperty')
  34. const { RequestClient } = require('@uppy/companion-client')
  35. const qsStringify = require('qs-stringify')
  36. const MiniXHRUpload = require('./MiniXHRUpload')
  37. const isXml = require('./isXml')
  38. function resolveUrl (origin, link) {
  39. return origin
  40. ? new URL_(link, origin).toString()
  41. : new URL_(link).toString()
  42. }
  43. /**
  44. * Get the contents of a named tag in an XML source string.
  45. *
  46. * @param {string} source - The XML source string.
  47. * @param {string} tagName - The name of the tag.
  48. * @returns {string} The contents of the tag, or the empty string if the tag does not exist.
  49. */
  50. function getXmlValue (source, tagName) {
  51. const start = source.indexOf(`<${tagName}>`)
  52. const end = source.indexOf(`</${tagName}>`, start)
  53. return start !== -1 && end !== -1
  54. ? source.slice(start + tagName.length + 2, end)
  55. : ''
  56. }
  57. function assertServerError (res) {
  58. if (res && res.error) {
  59. const error = new Error(res.message)
  60. Object.assign(error, res.error)
  61. throw error
  62. }
  63. return res
  64. }
  65. // warning deduplication flag: see `getResponseData()` XHRUpload option definition
  66. let warnedSuccessActionStatus = false
  67. module.exports = class AwsS3 extends BasePlugin {
  68. static VERSION = require('../package.json').version
  69. constructor (uppy, opts) {
  70. super(uppy, opts)
  71. this.type = 'uploader'
  72. this.id = this.opts.id || 'AwsS3'
  73. this.title = 'AWS S3'
  74. this.defaultLocale = {
  75. strings: {
  76. timedOut: 'Upload stalled for %{seconds} seconds, aborting.',
  77. },
  78. }
  79. const defaultOptions = {
  80. timeout: 30 * 1000,
  81. limit: 0,
  82. metaFields: [], // have to opt in
  83. getUploadParameters: this.getUploadParameters.bind(this),
  84. }
  85. this.opts = { ...defaultOptions, ...opts }
  86. this.i18nInit()
  87. this.client = new RequestClient(uppy, opts)
  88. this.handleUpload = this.handleUpload.bind(this)
  89. this.requests = new RateLimitedQueue(this.opts.limit)
  90. }
  91. setOptions (newOpts) {
  92. super.setOptions(newOpts)
  93. this.i18nInit()
  94. }
  95. i18nInit () {
  96. this.translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale])
  97. this.i18n = this.translator.translate.bind(this.translator)
  98. this.setPluginState() // so that UI re-renders and we see the updated locale
  99. }
  100. getUploadParameters (file) {
  101. if (!this.opts.companionUrl) {
  102. throw new Error('Expected a `companionUrl` option containing a Companion address.')
  103. }
  104. const filename = file.meta.name
  105. const type = file.meta.type
  106. const metadata = {}
  107. this.opts.metaFields.forEach((key) => {
  108. if (file.meta[key] != null) {
  109. metadata[key] = file.meta[key].toString()
  110. }
  111. })
  112. const query = qsStringify({ filename, type, metadata })
  113. return this.client.get(`s3/params?${query}`)
  114. .then(assertServerError)
  115. }
  116. validateParameters (file, params) {
  117. const valid = typeof params === 'object' && params
  118. && typeof params.url === 'string'
  119. && (typeof params.fields === 'object' || params.fields == null)
  120. if (!valid) {
  121. 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.`)
  122. console.error(err)
  123. throw err
  124. }
  125. const methodIsValid = params.method == null || /^(put|post)$/i.test(params.method)
  126. if (!methodIsValid) {
  127. 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.`)
  128. console.error(err)
  129. throw err
  130. }
  131. }
  132. handleUpload (fileIDs) {
  133. /**
  134. * keep track of `getUploadParameters()` responses
  135. * so we can cancel the calls individually using just a file ID
  136. *
  137. * @type {object.<string, Promise>}
  138. */
  139. const paramsPromises = Object.create(null)
  140. function onremove (file) {
  141. const { id } = file
  142. if (hasProperty(paramsPromises, id)) {
  143. paramsPromises[id].abort()
  144. }
  145. }
  146. this.uppy.on('file-removed', onremove)
  147. fileIDs.forEach((id) => {
  148. const file = this.uppy.getFile(id)
  149. this.uppy.emit('upload-started', file)
  150. })
  151. const getUploadParameters = this.requests.wrapPromiseFunction((file) => {
  152. return this.opts.getUploadParameters(file)
  153. })
  154. const numberOfFiles = fileIDs.length
  155. return settle(fileIDs.map((id, index) => {
  156. paramsPromises[id] = getUploadParameters(this.uppy.getFile(id))
  157. return paramsPromises[id].then((params) => {
  158. delete paramsPromises[id]
  159. const file = this.uppy.getFile(id)
  160. this.validateParameters(file, params)
  161. const {
  162. method = 'post',
  163. url,
  164. fields,
  165. headers,
  166. } = params
  167. const xhrOpts = {
  168. method,
  169. formData: method.toLowerCase() === 'post',
  170. endpoint: url,
  171. metaFields: fields ? Object.keys(fields) : [],
  172. }
  173. if (headers) {
  174. xhrOpts.headers = headers
  175. }
  176. this.uppy.setFileState(file.id, {
  177. meta: { ...file.meta, ...fields },
  178. xhrUpload: xhrOpts,
  179. })
  180. return this._uploader.uploadFile(file.id, index, numberOfFiles)
  181. }).catch((error) => {
  182. delete paramsPromises[id]
  183. const file = this.uppy.getFile(id)
  184. this.uppy.emit('upload-error', file, error)
  185. })
  186. })).then((settled) => {
  187. // cleanup.
  188. this.uppy.off('file-removed', onremove)
  189. return settled
  190. })
  191. }
  192. install () {
  193. const uppy = this.uppy
  194. this.uppy.addUploader(this.handleUpload)
  195. // Get the response data from a successful XMLHttpRequest instance.
  196. // `content` is the S3 response as a string.
  197. // `xhr` is the XMLHttpRequest instance.
  198. function defaultGetResponseData (content, xhr) {
  199. const opts = this
  200. // If no response, we've hopefully done a PUT request to the file
  201. // in the bucket on its full URL.
  202. if (!isXml(content, xhr)) {
  203. if (opts.method.toUpperCase() === 'POST') {
  204. if (!warnedSuccessActionStatus) {
  205. 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')
  206. warnedSuccessActionStatus = true
  207. }
  208. // The responseURL won't contain the object key. Give up.
  209. return { location: null }
  210. }
  211. // responseURL is not available in older browsers.
  212. if (!xhr.responseURL) {
  213. return { location: null }
  214. }
  215. // Trim the query string because it's going to be a bunch of presign
  216. // parameters for a PUT request—doing a GET request with those will
  217. // always result in an error
  218. return { location: xhr.responseURL.replace(/\?.*$/, '') }
  219. }
  220. return {
  221. // Some S3 alternatives do not reply with an absolute URL.
  222. // Eg DigitalOcean Spaces uses /$bucketName/xyz
  223. location: resolveUrl(xhr.responseURL, getXmlValue(content, 'Location')),
  224. bucket: getXmlValue(content, 'Bucket'),
  225. key: getXmlValue(content, 'Key'),
  226. etag: getXmlValue(content, 'ETag'),
  227. }
  228. }
  229. // Get the error data from a failed XMLHttpRequest instance.
  230. // `content` is the S3 response as a string.
  231. // `xhr` is the XMLHttpRequest instance.
  232. function defaultGetResponseError (content, xhr) {
  233. // If no response, we don't have a specific error message, use the default.
  234. if (!isXml(content, xhr)) {
  235. return
  236. }
  237. const error = getXmlValue(content, 'Message')
  238. return new Error(error)
  239. }
  240. const xhrOptions = {
  241. fieldName: 'file',
  242. responseUrlFieldName: 'location',
  243. timeout: this.opts.timeout,
  244. // Share the rate limiting queue with XHRUpload.
  245. __queue: this.requests,
  246. responseType: 'text',
  247. getResponseData: this.opts.getResponseData || defaultGetResponseData,
  248. getResponseError: defaultGetResponseError,
  249. }
  250. // Only for MiniXHRUpload, remove once we can depend on XHRUpload directly again
  251. xhrOptions.i18n = this.i18n
  252. // Revert to `this.uppy.use(XHRUpload)` once the big comment block at the top of
  253. // this file is solved
  254. this._uploader = new MiniXHRUpload(this.uppy, xhrOptions)
  255. }
  256. uninstall () {
  257. this.uppy.removeUploader(this.handleUpload)
  258. }
  259. }