From ec11bda449cfab30ea8747c164463cff9ba6886f Mon Sep 17 00:00:00 2001
From: Alan Grainger <alan.grainger@gmail.com>
Date: Sun, 10 Nov 2024 21:38:40 +0100
Subject: [PATCH] Fix issue when streaming through Cloudflare

---
 app/package.json  |  2 +-
 app/src/render.ts | 17 +++++++++--------
 2 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/app/package.json b/app/package.json
index 348b164..8d3fa2a 100644
--- a/app/package.json
+++ b/app/package.json
@@ -1,6 +1,6 @@
 {
   "name": "immich-public-proxy",
-  "version": "1.3.8",
+  "version": "1.3.9",
   "scripts": {
     "dev": "ts-node src/index.ts",
     "build": "npx tsc",
diff --git a/app/src/render.ts b/app/src/render.ts
index 5ab937b..9b58570 100644
--- a/app/src/render.ts
+++ b/app/src/render.ts
@@ -15,14 +15,17 @@ class Render {
    */
   async assetBuffer (req: IncomingShareRequest, res: Response, asset: Asset, size?: ImageSize) {
     // Prepare the request
+    const headerList = ['content-type', 'content-length', 'last-modified', 'etag']
     size = size === ImageSize.thumbnail ? ImageSize.thumbnail : ImageSize.original
     const subpath = asset.type === AssetType.video ? '/video/playback' : '/' + size
     const headers = { range: '' }
-    if (asset.type === AssetType.video && req.range) {
-      const start = req.range.replace(/bytes=/, '').split('-')[0]
+    if (asset.type === AssetType.video) {
+      const start = (req.range || '').replace(/bytes=/, '').split('-')[0]
       const startByte = parseInt(start, 10) || 0
       const endByte = startByte + 2499999
       headers.range = `bytes=${startByte}-${endByte}`
+      headerList.push('accept-ranges', 'cache-control', 'content-range')
+      res.status(206) // Partial Content
     }
     const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + subpath, {
       key: asset.key,
@@ -33,12 +36,10 @@ class Render {
     // Return the response to the client
     if (data.status >= 200 && data.status < 300) {
       // Populate the response headers
-      ['content-type', 'content-length', 'last-modified', 'etag', 'content-range']
-        .forEach(header => {
-          const value = data.headers.get(header)
-          if (value) res.setHeader(header, value)
-        })
-      if (headers.range) res.status(206) // Partial Content
+      headerList.forEach(header => {
+        const value = data.headers.get(header)
+        if (value) res.setHeader(header, value)
+      })
       // Return the body
       await data.body?.pipeTo(
         new WritableStream({