customprovider.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. const request = require('request')
  2. const BASE_URL = 'https://api.unsplash.com'
  3. /**
  4. * an example of a custom provider module. It implements @uppy/companion's Provider interface
  5. */
  6. class MyCustomProvider {
  7. constructor (options) {
  8. this.authProvider = 'myunsplash'
  9. }
  10. list ({ token, directory }, done) {
  11. const path = directory ? `/${directory}/photos` : ''
  12. const options = {
  13. url: `${BASE_URL}/collections${path}`,
  14. method: 'GET',
  15. json: true,
  16. headers: {
  17. Authorization: `Bearer ${token}`
  18. }
  19. }
  20. request(options, (err, resp, body) => {
  21. if (err) {
  22. console.log(err)
  23. done(err)
  24. return
  25. }
  26. done(null, this._adaptData(body))
  27. })
  28. }
  29. download ({ id, token }, onData) {
  30. const options = {
  31. url: `${BASE_URL}/photos/${id}`,
  32. method: 'GET',
  33. json: true,
  34. headers: {
  35. Authorization: `Bearer ${token}`
  36. }
  37. }
  38. request(options, (err, resp, body) => {
  39. if (err) {
  40. console.log(err)
  41. return
  42. }
  43. const url = body.links.download
  44. request.get(url)
  45. .on('data', (chunk) => onData(null, chunk))
  46. .on('end', () => onData(null, null))
  47. .on('error', (err) => console.log(err))
  48. })
  49. }
  50. size ({ id, token }, done) {
  51. const options = {
  52. url: `${BASE_URL}/photos/${id}`,
  53. method: 'GET',
  54. json: true,
  55. headers: {
  56. Authorization: `Bearer ${token}`
  57. }
  58. }
  59. request(options, (err, resp, body) => {
  60. if (err) {
  61. console.log(err)
  62. done(err)
  63. return
  64. }
  65. done(null, body.width * body.height)
  66. })
  67. }
  68. _adaptData (res) {
  69. const data = {
  70. username: null,
  71. items: [],
  72. nextPagePath: null
  73. }
  74. const items = res
  75. items.forEach((item) => {
  76. const isFolder = !!item.published_at
  77. data.items.push({
  78. isFolder: isFolder,
  79. icon: isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
  80. name: item.title || item.description,
  81. mimeType: isFolder ? null : 'image/jpeg',
  82. id: item.id,
  83. thumbnail: isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
  84. requestPath: item.id,
  85. modifiedDate: item.updated_at,
  86. size: null
  87. })
  88. })
  89. return data
  90. }
  91. }
  92. module.exports = MyCustomProvider