diff --git a/package-lock.json b/package-lock.json index f142a1b..b523072 100755 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "multer": "^1.4.5-lts.1", "mysql2": "^3.11.3", "pg": "^8.13.0", + "range-parser": "^1.2.1", "sharp": "^0.33.5", "swagger-jsdoc": "^6.2.8", "swagger-ui-express": "^5.0.1" diff --git a/package.json b/package.json index 24e26f1..c4aef2f 100755 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "multer": "^1.4.5-lts.1", "mysql2": "^3.11.3", "pg": "^8.13.0", + "range-parser": "^1.2.1", "sharp": "^0.33.5", "swagger-jsdoc": "^6.2.8", "swagger-ui-express": "^5.0.1" diff --git a/routes/videoRoutes.js b/routes/videoRoutes.js index 511778e..bfd2096 100644 --- a/routes/videoRoutes.js +++ b/routes/videoRoutes.js @@ -2,6 +2,7 @@ const express = require('express'); const router = express.Router(); const db = require('../db'); const fs = require('fs'); +const rangeParser = require('range-parser'); const path = require('path'); const serverError = require('../utils/serverError'); const videoManager = require('../src/video/videoManager'); @@ -270,14 +271,32 @@ router.get('/videos/file/:video_id', (req, res) => { return res.status(400).json({ error: 'Video not yet produced' }); } const videoPath = video.video_file; - console.log('Video path:', videoPath); - fs.access(videoPath, fs.constants.F_OK, (err) => { - if (err) { - console.error('Video not found:', err); - return res.status(404).json({ error: 'Video not found' }); - } - res.download(videoPath); - }); + const stat = fs.statSync(videoPath); + const fileSize = stat.size; + const range = req.headers.range; + + if (range) { + const parts = rangeParser(fileSize, range); + const start = parts[0].start; + const end = parts[0].end; + const chunksize = (end - start) + 1; + const file = fs.createReadStream(videoPath, { start, end }); + const head = { + 'Content-Range': `bytes ${start}-${end}/${fileSize}`, + 'Accept-Ranges': 'bytes', + 'Content-Length': chunksize, + 'Content-Type': 'video/mp4', + }; + res.writeHead(206, head); + file.pipe(res); + } else { + const head = { + 'Content-Length': fileSize, + 'Content-Type': 'video/mp4', + }; + res.writeHead(200, head); + fs.createReadStream(videoPath).pipe(res); + } }); });