mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
feat(upload): S3 multipart upload with offline resume and wake lock (#391)
* feat(upload): implement S3 multipart upload with offline resume and wake lock * fix(upload): harden S3 sign and abort authorization, await confirmation, and clean up failed multipart uploads * fix(webui): resume multipart upload on network recovery and log online event * fix(webui): remove offline and online toast notifications
This commit is contained in:
@@ -8,11 +8,11 @@ import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { uploadFilesWithUppy } from '@/ui/lib/uploader'
|
||||
import type {
|
||||
AssetInfo,
|
||||
CollectionInfo,
|
||||
CreateUploadTaskRequest,
|
||||
PresignedUrl,
|
||||
SearchCondition,
|
||||
SearchSort,
|
||||
ShareLinkInfo,
|
||||
@@ -461,19 +461,6 @@ export function FileBrowser({
|
||||
},
|
||||
})
|
||||
|
||||
const $confirmUpload = client.api.teams[':teamId'].upload.tasks[':taskId'].$patch
|
||||
const { mutateAsync: confirmUpload } = useMutation<
|
||||
InferResponseType<typeof $confirmUpload>,
|
||||
Error,
|
||||
InferRequestType<typeof $confirmUpload>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $confirmUpload(request)
|
||||
if (!res.ok) throw new Error('Failed to confirm upload')
|
||||
return (await res.json()) as InferResponseType<typeof $confirmUpload>
|
||||
},
|
||||
})
|
||||
|
||||
const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post
|
||||
const { mutate: createUploadTaskMutation } = useMutation<
|
||||
InferResponseType<typeof $createUploadTask>,
|
||||
@@ -496,11 +483,12 @@ export function FileBrowser({
|
||||
// Register task and files in the store for real-time progress tracking
|
||||
const filesProgressInfo = currentFiles
|
||||
.map((f) => {
|
||||
const assetInfo = data.createdAssets?.find((a) => a.tempId === f.id)
|
||||
const urlInfo = (
|
||||
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
|
||||
)?.find((p) => p.id === f.id)
|
||||
return {
|
||||
fileId: urlInfo?.fileId || f.id,
|
||||
fileId: assetInfo?.assetId || urlInfo?.fileId || f.id,
|
||||
name: f.file.name,
|
||||
size: f.file.size,
|
||||
}
|
||||
@@ -522,12 +510,14 @@ export function FileBrowser({
|
||||
return path.length === 1
|
||||
})
|
||||
.map((f) => {
|
||||
const assetInfo = data.createdAssets?.find((a) => a.tempId === f.id)
|
||||
const urlInfo = (
|
||||
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
|
||||
)?.find((p) => p.id === f.id)
|
||||
const fileId = assetInfo?.assetId || urlInfo?.fileId || f.id
|
||||
const hasUrl = !!urlInfo && !!urlInfo.url
|
||||
return {
|
||||
id: urlInfo?.fileId || f.id,
|
||||
id: fileId,
|
||||
name: f.file.name,
|
||||
sizeByte: f.file.size,
|
||||
fileCount: 0,
|
||||
@@ -564,7 +554,20 @@ export function FileBrowser({
|
||||
queryKey: ['teams', teamId, 'upload', 'tasks'],
|
||||
})
|
||||
|
||||
await uploadFiles(currentFiles, data.presignedUrls, data.taskId!)
|
||||
await uploadFilesWithUppy({
|
||||
files: currentFiles,
|
||||
taskId: data.taskId!,
|
||||
teamId: teamId!,
|
||||
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
|
||||
createdAssets: data.createdAssets,
|
||||
presignedUrls: data.presignedUrls,
|
||||
onFileFinished: async (fileId) => {
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
setLocalUploadingFiles((prev) => prev.filter((f) => f.id !== fileId))
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
@@ -574,12 +577,7 @@ export function FileBrowser({
|
||||
},
|
||||
})
|
||||
|
||||
const incrementUploading = useUploadStore((state) => state.increment)
|
||||
const decrementUploading = useUploadStore((state) => state.decrement)
|
||||
const startTask = useUploadStore((state) => state.startTask)
|
||||
const updateFileProgress = useUploadStore((state) => state.updateFileProgress)
|
||||
const completeFile = useUploadStore((state) => state.completeFile)
|
||||
const failFile = useUploadStore((state) => state.failFile)
|
||||
const { fields } = useFieldStore()
|
||||
const displayedFields = useMemo(() => {
|
||||
if (!isShareView) return fields.filter((f) => f.visible)
|
||||
@@ -737,123 +735,6 @@ export function FileBrowser({
|
||||
folderInputRef.current?.click()
|
||||
}
|
||||
|
||||
const uploadFiles = async (
|
||||
files: FileWithId[],
|
||||
presignedUrls: PresignedUrl[] | undefined,
|
||||
taskId: string,
|
||||
) => {
|
||||
const uploadUrlMap = presignedUrls?.reduce(
|
||||
(acc: Record<string, { url: string; fileId: string }>, item: PresignedUrl) => {
|
||||
if (item.id) {
|
||||
acc[item.id] = {
|
||||
url: item.url || '',
|
||||
fileId: item.fileId || '',
|
||||
}
|
||||
}
|
||||
return acc
|
||||
},
|
||||
{},
|
||||
)
|
||||
if (!uploadUrlMap) return
|
||||
|
||||
const concurrencyLimit = 5
|
||||
const filesToUpload = [...files]
|
||||
|
||||
const uploadNext = async () => {
|
||||
while (filesToUpload.length > 0) {
|
||||
const file = filesToUpload.shift()
|
||||
if (file) {
|
||||
const uploadInfo = uploadUrlMap[file.id]
|
||||
if (uploadInfo && uploadInfo.url) {
|
||||
incrementUploading()
|
||||
try {
|
||||
try {
|
||||
const xhr = new XMLHttpRequest()
|
||||
const uploadPromise = new Promise<{ ok: boolean; status: number }>(
|
||||
(resolve, reject) => {
|
||||
xhr.open('PUT', uploadInfo.url)
|
||||
xhr.setRequestHeader('Content-Type', file.file.type)
|
||||
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) {
|
||||
updateFileProgress(taskId, uploadInfo.fileId, event.loaded)
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve({ ok: true, status: xhr.status })
|
||||
} else {
|
||||
resolve({ ok: false, status: xhr.status })
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onerror = () => {
|
||||
reject(new Error('Network error'))
|
||||
}
|
||||
|
||||
xhr.onabort = () => {
|
||||
reject(new Error('Upload aborted'))
|
||||
}
|
||||
|
||||
xhr.send(file.file)
|
||||
},
|
||||
)
|
||||
|
||||
const resp = await uploadPromise
|
||||
|
||||
if (resp.ok) {
|
||||
completeFile(taskId, uploadInfo.fileId)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
failFile(taskId, uploadInfo.fileId)
|
||||
toast.error(`Failed to upload file: ${file.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with status: ${resp.status}`,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
failFile(taskId, uploadInfo.fileId)
|
||||
toast.error(`Failed to upload file: ${file.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
} finally {
|
||||
decrementUploading()
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
setLocalUploadingFiles((prev) =>
|
||||
prev.filter((f) => f.id !== uploadInfo.fileId && f.id !== file.id),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const activeUploaders = Array(concurrencyLimit)
|
||||
.fill(null)
|
||||
.map(() => uploadNext())
|
||||
await Promise.all(activeUploaders)
|
||||
}
|
||||
|
||||
const processAndUploadFiles = useCallback(
|
||||
(files: FileList | File[], overrideParentId?: string) => {
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
@@ -347,10 +347,10 @@ describe('MobileFileBrowser', () => {
|
||||
expect(patchMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
param: { teamId: 'team-1', taskId: 'task-2' },
|
||||
json: {
|
||||
json: expect.objectContaining({
|
||||
fileId: 'server-file-2',
|
||||
errorMessage: 'upload failed with status: 500',
|
||||
},
|
||||
errorMessage: expect.any(String),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -412,10 +412,10 @@ describe('MobileFileBrowser', () => {
|
||||
expect(patchMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
param: { teamId: 'team-1', taskId: 'task-3' },
|
||||
json: {
|
||||
json: expect.objectContaining({
|
||||
fileId: 'server-file-3',
|
||||
errorMessage: 'upload failed with error: Network error',
|
||||
},
|
||||
errorMessage: expect.any(String),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -4,7 +4,8 @@ import { client } from '@/ui/api/client'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import type { AssetInfo, CreateUploadTaskRequest, PresignedUrl } from '@shumai/dtos'
|
||||
import { uploadFilesWithUppy } from '@/ui/lib/uploader'
|
||||
import type { AssetInfo, CreateUploadTaskRequest } from '@shumai/dtos'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
@@ -197,130 +198,7 @@ export function MobileFileBrowser({
|
||||
])
|
||||
|
||||
// Upload actions
|
||||
const incrementUploading = useUploadStore((state) => state.increment)
|
||||
const decrementUploading = useUploadStore((state) => state.decrement)
|
||||
const startTask = useUploadStore((state) => state.startTask)
|
||||
const updateFileProgress = useUploadStore((state) => state.updateFileProgress)
|
||||
const completeFile = useUploadStore((state) => state.completeFile)
|
||||
const failFile = useUploadStore((state) => state.failFile)
|
||||
|
||||
const $confirmUpload = client.api.teams[':teamId'].upload.tasks[':taskId'].$patch
|
||||
const { mutateAsync: confirmUpload } = useMutation<
|
||||
InferResponseType<typeof $confirmUpload>,
|
||||
Error,
|
||||
InferRequestType<typeof $confirmUpload>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $confirmUpload(request)
|
||||
if (!res.ok) throw new Error('Failed to confirm upload')
|
||||
return (await res.json()) as InferResponseType<typeof $confirmUpload>
|
||||
},
|
||||
})
|
||||
|
||||
const uploadFiles = async (
|
||||
filesList: FileWithId[],
|
||||
presignedUrls: PresignedUrl[] | undefined,
|
||||
taskId: string,
|
||||
) => {
|
||||
const uploadUrlMap = presignedUrls?.reduce(
|
||||
(acc: Record<string, { url: string; fileId: string }>, item: PresignedUrl) => {
|
||||
if (item.id) {
|
||||
acc[item.id] = {
|
||||
url: item.url || '',
|
||||
fileId: item.fileId || '',
|
||||
}
|
||||
}
|
||||
return acc
|
||||
},
|
||||
{},
|
||||
)
|
||||
if (!uploadUrlMap) return
|
||||
|
||||
const concurrencyLimit = 5
|
||||
const queue = [...filesList]
|
||||
|
||||
const uploadNext = async () => {
|
||||
while (queue.length > 0) {
|
||||
const item = queue.shift()
|
||||
if (item) {
|
||||
const uploadInfo = uploadUrlMap[item.id]
|
||||
if (uploadInfo && uploadInfo.url) {
|
||||
incrementUploading()
|
||||
try {
|
||||
const xhr = new XMLHttpRequest()
|
||||
const uploadPromise = new Promise<{ ok: boolean; status: number }>(
|
||||
(resolve, reject) => {
|
||||
xhr.open('PUT', uploadInfo.url)
|
||||
xhr.setRequestHeader('Content-Type', item.file.type)
|
||||
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) {
|
||||
updateFileProgress(taskId, uploadInfo.fileId, event.loaded)
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve({ ok: true, status: xhr.status })
|
||||
} else {
|
||||
resolve({ ok: false, status: xhr.status })
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onerror = () => reject(new Error('Network error'))
|
||||
xhr.onabort = () => reject(new Error('Upload aborted'))
|
||||
xhr.send(item.file)
|
||||
},
|
||||
)
|
||||
|
||||
const resp = await uploadPromise
|
||||
if (resp.ok) {
|
||||
completeFile(taskId, uploadInfo.fileId)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
failFile(taskId, uploadInfo.fileId)
|
||||
toast.error(`Failed to upload file: ${item.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with status: ${resp.status}`,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
failFile(taskId, uploadInfo.fileId)
|
||||
toast.error(`Failed to upload file: ${item.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
|
||||
},
|
||||
})
|
||||
return
|
||||
} finally {
|
||||
decrementUploading()
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const activeUploaders = Array(concurrencyLimit)
|
||||
.fill(null)
|
||||
.map(() => uploadNext())
|
||||
await Promise.all(activeUploaders)
|
||||
}
|
||||
|
||||
const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post
|
||||
const { mutate: createUploadTaskMutation } = useMutation<
|
||||
@@ -341,9 +219,10 @@ export function MobileFileBrowser({
|
||||
const currentFiles = context?.files || []
|
||||
const filesProgressInfo = currentFiles
|
||||
.map((f) => {
|
||||
const assetInfo = data.createdAssets?.find((a) => a.tempId === f.id)
|
||||
const urlInfo = data.presignedUrls?.find((p) => p.id === f.id)
|
||||
return {
|
||||
fileId: urlInfo?.fileId || f.id,
|
||||
fileId: assetInfo?.assetId || urlInfo?.fileId || f.id,
|
||||
name: f.file.name,
|
||||
size: f.file.size,
|
||||
}
|
||||
@@ -361,7 +240,17 @@ export function MobileFileBrowser({
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
|
||||
|
||||
await uploadFiles(currentFiles, data.presignedUrls, data.taskId!)
|
||||
await uploadFilesWithUppy({
|
||||
files: currentFiles,
|
||||
taskId: data.taskId!,
|
||||
teamId: teamId!,
|
||||
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
|
||||
createdAssets: data.createdAssets,
|
||||
presignedUrls: data.presignedUrls,
|
||||
onFileFinished: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
|
||||
},
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { activeUploads, uploadFilesWithUppy, isNetworkIssue } from './uploader'
|
||||
import { acquireWakeLock, releaseWakeLock } from './wake-lock'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
upload: {
|
||||
tasks: {
|
||||
':taskId': {
|
||||
$patch: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
import { Uppy, type Meta, type UppyFile } from '@uppy/core'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
describe('Uploader', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
activeUploads.clear()
|
||||
useUploadStore.setState({ uploading: 0, tasks: {}, fileProgress: {} })
|
||||
})
|
||||
|
||||
it('manages activeUploads and sends beacon on pagehide', () => {
|
||||
activeUploads.set('file-1', {
|
||||
teamId: 'team-1',
|
||||
taskId: 'task-1',
|
||||
fileId: 'file-1',
|
||||
key: 'files/test.mp4',
|
||||
uploadId: 'up-123',
|
||||
})
|
||||
|
||||
const sendBeaconSpy = vi.fn().mockReturnValue(true)
|
||||
Object.defineProperty(navigator, 'sendBeacon', {
|
||||
value: sendBeaconSpy,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
window.dispatchEvent(new Event('pagehide'))
|
||||
|
||||
expect(sendBeaconSpy).toHaveBeenCalledWith(
|
||||
'/api/teams/team-1/upload/tasks/task-1/abort',
|
||||
expect.any(Blob),
|
||||
)
|
||||
expect(activeUploads.size).toBe(0)
|
||||
})
|
||||
|
||||
it('acquires and releases wake lock', async () => {
|
||||
const releaseSpy = vi.fn().mockResolvedValue(undefined)
|
||||
const requestSpy = vi.fn().mockResolvedValue({
|
||||
release: releaseSpy,
|
||||
addEventListener: vi.fn(),
|
||||
})
|
||||
|
||||
Object.defineProperty(navigator, 'wakeLock', {
|
||||
value: { request: requestSpy },
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
await acquireWakeLock()
|
||||
expect(requestSpy).toHaveBeenCalledWith('screen')
|
||||
|
||||
await releaseWakeLock()
|
||||
expect(releaseSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs uploadFilesWithUppy with empty files without error', async () => {
|
||||
await expect(
|
||||
uploadFilesWithUppy({
|
||||
files: [],
|
||||
taskId: 'task-1',
|
||||
teamId: 'team-1',
|
||||
storageBackend: 's3',
|
||||
}),
|
||||
).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('awaits confirmation patch before uploadFilesWithUppy resolves', async () => {
|
||||
useUploadStore
|
||||
.getState()
|
||||
.startTask('task-1', 'task-1', [{ fileId: 'file-1', name: 'test.mp4', size: 100 }])
|
||||
|
||||
let patchResolved = false
|
||||
vi.mocked(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).mockImplementationOnce(
|
||||
async () => {
|
||||
await new Promise((r) => setTimeout(r, 30))
|
||||
patchResolved = true
|
||||
return { ok: true, json: async () => ({}) } as unknown as Awaited<
|
||||
ReturnType<(typeof client.api.teams)[':teamId']['upload']['tasks'][':taskId']['$patch']>
|
||||
>
|
||||
},
|
||||
)
|
||||
|
||||
const addFileSpy = vi.spyOn(Uppy.prototype, 'addFile').mockReturnValue('f1')
|
||||
|
||||
const uploadPromise = uploadFilesWithUppy({
|
||||
files: [{ id: 'temp-1', file: new File(['content'], 'test.mp4', { type: 'video/mp4' }) }],
|
||||
taskId: 'task-1',
|
||||
teamId: 'team-1',
|
||||
storageBackend: 's3',
|
||||
createdAssets: [{ tempId: 'temp-1', assetId: 'file-1', key: 'files/test.mp4' }],
|
||||
})
|
||||
|
||||
await new Promise((r) => setTimeout(r, 10))
|
||||
const capturedUppy = addFileSpy.mock.contexts[0] as Uppy
|
||||
expect(capturedUppy).toBeDefined()
|
||||
const mockFile = {
|
||||
name: 'test.mp4',
|
||||
meta: { fileId: 'file-1' },
|
||||
} as unknown as UppyFile<Meta, Record<string, never>>
|
||||
capturedUppy.emit('upload-success', mockFile, { status: 200 })
|
||||
capturedUppy.emit('complete', { successful: [mockFile], failed: [] })
|
||||
|
||||
// At this point, patch is still in-flight
|
||||
expect(patchResolved).toBe(false)
|
||||
|
||||
await uploadPromise
|
||||
expect(patchResolved).toBe(true)
|
||||
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('completed')
|
||||
addFileSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('marks file as failed and shows toast when confirmation patch fails', async () => {
|
||||
useUploadStore
|
||||
.getState()
|
||||
.startTask('task-1', 'task-1', [{ fileId: 'file-1', name: 'test.mp4', size: 100 }])
|
||||
|
||||
vi.mocked(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
statusText: 'Server Error',
|
||||
} as unknown as Awaited<
|
||||
ReturnType<(typeof client.api.teams)[':teamId']['upload']['tasks'][':taskId']['$patch']>
|
||||
>)
|
||||
|
||||
const addFileSpy = vi.spyOn(Uppy.prototype, 'addFile').mockReturnValue('f1')
|
||||
|
||||
const uploadPromise = uploadFilesWithUppy({
|
||||
files: [{ id: 'temp-1', file: new File(['content'], 'test.mp4', { type: 'video/mp4' }) }],
|
||||
taskId: 'task-1',
|
||||
teamId: 'team-1',
|
||||
storageBackend: 's3',
|
||||
createdAssets: [{ tempId: 'temp-1', assetId: 'file-1', key: 'files/test.mp4' }],
|
||||
})
|
||||
|
||||
await new Promise((r) => setTimeout(r, 10))
|
||||
const capturedUppy = addFileSpy.mock.contexts[0] as Uppy
|
||||
expect(capturedUppy).toBeDefined()
|
||||
const mockFile = {
|
||||
name: 'test.mp4',
|
||||
meta: { fileId: 'file-1' },
|
||||
} as unknown as UppyFile<Meta, Record<string, never>>
|
||||
capturedUppy.emit('upload-success', mockFile, { status: 200 })
|
||||
capturedUppy.emit('complete', { successful: [mockFile], failed: [] })
|
||||
|
||||
await uploadPromise
|
||||
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('failed')
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('Failed to confirm upload'))
|
||||
addFileSpy.mockRestore()
|
||||
})
|
||||
|
||||
describe('isNetworkIssue', () => {
|
||||
it('detects offline state and various network error indicators', () => {
|
||||
Object.defineProperty(navigator, 'onLine', { value: false, configurable: true })
|
||||
expect(isNetworkIssue(new Error('Any error'))).toBe(true)
|
||||
expect(isNetworkIssue()).toBe(true)
|
||||
|
||||
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })
|
||||
expect(isNetworkIssue(new Error('Failed to fetch'))).toBe(true)
|
||||
expect(isNetworkIssue(new Error('NetworkError when attempting to fetch resource.'))).toBe(
|
||||
true,
|
||||
)
|
||||
expect(isNetworkIssue(new Error('net::ERR_INTERNET_DISCONNECTED'))).toBe(true)
|
||||
expect(isNetworkIssue({ name: 'S3NetworkError', message: 'S3 request failed' })).toBe(true)
|
||||
expect(isNetworkIssue({ name: 'NetworkError', message: 'Network failed' })).toBe(true)
|
||||
expect(isNetworkIssue({ isNetworkError: true })).toBe(true)
|
||||
expect(isNetworkIssue({ request: { readyState: 4, status: 0 } })).toBe(true)
|
||||
|
||||
expect(isNetworkIssue(new Error('403 Forbidden'))).toBe(false)
|
||||
expect(isNetworkIssue(new Error('400 Bad Request'))).toBe(false)
|
||||
expect(isNetworkIssue(null)).toBe(false)
|
||||
expect(isNetworkIssue(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
it('pauses on network disconnect, does not report terminal failure, and resumes on back-online', async () => {
|
||||
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })
|
||||
useUploadStore
|
||||
.getState()
|
||||
.startTask('task-1', 'task-1', [{ fileId: 'file-1', name: 'test.mp4', size: 100 }])
|
||||
|
||||
const addFileSpy = vi.spyOn(Uppy.prototype, 'addFile').mockReturnValue('f1')
|
||||
const retryAllSpy = vi.spyOn(Uppy.prototype, 'retryAll').mockResolvedValue(undefined as never)
|
||||
|
||||
const uploadPromise = uploadFilesWithUppy({
|
||||
files: [{ id: 'temp-1', file: new File(['content'], 'test.mp4', { type: 'video/mp4' }) }],
|
||||
taskId: 'task-1',
|
||||
teamId: 'team-1',
|
||||
storageBackend: 's3',
|
||||
createdAssets: [{ tempId: 'temp-1', assetId: 'file-1', key: 'files/test.mp4' }],
|
||||
})
|
||||
|
||||
await new Promise((r) => setTimeout(r, 10))
|
||||
const capturedUppy = addFileSpy.mock.contexts[0] as Uppy
|
||||
expect(capturedUppy).toBeDefined()
|
||||
|
||||
const mockFile = {
|
||||
id: 'f1',
|
||||
name: 'test.mp4',
|
||||
meta: { fileId: 'file-1' },
|
||||
} as unknown as UppyFile<Meta, Record<string, never>>
|
||||
|
||||
// 1. Simulate turning off Wi-Fi
|
||||
Object.defineProperty(navigator, 'onLine', { value: false, configurable: true })
|
||||
window.dispatchEvent(new Event('offline'))
|
||||
|
||||
const networkError = new Error('Failed to fetch')
|
||||
capturedUppy.emit('upload-error', mockFile, networkError)
|
||||
capturedUppy.emit('complete', {
|
||||
successful: [],
|
||||
failed: [{ ...mockFile, error: 'Failed to fetch' }],
|
||||
})
|
||||
|
||||
// Wait a tick to verify nothing aborted or marked failed
|
||||
await new Promise((r) => setTimeout(r, 20))
|
||||
|
||||
// File must NOT be marked failed in store, activeUploads must retain file, no PATCH with error
|
||||
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('uploading')
|
||||
expect(activeUploads.has('file-1')).toBe(true)
|
||||
expect(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).not.toHaveBeenCalled()
|
||||
|
||||
// 2. Simulate turning Wi-Fi back on
|
||||
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })
|
||||
window.dispatchEvent(new Event('online'))
|
||||
|
||||
expect(retryAllSpy).toHaveBeenCalled()
|
||||
|
||||
// 3. Simulate successful upload on retry
|
||||
capturedUppy.emit('upload-success', mockFile, { status: 200 })
|
||||
capturedUppy.emit('complete', { successful: [mockFile], failed: [] })
|
||||
|
||||
await uploadPromise
|
||||
|
||||
// Confirm that confirmation patch was called without errorMessage
|
||||
expect(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).toHaveBeenCalledWith({
|
||||
param: { teamId: 'team-1', taskId: 'task-1' },
|
||||
json: { fileId: 'file-1' },
|
||||
})
|
||||
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('completed')
|
||||
expect(activeUploads.size).toBe(0)
|
||||
|
||||
addFileSpy.mockRestore()
|
||||
retryAllSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('fails permanently on non-network error and reports error to server', async () => {
|
||||
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })
|
||||
useUploadStore
|
||||
.getState()
|
||||
.startTask('task-1', 'task-1', [{ fileId: 'file-1', name: 'test.mp4', size: 100 }])
|
||||
|
||||
const addFileSpy = vi.spyOn(Uppy.prototype, 'addFile').mockReturnValue('f1')
|
||||
|
||||
const uploadPromise = uploadFilesWithUppy({
|
||||
files: [{ id: 'temp-1', file: new File(['content'], 'test.mp4', { type: 'video/mp4' }) }],
|
||||
taskId: 'task-1',
|
||||
teamId: 'team-1',
|
||||
storageBackend: 's3',
|
||||
createdAssets: [{ tempId: 'temp-1', assetId: 'file-1', key: 'files/test.mp4' }],
|
||||
})
|
||||
|
||||
await new Promise((r) => setTimeout(r, 10))
|
||||
const capturedUppy = addFileSpy.mock.contexts[0] as Uppy
|
||||
expect(capturedUppy).toBeDefined()
|
||||
|
||||
const mockFile = {
|
||||
id: 'f1',
|
||||
name: 'test.mp4',
|
||||
meta: { fileId: 'file-1' },
|
||||
} as unknown as UppyFile<Meta, Record<string, never>>
|
||||
|
||||
const permanentError = new Error('403 Forbidden')
|
||||
capturedUppy.emit('upload-error', mockFile, permanentError)
|
||||
capturedUppy.emit('complete', {
|
||||
successful: [],
|
||||
failed: [{ ...mockFile, error: '403 Forbidden' }],
|
||||
})
|
||||
|
||||
await uploadPromise
|
||||
|
||||
expect(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).toHaveBeenCalledWith({
|
||||
param: { teamId: 'team-1', taskId: 'task-1' },
|
||||
json: { fileId: 'file-1', errorMessage: '403 Forbidden' },
|
||||
})
|
||||
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('failed')
|
||||
expect(activeUploads.size).toBe(0)
|
||||
|
||||
addFileSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,425 @@
|
||||
import { Uppy } from '@uppy/core'
|
||||
import AwsS3 from '@uppy/aws-s3'
|
||||
import XHRUpload from '@uppy/xhr-upload'
|
||||
import type { PresignedUrl } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { toast } from 'sonner'
|
||||
import { acquireWakeLock, releaseWakeLock } from './wake-lock'
|
||||
|
||||
export type FileWithId = {
|
||||
id: string
|
||||
file: File
|
||||
}
|
||||
|
||||
export interface ActiveUploadFile {
|
||||
teamId: string
|
||||
taskId: string
|
||||
fileId: string
|
||||
key?: string
|
||||
uploadId?: string
|
||||
}
|
||||
|
||||
export const activeUploads = new Map<string, ActiveUploadFile>()
|
||||
|
||||
// Setup beforeunload and pagehide listeners once
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('beforeunload', (e) => {
|
||||
if (useUploadStore.getState().uploading > 0 || activeUploads.size > 0) {
|
||||
e.preventDefault()
|
||||
e.returnValue = ''
|
||||
}
|
||||
})
|
||||
|
||||
window.addEventListener('pagehide', () => {
|
||||
if (activeUploads.size === 0) return
|
||||
|
||||
for (const item of activeUploads.values()) {
|
||||
const url = `/api/teams/${item.teamId}/upload/tasks/${item.taskId}/abort`
|
||||
const payload = JSON.stringify({
|
||||
fileId: item.fileId,
|
||||
uploadId: item.uploadId,
|
||||
key: item.key,
|
||||
})
|
||||
|
||||
try {
|
||||
if ('sendBeacon' in navigator) {
|
||||
const blob = new Blob([payload], { type: 'application/json' })
|
||||
navigator.sendBeacon(url, blob)
|
||||
} else {
|
||||
fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: payload,
|
||||
keepalive: true,
|
||||
credentials: 'include',
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed to send abort beacon:', err)
|
||||
}
|
||||
}
|
||||
activeUploads.clear()
|
||||
})
|
||||
}
|
||||
|
||||
export function isNetworkIssue(error?: unknown): boolean {
|
||||
if (typeof navigator !== 'undefined' && !navigator.onLine) {
|
||||
return true
|
||||
}
|
||||
if (!error) return false
|
||||
const err = error as Record<string, unknown>
|
||||
if (err.isNetworkError === true) return true
|
||||
if (err.name === 'S3NetworkError' || err.name === 'NetworkError') return true
|
||||
const msg = (typeof err.message === 'string' ? err.message : '').toLowerCase()
|
||||
if (
|
||||
msg.includes('network error') ||
|
||||
msg.includes('failed to fetch') ||
|
||||
msg.includes('networkerror') ||
|
||||
msg.includes('load failed') ||
|
||||
msg.includes('err_internet_disconnected')
|
||||
) {
|
||||
return true
|
||||
}
|
||||
const req = err.request as Record<string, unknown> | undefined
|
||||
if (req && req.status === 0) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export interface StartUploadOptions {
|
||||
files: FileWithId[]
|
||||
taskId: string
|
||||
teamId: string
|
||||
storageBackend: 's3' | 'local'
|
||||
createdAssets?: Array<{ tempId: string; assetId: string; key?: string }>
|
||||
presignedUrls?: PresignedUrl[]
|
||||
onFileFinished?: (fileId: string) => void | Promise<void>
|
||||
}
|
||||
|
||||
export async function uploadFilesWithUppy({
|
||||
files,
|
||||
taskId,
|
||||
teamId,
|
||||
storageBackend,
|
||||
createdAssets = [],
|
||||
presignedUrls = [],
|
||||
onFileFinished,
|
||||
}: StartUploadOptions): Promise<void> {
|
||||
if (!files.length) return
|
||||
|
||||
await acquireWakeLock()
|
||||
|
||||
const store = useUploadStore.getState()
|
||||
const { increment, decrement, updateFileProgress, completeFile, failFile } = store
|
||||
|
||||
// Build lookup maps
|
||||
const assetByTempId = new Map<string, { assetId: string; key?: string }>()
|
||||
for (const a of createdAssets) {
|
||||
assetByTempId.set(a.tempId, { assetId: a.assetId, key: a.key })
|
||||
}
|
||||
|
||||
const urlByTempId = new Map<string, { url: string; fileId: string }>()
|
||||
for (const p of presignedUrls) {
|
||||
if (p.id) {
|
||||
urlByTempId.set(p.id, { url: p.url || '', fileId: p.fileId || '' })
|
||||
}
|
||||
}
|
||||
|
||||
const fileIdByKey = new Map<string, string>()
|
||||
|
||||
const uppy = new Uppy({
|
||||
autoProceed: true,
|
||||
allowMultipleUploadBatches: false,
|
||||
})
|
||||
|
||||
if (storageBackend === 's3') {
|
||||
uppy.use(AwsS3, {
|
||||
shouldUseMultipart: (file) => (file.size || 0) > 100 * 1024 * 1024,
|
||||
getChunkSize: ({ size }) => {
|
||||
if (size > 5 * 1024 * 1024 * 1024) return 32 * 1024 * 1024 // 32MB
|
||||
if (size > 1 * 1024 * 1024 * 1024) return 16 * 1024 * 1024 // 16MB
|
||||
return 8 * 1024 * 1024 // 8MB
|
||||
},
|
||||
generateObjectKey: (file) => (file.meta.key as string) || file.name,
|
||||
signRequest: async (req) => {
|
||||
const uploadId = 'uploadId' in req ? req.uploadId : undefined
|
||||
const partNumber = 'partNumber' in req ? req.partNumber : undefined
|
||||
const fileId = fileIdByKey.get(req.key)
|
||||
|
||||
if (fileId && uploadId) {
|
||||
const active = activeUploads.get(fileId)
|
||||
if (active) {
|
||||
active.uploadId = uploadId
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(`/api/teams/${teamId}/upload/sign`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
key: req.key,
|
||||
method: req.method,
|
||||
uploadId,
|
||||
partNumber,
|
||||
fileId,
|
||||
}),
|
||||
credentials: 'include',
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to sign request: ${res.statusText}`)
|
||||
}
|
||||
|
||||
const data = (await res.json()) as { url: string }
|
||||
return { url: data.url }
|
||||
},
|
||||
})
|
||||
} else {
|
||||
uppy.use(XHRUpload, {
|
||||
endpoint: (fileOrBundle) => {
|
||||
const file = Array.isArray(fileOrBundle) ? fileOrBundle[0] : fileOrBundle
|
||||
return (file?.meta?.url as string) || ''
|
||||
},
|
||||
method: 'PUT',
|
||||
formData: false,
|
||||
headers: (file) => ({
|
||||
'Content-Type': file.type || 'application/octet-stream',
|
||||
}),
|
||||
getResponseData: (xhr) => {
|
||||
try {
|
||||
return xhr.responseText ? JSON.parse(xhr.responseText) : {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
},
|
||||
shouldRetry: () => false,
|
||||
limit: 5,
|
||||
})
|
||||
}
|
||||
|
||||
const confirmationPromises = new Map<string, Promise<void>>()
|
||||
const retryCounts = new Map<string, number>()
|
||||
const MAX_ONLINE_RETRIES = 3
|
||||
let retryTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
const triggerRetry = () => {
|
||||
if (typeof navigator !== 'undefined' && !navigator.onLine) {
|
||||
console.log('[Uploader] Delaying retry because browser is currently offline.')
|
||||
return
|
||||
}
|
||||
console.log('[Uploader] Calling uppy.retryAll() to resume paused/failed uploads...')
|
||||
uppy.retryAll().catch((err: unknown) => {
|
||||
console.error('[Uploader] Error during retryAll:', err)
|
||||
})
|
||||
}
|
||||
|
||||
const scheduleRetry = (delayMs = 2000) => {
|
||||
if (retryTimeout) return
|
||||
retryTimeout = setTimeout(() => {
|
||||
retryTimeout = null
|
||||
triggerRetry()
|
||||
}, delayMs)
|
||||
}
|
||||
|
||||
// Network recovery: native back-online event and browser online/offline events
|
||||
const handleBackOnline = () => {
|
||||
const isOnline = typeof navigator !== 'undefined' ? navigator.onLine : true
|
||||
console.log(`[Uploader] Network 'online' event received! navigator.onLine = ${isOnline}`)
|
||||
triggerRetry()
|
||||
}
|
||||
|
||||
const handleOffline = () => {
|
||||
const isOnline = typeof navigator !== 'undefined' ? navigator.onLine : false
|
||||
console.warn(`[Uploader] Network 'offline' event received! navigator.onLine = ${isOnline}`)
|
||||
}
|
||||
|
||||
uppy.on('back-online', handleBackOnline)
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('online', handleBackOnline)
|
||||
window.addEventListener('offline', handleOffline)
|
||||
}
|
||||
|
||||
uppy.on('upload-progress', (file, progress) => {
|
||||
if (!file) return
|
||||
const fileId = file.meta.fileId as string
|
||||
if (fileId && progress.bytesUploaded != null) {
|
||||
updateFileProgress(taskId, fileId, progress.bytesUploaded)
|
||||
}
|
||||
})
|
||||
|
||||
uppy.on('upload-success', (file) => {
|
||||
if (!file) return
|
||||
const fileId = file.meta.fileId as string
|
||||
activeUploads.delete(fileId)
|
||||
|
||||
const confirmPromise = (async () => {
|
||||
try {
|
||||
const res = await client.api.teams[':teamId'].upload.tasks[':taskId'].$patch({
|
||||
param: { teamId, taskId },
|
||||
json: { fileId },
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to confirm upload: ${res.statusText}`)
|
||||
}
|
||||
completeFile(taskId, fileId)
|
||||
decrement()
|
||||
await onFileFinished?.(fileId)
|
||||
} catch (err) {
|
||||
console.error('Failed to confirm upload:', err)
|
||||
failFile(taskId, fileId)
|
||||
decrement()
|
||||
toast.error(`Failed to confirm upload: ${file.name}`)
|
||||
await onFileFinished?.(fileId)
|
||||
throw err
|
||||
}
|
||||
})()
|
||||
|
||||
confirmationPromises.set(fileId, confirmPromise)
|
||||
})
|
||||
|
||||
const handlePermanentError = (
|
||||
file: { name: string; meta: Record<string, unknown> },
|
||||
error: unknown,
|
||||
) => {
|
||||
const fileId = file.meta.fileId as string
|
||||
if (!activeUploads.has(fileId)) return
|
||||
activeUploads.delete(fileId)
|
||||
failFile(taskId, fileId)
|
||||
decrement()
|
||||
|
||||
toast.error(`Failed to upload file: ${file.name}`)
|
||||
|
||||
const errorPromise = (async () => {
|
||||
try {
|
||||
await client.api.teams[':teamId'].upload.tasks[':taskId'].$patch({
|
||||
param: { teamId, taskId },
|
||||
json: {
|
||||
fileId,
|
||||
errorMessage: (error as Error)?.message || 'Upload failed',
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Failed to report upload failure:', err)
|
||||
}
|
||||
await onFileFinished?.(fileId)
|
||||
})()
|
||||
|
||||
confirmationPromises.set(fileId, errorPromise)
|
||||
}
|
||||
|
||||
uppy.on('upload-error', (file, error) => {
|
||||
if (!file) return
|
||||
console.error(`[Uploader] upload-error for ${file.name}:`, error)
|
||||
|
||||
if (isNetworkIssue(error)) {
|
||||
console.warn(
|
||||
`[Uploader] Network error detected for ${file.name}. Keeping upload active to resume when connection is restored.`,
|
||||
)
|
||||
|
||||
if (typeof navigator !== 'undefined' && navigator.onLine) {
|
||||
const fileId = file.meta.fileId as string
|
||||
const attempts = (retryCounts.get(fileId) || 0) + 1
|
||||
retryCounts.set(fileId, attempts)
|
||||
|
||||
if (attempts > MAX_ONLINE_RETRIES) {
|
||||
console.error(
|
||||
`[Uploader] Exceeded max online retries (${MAX_ONLINE_RETRIES}) for ${file.name}. Failing permanently.`,
|
||||
)
|
||||
handlePermanentError(file, error)
|
||||
return
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[Uploader] Scheduling retry for ${file.name} (attempt ${attempts}/${MAX_ONLINE_RETRIES})...`,
|
||||
)
|
||||
scheduleRetry(2000)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
handlePermanentError(file, error)
|
||||
})
|
||||
|
||||
// Add files to Uppy
|
||||
for (const item of files) {
|
||||
const assetInfo = assetByTempId.get(item.id)
|
||||
const urlInfo = urlByTempId.get(item.id)
|
||||
const fileId = assetInfo?.assetId || urlInfo?.fileId || item.id
|
||||
const key = assetInfo?.key
|
||||
const url = urlInfo?.url
|
||||
|
||||
if (key) {
|
||||
fileIdByKey.set(key, fileId)
|
||||
}
|
||||
|
||||
activeUploads.set(fileId, {
|
||||
teamId,
|
||||
taskId,
|
||||
fileId,
|
||||
key,
|
||||
})
|
||||
|
||||
increment()
|
||||
|
||||
uppy.addFile({
|
||||
name: item.file.name,
|
||||
type: item.file.type,
|
||||
data: item.file,
|
||||
meta: {
|
||||
fileId,
|
||||
key,
|
||||
url,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Wait until Uppy completes all files and all confirmations settle
|
||||
try {
|
||||
await new Promise<void>((resolve) => {
|
||||
const checkCompletion = (result?: { failed?: unknown[] }) => {
|
||||
if (activeUploads.size === 0) {
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
|
||||
const failedFiles = result?.failed || []
|
||||
const isOffline = typeof navigator !== 'undefined' && !navigator.onLine
|
||||
const hasNetworkFailures =
|
||||
isOffline || failedFiles.some((f) => isNetworkIssue((f as { error?: unknown })?.error))
|
||||
|
||||
if (hasNetworkFailures) {
|
||||
console.log(
|
||||
'[Uploader] Batch completed with network issues; waiting for reconnection to resume...',
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
for (const f of failedFiles) {
|
||||
const file = f as { name: string; meta: Record<string, unknown> }
|
||||
handlePermanentError(file, (f as { error?: unknown })?.error)
|
||||
}
|
||||
|
||||
if (activeUploads.size === 0) {
|
||||
resolve()
|
||||
}
|
||||
}
|
||||
|
||||
uppy.on('complete', checkCompletion)
|
||||
uppy.on('cancel-all', () => {
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
|
||||
await Promise.allSettled(Array.from(confirmationPromises.values()))
|
||||
} finally {
|
||||
if (retryTimeout) {
|
||||
clearTimeout(retryTimeout)
|
||||
}
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener('online', handleBackOnline)
|
||||
window.removeEventListener('offline', handleOffline)
|
||||
}
|
||||
await releaseWakeLock()
|
||||
uppy.destroy()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
let wakeLockSentinel: WakeLockSentinel | null = null
|
||||
let wakeLockCount = 0
|
||||
|
||||
export async function acquireWakeLock(): Promise<void> {
|
||||
wakeLockCount++
|
||||
if (wakeLockCount > 1 && wakeLockSentinel) {
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof navigator !== 'undefined' && 'wakeLock' in navigator) {
|
||||
try {
|
||||
wakeLockSentinel = await navigator.wakeLock.request('screen')
|
||||
wakeLockSentinel.addEventListener('release', () => {
|
||||
wakeLockSentinel = null
|
||||
})
|
||||
} catch (err) {
|
||||
console.warn('Screen Wake Lock request failed:', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function releaseWakeLock(): Promise<void> {
|
||||
wakeLockCount = Math.max(0, wakeLockCount - 1)
|
||||
if (wakeLockCount === 0 && wakeLockSentinel) {
|
||||
try {
|
||||
await wakeLockSentinel.release()
|
||||
} catch (err) {
|
||||
console.warn('Screen Wake Lock release failed:', err)
|
||||
} finally {
|
||||
wakeLockSentinel = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', async () => {
|
||||
if (document.visibilityState === 'visible' && wakeLockCount > 0 && !wakeLockSentinel) {
|
||||
try {
|
||||
if (typeof navigator !== 'undefined' && 'wakeLock' in navigator) {
|
||||
wakeLockSentinel = await navigator.wakeLock.request('screen')
|
||||
wakeLockSentinel.addEventListener('release', () => {
|
||||
wakeLockSentinel = null
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Screen Wake Lock re-acquisition failed:', err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -53,6 +53,9 @@
|
||||
"@tanstack/react-router": "1.170.11",
|
||||
"@tanstack/react-table": "8.21.3",
|
||||
"@tanstack/react-virtual": "3.14.10",
|
||||
"@uppy/aws-s3": "6.0.0",
|
||||
"@uppy/core": "6.0.0",
|
||||
"@uppy/xhr-upload": "6.0.0",
|
||||
"better-auth": "1.6.11",
|
||||
"class-variance-authority": "0.7.1",
|
||||
"clsx": "2.1.1",
|
||||
|
||||
Reference in New Issue
Block a user