116 lines
4.2 KiB
TypeScript
116 lines
4.2 KiB
TypeScript
import { FileService } from './file'
|
|
import { waitForUploadCompletion, isTransientCompletionError } from './upload-completion'
|
|
import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types'
|
|
import { calculateFileHash } from '@/utils/file-processing'
|
|
|
|
export const CHUNK_SIZE = 100 * 1024 * 1024
|
|
|
|
type ChunkedUploadOptions = {
|
|
expireValue: number
|
|
expireStyle: string
|
|
onFinalizing?: () => void
|
|
onHashCalculated?: (hash: string) => void
|
|
onProgress?: (progress: UploadProgress) => void
|
|
messages?: {
|
|
initFailed?: string
|
|
chunkFailed?: (index: number) => string
|
|
completeFailed?: string
|
|
}
|
|
}
|
|
|
|
type ChunkedUploadResult = ChunkUploadInitResponse | FileUploadResponse
|
|
|
|
// Keep the completion session across a manual retry after a network failure.
|
|
// The same File object is retained by the send form; no credentials are persisted.
|
|
const pendingCompletion = new WeakMap<File, { uploadId: string; expireValue: number; expireStyle: string }>()
|
|
|
|
async function finishUpload(file: File, options: ChunkedUploadOptions): Promise<ApiResponse<ChunkedUploadResult>> {
|
|
const session = pendingCompletion.get(file)!
|
|
options.onProgress?.({loaded:file.size,total:file.size,percentage:99})
|
|
options.onFinalizing?.()
|
|
try {
|
|
const response = await waitForUploadCompletion(() => FileService.completeChunkUpload(session.uploadId, {
|
|
expire_value: session.expireValue, expire_style: session.expireStyle
|
|
}))
|
|
if (response.code !== 200) throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed')
|
|
pendingCompletion.delete(file)
|
|
return response
|
|
} catch (error) {
|
|
if (!isTransientCompletionError(error)) pendingCompletion.delete(file)
|
|
throw error
|
|
}
|
|
}
|
|
|
|
const calculateCompletedBytes = (uploadedChunks: Set<number>, chunkSize: number, fileSize: number) =>
|
|
Array.from(uploadedChunks).reduce((total, index) => {
|
|
const chunkStart = index * chunkSize
|
|
const chunkEnd = Math.min((index + 1) * chunkSize, fileSize)
|
|
return total + Math.max(0, chunkEnd - chunkStart)
|
|
}, 0)
|
|
|
|
export const uploadChunkedFile = async (
|
|
file: File,
|
|
options: ChunkedUploadOptions
|
|
): Promise<ApiResponse<ChunkedUploadResult>> => {
|
|
if (pendingCompletion.has(file)) return finishUpload(file, options)
|
|
const fileHash = await calculateFileHash(file)
|
|
options.onHashCalculated?.(fileHash)
|
|
|
|
const initResponse = await FileService.initChunkUpload({
|
|
file_name: file.name,
|
|
file_size: file.size,
|
|
chunk_size: Math.min(CHUNK_SIZE, file.size),
|
|
file_hash: fileHash
|
|
})
|
|
|
|
if (initResponse.code !== 200) {
|
|
throw new Error(options.messages?.initFailed || 'Init chunk upload failed')
|
|
}
|
|
|
|
if (initResponse.detail?.existed) {
|
|
return initResponse
|
|
}
|
|
|
|
const initDetail = initResponse.detail
|
|
const uploadId = initDetail?.upload_id
|
|
if (!uploadId) {
|
|
throw new Error(options.messages?.initFailed || 'Init chunk upload failed')
|
|
}
|
|
|
|
const chunkSize = initDetail.chunk_size || CHUNK_SIZE
|
|
const chunks = Math.ceil(file.size / chunkSize)
|
|
const uploadedChunks = new Set(initDetail.uploaded_chunks || [])
|
|
options.onProgress?.({loaded:calculateCompletedBytes(uploadedChunks,chunkSize,file.size),total:file.size,percentage:0})
|
|
for (let index = 0; index < chunks; index++) {
|
|
if (uploadedChunks.has(index)) {
|
|
continue
|
|
}
|
|
|
|
const start = index * chunkSize
|
|
const end = Math.min(start + chunkSize, file.size)
|
|
const chunk = file.slice(start, end)
|
|
const chunkResponse = await FileService.uploadChunk(
|
|
uploadId,
|
|
index,
|
|
new Blob([chunk], { type: file.type }),
|
|
(progress) => {
|
|
const completedBytes = calculateCompletedBytes(uploadedChunks, chunkSize, file.size)
|
|
const percentage = Math.round(((completedBytes + progress.loaded) * 100) / file.size)
|
|
options.onProgress?.({
|
|
loaded: completedBytes + progress.loaded,
|
|
total: file.size,
|
|
percentage: Math.min(percentage, 99)
|
|
})
|
|
}
|
|
)
|
|
|
|
if (chunkResponse.code !== 200) {
|
|
throw new Error(options.messages?.chunkFailed?.(index) || `Chunk upload failed: ${index}`)
|
|
}
|
|
uploadedChunks.add(index)
|
|
}
|
|
|
|
pendingCompletion.set(file, { uploadId, expireValue: options.expireValue, expireStyle: options.expireStyle })
|
|
return finishUpload(file, options)
|
|
}
|