Skip to content
← Public packages

@kentcdodds/photo-portfolio

A fast, photo-first portfolio site you update by chatting with your agent: galleries, about, contact, and one-step rollback.

FollowFork

Files

ingest.ts

131 lines · 4.1 KB · TypeScript
import * as s from 'remix/data-schema'
import type { Photo, PhotoCredits, SiteConfig } from '../domain/types.ts'
import { httpUrl, longText, strictObject } from '../domain/validation.ts'
import { base64ToBytes } from '../store/base64.ts'
import {
	discardMedia,
	saveMedia,
	type SiteStorage,
} from '../store/site-store.ts'
import { processImage } from './process.ts'

/** Photos per export call. Each one is decoded and re-encoded 6–8 times, so batches stay small. */
export const maxPhotosPerCall = 6
/** Largest upload accepted (bytes), from a URL or base64. */
export const maxUploadBytes = 30 * 1024 * 1024

/** One photo to add: exactly one of `url` (direct image link) or `base64`. */
export type PhotoInput = {
	url?: string
	base64?: string
	alt?: string
	caption?: string
}

export const photoInputSchema = strictObject({
	url: s.optional(httpUrl()),
	base64: s.optional(s.string()),
	alt: s.optional(longText(300)),
	caption: s.optional(longText(300)),
}).refine(
	(photo: PhotoInput) => Boolean(photo.url) !== Boolean(photo.base64),
	'pass exactly one of url or base64',
)

export const photoBatchSchema = s
	.array(photoInputSchema)
	.refine(
		(photos: Array<PhotoInput>) => photos.length > 0,
		'pass at least one photo',
	)
	.refine(
		(photos: Array<PhotoInput>) => photos.length <= maxPhotosPerCall,
		`pass at most ${maxPhotosPerCall} photos per call; send the rest with add-photos`,
	)

function newPhotoId() {
	const bytes = crypto.getRandomValues(new Uint8Array(8))
	return `ph_${Array.from(bytes, (b) => b.toString(36).padStart(2, '0'))
		.join('')
		.slice(0, 12)}`
}

async function readSource(input: PhotoInput): Promise<Uint8Array> {
	if (input.base64) {
		const bytes = base64ToBytes(input.base64)
		if (bytes.length > maxUploadBytes)
			throw new Error('File is larger than 30 MB.')
		return bytes
	}
	const response = await fetch(input.url!, {
		redirect: 'follow',
		// Some hosts (Wikimedia, many CDNs) refuse requests without a User-Agent.
		headers: { 'user-agent': 'photo-portfolio/0.1 (Kody package)' },
	})
	if (!response.ok)
		throw new Error(
			`Download failed (HTTP ${response.status}) for ${input.url}.`,
		)
	const declared = Number(response.headers.get('content-length') ?? 0)
	if (declared > maxUploadBytes) throw new Error('File is larger than 30 MB.')
	const bytes = new Uint8Array(await response.arrayBuffer())
	if (bytes.length > maxUploadBytes)
		throw new Error('File is larger than 30 MB.')
	return bytes
}

function creditExifFor(config: SiteConfig, now: string) {
	if (!config.embedCopyright) return undefined
	const year = now.slice(0, 4)
	return {
		artist: config.photographerName,
		copyright: `© ${year} ${config.photographerName}`,
	}
}

function hasCredits(credits: PhotoCredits) {
	return Object.values(credits).some(Boolean)
}

/**
 * Download/decode, resize, encode, and store a batch of photos. All or nothing:
 * if any photo fails, media already stored for this batch is deleted and the
 * error names the photo (1-based) and what went wrong.
 */
export async function ingestPhotos(
	storage: SiteStorage,
	inputs: Array<PhotoInput>,
	options: { config: SiteConfig; fallbackAlt: string; now: string },
): Promise<Array<Photo>> {
	const photos: Array<Photo> = []
	for (const [index, input] of inputs.entries()) {
		const id = newPhotoId()
		try {
			const processed = await processImage(await readSource(input), {
				creditExif: creditExifFor(options.config, options.now),
			})
			await saveMedia(storage, id, processed.files)
			const caption = input.caption?.trim()
			photos.push({
				id,
				source: 'stored',
				width: processed.width,
				height: processed.height,
				alt: input.alt?.trim() || caption || options.fallbackAlt,
				...(caption ? { caption } : {}),
				blurhash: processed.blurhash,
				lqip: processed.lqip,
				variants: processed.files.map((file) => file.variant),
				...(hasCredits(processed.credits)
					? { credits: processed.credits }
					: {}),
				addedAt: options.now,
			})
		} catch (error) {
			await discardMedia(storage, [...photos.map((photo) => photo.id), id])
			const reason = error instanceof Error ? error.message : String(error)
			throw new Error(`Photo ${index + 1} of ${inputs.length}: ${reason}`)
		}
	}
	return photos
}