ProviderView.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import { h } from 'preact'
  2. import { getSafeFileId } from '@uppy/utils/lib/generateFileID'
  3. import AuthView from './AuthView.jsx'
  4. import Header from './Header.jsx'
  5. import Browser from '../Browser.jsx'
  6. import LoaderView from '../Loader.jsx'
  7. import CloseWrapper from '../CloseWrapper.js'
  8. import View from '../View.js'
  9. import packageJson from '../../package.json'
  10. function getOrigin () {
  11. // eslint-disable-next-line no-restricted-globals
  12. return location.origin
  13. }
  14. function getRegex (value) {
  15. if (typeof value === 'string') {
  16. return new RegExp(`^${value}$`)
  17. } if (value instanceof RegExp) {
  18. return value
  19. }
  20. return undefined
  21. }
  22. function isOriginAllowed (origin, allowedOrigin) {
  23. const patterns = Array.isArray(allowedOrigin) ? allowedOrigin.map(getRegex) : [getRegex(allowedOrigin)]
  24. return patterns
  25. .some((pattern) => pattern?.test(origin) || pattern?.test(`${origin}/`)) // allowing for trailing '/'
  26. }
  27. /**
  28. * Class to easily generate generic views for Provider plugins
  29. */
  30. export default class ProviderView extends View {
  31. static VERSION = packageJson.version
  32. /**
  33. * @param {object} plugin instance of the plugin
  34. * @param {object} opts
  35. */
  36. constructor (plugin, opts) {
  37. super(plugin, opts)
  38. // set default options
  39. const defaultOptions = {
  40. viewType: 'list',
  41. showTitles: true,
  42. showFilter: true,
  43. showBreadcrumbs: true,
  44. }
  45. // merge default options with the ones set by user
  46. this.opts = { ...defaultOptions, ...opts }
  47. // Logic
  48. this.filterQuery = this.filterQuery.bind(this)
  49. this.clearFilter = this.clearFilter.bind(this)
  50. this.getFolder = this.getFolder.bind(this)
  51. this.getNextFolder = this.getNextFolder.bind(this)
  52. this.logout = this.logout.bind(this)
  53. this.handleAuth = this.handleAuth.bind(this)
  54. this.handleScroll = this.handleScroll.bind(this)
  55. this.donePicking = this.donePicking.bind(this)
  56. // Visual
  57. this.render = this.render.bind(this)
  58. // Set default state for the plugin
  59. this.plugin.setPluginState({
  60. authenticated: false,
  61. files: [],
  62. folders: [],
  63. directories: [],
  64. filterInput: '',
  65. isSearchVisible: false,
  66. currentSelection: [],
  67. })
  68. }
  69. // eslint-disable-next-line class-methods-use-this
  70. tearDown () {
  71. // Nothing.
  72. }
  73. #updateFilesAndFolders (res, files, folders) {
  74. this.nextPagePath = res.nextPagePath
  75. res.items.forEach((item) => {
  76. if (item.isFolder) {
  77. folders.push(item)
  78. } else {
  79. files.push(item)
  80. }
  81. })
  82. this.plugin.setPluginState({ folders, files })
  83. }
  84. /**
  85. * Based on folder ID, fetch a new folder and update it to state
  86. *
  87. * @param {string} id Folder id
  88. * @returns {Promise} Folders/files in folder
  89. */
  90. async getFolder (id, name) {
  91. this.setLoading(true)
  92. try {
  93. const res = await this.provider.list(id)
  94. const folders = []
  95. const files = []
  96. let updatedDirectories
  97. const state = this.plugin.getPluginState()
  98. const index = state.directories.findIndex((dir) => id === dir.id)
  99. if (index !== -1) {
  100. updatedDirectories = state.directories.slice(0, index + 1)
  101. } else {
  102. updatedDirectories = state.directories.concat([{ id, title: name }])
  103. }
  104. this.username = res.username || this.username
  105. this.#updateFilesAndFolders(res, files, folders)
  106. this.plugin.setPluginState({ directories: updatedDirectories, filterInput: '' })
  107. } catch (err) {
  108. this.handleError(err)
  109. } finally {
  110. this.setLoading(false)
  111. }
  112. }
  113. /**
  114. * Fetches new folder
  115. *
  116. * @param {object} folder
  117. */
  118. getNextFolder (folder) {
  119. this.getFolder(folder.requestPath, folder.name)
  120. this.lastCheckbox = undefined
  121. }
  122. /**
  123. * Removes session token on client side.
  124. */
  125. logout () {
  126. this.provider.logout()
  127. .then((res) => {
  128. if (res.ok) {
  129. if (!res.revoked) {
  130. const message = this.plugin.uppy.i18n('companionUnauthorizeHint', {
  131. provider: this.plugin.title,
  132. url: res.manual_revoke_url,
  133. })
  134. this.plugin.uppy.info(message, 'info', 7000)
  135. }
  136. const newState = {
  137. authenticated: false,
  138. files: [],
  139. folders: [],
  140. directories: [],
  141. filterInput: '',
  142. }
  143. this.plugin.setPluginState(newState)
  144. }
  145. }).catch(this.handleError)
  146. }
  147. filterQuery (input) {
  148. this.plugin.setPluginState({ filterInput: input })
  149. }
  150. clearFilter () {
  151. this.plugin.setPluginState({ filterInput: '' })
  152. }
  153. async handleAuth () {
  154. await this.provider.ensurePreAuth()
  155. const authState = btoa(JSON.stringify({ origin: getOrigin() }))
  156. const clientVersion = `@uppy/provider-views=${ProviderView.VERSION}`
  157. const link = this.provider.authUrl({ state: authState, uppyVersions: clientVersion })
  158. const authWindow = window.open(link, '_blank')
  159. const handleToken = (e) => {
  160. if (e.source !== authWindow) {
  161. this.plugin.uppy.log('rejecting event from unknown source')
  162. return
  163. }
  164. if (!isOriginAllowed(e.origin, this.plugin.opts.companionAllowedHosts) || e.source !== authWindow) {
  165. this.plugin.uppy.log(`rejecting event from ${e.origin} vs allowed pattern ${this.plugin.opts.companionAllowedHosts}`)
  166. }
  167. // Check if it's a string before doing the JSON.parse to maintain support
  168. // for older Companion versions that used object references
  169. const data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data
  170. if (data.error) {
  171. this.plugin.uppy.log('auth aborted', 'warning')
  172. const { uppy } = this.plugin
  173. const message = uppy.i18n('authAborted')
  174. uppy.info({ message }, 'warning', 5000)
  175. return
  176. }
  177. if (!data.token) {
  178. this.plugin.uppy.log('did not receive token from auth window', 'error')
  179. return
  180. }
  181. authWindow.close()
  182. window.removeEventListener('message', handleToken)
  183. this.provider.setAuthToken(data.token)
  184. this.preFirstRender()
  185. }
  186. window.addEventListener('message', handleToken)
  187. }
  188. async handleScroll (event) {
  189. const path = this.nextPagePath || null
  190. if (this.shouldHandleScroll(event) && path) {
  191. this.isHandlingScroll = true
  192. try {
  193. const response = await this.provider.list(path)
  194. const { files, folders } = this.plugin.getPluginState()
  195. this.#updateFilesAndFolders(response, files, folders)
  196. } catch (error) {
  197. this.handleError(error)
  198. } finally {
  199. this.isHandlingScroll = false
  200. }
  201. }
  202. }
  203. async* recursivelyListAllFiles (path) {
  204. let curPath = path
  205. // need to repeat the list call until there are no more pages
  206. while (curPath) {
  207. const res = await this.provider.list(curPath)
  208. for (const item of res.items) {
  209. if (item.isFolder) {
  210. // recursively call self for folder
  211. yield* this.recursivelyListAllFiles(item.requestPath)
  212. } else {
  213. yield item
  214. }
  215. }
  216. curPath = res.nextPagePath
  217. }
  218. }
  219. async donePicking () {
  220. this.setLoading(true)
  221. try {
  222. const { currentSelection } = this.plugin.getPluginState()
  223. const messages = []
  224. const newFiles = []
  225. // eslint-disable-next-line no-unreachable-loop
  226. for (const file of currentSelection) {
  227. if (file.isFolder) {
  228. const { requestPath, name } = file
  229. let isEmpty = true
  230. let numNewFiles = 0
  231. for await (const fileInFolder of this.recursivelyListAllFiles(requestPath)) {
  232. const tagFile = this.getTagFile(fileInFolder)
  233. const id = getSafeFileId(tagFile)
  234. // If the same folder is added again, we don't want to send
  235. // X amount of duplicate file notifications, we want to say
  236. // the folder was already added. This checks if all files are duplicate,
  237. // if that's the case, we don't add the files.
  238. if (!this.plugin.uppy.checkIfFileAlreadyExists(id)) {
  239. newFiles.push(fileInFolder)
  240. numNewFiles++
  241. this.setLoading(this.plugin.uppy.i18n('addedNumFiles', { numFiles: numNewFiles }))
  242. }
  243. isEmpty = false
  244. }
  245. let message
  246. if (isEmpty) {
  247. message = this.plugin.uppy.i18n('emptyFolderAdded')
  248. } else if (numNewFiles === 0) {
  249. message = this.plugin.uppy.i18n('folderAlreadyAdded', {
  250. folder: name,
  251. })
  252. } else {
  253. message = this.plugin.uppy.i18n('folderAdded', {
  254. smart_count: numNewFiles, folder: name,
  255. })
  256. }
  257. messages.push(message)
  258. } else {
  259. newFiles.push(file)
  260. }
  261. }
  262. // Note: this.plugin.uppy.addFiles must be only run once we are done fetching all files,
  263. // because it will cause the loading screen to disappear,
  264. // and that will allow the user to start the upload, so we need to make sure we have
  265. // finished all async operations before we add any file
  266. // see https://github.com/transloadit/uppy/pull/4384
  267. this.plugin.uppy.log('Adding remote provider files')
  268. this.plugin.uppy.addFiles(newFiles.map((file) => this.getTagFile(file)))
  269. this.plugin.setPluginState({ filterInput: '' })
  270. messages.forEach(message => this.plugin.uppy.info(message))
  271. this.clearSelection()
  272. } catch (err) {
  273. this.handleError(err)
  274. } finally {
  275. this.setLoading(false)
  276. }
  277. }
  278. render (state, viewOptions = {}) {
  279. const { authenticated, didFirstRender } = this.plugin.getPluginState()
  280. const { i18n } = this.plugin.uppy
  281. if (!didFirstRender) {
  282. this.preFirstRender()
  283. }
  284. const targetViewOptions = { ...this.opts, ...viewOptions }
  285. const { files, folders, filterInput, loading, currentSelection } = this.plugin.getPluginState()
  286. const { isChecked, toggleCheckbox, recordShiftKeyPress, filterItems } = this
  287. const hasInput = filterInput !== ''
  288. const headerProps = {
  289. showBreadcrumbs: targetViewOptions.showBreadcrumbs,
  290. getFolder: this.getFolder,
  291. directories: this.plugin.getPluginState().directories,
  292. pluginIcon: this.plugin.icon,
  293. title: this.plugin.title,
  294. logout: this.logout,
  295. username: this.username,
  296. i18n,
  297. }
  298. const browserProps = {
  299. isChecked,
  300. toggleCheckbox,
  301. recordShiftKeyPress,
  302. currentSelection,
  303. files: hasInput ? filterItems(files) : files,
  304. folders: hasInput ? filterItems(folders) : folders,
  305. username: this.username,
  306. getNextFolder: this.getNextFolder,
  307. getFolder: this.getFolder,
  308. // For SearchFilterInput component
  309. showSearchFilter: targetViewOptions.showFilter,
  310. search: this.filterQuery,
  311. clearSearch: this.clearFilter,
  312. searchTerm: filterInput,
  313. searchOnInput: true,
  314. searchInputLabel: i18n('filter'),
  315. clearSearchLabel: i18n('resetFilter'),
  316. noResultsLabel: i18n('noFilesFound'),
  317. logout: this.logout,
  318. handleScroll: this.handleScroll,
  319. done: this.donePicking,
  320. cancel: this.cancelPicking,
  321. headerComponent: Header(headerProps),
  322. title: this.plugin.title,
  323. viewType: targetViewOptions.viewType,
  324. showTitles: targetViewOptions.showTitles,
  325. showBreadcrumbs: targetViewOptions.showBreadcrumbs,
  326. pluginIcon: this.plugin.icon,
  327. i18n: this.plugin.uppy.i18n,
  328. uppyFiles: this.plugin.uppy.getFiles(),
  329. validateRestrictions: (...args) => this.plugin.uppy.validateRestrictions(...args),
  330. }
  331. if (loading) {
  332. return (
  333. <CloseWrapper onUnmount={this.clearSelection}>
  334. <LoaderView i18n={this.plugin.uppy.i18n} loading={loading} />
  335. </CloseWrapper>
  336. )
  337. }
  338. if (!authenticated) {
  339. return (
  340. <CloseWrapper onUnmount={this.clearSelection}>
  341. <AuthView
  342. pluginName={this.plugin.title}
  343. pluginIcon={this.plugin.icon}
  344. handleAuth={this.handleAuth}
  345. i18n={this.plugin.uppy.i18n}
  346. i18nArray={this.plugin.uppy.i18nArray}
  347. />
  348. </CloseWrapper>
  349. )
  350. }
  351. return (
  352. <CloseWrapper onUnmount={this.clearSelection}>
  353. {/* eslint-disable-next-line react/jsx-props-no-spreading */}
  354. <Browser {...browserProps} />
  355. </CloseWrapper>
  356. )
  357. }
  358. }