fix(archive): close metadata websocket on completion

This commit is contained in:
localhost 2026-08-20 18:25:29 +02:00
parent eb535c3405
commit 4e45a313b7
1 changed files with 43 additions and 26 deletions

View File

@ -1,17 +1,22 @@
import WebSocket from 'ws'; import WebSocket from 'ws'
async function downloadVideo(ws: any, id: string): Promise<{ fail: boolean, message: string, size: number }> { interface WsLike {
return new Promise(async (resolve, reject) => { send: (msg: string) => void
}
async function downloadVideo(ws: WsLike, id: string): Promise<{ fail: boolean, message: string, size: number }> {
const { promise, resolve } = Promise.withResolvers<{ fail: boolean, message: string, size: number }>()
let isDownloading = true let isDownloading = true
const downloader = new WebSocket(`ws://${(process.env.METADATA!).replace('http://', '')}/download/${id}`) const downloader = new WebSocket(`ws://${(process.env.METADATA!).replace('http://', '')}/download/${id}`)
let size: number = 0 let size = 0
downloader.on('message', async function message(data: any) { downloader.on('message', function message(data: unknown) {
const text = data.toString() const text = String(data)
if (text.startsWith('VIDEOSIZE-')) { if (text.startsWith('VIDEOSIZE-')) {
size = parseInt(text.replace('VIDEOSIZE-', '')) size = parseInt(text.replace('VIDEOSIZE-', ''))
} else if (text == 'done') { } else if (text === 'done') {
isDownloading = false isDownloading = false
downloader.close()
return resolve({ return resolve({
fail: false, fail: false,
message: '', message: '',
@ -24,14 +29,26 @@ async function downloadVideo(ws: any, id: string): Promise<{ fail: boolean, mess
downloader.on('close', function close() { downloader.on('close', function close() {
if (!isDownloading) return if (!isDownloading) return
isDownloading = false
return resolve({ return resolve({
fail: true, fail: true,
message: 'The metadata server unexpectedly closed the websocket. Please try again.', message: 'The metadata server unexpectedly closed the websocket. Please try again.',
size size
}) })
}) })
downloader.on('error', function error(err: Error) {
if (!isDownloading) return
isDownloading = false
downloader.close()
return resolve({
fail: true,
message: `WebSocket error: ${err?.message || String(err)}`,
size
}) })
})
return promise
} }
export { downloadVideo } export { downloadVideo }