Skip to content

Commit 1efef38

Browse files
authored
Merge pull request #19 from oriverk/dev
fix: fix embed content images
2 parents c4e8803 + 3e7ebdc commit 1efef38

File tree

49 files changed

+111
-64
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+111
-64
lines changed

.contents/card-links.json

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
{
2-
"https://oriverk.dev/blog/20240300-gfm-alerts/": {
3-
"title": "GFM Alerts記法のスニペットを設定する | oriverk.dev",
4-
"description": "",
5-
"image": "https://oriverk.dev/api/og/blog/20240300-gfm-alerts.png"
6-
},
72
"https://www.youtube.com/watch?v=ZXsQAXx_ao0": {
83
"title": "Shia LaBeouf \"Just Do It\" Motivational Speech (Original Video by LaBeouf, Rönkkö & Turner)",
94
"description": "Joshua Parker's segment from #INTRODUCTIONS (2015) by LaBeouf, Rönkkö & Turner http://labeoufronkkoturner.com Full 30-minute version: https://vimeo.com/12509...",
105
"image": "https://i.ytimg.com/vi/ZXsQAXx_ao0/maxresdefault.jpg"
116
},
7+
"https://oriverk.dev/blog/20240300-gfm-alerts/": {
8+
"title": "GFM Alerts記法のスニペットを設定する | oriverk.dev",
9+
"description": "",
10+
"image": "https://oriverk.dev/api/og/blog/20240300-gfm-alerts.webp"
11+
},
1212
"https://github.com/octocat/Hello-World/blob/master/README": {
1313
"title": "Hello-World/README at master · octocat/Hello-World",
1414
"description": "My first repository on GitHub! Contribute to octocat/Hello-World development by creating an account on GitHub.",
15-
"image": "https://opengraph.githubassets.com/672a894454a1838d578f8e26229dbfd8158d4889b334944ee8987d9951e366aa/octocat/Hello-World"
15+
"image": "https://opengraph.githubassets.com/520dceae5ded345e6c8fe143a140ba5152bb7031694d6f35f1a84ae01a9e6480/octocat/Hello-World"
1616
},
1717
"https://www.youtube.com/watch?v=dQw4w9WgXcQ": {
1818
"title": "Rick Astley - Never Gonna Give You Up (Official Music Video)",
1919
"description": "The official video for “Never Gonna Give You Up” by Rick Astley. The new album 'Are We There Yet?' is out now: Download here: https://RickAstley.lnk.to/AreWe...",
2020
"image": "https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg"
2121
}
22-
}
22+
}

src/pages/api/og/[...path].ts

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import fs from "node:fs";
2+
import * as nodePath from "node:path";
23
import { getBlog } from "@/utils/getBlog";
34
import { getOgImage } from "@/utils/getOgImage";
45
import { hashStringToSHA256 } from "@/utils/hashStringToSHA256";
@@ -8,13 +9,19 @@ import type {
89
GetStaticPaths,
910
InferGetStaticPropsType,
1011
} from "astro";
12+
import urlJoin from "url-join";
1113

1214
const blog = await getBlog();
15+
const extension: "jpg" | "png" | "webp" | "avif" = "webp";
16+
17+
export function getOgImageSrc(origin: string, pathname: string) {
18+
return urlJoin(origin, "api/og", `${pathname}.${extension}`)
19+
}
1320

