Files
FileCodeBoxFronted2026/src/composables/useSendSubmit.ts
T

149 lines
4.6 KiB
TypeScript

import { FileService, PresignUploadService, uploadChunkedFile, UploadCancellation, UploadInterrupted, isUploadInterrupted } from '@/services'
import type { AlertType, ApiResponse, ExpireStyle, UploadProgress } from '@/types'
import { calculateFileHash, packFilesAsZip } from '@/utils/file-processing'
import { usePresignedUpload } from './usePresignedUpload'
type Translate = (
key: string,
params?: Record<string, string | number | undefined>
) => string
type UseSendSubmitOptions = {
getMaxFileSize: () => number
getChunkSizeMB: () => number
notify: (message: string, type: AlertType) => void
translate: Translate
onProgress: (progress: UploadProgress) => void
onFinalizing: () => void
onHashCalculated: (hash: string) => void
}
type SubmitFileOptions = {
selectedFile: File | null
selectedFiles: File[]
expireValue: number
expireStyle: string
enableChunk: boolean
validateFileSize: (file: File) => boolean
}
type SubmitTextOptions = {
text: string
expireValue: number
expireStyle: string
}
export function useSendSubmit(options: UseSendSubmitOptions) {
let active: UploadCancellation | undefined
const requestCancel = () => active?.request()
const needsCleanup = () => Boolean(active?.signal.aborted && active.needsCleanup)
const retryCleanup = async () => active?.clean()
const { uploadFile: presignUploadFile, reset: resetPresignUpload } = usePresignedUpload({
getMaxFileSize: options.getMaxFileSize,
notify: options.notify
})
const handleChunkUpload = async (
file: File,
expireValue: number,
expireStyle: string
): Promise<ApiResponse> => {
return uploadChunkedFile(file, {
expireValue,
expireStyle,
cancellation: active,
chunkSizeMB: options.getChunkSizeMB(),
onHashCalculated: options.onHashCalculated,
onFinalizing: options.onFinalizing,
onProgress: (progress: UploadProgress) => {
options.onProgress(progress)
},
messages: {
initFailed: options.translate('send.messages.initChunkUploadFailed'),
chunkFailed: (index) => options.translate('send.messages.chunkUploadFailed', { index }),
completeFailed: options.translate('send.messages.completeUploadFailed')
}
})
}
const handlePresignedUpload = async (
file: File,
expireValue: number,
expireStyle: string
): Promise<ApiResponse<{ code?: string; name?: string }>> => {
const code = await presignUploadFile(file, {
expireValue,
expireStyle: expireStyle as ExpireStyle,
signal: active?.signal,
onSession: (uploadId) => active?.register(() => PresignUploadService.cancelUpload(uploadId)),
onProgress: (progress) => {
options.onProgress(progress)
}
})
if (!code) {
throw new Error(options.translate('send.messages.uploadFailed'))
}
return {
code: 200,
detail: {
code,
name: file.name
}
}
}
const submitFile = async ({
selectedFile,
selectedFiles,
expireValue,
expireStyle,
enableChunk,
validateFileSize
}: SubmitFileOptions): Promise<ApiResponse | null> => {
if (needsCleanup()) throw new Error('请先重试中断并清理上次上传')
const operation = new UploadCancellation()
active = operation
let fileToUpload = selectedFile
try {
if (selectedFiles.length > 0) {
options.notify('正在打包文件...', 'success')
fileToUpload = await packFilesAsZip(selectedFiles)
if (!validateFileSize(fileToUpload)) {
return null
}
options.onHashCalculated(await calculateFileHash(fileToUpload))
}
if (!fileToUpload) {
throw new Error(options.translate('send.messages.selectFile'))
}
operation.check()
options.onProgress({ loaded:0,total:fileToUpload.size,percentage:0 })
const result = await (enableChunk
? handleChunkUpload(fileToUpload, expireValue, expireStyle)
: handlePresignedUpload(fileToUpload, expireValue, expireStyle))
operation.clear()
return result
} catch (error) {
if (!operation.signal.aborted || isUploadInterrupted(error)) throw error
const cleanup = await operation.clean()
if (cleanup?.detail?.completed && cleanup.detail.code) return cleanup
throw new UploadInterrupted(Boolean(cleanup?.detail?.cleanup_pending))
}
}
const submitText = ({ text, expireValue, expireStyle }: SubmitTextOptions) =>
FileService.uploadText(text, expireValue, expireStyle)
return {
requestCancel, needsCleanup, retryCleanup, isUploadInterrupted,
resetPresignUpload,
submitFile,
submitText
}
}