customprovider.js 2.2 KB

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