From 006aaf361391423098da46893f282db683d26151 Mon Sep 17 00:00:00 2001 From: kakkokari-gtyih Date: Sat, 6 Jan 2024 19:17:22 +0900 Subject: [PATCH] fix (rangeRequest) --- .../backend/src/server/FileServerService.ts | 40 +++++++++++++++---- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/packages/backend/src/server/FileServerService.ts b/packages/backend/src/server/FileServerService.ts index 6d42bf49f8..7745a6cb78 100644 --- a/packages/backend/src/server/FileServerService.ts +++ b/packages/backend/src/server/FileServerService.ts @@ -168,7 +168,7 @@ export class FileServerService { } if (!image) { - if (request.headers.range) { + if (request.headers.range && file.file.size > 0) { const range = request.headers.range as string; const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); @@ -228,7 +228,7 @@ export class FileServerService { reply.header('Cache-Control', 'max-age=31536000, immutable'); reply.header('Content-Disposition', contentDisposition('inline', filename)); - if (request.headers.range) { + if (request.headers.range && file.file.size > 0) { const range = request.headers.range as string; const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); @@ -254,7 +254,7 @@ export class FileServerService { reply.header('Cache-Control', 'max-age=31536000, immutable'); reply.header('Content-Disposition', contentDisposition('inline', file.filename)); - if (request.headers.range) { + if (request.headers.range && file.file.size > 0) { const range = request.headers.range as string; const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); @@ -407,11 +407,35 @@ export class FileServerService { } if (!image) { - image = { - data: fs.createReadStream(file.path), - ext: file.ext, - type: file.mime, - }; + if (request.headers.range && file.file && file.file.size > 0) { + const range = request.headers.range as string; + const parts = range.replace(/bytes=/, '').split('-'); + const start = parseInt(parts[0], 10); + let end = parts[1] ? parseInt(parts[1], 10) : file.file.size - 1; + if (end > file.file.size) { + end = file.file.size - 1; + } + const chunksize = end - start + 1; + + image = { + data: fs.createReadStream(file.path, { + start, + end, + }), + ext: file.ext, + type: file.mime, + }; + + reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`); + reply.header('Accept-Ranges', 'bytes'); + reply.header('Content-Length', chunksize); + } else { + image = { + data: fs.createReadStream(file.path), + ext: file.ext, + type: file.mime, + }; + } } if ('cleanup' in file) {