|
| 1 | +// app/api/spotify/route.ts |
| 2 | + |
| 3 | +import { NextResponse } from 'next/server'; |
| 4 | +import { getCurrentlyPlaying } from '@/services/spotify/api'; |
| 5 | +import { generateSpotifySVG } from '@/lib/svg/spotify'; |
| 6 | +import { spotifyParamsSchema, coerceQueryParams } from '@/lib/validations'; |
| 7 | +import { optimizeSVG } from '@/lib/svg/optimizer'; |
| 8 | +import crypto from 'crypto'; |
| 9 | + |
| 10 | +const SVG_CSP_HEADER = |
| 11 | + "default-src 'none'; style-src 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; connect-src https://fonts.gstatic.com; img-src data:;"; |
| 12 | + |
| 13 | +/** |
| 14 | + * Fetch an image and convert it to a base64 data URI |
| 15 | + */ |
| 16 | +async function fetchImageAsBase64(url: string): Promise<string | null> { |
| 17 | + try { |
| 18 | + const response = await fetch(url, { cache: 'force-cache' }); |
| 19 | + if (!response.ok) return null; |
| 20 | + const arrayBuffer = await response.arrayBuffer(); |
| 21 | + const buffer = Buffer.from(arrayBuffer); |
| 22 | + const contentType = response.headers.get('content-type') || 'image/jpeg'; |
| 23 | + return `data:${contentType};base64,${buffer.toString('base64')}`; |
| 24 | + } catch (error) { |
| 25 | + console.warn('Error fetching image for base64 encoding:', error); |
| 26 | + return null; |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +export async function GET(request: Request) { |
| 31 | + const { searchParams } = new URL(request.url); |
| 32 | + |
| 33 | + const parseResult = spotifyParamsSchema.safeParse(coerceQueryParams(searchParams)); |
| 34 | + |
| 35 | + if (!parseResult.success) { |
| 36 | + const fieldErrors = parseResult.error.flatten(); |
| 37 | + const firstError = |
| 38 | + Object.values(fieldErrors.fieldErrors).flat()[0] ?? |
| 39 | + fieldErrors.formErrors[0] ?? |
| 40 | + 'Invalid parameters'; |
| 41 | + |
| 42 | + const errorSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="400" height="150" viewBox="0 0 400 150"> |
| 43 | + <rect width="400" height="150" fill="#2d0000" rx="8"/> |
| 44 | + <text x="200" y="75" text-anchor="middle" dominant-baseline="central" fill="#ffcccc" font-family="sans-serif" font-size="13">${firstError}</text> |
| 45 | + </svg>`; |
| 46 | + |
| 47 | + return new NextResponse(errorSvg, { |
| 48 | + status: 400, |
| 49 | + headers: { |
| 50 | + 'Content-Type': 'image/svg+xml', |
| 51 | + 'Cache-Control': 'no-store', |
| 52 | + 'Content-Security-Policy': SVG_CSP_HEADER, |
| 53 | + }, |
| 54 | + }); |
| 55 | + } |
| 56 | + |
| 57 | + const params = parseResult.data; |
| 58 | + |
| 59 | + const trackData = await getCurrentlyPlaying(); |
| 60 | + let imageBase64: string | null = null; |
| 61 | + |
| 62 | + if (trackData.isPlaying && trackData.albumImageUrl) { |
| 63 | + imageBase64 = await fetchImageAsBase64(trackData.albumImageUrl); |
| 64 | + } |
| 65 | + |
| 66 | + let svg = await generateSpotifySVG(trackData, params, imageBase64); |
| 67 | + |
| 68 | + if (params.minify) { |
| 69 | + svg = optimizeSVG(svg); |
| 70 | + } |
| 71 | + |
| 72 | + const isRefreshRequested = params.refresh || params.bypassCache; |
| 73 | + const cacheControl = isRefreshRequested |
| 74 | + ? 'no-cache, no-store, must-revalidate' |
| 75 | + : 'public, max-age=30, s-maxage=30, stale-while-revalidate=30'; |
| 76 | + |
| 77 | + const etag = crypto.createHash('sha256').update(svg).digest('hex'); |
| 78 | + const weakEtag = `W/"${etag}"`; |
| 79 | + const ifNoneMatch = request.headers.get('if-none-match'); |
| 80 | + |
| 81 | + if (ifNoneMatch) { |
| 82 | + const etags = ifNoneMatch.split(',').map((e) => e.trim()); |
| 83 | + if (etags.includes(weakEtag) || etags.includes(`"${etag}"`)) { |
| 84 | + return new NextResponse(null, { |
| 85 | + status: 304, |
| 86 | + headers: { |
| 87 | + 'Cache-Control': cacheControl, |
| 88 | + ETag: weakEtag, |
| 89 | + }, |
| 90 | + }); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + return new NextResponse(svg, { |
| 95 | + headers: { |
| 96 | + 'Content-Type': 'image/svg+xml; charset=utf-8', |
| 97 | + 'Cache-Control': cacheControl, |
| 98 | + 'Content-Security-Policy': SVG_CSP_HEADER, |
| 99 | + ETag: weakEtag, |
| 100 | + }, |
| 101 | + }); |
| 102 | +} |
0 commit comments