Skip to content

Commit

Permalink
🚑 特殊文字がTofuになる
Browse files Browse the repository at this point in the history
  • Loading branch information
arrow2nd committed Nov 23, 2023
1 parent ef11e9f commit 0906380
Showing 1 changed file with 47 additions and 6 deletions.
53 changes: 47 additions & 6 deletions app/[id]/opengraph-image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { getPoem, splitPoemText } from "libs/utils";

import { SiteInfo } from "data/site";

import { Poem } from "types/poem";

export const runtime = "edge";

export const alt = SiteInfo.description;
Expand All @@ -22,17 +24,19 @@ export default async function Image({ params }: { params: { id: string } }) {
});
}

const kiwiMaru = fetch(
new URL(
"https://fonts.bunny.net/kiwi-maru/files/kiwi-maru-japanese-400-normal.woff"
)
).then((res) => res.arrayBuffer());
const kiwiMaru = await fetchFont(poem);
if (!kiwiMaru) {
return new Response("Failed to fetch font", {
status: 500
});
}

const lines = splitPoemText(poem.text);

return new ImageResponse(
(
<div
lang="ja-JP"
style={{
color: "#4C7ABE",
width: "100%",
Expand Down Expand Up @@ -76,10 +80,47 @@ export default async function Image({ params }: { params: { id: string } }) {
fonts: [
{
name: "Kiwi Maru",
data: await kiwiMaru,
data: kiwiMaru,
style: "normal"
}
]
}
);
}

/**
* Google Fonts からポエムの表示に必要なフォントを取得する
* 参考: https://github.com/vercel/satori/blob/29fe2e4a9676a1ba41c361ec1a547d6de329b039/playground/pages/api/font.ts#L86
* @param poem ポエム
* @returns フォントデータ
*/
async function fetchFont({
clothesName,
idolName,
text
}: Poem): Promise<ArrayBuffer | null> {
// Kiwi Maru
const API = `https://fonts.googleapis.com/css2?family=Kiwi+Maru&text=${encodeURIComponent(
clothesName + idolName + text
)}`;

const css = await (
await fetch(API, {
headers: {
// Make sure it returns TTF.
"User-Agent":
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1"
}
})
).text();

const resource = css.match(
/src: url\((.+)\) format\('(opentype|truetype)'\)/
);

if (!resource) return null;

const res = await fetch(resource[1]);

return res.arrayBuffer();
}

0 comments on commit 0906380

Please sign in to comment.