-
Notifications
You must be signed in to change notification settings - Fork 26
/
share.ts
196 lines (172 loc) · 6.3 KB
/
share.ts
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import { ChatCraftChat, SerializedChatCraftChat } from "./ChatCraftChat";
/**
* @param chat
* @param user
* @returns url that contains chat in cloud storage
*/
export function createDataShareUrl(chat: ChatCraftChat, user: User) {
return createShareUrl(chat, user, "/api/share");
}
/**
* by default returns url that tells chatcraft to load shared chat
* @param chat
* @param user
* @param prefix
* @returns url
*/
export function createShareUrl(chat: ChatCraftChat, user: User, prefix = "/c") {
const { origin } = new URL(location.href);
const shareUrl = new URL(`${prefix}/${user.username}/${chat.id}`, origin);
return shareUrl.href;
}
/**
* Converts "/api/share"-style URLs before passing it to UI
* This is done to avoid react-router-dom issue involving "/api/share"-style URLs
* @param url
* @returns url
*/
export function convertToShareUrl(url: string) {
return url.includes("/api/share") ? url.replace("/api/share", "/c") : url;
}
/**
* Generate static html with our messages in yaml form so they can both be parsed by us and by scrapers/browsers/etc
* Uses our index.html as a base
* @param chat Chatcraft chat
* @returns sane-looking html
*/
function generateSharingHTML(chat: ChatCraftChat, user: User) {
const cloned = document.cloneNode(true);
const clonedDocument = cloned instanceof Document ? cloned : null;
const mainElement = clonedDocument?.querySelector("main");
if (!clonedDocument || !mainElement) {
throw new Error("index.html changed without updating this code!");
}
mainElement.innerHTML = "";
// Use html-escaped yaml for payload
const preElement = document.createElement("pre");
preElement.textContent = chat.toYAML();
mainElement.append(preElement);
[...mainElement.attributes].forEach((attr: Attr) =>
mainElement.attributes.removeNamedItem(attr.name)
);
const lastMessage = chat.messages().pop();
const lastMessageText = lastMessage?.text;
// remove script+style tags
clonedDocument.head.querySelectorAll("style")?.forEach((x) => x.remove());
clonedDocument.head.querySelectorAll("script")?.forEach((x) => x.remove());
// set a meta refresh tag to redirect to the UI without scripting
setMetaContent(clonedDocument, "http-equiv", "refresh", `0;url=${createShareUrl(chat, user)}`);
// Set various types of titles/summaries
setMetaContent(clonedDocument, "property", "og:title", chat.summary);
setMetaContent(clonedDocument, "property", "og:url", createShareUrl(chat, user));
setMetaContent(clonedDocument, "property", "og:type", "website");
setMetaContent(clonedDocument, "name", "description", chat.summary);
setMetaContent(clonedDocument, "name", "twitter:card", "summary_large_image");
setMetaContent(clonedDocument, "name", "twitter:title", "chatcraft.org");
setMetaContent(clonedDocument, "name", "twitter:description", chat.summary);
setMetaContent(
clonedDocument,
"name",
"twitter:image",
"https://chatcraft.org/favicon-32x32.png"
);
setDocumentTitle(clonedDocument, chat.summary);
// Set OG bulk text to be that of last message
if (lastMessageText) {
setMetaContent(clonedDocument, "property", "og:description", lastMessageText);
}
return clonedDocument.documentElement.outerHTML;
}
function setMetaContent(
document: Document,
name_or_propery: string,
property: string,
content: string
) {
// First, try to find an existing tag
let metaElement = document.head.querySelector(`meta[${name_or_propery}='${property}']`);
// create a new meta tag with the specified property and content
if (!metaElement) {
// Try to insert the new tag next to other similar ones
metaElement = document.createElement("meta");
// Initially set lastInit to the last child of the head
let lastNode = document.head.lastChild;
if (!lastNode) {
lastNode = document.createTextNode("\n");
document.head.appendChild(lastNode);
}
// Query all existing meta tags in the document head
const metas = document.head.querySelectorAll(`meta[${name_or_propery}]`);
if (metas.length > 0) {
// If there are existing meta tags, update lastInit to the last meta tag
lastNode = metas[metas.length - 1];
}
lastNode.after(document.createTextNode("\n"));
lastNode.after(metaElement);
lastNode.after(document.createTextNode("\n"));
}
metaElement.setAttribute(name_or_propery, property);
metaElement.setAttribute("content", content);
}
function setDocumentTitle(document: Document, title: string) {
let titleElement = document.head.querySelector("title");
if (!titleElement) {
titleElement = document.createElement("title");
document.head.appendChild(titleElement);
document.head.appendChild(document.createTextNode("\n"));
}
titleElement.textContent = title;
}
export async function createShare(chat: ChatCraftChat, user: User) {
const res = await fetch(`/api/share/${user.username}/${chat.id}`, {
method: "PUT",
credentials: "same-origin",
headers: {
"Content-Type": "text/html",
},
body: generateSharingHTML(chat, user),
});
if (!res.ok) {
const {
message,
}: {
message?: string;
} = await res.json();
throw new Error(`Unable to share chat: ${message || "unknown error"}`);
}
}
export async function loadShare(user: string, id: string) {
const res = await fetch(`/api/share/${user}/${id}`);
if (!res.ok) {
throw new Error("Unable to load shared chat" + (await res.text()));
}
const text = await res.text();
try {
// Try to parse the response as JSON
const serialized: SerializedChatCraftChat = JSON.parse(text);
return ChatCraftChat.fromJSON(serialized);
} catch (error) {
// If JSON parsing fails, try to parse as HTML with embedded yaml
}
const parser = new DOMParser();
const doc = parser.parseFromString(text, "text/html");
const yamlText = doc.querySelector("main")?.textContent;
if (!yamlText) {
throw new Error("No shared found in the shared html");
}
return ChatCraftChat.fromYAML(yamlText);
}
export async function deleteShare(user: User, chatId: string) {
const res = await fetch(`/api/share/${user.username}/${chatId}`, {
method: "DELETE",
credentials: "same-origin",
});
if (!res.ok) {
const {
message,
}: {
message?: string;
} = await res.json();
throw new Error(`Unable to unshare chat: ${message || "unknown error"}`);
}
}