aboutsummaryrefslogtreecommitdiff
path: root/apps/web/app/(canvas)/lib/createAssetUrl.ts
blob: 05c2baea0a16edbc7a360e49b127c6b7918a75cd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import {
  AssetRecordType,
  TLAsset,
  getHashForString,
  truncateStringWithEllipsis,
} from "tldraw";
// import { BOOKMARK_ENDPOINT } from './config'

interface ResponseBody {
  title?: string;
  description?: string;
  image?: string;
}

export async function createAssetFromUrl({
  url,
}: {
  type: "url";
  url: string;
}): Promise<TLAsset> {
  // try {
  // 	// First, try to get the meta data from our endpoint
  // 	const meta = (await (
  // 		await fetch(BOOKMARK_ENDPOINT, {
  // 			method: 'POST',
  // 			headers: {
  // 				'Content-Type': 'application/json',
  // 			},
  // 			body: JSON.stringify({
  // 				url,
  // 			}),
  // 		})
  // 	).json()) as ResponseBody

  // 	return {
  // 		id: AssetRecordType.createId(getHashForString(url)),
  // 		typeName: 'asset',
  // 		type: 'bookmark',
  // 		props: {
  // 			src: url,
  // 			description: meta.description ?? '',
  // 			image: meta.image ?? '',
  // 			title: meta.title ?? truncateStringWithEllipsis(url, 32),
  // 		},
  // 		meta: {},
  // 	}
  // } catch (error) {
  // Otherwise, fallback to fetching data from the url

  let meta: { image: string; title: string; description: string };

  try {
    const resp = await fetch(url, { method: "GET", mode: "no-cors" });
    const html = await resp.text();
    const doc = new DOMParser().parseFromString(html, "text/html");
    meta = {
      image:
        doc.head
          .querySelector('meta[property="og:image"]')
          ?.getAttribute("content") ?? "",
      title:
        doc.head
          .querySelector('meta[property="og:title"]')
          ?.getAttribute("content") ?? truncateStringWithEllipsis(url, 32),
      description:
        doc.head
          .querySelector('meta[property="og:description"]')
          ?.getAttribute("content") ?? "",
    };
  } catch (error) {
    console.error(error);
    meta = {
      image: "",
      title: truncateStringWithEllipsis(url, 32),
      description: "",
    };
  }

  // Create the bookmark asset from the meta
  return {
    id: AssetRecordType.createId(getHashForString(url)),
    typeName: "asset",
    type: "bookmark",
    props: {
      src: url,
      image: meta.image,
      title: meta.title,
      description: meta.description,
      favicon: meta.image,
    },
    meta: {},
  };
  // }
}