Files
otunes/apps/web/lib/serve-cover.ts
T

109 lines
2.9 KiB
TypeScript

import fs from "node:fs/promises"
import path from "node:path"
import sharp from "sharp"
export const PLACEHOLDER_PATH = path.join(
process.cwd(),
"public/placeholder-album.svg"
)
const COVER_IMAGE_SIZES = new Set([64, 128, 192, 256, 384, 512, 768, 1024])
const COVER_CACHE_CONTROL = "public, max-age=300, stale-while-revalidate=86400"
const MIME_TYPES: Record<string, string> = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".gif": "image/gif",
".svg": "image/svg+xml",
}
function contentTypeFor(filePath: string) {
return (
MIME_TYPES[path.extname(filePath).toLowerCase()] ??
"application/octet-stream"
)
}
function requestedCoverSize(request: Request): number | undefined {
const value = new URL(request.url).searchParams.get("size")
if (!value) return undefined
const size = Number.parseInt(value, 10)
return COVER_IMAGE_SIZES.has(size) ? size : undefined
}
/**
* Serves stored playlist artwork as a square WebP, `?size=` pixels a side
* (1024 by default). URLs
* carry the artwork's version (`?v=`), so new artwork gets a new URL and
* versioned responses can be cached for good.
*/
export async function serveStoredCover(image: Buffer, request: Request) {
const size = requestedCoverSize(request) ?? 1024
const data = await sharp(image)
.rotate()
.resize(size, size, { fit: "cover", withoutEnlargement: true })
.webp({ quality: 80 })
.toBuffer()
return new Response(new Uint8Array(data), {
headers: {
"Content-Type": "image/webp",
"Cache-Control": new URL(request.url).searchParams.has("v")
? "public, max-age=31536000, immutable"
: COVER_CACHE_CONTROL,
},
})
}
export async function serveCoverFile(
coverPath: string | null | undefined,
request: Request
) {
if (coverPath) {
const size = requestedCoverSize(request)
if (size) {
try {
const data = await sharp(coverPath)
.rotate()
.resize(size, size, {
fit: "cover",
withoutEnlargement: true,
})
.webp({ quality: 80 })
.toBuffer()
return new Response(new Uint8Array(data), {
headers: {
"Content-Type": "image/webp",
"Cache-Control": COVER_CACHE_CONTROL,
},
})
} catch {
// Fall back to the original file when its format cannot be transformed.
}
}
try {
const data = await fs.readFile(coverPath)
return new Response(data, {
headers: {
"Content-Type": contentTypeFor(coverPath),
"Cache-Control": COVER_CACHE_CONTROL,
},
})
} catch {
// Fall through to placeholder when the file is missing on disk.
}
}
const placeholder = await fs.readFile(PLACEHOLDER_PATH)
return new Response(placeholder, {
headers: {
"Content-Type": "image/svg+xml",
"Cache-Control": "no-cache",
},
})
}