1421
export const getStaticPaths = (async () => {
1522
const results = [...blog].map((post) => {
1623
const { collection, slug, data } = post;
17-
const path = `${collection}/${slug}`;
24+
const path = `${collection}/${slug}.${extension}`;
1825
return {
1926
params: { path },
2027
props: {
@@ -31,18 +38,13 @@ export const GET: APIRoute = async (context: APIContext) => {
3138
const { params, props } = context;
3239
const { path = "" } = params;
3340
const { title } = props as Props;
34-
const post = blog.find((post) => `${post.collection}/${post.slug}` === path);
41+
const post = blog.find((post) => `${post.collection}/${post.slug}.${extension}` === path);
3542
if (!post || !title) return new Response("Page not found", { status: 404 });
3643

3744
let imageBuffer: Buffer;
3845
const hash = await hashStringToSHA256(path);
39-
const imageDir = "./src/assets/images/og";
40-
const extension: "jpg" | "png" | "webp" | "avif" = "webp";
41-
const imagePath = `${imageDir}/${hash}.${extension}`;
42-
43-
if (!fs.existsSync(imageDir)) {
44-
fs.mkdirSync(imageDir);
45-
}
46+
const dirPath = nodePath.join(process.cwd(), "src/assets/images/og");
47+
const imagePath = nodePath.join(dirPath, `${hash}.${extension}`);
4648

4749
if (fs.existsSync(imagePath)) {
4850
imageBuffer = fs.readFileSync(imagePath);
@@ -53,7 +55,10 @@ export const GET: APIRoute = async (context: APIContext) => {
5355
debug: import.meta.env.DEV,
5456
});
5557
imageBuffer = result;
56-
fs.writeFileSync(imagePath, imageBuffer);
58+
59+
if (import.meta.env.PROD) {
60+
fs.writeFileSync(imagePath, imageBuffer);
61+
}
5762
}
5863

5964
return new Response(imageBuffer);

src/pages/blog/[...slug].astro

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import Toc from "@/components/ui/Toc/index.astro";
88
import Layout from "@/layouts/Layout.astro";
99
import { getBlog, getTocHierarchy } from "@/utils/getBlog";
1010
import type { GetStaticPaths, InferGetStaticPropsType } from "astro";
11-
import urlJoin from "url-join";
11+
import { getOgImageSrc } from "@/pages/api/og/[...path]";
1212
1313
export const getStaticPaths = (async () => {
1414
const blog = await getBlog();
@@ -23,9 +23,8 @@ export const getStaticPaths = (async () => {
2323
2424
type Props = InferGetStaticPropsType<typeof getStaticPaths>;
2525
const { post } = Astro.props as Props;
26-
const { id, slug, body, collection, render, data } = post;
27-
const place = `${collection}/${id}`;
28-
const { title, description, tags, create, update, image, published, noindex } =
26+
const { render, data } = post;
27+
const { title, description, tags, create, update, image, noindex } =
2928
data;
3029
const lastModified = update || create;
3130
const date = lastModified.toLocaleDateString("ja-JP", {
@@ -36,7 +35,8 @@ const date = lastModified.toLocaleDateString("ja-JP", {
3635
const isoDate = lastModified.toISOString();
3736
const { Content, headings } = await render();
3837
const toc = getTocHierarchy(headings);
39-
const ogImage = urlJoin(Astro.url.origin, "/api/og/blog", slug);
38+
const { origin, pathname } = Astro.url
39+
const ogImage = getOgImageSrc(origin, pathname)
4040
4141
export const components = {
4242
a: AstroLink,
@@ -51,7 +51,7 @@ export const components = {
5151
<h1>{title}</h1>
5252
<div class="info">
5353
<time datetime={isoDate}>{date}</time>
54-
{tags.length && (
54+
{!!tags.length && (
5555
<>
5656
<span>/</span>
5757
<div class="tags">

src/utils/feed.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
1+
import fs from "node:fs";
12
import type { FeedItem } from "@/types/feed";
2-
import FeedJson from "../../.contents/feed.json";
3+
4+
if (!fs.existsSync("./.contents/feed.json")) {
5+
fs.writeFileSync("./.contents/feed.json", "[]");
6+
}
37

48
export function getFeedItems() {
5-
const results: FeedItem[] = FeedJson;
9+
const results: FeedItem[] = JSON.parse(
10+
fs.readFileSync("./.contents/feed.json", { encoding: "utf-8" }),
11+
);
612
return results;
713
}
814

src/utils/getEmbedImageSrc.ts

Lines changed: 50 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,29 @@ const size = 400;
1515
// })
1616
// }
1717

18-
if (!fs.existsSync("./.contents")) {
19-
fs.mkdirSync("./.contents");
20-
}
21-
if (!fs.existsSync("./.contents/external-image.json")) {
22-
fs.writeFileSync("./.contents/external-image.json", "{}");
23-
}
24-
const externalImageJson: Record<string, string> = JSON.parse(
25-
fs.readFileSync("./.contents/external-image.json", { encoding: "utf-8" }),
26-
);
18+
// if (!fs.existsSync("./.contents")) {
19+
// fs.mkdirSync("./.contents");
20+
// }
21+
// if (!fs.existsSync("./.contents/external-image.json")) {
22+
// fs.writeFileSync("./.contents/external-image.json", "{}");
23+
// }
24+
// const externalImageJson: Record<string, string> = JSON.parse(
25+
// fs.readFileSync("./.contents/external-image.json", { encoding: "utf-8" }),
26+
// );
2727

2828
export async function getEmbedImageSrc(url: string) {
29-
let src = "";
29+
let result = "";
30+
const hash = await hashStringToSHA256(url);
31+
const generatedPath = path.join(
32+
process.cwd(),
33+
`src/assets/images/embed/${hash}.${extension}`,
34+
);
35+
console.log("generatedPath:", generatedPath);
36+
console.log("fs.existsSync(generatedPath):", fs.existsSync(generatedPath));
3037

31-
if (externalImageJson[url]) {
32-
src = externalImageJson[url];
33-
} else if (import.meta.env.PROD) {
34-
const hash = await hashStringToSHA256(url);
35-
const imagePath = path.join(publicPath, dir, `${hash}.${extension}`);
38+
if (fs.existsSync(generatedPath)) {
39+
result = generatedPath;
40+
} else {
3641
const response = await fetch(url);
3742
if (!response.ok) {
3843
throw new Error(
@@ -46,10 +51,35 @@ export async function getEmbedImageSrc(url: string) {
4651
quality,
4752
})
4853
.toBuffer();
49-
fs.writeFileSync(imagePath, imageBuffer);
50-
const result = `/assets/${hash}.${extension}`;
51-
return result;
52-
} else {
53-
return url;
54+
fs.writeFileSync(generatedPath, imageBuffer);
55+
result = generatedPath;
5456
}
57+
return result;
58+
59+
// let src = "";
60+
61+
// if (externalImageJson[url]) {
62+
// src = externalImageJson[url];
63+
// } else if (import.meta.env.PROD) {
64+
// const hash = await hashStringToSHA256(url);
65+
// const imagePath = path.join(publicPath, dir, `${hash}.${extension}`);
66+
// const response = await fetch(url);
67+
// if (!response.ok) {
68+
// throw new Error(
69+
// `Failed to fetch the image. Status code: ${response.status}`,
70+
// );
71+
// }
72+
// const buffer = await response.arrayBuffer();
73+
// const imageBuffer = await sharp(buffer)
74+
// .resize(size)
75+
// .toFormat(extension, {
76+
// quality,
77+
// })
78+
// .toBuffer();
79+
// fs.writeFileSync(imagePath, imageBuffer);
80+
// const result = `/assets/${hash}.${extension}`;
81+
// return result;
82+
// } else {
83+
// return url;
84+
// }
5585
}

src/utils/getSiteMetadata.ts

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,16 @@
11
import fs from "node:fs";
22
import type { CardLinkEmbedType } from "@/types/oembed";
33
import fetchSiteMetadata from "fetch-site-metadata";
4-
import { getEmbedImageSrc } from "./getEmbedImageSrc";
54

65
const dir = "./.contents";
76
const jsonPath = `${dir}/card-links.json`;
8-
if (!fs.existsSync(dir)) {
9-
fs.mkdirSync(dir);
10-
}
117
if (!fs.existsSync(jsonPath)) {
128
fs.writeFileSync(jsonPath, JSON.stringify({}, null, 2));
139
}
1410

15-
const jsonString = fs.readFileSync("./.contents/card-links.json", {
16-
encoding: "utf-8",
17-
});
18-
const linksJson: Record<string, CardLinkEmbedType> = JSON.parse(jsonString);
11+
const linksJson: Record<string, CardLinkEmbedType> = JSON.parse(
12+
fs.readFileSync("./.contents/card-links.json", { encoding: "utf-8" }),
13+
);
1914

2015
export async function getSiteMetadata(url: string) {
2116
let result: CardLinkEmbedType;
@@ -28,7 +23,6 @@ export async function getSiteMetadata(url: string) {
2823
image,
2924
};
3025
} else {
31-
console.log("now fetching site metadata...");
3226
const {
3327
title = "",
3428
description = "",
@@ -46,10 +40,6 @@ export async function getSiteMetadata(url: string) {
4640
}
4741
}
4842

49-
// if(result.image){
50-
// const hoge = await getEmbedImageSrc(result.image)
51-
// }
52-
5343
return {
5444
src: url,
5545
...result,

src/utils/github/getUserContent.ts

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,31 @@
1+
import fs from "node:fs";
12
import type { UserContent } from "@/types/github";
2-
import contributionsJson from "../../../.contents/contributions.json";
3-
import repositoryJson from "../../../.contents/repository.json";
3+
import type { ContributionsCollection } from "@octokit/graphql-schema";
4+
5+
const repositoryJsonPath = "./.contents/repository.json";
6+
const contributionsJsonPath = "./.contents/contributions.json";
7+
8+
if (!fs.existsSync(contributionsJsonPath)) {
9+
fs.writeFileSync(contributionsJsonPath, "{}");
10+
}
11+
12+
if (!fs.existsSync(repositoryJsonPath)) {
13+
fs.writeFileSync(repositoryJsonPath, "[]");
14+
}
415

516
export function getUserContent(): UserContent {
17+
const repositoryJson: UserContent["repositoryItems"] = JSON.parse(
18+
fs.readFileSync(repositoryJsonPath, { encoding: "utf-8" }),
19+
);
20+
const contributionsJson: Pick<
21+
ContributionsCollection,
22+
"contributionCalendar"
23+
> = JSON.parse(fs.readFileSync(contributionsJsonPath, { encoding: "utf-8" }));
24+
625
const repositoryItems: UserContent["repositoryItems"] = repositoryJson.filter(
726
(repo) => !repo.isFork,
827
);
9-
const { contributionCalendar } = contributionsJson as unknown as Pick<
10-
UserContent,
11-
"contributionCalendar"
12-
>;
28+
const { contributionCalendar } = contributionsJson;
1329

1430
return {
1531
repositoryItems,

0 commit comments

Comments
 (0)