Various AT Protocol integrations with obsidian
1import { requestUrl } from "obsidian";
2
3const imageCache = new Map<string, string>();
4
5function isValidUrl(url: string): boolean {
6 try {
7 const u = new URL(url);
8 return u.protocol === "http:" || u.protocol === "https:";
9 } catch {
10 return false;
11 }
12}
13
14export async function fetchOgImage(url: string): Promise<string | undefined> {
15 if (imageCache.has(url)) {
16 return imageCache.get(url) || undefined;
17 }
18 if (!isValidUrl(url)) {
19 return undefined;
20 }
21
22 try {
23 const res = await requestUrl({ url, method: "GET" });
24 const match = res.text.match(
25 /<meta[^>]+(?:property="og:image"|name="twitter:image")[^>]+content="([^"]+)"/i
26 ) || res.text.match(
27 /<meta[^>]+content="([^"]+)"[^>]+(?:property="og:image"|name="twitter:image")/i
28 );
29 imageCache.set(url, match?.[1] ?? "");
30 return match?.[1];
31 } catch (e) {
32 return undefined;
33 }
34}