From e64c34adea6ad918511f26c8c22ff76500d51ba3 Mon Sep 17 00:00:00 2001
From: Madeline <46743919+MaddyUnderStars@users.noreply.github.com>
Date: Sun, 3 Sep 2023 14:17:11 +1000
Subject: Rewrite thumbnail/image generation for embeds
---
src/api/util/utility/EmbedHandlers.ts | 148 +++++++++++++++-------------------
1 file changed, 65 insertions(+), 83 deletions(-)
(limited to 'src')
diff --git a/src/api/util/utility/EmbedHandlers.ts b/src/api/util/utility/EmbedHandlers.ts
index af01a32f..b1e6b866 100644
--- a/src/api/util/utility/EmbedHandlers.ts
+++ b/src/api/util/utility/EmbedHandlers.ts
@@ -16,7 +16,7 @@
along with this program. If not, see .
*/
-import { Config, Embed, EmbedType } from "@spacebar/util";
+import { Config, Embed, EmbedImage, EmbedType } from "@spacebar/util";
import * as cheerio from "cheerio";
import crypto from "crypto";
import fetch, { RequestInit } from "node-fetch";
@@ -35,6 +35,20 @@ export const DEFAULT_FETCH_OPTIONS: RequestInit = {
method: "GET",
};
+const makeEmbedImage = (
+ url: string | undefined,
+ width: number | undefined,
+ height: number | undefined,
+): Required | undefined => {
+ if (!url || !width || !height) return undefined;
+ return {
+ url,
+ width,
+ height,
+ proxy_url: getProxyUrl(new URL(url), width, height),
+ };
+};
+
let hasWarnedAboutImagor = false;
export const getProxyUrl = (
@@ -82,6 +96,15 @@ const getMeta = ($: cheerio.CheerioAPI, name: string): string | undefined => {
return ret.trim().length == 0 ? undefined : ret;
};
+const tryParseInt = (str: string | undefined) => {
+ if (!str) return undefined;
+ try {
+ return parseInt(str);
+ } catch (e) {
+ return undefined;
+ }
+};
+
export const getMetaDescriptions = (text: string) => {
const $ = cheerio.load(text);
@@ -94,8 +117,8 @@ export const getMetaDescriptions = (text: string) => {
image: getMeta($, "og:image") || getMeta($, "twitter:image"),
image_fallback: $(`image`).attr("src"),
video_fallback: $(`video`).attr("src"),
- width: parseInt(getMeta($, "og:image:width") || "0"),
- height: parseInt(getMeta($, "og:image:height") || "0"),
+ width: tryParseInt(getMeta($, "og:image:width")),
+ height: tryParseInt(getMeta($, "og:image:height")),
url: getMeta($, "og:url"),
youtube_embed: getMeta($, "og:video:secure_url"),
@@ -120,13 +143,11 @@ const genericImageHandler = async (url: URL): Promise