First commit
This commit is contained in:
108
backend/src/images.ts
Normal file
108
backend/src/images.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
|
||||
export const IMAGE_DIR = join(import.meta.dirname, '..', 'data', 'images')
|
||||
export const PLAYMAT_DIR = join(import.meta.dirname, '..', 'data', 'playmats')
|
||||
|
||||
const MAX_PLAYMAT_BYTES = 3_000_000
|
||||
const PLAYMAT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
||||
const PLAYMAT_DATA_URL = /^data:image\/jpeg;base64,([A-Za-z0-9+/]+={0,2})$/
|
||||
const JPEG_SIGNATURE = Buffer.from([0xff, 0xd8, 0xff])
|
||||
|
||||
export class PlaymatError extends Error {}
|
||||
|
||||
const downloads = new Map<string, Promise<Buffer>>()
|
||||
|
||||
/** Only accept art from Scryfall's image host, never an arbitrary URL from the data file. */
|
||||
export function scryfallImageUrl(uri: string | undefined): string | undefined {
|
||||
if (!uri) return undefined
|
||||
try {
|
||||
const url = new URL(uri)
|
||||
const scryfall = url.hostname === 'scryfall.io' || url.hostname.endsWith('.scryfall.io')
|
||||
return url.protocol === 'https:' && scryfall ? url.href : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Scryfall serves the same art wider for playmats; swap the size segment of a normal image URL. */
|
||||
export function scryfallArtUrl(uri: string | undefined): string | undefined {
|
||||
const source = scryfallImageUrl(uri)
|
||||
if (!source) return undefined
|
||||
return scryfallImageUrl(source.replace('/normal/', '/art_crop/'))
|
||||
}
|
||||
|
||||
async function cachedImage(key: string, source: string, dir: string): Promise<Buffer> {
|
||||
const file = join(dir, `${key}.jpg`)
|
||||
|
||||
try {
|
||||
return await readFile(file)
|
||||
} catch {
|
||||
// Not cached yet.
|
||||
}
|
||||
|
||||
let download = downloads.get(file)
|
||||
if (!download) {
|
||||
download = (async () => {
|
||||
const response = await fetch(source, {
|
||||
headers: { 'User-Agent': 'commander-api/0.1', Accept: 'image/jpeg,image/*' },
|
||||
})
|
||||
if (!response.ok || !response.headers.get('content-type')?.startsWith('image/')) {
|
||||
throw new Error(`Scryfall image request failed: ${response.status}`)
|
||||
}
|
||||
|
||||
const data = Buffer.from(await response.arrayBuffer())
|
||||
await mkdir(dir, { recursive: true })
|
||||
const temp = `${file}.tmp`
|
||||
await writeFile(temp, data)
|
||||
await rename(temp, file)
|
||||
return data
|
||||
})().finally(() => downloads.delete(file))
|
||||
downloads.set(file, download)
|
||||
}
|
||||
|
||||
return download
|
||||
}
|
||||
|
||||
/** Return a card's face, downloading it from Scryfall once and keeping a copy on disk. */
|
||||
export function cardImage(oracleId: string, source: string, dir = IMAGE_DIR): Promise<Buffer> {
|
||||
return cachedImage(encodeURIComponent(oracleId), source, dir)
|
||||
}
|
||||
|
||||
/** Wide art crop used as a playmat. Cached separately from the card face. */
|
||||
export function cardArt(oracleId: string, source: string, dir = IMAGE_DIR): Promise<Buffer> {
|
||||
return cachedImage(`art-${encodeURIComponent(oracleId)}`, source, dir)
|
||||
}
|
||||
|
||||
/** Validate and store an uploaded playmat, returning the id used in its URL. */
|
||||
export async function storePlaymatImage(dataUrl: string, dir = PLAYMAT_DIR): Promise<string> {
|
||||
const match = PLAYMAT_DATA_URL.exec(dataUrl)
|
||||
if (!match) throw new PlaymatError('Playmat must be a base64 JPEG image')
|
||||
const data = Buffer.from(match[1], 'base64')
|
||||
if (!data.length || data.length > MAX_PLAYMAT_BYTES) {
|
||||
throw new PlaymatError('Playmat image must be under 3 MB')
|
||||
}
|
||||
if (!data.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)) {
|
||||
throw new PlaymatError('Playmat image is not a JPEG')
|
||||
}
|
||||
|
||||
const id = randomUUID()
|
||||
await mkdir(dir, { recursive: true })
|
||||
await writeFile(join(dir, `${id}.jpg`), data)
|
||||
return id
|
||||
}
|
||||
|
||||
export async function playmatImage(id: string, dir = PLAYMAT_DIR): Promise<Buffer | undefined> {
|
||||
if (!PLAYMAT_ID.test(id)) return undefined
|
||||
try {
|
||||
return await readFile(join(dir, `${id}.jpg`))
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export async function deletePlaymatImage(id: string, dir = PLAYMAT_DIR): Promise<void> {
|
||||
if (!PLAYMAT_ID.test(id)) return
|
||||
await rm(join(dir, `${id}.jpg`), { force: true })
|
||||
}
|
||||
Reference in New Issue
Block a user