Provider.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. 'use strict'
  2. const qsStringify = require('qs-stringify')
  3. const RequestClient = require('./RequestClient')
  4. const tokenStorage = require('./tokenStorage')
  5. const _getName = (id) => {
  6. return id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
  7. }
  8. module.exports = class Provider extends RequestClient {
  9. constructor (uppy, opts) {
  10. super(uppy, opts)
  11. this.provider = opts.provider
  12. this.id = this.provider
  13. this.name = this.opts.name || _getName(this.id)
  14. this.pluginId = this.opts.pluginId
  15. this.tokenKey = `companion-${this.pluginId}-auth-token`
  16. this.companionKeysParams = this.opts.companionKeysParams
  17. this.preAuthToken = null
  18. }
  19. headers () {
  20. return Promise.all([super.headers(), this.getAuthToken()])
  21. .then(([headers, token]) => {
  22. const authHeaders = {}
  23. if (token) {
  24. authHeaders['uppy-auth-token'] = token
  25. }
  26. if (this.companionKeysParams) {
  27. authHeaders['uppy-credentials-params'] = btoa(
  28. JSON.stringify({ params: this.companionKeysParams })
  29. )
  30. }
  31. return { ...headers, ...authHeaders }
  32. })
  33. }
  34. onReceiveResponse (response) {
  35. response = super.onReceiveResponse(response)
  36. const plugin = this.uppy.getPlugin(this.pluginId)
  37. const oldAuthenticated = plugin.getPluginState().authenticated
  38. const authenticated = oldAuthenticated ? response.status !== 401 : response.status < 400
  39. plugin.setPluginState({ authenticated })
  40. return response
  41. }
  42. setAuthToken (token) {
  43. return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token)
  44. }
  45. getAuthToken () {
  46. return this.uppy.getPlugin(this.pluginId).storage.getItem(this.tokenKey)
  47. }
  48. authUrl (queries = {}) {
  49. if (this.preAuthToken) {
  50. queries.uppyPreAuthToken = this.preAuthToken
  51. }
  52. let strigifiedQueries = qsStringify(queries)
  53. strigifiedQueries = strigifiedQueries ? `?${strigifiedQueries}` : strigifiedQueries
  54. return `${this.hostname}/${this.id}/connect${strigifiedQueries}`
  55. }
  56. fileUrl (id) {
  57. return `${this.hostname}/${this.id}/get/${id}`
  58. }
  59. fetchPreAuthToken () {
  60. if (!this.companionKeysParams) {
  61. return Promise.resolve()
  62. }
  63. return this.post(`${this.id}/preauth/`, { params: this.companionKeysParams })
  64. .then((res) => {
  65. this.preAuthToken = res.token
  66. }).catch((err) => {
  67. this.uppy.log(`[CompanionClient] unable to fetch preAuthToken ${err}`, 'warning')
  68. })
  69. }
  70. list (directory) {
  71. return this.get(`${this.id}/list/${directory || ''}`)
  72. }
  73. logout () {
  74. return this.get(`${this.id}/logout`)
  75. .then((response) => Promise.all([
  76. response,
  77. this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey),
  78. ])).then(([response]) => response)
  79. }
  80. static initPlugin (plugin, opts, defaultOpts) {
  81. plugin.type = 'acquirer'
  82. plugin.files = []
  83. if (defaultOpts) {
  84. plugin.opts = { ...defaultOpts, ...opts }
  85. }
  86. if (opts.serverUrl || opts.serverPattern) {
  87. throw new Error('`serverUrl` and `serverPattern` have been renamed to `companionUrl` and `companionAllowedHosts` respectively in the 0.30.5 release. Please consult the docs (for example, https://uppy.io/docs/instagram/ for the Instagram plugin) and use the updated options.`')
  88. }
  89. if (opts.companionAllowedHosts) {
  90. const pattern = opts.companionAllowedHosts
  91. // validate companionAllowedHosts param
  92. if (typeof pattern !== 'string' && !Array.isArray(pattern) && !(pattern instanceof RegExp)) {
  93. throw new TypeError(`${plugin.id}: the option "companionAllowedHosts" must be one of string, Array, RegExp`)
  94. }
  95. plugin.opts.companionAllowedHosts = pattern
  96. } else {
  97. // does not start with https://
  98. if (/^(?!https?:\/\/).*$/i.test(opts.companionUrl)) {
  99. plugin.opts.companionAllowedHosts = `https://${opts.companionUrl.replace(/^\/\//, '')}`
  100. } else {
  101. plugin.opts.companionAllowedHosts = new URL(opts.companionUrl).origin
  102. }
  103. }
  104. plugin.storage = plugin.opts.storage || tokenStorage
  105. }
  106. }