- Virtualize mobile lists and defer queue loading - Split playback state from actions to reduce rerenders - Skip invalid or unnecessary Convex queries Reviewed-on: #18
87 lines
2.1 KiB
TypeScript
87 lines
2.1 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
|
|
}
|
|
|
|
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",
|
|
},
|
|
})
|
|
}
|