✨ feat(core): 实现管理端后台界面及核心功能模块
* 初始化后台管理布局与路由框架 * 新增文件管理、仪表盘、系统设置及日志视图 * 实现文件上传预签名、提取流程及发送记录管理 * 构建常用组件库如模态框、表格、分页及进度条 * 引入多语言支持(中英文)及主题切换功能 * 封装后台业务逻辑 Hooks 和数据持久化存储功能
This commit is contained in:
1 parent
925c6450ac
commit
8badb80600
114 files changed
+18812
No files matched your search
@@ -0,0 +1,10 @@
|
||||
import api from './client'
|
||||
import type { AdminActivityListParams, AdminActivityListResponse, ApiResponse } from '@/types'
|
||||
|
||||
export class ActivityService {
|
||||
static async getAdminActivities(
|
||||
params: AdminActivityListParams
|
||||
): Promise<ApiResponse<AdminActivityListResponse>> {
|
||||
return api.get('/admin/activities', { params })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import api from './client'
|
||||
import type { AdminUser, ApiResponse } from '@/types'
|
||||
|
||||
export class AuthService {
|
||||
static async login(password: string): Promise<ApiResponse<AdminUser>> {
|
||||
return api.post('/admin/login', { password })
|
||||
}
|
||||
|
||||
static async logout(): Promise<ApiResponse> {
|
||||
return api.post('/admin/logout')
|
||||
}
|
||||
|
||||
static async verifyToken(): Promise<ApiResponse<AdminUser>> {
|
||||
return api.get('/admin/verify')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { API_STATUS_CODES, TIME_CONSTANTS } from '@/constants'
|
||||
import type { ApiErrorPayload } from '@/types'
|
||||
import { clearStoredToken, readStoredToken } from '@/utils/auth-storage'
|
||||
|
||||
export const AUTH_EVENTS = {
|
||||
UNAUTHORIZED: 'filecodebox:auth:unauthorized'
|
||||
} as const
|
||||
|
||||
const rawBaseURL =
|
||||
import.meta.env.MODE === 'production'
|
||||
? import.meta.env.VITE_API_BASE_URL_PROD
|
||||
: import.meta.env.VITE_API_BASE_URL_DEV
|
||||
|
||||
export const apiBaseURL = typeof rawBaseURL === 'string' ? rawBaseURL.replace(/\/+$/, '') : ''
|
||||
|
||||
const clientOptions = {
|
||||
baseURL: apiBaseURL,
|
||||
timeout: TIME_CONSTANTS.REQUEST_TIMEOUT,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}
|
||||
|
||||
const apiClient = axios.create(clientOptions)
|
||||
export const rawApiClient = axios.create(clientOptions)
|
||||
|
||||
const attachAuthToken = (config: InternalAxiosRequestConfig) => {
|
||||
const token = readStoredToken()
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
const handleAuthError = (error: AxiosError<ApiErrorPayload>) => {
|
||||
if (error.response?.status === API_STATUS_CODES.UNAUTHORIZED) {
|
||||
clearStoredToken()
|
||||
window.dispatchEvent(new CustomEvent(AUTH_EVENTS.UNAUTHORIZED))
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
apiClient.interceptors.request.use(
|
||||
attachAuthToken,
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
|
||||
rawApiClient.interceptors.request.use(
|
||||
attachAuthToken,
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response.data,
|
||||
handleAuthError
|
||||
)
|
||||
|
||||
rawApiClient.interceptors.response.use((response) => response, handleAuthError)
|
||||
|
||||
export default apiClient
|
||||
@@ -0,0 +1,52 @@
|
||||
import api from './client'
|
||||
import type { ApiResponse, ConfigState, PublicConfigPayload } from '@/types'
|
||||
|
||||
const isPublicConfigEnvelope = (
|
||||
detail: ConfigState | PublicConfigPayload | null | undefined
|
||||
): detail is PublicConfigPayload => {
|
||||
return !!detail && typeof detail === 'object' && 'config' in detail
|
||||
}
|
||||
|
||||
const normalizeUserConfigResponse = (
|
||||
response: ApiResponse<ConfigState | PublicConfigPayload>
|
||||
): ApiResponse<PublicConfigPayload> => {
|
||||
if (isPublicConfigEnvelope(response.detail)) {
|
||||
return {
|
||||
...response,
|
||||
detail: {
|
||||
config: response.detail.config,
|
||||
meta: response.detail.meta
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...response,
|
||||
detail: {
|
||||
config: response.detail ?? {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class ConfigService {
|
||||
static async getConfig(): Promise<ApiResponse<ConfigState>> {
|
||||
return api.get('/admin/config/get')
|
||||
}
|
||||
|
||||
static async getUserConfig(): Promise<ApiResponse<PublicConfigPayload>> {
|
||||
try {
|
||||
const response = (await api.get('/api/v1/config')) as ApiResponse<
|
||||
ConfigState | PublicConfigPayload
|
||||
>
|
||||
|
||||
return normalizeUserConfigResponse(response)
|
||||
} catch {
|
||||
const response = (await api.post('/')) as ApiResponse<ConfigState>
|
||||
return normalizeUserConfigResponse(response)
|
||||
}
|
||||
}
|
||||
|
||||
static async updateConfig(config: Partial<ConfigState>): Promise<ApiResponse> {
|
||||
return api.patch('/admin/config/update', config)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import api, { rawApiClient } from './client'
|
||||
import { multipartUploadConfig } from './shared'
|
||||
import type {
|
||||
AdminBatchDeleteFilesResponse,
|
||||
AdminBatchPolicyActionRequest,
|
||||
AdminBatchPolicyActionResponse,
|
||||
AdminBatchUpdateFilesRequest,
|
||||
AdminBatchUpdateFilesResponse,
|
||||
AdminFilePatchPayload,
|
||||
AdminFileDetailResponse,
|
||||
AdminFileListParams,
|
||||
AdminFileMetadataRequest,
|
||||
AdminFilePolicyActionRequest,
|
||||
AdminFilePreviewResponse,
|
||||
AdminFileViewPreset,
|
||||
AdminFileViewPresetRequest,
|
||||
AdminFileViewPresetsResponse,
|
||||
ApiResponse,
|
||||
ChunkUploadCompleteRequest,
|
||||
ChunkUploadInitRequest,
|
||||
ChunkUploadInitResponse,
|
||||
ChunkUploadResponse,
|
||||
FileEditForm,
|
||||
FileInfo,
|
||||
FileListResponse,
|
||||
FileUploadResponse,
|
||||
ShareMetadataResponse,
|
||||
ShareSelectResponse,
|
||||
TextSendResponse,
|
||||
UploadProgress
|
||||
} from '@/types'
|
||||
|
||||
const urlEncodedConfig = {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
}
|
||||
}
|
||||
|
||||
const toUrlEncodedForm = (data: Record<string, string | number>) => {
|
||||
const form = new URLSearchParams()
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
form.append(key, String(value))
|
||||
})
|
||||
return form
|
||||
}
|
||||
|
||||
const isMethodFallbackError = (error: unknown) => {
|
||||
const status = (error as { response?: { status?: number } })?.response?.status
|
||||
return status === 404 || status === 405
|
||||
}
|
||||
|
||||
export class FileService {
|
||||
static async uploadFile(
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<ApiResponse<FileUploadResponse>> {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return api.post('/share/file/', formData, multipartUploadConfig(onProgress))
|
||||
}
|
||||
|
||||
static async uploadText(
|
||||
text: string,
|
||||
expireValue = 1,
|
||||
expireStyle = 'day'
|
||||
): Promise<ApiResponse<TextSendResponse>> {
|
||||
const formData = new FormData()
|
||||
formData.append('text', text)
|
||||
formData.append('expire_value', String(expireValue))
|
||||
formData.append('expire_style', expireStyle)
|
||||
return api.post('/share/text/', formData, multipartUploadConfig())
|
||||
}
|
||||
|
||||
static async initChunkUpload(
|
||||
request: ChunkUploadInitRequest
|
||||
): Promise<ApiResponse<ChunkUploadInitResponse>> {
|
||||
return api.post(
|
||||
'/chunk/upload/init/',
|
||||
toUrlEncodedForm({
|
||||
file_name: request.file_name,
|
||||
file_size: request.file_size,
|
||||
chunk_size: request.chunk_size,
|
||||
file_hash: request.file_hash
|
||||
}),
|
||||
urlEncodedConfig
|
||||
)
|
||||
}
|
||||
|
||||
static async uploadChunk(
|
||||
uploadId: string,
|
||||
chunkIndex: number,
|
||||
chunk: Blob,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<ApiResponse<ChunkUploadResponse>> {
|
||||
const formData = new FormData()
|
||||
formData.append('chunk', chunk)
|
||||
return api.post(
|
||||
`/chunk/upload/chunk/${uploadId}/${chunkIndex}`,
|
||||
formData,
|
||||
multipartUploadConfig(onProgress)
|
||||
)
|
||||
}
|
||||
|
||||
static async completeChunkUpload(
|
||||
uploadId: string,
|
||||
request: ChunkUploadCompleteRequest
|
||||
): Promise<ApiResponse<FileUploadResponse>> {
|
||||
return api.post(
|
||||
`/chunk/upload/complete/${uploadId}`,
|
||||
toUrlEncodedForm({
|
||||
expire_value: request.expire_value,
|
||||
expire_style: request.expire_style
|
||||
}),
|
||||
urlEncodedConfig
|
||||
)
|
||||
}
|
||||
|
||||
static async selectFile(code: string): Promise<ApiResponse<ShareSelectResponse>> {
|
||||
return api.post('/share/select/', { code })
|
||||
}
|
||||
|
||||
static async inspectFile(code: string): Promise<ApiResponse<ShareMetadataResponse>> {
|
||||
return api.post('/share/metadata/', { code })
|
||||
}
|
||||
|
||||
static async getFile(code: string): Promise<ApiResponse<FileInfo>> {
|
||||
return api.get(`/file/${code}`)
|
||||
}
|
||||
|
||||
static async downloadFile(code: string): Promise<Blob> {
|
||||
const response = await rawApiClient.get<Blob>(`/download/${code}`, {
|
||||
responseType: 'blob'
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
static async getAdminFileList(
|
||||
params: AdminFileListParams
|
||||
): Promise<ApiResponse<FileListResponse>> {
|
||||
return api.get('/admin/file/list', { params })
|
||||
}
|
||||
|
||||
static async getAdminFileDetail(id: number): Promise<ApiResponse<AdminFileDetailResponse>> {
|
||||
return api.get('/admin/file/detail', {
|
||||
params: { id }
|
||||
})
|
||||
}
|
||||
|
||||
static async updateFile(data: FileEditForm | AdminFilePatchPayload): Promise<ApiResponse> {
|
||||
return api.patch('/admin/file/update', data)
|
||||
}
|
||||
|
||||
static async applyAdminFilePolicyAction(
|
||||
data: AdminFilePolicyActionRequest
|
||||
): Promise<ApiResponse<AdminFileDetailResponse>> {
|
||||
try {
|
||||
return await api.patch('/admin/file/policy-action', data)
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/policy-action', data)
|
||||
}
|
||||
}
|
||||
|
||||
static async applyAdminFilesPolicyAction(
|
||||
data: AdminBatchPolicyActionRequest
|
||||
): Promise<ApiResponse<AdminBatchPolicyActionResponse>> {
|
||||
try {
|
||||
return await api.patch('/admin/file/batch-policy-action', data)
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/batch-policy-action', data)
|
||||
}
|
||||
}
|
||||
|
||||
static async updateAdminFileMetadata(
|
||||
data: AdminFileMetadataRequest
|
||||
): Promise<ApiResponse<AdminFileDetailResponse>> {
|
||||
try {
|
||||
return await api.patch('/admin/file/metadata', data)
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/metadata', data)
|
||||
}
|
||||
}
|
||||
|
||||
static async getAdminFileViewPresets(): Promise<ApiResponse<AdminFileViewPresetsResponse>> {
|
||||
return api.get('/admin/file/view-presets')
|
||||
}
|
||||
|
||||
static async saveAdminFileViewPreset(
|
||||
data: AdminFileViewPresetRequest
|
||||
): Promise<ApiResponse<AdminFileViewPreset>> {
|
||||
try {
|
||||
return await api.patch('/admin/file/view-presets', data)
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/view-presets', data)
|
||||
}
|
||||
}
|
||||
|
||||
static async updateAdminFiles(
|
||||
data: AdminBatchUpdateFilesRequest
|
||||
): Promise<ApiResponse<AdminBatchUpdateFilesResponse>> {
|
||||
return api.patch('/admin/file/batch-update', data)
|
||||
}
|
||||
|
||||
static async deleteAdminFile(id: number): Promise<ApiResponse> {
|
||||
return api.delete('/admin/file/delete', {
|
||||
data: { id }
|
||||
})
|
||||
}
|
||||
|
||||
static async deleteAdminFiles(
|
||||
ids: number[]
|
||||
): Promise<ApiResponse<AdminBatchDeleteFilesResponse>> {
|
||||
return api.delete('/admin/file/batch-delete', {
|
||||
data: { ids }
|
||||
})
|
||||
}
|
||||
|
||||
static async deleteAdminFileViewPreset(id: string): Promise<ApiResponse> {
|
||||
try {
|
||||
return await api.delete('/admin/file/view-presets', {
|
||||
data: { id }
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/view-presets/delete', { id })
|
||||
}
|
||||
}
|
||||
|
||||
static async downloadAdminFile(
|
||||
id: number
|
||||
): Promise<{ data: Blob; headers: Record<string, string> }> {
|
||||
const response = await rawApiClient.get<Blob>('/admin/file/download', {
|
||||
params: { id },
|
||||
responseType: 'blob'
|
||||
})
|
||||
return {
|
||||
data: response.data,
|
||||
headers: response.headers as Record<string, string>
|
||||
}
|
||||
}
|
||||
|
||||
static async previewAdminFile(
|
||||
id: number,
|
||||
maxChars = 20000
|
||||
): Promise<ApiResponse<AdminFilePreviewResponse>> {
|
||||
return api.get('/admin/file/preview', {
|
||||
params: {
|
||||
id,
|
||||
maxChars
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export { AUTH_EVENTS } from './client'
|
||||
export { ActivityService } from './activity'
|
||||
export { AuthService } from './auth'
|
||||
export { ConfigService } from './config'
|
||||
export { FileService } from './file'
|
||||
export { PresignUploadService } from './presign-upload'
|
||||
export { StatsService } from './stats'
|
||||
export { TrashService } from './trash'
|
||||
export { uploadChunkedFile } from './upload-strategy'
|
||||
@@ -0,0 +1,58 @@
|
||||
import api from './client'
|
||||
import { multipartUploadConfig } from './shared'
|
||||
import { uploadToExternalUrl } from './upload-client'
|
||||
import type {
|
||||
ApiResponse,
|
||||
PresignConfirmRequest,
|
||||
PresignInitRequest,
|
||||
PresignInitResponse,
|
||||
PresignStatusResponse,
|
||||
PresignUploadResult,
|
||||
UploadProgress
|
||||
} from '@/types'
|
||||
|
||||
export class PresignUploadService {
|
||||
static async initUpload(request: PresignInitRequest): Promise<ApiResponse<PresignInitResponse>> {
|
||||
return api.post('/presign/upload/init', request)
|
||||
}
|
||||
|
||||
static async proxyUpload(
|
||||
uploadId: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void,
|
||||
uploadUrl?: string
|
||||
): Promise<ApiResponse<PresignUploadResult>> {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return api.put(
|
||||
uploadUrl || `/presign/upload/proxy/${uploadId}`,
|
||||
formData,
|
||||
multipartUploadConfig(onProgress)
|
||||
)
|
||||
}
|
||||
|
||||
static async confirmUpload(
|
||||
uploadId: string,
|
||||
request?: PresignConfirmRequest
|
||||
): Promise<ApiResponse<PresignUploadResult>> {
|
||||
return api.post(`/presign/upload/confirm/${uploadId}`, request || {})
|
||||
}
|
||||
|
||||
static async getUploadStatus(uploadId: string): Promise<ApiResponse<PresignStatusResponse>> {
|
||||
return api.get(`/presign/upload/status/${uploadId}`)
|
||||
}
|
||||
|
||||
static async cancelUpload(uploadId: string): Promise<ApiResponse<{ message: string }>> {
|
||||
return api.delete(`/presign/upload/${uploadId}`)
|
||||
}
|
||||
|
||||
static async directUploadToS3(
|
||||
uploadUrl: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<boolean> {
|
||||
await uploadToExternalUrl(uploadUrl, file, onProgress)
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { AxiosRequestConfig } from 'axios'
|
||||
import type { UploadProgress } from '@/types'
|
||||
|
||||
export const multipartUploadConfig = (
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): AxiosRequestConfig => ({
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
},
|
||||
timeout: 0,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (onProgress && progressEvent.total) {
|
||||
onProgress({
|
||||
loaded: progressEvent.loaded,
|
||||
total: progressEvent.total,
|
||||
percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
import api from './client'
|
||||
import type { AnalyticsData, ApiResponse, DashboardData } from '@/types'
|
||||
|
||||
export class StatsService {
|
||||
static async getDashboard(): Promise<ApiResponse<DashboardData>> {
|
||||
return api.get('/admin/dashboard')
|
||||
}
|
||||
|
||||
static async getAnalytics(start?: string, end?: string): Promise<ApiResponse<AnalyticsData>> {
|
||||
return api.get('/admin/analytics', {
|
||||
params: {
|
||||
start,
|
||||
end
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import api from './client'
|
||||
import type { ApiResponse, TrashListParams, TrashListResponse } from '@/types'
|
||||
|
||||
export class TrashService {
|
||||
static async list(params: TrashListParams): Promise<ApiResponse<TrashListResponse>> {
|
||||
return api.get('/admin/trash/list', { params })
|
||||
}
|
||||
|
||||
static async restore(id: number): Promise<ApiResponse> {
|
||||
return api.post('/admin/trash/restore', { id })
|
||||
}
|
||||
|
||||
static async purge(id: number): Promise<ApiResponse> {
|
||||
return api.delete('/admin/trash/purge', { data: { id } })
|
||||
}
|
||||
|
||||
static async updateRetention(id: number, retentionDays: number): Promise<ApiResponse> {
|
||||
return api.post('/admin/trash/retention', { id, retentionDays })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import axios from 'axios'
|
||||
import type { UploadProgress } from '@/types'
|
||||
|
||||
export async function uploadToExternalUrl(
|
||||
uploadUrl: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<void> {
|
||||
await axios.put(uploadUrl, file, {
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream'
|
||||
},
|
||||
timeout: 0,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (!onProgress || !progressEvent.total) {
|
||||
return
|
||||
}
|
||||
|
||||
onProgress({
|
||||
loaded: progressEvent.loaded,
|
||||
total: progressEvent.total,
|
||||
percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { FileService } from './file'
|
||||
import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types'
|
||||
import { calculateFileHash } from '@/utils/file-processing'
|
||||
|
||||
const CHUNK_SIZE = 5 * 1024 * 1024
|
||||
|
||||
type ChunkedUploadOptions = {
|
||||
expireValue: number
|
||||
expireStyle: string
|
||||
onHashCalculated?: (hash: string) => void
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
messages?: {
|
||||
initFailed?: string
|
||||
chunkFailed?: (index: number) => string
|
||||
completeFailed?: string
|
||||
}
|
||||
onStatus?: (status: 'initializing' | 'uploading' | 'confirming' | 'success' | 'error') => void
|
||||
}
|
||||
|
||||
type ChunkedUploadResult = ChunkUploadInitResponse | FileUploadResponse
|
||||
|
||||
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>> => {
|
||||
options.onStatus?.('initializing')
|
||||
const fileHash = await calculateFileHash(file)
|
||||
options.onHashCalculated?.(fileHash)
|
||||
|
||||
const chunks = Math.ceil(file.size / CHUNK_SIZE)
|
||||
const initResponse = await FileService.initChunkUpload({
|
||||
file_name: file.name,
|
||||
file_size: file.size,
|
||||
chunk_size: CHUNK_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 uploadedChunks = new Set(initDetail.uploaded_chunks || [])
|
||||
options.onStatus?.('uploading')
|
||||
for (let index = 0; index < chunks; index++) {
|
||||
if (uploadedChunks.has(index)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const start = index * CHUNK_SIZE
|
||||
const end = Math.min(start + CHUNK_SIZE, 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, CHUNK_SIZE, 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)
|
||||
}
|
||||
|
||||
options.onStatus?.('confirming')
|
||||
const completeResponse = await FileService.completeChunkUpload(uploadId, {
|
||||
expire_value: options.expireValue,
|
||||
expire_style: options.expireStyle
|
||||
})
|
||||
|
||||
if (completeResponse.code !== 200) {
|
||||
options.onStatus?.('error')
|
||||
throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed')
|
||||
}
|
||||
|
||||
options.onStatus?.('success')
|
||||
return completeResponse
|
||||
}
|
||||
Reference in new issue
Block a user