Skip to content

Commit

Permalink
Merge pull request #19 from oriverk/dev
Browse files Browse the repository at this point in the history
fix: fix embed content images
  • Loading branch information
oriverk authored Apr 21, 2024
2 parents c4e8803 + 3e7ebdc commit 1efef38
Show file tree
Hide file tree
Showing 49 changed files with 111 additions and 64 deletions.
14 changes: 7 additions & 7 deletions .contents/card-links.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
{
"https://oriverk.dev/blog/20240300-gfm-alerts/": {
"title": "GFM Alerts記法のスニペットを設定する | oriverk.dev",
"description": "",
"image": "https://oriverk.dev/api/og/blog/20240300-gfm-alerts.png"
},
"https://www.youtube.com/watch?v=ZXsQAXx_ao0": {
"title": "Shia LaBeouf \"Just Do It\" Motivational Speech (Original Video by LaBeouf, Rönkkö & Turner)",
"description": "Joshua Parker's segment from #INTRODUCTIONS (2015) by LaBeouf, Rönkkö & Turner http://labeoufronkkoturner.com Full 30-minute version: https://vimeo.com/12509...",
"image": "https://i.ytimg.com/vi/ZXsQAXx_ao0/maxresdefault.jpg"
},
"https://oriverk.dev/blog/20240300-gfm-alerts/": {
"title": "GFM Alerts記法のスニペットを設定する | oriverk.dev",
"description": "",
"image": "https://oriverk.dev/api/og/blog/20240300-gfm-alerts.webp"
},
"https://github.com/octocat/Hello-World/blob/master/README": {
"title": "Hello-World/README at master · octocat/Hello-World",
"description": "My first repository on GitHub! Contribute to octocat/Hello-World development by creating an account on GitHub.",
"image": "https://opengraph.githubassets.com/672a894454a1838d578f8e26229dbfd8158d4889b334944ee8987d9951e366aa/octocat/Hello-World"
"image": "https://opengraph.githubassets.com/520dceae5ded345e6c8fe143a140ba5152bb7031694d6f35f1a84ae01a9e6480/octocat/Hello-World"
},
"https://www.youtube.com/watch?v=dQw4w9WgXcQ": {
"title": "Rick Astley - Never Gonna Give You Up (Official Music Video)",
"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...",
"image": "https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg"
}
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
25 changes: 15 additions & 10 deletions src/pages/api/og/[...path].ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fs from "node:fs";
import * as nodePath from "node:path";
import { getBlog } from "@/utils/getBlog";
import { getOgImage } from "@/utils/getOgImage";
import { hashStringToSHA256 } from "@/utils/hashStringToSHA256";
Expand All @@ -8,13 +9,19 @@ import type {
GetStaticPaths,
InferGetStaticPropsType,
} from "astro";
import urlJoin from "url-join";

const blog = await getBlog();
const extension: "jpg" | "png" | "webp" | "avif" = "webp";

export function getOgImageSrc(origin: string, pathname: string) {
return urlJoin(origin, "api/og", `${pathname}.${extension}`)
}

export const getStaticPaths = (async () => {
const results = [...blog].map((post) => {
const { collection, slug, data } = post;
const path = `${collection}/${slug}`;
const path = `${collection}/${slug}.${extension}`;
return {
params: { path },
props: {
Expand All @@ -31,18 +38,13 @@ export const GET: APIRoute = async (context: APIContext) => {
const { params, props } = context;
const { path = "" } = params;
const { title } = props as Props;
const post = blog.find((post) => `${post.collection}/${post.slug}` === path);
const post = blog.find((post) => `${post.collection}/${post.slug}.${extension}` === path);
if (!post || !title) return new Response("Page not found", { status: 404 });

let imageBuffer: Buffer;
const hash = await hashStringToSHA256(path);
const imageDir = "./src/assets/images/og";
const extension: "jpg" | "png" | "webp" | "avif" = "webp";
const imagePath = `${imageDir}/${hash}.${extension}`;

if (!fs.existsSync(imageDir)) {
fs.mkdirSync(imageDir);
}
const dirPath = nodePath.join(process.cwd(), "src/assets/images/og");
const imagePath = nodePath.join(dirPath, `${hash}.${extension}`);

if (fs.existsSync(imagePath)) {
imageBuffer = fs.readFileSync(imagePath);
Expand All @@ -53,7 +55,10 @@ export const GET: APIRoute = async (context: APIContext) => {
debug: import.meta.env.DEV,
});
imageBuffer = result;
fs.writeFileSync(imagePath, imageBuffer);

if (import.meta.env.PROD) {
fs.writeFileSync(imagePath, imageBuffer);
}
}

return new Response(imageBuffer);
Expand Down
12 changes: 6 additions & 6 deletions src/pages/blog/[...slug].astro
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Toc from "@/components/ui/Toc/index.astro";
import Layout from "@/layouts/Layout.astro";
import { getBlog, getTocHierarchy } from "@/utils/getBlog";
import type { GetStaticPaths, InferGetStaticPropsType } from "astro";
import urlJoin from "url-join";
import { getOgImageSrc } from "@/pages/api/og/[...path]";
export const getStaticPaths = (async () => {
const blog = await getBlog();
Expand All @@ -23,9 +23,8 @@ export const getStaticPaths = (async () => {
type Props = InferGetStaticPropsType<typeof getStaticPaths>;
const { post } = Astro.props as Props;
const { id, slug, body, collection, render, data } = post;
const place = `${collection}/${id}`;
const { title, description, tags, create, update, image, published, noindex } =
const { render, data } = post;
const { title, description, tags, create, update, image, noindex } =
data;
const lastModified = update || create;
const date = lastModified.toLocaleDateString("ja-JP", {
Expand All @@ -36,7 +35,8 @@ const date = lastModified.toLocaleDateString("ja-JP", {
const isoDate = lastModified.toISOString();
const { Content, headings } = await render();
const toc = getTocHierarchy(headings);
const ogImage = urlJoin(Astro.url.origin, "/api/og/blog", slug);
const { origin, pathname } = Astro.url
const ogImage = getOgImageSrc(origin, pathname)
export const components = {
a: AstroLink,
Expand All @@ -51,7 +51,7 @@ export const components = {
<h1>{title}</h1>
<div class="info">
<time datetime={isoDate}>{date}</time>
{tags.length && (
{!!tags.length && (
<>
<span>/</span>
<div class="tags">
Expand Down
10 changes: 8 additions & 2 deletions src/utils/feed.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import fs from "node:fs";
import type { FeedItem } from "@/types/feed";
import FeedJson from "../../.contents/feed.json";

if (!fs.existsSync("./.contents/feed.json")) {
fs.writeFileSync("./.contents/feed.json", "[]");
}

export function getFeedItems() {
const results: FeedItem[] = FeedJson;
const results: FeedItem[] = JSON.parse(
fs.readFileSync("./.contents/feed.json", { encoding: "utf-8" }),
);
return results;
}

Expand Down
70 changes: 50 additions & 20 deletions src/utils/getEmbedImageSrc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,29 @@ const size = 400;
// })
// }

if (!fs.existsSync("./.contents")) {
fs.mkdirSync("./.contents");
}
if (!fs.existsSync("./.contents/external-image.json")) {
fs.writeFileSync("./.contents/external-image.json", "{}");
}
const externalImageJson: Record<string, string> = JSON.parse(
fs.readFileSync("./.contents/external-image.json", { encoding: "utf-8" }),
);
// if (!fs.existsSync("./.contents")) {
// fs.mkdirSync("./.contents");
// }
// if (!fs.existsSync("./.contents/external-image.json")) {
// fs.writeFileSync("./.contents/external-image.json", "{}");
// }
// const externalImageJson: Record<string, string> = JSON.parse(
// fs.readFileSync("./.contents/external-image.json", { encoding: "utf-8" }),
// );

export async function getEmbedImageSrc(url: string) {
let src = "";
let result = "";
const hash = await hashStringToSHA256(url);
const generatedPath = path.join(
process.cwd(),
`src/assets/images/embed/${hash}.${extension}`,
);
console.log("generatedPath:", generatedPath);
console.log("fs.existsSync(generatedPath):", fs.existsSync(generatedPath));

if (externalImageJson[url]) {
src = externalImageJson[url];
} else if (import.meta.env.PROD) {
const hash = await hashStringToSHA256(url);
const imagePath = path.join(publicPath, dir, `${hash}.${extension}`);
if (fs.existsSync(generatedPath)) {
result = generatedPath;
} else {
const response = await fetch(url);
if (!response.ok) {
throw new Error(
Expand All @@ -46,10 +51,35 @@ export async function getEmbedImageSrc(url: string) {
quality,
})
.toBuffer();
fs.writeFileSync(imagePath, imageBuffer);
const result = `/assets/${hash}.${extension}`;
return result;
} else {
return url;
fs.writeFileSync(generatedPath, imageBuffer);
result = generatedPath;
}
return result;

// let src = "";

// if (externalImageJson[url]) {
// src = externalImageJson[url];
// } else if (import.meta.env.PROD) {
// const hash = await hashStringToSHA256(url);
// const imagePath = path.join(publicPath, dir, `${hash}.${extension}`);
// const response = await fetch(url);
// if (!response.ok) {
// throw new Error(
// `Failed to fetch the image. Status code: ${response.status}`,
// );
// }
// const buffer = await response.arrayBuffer();
// const imageBuffer = await sharp(buffer)
// .resize(size)
// .toFormat(extension, {
// quality,
// })
// .toBuffer();
// fs.writeFileSync(imagePath, imageBuffer);
// const result = `/assets/${hash}.${extension}`;
// return result;
// } else {
// return url;
// }
}
16 changes: 3 additions & 13 deletions src/utils/getSiteMetadata.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
import fs from "node:fs";
import type { CardLinkEmbedType } from "@/types/oembed";
import fetchSiteMetadata from "fetch-site-metadata";
import { getEmbedImageSrc } from "./getEmbedImageSrc";

const dir = "./.contents";
const jsonPath = `${dir}/card-links.json`;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
if (!fs.existsSync(jsonPath)) {
fs.writeFileSync(jsonPath, JSON.stringify({}, null, 2));
}

const jsonString = fs.readFileSync("./.contents/card-links.json", {
encoding: "utf-8",
});
const linksJson: Record<string, CardLinkEmbedType> = JSON.parse(jsonString);
const linksJson: Record<string, CardLinkEmbedType> = JSON.parse(
fs.readFileSync("./.contents/card-links.json", { encoding: "utf-8" }),
);

export async function getSiteMetadata(url: string) {
let result: CardLinkEmbedType;
Expand All @@ -28,7 +23,6 @@ export async function getSiteMetadata(url: string) {
image,
};
} else {
console.log("now fetching site metadata...");
const {
title = "",
description = "",
Expand All @@ -46,10 +40,6 @@ export async function getSiteMetadata(url: string) {
}
}

// if(result.image){
// const hoge = await getEmbedImageSrc(result.image)
// }

return {
src: url,
...result,
Expand Down
28 changes: 22 additions & 6 deletions src/utils/github/getUserContent.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,31 @@
import fs from "node:fs";
import type { UserContent } from "@/types/github";
import contributionsJson from "../../../.contents/contributions.json";
import repositoryJson from "../../../.contents/repository.json";
import type { ContributionsCollection } from "@octokit/graphql-schema";

const repositoryJsonPath = "./.contents/repository.json";
const contributionsJsonPath = "./.contents/contributions.json";

if (!fs.existsSync(contributionsJsonPath)) {
fs.writeFileSync(contributionsJsonPath, "{}");
}

if (!fs.existsSync(repositoryJsonPath)) {
fs.writeFileSync(repositoryJsonPath, "[]");
}

export function getUserContent(): UserContent {
const repositoryJson: UserContent["repositoryItems"] = JSON.parse(
fs.readFileSync(repositoryJsonPath, { encoding: "utf-8" }),
);
const contributionsJson: Pick<
ContributionsCollection,
"contributionCalendar"
> = JSON.parse(fs.readFileSync(contributionsJsonPath, { encoding: "utf-8" }));

const repositoryItems: UserContent["repositoryItems"] = repositoryJson.filter(
(repo) => !repo.isFork,
);
const { contributionCalendar } = contributionsJson as unknown as Pick<
UserContent,
"contributionCalendar"
>;
const { contributionCalendar } = contributionsJson;

return {
repositoryItems,
Expand Down

0 comments on commit 1efef38

Please sign in to comment.