diff --git a/src/composables/usePresignedUpload.ts b/src/composables/usePresignedUpload.ts index 97630af..f6ebac3 100644 --- a/src/composables/usePresignedUpload.ts +++ b/src/composables/usePresignedUpload.ts @@ -141,11 +141,14 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) { if (response.code === 200 && response.detail) { uploadSession.value = response.detail + options?.onSession?.(response.detail.upload_id) + options?.signal?.throwIfAborted() return response.detail } else { throw new Error(response.message || '初始化上传失败') } } catch (error) { + if (options?.signal?.aborted) throw error handleUploadError(error) return null } @@ -167,7 +170,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) { const uploadSuccess = await PresignUploadService.directUploadToS3( session.upload_url, file, - progressHandler + progressHandler, options?.signal ) if (!uploadSuccess) { @@ -175,11 +178,12 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) { } // 确认上传 + options?.signal?.throwIfAborted() presignStatus.value = PRESIGN_UPLOAD_STATUS.CONFIRMING const confirmResponse = await PresignUploadService.confirmUpload(session.upload_id, { expire_value: options?.expireValue ?? DEFAULT_EXPIRE_VALUE, expire_style: options?.expireStyle ?? DEFAULT_EXPIRE_STYLE - }) + }, options?.signal) if (confirmResponse.code === 200 && confirmResponse.detail?.code) { presignStatus.value = PRESIGN_UPLOAD_STATUS.SUCCESS @@ -196,6 +200,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) { throw new Error(confirmResponse.message || '确认上传失败') } } catch (error) { + if (options?.signal?.aborted) throw error handleUploadError(error) return null } @@ -219,7 +224,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) { session.upload_id, file, progressHandler, - uploadUrl + uploadUrl, options?.signal ) if (response.code === 200 && response.detail?.code) { @@ -237,6 +242,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) { throw new Error(response.message || '代理上传失败') } } catch (error) { + if (options?.signal?.aborted) throw error handleUploadError(error) return null } diff --git a/src/composables/useSendFlow.ts b/src/composables/useSendFlow.ts index 281021f..4cb6c72 100644 --- a/src/composables/useSendFlow.ts +++ b/src/composables/useSendFlow.ts @@ -32,6 +32,9 @@ export function useSendFlow() { const showDrawer = ref(false) const selectedRecord = ref(null) const isSubmitting = ref(false) + const isCancelling = ref(false) + const cleanupPending = ref(false) + const submitMessage = ref('') const isFinalizing = ref(false) const fileHash = ref('') const sendRecords = computed(() => fileDataStore.shareData) @@ -59,7 +62,7 @@ export function useSendFlow() { alertStore.showAlert(message, type) } const sentRecordActions = createSentRecordActions(notifyCopyResult) - const { resetPresignUpload, submitFile, submitText } = useSendSubmit({ + const { requestCancel, needsCleanup, retryCleanup, isUploadInterrupted, resetPresignUpload, submitFile, submitText } = useSendSubmit({ getMaxFileSize: () => configStore.uploadSizeLimit, notify: (message, type) => alertStore.showAlert(message, type), translate: t, @@ -211,8 +214,9 @@ export function useSendFlow() { } const handleSubmit = async () => { - if (isSubmitting.value) return + if (isSubmitting.value || cleanupPending.value) return isSubmitting.value = true + submitMessage.value = '' try { if (sendType.value === 'file' && !selectedFile.value && selectedFiles.value.length === 0) { @@ -286,16 +290,37 @@ export function useSendFlow() { throw new Error(t('send.messages.serverError')) } } catch (error: unknown) { - alertStore.showAlert(getErrorMessage(error, t('send.messages.sendFailed')), 'error') + if (isUploadInterrupted(error)) { + submitMessage.value = error.cleanupPending ? '上传已中断,临时文件将在上传授权到期后自动清理' : '上传已中断,临时分片已清理,可重新发送' + } else { + cleanupPending.value = needsCleanup() + submitMessage.value = cleanupPending.value ? '传输已停止,临时文件清理未完成,请重试中断' : getErrorMessage(error, t('send.messages.sendFailed')) + alertStore.showAlert(submitMessage.value, 'error') + } } finally { uploadProgress.value = 0 uploadedBytes.value = 0 totalBytes.value = 0 + isCancelling.value = false isSubmitting.value = false isFinalizing.value = false } } + const cancelUpload = async () => { + if (isCancelling.value) return + isCancelling.value = true + requestCancel() + if (isSubmitting.value) return + try { + const result = await retryCleanup() + cleanupPending.value = false + submitMessage.value = result?.detail?.completed ? `文件已上传完成,取件码:${result.detail.code}` : '上传已中断,临时分片已清理' + } catch { + submitMessage.value = '临时文件清理失败,请再次点击重试中断' + } finally { isCancelling.value = false } + } + const toggleDrawer = () => { showDrawer.value = !showDrawer.value } @@ -330,6 +355,7 @@ export function useSendFlow() { showDrawer, selectedRecord, isSubmitting, + isCancelling, cleanupPending, submitMessage, cancelUpload, isFinalizing, sendRecords, uploadDescription, diff --git a/src/composables/useSendSubmit.ts b/src/composables/useSendSubmit.ts index 59a59ba..cc4d5b9 100644 --- a/src/composables/useSendSubmit.ts +++ b/src/composables/useSendSubmit.ts @@ -1,4 +1,4 @@ -import { FileService, uploadChunkedFile } from '@/services' +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' @@ -33,6 +33,10 @@ type SubmitTextOptions = { } 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 @@ -46,6 +50,7 @@ export function useSendSubmit(options: UseSendSubmitOptions) { return uploadChunkedFile(file, { expireValue, expireStyle, + cancellation: active, onHashCalculated: options.onHashCalculated, onFinalizing: options.onFinalizing, onProgress: (progress: UploadProgress) => { @@ -67,6 +72,8 @@ export function useSendSubmit(options: UseSendSubmitOptions) { 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) } @@ -93,30 +100,45 @@ export function useSendSubmit(options: UseSendSubmitOptions) { enableChunk, validateFileSize }: SubmitFileOptions): Promise => { + 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 + if (selectedFiles.length > 0) { + options.notify('正在打包文件...', 'success') + fileToUpload = await packFilesAsZip(selectedFiles) + if (!validateFileSize(fileToUpload)) { + return null + } + options.onHashCalculated(await calculateFileHash(fileToUpload)) } - options.onHashCalculated(await calculateFileHash(fileToUpload)) - } - if (!fileToUpload) { - throw new Error(options.translate('send.messages.selectFile')) - } + if (!fileToUpload) { + throw new Error(options.translate('send.messages.selectFile')) + } - return enableChunk - ? handleChunkUpload(fileToUpload, expireValue, expireStyle) - : handlePresignedUpload(fileToUpload, expireValue, expireStyle) + 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 diff --git a/src/services/file.ts b/src/services/file.ts index b1eef53..376e392 100644 --- a/src/services/file.ts +++ b/src/services/file.ts @@ -87,33 +87,18 @@ export class FileService { ) } - static async uploadChunk( - uploadId: string, - chunkIndex: number, - chunk: Blob, - onProgress?: (progress: UploadProgress) => void - ): Promise> { - const formData = new FormData() - formData.append('chunk', chunk) - return api.post( - `/chunk/upload/chunk/${uploadId}/${chunkIndex}`, - formData, - multipartUploadConfig(onProgress) - ) + static async uploadChunk(uploadId: string, chunkIndex: number, chunk: Blob, onProgress?: (progress: UploadProgress) => void, signal?: AbortSignal): Promise> { + return api.post(`/chunk/upload/raw/${uploadId}/${chunkIndex}`, chunk, { + ...multipartUploadConfig(onProgress), headers: { 'Content-Type': 'application/octet-stream' }, signal + }) } - static async completeChunkUpload( - uploadId: string, - request: ChunkUploadCompleteRequest - ): Promise> { - return api.post( - `/chunk/upload/complete/${uploadId}`, - toUrlEncodedForm({ - expire_value: request.expire_value, - expire_style: request.expire_style - }), - urlEncodedConfig - ) + static async cancelChunkUpload(uploadId: string): Promise> { + return api.delete(`/chunk/upload/${uploadId}`) + } + + static async completeChunkUpload(uploadId: string, request: ChunkUploadCompleteRequest, signal?: AbortSignal): Promise> { + return api.post(`/chunk/upload/complete/${uploadId}`, toUrlEncodedForm({expire_value:request.expire_value,expire_style:request.expire_style}), {...urlEncodedConfig,signal}) } static async selectFile(code: string): Promise> { diff --git a/src/services/index.ts b/src/services/index.ts index c002b4b..0374385 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -9,3 +9,5 @@ export { TrashService } from './trash' export { uploadChunkedFile } from './upload-strategy' export { LocalShareService } from './local-share' + +export { UploadCancellation, UploadInterrupted, isUploadInterrupted } from './upload-cancellation' diff --git a/src/services/presign-upload.ts b/src/services/presign-upload.ts index 47c6684..eed3b1b 100644 --- a/src/services/presign-upload.ts +++ b/src/services/presign-upload.ts @@ -20,7 +20,8 @@ export class PresignUploadService { uploadId: string, file: File, onProgress?: (progress: UploadProgress) => void, - uploadUrl?: string + uploadUrl?: string, + signal?: AbortSignal ): Promise> { const formData = new FormData() formData.append('file', file) @@ -28,31 +29,33 @@ export class PresignUploadService { return api.put( uploadUrl || `/presign/upload/proxy/${uploadId}`, formData, - multipartUploadConfig(onProgress) + {...multipartUploadConfig(onProgress),signal} ) } static async confirmUpload( uploadId: string, - request?: PresignConfirmRequest + request?: PresignConfirmRequest, + signal?: AbortSignal ): Promise> { - return api.post(`/presign/upload/confirm/${uploadId}`, request || {}) + return api.post(`/presign/upload/confirm/${uploadId}`, request || {}, {signal}) } static async getUploadStatus(uploadId: string): Promise> { return api.get(`/presign/upload/status/${uploadId}`) } - static async cancelUpload(uploadId: string): Promise> { + static async cancelUpload(uploadId: string): Promise> { return api.delete(`/presign/upload/${uploadId}`) } static async directUploadToS3( uploadUrl: string, file: File, - onProgress?: (progress: UploadProgress) => void + onProgress?: (progress: UploadProgress) => void, + signal?: AbortSignal ): Promise { - await uploadToExternalUrl(uploadUrl, file, onProgress) + await uploadToExternalUrl(uploadUrl, file, onProgress, signal) return true } } diff --git a/src/services/upload-cancellation.ts b/src/services/upload-cancellation.ts new file mode 100644 index 0000000..9467624 --- /dev/null +++ b/src/services/upload-cancellation.ts @@ -0,0 +1,26 @@ +import type { ApiResponse } from '@/types' +export type CancelResult = ApiResponse<{ cancelled?: boolean; cleanup_pending?: boolean; completed?: boolean; code?: string; name?: string }> +export class UploadInterrupted extends Error { + constructor(public readonly cleanupPending = false) { super('上传已中断'); this.name = 'UploadInterrupted' } +} +export class UploadCancellation { + readonly controller = new AbortController() + private cleanup?: () => Promise + private cleaning?: Promise + get signal() { return this.controller.signal } + get needsCleanup() { return Boolean(this.cleanup) } + request() { this.controller.abort() } + check() { if (this.signal.aborted) throw new UploadInterrupted() } + register(cleanup: () => Promise) { this.cleanup = cleanup } + clear() { this.cleanup = undefined } + async clean(): Promise { + if (this.cleaning) return this.cleaning + if (!this.cleanup) return undefined + this.cleaning = this.cleanup().then(result => { + if (result.code !== 200) throw new Error('上传已停止,临时分片清理失败,请重试中断') + this.clear(); return result + }).finally(() => { this.cleaning = undefined }) + return this.cleaning + } +} +export function isUploadInterrupted(error: unknown): error is UploadInterrupted { return error instanceof UploadInterrupted } diff --git a/src/services/upload-client.ts b/src/services/upload-client.ts index 062fe77..8fd2fe4 100644 --- a/src/services/upload-client.ts +++ b/src/services/upload-client.ts @@ -4,9 +4,11 @@ import type { UploadProgress } from '@/types' export async function uploadToExternalUrl( uploadUrl: string, file: File, - onProgress?: (progress: UploadProgress) => void + onProgress?: (progress: UploadProgress) => void, + signal?: AbortSignal ): Promise { await axios.put(uploadUrl, file, { + signal, headers: { 'Content-Type': 'application/octet-stream' }, diff --git a/src/services/upload-completion.ts b/src/services/upload-completion.ts index 9535bdd..add0e4a 100644 --- a/src/services/upload-completion.ts +++ b/src/services/upload-completion.ts @@ -5,15 +5,17 @@ export function isTransientCompletionError(error: unknown): boolean { return !failure?.response || [408, 502, 503, 504].includes(failure.response.status || 0) } -export async function waitForUploadCompletion(request: () => Promise>, onFinalizing?: () => void): Promise> { +export async function waitForUploadCompletion(request: () => Promise>, onFinalizing?: () => void, signal?: AbortSignal): Promise> { let announced = false, failures = 0 while (true) { + signal?.throwIfAborted() try { const response = await request() failures = 0 if (response.code !== 202) return response if (!announced) { announced = true; onFinalizing?.() } } catch (error) { + signal?.throwIfAborted() if (!isTransientCompletionError(error) || ++failures >= 4) throw error } await new Promise(resolve => setTimeout(resolve, Math.min(1000 * (failures || 1), 3000))) diff --git a/src/services/upload-strategy.ts b/src/services/upload-strategy.ts index 5273812..80864bf 100644 --- a/src/services/upload-strategy.ts +++ b/src/services/upload-strategy.ts @@ -1,4 +1,5 @@ import { FileService } from './file' +import { UploadCancellation, UploadInterrupted } from './upload-cancellation' import { waitForUploadCompletion, isTransientCompletionError } from './upload-completion' import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types' import { calculateFileHash } from '@/utils/file-processing' @@ -6,6 +7,7 @@ import { calculateFileHash } from '@/utils/file-processing' export const CHUNK_SIZE = 100 * 1024 * 1024 type ChunkedUploadOptions = { + cancellation?: UploadCancellation expireValue: number expireStyle: string onFinalizing?: () => void @@ -31,7 +33,7 @@ async function finishUpload(file: File, options: ChunkedUploadOptions): Promise< try { const response = await waitForUploadCompletion(() => FileService.completeChunkUpload(session.uploadId, { expire_value: session.expireValue, expire_style: session.expireStyle - })) + }, options.cancellation?.signal), undefined, options.cancellation?.signal) if (response.code !== 200) throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed') pendingCompletion.delete(file) return response @@ -48,12 +50,19 @@ const calculateCompletedBytes = (uploadedChunks: Set, chunkSize: number, return total + Math.max(0, chunkEnd - chunkStart) }, 0) -export const uploadChunkedFile = async ( +const runChunkedFile = async ( file: File, options: ChunkedUploadOptions ): Promise> => { - if (pendingCompletion.has(file)) return finishUpload(file, options) + if (pendingCompletion.has(file)) { + const previous = pendingCompletion.get(file)! + options.cancellation?.register(() => FileService.cancelChunkUpload(previous.uploadId)) + options.cancellation?.check() + return finishUpload(file, options) + } + options.cancellation?.check() const fileHash = await calculateFileHash(file) + options.cancellation?.check() options.onHashCalculated?.(fileHash) const initResponse = await FileService.initChunkUpload({ @@ -77,11 +86,14 @@ export const uploadChunkedFile = async ( throw new Error(options.messages?.initFailed || 'Init chunk upload failed') } + options.cancellation?.register(() => FileService.cancelChunkUpload(uploadId)) + options.cancellation?.check() 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++) { + options.cancellation?.check() if (uploadedChunks.has(index)) { continue } @@ -101,7 +113,7 @@ export const uploadChunkedFile = async ( total: file.size, percentage: Math.min(percentage, 99) }) - } + }, options.cancellation?.signal ) if (chunkResponse.code !== 200) { @@ -113,3 +125,17 @@ export const uploadChunkedFile = async ( pendingCompletion.set(file, { uploadId, expireValue: options.expireValue, expireStyle: options.expireStyle }) return finishUpload(file, options) } + +export async function uploadChunkedFile(file: File, options: ChunkedUploadOptions): Promise> { + try { + const result = await runChunkedFile(file, options) + options.cancellation?.clear() + return result + } catch (error) { + if (!options.cancellation?.signal.aborted) throw error + pendingCompletion.delete(file) + const cancelled = await options.cancellation.clean() + if (cancelled?.detail?.completed && cancelled.detail.code) return cancelled as ApiResponse + throw new UploadInterrupted() + } +} diff --git a/src/types/dashboard.ts b/src/types/dashboard.ts index 5552a9a..07c5ff1 100644 --- a/src/types/dashboard.ts +++ b/src/types/dashboard.ts @@ -106,6 +106,14 @@ export interface AnalyticsDailyRow { } export interface AnalyticsFileRow { + status?: 'active' | 'expired' | 'trashed' | 'purged' | 'deleted' | 'history' + is_trashed?: boolean + is_purged?: boolean + trash_reason?: string + was_restored?: boolean + can_download?: boolean + trashed_at?: string + purged_at?: string code: string name: string size: number | string diff --git a/src/types/presign-upload.ts b/src/types/presign-upload.ts index abb09ea..118b323 100644 --- a/src/types/presign-upload.ts +++ b/src/types/presign-upload.ts @@ -49,6 +49,8 @@ export interface PresignStatusResponse { } export interface PresignUploadOptions { + signal?: AbortSignal + onSession?: (uploadId: string) => void expireValue?: number expireStyle?: ExpireStyle onProgress?: (progress: UploadProgress) => void diff --git a/src/utils/history-status.ts b/src/utils/history-status.ts new file mode 100644 index 0000000..b3be203 --- /dev/null +++ b/src/utils/history-status.ts @@ -0,0 +1,10 @@ +import type { AnalyticsFileRow } from '@/types' +import { getTrashReasonLabel } from './trashPresentation.ts' + +export function getHistoryStatusLabel(file: AnalyticsFileRow): string { + if (file.status === 'purged' || file.is_purged) return '已清理' + if (file.status === 'trashed' || file.is_trashed) return file.trash_reason ? getTrashReasonLabel(file.trash_reason) : '回收站中' + if (file.current || file.status === 'active' || file.status === 'expired') return file.was_restored ? '现存,已从回收站恢复' : '现存' + if (file.deleted) return '已删除' + return '历史' +} diff --git a/src/utils/trashPresentation.ts b/src/utils/trashPresentation.ts index b6bf884..e6e2b82 100644 --- a/src/utils/trashPresentation.ts +++ b/src/utils/trashPresentation.ts @@ -19,11 +19,7 @@ export function formatTrashTime(value?: string | null, now?: number): string { } export function getTrashPresentation(item: TrashFileItem, now: number) { - const reasons: Record = { - manual: '手动删除', batch_delete: '批量删除', expired_time: '保存到期', - expired_count: '次数用尽', expired_both: '到期且次数用尽', expired: '历史自动回收' - } - const reason = item.trashReason ? reasons[item.trashReason] || '其他原因' : '未记录' + const reason = getTrashReasonLabel(item.trashReason) if (item.isTrashPurged) return { state: '已清理', tone: 'muted', reason, reminder: '', @@ -45,3 +41,8 @@ export function getTrashPresentation(item: TrashFileItem, now: number) { note: valid && remainingMs <= 0 ? '已到清理时间,等待后台处理。' : '' } } + +export function getTrashReasonLabel(reason?: string | null): string { + const labels: Record = {manual:'手动删除',batch_delete:'批量删除',expired_time:'保存到期',expired_count:'次数用尽',expired_both:'到期且次数用尽',expired:'历史自动回收'} + return reason ? labels[reason] || '其他原因' : '未记录' +} diff --git a/src/views/SendFileView.vue b/src/views/SendFileView.vue index 6236b49..4b4bc1c 100644 --- a/src/views/SendFileView.vue +++ b/src/views/SendFileView.vue @@ -14,10 +14,12 @@
+
+
@@ -28,7 +30,7 @@ :progress="uploadProgress" :uploaded-bytes="uploadedBytes" :total-bytes="totalBytes" - :disabled="isSubmitting" + :disabled="isSubmitting || cleanupPending" :upload-status="isFinalizing ? 'confirming' : isSubmitting ? 'uploading' : 'idle'" :description="uploadDescription" @file-selected="handleFileSelected" @@ -44,15 +46,17 @@ />
+
+
+ +

正在停止传输并清理临时文件,请稍候。

+

{{ submitMessage }}

@@ -168,6 +175,7 @@ const { showDrawer, selectedRecord, isSubmitting, + isCancelling, cleanupPending, submitMessage, cancelUpload, isFinalizing, sendRecords, uploadDescription, diff --git a/src/views/manage/FileManageView.vue b/src/views/manage/FileManageView.vue index d63fbcd..2edbc89 100644 --- a/src/views/manage/FileManageView.vue +++ b/src/views/manage/FileManageView.vue @@ -1704,6 +1704,7 @@