-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFilesUploader.tsx
More file actions
441 lines (401 loc) · 13.2 KB
/
FilesUploader.tsx
File metadata and controls
441 lines (401 loc) · 13.2 KB
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
import React, { useState, useRef, useEffect } from "react";
import axios from "axios";
import {
Button,
Divider,
Form,
Icon,
Modal,
ModalProps,
Checkbox,
} from "semantic-ui-react";
import ProgressBar from "../ProgressBar";
import useGlobalError from "../error/ErrorHooks";
import FileUploader from "../FileUploader";
import { z } from "zod";
import api from "../../api";
import { useTypedSelector } from "../../state/hooks";
import tusUpload from "../../utils/tusUpload";
import { calculateVideoLength } from "../../utils/assetHelpers";
import { supportTicketAttachmentAllowedTypes } from "../../utils/supportHelpers";
type _AddProps = {
mode: "add";
directory: string;
projectHasDefaultLicense?: boolean;
};
type _ReplaceProps = {
mode: "replace";
fileID: string;
};
type FilesUploaderProps = ModalProps & {
show: boolean;
onClose: () => void;
projectID: string;
uploadPath: string;
onFinishedUpload: () => void;
} & (_AddProps | _ReplaceProps);
const MAX_ADD_FILES = 20;
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
/**
* Modal interface to upload Project Files to a Project.
*/
const FilesUploader: React.FC<FilesUploaderProps> = ({
show,
onClose,
directory,
projectID,
uploadPath,
projectHasDefaultLicense = false,
onFinishedUpload,
mode = "add",
fileID,
...props
}) => {
// Global State & Error Handling
const { handleGlobalError } = useGlobalError();
const user = useTypedSelector((state) => state.user);
const org = useTypedSelector((state) => state.org);
// State
const [loading, setLoading] = useState<boolean>(false);
const [urlDisabled, setUrlDisabled] = useState<boolean>(false);
const [files, setFiles] = useState<File[]>([]);
const [fileDisabled, setFileDisabled] = useState<boolean>(false);
const [validURL, setValidURL] = useState<boolean>(false);
const [urlInput, setUrlInput] = useState<string>("");
const [overwriteName, setOverwriteName] = useState<boolean>(true);
const [percentUploaded, setPercentUploaded] = useState<number>(0);
const [finishedFileTransfer, setFinishedFileTransfer] =
useState<boolean>(false);
const abortControllerRef = useRef<AbortController>(new AbortController());
const URL_SCHEMA = z.string().trim().url();
const dirText = directory ? directory : "root";
// Reset URL input when modal is closed/opened
useEffect(() => {
if (show) {
setUrlInput("");
setUrlDisabled(false);
setFileDisabled(false);
}
}, [show]);
// Disable file upload if URL is entered
useEffect(() => {
if (urlInput) {
setFileDisabled(true);
} else {
setFileDisabled(false);
}
}, [urlInput]);
// Disable URL input if files are selected
useEffect(() => {
if (files.length > 0) {
setUrlDisabled(true);
} else {
setUrlDisabled(false);
}
}, [files]);
useEffect(() => {
if (!urlInput) return;
const result = URL_SCHEMA.safeParse(urlInput);
if (result.success) {
setValidURL(true);
} else {
setValidURL(false);
}
}, [urlInput]);
/**
* Handles upload to the server after files are collected using the FileUploader.
*
* @param {File[]} files - Files selected for upload by the user.
*/
async function handleUpload(files: File[]) {
try {
if (!files || files.length === 0) {
return;
}
setLoading(true);
const formData = new FormData();
formData.append("parentID", uploadPath);
// If uploader exists in authors collection, add them as an author to the file
// if (mode === "add" && user) {
// const authorsRes = await api.getAuthors({ query: user.email });
// if (authorsRes.data.err) {
// console.error(authorsRes.data.errMsg);
// }
// if (!authorsRes.data.authors) {
// console.error("An error occurred while getting authors");
// }
// if (authorsRes.data.authors) {
// const foundAuthor = authorsRes.data.authors.find(
// (author) => author.email === user.email
// );
// if (foundAuthor && foundAuthor._id) {
// formData.append("authors", [foundAuthor._id].toString());
// }
// }
// }
if (mode === "replace") {
formData.append("overwriteName", overwriteName.toString()); // Only used for replace mode
}
const videoFiles = files.filter((file) => file.type.startsWith("video"));
const standardFiles = files.filter(
(file) => !file.type.startsWith("video")
);
const videoCheckPromises = videoFiles.map((file) => {
return calculateVideoLength(file);
});
const videoCheckResults = await Promise.allSettled(videoCheckPromises);
videoCheckResults.forEach((result) => {
if (result.status === "rejected" || !result.value) {
throw new Error("Failed to calculate video length");
}
if (result.value > org.videoLengthLimit * 60) {
throw new Error(
`Video length exceeds the organization's limit of ${org.videoLengthLimit} minutes.`
);
}
});
// Handle video files with Cloudflare Stream
const videoData: { videoID: string; videoName: string }[] = [];
const videoPromises = videoFiles.map((file) => {
return (async () => {
const uploadId = await tusUpload(
file,
api.cloudflareStreamUploadURL,
(progress) => {
setPercentUploaded(progress / videoFiles.length);
if (
progress / videoFiles.length === 100 &&
standardFiles.length === 0
) {
// If this is the last file to upload, set finished to true
setFinishedFileTransfer(true);
}
},
abortControllerRef.current.signal,
{
maxDurationSeconds: org.videoLengthLimit * 60,
}
);
if (!uploadId) throw new Error("Failed to upload video file");
videoData.push({ videoID: uploadId, videoName: file.name });
})();
});
await Promise.all(videoPromises);
if (videoData.length > 0) {
formData.append("videoData", JSON.stringify(videoData));
}
// Handle non-video files
standardFiles.forEach((file) => {
formData.append("files", file);
});
const opts = {
onUploadProgress: (progressEvent: any) => {
if (
typeof progressEvent.loaded === "number" &&
typeof progressEvent.total === "number"
) {
const progress = (progressEvent.loaded / progressEvent.total) * 100;
setPercentUploaded(progress);
if (progress === 100) {
setFinishedFileTransfer(true);
}
}
},
signal: abortControllerRef.current.signal,
};
const uploadRes =
mode === "add"
? await api.addProjectFile(projectID, formData, opts)
: await api.replaceProjectFile_FormData(
projectID,
fileID,
formData,
opts
);
if (uploadRes.data.err) {
throw new Error(uploadRes.data.errMsg);
}
cleanupFileUploader();
} catch (e: any) {
if (e.message === "canceled") return; // Noop if canceled
setLoading(false);
handleGlobalError(e);
}
}
async function handleURLUpload() {
try {
setLoading(true);
await URL_SCHEMA.parseAsync(urlInput); // Will throw if invalid URL
const formData = new FormData();
formData.append("parentID", uploadPath);
formData.append("fileURL", urlInput);
formData.append("isURL", "true");
formData.append("overwriteName", overwriteName.toString());
const url =
mode === "add"
? `/project/${projectID}/files`
: `/project/${projectID}/files/${fileID}`;
const signal = abortControllerRef.current.signal;
const res =
mode === "add"
? await api.addProjectFile(projectID, formData, { signal })
: await axios.put(url, formData, { signal });
if (res.data.err) {
throw new Error(res.data.errMsg);
}
cleanupFileUploader();
} catch (err) {
handleGlobalError(err);
} finally {
setLoading(false);
}
}
async function handleCancelUpload() {
try {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
abortControllerRef.current = new AbortController(); // Reset abort controller
cleanupFileUploader();
} catch (err) {
handleGlobalError(err);
}
}
function cleanupFileUploader() {
setLoading(false);
setPercentUploaded(0);
setFinishedFileTransfer(false);
onFinishedUpload();
}
async function saveFilesToState(filesToSet: FileList) {
setFiles([...Array.from(filesToSet)]);
}
return (
<Modal size="large" open={show} onClose={onClose} {...props}>
<Modal.Header>
{mode === "add" ? "Upload Files" : "Replace Files"}
</Modal.Header>
<Modal.Content>
{!loading ? (
<div>
{mode === "replace" && (
<div className="flex flex-col justify-center items-center">
<p className="mb-2 text-center">
<strong>Warning:</strong> Replacing an existing file with a
new file or URL will remove and overwrite the old file. This
action cannot be undone!
</p>
<Checkbox
label="Overwrite file name?"
toggle
className="mb-4"
checked={overwriteName}
onChange={() => setOverwriteName(!overwriteName)}
/>
</div>
)}
{mode === "add" && (
<p>
Files will be uploaded to the <strong>{dirText}</strong> folder.
Up to <strong>{MAX_ADD_FILES} files</strong> can be uploaded at
once, with a maximum of <strong>100 MB</strong> each. Your
organization has a video length limit of{" "}
<strong>{org.videoLengthLimit}</strong> minutes.
</p>
)}
<FileUploader
className="mt-2"
fileTypes={supportTicketAttachmentAllowedTypes}
maxFiles={mode === "add" ? MAX_ADD_FILES : 1}
maxFileSize={MAX_FILE_SIZE}
onUpload={saveFilesToState}
disabled={fileDisabled}
minFiles={1}
/>
<Divider horizontal>Or</Divider>
<div>
<Form onSubmit={(e) => e.preventDefault()}>
<div className="">
<label className="form-field-label">
Externally Hosted Asset URL{" "}
<span className="italic">
(this will not download the asset to Conductor)
</span>
</label>
<Form.Input
type="url"
value={urlInput}
onChange={(e) => setUrlInput(e.target.value)}
placeholder="https://example.com/my-asset.png"
disabled={urlDisabled}
error={!validURL && urlInput ? true : false}
/>
{!validURL && urlInput && (
<p className="text-red-400 -mt-3">
Please enter a valid URL.
</p>
)}
</div>
</Form>
</div>
{projectHasDefaultLicense && (
<p className="mt-4 text-center italic">
This project has a default license set for assets. You can
change the license information for this file after uploading as
needed.
</p>
)}
</div>
) : (
<ProgressBar
id="upload-progress"
label={
<label
htmlFor="upload-progress"
className="block text-center mb-4 font-semibold"
>
{!finishedFileTransfer ? "Uploading..." : "Finishing..."}
</label>
}
value={percentUploaded}
max={100}
/>
)}
</Modal.Content>
<Modal.Actions>
{!loading ? (
<Button onClick={onClose}>Cancel</Button>
) : (
<Button onClick={handleCancelUpload}>Cancel Upload</Button>
)}
{urlInput && !urlDisabled && (
<Button
color="green"
icon
labelPosition="left"
disabled={!validURL}
loading={loading}
onClick={handleURLUpload}
>
<Icon name="save" />
Save URL
</Button>
)}
{files.length > 0 && !fileDisabled && (
<Button
color="green"
icon
labelPosition="left"
loading={loading}
onClick={() => handleUpload(files)}
disabled={fileDisabled || loading}
>
<Icon name="upload" />
Upload Files
</Button>
)}
</Modal.Actions>
</Modal>
);
};
export default FilesUploader;