Colubrina/backend/lib/resolveEmbeds.js

99 lines
3 KiB
JavaScript
Raw Normal View History

2022-06-05 22:58:18 +10:00
const { Message } = require("../models")
const axios = require("axios")
const ogs = require("open-graph-scraper")
const cryptoRandomString = require("crypto-random-string")
const blacklist = require("./blacklist.json")
module.exports = async function (message) {
2022-06-05 22:58:18 +10:00
return new Promise(async (resolve, reject) => {
try {
if (message.content) {
2023-02-12 17:01:08 +11:00
const regex = /(https?:\/\/\S+)/g
2022-06-05 22:58:18 +10:00
let links = message.content.match(regex)
if (links) {
if (links.length > 3) links = links.slice(0, 3)
const promises = links.map(async (embedLink, i) => {
let embed = {}
const linkURL = new URL(embedLink)
2022-06-05 22:58:18 +10:00
if (blacklist.includes(linkURL.hostname)) {
console.log(`Blacklisted link ${linkURL.hostname}`)
return {
embedLink,
2022-06-05 22:58:18 +10:00
openGraph: {
ogDescription:
"This link cannot be mediaproxied at this time.",
ogTitle: "Blacklisted link"
},
type: "openGraph"
}
2022-06-05 22:58:18 +10:00
}
await ogs({
headers: {
"user-agent": "Googlebot/2.1 (+http://www.google.com/bot.html)"
},
url: embedLink
2022-06-05 22:58:18 +10:00
})
.then((result) => {
if (result?.result) {
embed = {
embedLink,
openGraph: result.result,
2022-06-05 22:58:18 +10:00
type: "openGraph"
}
2022-06-05 22:58:18 +10:00
}
})
2023-02-12 17:01:08 +11:00
.catch(async () => {
2022-06-05 22:58:18 +10:00
await axios
.get(embedLink, {
2022-06-05 22:58:18 +10:00
headers: {
"user-agent":
"Googlebot/2.1 (+http://www.google.com/bot.html)"
}
})
.then((res) => {
// If content type is image
2022-06-05 22:58:18 +10:00
if (res.headers["content-type"].startsWith("image/")) {
const securityToken = cryptoRandomString({ length: 32 })
embed = {
2022-06-05 22:58:18 +10:00
type: "image",
link: embedLink,
2022-06-05 22:58:18 +10:00
securityToken,
mediaProxyLink:
"/api/v1/mediaproxy/" +
message.id +
"/" +
i +
"/" +
securityToken
}
2022-06-05 22:58:18 +10:00
}
})
.catch((e) => {
console.log(e)
})
2022-06-05 22:58:18 +10:00
})
return embed
})
const embeds = await Promise.all(promises)
2022-06-05 22:58:18 +10:00
await Message.update(
{
embeds
2022-06-05 22:58:18 +10:00
},
{
where: {
id: message.id
}
}
)
resolve(embeds)
} else {
reject()
}
} else {
reject()
}
} catch (e) {
console.log(e)
2022-06-05 22:58:18 +10:00
}
})
}