forked from box/box-ui-elements
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContentUploader.tsx
1317 lines (1157 loc) · 42.8 KB
/
ContentUploader.tsx
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'regenerator-runtime/runtime';
import React, { Component } from 'react';
import classNames from 'classnames';
import cloneDeep from 'lodash/cloneDeep';
import getProp from 'lodash/get';
import noop from 'lodash/noop';
import uniqueid from 'lodash/uniqueId';
import { TooltipProvider } from '@box/blueprint-web';
import DroppableContent from './DroppableContent';
import Footer from './Footer';
import UploadsManager from './UploadsManager';
import API from '../../api';
import Browser from '../../utils/Browser';
import Internationalize from '../common/Internationalize';
import makeResponsive from '../common/makeResponsive';
import FolderUpload from '../../api/uploads/FolderUpload';
import { getTypedFileId, getTypedFolderId } from '../../utils/file';
import {
getDataTransferItemId,
getFile,
getFileAPIOptions,
getFileFromDataTransferItem,
getFileId,
getDataTransferItemAPIOptions,
getPackageFileFromDataTransferItem,
isDataTransferItemAFolder,
isDataTransferItemAPackage,
isMultiputSupported,
} from '../../utils/uploads';
import {
DEFAULT_ROOT,
CLIENT_NAME_CONTENT_UPLOADER,
DEFAULT_HOSTNAME_API,
DEFAULT_HOSTNAME_UPLOAD,
ERROR_CODE_UPLOAD_FILE_LIMIT,
STATUS_COMPLETE,
STATUS_ERROR,
STATUS_IN_PROGRESS,
STATUS_PENDING,
STATUS_STAGED,
VIEW_ERROR,
VIEW_UPLOAD_EMPTY,
VIEW_UPLOAD_IN_PROGRESS,
VIEW_UPLOAD_SUCCESS,
} from '../../constants';
import type { BoxItem, StringMap, Token, View } from '../../common/types/core';
import type {
UploadDataTransferItemWithAPIOptions,
UploadFile,
UploadFileWithAPIOptions,
UploadItem,
UploadItemAPIOptions,
UploadStatus,
} from '../../common/types/upload';
import '../common/fonts.scss';
import '../common/base.scss';
export interface ContentUploaderProps {
apiHost: string;
chunked: boolean;
className: string;
clientName: string;
dataTransferItems: Array<DataTransferItem | UploadDataTransferItemWithAPIOptions>;
fileLimit: number;
files?: Array<UploadFileWithAPIOptions | File>;
isDraggingItemsToUploadsManager?: boolean;
isFolderUploadEnabled: boolean;
isLarge: boolean;
isPartialUploadEnabled: boolean;
isPrepopulateFilesEnabled?: boolean;
isResumableUploadsEnabled: boolean;
isSmall: boolean;
isTouch: boolean;
isUploadFallbackLogicEnabled: boolean;
language?: string;
measureRef: (ref: Element | null) => void;
messages?: StringMap;
onBeforeUpload: (file: Array<UploadFileWithAPIOptions | File>) => void;
onCancel: (items?: UploadItem[]) => void;
onClickCancel: (item: UploadItem) => void;
onClickResume: (item: UploadItem) => void;
onClickRetry: (item: UploadItem) => void;
onClose: () => void;
onComplete: (items: UploadItem[]) => void;
onError: Function;
onMinimize?: () => void;
onProgress: (item: UploadItem) => void;
onResume: (item: UploadItem) => void;
onUpgradeCTAClick?: () => void;
onUpload: (item?: UploadItem | BoxItem) => void;
overwrite: boolean;
requestInterceptor?: Function;
responseInterceptor?: Function;
rootFolderId: string;
sharedLink?: string;
sharedLinkPassword?: string;
token?: Token;
uploadHost: string;
useUploadsManager?: boolean;
}
type State = {
errorCode?: string;
isUploadsManagerExpanded: boolean;
itemIds: Object;
items: UploadItem[];
view: View;
};
const CHUNKED_UPLOAD_MIN_SIZE_BYTES = 104857600; // 100MB
const FILE_LIMIT_DEFAULT = 100; // Upload at most 100 files at once by default
const HIDE_UPLOAD_MANAGER_DELAY_MS_DEFAULT = 8000;
const EXPAND_UPLOADS_MANAGER_ITEMS_NUM_THRESHOLD = 5;
const UPLOAD_CONCURRENCY = 6;
class ContentUploader extends Component<ContentUploaderProps, State> {
id: string;
props: ContentUploaderProps;
state: State;
rootElement: HTMLElement;
appElement: HTMLElement;
resetItemsTimeout: ReturnType<typeof setTimeout>;
isAutoExpanded: boolean = false;
itemsRef: React.MutableRefObject<UploadItem[]>;
itemIdsRef: React.MutableRefObject<Object>;
static defaultProps = {
apiHost: DEFAULT_HOSTNAME_API,
chunked: true,
className: '',
clientName: CLIENT_NAME_CONTENT_UPLOADER,
dataTransferItems: [],
files: [],
fileLimit: FILE_LIMIT_DEFAULT,
isDraggingItemsToUploadsManager: false,
isFolderUploadEnabled: false,
isPartialUploadEnabled: false,
isPrepopulateFilesEnabled: false,
isResumableUploadsEnabled: false,
isUploadFallbackLogicEnabled: false,
onBeforeUpload: noop,
onCancel: noop,
onClickCancel: noop,
onClickResume: noop,
onClickRetry: noop,
onClose: noop,
onComplete: noop,
onError: noop,
onMinimize: noop,
onProgress: noop,
onResume: noop,
onUpload: noop,
overwrite: true,
rootFolderId: DEFAULT_ROOT,
uploadHost: DEFAULT_HOSTNAME_UPLOAD,
useUploadsManager: false,
};
/**
* [constructor]
*
* @return {ContentUploader}
*/
constructor(props: ContentUploaderProps) {
super(props);
const { rootFolderId, token, useUploadsManager } = props;
this.state = {
view: (rootFolderId && token) || useUploadsManager ? VIEW_UPLOAD_EMPTY : VIEW_ERROR,
items: [],
errorCode: '',
itemIds: {},
isUploadsManagerExpanded: false,
};
this.id = uniqueid('bcu_');
this.itemsRef = React.createRef();
this.itemsRef.current = [];
this.itemIdsRef = React.createRef();
this.itemIdsRef.current = {};
}
/**
* Fetches the root folder on load
*
* @private
* @inheritdoc
* @return {void}
*/
componentDidMount() {
this.rootElement = document.getElementById(this.id);
this.appElement = this.rootElement;
const { files, isPrepopulateFilesEnabled } = this.props;
// isPrepopulateFilesEnabled is a prop used to pre-populate files without clicking upload button.
if (isPrepopulateFilesEnabled && files && files.length > 0) {
this.addFilesToUploadQueue(files, this.upload);
}
}
/**
* Cancels pending uploads
*
* @private
* @inheritdoc
* @return {void}
*/
componentWillUnmount() {
this.cancel();
}
/**
* Adds new items to the queue when files prop gets updated in window view
*
* @return {void}
*/
componentDidUpdate() {
const { files, dataTransferItems, useUploadsManager } = this.props;
const hasFiles = Array.isArray(files) && files.length > 0;
const hasItems = Array.isArray(dataTransferItems) && dataTransferItems.length > 0;
const hasUploads = hasFiles || hasItems;
if (!useUploadsManager || !hasUploads) {
return;
}
// TODO: this gets called unnecessarily (upon each render regardless of the queue not changing)
this.addFilesWithOptionsToUploadQueueAndStartUpload(files, dataTransferItems);
}
/**
* Create and return new instance of API creator
*
* @param {UploadItemAPIOptions} [uploadAPIOptions]
* @return {API}
*/
createAPIFactory(uploadAPIOptions?: UploadItemAPIOptions): API {
const { rootFolderId } = this.props;
const folderId = getProp(uploadAPIOptions, 'folderId') || rootFolderId;
const fileId = getProp(uploadAPIOptions, 'fileId');
const itemFolderId = getTypedFolderId(folderId);
const itemFileId = fileId ? getTypedFileId(fileId) : null;
return new API({
...this.getBaseAPIOptions(),
id: itemFileId || itemFolderId,
...uploadAPIOptions,
});
}
/**
* Return base API options from props
*
* @private
* @returns {Object}
*/
getBaseAPIOptions = (): Object => {
const {
apiHost,
clientName,
requestInterceptor,
responseInterceptor,
sharedLink,
sharedLinkPassword,
token,
uploadHost,
} = this.props;
return {
apiHost,
clientName,
requestInterceptor,
responseInterceptor,
sharedLink,
sharedLinkPassword,
token,
uploadHost,
};
};
/**
* Given an array of files, return the files that are new to the Content Uploader
*
* @param {Array<UploadFileWithAPIOptions | File>} files
*/
getNewFiles = (files: Array<UploadFileWithAPIOptions | File>): Array<UploadFileWithAPIOptions | File> => {
const { rootFolderId } = this.props;
return Array.from(files).filter(file => !this.itemIdsRef.current[getFileId(file, rootFolderId)]);
};
/**
* Given an array of files, return the files that are new to the Content Uploader
*
* @param {Array<UploadFileWithAPIOptions | File>} files
*/
getNewDataTransferItems = (
items: Array<DataTransferItem | UploadDataTransferItemWithAPIOptions>,
): Array<DataTransferItem | UploadDataTransferItemWithAPIOptions> => {
const { rootFolderId } = this.props;
return Array.from(items).filter(item => !this.itemIdsRef.current[getDataTransferItemId(item, rootFolderId)]);
};
/**
* Converts File API to upload items and adds to upload queue.
*
* @private
* @param {Array<UploadFileWithAPIOptions | UploadFile>} files - Files to be added to upload queue
* @param {Function} itemUpdateCallback - function to be invoked after items status are updated
* @param {boolean} [isRelativePathIgnored] - if true webkitRelativePath property is ignored
* @return {void}
*/
addFilesToUploadQueue = (
files: Array<UploadFileWithAPIOptions | UploadFile>,
itemUpdateCallback?: Function,
isRelativePathIgnored: boolean = false,
) => {
const { isPrepopulateFilesEnabled, onBeforeUpload, rootFolderId } = this.props;
if (!files || files.length === 0) {
return;
}
const newFiles = this.getNewFiles(files);
if (newFiles.length === 0) {
return;
}
const newItemIds = {};
newFiles.forEach(file => {
newItemIds[getFileId(file, rootFolderId)] = true;
});
clearTimeout(this.resetItemsTimeout);
const firstFile = getFile(newFiles[0]);
const newItemIdsState = { ...this.itemIdsRef.current, ...newItemIds };
this.itemIdsRef.current = newItemIdsState;
this.setState({ itemIds: newItemIdsState }, () => {
onBeforeUpload(newFiles);
if (firstFile.webkitRelativePath && !isRelativePathIgnored) {
// webkitRelativePath should be ignored when the upload destination folder is known
this.addFilesWithRelativePathToQueue(newFiles, itemUpdateCallback);
} else {
this.addFilesWithoutRelativePathToQueue(
newFiles,
isPrepopulateFilesEnabled ? this.upload : itemUpdateCallback,
);
}
});
};
/**
* Add dropped items to the upload queue
*
* @private
* @param {DataTransfer} droppedItems
* @param {Function} itemUpdateCallback
* @returns {void}
*/
addDroppedItemsToUploadQueue = (droppedItems: DataTransfer, itemUpdateCallback: Function): void => {
if (droppedItems.items) {
this.addDataTransferItemsToUploadQueue(droppedItems.items, itemUpdateCallback);
} else {
this.addFilesToUploadQueue(Array.from(droppedItems.files), itemUpdateCallback);
}
};
/**
* Add dataTransferItems to the upload queue
*
* @private
* @param {DataTransferItemList} dataTransferItems
* @param {Function} itemUpdateCallback
* @returns {void}
*/
addDataTransferItemsToUploadQueue = (
dataTransferItems: DataTransferItemList | Array<DataTransferItem | UploadDataTransferItemWithAPIOptions>,
itemUpdateCallback: Function,
): void => {
const { isFolderUploadEnabled } = this.props;
if (!dataTransferItems || dataTransferItems.length === 0) {
return;
}
const folderItems = [];
const fileItems = [];
const packageItems = [];
Array.from(dataTransferItems).forEach(item => {
const isDirectory = isDataTransferItemAFolder(item);
if (Browser.isSafari() && isDataTransferItemAPackage(item)) {
packageItems.push(item);
} else if (isDirectory && isFolderUploadEnabled) {
folderItems.push(item);
} else if (!isDirectory) {
fileItems.push(item);
}
});
this.addFileDataTransferItemsToUploadQueue(fileItems, itemUpdateCallback);
this.addPackageDataTransferItemsToUploadQueue(packageItems, itemUpdateCallback);
this.addFolderDataTransferItemsToUploadQueue(folderItems, itemUpdateCallback);
};
/**
* Add dataTransferItem of file type to the upload queue
*
* @private
* @param {Array<DataTransferItem | UploadDataTransferItemWithAPIOptions>} dataTransferItems
* @param {Function} itemUpdateCallback
* @returns {Promise<void>}
*/
addFileDataTransferItemsToUploadQueue = async (
dataTransferItems: Array<DataTransferItem | UploadDataTransferItemWithAPIOptions>,
itemUpdateCallback: Function,
): Promise<void> => {
const files = await Promise.all(dataTransferItems.map(item => getFileFromDataTransferItem(item)));
this.addFilesToUploadQueue(
files.filter(file => file),
itemUpdateCallback,
);
};
/**
* Add dataTransferItem of package type to the upload queue
*
* @private
* @param {Array<DataTransferItem | UploadDataTransferItemWithAPIOptions>} dataTransferItems
* @param {Function} itemUpdateCallback
* @returns {void}
*/
addPackageDataTransferItemsToUploadQueue = (
dataTransferItems: Array<DataTransferItem | UploadDataTransferItemWithAPIOptions>,
itemUpdateCallback: Function,
): void => {
const packageFiles = dataTransferItems.map(item => getPackageFileFromDataTransferItem(item));
this.addFilesToUploadQueue(
packageFiles.filter(packageFile => packageFile),
itemUpdateCallback,
);
};
/**
* Add dataTransferItem of folder type to the upload queue
*
* @private
* @param {Array<DataTransferItem | UploadDataTransferItemWithAPIOptions>} dataTransferItems
* @param {Function} itemUpdateCallback
* @returns {void}
*/
addFolderDataTransferItemsToUploadQueue = (
dataTransferItems: Array<DataTransferItem | UploadDataTransferItemWithAPIOptions>,
itemUpdateCallback: Function,
): void => {
const { rootFolderId } = this.props;
if (dataTransferItems.length === 0) {
return;
}
const newItems = this.getNewDataTransferItems(dataTransferItems);
newItems.forEach(item => {
this.itemIdsRef.current[getDataTransferItemId(item, rootFolderId)] = true;
});
if (newItems.length === 0) {
return;
}
const fileAPIOptions = getDataTransferItemAPIOptions(newItems[0]);
const { folderId = rootFolderId } = fileAPIOptions;
const folderUploads = newItems.map(item => {
const folderUpload = this.getFolderUploadAPI(folderId);
folderUpload.buildFolderTreeFromDataTransferItem(item);
return {
api: folderUpload,
extension: '',
isFolder: true,
name: folderUpload.folder.name,
options: fileAPIOptions,
progress: 0,
size: 1,
status: STATUS_PENDING,
};
});
this.addToQueue(folderUploads, itemUpdateCallback);
};
/**
* Converts File API to upload items and adds to upload queue for files with webkitRelativePath.
*
* @private
* @param {Array<UploadFileWithAPIOptions | File>} files - Files to be added to upload queue
* @param {Function} itemUpdateCallback - function to be invoked after items status are updated
* @return {void}
*/
addFilesWithRelativePathToQueue(files: Array<UploadFileWithAPIOptions | File>, itemUpdateCallback: Function) {
if (files.length === 0) {
return;
}
const { rootFolderId } = this.props;
const fileAPIOptions = getFileAPIOptions(files[0]);
const { folderId = rootFolderId } = fileAPIOptions;
const folderUpload = this.getFolderUploadAPI(folderId);
// Only 1 folder tree can be built with files having webkitRelativePath properties
folderUpload.buildFolderTreeFromWebkitRelativePath(files);
this.addFolderToUploadQueue(folderUpload, itemUpdateCallback, fileAPIOptions);
}
/**
* Get folder upload API instance
*
* @private
* @param {string} folderId
* @return {FolderUpload}
*/
getFolderUploadAPI = (folderId: string): FolderUpload => {
const uploadBaseAPIOptions = this.getBaseAPIOptions();
return new FolderUpload(this.addFilesToUploadQueue, folderId, this.addToQueue, uploadBaseAPIOptions);
};
/**
* Add folder to upload queue
*
* @private
* @param {FolderUpload} folderUpload
* @param {Function} itemUpdateCallback
* @param {Object} apiOptions
* @return {void}
*/
addFolderToUploadQueue = (folderUpload: FolderUpload, itemUpdateCallback: Function, apiOptions: Object): void => {
this.addToQueue(
[
// $FlowFixMe no file property
{
api: folderUpload,
extension: '',
isFolder: true,
name: folderUpload.folder.name,
options: apiOptions,
progress: 0,
size: 1,
status: STATUS_PENDING,
},
],
itemUpdateCallback,
);
};
/**
* Converts File API to upload items and adds to upload queue for files with webkitRelativePath missing or ignored.
*
* @private
* @param {Array<UploadFileWithAPIOptions | File>} files - Files to be added to upload queue
* @param {Function} itemUpdateCallback - function to be invoked after items status are updated
* @return {void}
*/
addFilesWithoutRelativePathToQueue = (
files: Array<UploadFileWithAPIOptions | File>,
itemUpdateCallback: Function,
) => {
const { rootFolderId } = this.props;
// Convert files from the file API to upload items
const newItems = files.map(file => {
const uploadFile = getFile(file);
const uploadAPIOptions = getFileAPIOptions(file);
const { name, size } = uploadFile;
// Extract extension or use empty string if file has no extension
let extension = name.substr(name.lastIndexOf('.') + 1);
if (extension.length === name.length) {
extension = '';
}
const api = this.getUploadAPI(uploadFile, uploadAPIOptions);
const uploadItem: UploadItem = {
api,
extension,
file: uploadFile,
name,
progress: 0,
size,
status: STATUS_PENDING,
};
if (uploadAPIOptions) {
uploadItem.options = uploadAPIOptions;
}
this.itemIdsRef.current[getFileId(uploadItem, rootFolderId)] = true;
return uploadItem;
});
if (newItems.length === 0) {
return;
}
this.setState({
itemIds: this.itemIdsRef.current,
});
this.addToQueue(newItems, itemUpdateCallback);
};
/**
* Add new items to the upload queue
*
* @private
* @param {Array<UploadFileWithAPIOptions | File>} newItems - Files to be added to upload queue
* @param {Function} itemUpdateCallback - function to be invoked after items status are updated
* @return {void}
*/
addToQueue = (newItems: UploadItem[], itemUpdateCallback: Function) => {
const { fileLimit, useUploadsManager } = this.props;
const { isUploadsManagerExpanded } = this.state;
let updatedItems = [];
const prevItemsNum = this.itemsRef.current.length;
const totalNumOfItems = prevItemsNum + newItems.length;
// Don't add more than fileLimit # of items
if (totalNumOfItems > fileLimit) {
updatedItems = this.itemsRef.current.concat(newItems.slice(0, fileLimit - prevItemsNum));
this.setState({
errorCode: ERROR_CODE_UPLOAD_FILE_LIMIT,
});
} else {
updatedItems = this.itemsRef.current.concat(newItems);
this.setState({ errorCode: '' });
// If the number of items being uploaded passes the threshold, expand the upload manager
if (
prevItemsNum < EXPAND_UPLOADS_MANAGER_ITEMS_NUM_THRESHOLD &&
totalNumOfItems >= EXPAND_UPLOADS_MANAGER_ITEMS_NUM_THRESHOLD &&
useUploadsManager &&
!isUploadsManagerExpanded
) {
this.isAutoExpanded = true;
this.expandUploadsManager();
}
}
this.updateViewAndCollection(updatedItems, () => {
if (itemUpdateCallback) {
itemUpdateCallback();
}
const { view } = this.state;
// Automatically start upload if other files are being uploaded
if (view === VIEW_UPLOAD_IN_PROGRESS) {
this.upload();
}
});
};
/**
* Returns a new API instance for the given file.
*
* @private
* @param {File} file - File to get a new API instance for
* @param {UploadItemAPIOptions} [uploadAPIOptions]
* @return {UploadAPI} - Instance of Upload API
*/
getUploadAPI(file: File, uploadAPIOptions?: UploadItemAPIOptions) {
const { chunked, isResumableUploadsEnabled, isUploadFallbackLogicEnabled } = this.props;
const { size } = file;
const factory = this.createAPIFactory(uploadAPIOptions);
if (chunked && size > CHUNKED_UPLOAD_MIN_SIZE_BYTES) {
if (isMultiputSupported()) {
const chunkedUploadAPI = factory.getChunkedUploadAPI();
if (isResumableUploadsEnabled) {
chunkedUploadAPI.isResumableUploadsEnabled = true;
}
if (isUploadFallbackLogicEnabled) {
chunkedUploadAPI.isUploadFallbackLogicEnabled = true;
}
return chunkedUploadAPI;
}
/* eslint-disable no-console */
console.warn(
'Chunked uploading is enabled, but not supported by your browser. You may need to enable HTTPS.',
);
/* eslint-enable no-console */
}
const plainUploadAPI = factory.getPlainUploadAPI();
if (isUploadFallbackLogicEnabled) {
plainUploadAPI.isUploadFallbackLogicEnabled = true;
}
return plainUploadAPI;
}
/**
* Removes an item from the upload queue. Cancels upload if in progress.
*
* @param {UploadItem} item - Item to remove
* @return {void}
*/
removeFileFromUploadQueue = (item: UploadItem) => {
const { onCancel, useUploadsManager } = this.props;
// Clear any error errorCode in footer
this.setState({ errorCode: '' });
const { api } = item;
api.cancel();
const itemIndex = this.itemsRef.current.indexOf(item);
const updatedItems = this.itemsRef.current
.slice(0, itemIndex)
.concat(this.itemsRef.current.slice(itemIndex + 1));
onCancel([item]);
this.updateViewAndCollection(updatedItems, () => {
// Minimize uploads manager if there are no more items
if (useUploadsManager && !updatedItems.length) {
this.minimizeUploadsManager();
}
const { view } = this.state;
if (view === VIEW_UPLOAD_IN_PROGRESS) {
this.upload();
}
});
};
/**
* Aborts uploads in progress and clears upload list.
*
* @private
* @return {void}
*/
cancel = () => {
this.itemsRef.current.forEach(uploadItem => {
const { api, status } = uploadItem;
if (status === STATUS_IN_PROGRESS) {
api.cancel();
}
});
// Reset upload collection
this.updateViewAndCollection([]);
};
/**
* Uploads all items in the upload collection.
*
* @private
* @return {void}
*/
upload = () => {
this.itemsRef.current.forEach(uploadItem => {
if (uploadItem.status === STATUS_PENDING) {
this.uploadFile(uploadItem);
}
});
};
/**
* Helper to upload a single file.
*
* @param {UploadItem} item - Upload item object
* @return {void}
*/
uploadFile(item: UploadItem) {
const { overwrite, rootFolderId } = this.props;
const { api, file, options } = item;
const numItemsUploading = this.itemsRef.current.filter(item_t => item_t.status === STATUS_IN_PROGRESS).length;
if (numItemsUploading >= UPLOAD_CONCURRENCY) {
return;
}
const uploadOptions: Object = {
file,
folderId: options && options.folderId ? options.folderId : rootFolderId,
errorCallback: error => this.handleUploadError(item, error),
progressCallback: event => this.handleUploadProgress(item, event),
successCallback: entries => this.handleUploadSuccess(item, entries),
overwrite,
fileId: options && options.fileId ? options.fileId : null,
};
item.status = STATUS_IN_PROGRESS;
const updatedItems = [...this.itemsRef.current];
updatedItems[this.itemsRef.current.indexOf(item)] = item;
api.upload(uploadOptions);
this.updateViewAndCollection(updatedItems);
}
/**
* Helper to resume uploading a single file.
*
* @param {UploadItem} item - Upload item object
* @return {void}
*/
resumeFile(item: UploadItem) {
const { onResume, overwrite, rootFolderId } = this.props;
const { api, file, options } = item;
const numItemsUploading = this.itemsRef.current.filter(item_t => item_t.status === STATUS_IN_PROGRESS).length;
if (numItemsUploading >= UPLOAD_CONCURRENCY) {
return;
}
const resumeOptions: Object = {
file,
folderId: options && options.folderId ? options.folderId : rootFolderId,
errorCallback: error => this.handleUploadError(item, error),
progressCallback: event => this.handleUploadProgress(item, event),
successCallback: entries => this.handleUploadSuccess(item, entries),
overwrite,
sessionId: api && api.sessionId ? api.sessionId : null,
fileId: options && options.fileId ? options.fileId : null,
};
item.status = STATUS_IN_PROGRESS;
delete item.error;
const updatedItems = [...this.itemsRef.current];
updatedItems[this.itemsRef.current.indexOf(item)] = item;
onResume(item);
api.resume(resumeOptions);
this.updateViewAndCollection(updatedItems);
}
/**
* Helper to reset a file. Cancels any current upload and resets progress.
*
* @param {UploadItem} item - Upload item to reset
* @return {void}
*/
resetFile(item: UploadItem) {
const { api, file, options } = item;
if (api && typeof api.cancel === 'function') {
api.cancel();
}
// Reset API, progress & status
item.api = this.getUploadAPI(file, options);
item.progress = 0;
item.status = STATUS_PENDING;
delete item.error;
const updatedItems = [...this.itemsRef.current];
updatedItems[this.itemsRef.current.indexOf(item)] = item;
this.updateViewAndCollection(updatedItems);
}
/**
* Handles a successful upload.
*
* @private
* @param {UploadItem} item - Upload item corresponding to success event
* @param {BoxItem[]} entries - Successfully uploaded Box File objects
* @return {void}
*/
handleUploadSuccess = (item: UploadItem, entries?: BoxItem[]) => {
const { onUpload, useUploadsManager } = this.props;
item.progress = 100;
if (!item.error) {
item.status = STATUS_COMPLETE;
}
// Cache Box File object of successfully uploaded item
if (entries && entries.length === 1) {
const [boxFile] = entries;
item.boxFile = boxFile;
}
const updatedItems = [...this.itemsRef.current];
updatedItems[this.itemsRef.current.indexOf(item)] = item;
// Broadcast that a file has been uploaded
if (useUploadsManager) {
onUpload(item);
this.checkClearUploadItems();
} else {
onUpload(item.boxFile);
}
this.updateViewAndCollection(updatedItems, () => {
const { view } = this.state;
if (view === VIEW_UPLOAD_IN_PROGRESS) {
this.upload();
}
});
};
resetUploadManagerExpandState = () => {
this.isAutoExpanded = false;
this.setState({
isUploadsManagerExpanded: false,
});
};
/**
* Updates view and internal upload collection with provided items.
*
* @private
* @param {UploadItem[]} item - Items to update collection with
* @param {Function} callback
* @return {void}
*/
updateViewAndCollection(items: UploadItem[], callback?: () => void) {
const {
isPartialUploadEnabled,
isResumableUploadsEnabled,
onComplete,
useUploadsManager,
}: ContentUploaderProps = this.props;
const someUploadIsInProgress = items.some(uploadItem => uploadItem.status !== STATUS_COMPLETE);
const someUploadHasFailed = items.some(uploadItem => uploadItem.status === STATUS_ERROR);
const allItemsArePending = !items.some(uploadItem => uploadItem.status !== STATUS_PENDING);
const noFileIsPendingOrInProgress = items.every(
uploadItem => uploadItem.status !== STATUS_PENDING && uploadItem.status !== STATUS_IN_PROGRESS,
);
const areAllItemsFinished = items.every(
uploadItem => uploadItem.status === STATUS_COMPLETE || uploadItem.status === STATUS_ERROR,
);
const uploadItemsStatus = isResumableUploadsEnabled ? areAllItemsFinished : noFileIsPendingOrInProgress;
let view = '';
if ((items && items.length === 0) || allItemsArePending) {
view = VIEW_UPLOAD_EMPTY;
} else if (isPartialUploadEnabled && areAllItemsFinished) {
const filesToBeUploaded = items.filter(item => item.status === STATUS_COMPLETE);
view = VIEW_UPLOAD_SUCCESS;
if (!useUploadsManager) {
onComplete(cloneDeep(filesToBeUploaded.map(item => item.boxFile)));
// Reset item collection after successful upload
items = [];
}
} else if (someUploadHasFailed && useUploadsManager) {
view = VIEW_ERROR;
} else if (someUploadIsInProgress) {
view = VIEW_UPLOAD_IN_PROGRESS;
} else {
view = VIEW_UPLOAD_SUCCESS;
if (!useUploadsManager) {
onComplete(cloneDeep(items.map(item => item.boxFile)));
// Reset item collection after successful upload
items = [];
}
}
if (uploadItemsStatus && useUploadsManager) {
if (this.isAutoExpanded) {
this.resetUploadManagerExpandState();
} // Else manually expanded so don't close
onComplete(items);
}
const state: Partial<State> = {
items,
view,
};
if (items.length === 0) {
this.itemIdsRef.current = {};
state.itemIds = {};
state.errorCode = '';
}
this.itemsRef.current = items;
this.setState(state as Pick<State, keyof State>, callback);