Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 11x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 2x | import { eq } from 'drizzle-orm';
import { generatedAvatarSVG } from '../avatars.ts';
import { openDatabase } from '../db/client.ts';
import { profile } from '../db/schema.ts';
import { resolveFormerHandle } from '../profiles.ts';
import type { PageContext } from './page.ts';
/** Icons change rarely and their URLs carry a version, so caches keep them a day. */
const AVATAR_CACHE = 'public, max-age=86400';
/** The same URL with the player's former handle replaced by the current one (query kept). */
export function movedTo(requestURL: string, former: string, current: string): string {
const url = new URL(requestURL);
const from = `/players/${encodeURIComponent(former)}`;
const to = `/players/${encodeURIComponent(current)}`;
return `${url.pathname.replace(from, to)}${url.search}`;
}
/** A player's icon: the uploaded image from R2, or the one generated from the account. */
export async function avatarImage(c: PageContext<'/players/:handle/avatar'>) {
const db = openDatabase(c.env.DB);
const handle = c.req.param('handle');
const found = await db.query.profile.findFirst({
where: eq(profile.handle, handle.toLowerCase()),
columns: { userId: true, avatarKey: true },
});
Iif (found === undefined) {
const current = await resolveFormerHandle(db, handle);
if (current !== undefined) return c.redirect(movedTo(c.req.url, handle, current), 301);
return c.body('Not Found', 404);
}
Iif (found.avatarKey?.startsWith('https://')) {
c.header('cache-control', 'public, max-age=300');
return c.redirect(found.avatarKey, 302);
}
if (found.avatarKey !== null) {
const object = await c.env.BLOBS.get(found.avatarKey);
Eif (object !== null) {
return c.body(object.body, 200, {
'content-type': object.httpMetadata?.contentType ?? 'application/octet-stream',
'cache-control': AVATAR_CACHE,
'x-content-type-options': 'nosniff',
});
}
}
return c.body(generatedAvatarSVG(found.userId), 200, {
'content-type': 'image/svg+xml',
'cache-control': AVATAR_CACHE,
});
}
|