-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseTusFileUpload.ts
More file actions
352 lines (299 loc) · 11.9 KB
/
useTusFileUpload.ts
File metadata and controls
352 lines (299 loc) · 11.9 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
'use client';
import { useState, useRef, useCallback } from 'react';
import * as tus from 'tus-js-client';
import { TUS_CLIENT_CONFIG } from '@/lib/upload/config/tus-upload-config';
import { QueuedFile } from '@/lib/upload/types/upload-types';
import { generateId, getPartCount, findOptimalBatch, formatFileSize, FileWithParts } from '@/lib/upload/utils/tus-file-utils';
export const useTusFileUpload = () => {
// SINGLE SOURCE OF TRUTH - Only one state for files
const [fileQueue, setFileQueue] = useState<QueuedFile[]>([]);
const [uploading, setUploading] = useState(false);
const [message, setMessage] = useState('');
// Simple refs for upload management
const activeUploadsRef = useRef<Map<string, tus.Upload>>(new Map());
const fileQueueRef = useRef<QueuedFile[]>([]);
// Keep ref in sync with state
fileQueueRef.current = fileQueue;
// UNIFIED STATUS UPDATE - Simplified with single responsibility
const updateFileStatus = useCallback((fileId: string, updates: Partial<QueuedFile>) => {
setFileQueue(prev => prev.map(file =>
file.id === fileId ? { ...file, ...updates } : file
));
}, []);
// Handle file selection
const handleFileSelection = useCallback((files: FileList | null) => {
if (!files) return;
let fileArray = Array.from(files);
// Filter out duplicates based on filename and size
const uniqueFiles = fileArray.filter(newFile => {
return !fileQueue.some(existingFile =>
existingFile.name === newFile.name && existingFile.size === newFile.size
);
});
// Show message if duplicates were filtered out
const duplicateCount = fileArray.length - uniqueFiles.length;
if (duplicateCount > 0) {
setMessage(`${duplicateCount} duplicate file${duplicateCount > 1 ? 's' : ''} skipped (same name and size).`);
}
// If no unique files remain, return early
if (uniqueFiles.length === 0) {
return;
}
// Check if adding these files would exceed the max selection limit
const currentFileCount = fileQueue.length;
const totalFiles = currentFileCount + uniqueFiles.length;
if (totalFiles > TUS_CLIENT_CONFIG.maxFileSelection) {
const remainingSlots = TUS_CLIENT_CONFIG.maxFileSelection - currentFileCount;
if (remainingSlots <= 0) {
setMessage(`Maximum ${TUS_CLIENT_CONFIG.maxFileSelection} files allowed. Remove some files first.`);
return;
}
const previousMessage = duplicateCount > 0 ? `${duplicateCount} duplicates skipped. ` : '';
setMessage(`${previousMessage}Only ${remainingSlots} more files can be added (${TUS_CLIENT_CONFIG.maxFileSelection} max).`);
fileArray = uniqueFiles.slice(0, remainingSlots);
} else {
fileArray = uniqueFiles;
if (duplicateCount === 0) {
setMessage('');
}
}
const queuedFiles: QueuedFile[] = fileArray.map(file => ({
id: generateId(),
file: file,
status: 'pending' as const,
progress: 0,
name: file.name,
size: file.size,
type: file.type,
uploadedBytes: 0
}));
// Append new files to existing queue instead of replacing
setFileQueue(prev => [...prev, ...queuedFiles]);
}, [fileQueue]);
// COMPLETE FILE UPLOAD - Upload entire file as single unit
const uploadFileComplete = useCallback((queuedFile: QueuedFile): Promise<void> => {
return new Promise((resolve, reject) => {
const file = queuedFile.file;
console.log(`Uploading complete file: ${file.name} (${formatFileSize(file.size)})`);
const upload = new tus.Upload(file, {
endpoint: TUS_CLIENT_CONFIG.endpoint,
chunkSize: TUS_CLIENT_CONFIG.chunkSize,
retryDelays: TUS_CLIENT_CONFIG.retryDelays,
metadata: {
filename: file.name,
filetype: file.type,
// No multipart metadata for complete file uploads
withFilename: TUS_CLIENT_CONFIG.withFilename,
onDuplicate: TUS_CLIENT_CONFIG.onDuplicate,
destinationPath: TUS_CLIENT_CONFIG.destinationPath
},
onError: reject,
onProgress: (bytesUploaded, bytesTotal) => {
const progress = (bytesUploaded / bytesTotal) * 100;
updateFileStatus(queuedFile.id, {
progress: Math.min(progress, 99),
uploadedBytes: bytesUploaded
});
},
onSuccess: () => {
updateFileStatus(queuedFile.id, { status: 'completed', progress: 100 });
resolve();
},
});
// Store upload reference for potential cancellation
activeUploadsRef.current.set(queuedFile.id, upload);
upload.start();
});
}, [updateFileStatus]);
// MULTIPART UPLOAD - Split file into parts and upload in parallel
const uploadFileMultipart = useCallback((queuedFile: QueuedFile): Promise<void> => {
return new Promise((resolve, reject) => {
const file = queuedFile.file;
const totalParts = getPartCount(file.size);
const multipartId = generateId();
const partSize = Math.ceil(file.size / totalParts);
console.log(`Uploading ${file.name} (${formatFileSize(file.size)}) in ${totalParts} parts`);
// Track bytes uploaded per part for accurate progress
const partBytesUploaded = new Array(totalParts).fill(0);
let completedParts = 0;
let hasError = false;
// Progress update function
const updateProgress = () => {
const totalBytesUploaded = partBytesUploaded.reduce((sum, bytes) => sum + bytes, 0);
const progress = (totalBytesUploaded / file.size) * 100;
updateFileStatus(queuedFile.id, {
progress: Math.min(progress, 99),
uploadedBytes: totalBytesUploaded
});
};
// Upload all parts in parallel
const partUploads = Array.from({ length: totalParts }, (_, i) =>
uploadPart(queuedFile, i, partSize, multipartId, totalParts, (bytesUploaded) => {
partBytesUploaded[i] = bytesUploaded;
updateProgress();
})
);
// Handle part completions
partUploads.forEach((uploadPromise, index) => {
uploadPromise
.then(() => {
if (hasError) return;
completedParts++;
// Check if all parts completed
if (completedParts === totalParts) {
updateFileStatus(queuedFile.id, { status: 'completed', progress: 100 });
resolve();
}
})
.catch((error) => {
if (!hasError) {
hasError = true;
reject(error);
}
});
});
});
}, [updateFileStatus]);
// Start upload process with dynamic stream-based batching
const startUpload = useCallback(() => {
if (!uploading && fileQueue.length > 0) {
processQueueDynamic();
}
}, [uploading, fileQueue]);
// Process the queue with dynamic stream-based batching and continuous monitoring
const processQueueDynamic = useCallback(async () => {
setUploading(true);
while (true) {
// Continuously check for pending files (including newly added ones)
const remainingFiles = fileQueueRef.current
.filter(f => f.status === 'pending')
.map(file => ({
id: file.id,
name: file.name,
size: file.size,
parts: getPartCount(file.size)
}));
// If no pending files, exit the loop
if (remainingFiles.length === 0) {
break;
}
// Find optimal batch using knapsack algorithm
const batch = findOptimalBatch(remainingFiles, TUS_CLIENT_CONFIG.maxStreamCount);
if (batch.length === 0) {
// If no valid batch found, take the first file
batch.push(remainingFiles[0]);
}
const totalStreams = batch.reduce((sum, file) => sum + file.parts, 0);
setMessage(`Uploading ${batch.length} files (${totalStreams} streams)...`);
// Start all files in batch simultaneously
const batchPromises = batch.map(async (fileInfo) => {
const queuedFile = fileQueueRef.current.find(f => f.id === fileInfo.id);
if (!queuedFile || queuedFile.status !== 'pending') {
return; // Skip if file was removed or status changed
}
try {
updateFileStatus(queuedFile.id, { status: 'uploading', progress: 0 });
if (fileInfo.parts === 1) {
// Single part - upload complete file
await uploadFileComplete(queuedFile);
} else {
// Multiple parts - upload with multipart logic
await uploadFileMultipart(queuedFile);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
updateFileStatus(queuedFile.id, {
status: 'error',
progress: 0,
error: errorMessage
});
}
});
// Wait for all files in batch to complete
await Promise.allSettled(batchPromises);
// Small delay to prevent tight loop and allow UI updates
await new Promise(resolve => setTimeout(resolve, 100));
}
setUploading(false);
setMessage('All files processed.');
}, [updateFileStatus, uploadFileComplete, uploadFileMultipart]);
// SIMPLIFIED PART UPLOAD - Clean, focused responsibility
const uploadPart = useCallback((
queuedFile: QueuedFile,
partIndex: number,
partSize: number,
multipartId: string,
totalParts: number,
onProgressUpdate: (bytesUploaded: number) => void
): Promise<void> => {
return new Promise((resolve, reject) => {
const file = queuedFile.file;
const start = partIndex * partSize;
const end = Math.min(start + partSize, file.size);
const partBlob = file.slice(start, end);
const partNumber = partIndex + 1;
const upload = new tus.Upload(partBlob, {
endpoint: TUS_CLIENT_CONFIG.endpoint,
chunkSize: TUS_CLIENT_CONFIG.chunkSize,
retryDelays: TUS_CLIENT_CONFIG.retryDelays,
metadata: {
filename: file.name,
filetype: file.type,
multipartId: multipartId,
partIndex: partNumber.toString(),
totalParts: totalParts.toString(),
originalFileSize: file.size.toString(),
withFilename: TUS_CLIENT_CONFIG.withFilename,
onDuplicate: TUS_CLIENT_CONFIG.onDuplicate,
destinationPath: TUS_CLIENT_CONFIG.destinationPath
},
onError: reject,
onProgress: (bytesUploaded, bytesTotal) => {
// Report actual bytes uploaded for this part
onProgressUpdate(bytesUploaded);
},
onSuccess: () => resolve(),
});
// Store upload reference for potential cancellation
activeUploadsRef.current.set(`${queuedFile.id}-${partIndex}`, upload);
upload.start();
});
}, []);
// Remove file from queue
const removeFile = useCallback((fileId: string) => {
// Cancel any active uploads for this file
activeUploadsRef.current.forEach((upload, key) => {
if (key.startsWith(fileId)) {
upload.abort();
activeUploadsRef.current.delete(key);
}
});
setFileQueue(prev => prev.filter(f => f.id !== fileId));
}, []);
// Clear all files
const clearQueue = useCallback(() => {
// Cancel all active uploads
activeUploadsRef.current.forEach(upload => upload.abort());
activeUploadsRef.current.clear();
setFileQueue([]);
setMessage('');
}, []);
// Clear completed and errored files
const clearCompleted = useCallback(() => {
setFileQueue(prev => prev.filter(f => f.status !== 'completed' && f.status !== 'error'));
}, []);
// Clear pending files only
const clearPending = useCallback(() => {
setFileQueue(prev => prev.filter(f => f.status !== 'pending'));
}, []);
return {
fileQueue,
uploading,
message,
handleFileSelection,
startUpload,
removeFile,
clearCompleted,
clearPending
};
};