From 0e5037d9bdd97521d0d5c6ecf145a62336a57eaf Mon Sep 17 00:00:00 2001 From: Samuel Fry Date: Sun, 18 Sep 2022 15:17:40 -0400 Subject: [PATCH] gracefully handle ffmpeg video errors --- src/pages/api/videos/upload.ts | 40 ++++++++++++++++++---------------- src/utils/deleteFile.ts | 7 ++++++ 2 files changed, 28 insertions(+), 19 deletions(-) create mode 100644 src/utils/deleteFile.ts diff --git a/src/pages/api/videos/upload.ts b/src/pages/api/videos/upload.ts index 76be844..e5a3c56 100644 --- a/src/pages/api/videos/upload.ts +++ b/src/pages/api/videos/upload.ts @@ -13,6 +13,7 @@ import { IFFMpegFileDetails, IFFMpegProgressData, } from 'ffmpeg-progress-wrapper'; +import { deleteFile } from '../../../utils/deleteFile'; const parser = multer({ storage: multer.diskStorage({ @@ -123,33 +124,34 @@ upload.post(async (req: MulterRequest, res) => { }); }, ); - videoTranscodingProcess.onDone().then(async () => { - console.log(`${newId} - Conversion finished`); - await prisma.videoProgress.delete({ - where: { - id: progress.id, - }, + videoTranscodingProcess + .onDone() + .then(async () => { + console.log(`${newId} - Conversion finished`); + await prisma.videoProgress.delete({ + where: { + id: progress.id, + }, + }); + deleteFile(tmpFile); + }) + .catch(async (err) => { + console.error(err); + await prisma.video.delete({ + where: { id: newId }, + }); + deleteFile(tmpFile); + deleteFile(`${env.DATA_DIR}/uploads/${newId}.mp4`); + deleteFile(`${env.DATA_DIR}/uploads/${newId}.jpg`); }); - fs.rmSync(tmpFile); - }); - - const returnVideo = await prisma.video.findFirst({ - where: { - id: newId, - }, - include: { - progress: true, - }, - }); return res.status(200).json({ message: 'Video successfully uploaded!', success: true, - video: returnVideo, }); } catch (e: any) { console.error(e); - fs.rmSync(tmpFile); + deleteFile(tmpFile); return res.status(500).json({ message: e.message, success: false, diff --git a/src/utils/deleteFile.ts b/src/utils/deleteFile.ts new file mode 100644 index 0000000..c142d79 --- /dev/null +++ b/src/utils/deleteFile.ts @@ -0,0 +1,7 @@ +import fs from 'fs'; + +export const deleteFile = (path: string) => { + if (fs.existsSync(path)) { + fs.unlinkSync(path); + } +};