index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. const { h, Component } = require('preact')
  2. const AuthView = require('./AuthView')
  3. const Browser = require('./Browser')
  4. const LoaderView = require('./Loader')
  5. const generateFileID = require('../../utils/generateFileID')
  6. const getFileType = require('../../utils/getFileType')
  7. const isPreviewSupported = require('../../utils/isPreviewSupported')
  8. /**
  9. * Array.prototype.findIndex ponyfill for old browsers.
  10. */
  11. function findIndex (array, predicate) {
  12. for (let i = 0; i < array.length; i++) {
  13. if (predicate(array[i])) return i
  14. }
  15. return -1
  16. }
  17. class CloseWrapper extends Component {
  18. componentWillUnmount () {
  19. this.props.onUnmount()
  20. }
  21. render () {
  22. return this.props.children[0]
  23. }
  24. }
  25. /**
  26. * Class to easily generate generic views for plugins
  27. *
  28. *
  29. * This class expects the plugin instance using it to have the following
  30. * accessor methods.
  31. * Each method takes the item whose property is to be accessed
  32. * as a param
  33. *
  34. * isFolder
  35. * @return {Boolean} for if the item is a folder or not
  36. * getItemData
  37. * @return {Object} that is format ready for uppy upload/download
  38. * getItemIcon
  39. * @return {Object} html instance of the item's icon
  40. * getItemSubList
  41. * @return {Array} sub-items in the item. e.g a folder may contain sub-items
  42. * getItemName
  43. * @return {String} display friendly name of the item
  44. * getMimeType
  45. * @return {String} mime type of the item
  46. * getItemId
  47. * @return {String} unique id of the item
  48. * getItemRequestPath
  49. * @return {String} unique request path of the item when making calls to uppy server
  50. * getItemModifiedDate
  51. * @return {object} or {String} date of when last the item was modified
  52. * getItemThumbnailUrl
  53. * @return {String}
  54. */
  55. module.exports = class ProviderView {
  56. /**
  57. * @param {object} instance of the plugin
  58. */
  59. constructor (plugin, opts) {
  60. this.plugin = plugin
  61. this.Provider = plugin[plugin.id]
  62. // set default options
  63. const defaultOptions = {
  64. viewType: 'list',
  65. showTitles: true,
  66. showFilter: true,
  67. showBreadcrumbs: true
  68. }
  69. // merge default options with the ones set by user
  70. this.opts = Object.assign({}, defaultOptions, opts)
  71. // Logic
  72. this.addFile = this.addFile.bind(this)
  73. this.filterItems = this.filterItems.bind(this)
  74. this.filterQuery = this.filterQuery.bind(this)
  75. this.toggleSearch = this.toggleSearch.bind(this)
  76. this.getFolder = this.getFolder.bind(this)
  77. this.getNextFolder = this.getNextFolder.bind(this)
  78. this.logout = this.logout.bind(this)
  79. this.checkAuth = this.checkAuth.bind(this)
  80. this.handleAuth = this.handleAuth.bind(this)
  81. this.handleDemoAuth = this.handleDemoAuth.bind(this)
  82. this.sortByTitle = this.sortByTitle.bind(this)
  83. this.sortByDate = this.sortByDate.bind(this)
  84. this.isActiveRow = this.isActiveRow.bind(this)
  85. this.isChecked = this.isChecked.bind(this)
  86. this.toggleCheckbox = this.toggleCheckbox.bind(this)
  87. this.handleError = this.handleError.bind(this)
  88. this.handleScroll = this.handleScroll.bind(this)
  89. this.donePicking = this.donePicking.bind(this)
  90. this.cancelPicking = this.cancelPicking.bind(this)
  91. this.clearSelection = this.clearSelection.bind(this)
  92. // Visual
  93. this.render = this.render.bind(this)
  94. this.clearSelection()
  95. }
  96. tearDown () {
  97. // Nothing.
  98. }
  99. _updateFilesAndFolders (res, files, folders) {
  100. this.plugin.getItemSubList(res).forEach((item) => {
  101. if (this.plugin.isFolder(item)) {
  102. folders.push(item)
  103. } else {
  104. files.push(item)
  105. }
  106. })
  107. this.plugin.setPluginState({ folders, files })
  108. }
  109. checkAuth () {
  110. this.plugin.setPluginState({ checkAuthInProgress: true })
  111. this.Provider.checkAuth()
  112. .then((authenticated) => {
  113. this.plugin.setPluginState({ checkAuthInProgress: false })
  114. this.plugin.onAuth(authenticated)
  115. })
  116. .catch((err) => {
  117. this.plugin.setPluginState({ checkAuthInProgress: false })
  118. this.handleError(err)
  119. })
  120. }
  121. /**
  122. * Based on folder ID, fetch a new folder and update it to state
  123. * @param {String} id Folder id
  124. * @return {Promise} Folders/files in folder
  125. */
  126. getFolder (id, name) {
  127. return this._loaderWrapper(
  128. this.Provider.list(id),
  129. (res) => {
  130. let folders = []
  131. let files = []
  132. let updatedDirectories
  133. const state = this.plugin.getPluginState()
  134. const index = findIndex(state.directories, (dir) => id === dir.id)
  135. if (index !== -1) {
  136. updatedDirectories = state.directories.slice(0, index + 1)
  137. } else {
  138. updatedDirectories = state.directories.concat([{id, title: name || this.plugin.getItemName(res)}])
  139. }
  140. this.username = this.username ? this.username : this.plugin.getUsername(res)
  141. this._updateFilesAndFolders(res, files, folders)
  142. this.plugin.setPluginState({ directories: updatedDirectories })
  143. },
  144. this.handleError)
  145. }
  146. /**
  147. * Fetches new folder
  148. * @param {Object} Folder
  149. * @param {String} title Folder title
  150. */
  151. getNextFolder (folder) {
  152. let id = this.plugin.getItemRequestPath(folder)
  153. this.getFolder(id, this.plugin.getItemName(folder))
  154. this.lastCheckbox = undefined
  155. }
  156. addFile (file) {
  157. const tagFile = {
  158. id: this.providerFileToId(file),
  159. source: this.plugin.id,
  160. data: this.plugin.getItemData(file),
  161. name: this.plugin.getItemName(file) || this.plugin.getItemId(file),
  162. type: this.plugin.getMimeType(file),
  163. isRemote: true,
  164. body: {
  165. fileId: this.plugin.getItemId(file)
  166. },
  167. remote: {
  168. serverUrl: this.plugin.opts.serverUrl,
  169. url: `${this.Provider.fileUrl(this.plugin.getItemRequestPath(file))}`,
  170. body: {
  171. fileId: this.plugin.getItemId(file)
  172. },
  173. providerOptions: this.Provider.opts
  174. }
  175. }
  176. const fileType = getFileType(tagFile)
  177. // TODO Should we just always use the thumbnail URL if it exists?
  178. if (fileType && isPreviewSupported(fileType)) {
  179. tagFile.preview = this.plugin.getItemThumbnailUrl(file)
  180. }
  181. this.plugin.uppy.log('Adding remote file')
  182. try {
  183. this.plugin.uppy.addFile(tagFile)
  184. } catch (err) {
  185. // Nothing, restriction errors handled in Core
  186. }
  187. }
  188. removeFile (id) {
  189. const { currentSelection } = this.plugin.getPluginState()
  190. this.plugin.setPluginState({
  191. currentSelection: currentSelection.filter((file) => file.id !== id)
  192. })
  193. }
  194. /**
  195. * Removes session token on client side.
  196. */
  197. logout () {
  198. this.Provider.logout(location.href)
  199. .then((res) => {
  200. if (res.ok) {
  201. const newState = {
  202. authenticated: false,
  203. files: [],
  204. folders: [],
  205. directories: []
  206. }
  207. this.plugin.setPluginState(newState)
  208. }
  209. }).catch(this.handleError)
  210. }
  211. filterQuery (e) {
  212. const state = this.plugin.getPluginState()
  213. this.plugin.setPluginState(Object.assign({}, state, {
  214. filterInput: e ? e.target.value : ''
  215. }))
  216. }
  217. toggleSearch (inputEl) {
  218. const state = this.plugin.getPluginState()
  219. this.plugin.setPluginState({
  220. isSearchVisible: !state.isSearchVisible,
  221. filterInput: ''
  222. })
  223. }
  224. filterItems (items) {
  225. const state = this.plugin.getPluginState()
  226. if (state.filterInput === '') {
  227. return items
  228. }
  229. return items.filter((folder) => {
  230. return this.plugin.getItemName(folder).toLowerCase().indexOf(state.filterInput.toLowerCase()) !== -1
  231. })
  232. }
  233. sortByTitle () {
  234. const state = Object.assign({}, this.plugin.getPluginState())
  235. const {files, folders, sorting} = state
  236. let sortedFiles = files.sort((fileA, fileB) => {
  237. if (sorting === 'titleDescending') {
  238. return this.plugin.getItemName(fileB).localeCompare(this.plugin.getItemName(fileA))
  239. }
  240. return this.plugin.getItemName(fileA).localeCompare(this.plugin.getItemName(fileB))
  241. })
  242. let sortedFolders = folders.sort((folderA, folderB) => {
  243. if (sorting === 'titleDescending') {
  244. return this.plugin.getItemName(folderB).localeCompare(this.plugin.getItemName(folderA))
  245. }
  246. return this.plugin.getItemName(folderA).localeCompare(this.plugin.getItemName(folderB))
  247. })
  248. this.plugin.setPluginState(Object.assign({}, state, {
  249. files: sortedFiles,
  250. folders: sortedFolders,
  251. sorting: (sorting === 'titleDescending') ? 'titleAscending' : 'titleDescending'
  252. }))
  253. }
  254. sortByDate () {
  255. const state = Object.assign({}, this.plugin.getPluginState())
  256. const {files, folders, sorting} = state
  257. let sortedFiles = files.sort((fileA, fileB) => {
  258. let a = new Date(this.plugin.getItemModifiedDate(fileA))
  259. let b = new Date(this.plugin.getItemModifiedDate(fileB))
  260. if (sorting === 'dateDescending') {
  261. return a > b ? -1 : a < b ? 1 : 0
  262. }
  263. return a > b ? 1 : a < b ? -1 : 0
  264. })
  265. let sortedFolders = folders.sort((folderA, folderB) => {
  266. let a = new Date(this.plugin.getItemModifiedDate(folderA))
  267. let b = new Date(this.plugin.getItemModifiedDate(folderB))
  268. if (sorting === 'dateDescending') {
  269. return a > b ? -1 : a < b ? 1 : 0
  270. }
  271. return a > b ? 1 : a < b ? -1 : 0
  272. })
  273. this.plugin.setPluginState(Object.assign({}, state, {
  274. files: sortedFiles,
  275. folders: sortedFolders,
  276. sorting: (sorting === 'dateDescending') ? 'dateAscending' : 'dateDescending'
  277. }))
  278. }
  279. sortBySize () {
  280. const state = Object.assign({}, this.plugin.getPluginState())
  281. const {files, sorting} = state
  282. // check that plugin supports file sizes
  283. if (!files.length || !this.plugin.getItemData(files[0]).size) {
  284. return
  285. }
  286. let sortedFiles = files.sort((fileA, fileB) => {
  287. let a = this.plugin.getItemData(fileA).size
  288. let b = this.plugin.getItemData(fileB).size
  289. if (sorting === 'sizeDescending') {
  290. return a > b ? -1 : a < b ? 1 : 0
  291. }
  292. return a > b ? 1 : a < b ? -1 : 0
  293. })
  294. this.plugin.setPluginState(Object.assign({}, state, {
  295. files: sortedFiles,
  296. sorting: (sorting === 'sizeDescending') ? 'sizeAscending' : 'sizeDescending'
  297. }))
  298. }
  299. isActiveRow (file) {
  300. return this.plugin.getPluginState().activeRow === this.plugin.getItemId(file)
  301. }
  302. isChecked (file) {
  303. const { currentSelection } = this.plugin.getPluginState()
  304. return currentSelection.some((item) => item === file)
  305. }
  306. /**
  307. * Adds all files found inside of specified folder.
  308. *
  309. * Uses separated state while folder contents are being fetched and
  310. * mantains list of selected folders, which are separated from files.
  311. */
  312. addFolder (folder) {
  313. const folderId = this.providerFileToId(folder)
  314. let state = this.plugin.getPluginState()
  315. let folders = state.selectedFolders || {}
  316. if (folderId in folders && folders[folderId].loading) {
  317. return
  318. }
  319. folders[folderId] = {loading: true, files: []}
  320. this.plugin.setPluginState({selectedFolders: folders})
  321. return this.Provider.list(this.plugin.getItemRequestPath(folder)).then((res) => {
  322. let files = []
  323. this.plugin.getItemSubList(res).forEach((item) => {
  324. if (!this.plugin.isFolder(item)) {
  325. this.addFile(item)
  326. files.push(this.providerFileToId(item))
  327. }
  328. })
  329. state = this.plugin.getPluginState()
  330. state.selectedFolders[folderId] = {loading: false, files: files}
  331. this.plugin.setPluginState({selectedFolders: folders})
  332. const dashboard = this.plugin.uppy.getPlugin('Dashboard')
  333. let message
  334. if (files.length) {
  335. message = dashboard.i18n('folderAdded', {
  336. smart_count: files.length, folder: this.plugin.getItemName(folder)
  337. })
  338. } else {
  339. message = dashboard.i18n('emptyFolderAdded')
  340. }
  341. this.plugin.uppy.info(message)
  342. }).catch((e) => {
  343. state = this.plugin.getPluginState()
  344. delete state.selectedFolders[folderId]
  345. this.plugin.setPluginState({selectedFolders: state.selectedFolders})
  346. this.handleError(e)
  347. })
  348. }
  349. /**
  350. * Toggles file/folder checkbox to on/off state while updating files list.
  351. *
  352. * Note that some extra complexity comes from supporting shift+click to
  353. * toggle multiple checkboxes at once, which is done by getting all files
  354. * in between last checked file and current one.
  355. */
  356. toggleCheckbox (e, file) {
  357. e.stopPropagation()
  358. e.preventDefault()
  359. let { folders, files } = this.plugin.getPluginState()
  360. let items = this.filterItems(folders.concat(files))
  361. // Shift-clicking selects a single consecutive list of items
  362. // starting at the previous click and deselects everything else.
  363. if (this.lastCheckbox && e.shiftKey) {
  364. let currentSelection
  365. const prevIndex = items.indexOf(this.lastCheckbox)
  366. const currentIndex = items.indexOf(file)
  367. if (prevIndex < currentIndex) {
  368. currentSelection = items.slice(prevIndex, currentIndex + 1)
  369. } else {
  370. currentSelection = items.slice(currentIndex, prevIndex + 1)
  371. }
  372. this.plugin.setPluginState({ currentSelection })
  373. return
  374. }
  375. this.lastCheckbox = file
  376. const { currentSelection } = this.plugin.getPluginState()
  377. if (this.isChecked(file)) {
  378. this.plugin.setPluginState({
  379. currentSelection: currentSelection.filter((item) => item !== file)
  380. })
  381. } else {
  382. this.plugin.setPluginState({
  383. currentSelection: currentSelection.concat([file])
  384. })
  385. }
  386. }
  387. providerFileToId (file) {
  388. return generateFileID({
  389. data: this.plugin.getItemData(file),
  390. name: this.plugin.getItemName(file) || this.plugin.getItemId(file),
  391. type: this.plugin.getMimeType(file)
  392. })
  393. }
  394. handleDemoAuth () {
  395. const state = this.plugin.getPluginState()
  396. this.plugin.setPluginState({}, state, {
  397. authenticated: true
  398. })
  399. }
  400. handleAuth () {
  401. const authState = btoa(JSON.stringify({ origin: location.origin }))
  402. const link = `${this.Provider.authUrl()}?state=${authState}`
  403. const authWindow = window.open(link, '_blank')
  404. const noProtocol = (url) => url.replace(/^(https?:|)\/\//, '')
  405. const handleToken = (e) => {
  406. const allowedOrigin = new RegExp(noProtocol(this.plugin.opts.serverPattern))
  407. if (!allowedOrigin.test(noProtocol(e.origin)) || e.source !== authWindow) {
  408. this.plugin.uppy.log(`rejecting event from ${e.origin} vs allowed pattern ${this.plugin.opts.serverPattern}`)
  409. return
  410. }
  411. authWindow.close()
  412. window.removeEventListener('message', handleToken)
  413. this.Provider.setAuthToken(e.data.token)
  414. this._loaderWrapper(this.Provider.checkAuth(), this.plugin.onAuth, this.handleError)
  415. }
  416. window.addEventListener('message', handleToken)
  417. }
  418. handleError (error) {
  419. const uppy = this.plugin.uppy
  420. const message = uppy.i18n('uppyServerError')
  421. uppy.log(error.toString())
  422. uppy.info({message: message, details: error.toString()}, 'error', 5000)
  423. }
  424. handleScroll (e) {
  425. const scrollPos = e.target.scrollHeight - (e.target.scrollTop + e.target.offsetHeight)
  426. const path = this.plugin.getNextPagePath ? this.plugin.getNextPagePath() : null
  427. if (scrollPos < 50 && path && !this._isHandlingScroll) {
  428. this.Provider.list(path)
  429. .then((res) => {
  430. const { files, folders } = this.plugin.getPluginState()
  431. this._updateFilesAndFolders(res, files, folders)
  432. }).catch(this.handleError)
  433. .then(() => { this._isHandlingScroll = false }) // always called
  434. this._isHandlingScroll = true
  435. }
  436. }
  437. donePicking () {
  438. const { currentSelection } = this.plugin.getPluginState()
  439. const promises = currentSelection.map((file) => {
  440. if (this.plugin.isFolder(file)) {
  441. return this.addFolder(file)
  442. } else {
  443. return this.addFile(file)
  444. }
  445. })
  446. this._loaderWrapper(Promise.all(promises), () => {
  447. this.clearSelection()
  448. const dashboard = this.plugin.uppy.getPlugin('Dashboard')
  449. if (dashboard) dashboard.hideAllPanels()
  450. }, () => {})
  451. }
  452. cancelPicking () {
  453. this.clearSelection()
  454. const dashboard = this.plugin.uppy.getPlugin('Dashboard')
  455. if (dashboard) dashboard.hideAllPanels()
  456. }
  457. clearSelection () {
  458. this.plugin.setPluginState({ currentSelection: [] })
  459. }
  460. // displays loader view while asynchronous request is being made.
  461. _loaderWrapper (promise, then, catch_) {
  462. promise
  463. .then(then).catch(catch_)
  464. .then(() => this.plugin.setPluginState({ loading: false })) // always called.
  465. this.plugin.setPluginState({ loading: true })
  466. }
  467. render (state) {
  468. const { authenticated, checkAuthInProgress, loading } = this.plugin.getPluginState()
  469. if (loading) {
  470. return (
  471. <CloseWrapper onUnmount={this.clearSelection}>
  472. <LoaderView />
  473. </CloseWrapper>
  474. )
  475. }
  476. if (!authenticated) {
  477. return (
  478. <CloseWrapper onUnmount={this.clearSelection}>
  479. <AuthView
  480. pluginName={this.plugin.title}
  481. pluginIcon={this.plugin.icon}
  482. demo={this.plugin.opts.demo}
  483. checkAuth={this.checkAuth}
  484. handleAuth={this.handleAuth}
  485. handleDemoAuth={this.handleDemoAuth}
  486. checkAuthInProgress={checkAuthInProgress} />
  487. </CloseWrapper>
  488. )
  489. }
  490. const browserProps = Object.assign({}, this.plugin.getPluginState(), {
  491. username: this.username,
  492. getNextFolder: this.getNextFolder,
  493. getFolder: this.getFolder,
  494. filterItems: this.filterItems,
  495. filterQuery: this.filterQuery,
  496. toggleSearch: this.toggleSearch,
  497. sortByTitle: this.sortByTitle,
  498. sortByDate: this.sortByDate,
  499. logout: this.logout,
  500. demo: this.plugin.opts.demo,
  501. isActiveRow: this.isActiveRow,
  502. isChecked: this.isChecked,
  503. toggleCheckbox: this.toggleCheckbox,
  504. getItemId: this.plugin.getItemId,
  505. getItemName: this.plugin.getItemName,
  506. getItemIcon: this.plugin.getItemIcon,
  507. handleScroll: this.handleScroll,
  508. done: this.donePicking,
  509. cancel: this.cancelPicking,
  510. title: this.plugin.title,
  511. viewType: this.opts.viewType,
  512. showTitles: this.opts.showTitles,
  513. showFilter: this.opts.showFilter,
  514. showBreadcrumbs: this.opts.showBreadcrumbs,
  515. pluginIcon: this.plugin.icon,
  516. i18n: this.plugin.uppy.i18n
  517. })
  518. return (
  519. <CloseWrapper onUnmount={this.clearSelection}>
  520. <Browser {...browserProps} />
  521. </CloseWrapper>
  522. )
  523. }
  524. }