-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ProviderView.jsx
476 lines (406 loc) · 14.8 KB
/
ProviderView.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import { h } from 'preact'
// eslint-disable-next-line import/no-unresolved
import PQueue from 'p-queue'
import { getSafeFileId } from '@uppy/utils/lib/generateFileID'
import AuthView from './AuthView.jsx'
import Header from './Header.jsx'
import Browser from '../Browser.jsx'
import LoaderView from '../Loader.jsx'
import CloseWrapper from '../CloseWrapper.js'
import View from '../View.js'
import packageJson from '../../package.json'
function getOrigin () {
// eslint-disable-next-line no-restricted-globals
return location.origin
}
function getRegex (value) {
if (typeof value === 'string') {
return new RegExp(`^${value}$`)
} if (value instanceof RegExp) {
return value
}
return undefined
}
function isOriginAllowed (origin, allowedOrigin) {
const patterns = Array.isArray(allowedOrigin) ? allowedOrigin.map(getRegex) : [getRegex(allowedOrigin)]
return patterns
.some((pattern) => pattern?.test(origin) || pattern?.test(`${origin}/`)) // allowing for trailing '/'
}
function formatDirectoryStack (directoryStack) {
return directoryStack.slice(1).map((directory) => directory.name).join('/')
}
function addPath (path, component) {
if (!path) return component
return `${path}/${component}`
}
/**
* Class to easily generate generic views for Provider plugins
*/
export default class ProviderView extends View {
static VERSION = packageJson.version
/**
* @param {object} plugin instance of the plugin
* @param {object} opts
*/
constructor (plugin, opts) {
super(plugin, opts)
// set default options
const defaultOptions = {
viewType: 'list',
showTitles: true,
showFilter: true,
showBreadcrumbs: true,
}
// merge default options with the ones set by user
this.opts = { ...defaultOptions, ...opts }
// Logic
this.filterQuery = this.filterQuery.bind(this)
this.clearFilter = this.clearFilter.bind(this)
this.getFolder = this.getFolder.bind(this)
this.getNextFolder = this.getNextFolder.bind(this)
this.logout = this.logout.bind(this)
this.handleAuth = this.handleAuth.bind(this)
this.handleScroll = this.handleScroll.bind(this)
this.donePicking = this.donePicking.bind(this)
// Visual
this.render = this.render.bind(this)
// Set default state for the plugin
this.plugin.setPluginState({
authenticated: false,
files: [],
folders: [],
directoryStack: [],
filterInput: '',
isSearchVisible: false,
currentSelection: [],
})
}
// eslint-disable-next-line class-methods-use-this
tearDown () {
// Nothing.
}
async #list (requestPath, absDirPath) {
const { username, nextPagePath, items } = await this.provider.list(requestPath)
this.username = username || this.username
return {
items: items.map((item) => ({
...item,
absDirPath,
})),
nextPagePath,
}
}
async #updateFilesAndFolders (requestPath, directoryStack, filesIn, foldersIn) {
const absDirPath = formatDirectoryStack(directoryStack)
const { items, nextPagePath } = await this.#list(requestPath, absDirPath)
this.nextPagePath = nextPagePath
const files = filesIn ? [...filesIn] : []
const folders = foldersIn ? [...foldersIn] : []
items.forEach((item) => {
if (item.isFolder) {
folders.push(item)
} else {
files.push(item)
}
})
this.plugin.setPluginState({ folders, files })
}
/**
* Select a folder based on its id: fetches the folder and then updates state with its contents
* TODO rename to something better like selectFolder or navigateToFolder (breaking change?)
*
* @param {string} requestPath
* the path we need to use when sending list request to companion (for some providers it's different from ID)
* @param {string} name used in the UI and to build the absDirPath
* @returns {Promise} Folders/files in folder
*/
async getFolder (requestPath, name) {
this.setLoading(true)
try {
this.lastCheckbox = undefined
let { directoryStack } = this.plugin.getPluginState()
const index = directoryStack.findIndex((dir) => requestPath === dir.requestPath)
if (index !== -1) {
// means we navigated back to a known directory (already in the stack), so cut the stack off there
directoryStack = directoryStack.slice(0, index + 1)
} else {
// we have navigated into a new (unknown) folder, add it to the stack
directoryStack = [...directoryStack, { requestPath, name }]
}
this.plugin.setPluginState({ directoryStack, filterInput: '' })
await this.#updateFilesAndFolders(requestPath, directoryStack)
} catch (err) {
this.handleError(err)
} finally {
this.setLoading(false)
}
}
/**
* Fetches new folder
*
* @param {object} folder
*/
getNextFolder (folder) {
this.getFolder(folder.requestPath, folder.name)
this.lastCheckbox = undefined
}
/**
* Removes session token on client side.
*/
logout () {
this.provider.logout()
.then((res) => {
if (res.ok) {
if (!res.revoked) {
const message = this.plugin.uppy.i18n('companionUnauthorizeHint', {
provider: this.plugin.title,
url: res.manual_revoke_url,
})
this.plugin.uppy.info(message, 'info', 7000)
}
const newState = {
authenticated: false,
files: [],
folders: [],
directoryStack: [],
filterInput: '',
}
this.plugin.setPluginState(newState)
}
}).catch(this.handleError)
}
filterQuery (input) {
this.plugin.setPluginState({ filterInput: input })
}
clearFilter () {
this.plugin.setPluginState({ filterInput: '' })
}
async handleAuth () {
await this.provider.ensurePreAuth()
const authState = btoa(JSON.stringify({ origin: getOrigin() }))
const clientVersion = `@uppy/provider-views=${ProviderView.VERSION}`
const link = this.provider.authUrl({ state: authState, uppyVersions: clientVersion })
const authWindow = window.open(link, '_blank')
const handleToken = (e) => {
if (e.source !== authWindow) {
this.plugin.uppy.log('rejecting event from unknown source')
return
}
if (!isOriginAllowed(e.origin, this.plugin.opts.companionAllowedHosts) || e.source !== authWindow) {
this.plugin.uppy.log(`rejecting event from ${e.origin} vs allowed pattern ${this.plugin.opts.companionAllowedHosts}`)
}
// Check if it's a string before doing the JSON.parse to maintain support
// for older Companion versions that used object references
const data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data
if (data.error) {
this.plugin.uppy.log('auth aborted', 'warning')
const { uppy } = this.plugin
const message = uppy.i18n('authAborted')
uppy.info({ message }, 'warning', 5000)
return
}
if (!data.token) {
this.plugin.uppy.log('did not receive token from auth window', 'error')
return
}
authWindow.close()
window.removeEventListener('message', handleToken)
this.provider.setAuthToken(data.token)
this.preFirstRender()
}
window.addEventListener('message', handleToken)
}
async handleScroll (event) {
const requestPath = this.nextPagePath || null
if (this.shouldHandleScroll(event) && requestPath) {
this.isHandlingScroll = true
try {
const { directoryStack, files, folders } = this.plugin.getPluginState()
await this.#updateFilesAndFolders(requestPath, directoryStack, files, folders)
} catch (error) {
this.handleError(error)
} finally {
this.isHandlingScroll = false
}
}
}
async #recursivelyListAllFiles ({ requestPath, absDirPath, relDirPath, queue, onFiles }) {
let curPath = requestPath
while (curPath) {
const res = await this.#list(curPath, absDirPath)
curPath = res.nextPagePath
const files = res.items.filter((item) => !item.isFolder)
const folders = res.items.filter((item) => item.isFolder)
onFiles(files)
// recursively queue call to self for each folder
const promises = folders.map(async (folder) => queue.add(async () => (
this.#recursivelyListAllFiles({
requestPath: folder.requestPath,
absDirPath: addPath(absDirPath, folder.name),
relDirPath: addPath(relDirPath, folder.name),
queue,
onFiles,
})
)))
await Promise.all(promises) // in case we get an error
}
}
async donePicking () {
this.setLoading(true)
try {
const { currentSelection } = this.plugin.getPluginState()
const messages = []
const newFiles = []
for (const selectedItem of currentSelection) {
const { requestPath } = selectedItem
const withRelDirPath = (newItem) => ({
...newItem,
// calculate the file's path relative to the user's selected item's path
// see https://github.com/transloadit/uppy/pull/4537#issuecomment-1614236655
relDirPath: newItem.absDirPath.replace(selectedItem.absDirPath, '').replace(/^\//, ''),
})
if (selectedItem.isFolder) {
let isEmpty = true
let numNewFiles = 0
const queue = new PQueue({ concurrency: 6 })
const onFiles = (files) => {
for (const newFile of files) {
const tagFile = this.getTagFile(newFile)
const id = getSafeFileId(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(withRelDirPath(newFile))
numNewFiles++
this.setLoading(this.plugin.uppy.i18n('addedNumFiles', { numFiles: numNewFiles }))
}
isEmpty = false
}
}
await this.#recursivelyListAllFiles({
requestPath,
absDirPath: addPath(selectedItem.absDirPath, selectedItem.name),
relDirPath: selectedItem.name,
queue,
onFiles,
})
await queue.onIdle()
let message
if (isEmpty) {
message = this.plugin.uppy.i18n('emptyFolderAdded')
} else if (numNewFiles === 0) {
message = this.plugin.uppy.i18n('folderAlreadyAdded', {
folder: selectedItem.name,
})
} else {
// TODO we don't really know at this point whether any files were actually added
// (only later after addFiles has been called) so we should probably rewrite this.
// Example: If all files fail to add due to restriction error, it will still say "Added 100 files from folder"
message = this.plugin.uppy.i18n('folderAdded', {
smart_count: numNewFiles, folder: selectedItem.name,
})
}
messages.push(message)
} else {
newFiles.push(withRelDirPath(selectedItem))
}
}
// Note: this.plugin.uppy.addFiles 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
this.plugin.uppy.log('Adding remote provider files')
this.plugin.uppy.addFiles(newFiles.map((file) => this.getTagFile(file)))
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 = {}) {
const { authenticated, didFirstRender } = this.plugin.getPluginState()
const { i18n } = this.plugin.uppy
if (!didFirstRender) {
this.preFirstRender()
}
const targetViewOptions = { ...this.opts, ...viewOptions }
const { files, folders, filterInput, loading, currentSelection } = this.plugin.getPluginState()
const { isChecked, toggleCheckbox, recordShiftKeyPress, filterItems } = this
const hasInput = filterInput !== ''
const headerProps = {
showBreadcrumbs: targetViewOptions.showBreadcrumbs,
getFolder: this.getFolder,
directoryStack: this.plugin.getPluginState().directoryStack,
pluginIcon: this.plugin.icon,
title: this.plugin.title,
logout: this.logout,
username: this.username,
i18n,
}
const browserProps = {
isChecked,
toggleCheckbox,
recordShiftKeyPress,
currentSelection,
files: hasInput ? filterItems(files) : files,
folders: hasInput ? filterItems(folders) : folders,
username: this.username,
getNextFolder: this.getNextFolder,
getFolder: this.getFolder,
// For SearchFilterInput component
showSearchFilter: targetViewOptions.showFilter,
search: this.filterQuery,
clearSearch: this.clearFilter,
searchTerm: filterInput,
searchOnInput: true,
searchInputLabel: i18n('filter'),
clearSearchLabel: i18n('resetFilter'),
noResultsLabel: i18n('noFilesFound'),
logout: this.logout,
handleScroll: this.handleScroll,
done: this.donePicking,
cancel: this.cancelPicking,
headerComponent: Header(headerProps),
title: this.plugin.title,
viewType: targetViewOptions.viewType,
showTitles: targetViewOptions.showTitles,
showBreadcrumbs: targetViewOptions.showBreadcrumbs,
pluginIcon: this.plugin.icon,
i18n: this.plugin.uppy.i18n,
uppyFiles: this.plugin.uppy.getFiles(),
validateRestrictions: (...args) => this.plugin.uppy.validateRestrictions(...args),
}
if (loading) {
return (
<CloseWrapper onUnmount={this.clearSelection}>
<LoaderView i18n={this.plugin.uppy.i18n} loading={loading} />
</CloseWrapper>
)
}
if (!authenticated) {
return (
<CloseWrapper onUnmount={this.clearSelection}>
<AuthView
pluginName={this.plugin.title}
pluginIcon={this.plugin.icon}
handleAuth={this.handleAuth}
i18n={this.plugin.uppy.i18n}
i18nArray={this.plugin.uppy.i18nArray}
/>
</CloseWrapper>
)
}
return (
<CloseWrapper onUnmount={this.clearSelection}>
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
<Browser {...browserProps} />
</CloseWrapper>
)
}
}