summary refs log tree commit diff
path: root/src/util
diff options
context:
space:
mode:
Diffstat (limited to 'src/util')
-rw-r--r--src/util/Channel.ts2
-rw-r--r--src/util/Message.ts76
-rw-r--r--src/util/User.ts12
-rw-r--r--src/util/cdn.ts24
-rw-r--r--src/util/instanceOf.ts3
5 files changed, 102 insertions, 15 deletions
diff --git a/src/util/Channel.ts b/src/util/Channel.ts

index c8df85bc..8dfc03bc 100644 --- a/src/util/Channel.ts +++ b/src/util/Channel.ts
@@ -45,7 +45,7 @@ export async function createChannel(channel: Partial<TextChannel | VoiceChannel> id: Snowflake.generate(), created_at: new Date(), // @ts-ignore - recipients: null + recipient_ids: null }).save(); await emitEvent({ event: "CHANNEL_CREATE", data: channel, guild_id: channel.guild_id } as ChannelCreateEvent); diff --git a/src/util/Message.ts b/src/util/Message.ts
index 0d3cdac7..9b928031 100644 --- a/src/util/Message.ts +++ b/src/util/Message.ts
@@ -1,14 +1,28 @@ -import { ChannelModel, MessageCreateEvent } from "@fosscord/server-util"; +import { ChannelModel, Embed, Message, MessageCreateEvent, MessageUpdateEvent } from "@fosscord/server-util"; import { Snowflake } from "@fosscord/server-util"; import { MessageModel } from "@fosscord/server-util"; import { PublicMemberProjection } from "@fosscord/server-util"; import { toObject } from "@fosscord/server-util"; import { getPermission } from "@fosscord/server-util"; -import { Message } from "@fosscord/server-util"; import { HTTPError } from "lambert-server"; +import fetch from "node-fetch"; +import cheerio from "cheerio"; import { emitEvent } from "./Event"; // TODO: check webhook, application, system author +const LINK_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g; + +const DEFAULT_FETCH_OPTIONS: any = { + redirect: "follow", + follow: 1, + headers: { + "user-agent": "Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)" + }, + size: 1024 * 1024 * 1, + compress: true, + method: "GET" +}; + export async function handleMessage(opts: Partial<Message>) { const channel = await ChannelModel.findOne({ id: opts.channel_id }, { guild_id: true, type: true, permission_overwrites: true }).exec(); if (!channel || !opts.channel_id) throw new HTTPError("Channel not found", 404); @@ -36,13 +50,67 @@ export async function handleMessage(opts: Partial<Message>) { mention_channels_ids: [], mention_role_ids: [], mention_user_ids: [], - attachments: [], // TODO: message attachments + attachments: opts.attachments || [], // TODO: message attachments embeds: opts.embeds || [], reactions: opts.reactions || [], type: opts.type ?? 0 }; } +// TODO: cache link result in db +export async function postHandleMessage(message: Message) { + var links = message.content?.match(LINK_REGEX); + if (!links) return; + + const data = { ...message }; + data.embeds = data.embeds.filter((x) => x.type !== "link"); + + links = links.slice(0, 5); // embed max 5 links + + for (const link of links) { + try { + const request = await fetch(link, DEFAULT_FETCH_OPTIONS); + + const text = await request.text(); + const $ = cheerio.load(text); + + const title = $('meta[property="og:title"]').attr("content"); + const provider_name = $('meta[property="og:site_name"]').text(); + const author_name = $('meta[property="article:author"]').attr("content"); + const description = $('meta[property="og:description"]').attr("content") || $('meta[property="description"]').attr("content"); + const image = $('meta[property="og:image"]').attr("content"); + const url = $('meta[property="og:url"]').attr("content"); + // TODO: color + const embed: Embed = { + provider: { + url: link, + name: provider_name + } + }; + + if (author_name) embed.author = { name: author_name }; + if (image) embed.thumbnail = { proxy_url: image, url: image }; + if (title) embed.title = title; + if (url) embed.url = url; + if (description) embed.description = description; + + if (title || description) { + data.embeds.push(embed); + } + } catch (error) {} + } + + await Promise.all([ + emitEvent({ + event: "MESSAGE_UPDATE", + guild_id: message.guild_id, + channel_id: message.channel_id, + data + } as MessageUpdateEvent), + MessageModel.updateOne({ id: message.id, channel_id: message.channel_id }, data).exec() + ]); +} + export async function sendMessage(opts: Partial<Message>) { const message = await handleMessage({ ...opts, id: Snowflake.generate(), timestamp: new Date() }); @@ -50,5 +118,7 @@ export async function sendMessage(opts: Partial<Message>) { await emitEvent({ event: "MESSAGE_CREATE", channel_id: opts.channel_id, data, guild_id: message.guild_id } as MessageCreateEvent); + postHandleMessage(data); // no await as it shouldnt block the message send function + return data; } diff --git a/src/util/User.ts b/src/util/User.ts
index 0f3768cc..107fc759 100644 --- a/src/util/User.ts +++ b/src/util/User.ts
@@ -1,20 +1,14 @@ -import { toObject, UserModel } from "@fosscord/server-util"; +import { toObject, UserModel, PublicUserProjection } from "@fosscord/server-util"; import { HTTPError } from "lambert-server"; -export const PublicUserProjection = { - username: true, - discriminator: true, - id: true, - public_flags: true, - avatar: true, -}; +export { PublicUserProjection }; export async function getPublicUser(user_id: string, additional_fields?: any) { const user = await UserModel.findOne( { id: user_id }, { ...PublicUserProjection, - ...additional_fields, + ...additional_fields } ).exec(); if (!user) throw new HTTPError("User not found", 404); diff --git a/src/util/cdn.ts b/src/util/cdn.ts new file mode 100644
index 00000000..a66e2215 --- /dev/null +++ b/src/util/cdn.ts
@@ -0,0 +1,24 @@ +import { Config } from "@fosscord/server-util"; +import FormData from "form-data"; +import fetch from "node-fetch"; + +export async function uploadFile(path: string, file: Express.Multer.File) { + const form = new FormData(); + form.append("file", file.buffer, { + contentType: file.mimetype, + filename: file.originalname + }); + + const response = await fetch(`${Config.get().cdn.endpoint || "http://localhost:3003"}${path}`, { + headers: { + signature: Config.get().security.requestSignature, + ...form.getHeaders() + }, + method: "POST", + body: form + }); + const result = await response.json(); + + if (response.status !== 200) throw result; + return result; +} diff --git a/src/util/instanceOf.ts b/src/util/instanceOf.ts
index b67bde27..93a92805 100644 --- a/src/util/instanceOf.ts +++ b/src/util/instanceOf.ts
@@ -74,10 +74,9 @@ export function instanceOf( ): Boolean { if (!ref) ref = { obj: null, key: "" }; if (!path) path = "body"; + if (!type) return true; // no type was specified try { - if (!type) return true; // no type was specified - if (value == null) { if (optional) return true; throw new FieldError("BASE_TYPE_REQUIRED", req.t("common:field.BASE_TYPE_REQUIRED"));