feat: compression 9

This commit is contained in:
jfmcarreira committed 2026-09-24 15:59:25 +01:00
1 parent a7afeac440
commit e88c222c22
4 files changed
+167 -117

No files matched your search

@@ -1,79 +1,86 @@
// pages/api/proxy.js
import { ENV } from '@/config/environment';
import { appDb } from '@/db';
import { apiKeys } from '@/db/schema';
import { and, eq } from 'drizzle-orm';
import { verify } from 'jsonwebtoken';
import { ENV } from '@/config/environment'
import { appDb } from '@/db'
import { apiKeys } from '@/db/schema'
import { and, eq } from 'drizzle-orm'
import { verify } from 'jsonwebtoken'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { NextApiRequest, NextApiResponse } from 'next'
export const config = {
api: {
bodyParser: false,
responseLimit: false,
},
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
return res.status(405).json({ message: 'Method Not Allowed' })
}
const { id, size, token, p } = req.query;
const { id, size, token, p } = req.query
if (!token) {
return res.status(401).json({ message: 'Unauthorized' })
}
let userId: string;
let userId: string
try {
const previewDecoded = verify(token as string, ENV.JWT_SECRET) as { token: string };
const mainDecoded = verify(previewDecoded.token, ENV.JWT_SECRET) as { userId: string };
userId = mainDecoded.userId;
} catch (error) {
const previewDecoded = verify(token as string, ENV.JWT_SECRET) as { token: string }
const mainDecoded = verify(previewDecoded.token, ENV.JWT_SECRET) as { userId: string }
userId = mainDecoded.userId
} catch {
return res.status(401).json({ message: 'Token is invalid' })
}
const [keyRow] = await appDb
.select({ secret: apiKeys.secret })
.from(apiKeys)
.where(and(eq(apiKeys.userId, userId), eq(apiKeys.purpose, "share")))
.limit(1);
.where(and(eq(apiKeys.userId, userId), eq(apiKeys.purpose, 'share')))
.limit(1)
if (!keyRow) {
return res.status(403).json({ message: 'Share key not configured. Please set up sharing in Power Tools.' });
return res.status(403).json({ message: 'Share key not configured. Please set up sharing in Power Tools.' })
}
const resource = p === "true" ? "people" : "assets";
const baseURL = `${ENV.IMMICH_URL}/api/${resource}/${id}`;
const version = size === "original" ? "original" : "thumbnail";
let targetUrl = `${baseURL}/${version}?size=${size}`;
const resource = p === 'true' ? 'people' : 'assets'
const baseURL = `${ENV.IMMICH_URL}/api/${resource}/${id}`
const version = size === 'original' ? 'original' : 'thumbnail'
const targetUrl = `${baseURL}/${version}?size=${size}`
try {
// Forward the request to the target API
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/octet-stream',
Accept: 'image/*,video/*,application/octet-stream',
'Accept-Encoding': 'identity',
'x-api-key': keyRow.secret,
},
})
if (!response.ok) {
const error = await response.json()
throw new Error("Error fetching thumbnail " + error.message)
console.error(`Shared asset request failed: ${response.status} ${targetUrl}`)
return res.redirect('https://placehold.co/400')
}
// Get the image data from the response
const imageBuffer = await response.arrayBuffer()
if (!response.body) {
return res.status(502).json({ message: 'Immich returned an empty response body' })
}
// Set the appropriate headers for the image response
res.setHeader('Content-Type', response.headers.get('Content-Type') || 'image/png')
res.setHeader('Content-Length', imageBuffer.byteLength)
const contentType = response.headers.get('content-type')
const contentLength = response.headers.get('content-length')
const cacheControl = response.headers.get('cache-control')
// Send the image data
res.send(Buffer.from(imageBuffer))
} catch (error: any) {
res.redirect("https://placehold.co/400")
console.error('Error:', error)
if (contentType) res.setHeader('Content-Type', contentType)
if (contentLength) res.setHeader('Content-Length', contentLength)
if (cacheControl) res.setHeader('Cache-Control', cacheControl)
await pipeline(Readable.fromWeb(response.body as any), res)
} catch (error) {
console.error('Shared asset proxy error:', error)
if (!res.headersSent) {
return res.redirect('https://placehold.co/400')
}
res.destroy(error as Error)
}
}
}
@@ -1,13 +1,14 @@
// pages/api/proxy.js
import { ENV } from '@/config/environment';
import { getCurrentUser } from '@/handlers/serverUtils/user.utils';
import { getUserHeaders } from '@/helpers/user.helper';
import { ENV } from '@/config/environment'
import { getCurrentUser } from '@/handlers/serverUtils/user.utils'
import { getUserHeaders } from '@/helpers/user.helper'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { NextApiRequest, NextApiResponse } from 'next'
export const config = {
api: {
bodyParser: false,
responseLimit: false,
},
}
@@ -15,38 +16,48 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (req.method !== 'GET') {
return res.status(405).json({ message: 'Method Not Allowed' })
}
const { id, size } = req.query;
const targetUrl = `${ENV.IMMICH_URL}/api/assets/${id}/thumbnail?size=${size || 'thumbnail'}`;
const user = await getCurrentUser(req);
const { id, size } = req.query
const targetUrl = `${ENV.IMMICH_URL}/api/assets/${id}/thumbnail?size=${size || 'thumbnail'}`
const user = await getCurrentUser(req)
if (!user) {
return res.status(403).json({ message: 'Unauthorized' })
}
try {
// Forward the request to the target API
const response = await fetch(targetUrl, {
method: 'GET',
headers: getUserHeaders(user, {
'Content-Type': 'application/octet-stream',
}),
headers: {
...getUserHeaders(user),
Accept: 'image/*',
'Accept-Encoding': 'identity',
},
})
if (!response.ok) {
console.error('HTTP error:', response)
throw new Error(`HTTP error! status: ${response.status}`)
console.error(`Thumbnail request failed: ${response.status} ${targetUrl}`)
return res.status(response.status).json({ message: 'Failed to fetch thumbnail' })
}
// Get the image data from the response
const imageBuffer = await response.arrayBuffer()
if (!response.body) {
return res.status(502).json({ message: 'Immich returned an empty thumbnail body' })
}
// Set the appropriate headers for the image response
res.setHeader('Content-Type', response.headers.get('Content-Type') || 'image/png')
res.setHeader('Content-Length', imageBuffer.byteLength)
const contentType = response.headers.get('content-type')
const contentLength = response.headers.get('content-length')
const cacheControl = response.headers.get('cache-control')
// Send the image data
res.send(Buffer.from(imageBuffer))
if (contentType) res.setHeader('Content-Type', contentType)
if (contentLength) res.setHeader('Content-Length', contentLength)
if (cacheControl) res.setHeader('Cache-Control', cacheControl)
await pipeline(Readable.fromWeb(response.body as any), res)
} catch (error) {
res.status(500).json({ message: 'Internal Server Error' })
console.error('Thumbnail proxy error:', error)
if (!res.headersSent) {
return res.status(500).json({ message: 'Internal Server Error' })
}
res.destroy(error as Error)
}
}
}
+56 -31
View File
@@ -1,53 +1,78 @@
// pages/api/proxy.js
import { ENV } from '@/config/environment';
import { getCurrentUser } from '@/handlers/serverUtils/user.utils';
import { getUserHeaders } from '@/helpers/user.helper';
import { ENV } from '@/config/environment'
import { getCurrentUser } from '@/handlers/serverUtils/user.utils'
import { getUserHeaders } from '@/helpers/user.helper'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { NextApiRequest, NextApiResponse } from 'next'
export const config = {
api: {
bodyParser: false,
responseLimit: false,
},
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return res.status(405).json({ message: 'Method Not Allowed' })
}
const { id } = req.query;
const targetUrl = `${ENV.IMMICH_URL}/api/assets/${id}/original`;
const user = await getCurrentUser(req);
const { id } = req.query
const targetUrl = `${ENV.IMMICH_URL}/api/assets/${id}/original`
const user = await getCurrentUser(req)
if (!user) {
return res.status(403).json({ message: 'Unauthorized' })
}
try {
// Forward the request to the target API
const response = await fetch(targetUrl, {
method: 'GET',
headers: getUserHeaders(user, {
'Content-Type': 'application/octet-stream',
}),
})
if (!response.ok) {
console.error('HTTP error:', response)
throw new Error(`HTTP error! status: ${response.status}`)
try {
const headers: Record<string, string> = {
...getUserHeaders(user),
Accept: 'video/*,application/octet-stream',
'Accept-Encoding': 'identity',
}
// Get the image data from the response
const imageBuffer = await response.arrayBuffer()
if (req.headers.range) {
headers.Range = req.headers.range
}
// Set the appropriate headers for the image response
res.setHeader('Content-Type', response.headers.get('Content-Type') || 'image/png')
res.setHeader('Content-Length', imageBuffer.byteLength)
const response = await fetch(targetUrl, {
method: req.method,
headers,
})
// Send the image data
res.send(Buffer.from(imageBuffer))
res.status(response.status)
const forwardedHeaders = [
'accept-ranges',
'cache-control',
'content-disposition',
'content-length',
'content-range',
'content-type',
'etag',
'last-modified',
]
for (const header of forwardedHeaders) {
const value = response.headers.get(header)
if (value) res.setHeader(header, value)
}
if (!response.ok && response.status !== 206) {
console.error(`Video request failed: ${response.status} ${targetUrl}`)
}
if (req.method === 'HEAD' || !response.body) {
return res.end()
}
await pipeline(Readable.fromWeb(response.body as any), res)
} catch (error) {
console.error('Error:', error)
res.status(500).json({ message: 'Internal Server Error' })
console.error('Video proxy error:', error)
if (!res.headersSent) {
return res.status(500).json({ message: 'Internal Server Error' })
}
res.destroy(error as Error)
}
}
}
+33 -26
View File
@@ -1,13 +1,14 @@
// pages/api/proxy.js
import { ENV } from '@/config/environment';
import { getCurrentUser } from '@/handlers/serverUtils/user.utils';
import { getUserHeaders } from '@/helpers/user.helper';
import { ENV } from '@/config/environment'
import { getCurrentUser } from '@/handlers/serverUtils/user.utils'
import { getUserHeaders } from '@/helpers/user.helper'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { NextApiRequest, NextApiResponse } from 'next'
export const config = {
api: {
bodyParser: false,
responseLimit: false,
},
}
@@ -15,42 +16,48 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (req.method !== 'GET') {
return res.status(405).json({ message: 'Method Not Allowed' })
}
const { id } = req.query;
const targetUrl = `${ENV.IMMICH_URL}/api/people/${id}/thumbnail`;
const currentUser = await getCurrentUser(req);
const { id } = req.query
const targetUrl = `${ENV.IMMICH_URL}/api/people/${id}/thumbnail`
const currentUser = await getCurrentUser(req)
if (!currentUser) {
return res.status(403).json({ message: 'Forbidden' })
}
try {
// Forward the request to the target API
const response = await fetch(targetUrl, {
method: 'GET',
headers: getUserHeaders(currentUser, {
'Content-Type': 'application/octet-stream',
}),
headers: {
...getUserHeaders(currentUser),
Accept: 'image/*',
'Accept-Encoding': 'identity',
},
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
console.error(`Person thumbnail request failed: ${response.status} ${targetUrl}`)
return res.redirect('https://placehold.co/400')
}
// Get the image data from the response
const imageBuffer = await response.arrayBuffer()
if (!response.body) {
return res.status(502).json({ message: 'Immich returned an empty thumbnail body' })
}
// Set the appropriate headers for the image response
res.setHeader('Content-Type', response.headers.get('Content-Type') || 'image/png')
res.setHeader('Content-Length', imageBuffer.byteLength)
const contentType = response.headers.get('content-type')
const contentLength = response.headers.get('content-length')
const cacheControl = response.headers.get('cache-control')
// Send the image data
res.send(Buffer.from(imageBuffer))
if (contentType) res.setHeader('Content-Type', contentType)
if (contentLength) res.setHeader('Content-Length', contentLength)
if (cacheControl) res.setHeader('Cache-Control', cacheControl)
await pipeline(Readable.fromWeb(response.body as any), res)
} catch (error) {
res.redirect("https://placehold.co/400")
console.error('Error:', error)
// res.status(500).json({ message: 'Internal Server Error' })
console.error('Person thumbnail proxy error:', error)
if (!res.headersSent) {
return res.redirect('https://placehold.co/400')
}
res.destroy(error as Error)
}
}
}