import { useState } from "react"; import * as tus from "tus-js-client"; interface UploadResult { url: string; fileId: string; // resource: any; } export function useTusUpload() { const [progress, setProgress] = useState(0); const [isUploading, setIsUploading] = useState(false); const [uploadError, setUploadError] = useState(null); const getFileId = (url: string) => { const parts = url.split("/"); // Find the index of the 'upload' segment const uploadIndex = parts.findIndex((part) => part === "upload"); if (uploadIndex === -1 || uploadIndex + 4 >= parts.length) { throw new Error("Invalid upload URL format"); } // Get the date parts and file ID (4 segments after 'upload') return parts.slice(uploadIndex + 1, uploadIndex + 5).join("/"); }; const handleFileUpload = async ( file: File, onSuccess: (result: UploadResult) => void, onError: (error: Error) => void ) => { setIsUploading(true); setProgress(0); setUploadError(null); const upload = new tus.Upload(file, { endpoint: "http://localhost:3000/upload", retryDelays: [0, 1000, 3000, 5000], metadata: { filename: file.name, filetype: file.type, }, onProgress: (bytesUploaded, bytesTotal) => { const uploadProgress = ( (bytesUploaded / bytesTotal) * 100 ).toFixed(2); setProgress(Number(uploadProgress)); }, onSuccess: async () => { try { if (upload.url) { const fileId = getFileId(upload.url); // const resource = await pollResourceStatus(fileId); setIsUploading(false); setProgress(100); onSuccess({ url: upload.url, fileId, // resource, }); } } catch (error) { const err = error instanceof Error ? error : new Error("Unknown error"); setIsUploading(false); setUploadError(err.message); onError(err); } }, onError: (error) => { setIsUploading(false); setUploadError(error.message); onError(error); }, }); upload.start(); }; return { progress, isUploading, uploadError, handleFileUpload, }; }