Files
gerbeur/api/middleware/og.ts
khannurien 1cb904d2cf
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 47s
v3: generated placeholder thumbnails for pages with no preview image, and a fix for hotlink-protected ones
Thumbnails were failing in two different ways that both ended as an empty box.

Cloudflare hotlink protection answers a cross-site Referer with 403, so images
we had extracted correctly (dles.aukspot.com's og:image among them) never
rendered — every onError handler set display:none and swallowed it. The new
Thumbnail component loads with referrerPolicy="no-referrer", retries once
through /api/proxy-image for hosts that reject an empty referrer too, and only
then falls back to a placeholder.

Separately, the extraction cascade ended at the page's icon and then a guessed
/favicon.ico, so thumbnailUrl was almost never empty — just a 16x16 icon
cover-cropped into a 128x72 box. It now stops at real artwork, with faviconUrl
and accentColor (theme-color / msapplication-TileColor / mask-icon) as their own
fields. An absent thumbnailUrl finally means "no artwork", which is what makes
the placeholder possible: the site's own color mixed into the theme surface,
with its favicon centered on it, or its initial. Contrast holds for any
third-party color by construction rather than by luminance math, so nyt only
has to set --thumb-tint-strength to 0% to stay monochrome and geocities only
has to raise it. Missing accents fall back to a stable hostname-derived hue, so
rows saved before this get a tint with no backfill.

Migration 0011 reclassifies favicon-shaped thumbnailUrls on existing dumps.
The journal mosaic keeps its pull-quote and text fallbacks — the placeholder
appears there only to repair a broken image.

Also fixed: refresh silently overwrote good metadata with a failure stub, the
refresh button swallowed every error, refresh never broadcast the update,
extractBestIcon ranked SVG icons below 16x16 PNGs, and shared links with no
artwork carried no og:image at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 19:43:55 +00:00

161 lines
5.0 KiB
TypeScript

import { Context, Next } from "@oak/oak";
import { getDump } from "../services/dump-service.ts";
import { getUserByUsername } from "../services/user-service.ts";
import { getPlaylistById } from "../services/playlist-service.ts";
import { OG_SITE_NAME, SITE_EMOJI } from "../config.ts";
import { emojiToCodepoint } from "../lib/site-icons.ts";
const ICON_VERSION = emojiToCodepoint(SITE_EMOJI);
interface OGMeta {
title: string;
description?: string;
imageUrl?: string;
/** True only for real artwork — a square site icon must not claim a wide card. */
imageIsWide?: boolean;
url: string;
}
function escapeAttr(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
function buildTags(meta: OGMeta): string {
const card = meta.imageUrl && meta.imageIsWide
? "summary_large_image"
: "summary";
const tags = [
`<title>${escapeAttr(meta.title)}</title>`,
`<meta property="og:site_name" content="${OG_SITE_NAME}" />`,
`<meta property="og:type" content="website" />`,
`<meta property="og:url" content="${escapeAttr(meta.url)}" />`,
`<meta property="og:title" content="${escapeAttr(meta.title)}" />`,
`<meta name="twitter:card" content="${card}" />`,
];
if (meta.description) {
tags.push(
`<meta name="description" content="${escapeAttr(meta.description)}" />`,
`<meta property="og:description" content="${
escapeAttr(meta.description)
}" />`,
);
}
if (meta.imageUrl) {
tags.push(
`<meta property="og:image" content="${escapeAttr(meta.imageUrl)}" />`,
);
}
return tags.join("\n ");
}
function inject(html: string, meta: OGMeta): string {
return html
.replace(/<title>[^<]*<\/title>/, "")
.replace("</head>", ` ${buildTags(meta)}\n </head>`);
}
let cachedHtml: string | null | undefined; // undefined = not yet loaded, null = not found
async function loadIndexHtml(): Promise<string | null> {
if (cachedHtml !== undefined) return cachedHtml;
for (
const path of [`${Deno.cwd()}/dist/index.html`, `${Deno.cwd()}/index.html`]
) {
try {
cachedHtml = (await Deno.readTextFile(path))
.replaceAll("__SITE_NAME__", OG_SITE_NAME)
.replaceAll("__SITE_EMOJI__", SITE_EMOJI)
.replaceAll("__ICON_VERSION__", ICON_VERSION);
return cachedHtml;
} catch {
continue;
}
}
cachedHtml = null;
return null;
}
const DUMP_RE = /^\/dumps\/([^/]+)$/;
// Allow an optional `/~/<tab>` suffix so linkable profile tabs keep OG meta.
const USER_RE = /^\/users\/([^/]+)(?:\/~\/[^/]+)?$/;
const PLAYLIST_RE = /^\/playlists\/([^/]+)$/;
export async function ogMiddleware(ctx: Context, next: Next) {
const { pathname } = ctx.request.url;
if (pathname.startsWith("/api/") || pathname.includes(".")) {
return await next();
}
const origin = ctx.request.url.origin;
const pageUrl = `${origin}${pathname}`;
let meta: OGMeta | null = null;
const dumpMatch = pathname.match(DUMP_RE);
const userMatch = pathname.match(USER_RE);
const playlistMatch = pathname.match(PLAYLIST_RE);
if (dumpMatch) {
try {
const dump = getDump(dumpMatch[1]);
let imageUrl: string | undefined;
if (dump.kind === "file" && dump.fileMime?.startsWith("image/")) {
imageUrl = `${origin}/api/files/${dump.id}`;
} else if (dump.richContent?.thumbnailUrl) {
imageUrl = dump.richContent.thumbnailUrl;
}
// No artwork: fall back to our own site icon rather than the target's
// favicon, which is typically too small to survive a social card (and may
// be hotlink-protected).
meta = {
title: dump.title,
description: dump.comment,
imageUrl: imageUrl ?? `${origin}/apple-touch-icon.png`,
imageIsWide: !!imageUrl,
url: pageUrl,
};
} catch { /* not found or private — serve default */ }
} else if (userMatch) {
try {
const user = getUserByUsername(userMatch[1]);
const imageUrl = user.avatarMime
? `${origin}/api/avatars/${user.id}`
: undefined;
meta = {
title: user.username,
description: user.description,
imageUrl: imageUrl ?? `${origin}/apple-touch-icon.png`,
url: pageUrl,
};
} catch { /* not found */ }
} else if (playlistMatch) {
try {
const playlist = getPlaylistById(playlistMatch[1]);
if (playlist.isPublic) {
const imageUrl = playlist.imageMime
? `${origin}/api/playlists/${playlist.id}/image`
: undefined;
meta = {
title: playlist.title,
description: playlist.description,
imageUrl: imageUrl ?? `${origin}/apple-touch-icon.png`,
url: pageUrl,
};
}
} catch { /* not found or private */ }
}
if (!meta) return await next();
const html = await loadIndexHtml();
if (!html) return await next();
ctx.response.headers.set("Content-Type", "text/html; charset=utf-8");
ctx.response.body = inject(html, meta);
}