Provider.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. 'use strict'
  2. require('whatwg-fetch')
  3. const _getName = (id) => {
  4. return id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
  5. }
  6. module.exports = class Provider {
  7. constructor (core, opts) {
  8. this.core = core
  9. this.opts = opts
  10. this.provider = opts.provider
  11. this.id = this.provider
  12. this.authProvider = opts.authProvider || this.provider
  13. this.name = this.opts.name || _getName(this.id)
  14. this.onReceiveResponse = this.onReceiveResponse.bind(this)
  15. }
  16. get hostname () {
  17. const uppyServer = this.core.state.uppyServer || {}
  18. const host = this.opts.host
  19. return uppyServer[host] || host
  20. }
  21. onReceiveResponse (response) {
  22. const uppyServer = this.core.state.uppyServer || {}
  23. const host = this.opts.host
  24. const headers = response.headers
  25. // Store the self-identified domain name for the uppy-server we just hit.
  26. if (headers.has('i-am') && headers.get('i-am') !== uppyServer[host]) {
  27. this.core.setState({
  28. uppyServer: Object.assign({}, uppyServer, {
  29. [host]: headers.get('i-am')
  30. })
  31. })
  32. }
  33. return response
  34. }
  35. checkAuth () {
  36. return fetch(`${this.hostname}/${this.id}/authorized`, {
  37. method: 'get',
  38. credentials: 'include',
  39. headers: {
  40. 'Accept': 'application/json',
  41. 'Content-Type': 'application/json'
  42. }
  43. })
  44. .then(this.onReceiveResponse)
  45. .then((res) => {
  46. return res.json()
  47. .then((payload) => {
  48. return payload.authenticated
  49. })
  50. })
  51. }
  52. authUrl () {
  53. return `${this.hostname}/${this.id}/connect`
  54. }
  55. fileUrl (id) {
  56. return `${this.hostname}/${this.id}/get/${id}`
  57. }
  58. list (directory) {
  59. return fetch(`${this.hostname}/${this.id}/list/${directory || ''}`, {
  60. method: 'get',
  61. credentials: 'include',
  62. headers: {
  63. 'Accept': 'application/json',
  64. 'Content-Type': 'application/json'
  65. }
  66. })
  67. .then(this.onReceiveResponse)
  68. .then((res) => res.json())
  69. }
  70. logout (redirect = location.href) {
  71. return fetch(`${this.hostname}/${this.id}/logout?redirect=${redirect}`, {
  72. method: 'get',
  73. credentials: 'include',
  74. headers: {
  75. 'Accept': 'application/json',
  76. 'Content-Type': 'application/json'
  77. }
  78. })
  79. }
  80. }