possumbot/modules/fedimbed.js
2024-08-21 15:00:40 +00:00

92 lines
3 KiB
JavaScript

import fedimbed from "../lib/fedimbed.js";
import { encode } from "html-entities";
import { JSDOM } from "jsdom";
import util from "util";
async function onMessage(client, event) {
const embed = await fedimbed(event.event.content.body);
if(!embed) return;
const dom = new JSDOM("<!DOCTYPE html><body></body>");
const document = dom.window.document;
var quote = document.createElement("blockquote");
if(!embed.embeds) {
var c = util.format(embed);
client.reply(event, c, `<pre><code>${encode(c)}</code></pre>`);
return;
}
for(const emb of embed.embeds) {
var link = document.createElement("a");
link.href = emb.url;
if(emb.thumbnail && emb.thumbnail.url) {
var avatar = document.createElement("img");
var matrixUrl = client.cache.get("fedimbed_" + emb.thumbnail.url);
if(!matrixUrl) {
const buffer = await fetch(emb.thumbnail.url, {
headers: {
"User-Agent": "PossumBot/1.0 (+https://bot.possum.city/)",
},
}).then((res) => res.arrayBuffer()).then((buf) => Buffer.from(buf));
const uploadResponse = await client.uploadContent(buffer, { rawResponse: false });
matrixUrl = uploadResponse.content_uri;
client.cache.set("fedimbed_" + emb.thumbnail.url, matrixUrl);
}
avatar.src = matrixUrl;
avatar.height = "16";
link.appendChild(avatar);
}
var linkText = document.createElement("span");
linkText.innerHTML = ((emb.thumbnail?.url) ? "&nbsp" : "") + emb.title;
link.appendChild(linkText);
quote.appendChild(link);
var text = document.createElement("p");
text.innerHTML = emb.description;
quote.appendChild(text);
}
for(const file of embed.files) {
var matrixUrl = client.cache.get("fedimbed_" + file.url);
if(!matrixUrl) {
const buffer = await fetch(file.url, {
headers: {
"User-Agent": "PossumBot/1.0 (+https://bot.possum.city/)",
},
}).then((res) => res.arrayBuffer()).then((buf) => Buffer.from(buf));
const uploadResponse = await client.uploadContent(buffer, { rawResponse: false });
matrixUrl = uploadResponse.content_uri;
client.cache.set("fedimbed_" + file.url, matrixUrl);
}
var media;
switch(file.type.split("/")[0]) {
case "audio":
media = document.createElement("audio");
break;
case "video":
media = document.createElement("video");
break;
case "image":
media = document.createElement("img");
break;
}
media.src = matrixUrl;
media.alt = file.desc;
quote.appendChild(media);
}
document.body.appendChild(quote);
let x = document.createElement("small");
x.innerHTML = "Powered by <a href=\"https://gitdab.com/Cynosphere/HiddenPhox/src/branch/rewrite/src/modules/fedimbed.js\">HF Fedimbed</a>";
document.body.appendChild(x);
client.reply(event, "This message uses HTML, which your client does not support.", document.body.outerHTML);
}
export default {
name: "fedimbed",
desc: "embed fediverse post contents",
hooks: {
message: onMessage
}
}