Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@uppy/provider-views: fix race condition when adding folders #4384

Merged
merged 26 commits into from
Apr 4, 2023
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions packages/@uppy/core/src/Uppy.js
Original file line number Diff line number Diff line change
Expand Up @@ -458,12 +458,9 @@ class Uppy {
const fileName = getFileName(fileType, fileDescriptor)
const fileExtension = getFileNameAndExtension(fileName).extension
const isRemote = Boolean(fileDescriptor.isRemote)
const fileID = generateFileID({
...fileDescriptor,
type: fileType,
})
const id = generateFileId2(fileDescriptor)

if (this.checkIfFileAlreadyExists(fileID)) {
if (this.checkIfFileAlreadyExists(id)) {
const error = new RestrictionError(this.i18n('noDuplicates', { fileName }))
this.#informAndEmit(error, fileDescriptor)
throw error
Expand All @@ -478,7 +475,7 @@ class Uppy {

let newFile = {
source: fileDescriptor.source || '',
id: fileID,
id,
name: fileName,
extension: fileExtension || '',
meta: {
Expand Down Expand Up @@ -1573,4 +1570,14 @@ class Uppy {
}
}

// todo come up with a better name or remove the need for two different generators
export function generateFileId2 (file) {
mifi marked this conversation as resolved.
Show resolved Hide resolved
const fileType = getFileType(file)

return generateFileID({
...file,
type: fileType,
})
}

export default Uppy
220 changes: 104 additions & 116 deletions packages/@uppy/provider-views/src/ProviderView/ProviderView.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { h } from 'preact'

import { generateFileId2 } from '@uppy/core/src/Uppy.js'

import AuthView from './AuthView.jsx'
import Header from './Header.jsx'
import Browser from '../Browser.jsx'
Expand Down Expand Up @@ -58,7 +60,6 @@ export default class ProviderView extends View {
this.logout = this.logout.bind(this)
this.handleAuth = this.handleAuth.bind(this)
this.handleScroll = this.handleScroll.bind(this)
this.listAllFiles = this.listAllFiles.bind(this)
this.donePicking = this.donePicking.bind(this)

// Visual
Expand Down Expand Up @@ -100,29 +101,31 @@ export default class ProviderView extends View {
* @param {string} id Folder id
* @returns {Promise} Folders/files in folder
*/
getFolder (id, name) {
return this.sharedHandler.loaderWrapper(
this.provider.list(id),
(res) => {
const folders = []
const files = []
let updatedDirectories

const state = this.plugin.getPluginState()
const index = state.directories.findIndex((dir) => id === dir.id)

if (index !== -1) {
updatedDirectories = state.directories.slice(0, index + 1)
} else {
updatedDirectories = state.directories.concat([{ id, title: name }])
}
async getFolder (id, name) {
this.setLoading(true)
Murderlon marked this conversation as resolved.
Show resolved Hide resolved
try {
const res = await this.provider.list(id)
const folders = []
const files = []
let updatedDirectories

const state = this.plugin.getPluginState()
const index = state.directories.findIndex((dir) => id === dir.id)

if (index !== -1) {
updatedDirectories = state.directories.slice(0, index + 1)
} else {
updatedDirectories = state.directories.concat([{ id, title: name }])
}

this.username = res.username || this.username
this.#updateFilesAndFolders(res, files, folders)
this.plugin.setPluginState({ directories: updatedDirectories, filterInput: '' })
},
this.handleError,
)
this.username = res.username || this.username
this.#updateFilesAndFolders(res, files, folders)
this.plugin.setPluginState({ directories: updatedDirectories, filterInput: '' })
} catch (err) {
this.handleError(err)
} finally {
this.setLoading(false)
}
}

/**
Expand Down Expand Up @@ -167,74 +170,6 @@ export default class ProviderView extends View {
this.plugin.setPluginState({ ...state, filterInput: e ? e.target.value : '' })
}

/**
* Adds all files found inside of specified folder.
*
* Uses separated state while folder contents are being fetched and
* mantains list of selected folders, which are separated from files.
*/
addFolder (folder) {
const folderId = this.providerFileToId(folder)
const folders = { ...this.plugin.getPluginState().selectedFolders }

if (folderId in folders && folders[folderId].loading) {
return
}

folders[folderId] = { loading: true, files: [] }

this.plugin.setPluginState({ selectedFolders: { ...folders } })

// eslint-disable-next-line consistent-return
return this.listAllFiles(folder.requestPath).then((files) => {
let count = 0

// If the same folder is added again, we don't want to send
// X amount of duplicate file notifications, we want to say
// the folder was already added. This checks if all files are duplicate,
// if that's the case, we don't add the files.
files.forEach(file => {
const id = this.providerFileToId(file)
if (!this.plugin.uppy.checkIfFileAlreadyExists(id)) {
count++
}
})

if (count > 0) {
files.forEach((file) => this.addFile(file))
}

const ids = files.map(this.providerFileToId)

folders[folderId] = {
loading: false,
files: ids,
}
this.plugin.setPluginState({ selectedFolders: folders, filterInput: '' })

let message

if (count === 0) {
message = this.plugin.uppy.i18n('folderAlreadyAdded', {
folder: folder.name,
})
} else if (files.length) {
message = this.plugin.uppy.i18n('folderAdded', {
smart_count: count, folder: folder.name,
})
} else {
message = this.plugin.uppy.i18n('emptyFolderAdded')
}

this.plugin.uppy.info(message)
}).catch((e) => {
const selectedFolders = { ...this.plugin.getPluginState().selectedFolders }
delete selectedFolders[folderId]
this.plugin.setPluginState({ selectedFolders })
this.handleError(e)
})
}

async handleAuth () {
await this.provider.ensurePreAuth()

Expand Down Expand Up @@ -296,35 +231,90 @@ export default class ProviderView extends View {
}
}

async listAllFiles (path, files = null) {
files = files || [] // eslint-disable-line no-param-reassign
const res = await this.provider.list(path)
res.items.forEach((item) => {
if (!item.isFolder) {
files.push(item)
} else {
this.addFolder(item)
async* recursivelyListAllFiles (path) {
let curPath = path

// need to repeat the list call until there are no more pages
while (curPath) {
const res = await this.provider.list(curPath)

for (const item of res.items) {
if (item.isFolder) {
// recursively call self for folder
yield* this.recursivelyListAllFiles(item.requestPath)
} else {
yield item
}
}
})
const moreFiles = res.nextPagePath
if (moreFiles) {
return this.listAllFiles(moreFiles, files)

curPath = res.nextPagePath
}
return files
}

donePicking () {
const { currentSelection } = this.plugin.getPluginState()
const promises = currentSelection.map((file) => {
if (file.isFolder) {
return this.addFolder(file)
async donePicking () {
this.setLoading(true)
try {
const { currentSelection } = this.plugin.getPluginState()

const messages = []
const newFiles = []

// eslint-disable-next-line no-unreachable-loop
for (const file of currentSelection) {
if (file.isFolder) {
const { requestPath, name } = file
let isEmpty = true
let numNewFiles = 0

for await (const fileInFolder of this.recursivelyListAllFiles(requestPath)) {
const tagFile = this.getTagFile(fileInFolder)
const id = generateFileId2(tagFile)
// If the same folder is added again, we don't want to send
// X amount of duplicate file notifications, we want to say
// the folder was already added. This checks if all files are duplicate,
// if that's the case, we don't add the files.
if (!this.plugin.uppy.checkIfFileAlreadyExists(id)) {
newFiles.push(fileInFolder)
mifi marked this conversation as resolved.
Show resolved Hide resolved
numNewFiles++
}
isEmpty = false
}

let message
if (isEmpty) {
message = this.plugin.uppy.i18n('emptyFolderAdded')
} else if (numNewFiles === 0) {
message = this.plugin.uppy.i18n('folderAlreadyAdded', {
folder: name,
})
} else {
message = this.plugin.uppy.i18n('folderAdded', {
smart_count: numNewFiles, folder: name,
})
}

messages.push(message)
} else {
newFiles.push(file)
}
}
return this.addFile(file)
})

this.sharedHandler.loaderWrapper(Promise.all(promises), () => {
// Note: this.addFile must be only run once we are done fetching all files,
// because it will cause the loading screen to disappear,
// and that will allow the user to start the upload, so we need to make sure we have
// finished all async operations before we add any file
// see https://github.com/transloadit/uppy/pull/4384
newFiles.forEach((file) => this.addFile(file))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it's not something to do in this PR, but we might consider having another way to signal the UI that the loading is not done, as it's not a great UX to get stuck on a loading screen for too long.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, there is currently no deterministic way to know whether we are still adding files. It probably requires as state machine of some sorts, where we can only be in one state at a time and a promise will make it move to the next. But that's a bigger undertaking.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would need to define then what should the UX be like. What do we show the user while files are loading? Is there anything more useful we can do than showing a loading screen and possibly a number of files loaded? We could immediately send them to the list of added files, and then disable the Upload button until everything is added, but I don't know how much value it gives the user to be able to browse files while new files are popping into view continuously, and they will not be able to click Upload.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could immediately send them to the list of added files, and then disable the Upload button until everything is added

To me that with a spinner of some sort or a progress bar is the UX I'd expect. The question is if it's enough of a common use case to prioritize implementing like that, if it's not trivial.

mifi marked this conversation as resolved.
Show resolved Hide resolved

this.plugin.setPluginState({ filterInput: '' })
messages.forEach(message => this.plugin.uppy.info(message))

this.clearSelection()
}, () => {})
} catch (err) {
this.handleError(err)
} finally {
this.setLoading(false)
}
}

render (state, viewOptions = {}) {
Expand All @@ -336,7 +326,7 @@ export default class ProviderView extends View {

const targetViewOptions = { ...this.opts, ...viewOptions }
const { files, folders, filterInput, loading, currentSelection } = this.plugin.getPluginState()
const { isChecked, toggleCheckbox, recordShiftKeyPress, filterItems } = this.sharedHandler
const { isChecked, toggleCheckbox, recordShiftKeyPress, filterItems } = this
const hasInput = filterInput !== ''
const headerProps = {
showBreadcrumbs: targetViewOptions.showBreadcrumbs,
Expand All @@ -359,11 +349,9 @@ export default class ProviderView extends View {
username: this.username,
getNextFolder: this.getNextFolder,
getFolder: this.getFolder,
filterItems: this.sharedHandler.filterItems,
filterQuery: this.filterQuery,
logout: this.logout,
handleScroll: this.handleScroll,
listAllFiles: this.listAllFiles,
done: this.donePicking,
cancel: this.cancelPicking,
headerComponent: Header(headerProps),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,20 +79,22 @@ export default class SearchProviderView extends View {
})
}

search (query) {
async search (query) {
const { searchTerm } = this.plugin.getPluginState()
if (query && query === searchTerm) {
// no need to search again as this is the same as the previous search
return undefined
return
}

return this.sharedHandler.loaderWrapper(
this.provider.search(query),
(res) => {
this.#updateFilesAndInputMode(res, [])
},
this.handleError,
)
this.setLoading(true)
try {
const res = await this.provider.search(query)
this.#updateFilesAndInputMode(res, [])
} catch (err) {
this.handleError(err)
} finally {
this.setLoading(false)
}
}

triggerSearchInput () {
Expand Down Expand Up @@ -120,11 +122,8 @@ export default class SearchProviderView extends View {

donePicking () {
const { currentSelection } = this.plugin.getPluginState()
const promises = currentSelection.map((file) => this.addFile(file))

this.sharedHandler.loaderWrapper(Promise.all(promises), () => {
this.clearSelection()
}, () => {})
currentSelection.forEach((file) => this.addFile(file))
this.clearSelection()
}

render (state, viewOptions = {}) {
Expand All @@ -136,7 +135,7 @@ export default class SearchProviderView extends View {

const targetViewOptions = { ...this.opts, ...viewOptions }
const { files, folders, filterInput, loading, currentSelection } = this.plugin.getPluginState()
const { isChecked, toggleCheckbox, filterItems } = this.sharedHandler
const { isChecked, toggleCheckbox, filterItems } = this
const hasInput = filterInput !== ''

const browserProps = {
Expand Down
Loading