Skip to content

Commit

Permalink
fix(msgData): split storing network messages into two collections
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-737 authored Dec 20, 2023
1 parent d3c8e69 commit 91d51b2
Show file tree
Hide file tree
Showing 17 changed files with 294 additions and 230 deletions.
56 changes: 31 additions & 25 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -86,25 +86,25 @@ model connectedList {
}

model hubs {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String @unique
description String
rating HubRating[]
ownerId String
iconUrl String
bannerUrl String?
private Boolean @default(true)
createdAt DateTime @default(now())
id String @id @default(auto()) @map("_id") @db.ObjectId
name String @unique
description String
rating HubRating[]
ownerId String
iconUrl String
bannerUrl String?
private Boolean @default(true)
createdAt DateTime @default(now())
// settings are stored as a number, each bit is a setting
settings Int
settings Int
// all the stuff below is relations to other collections
invites hubInvites[]
messages messageData[]
moderators HubModerator[]
connections connectedList[]
logChannels HubLogChannels?
invites hubInvites[]
moderators HubModerator[]
connections connectedList[]
logChannels HubLogChannels?
// approved Boolean @default(false)
// official Boolean @default(false)
originalMessages originalMessages[]
}

model hubInvites {
Expand All @@ -115,16 +115,22 @@ model hubInvites {
hubId String @db.ObjectId
}

model messageData {
id String @id @default(auto()) @map("_id") @db.ObjectId
authorId String
channelAndMessageIds MessageDataChannelAndMessageIds[]
referenceDocId String? @db.ObjectId
serverId String
timestamp DateTime
reactions Json? // eg. {"👎": ["9893820930928", "39283902803982"]} "emoji": userId[] basically
hub hubs? @relation(fields: [hubId], references: [id])
hubId String? @db.ObjectId
model originalMessages {
messageId String @id @map("_id") @db.String
serverId String
authorId String
reactions Json? // eg. {"👎": ["9893820930928", "39283902803982"]} "emoji": userId[] basically
broadcastMsgs broadcastedMessages[] // Ids of messages that were broadcasted to other hubs
messageReference String? @db.String // id of the original message this message is replying to
hub hubs? @relation(fields: [hubId], references: [id])
hubId String? @db.ObjectId
}

model broadcastedMessages {
messageId String @id @map("_id")
channelId String
originalMsg originalMessages @relation(fields: [originalMsgId], references: [messageId])
originalMsgId String @db.String
}

model userBadges {
Expand Down
4 changes: 2 additions & 2 deletions src/InterChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,8 @@ class InterChat extends SuperClient {
this.on('debug', (debug) => {
Logger.debug(debug);
});
this.rest.on('restDebug', (debug) => Logger.debug(`[REST] ${debug}`));
this.rest.on('rateLimited', (rateLimitData) => Logger.warn(rateLimitData));
this.rest.on('restDebug', (debug) => Logger.debug(debug));
this.rest.on('rateLimited', (rl) => Logger.warn(`Rate limited: ${JSON.stringify(rl)}`));
}
}

Expand Down
82 changes: 40 additions & 42 deletions src/commands/context-menu/blacklist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,16 @@ export default class Blacklist extends BaseCommand {
async execute(interaction: MessageContextMenuCommandInteraction) {
const locale = interaction.user.locale;

const messageInDb = await db.messageData.findFirst({
where: {
channelAndMessageIds: { some: { messageId: interaction.targetId } },
hub: {
OR: [
{ moderators: { some: { userId: interaction.user.id } } },
{ ownerId: interaction.user.id },
],
},
},
const messageInDb = await db.broadcastedMessages.findFirst({
where: { messageId: interaction.targetId },
include: { originalMsg: { include: { hub: true } } },
});

if (!messageInDb) {
if (
!messageInDb ||
(messageInDb.originalMsg?.hub?.ownerId !== interaction.user.id &&
!messageInDb.originalMsg?.hub?.moderators.find((mod) => mod.userId === interaction.user.id))
) {
interaction.reply({
embeds: [
simpleEmbed(
Expand All @@ -70,8 +67,7 @@ export default class Blacklist extends BaseCommand {
new CustomID()
.setIdentifier('blacklist', 'user')
.addArgs(interaction.user.id)
.addArgs(messageInDb.id)
.addArgs('u=1')
.addArgs(messageInDb.originalMsgId)
.toString(),
)
.setLabel(t({ phrase: 'blacklist.button.user', locale }))
Expand All @@ -82,11 +78,10 @@ export default class Blacklist extends BaseCommand {
new CustomID()
.setIdentifier('blacklist', 'server')
.addArgs(interaction.user.id)
.addArgs(messageInDb.id)
.addArgs('s=1')
.addArgs(messageInDb.originalMsgId)
.toString(),
)
.setLabel(t({ phrase: 'blacklist.button.user', locale }))
.setLabel(t({ phrase: 'blacklist.button.server', locale }))
.setStyle(ButtonStyle.Secondary)
.setEmoji('🏠'),
);
Expand All @@ -109,15 +104,13 @@ export default class Blacklist extends BaseCommand {
}

const messageDocId = customId.args[1];
const blacklistType = customId.args[2];

const modal = new ModalBuilder()
.setTitle('Blacklist')
.setCustomId(
new CustomID()
.setIdentifier('blacklist_modal')
.setIdentifier('blacklist_modal', customId.postfix)
.addArgs(messageDocId)
.addArgs(blacklistType)
.toString(),
)
.addComponents(
Expand All @@ -140,7 +133,10 @@ export default class Blacklist extends BaseCommand {
t({ phrase: 'blacklist.modal.duration.label', locale: interaction.user.locale }),
)
.setPlaceholder(
t({ phrase: 'blacklist.modal.reason.placeholder', locale: interaction.user.locale }),
t({
phrase: 'blacklist.modal.duration.placeholder',
locale: interaction.user.locale,
}),
)
.setStyle(TextInputStyle.Short)
.setMinLength(2)
Expand All @@ -156,14 +152,16 @@ export default class Blacklist extends BaseCommand {
await interaction.deferUpdate();

const customId = CustomID.parseCustomId(interaction.customId);
const messageDocId = customId.args[0];
const blacklistType = customId.args[1];
const messageId = customId.args[0];

const messageInDb = await db.messageData.findFirst({
where: { id: messageDocId },
});
const originalMsg = (
await db.broadcastedMessages.findFirst({
where: { messageId },
include: { originalMsg: true },
})
)?.originalMsg;

if (!messageInDb?.hubId) {
if (!originalMsg?.hubId) {
await interaction.reply({
content: t({ phrase: 'errors.networkMessageExpired', locale: interaction.user.locale }),
ephemeral: true,
Expand Down Expand Up @@ -191,31 +189,31 @@ export default class Blacklist extends BaseCommand {
const blacklistManager = interaction.client.getBlacklistManager();

// user blacklist
if (blacklistType.startsWith('u=')) {
const user = await interaction.client.users.fetch(messageInDb.authorId).catch(() => null);
if (customId.postfix === 'user') {
const user = await interaction.client.users.fetch(originalMsg.authorId).catch(() => null);
successEmbed.setDescription(
t(
{ phrase: 'blacklist.user.success', locale: interaction.user.locale },
{ username: user?.username ?? 'Unknown User', emoji: emojis.tick },
),
);
await blacklistManager.addUserBlacklist(
messageInDb.hubId,
messageInDb.authorId,
originalMsg.hubId,
originalMsg.authorId,
reason,
interaction.user.id,
expires,
);

if (expires) {
blacklistManager.scheduleRemoval('user', messageInDb.authorId, messageInDb.hubId, expires);
blacklistManager.scheduleRemoval('user', originalMsg.authorId, originalMsg.hubId, expires);
}
if (user) {
blacklistManager
.notifyBlacklist('user', messageInDb.authorId, messageInDb.hubId, expires, reason)
.notifyBlacklist('user', originalMsg.authorId, originalMsg.hubId, expires, reason)
.catch(() => null);

const networkLogger = new NetworkLogger(messageInDb.hubId);
const networkLogger = new NetworkLogger(originalMsg.hubId);
await networkLogger.logBlacklist(user, interaction.user, reason, expires);
}

Expand All @@ -224,7 +222,7 @@ export default class Blacklist extends BaseCommand {

// server blacklist
else {
const server = interaction.client.guilds.cache.get(messageInDb.serverId);
const server = interaction.client.guilds.cache.get(originalMsg.serverId);

successEmbed.setDescription(
t(
Expand All @@ -234,8 +232,8 @@ export default class Blacklist extends BaseCommand {
);

await blacklistManager.addServerBlacklist(
messageInDb.serverId,
messageInDb.hubId,
originalMsg.serverId,
originalMsg.hubId,
reason,
interaction.user.id,
expires,
Expand All @@ -244,27 +242,27 @@ export default class Blacklist extends BaseCommand {
// Notify server of blacklist
await blacklistManager.notifyBlacklist(
'server',
messageInDb.serverId,
messageInDb.hubId,
originalMsg.serverId,
originalMsg.hubId,
expires,
reason,
);

if (expires) {
blacklistManager.scheduleRemoval(
'server',
messageInDb.serverId,
messageInDb.hubId,
originalMsg.serverId,
originalMsg.hubId,
expires,
);
}

await db.connectedList.deleteMany({
where: { serverId: messageInDb.serverId, hubId: messageInDb.hubId },
where: { serverId: originalMsg.serverId, hubId: originalMsg.hubId },
});

if (server) {
const networkLogger = new NetworkLogger(messageInDb.hubId);
const networkLogger = new NetworkLogger(originalMsg.hubId);
await networkLogger
.logBlacklist(server, interaction.user, reason, expires)
.catch(() => null);
Expand Down
21 changes: 11 additions & 10 deletions src/commands/context-menu/deleteMsg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {
import BaseCommand from '../BaseCommand.js';
import { checkIfStaff } from '../../utils/Utils.js';
import { emojis } from '../../utils/Constants.js';
import db from '../../utils/Db.js';
import { t } from '../../utils/Locale.js';
import db from '../../utils/Db.js';

export default class DeleteMessage extends BaseCommand {
readonly data: RESTPostAPIApplicationCommandsJSONBody = {
Expand All @@ -20,9 +20,9 @@ export default class DeleteMessage extends BaseCommand {
async execute(interaction: ContextMenuCommandInteraction<CacheType>) {
await interaction.deferReply({ ephemeral: true });

const messageInDb = await db?.messageData.findFirst({
where: { channelAndMessageIds: { some: { messageId: { equals: interaction.targetId } } } },
include: { hub: true },
const messageInDb = await db?.broadcastedMessages.findFirst({
where: { messageId: interaction.targetId },
include: { originalMsg: { include: { hub: true, broadcastMsgs: true } } },
});

if (!messageInDb) {
Expand All @@ -37,9 +37,9 @@ export default class DeleteMessage extends BaseCommand {
const interchatStaff = checkIfStaff(interaction.user.id);
if (
!interchatStaff &&
!messageInDb.hub?.moderators.find((m) => m.userId === interaction.user.id) &&
messageInDb.hub?.ownerId !== interaction.user.id &&
interaction.user.id !== messageInDb.authorId
!messageInDb.originalMsg.hub?.moderators.find((m) => m.userId === interaction.user.id) &&
messageInDb.originalMsg.hub?.ownerId !== interaction.user.id &&
interaction.user.id !== messageInDb.originalMsg.authorId
) {
return await interaction.editReply(
t({
Expand All @@ -51,9 +51,10 @@ export default class DeleteMessage extends BaseCommand {

// find all the messages through the network
const channelSettingsArr = await db.connectedList.findMany({
where: { channelId: { in: messageInDb.channelAndMessageIds.map((c) => c.channelId) } },
where: { channelId: { in: messageInDb.originalMsg.broadcastMsgs.map((c) => c.channelId) } },
});
const results = messageInDb.channelAndMessageIds.map(async (element) => {

const results = messageInDb.originalMsg.broadcastMsgs.map(async (element) => {
const connection = channelSettingsArr.find((c) => c.channelId === element.channelId);
if (!connection) return false;

Expand Down Expand Up @@ -82,7 +83,7 @@ export default class DeleteMessage extends BaseCommand {
},
{
emoji: emojis.yes,
user: `<@${messageInDb.authorId}>`,
user: `<@${messageInDb.originalMsg.authorId}>`,
deleted: deleted.toString(),
total: resultsArray.length.toString(),
},
Expand Down
Loading

0 comments on commit 91d51b2

Please sign in to comment.