notion.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import { cache } from "react";
  2. import { NotionAPI } from "notion-client";
  3. import { Block, ExtendedRecordMap } from "notion-types";
  4. import { getBlockValue, getPageTitle } from "notion-utils";
  5. import { Blog } from "@/types/blog";
  6. import { notionBlogConfig } from "@/config/site";
  7. import type { Locale } from "@/lib/i18n";
  8. // notion-client 8 sends a browser-acceptable User-Agent and understands Notion's
  9. // nested { value: { value, role } } block entries, so no workarounds are needed.
  10. const notion = new NotionAPI();
  11. /** A block's value, whether Notion returned it flat or nested. */
  12. export const blockOf = (
  13. entry: ExtendedRecordMap["block"][string] | undefined,
  14. ) => getBlockValue<Block>(entry);
  15. export const getPageContent = cache(async (pageId: string) => {
  16. const recordMap = await notion.getPage(pageId);
  17. const title = getPageTitle(recordMap);
  18. const blocks = recordMap.block;
  19. return { title, blocks, recordMap };
  20. });
  21. export async function getAllBlogPosts(pageId: string) {
  22. const recordMap = await notion.getPage(pageId);
  23. const blocks = recordMap.block;
  24. const blogPosts: Blog[] = [];
  25. Object.entries(blocks).forEach(([key, value]) => {
  26. const block = blockOf(value);
  27. if (
  28. !block ||
  29. key === notionBlogConfig.blogParentId ||
  30. block.type !== "page" ||
  31. !block.properties?.title ||
  32. // Only the Blog page's own children: a post's translation is a page too.
  33. block.parent_id !== pageId
  34. ) {
  35. return;
  36. }
  37. blogPosts.push({
  38. id: key,
  39. block,
  40. pageCover: block.format?.page_cover ?? "",
  41. title: block.properties.title[0][0],
  42. createdAt: block.created_time ? new Date(block.created_time) : null,
  43. lastEditedAt: block.last_edited_time
  44. ? new Date(block.last_edited_time)
  45. : null,
  46. description:
  47. (block.properties as Record<string, unknown[][]>)?.[
  48. "\\u2O5F"
  49. ]?.[0]?.[0]?.toString() ?? "",
  50. });
  51. });
  52. blogPosts.sort(
  53. (a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0),
  54. );
  55. return blogPosts;
  56. }
  57. const CJK = /[\u3400-\u9fff]/;
  58. const plainTitle = (block: Block | undefined) =>
  59. (block?.properties?.title as string[][] | undefined)
  60. ?.map((chunk) => chunk[0])
  61. .join("") ?? "";
  62. /**
  63. * A post's Chinese version: a sub-page inside the post with a Chinese title.
  64. * An empty sub-page translates only the title (for posts that are all photos).
  65. */
  66. export function findTranslation(
  67. post: Block | undefined,
  68. blocks: ExtendedRecordMap["block"],
  69. ) {
  70. for (const id of post?.content ?? []) {
  71. const block = blockOf(blocks[id]);
  72. const title = plainTitle(block);
  73. if (block?.type === "page" && CJK.test(title)) {
  74. return { id, title, empty: !block.content?.length };
  75. }
  76. }
  77. return null;
  78. }
  79. /** The recordMap with one child taken out of a block, so the page renders without it. */
  80. function withoutChild(
  81. recordMap: ExtendedRecordMap,
  82. parentId: string,
  83. childId: string,
  84. ): ExtendedRecordMap {
  85. const entry = structuredClone(recordMap.block[parentId]);
  86. const parent = blockOf(entry);
  87. if (parent?.content) {
  88. parent.content = parent.content.filter((id) => id !== childId);
  89. }
  90. return { ...recordMap, block: { ...recordMap.block, [parentId]: entry } };
  91. }
  92. /**
  93. * A post in the given language. The URL always uses the original post's id; in
  94. * Chinese the content comes from its translation when it has one, and the
  95. * original (marked untranslated) when it doesn't.
  96. */
  97. export const getPost = cache(async (lang: Locale, postId: string) => {
  98. const { recordMap, title } = await getPageContent(postId);
  99. const block = blockOf(recordMap.block[postId]);
  100. const translation = findTranslation(block, recordMap.block);
  101. const original = translation
  102. ? withoutChild(recordMap, postId, translation.id)
  103. : recordMap;
  104. const base = { block, recordMap: original, rootPageId: postId };
  105. if (lang === "en") return { ...base, title, translated: true };
  106. if (!translation) return { ...base, title, translated: false };
  107. if (translation.empty) {
  108. return { ...base, title: translation.title, translated: true };
  109. }
  110. const zh = await getPageContent(translation.id);
  111. return {
  112. block,
  113. recordMap: zh.recordMap,
  114. rootPageId: translation.id,
  115. title: translation.title,
  116. translated: true,
  117. };
  118. });
  119. /**
  120. * Every post, titled in the given language. Chinese titles come from the
  121. * translations: the posts' child blocks are fetched in a few batches rather
  122. * than loading every post (Notion throttles a burst of whole pages).
  123. */
  124. export async function getBlogPosts(lang: Locale) {
  125. const posts = await getAllBlogPosts(notionBlogConfig.blogParentId);
  126. if (lang === "en") return posts;
  127. const ids = posts.flatMap((post) => post.block.content ?? []);
  128. const batches = Array.from({ length: Math.ceil(ids.length / 100) }, (_, i) =>
  129. ids.slice(i * 100, (i + 1) * 100),
  130. );
  131. try {
  132. const chunks = await Promise.all(
  133. batches.map((batch) => notion.getBlocks(batch)),
  134. );
  135. const blocks = Object.assign(
  136. {},
  137. ...chunks.map((chunk) => chunk.recordMap.block),
  138. ) as ExtendedRecordMap["block"];
  139. return posts.map((post) => {
  140. const translation = findTranslation(post.block, blocks);
  141. return translation ? { ...post, title: translation.title } : post;
  142. });
  143. } catch (error) {
  144. console.error("Failed to load post translations", error);
  145. return posts;
  146. }
  147. }
  148. /** Extract a plain-text excerpt from a Notion recordMap (first ~160 chars). */
  149. export function extractDescription(recordMap: ExtendedRecordMap): string {
  150. const blocks = Object.values(recordMap.block);
  151. for (const block of blocks) {
  152. const value = blockOf(block);
  153. if (!value) continue;
  154. if (value.type !== "text" && value.type !== "quote") continue;
  155. const text = value.properties?.title
  156. ?.map((chunk: unknown[]) => chunk[0])
  157. .join("")
  158. .trim();
  159. if (text && text.length > 0) {
  160. return text.length > 160 ? text.slice(0, 157) + "..." : text;
  161. }
  162. }
  163. return "";
  164. }
  165. export const customMapImageUrl = (url: string, block: Block): string => {
  166. if (!url) {
  167. throw new Error("URL can't be empty");
  168. }
  169. if (url.startsWith("data:")) {
  170. return url;
  171. } // more recent versions of notion don't proxy unsplash images
  172. if (url.startsWith("https://images.unsplash.com")) {
  173. return url;
  174. }
  175. try {
  176. const u = new URL(url);
  177. if (
  178. u.pathname.startsWith("/secure.notion-static.com") &&
  179. u.hostname.endsWith(".amazonaws.com")
  180. ) {
  181. if (
  182. u.searchParams.has("X-Amz-Credential") &&
  183. u.searchParams.has("X-Amz-Signature") &&
  184. u.searchParams.has("X-Amz-Algorithm")
  185. ) {
  186. // if the URL is already signed, then use it as-is
  187. url = u.origin + u.pathname;
  188. }
  189. }
  190. } catch {
  191. // ignore invalid urls
  192. }
  193. if (url.startsWith("/images")) {
  194. url = `https://www.notion.so${url}`;
  195. }
  196. url = `https://www.notion.so${
  197. url.startsWith("/image") ? url : `/image/${encodeURIComponent(url)}`
  198. }`;
  199. const notionImageUrlV2 = new URL(url);
  200. let table = block.parent_table === "space" ? "block" : block.parent_table;
  201. if (table === "collection" || table === "team") {
  202. table = "block";
  203. }
  204. notionImageUrlV2.searchParams.set("table", table);
  205. notionImageUrlV2.searchParams.set("id", block.id);
  206. notionImageUrlV2.searchParams.set("cache", "v2");
  207. url = notionImageUrlV2.toString();
  208. return url;
  209. };
  210. const NOTION_HOST =
  211. /(^|\.)(notion\.so|notion\.com|notion-static\.com|notionusercontent\.com|amazonaws\.com)$/;
  212. /**
  213. * A page cover's URL. Covers linked from other sites (Wikimedia, Unsplash, ...)
  214. * load from where they live: Notion's image proxy gets rate-limited by some of
  215. * them. Covers uploaded to Notion still go through Notion.
  216. */
  217. export const coverImageUrl = (url: string, block: Block): string => {
  218. try {
  219. const { protocol, hostname } = new URL(url);
  220. if (protocol === "https:" && !NOTION_HOST.test(hostname)) return url;
  221. } catch {
  222. // A Notion path such as /images/page-cover/..., handled below.
  223. }
  224. return customMapImageUrl(url, block);
  225. };