[Video] Make compress/upload cancelable (#4996)

* add abort controller to video upload system

* rm log

* rm log 2
This commit is contained in:
Samuel Newman 2024-08-29 17:00:12 +01:00 committed by GitHub
parent 551c4a4f32
commit ea5ab99399
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 104 additions and 58 deletions

View file

@ -0,0 +1,20 @@
export function cancelable<A, T>(
f: (args: A) => Promise<T>,
signal: AbortSignal,
) {
return (args: A) => {
return new Promise<T>((resolve, reject) => {
signal.addEventListener('abort', () => {
reject(new AbortError())
})
f(args).then(resolve, reject)
})
}
}
export class AbortError extends Error {
constructor() {
super('Aborted')
this.name = 'AbortError'
}
}

View file

@ -8,19 +8,25 @@ export type CompressedVideo = {
export async function compressVideo(
file: string,
opts?: {
getCancellationId?: (id: string) => void
signal?: AbortSignal
onProgress?: (progress: number) => void
},
): Promise<CompressedVideo> {
const {onProgress, getCancellationId} = opts || {}
const {onProgress, signal} = opts || {}
const compressed = await Video.compress(
file,
{
getCancellationId,
compressionMethod: 'manual',
bitrate: 3_000_000, // 3mbps
maxSize: 1920,
getCancellationId: id => {
if (signal) {
signal.addEventListener('abort', () => {
Video.cancelCompression(id)
})
}
},
},
onProgress,
)

View file

@ -10,8 +10,9 @@ export type CompressedVideo = {
// doesn't actually compress, but throws if >100MB
export async function compressVideo(
file: string,
_callbacks?: {
onProgress: (progress: number) => void
_opts?: {
signal?: AbortSignal
onProgress?: (progress: number) => void
},
): Promise<CompressedVideo> {
const blob = await fetch(file).then(res => res.blob())