mirror of
https://github.com/Hessenuk/DiscordTickets.git
synced 2025-02-23 10:51:22 +02:00
perf: threads everywhere! (for encryption & decryption)
This commit is contained in:
parent
5a908e77a7
commit
d99cb202d5
@ -1,11 +1,10 @@
|
|||||||
/* eslint-disable no-underscore-dangle */
|
/* eslint-disable no-underscore-dangle */
|
||||||
const { Autocompleter } = require('@eartharoid/dbf');
|
const { Autocompleter } = require('@eartharoid/dbf');
|
||||||
const emoji = require('node-emoji');
|
const emoji = require('node-emoji');
|
||||||
const Cryptr = require('cryptr');
|
|
||||||
const { decrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
const Keyv = require('keyv');
|
const Keyv = require('keyv');
|
||||||
const ms = require('ms');
|
const ms = require('ms');
|
||||||
const { isStaff } = require('../lib/users');
|
const { isStaff } = require('../lib/users');
|
||||||
|
const { reusable } = require('../lib/threads');
|
||||||
|
|
||||||
module.exports = class TicketCompleter extends Autocompleter {
|
module.exports = class TicketCompleter extends Autocompleter {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -30,6 +29,7 @@ module.exports = class TicketCompleter extends Autocompleter {
|
|||||||
let tickets = await this.cache.get(cacheKey);
|
let tickets = await this.cache.get(cacheKey);
|
||||||
|
|
||||||
if (!tickets) {
|
if (!tickets) {
|
||||||
|
const cmd = client.commands.commands.slash.get('transcript');
|
||||||
const { locale } = await client.prisma.guild.findUnique({
|
const { locale } = await client.prisma.guild.findUnique({
|
||||||
select: { locale: true },
|
select: { locale: true },
|
||||||
where: { id: guildId },
|
where: { id: guildId },
|
||||||
@ -42,15 +42,25 @@ module.exports = class TicketCompleter extends Autocompleter {
|
|||||||
open,
|
open,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
tickets = tickets
|
|
||||||
.filter(ticket => client.commands.commands.slash.get('transcript').shouldAllowAccess(interaction, ticket))
|
const worker = await reusable('crypto');
|
||||||
.map(ticket => {
|
try {
|
||||||
const date = new Date(ticket.createdAt).toLocaleString([locale, 'en-GB'], { dateStyle: 'short' });
|
tickets = await Promise.all(
|
||||||
const topic = ticket.topic ? '- ' + decrypt(ticket.topic).replace(/\n/g, ' ').substring(0, 50) : '';
|
tickets
|
||||||
const category = emoji.hasEmoji(ticket.category.emoji) ? emoji.get(ticket.category.emoji) + ' ' + ticket.category.name : ticket.category.name;
|
.filter(ticket => cmd.shouldAllowAccess(interaction, ticket))
|
||||||
ticket._name = `${category} #${ticket.number} (${date}) ${topic}`;
|
.map(async ticket => {
|
||||||
return ticket;
|
const getTopic = async () => (await worker.decrypt(ticket.topic)).replace(/\n/g, ' ').substring(0, 50);
|
||||||
});
|
const date = new Date(ticket.createdAt).toLocaleString([locale, 'en-GB'], { dateStyle: 'short' });
|
||||||
|
const topic = ticket.topic ? '- ' + (await getTopic()) : '';
|
||||||
|
const category = emoji.hasEmoji(ticket.category.emoji) ? emoji.get(ticket.category.emoji) + ' ' + ticket.category.name : ticket.category.name;
|
||||||
|
ticket._name = `${category} #${ticket.number} (${date}) ${topic}`;
|
||||||
|
return ticket;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await worker.terminate();
|
||||||
|
}
|
||||||
|
|
||||||
this.cache.set(cacheKey, tickets, ms('1m'));
|
this.cache.set(cacheKey, tickets, ms('1m'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,9 +7,8 @@ const {
|
|||||||
TextInputBuilder,
|
TextInputBuilder,
|
||||||
TextInputStyle,
|
TextInputStyle,
|
||||||
} = require('discord.js');
|
} = require('discord.js');
|
||||||
|
const { reusable } = require('../lib/threads');
|
||||||
const emoji = require('node-emoji');
|
const emoji = require('node-emoji');
|
||||||
const Cryptr = require('cryptr');
|
|
||||||
const cryptr = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
|
|
||||||
module.exports = class EditButton extends Button {
|
module.exports = class EditButton extends Button {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -35,75 +34,87 @@ module.exports = class EditButton extends Button {
|
|||||||
|
|
||||||
const getMessage = client.i18n.getLocale(ticket.guild.locale);
|
const getMessage = client.i18n.getLocale(ticket.guild.locale);
|
||||||
|
|
||||||
if (ticket.questionAnswers.length === 0) {
|
const worker = await reusable('crypto');
|
||||||
const field = new TextInputBuilder()
|
|
||||||
.setCustomId('topic')
|
try {
|
||||||
.setLabel(getMessage('modals.topic.label'))
|
if (ticket.questionAnswers.length === 0) {
|
||||||
.setStyle(TextInputStyle.Paragraph)
|
const field = new TextInputBuilder()
|
||||||
.setMaxLength(1000)
|
.setCustomId('topic')
|
||||||
.setMinLength(5)
|
.setLabel(getMessage('modals.topic.label'))
|
||||||
.setPlaceholder(getMessage('modals.topic.placeholder'))
|
.setStyle(TextInputStyle.Paragraph)
|
||||||
.setRequired(true);
|
.setMaxLength(1000)
|
||||||
if (ticket.topic) field.setValue(cryptr.decrypt(ticket.topic));
|
.setMinLength(5)
|
||||||
await interaction.showModal(
|
.setPlaceholder(getMessage('modals.topic.placeholder'))
|
||||||
new ModalBuilder()
|
.setRequired(true);
|
||||||
.setCustomId(JSON.stringify({
|
if (ticket.topic) field.setValue(await worker.decrypt(ticket.topic));
|
||||||
action: 'topic',
|
await interaction.showModal(
|
||||||
edit: true,
|
new ModalBuilder()
|
||||||
}))
|
.setCustomId(JSON.stringify({
|
||||||
.setTitle(ticket.category.name)
|
action: 'topic',
|
||||||
.setComponents(
|
edit: true,
|
||||||
new ActionRowBuilder()
|
}))
|
||||||
.setComponents(field),
|
.setTitle(ticket.category.name)
|
||||||
),
|
.setComponents(
|
||||||
);
|
new ActionRowBuilder()
|
||||||
} else {
|
.setComponents(field),
|
||||||
await interaction.showModal(
|
),
|
||||||
new ModalBuilder()
|
);
|
||||||
.setCustomId(JSON.stringify({
|
} else {
|
||||||
action: 'questions',
|
await interaction.showModal(
|
||||||
edit: true,
|
new ModalBuilder()
|
||||||
}))
|
.setCustomId(JSON.stringify({
|
||||||
.setTitle(ticket.category.name)
|
action: 'questions',
|
||||||
.setComponents(
|
edit: true,
|
||||||
ticket.questionAnswers
|
}))
|
||||||
.filter(a => a.question.type === 'TEXT') // TODO: remove this when modals support select menus
|
.setTitle(ticket.category.name)
|
||||||
.map(a => {
|
.setComponents(
|
||||||
if (a.question.type === 'TEXT') {
|
await Promise.all(
|
||||||
const field = new TextInputBuilder()
|
ticket.questionAnswers
|
||||||
.setCustomId(String(a.id))
|
.filter(a => a.question.type === 'TEXT') // TODO: remove this when modals support select menus
|
||||||
.setLabel(a.question.label)
|
.map(async a => {
|
||||||
.setStyle(a.question.style)
|
if (a.question.type === 'TEXT') {
|
||||||
.setMaxLength(Math.min(a.question.maxLength, 1000))
|
const field = new TextInputBuilder()
|
||||||
.setMinLength(a.question.minLength)
|
.setCustomId(String(a.id))
|
||||||
.setPlaceholder(a.question.placeholder)
|
.setLabel(a.question.label)
|
||||||
.setRequired(a.question.required);
|
.setStyle(a.question.style)
|
||||||
if (a.value) field.setValue(cryptr.decrypt(a.value));
|
.setMaxLength(Math.min(a.question.maxLength, 1000))
|
||||||
else if (a.question.value) field.setValue(a.question.value);
|
.setMinLength(a.question.minLength)
|
||||||
return new ActionRowBuilder().setComponents(field);
|
.setPlaceholder(a.question.placeholder)
|
||||||
} else if (a.question.type === 'MENU') {
|
.setRequired(a.question.required);
|
||||||
return new ActionRowBuilder()
|
if (a.value) field.setValue(await worker.decrypt(a.value));
|
||||||
.setComponents(
|
else if (a.question.value) field.setValue(a.question.value);
|
||||||
new StringSelectMenuBuilder()
|
return new ActionRowBuilder().setComponents(field);
|
||||||
.setCustomId(a.question.id)
|
} else if (a.question.type === 'MENU') {
|
||||||
.setPlaceholder(a.question.placeholder || a.question.label)
|
return new ActionRowBuilder()
|
||||||
.setMaxValues(a.question.maxLength)
|
.setComponents(
|
||||||
.setMinValues(a.question.minLength)
|
new StringSelectMenuBuilder()
|
||||||
.setOptions(
|
.setCustomId(a.question.id)
|
||||||
a.question.options.map((o, i) => {
|
.setPlaceholder(a.question.placeholder || a.question.label)
|
||||||
const builder = new StringSelectMenuOptionBuilder()
|
.setMaxValues(a.question.maxLength)
|
||||||
.setValue(String(i))
|
.setMinValues(a.question.minLength)
|
||||||
.setLabel(o.label);
|
.setOptions(
|
||||||
if (o.description) builder.setDescription(o.description);
|
a.question.options.map((o, i) => {
|
||||||
if (o.emoji) builder.setEmoji(emoji.hasEmoji(o.emoji) ? emoji.get(o.emoji) : { id: o.emoji });
|
const builder = new StringSelectMenuOptionBuilder()
|
||||||
return builder;
|
.setValue(String(i))
|
||||||
}),
|
.setLabel(o.label);
|
||||||
),
|
if (o.description) builder.setDescription(o.description);
|
||||||
);
|
if (o.emoji) {
|
||||||
}
|
builder.setEmoji(emoji.hasEmoji(o.emoji)
|
||||||
}),
|
? emoji.get(o.emoji)
|
||||||
),
|
: { id: o.emoji });
|
||||||
);
|
}
|
||||||
|
return builder;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await worker.terminate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -5,8 +5,7 @@ const {
|
|||||||
} = require('discord.js');
|
} = require('discord.js');
|
||||||
const { isStaff } = require('../../lib/users');
|
const { isStaff } = require('../../lib/users');
|
||||||
const ExtendedEmbedBuilder = require('../../lib/embed');
|
const ExtendedEmbedBuilder = require('../../lib/embed');
|
||||||
const Cryptr = require('cryptr');
|
const { reusable } = require('../../lib/threads');
|
||||||
const { decrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
|
|
||||||
module.exports = class TicketsSlashCommand extends SlashCommand {
|
module.exports = class TicketsSlashCommand extends SlashCommand {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -116,33 +115,44 @@ module.exports = class TicketsSlashCommand extends SlashCommand {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (open.length >= 1) {
|
const worker = await reusable('crypto');
|
||||||
fields.push({
|
try {
|
||||||
name: getMessage('commands.slash.tickets.response.fields.open.name'),
|
if (open.length >= 1) {
|
||||||
value: open.map(ticket => {
|
fields.push({
|
||||||
const topic = ticket.topic ? `- \`${decrypt(ticket.topic).replace(/\n/g, ' ').slice(0, 30)}\`` : '';
|
name: getMessage('commands.slash.tickets.response.fields.open.name'),
|
||||||
return `> <#${ticket.id}> ${topic}`;
|
value: (await Promise.all(
|
||||||
}).join('\n'),
|
open.map(async ticket => {
|
||||||
});
|
const getTopic = async () => (await worker.decrypt(ticket.topic)).replace(/\n/g, ' ').substring(0, 30);
|
||||||
}
|
const topic = ticket.topic ? `- \`${await getTopic()}\`` : '';
|
||||||
|
return `> <#${ticket.id}> ${topic}`;
|
||||||
|
}),
|
||||||
|
)).join('\n'),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (closed.length === 0) {
|
if (closed.length === 0) {
|
||||||
const newCommand = client.application.commands.cache.find(c => c.name === 'new');
|
const newCommand = client.application.commands.cache.find(c => c.name === 'new');
|
||||||
fields.push({
|
fields.push({
|
||||||
name: getMessage('commands.slash.tickets.response.fields.closed.name'),
|
name: getMessage('commands.slash.tickets.response.fields.closed.name'),
|
||||||
value: getMessage(`commands.slash.tickets.response.fields.closed.none.${ownOrOther}`, {
|
value: getMessage(`commands.slash.tickets.response.fields.closed.none.${ownOrOther}`, {
|
||||||
new: `</${newCommand.name}:${newCommand.id}>`,
|
new: `</${newCommand.name}:${newCommand.id}>`,
|
||||||
user: member.user.toString(),
|
user: member.user.toString(),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
fields.push({
|
fields.push({
|
||||||
name: getMessage('commands.slash.tickets.response.fields.closed.name'),
|
name: getMessage('commands.slash.tickets.response.fields.closed.name'),
|
||||||
value: closed.map(ticket => {
|
value: (await Promise.all(
|
||||||
const topic = ticket.topic ? `- \`${decrypt(ticket.topic).replace(/\n/g, ' ').slice(0, 30)}\`` : '';
|
closed.map(async ticket => {
|
||||||
return `> ${ticket.category.name} #${ticket.number} (\`${ticket.id}\`) ${topic}`;
|
const getTopic = async () => (await worker.decrypt(ticket.topic)).replace(/\n/g, ' ').substring(0, 30);
|
||||||
}).join('\n'),
|
const topic = ticket.topic ? `- \`${await getTopic()}\`` : '';
|
||||||
});
|
return `> ${ticket.category.name} #${ticket.number} (\`${ticket.id}\`) ${topic}`;
|
||||||
|
}),
|
||||||
|
)).join('\n'),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await worker.terminate();
|
||||||
}
|
}
|
||||||
// TODO: add portal URL to view all (this list is limited to the last 10)
|
// TODO: add portal URL to view all (this list is limited to the last 10)
|
||||||
|
|
||||||
|
@ -5,9 +5,8 @@ const {
|
|||||||
TextInputBuilder,
|
TextInputBuilder,
|
||||||
TextInputStyle,
|
TextInputStyle,
|
||||||
} = require('discord.js');
|
} = require('discord.js');
|
||||||
const Cryptr = require('cryptr');
|
|
||||||
const { decrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
const ExtendedEmbedBuilder = require('../../lib/embed');
|
const ExtendedEmbedBuilder = require('../../lib/embed');
|
||||||
|
const { quick } = require('../../lib/threads');
|
||||||
|
|
||||||
module.exports = class TopicSlashCommand extends SlashCommand {
|
module.exports = class TopicSlashCommand extends SlashCommand {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -66,7 +65,8 @@ module.exports = class TopicSlashCommand extends SlashCommand {
|
|||||||
.setPlaceholder(getMessage('modals.topic.placeholder'))
|
.setPlaceholder(getMessage('modals.topic.placeholder'))
|
||||||
.setRequired(true);
|
.setRequired(true);
|
||||||
|
|
||||||
if (ticket.topic) field.setValue(decrypt(ticket.topic)); // why can't discord.js accept null or undefined :(
|
// why can't discord.js accept null or undefined :(
|
||||||
|
if (ticket.topic) field.setValue(await quick('crypto', w => w.decrypt(ticket.topic)));
|
||||||
|
|
||||||
await interaction.showModal(
|
await interaction.showModal(
|
||||||
new ModalBuilder()
|
new ModalBuilder()
|
||||||
|
@ -7,9 +7,8 @@ const fs = require('fs');
|
|||||||
const { join } = require('path');
|
const { join } = require('path');
|
||||||
const Mustache = require('mustache');
|
const Mustache = require('mustache');
|
||||||
const { AttachmentBuilder } = require('discord.js');
|
const { AttachmentBuilder } = require('discord.js');
|
||||||
const Cryptr = require('cryptr');
|
|
||||||
const { decrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
const ExtendedEmbedBuilder = require('../../lib/embed');
|
const ExtendedEmbedBuilder = require('../../lib/embed');
|
||||||
|
const { quick } = require('../../lib/threads');
|
||||||
|
|
||||||
module.exports = class TranscriptSlashCommand extends SlashCommand {
|
module.exports = class TranscriptSlashCommand extends SlashCommand {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -61,31 +60,9 @@ module.exports = class TranscriptSlashCommand extends SlashCommand {
|
|||||||
/** @type {import("client")} */
|
/** @type {import("client")} */
|
||||||
const client = this.client;
|
const client = this.client;
|
||||||
|
|
||||||
ticket.claimedBy = ticket.archivedUsers.find(u => u.userId === ticket.claimedById);
|
// TODO: use a pool of multiple threads
|
||||||
ticket.closedBy = ticket.archivedUsers.find(u => u.userId === ticket.closedById);
|
// this is still slow for lots of messages
|
||||||
ticket.createdBy = ticket.archivedUsers.find(u => u.userId === ticket.createdById);
|
ticket = await quick('transcript', w => w(ticket));
|
||||||
|
|
||||||
if (ticket.closedReason) ticket.closedReason = decrypt(ticket.closedReason);
|
|
||||||
if (ticket.feedback?.comment) ticket.feedback.comment = decrypt(ticket.feedback.comment);
|
|
||||||
if (ticket.topic) ticket.topic = decrypt(ticket.topic).replace(/\n/g, '\n\t');
|
|
||||||
|
|
||||||
ticket.archivedUsers.forEach((user, i) => {
|
|
||||||
if (user.displayName) user.displayName = decrypt(user.displayName);
|
|
||||||
user.username = decrypt(user.username);
|
|
||||||
ticket.archivedUsers[i] = user;
|
|
||||||
});
|
|
||||||
|
|
||||||
ticket.archivedMessages.forEach((message, i) => {
|
|
||||||
message.author = ticket.archivedUsers.find(u => u.userId === message.authorId);
|
|
||||||
message.content = JSON.parse(decrypt(message.content));
|
|
||||||
message.text = message.content.content?.replace(/\n/g, '\n\t') ?? '';
|
|
||||||
message.content.attachments?.forEach(a => (message.text += '\n\t' + a.url));
|
|
||||||
message.content.embeds?.forEach(() => (message.text += '\n\t[embedded content]'));
|
|
||||||
message.number = 'M' + String(i + 1).padStart(ticket.archivedMessages.length.toString().length, '0');
|
|
||||||
ticket.archivedMessages[i] = message;
|
|
||||||
});
|
|
||||||
|
|
||||||
ticket.pinnedMessageIds = ticket.pinnedMessageIds.map(id => ticket.archivedMessages.find(message => message.id === id)?.number);
|
|
||||||
|
|
||||||
const channelName = ticket.category.channelName
|
const channelName = ticket.category.channelName
|
||||||
.replace(/{+\s?(user)?name\s?}+/gi, ticket.createdBy?.username)
|
.replace(/{+\s?(user)?name\s?}+/gi, ticket.createdBy?.username)
|
||||||
|
@ -3,8 +3,8 @@ const {
|
|||||||
ApplicationCommandOptionType,
|
ApplicationCommandOptionType,
|
||||||
EmbedBuilder,
|
EmbedBuilder,
|
||||||
} = require('discord.js');
|
} = require('discord.js');
|
||||||
const Cryptr = require('cryptr');
|
const { quick } = require('../../lib/threads');
|
||||||
const { decrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
|
|
||||||
module.exports = class TransferSlashCommand extends SlashCommand {
|
module.exports = class TransferSlashCommand extends SlashCommand {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -71,7 +71,7 @@ module.exports = class TransferSlashCommand extends SlashCommand {
|
|||||||
}),
|
}),
|
||||||
interaction.channel.edit({
|
interaction.channel.edit({
|
||||||
name: channelName,
|
name: channelName,
|
||||||
topic: `${member.toString()}${ticket.topic?.length > 0 ? ` | ${decrypt(ticket.topic)}` : ''}`,
|
topic: `${member.toString()}${ticket.topic && ` | ${await quick('crypto', w => w.decrypt(ticket.topic))}`}`,
|
||||||
}),
|
}),
|
||||||
interaction.channel.permissionOverwrites.edit(
|
interaction.channel.permissionOverwrites.edit(
|
||||||
member,
|
member,
|
||||||
|
@ -39,7 +39,7 @@ async function sendToHouston(client) {
|
|||||||
activated_users: users._count,
|
activated_users: users._count,
|
||||||
arch: process.arch,
|
arch: process.arch,
|
||||||
database: process.env.DB_PROVIDER,
|
database: process.env.DB_PROVIDER,
|
||||||
guilds: await relativePool(0.25, 'stats', pool => Promise.all(
|
guilds: await relativePool(.25, 'stats', pool => Promise.all(
|
||||||
guilds
|
guilds
|
||||||
.filter(guild => client.guilds.cache.has(guild.id))
|
.filter(guild => client.guilds.cache.has(guild.id))
|
||||||
.map(guild => {
|
.map(guild => {
|
||||||
|
@ -8,13 +8,13 @@ const { cpus } = require('node:os');
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Use a thread pool of a fixed size
|
* Use a thread pool of a fixed size
|
||||||
* @param {number} size number of threads
|
|
||||||
* @param {string} name name of file in workers directory
|
* @param {string} name name of file in workers directory
|
||||||
* @param {function} fun async function
|
* @param {function} fun async function
|
||||||
|
* @param {import('threads/dist/master/pool').PoolOptions} options
|
||||||
* @returns {Promise<any>}
|
* @returns {Promise<any>}
|
||||||
*/
|
*/
|
||||||
async function pool(size, name, fun) {
|
async function pool(name, fun, options) {
|
||||||
const pool = Pool(() => spawn(new Worker(`./workers/${name}.js`)), { size });
|
const pool = Pool(() => spawn(new Worker(`./workers/${name}.js`)), options);
|
||||||
try {
|
try {
|
||||||
return await fun(pool);
|
return await fun(pool);
|
||||||
} finally {
|
} finally {
|
||||||
@ -40,19 +40,35 @@ async function quick(name, fun) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Use a thread pool of a variable size
|
* Use a thread pool of a variable size
|
||||||
* @param {number} size fraction of available CPU cores to use (ceil'd)
|
* @param {number} fraction fraction of available CPU cores to use (ceil'd)
|
||||||
* @param {string} name name of file in workers directory
|
* @param {string} name name of file in workers directory
|
||||||
* @param {function} fun async function
|
* @param {function} fun async function
|
||||||
|
* @param {import('threads/dist/master/pool').PoolOptions} options
|
||||||
* @returns {Promise<any>}
|
* @returns {Promise<any>}
|
||||||
*/
|
*/
|
||||||
function relativePool(fraction, ...args) {
|
function relativePool(fraction, name, fun, options) {
|
||||||
// ! ceiL: at least 1
|
// ! ceiL: at least 1
|
||||||
const poolSize = Math.ceil(fraction * cpus().length);
|
const size = Math.ceil(fraction * cpus().length);
|
||||||
return pool(poolSize, ...args);
|
return pool(name, fun, {
|
||||||
|
...options,
|
||||||
|
size,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spawn one thread
|
||||||
|
* @param {string} name name of file in workers directory
|
||||||
|
* @returns {Promise<{terminate: function}>}
|
||||||
|
*/
|
||||||
|
async function reusable(name) {
|
||||||
|
const thread = await spawn(new Worker(`./workers/${name}.js`));
|
||||||
|
thread.terminate = () => Thread.terminate(thread);
|
||||||
|
return thread;
|
||||||
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
pool,
|
pool,
|
||||||
quick,
|
quick,
|
||||||
relativePool,
|
relativePool,
|
||||||
|
reusable,
|
||||||
};
|
};
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
const Cryptr = require('cryptr');
|
const { reusable } = require('../threads');
|
||||||
const { encrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns highest (roles.highest) hoisted role, or everyone
|
* Returns highest (roles.highest) hoisted role, or everyone
|
||||||
@ -71,85 +71,90 @@ module.exports = class TicketArchiver {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const member of members) {
|
const worker = await reusable('crypto');
|
||||||
const data = {
|
try {
|
||||||
avatar: member.avatar || member.user.avatar, // TODO: save avatar in user/avatars/
|
for (const member of members) {
|
||||||
bot: member.user.bot,
|
const data = {
|
||||||
discriminator: member.user.discriminator,
|
avatar: member.avatar || member.user.avatar, // TODO: save avatar in user/avatars/
|
||||||
displayName: member.displayName ? encrypt(member.displayName) : null,
|
bot: member.user.bot,
|
||||||
roleId: !!member && hoistedRole(member).id,
|
discriminator: member.user.discriminator,
|
||||||
ticketId,
|
displayName: member.displayName ? await worker.encrypt(member.displayName) : null,
|
||||||
userId: member.user.id,
|
roleId: !!member && hoistedRole(member).id,
|
||||||
username: encrypt(member.user.username),
|
ticketId,
|
||||||
};
|
userId: member.user.id,
|
||||||
await this.client.prisma.archivedUser.upsert({
|
username: await worker.encrypt(member.user.username),
|
||||||
create: data,
|
};
|
||||||
update: data,
|
await this.client.prisma.archivedUser.upsert({
|
||||||
where: {
|
create: data,
|
||||||
ticketId_userId: {
|
update: data,
|
||||||
ticketId,
|
where: {
|
||||||
userId: member.user.id,
|
ticketId_userId: {
|
||||||
|
ticketId,
|
||||||
|
userId: member.user.id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let reference;
|
||||||
|
if (message.reference) reference = await message.fetchReference();
|
||||||
|
|
||||||
|
const messageD = {
|
||||||
|
author: {
|
||||||
|
connect: {
|
||||||
|
ticketId_userId: {
|
||||||
|
ticketId,
|
||||||
|
userId: message.author?.id || 'default',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
content: await worker.encrypt(
|
||||||
}
|
JSON.stringify({
|
||||||
|
attachments: [...message.attachments.values()],
|
||||||
let reference;
|
components: [...message.components.values()],
|
||||||
if (message.reference) reference = await message.fetchReference();
|
content: message.content,
|
||||||
|
embeds: message.embeds.map(embed => ({ ...embed })),
|
||||||
const messageD = {
|
reference: reference ? reference.id : null,
|
||||||
author: {
|
|
||||||
connect: {
|
|
||||||
ticketId_userId: {
|
|
||||||
ticketId,
|
|
||||||
userId: message.author?.id || 'default',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
content: encrypt(
|
|
||||||
JSON.stringify({
|
|
||||||
attachments: [...message.attachments.values()],
|
|
||||||
components: [...message.components.values()],
|
|
||||||
content: message.content,
|
|
||||||
embeds: message.embeds.map(embed => ({ ...embed })),
|
|
||||||
reference: reference ? reference.id : null,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
createdAt: message.createdAt,
|
|
||||||
edited: !!message.editedAt,
|
|
||||||
external,
|
|
||||||
id: message.id,
|
|
||||||
};
|
|
||||||
|
|
||||||
return await this.client.prisma.ticket.update({
|
|
||||||
data: {
|
|
||||||
archivedChannels: {
|
|
||||||
upsert: channels.map(channel => {
|
|
||||||
const data = {
|
|
||||||
channelId: channel.id,
|
|
||||||
name: channel.name,
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
create: data,
|
|
||||||
update: data,
|
|
||||||
where: {
|
|
||||||
ticketId_channelId: {
|
|
||||||
channelId: channel.id,
|
|
||||||
ticketId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}),
|
}),
|
||||||
},
|
),
|
||||||
archivedMessages: {
|
createdAt: message.createdAt,
|
||||||
upsert: {
|
edited: !!message.editedAt,
|
||||||
create: messageD,
|
external,
|
||||||
update: messageD,
|
id: message.id,
|
||||||
where: { id: message.id },
|
};
|
||||||
|
|
||||||
|
return await this.client.prisma.ticket.update({
|
||||||
|
data: {
|
||||||
|
archivedChannels: {
|
||||||
|
upsert: channels.map(channel => {
|
||||||
|
const data = {
|
||||||
|
channelId: channel.id,
|
||||||
|
name: channel.name,
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
create: data,
|
||||||
|
update: data,
|
||||||
|
where: {
|
||||||
|
ticketId_channelId: {
|
||||||
|
channelId: channel.id,
|
||||||
|
ticketId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
archivedMessages: {
|
||||||
|
upsert: {
|
||||||
|
create: messageD,
|
||||||
|
update: messageD,
|
||||||
|
where: { id: message.id },
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
where: { id: ticketId },
|
||||||
where: { id: ticketId },
|
});
|
||||||
});
|
} finally {
|
||||||
|
await worker.terminate();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -19,13 +19,13 @@ const { logTicketEvent } = require('../logging');
|
|||||||
const { isStaff } = require('../users');
|
const { isStaff } = require('../users');
|
||||||
const { Collection } = require('discord.js');
|
const { Collection } = require('discord.js');
|
||||||
const spacetime = require('spacetime');
|
const spacetime = require('spacetime');
|
||||||
const Cryptr = require('cryptr');
|
|
||||||
const {
|
|
||||||
decrypt,
|
|
||||||
encrypt,
|
|
||||||
} = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
const { getSUID } = require('../logging');
|
const { getSUID } = require('../logging');
|
||||||
const { getAverageTimes } = require('../stats');
|
const { getAverageTimes } = require('../stats');
|
||||||
|
const {
|
||||||
|
quick,
|
||||||
|
reusable,
|
||||||
|
} = require('../threads');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {import('@prisma/client').Category &
|
* @typedef {import('@prisma/client').Category &
|
||||||
@ -148,7 +148,9 @@ module.exports = class TicketManager {
|
|||||||
/**
|
/**
|
||||||
* @param {object} data
|
* @param {object} data
|
||||||
* @param {string} data.categoryId
|
* @param {string} data.categoryId
|
||||||
* @param {import("discord.js").ChatInputCommandInteraction|import("discord.js").ButtonInteraction|import("discord.js").SelectMenuInteraction} data.interaction
|
* @param {import("discord.js").ChatInputCommandInteraction
|
||||||
|
* | import("discord.js").ButtonInteraction
|
||||||
|
* | import("discord.js").SelectMenuInteraction} data.interaction
|
||||||
* @param {string?} [data.topic]
|
* @param {string?} [data.topic]
|
||||||
*/
|
*/
|
||||||
async create({
|
async create({
|
||||||
@ -353,7 +355,9 @@ module.exports = class TicketManager {
|
|||||||
/**
|
/**
|
||||||
* @param {object} data
|
* @param {object} data
|
||||||
* @param {string} data.category
|
* @param {string} data.category
|
||||||
* @param {import("discord.js").ButtonInteraction|import("discord.js").SelectMenuInteraction|import("discord.js").ModalSubmitInteraction} data.interaction
|
* @param {import("discord.js").ButtonInteraction
|
||||||
|
* | import("discord.js").SelectMenuInteraction
|
||||||
|
* | import("discord.js").ModalSubmitInteraction} data.interaction
|
||||||
* @param {string?} [data.topic]
|
* @param {string?} [data.topic]
|
||||||
*/
|
*/
|
||||||
async postQuestions({
|
async postQuestions({
|
||||||
@ -367,11 +371,22 @@ module.exports = class TicketManager {
|
|||||||
let answers;
|
let answers;
|
||||||
if (interaction.isModalSubmit()) {
|
if (interaction.isModalSubmit()) {
|
||||||
if (action === 'questions') {
|
if (action === 'questions') {
|
||||||
answers = category.questions.filter(q => q.type === 'TEXT').map(q => ({
|
const worker = await reusable('crypto');
|
||||||
questionId: q.id,
|
try {
|
||||||
userId: interaction.user.id,
|
answers = await Promise.all(
|
||||||
value: interaction.fields.getTextInputValue(q.id) ? encrypt(interaction.fields.getTextInputValue(q.id)) : '',
|
category.questions
|
||||||
}));
|
.filter(q => q.type === 'TEXT')
|
||||||
|
.map(async q => ({
|
||||||
|
questionId: q.id,
|
||||||
|
userId: interaction.user.id,
|
||||||
|
value: interaction.fields.getTextInputValue(q.id)
|
||||||
|
? await worker.encrypt(interaction.fields.getTextInputValue(q.id))
|
||||||
|
: '', // TODO: maybe this should be null?
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await worker.terminate();
|
||||||
|
}
|
||||||
if (category.customTopic) topic = interaction.fields.getTextInputValue(category.customTopic);
|
if (category.customTopic) topic = interaction.fields.getTextInputValue(category.customTopic);
|
||||||
} else if (action === 'topic') {
|
} else if (action === 'topic') {
|
||||||
topic = interaction.fields.getTextInputValue('topic');
|
topic = interaction.fields.getTextInputValue('topic');
|
||||||
@ -612,7 +627,7 @@ module.exports = class TicketManager {
|
|||||||
embed.addFields({
|
embed.addFields({
|
||||||
inline: false,
|
inline: false,
|
||||||
name: getMessage('ticket.references_ticket.fields.topic'),
|
name: getMessage('ticket.references_ticket.fields.topic'),
|
||||||
value: decrypt(ticket.topic),
|
value: await quick('crypto', worker => worker.decrypt(ticket.topic)),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
await channel.send({ embeds: [embed] });
|
await channel.send({ embeds: [embed] });
|
||||||
@ -631,7 +646,7 @@ module.exports = class TicketManager {
|
|||||||
id: channel.id,
|
id: channel.id,
|
||||||
number,
|
number,
|
||||||
openingMessageId: sent.id,
|
openingMessageId: sent.id,
|
||||||
topic: topic ? encrypt(topic) : null,
|
topic: topic ? await quick('crypto', worker => worker.encrypt(topic)) : null,
|
||||||
};
|
};
|
||||||
if (referencesTicketId) data.referencesTicket = { connect: { id: referencesTicketId } };
|
if (referencesTicketId) data.referencesTicket = { connect: { id: referencesTicketId } };
|
||||||
if (answers) data.questionAnswers = { createMany: { data: answers } };
|
if (answers) data.questionAnswers = { createMany: { data: answers } };
|
||||||
@ -1073,7 +1088,9 @@ module.exports = class TicketManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("discord.js").ChatInputCommandInteraction|import("discord.js").ButtonInteraction|import("discord.js").ModalSubmitInteraction} interaction
|
* @param {import("discord.js").ChatInputCommandInteraction
|
||||||
|
* | import("discord.js").ButtonInteraction
|
||||||
|
* | import("discord.js").ModalSubmitInteraction} interaction
|
||||||
* @param {string} reason
|
* @param {string} reason
|
||||||
*/
|
*/
|
||||||
async requestClose(interaction, reason) {
|
async requestClose(interaction, reason) {
|
||||||
@ -1143,7 +1160,9 @@ module.exports = class TicketManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import("discord.js").ChatInputCommandInteraction|import("discord.js").ButtonInteraction|import("discord.js").ModalSubmitInteraction} interaction
|
* @param {import("discord.js").ChatInputCommandInteraction
|
||||||
|
* | import("discord.js").ButtonInteraction
|
||||||
|
* | import("discord.js").ModalSubmitInteraction} interaction
|
||||||
*/
|
*/
|
||||||
async acceptClose(interaction) {
|
async acceptClose(interaction) {
|
||||||
const ticket = await this.getTicket(interaction.channel.id);
|
const ticket = await this.getTicket(interaction.channel.id);
|
||||||
@ -1191,7 +1210,7 @@ module.exports = class TicketManager {
|
|||||||
where: { id: closedBy },
|
where: { id: closedBy },
|
||||||
},
|
},
|
||||||
} || undefined, // Prisma wants undefined not null because it is a relation
|
} || undefined, // Prisma wants undefined not null because it is a relation
|
||||||
closedReason: reason && encrypt(reason),
|
closedReason: reason && await quick('crypto', worker => worker.encrypt(reason)),
|
||||||
messageCount: archivedMessages,
|
messageCount: archivedMessages,
|
||||||
open: false,
|
open: false,
|
||||||
};
|
};
|
||||||
@ -1248,7 +1267,7 @@ module.exports = class TicketManager {
|
|||||||
embed.addFields({
|
embed.addFields({
|
||||||
inline: true,
|
inline: true,
|
||||||
name: getMessage('dm.closed.fields.topic'),
|
name: getMessage('dm.closed.fields.topic'),
|
||||||
value: decrypt(ticket.topic),
|
value: await quick('crypto', worker => worker.decrypt(ticket.topic)),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
11
src/lib/workers/crypto.js
Normal file
11
src/lib/workers/crypto.js
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
const { expose } = require('threads/worker');
|
||||||
|
const Cryptr = require('cryptr');
|
||||||
|
const {
|
||||||
|
encrypt,
|
||||||
|
decrypt,
|
||||||
|
} = new Cryptr(process.env.ENCRYPTION_KEY);
|
||||||
|
|
||||||
|
expose({
|
||||||
|
decrypt,
|
||||||
|
encrypt,
|
||||||
|
});
|
36
src/lib/workers/transcript.js
Normal file
36
src/lib/workers/transcript.js
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
const { expose } = require('threads/worker');
|
||||||
|
const Cryptr = require('cryptr');
|
||||||
|
const { decrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
|
||||||
|
|
||||||
|
function getTranscript(ticket) {
|
||||||
|
ticket.claimedBy = ticket.archivedUsers.find(u => u.userId === ticket.claimedById);
|
||||||
|
ticket.closedBy = ticket.archivedUsers.find(u => u.userId === ticket.closedById);
|
||||||
|
ticket.createdBy = ticket.archivedUsers.find(u => u.userId === ticket.createdById);
|
||||||
|
|
||||||
|
if (ticket.closedReason) ticket.closedReason = decrypt(ticket.closedReason);
|
||||||
|
if (ticket.feedback?.comment) ticket.feedback.comment = decrypt(ticket.feedback.comment);
|
||||||
|
if (ticket.topic) ticket.topic = decrypt(ticket.topic).replace(/\n/g, '\n\t');
|
||||||
|
|
||||||
|
ticket.archivedUsers.forEach((user, i) => {
|
||||||
|
if (user.displayName) user.displayName = decrypt(user.displayName);
|
||||||
|
user.username = decrypt(user.username);
|
||||||
|
ticket.archivedUsers[i] = user;
|
||||||
|
});
|
||||||
|
|
||||||
|
ticket.archivedMessages.forEach((message, i) => {
|
||||||
|
message.author = ticket.archivedUsers.find(u => u.userId === message.authorId);
|
||||||
|
message.content = JSON.parse(decrypt(message.content));
|
||||||
|
message.text = message.content.content?.replace(/\n/g, '\n\t') ?? '';
|
||||||
|
message.content.attachments?.forEach(a => (message.text += '\n\t' + a.url));
|
||||||
|
message.content.embeds?.forEach(() => (message.text += '\n\t[embedded content]'));
|
||||||
|
message.number = 'M' + String(i + 1).padStart(ticket.archivedMessages.length.toString().length, '0');
|
||||||
|
ticket.archivedMessages[i] = message;
|
||||||
|
});
|
||||||
|
|
||||||
|
ticket.pinnedMessageIds = ticket.pinnedMessageIds.map(id => ticket.archivedMessages.find(message => message.id === id)?.number);
|
||||||
|
return ticket;
|
||||||
|
}
|
||||||
|
|
||||||
|
expose(getTranscript);
|
||||||
|
|
||||||
|
|
@ -1,8 +1,7 @@
|
|||||||
const { Listener } = require('@eartharoid/dbf');
|
const { Listener } = require('@eartharoid/dbf');
|
||||||
const { AuditLogEvent } = require('discord.js');
|
const { AuditLogEvent } = require('discord.js');
|
||||||
const { logMessageEvent } = require('../../lib/logging');
|
const { logMessageEvent } = require('../../lib/logging');
|
||||||
const Cryptr = require('cryptr');
|
const { quick } = require('../../lib/threads');
|
||||||
const { decrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
|
|
||||||
module.exports = class extends Listener {
|
module.exports = class extends Listener {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -38,8 +37,11 @@ module.exports = class extends Listener {
|
|||||||
if (ticket.guild.archive) {
|
if (ticket.guild.archive) {
|
||||||
try {
|
try {
|
||||||
const archived = await client.prisma.archivedMessage.findUnique({ where: { id: message.id } });
|
const archived = await client.prisma.archivedMessage.findUnique({ where: { id: message.id } });
|
||||||
if (archived) {
|
if (archived?.content) {
|
||||||
if (!content) content = JSON.parse(decrypt(archived.content)).content; // won't be cleaned
|
if (!content) {
|
||||||
|
const string = await quick('crypto', worker => worker.decrypt(archived.content));
|
||||||
|
content = JSON.parse(string).content; // won't be cleaned
|
||||||
|
}
|
||||||
await client.prisma.archivedMessage.update({
|
await client.prisma.archivedMessage.update({
|
||||||
data: { deleted: true },
|
data: { deleted: true },
|
||||||
where: { id: message.id },
|
where: { id: message.id },
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
const { Modal } = require('@eartharoid/dbf');
|
const { Modal } = require('@eartharoid/dbf');
|
||||||
const ExtendedEmbedBuilder = require('../lib/embed');
|
const ExtendedEmbedBuilder = require('../lib/embed');
|
||||||
const Cryptr = require('cryptr');
|
const { quick } = require('../lib/threads');
|
||||||
const { encrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
|
|
||||||
module.exports = class FeedbackModal extends Modal {
|
module.exports = class FeedbackModal extends Modal {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -26,7 +25,7 @@ module.exports = class FeedbackModal extends Modal {
|
|||||||
rating = Math.min(Math.max(rating, 1), 5); // clamp between 1 and 5 (0 and null become 1, 6 becomes 5)
|
rating = Math.min(Math.max(rating, 1), 5); // clamp between 1 and 5 (0 and null become 1, 6 becomes 5)
|
||||||
|
|
||||||
const data = {
|
const data = {
|
||||||
comment: comment?.length > 0 ? encrypt(comment) : null,
|
comment: comment?.length > 0 ? await quick('crypto', worker => worker.encrypt(comment)) : null,
|
||||||
guild: { connect: { id: interaction.guild.id } },
|
guild: { connect: { id: interaction.guild.id } },
|
||||||
rating,
|
rating,
|
||||||
user: { connect: { id: interaction.user.id } },
|
user: { connect: { id: interaction.user.id } },
|
||||||
@ -65,4 +64,4 @@ module.exports = class FeedbackModal extends Modal {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -2,11 +2,8 @@ const { Modal } = require('@eartharoid/dbf');
|
|||||||
const { EmbedBuilder } = require('discord.js');
|
const { EmbedBuilder } = require('discord.js');
|
||||||
const ExtendedEmbedBuilder = require('../lib/embed');
|
const ExtendedEmbedBuilder = require('../lib/embed');
|
||||||
const { logTicketEvent } = require('../lib/logging');
|
const { logTicketEvent } = require('../lib/logging');
|
||||||
const Cryptr = require('cryptr');
|
const { reusable } = require('../lib/threads');
|
||||||
const {
|
|
||||||
encrypt,
|
|
||||||
decrypt,
|
|
||||||
} = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
|
|
||||||
module.exports = class QuestionsModal extends Modal {
|
module.exports = class QuestionsModal extends Modal {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -26,101 +23,111 @@ module.exports = class QuestionsModal extends Modal {
|
|||||||
const client = this.client;
|
const client = this.client;
|
||||||
|
|
||||||
if (id.edit) {
|
if (id.edit) {
|
||||||
await interaction.deferReply({ ephemeral: true });
|
const worker = await reusable('crypto');
|
||||||
|
try {
|
||||||
|
await interaction.deferReply({ ephemeral: true });
|
||||||
|
|
||||||
const { category } = await client.prisma.ticket.findUnique({
|
const { category } = await client.prisma.ticket.findUnique({
|
||||||
select: { category: { select: { customTopic: true } } },
|
select: { category: { select: { customTopic: true } } },
|
||||||
where: { id: interaction.channel.id },
|
where: { id: interaction.channel.id },
|
||||||
});
|
});
|
||||||
const select = {
|
const select = {
|
||||||
createdById: true,
|
createdById: true,
|
||||||
guild: {
|
guild: {
|
||||||
select: {
|
select: {
|
||||||
footer: true,
|
footer: true,
|
||||||
locale: true,
|
locale: true,
|
||||||
successColour: true,
|
successColour: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
id: true,
|
id: true,
|
||||||
openingMessageId: true,
|
openingMessageId: true,
|
||||||
questionAnswers: { include: { question: true } },
|
questionAnswers: { include: { question: true } },
|
||||||
};
|
};
|
||||||
const original = await client.prisma.ticket.findUnique({
|
const original = await client.prisma.ticket.findUnique({
|
||||||
select,
|
select,
|
||||||
where: { id: interaction.channel.id },
|
where: { id: interaction.channel.id },
|
||||||
});
|
|
||||||
|
|
||||||
let topic;
|
|
||||||
if (category.customTopic) {
|
|
||||||
const customTopicAnswer = original.questionAnswers.find(a => a.question.id === category.customTopic);
|
|
||||||
if (!customTopicAnswer) throw new Error('Custom topic answer not found');
|
|
||||||
topic = interaction.fields.getTextInputValue(String(customTopicAnswer.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
const ticket = await client.prisma.ticket.update({
|
|
||||||
data: {
|
|
||||||
questionAnswers: {
|
|
||||||
update: interaction.fields.fields.map(f => ({
|
|
||||||
data: { value: f.value ? encrypt(f.value) : '' },
|
|
||||||
where: { id: Number(f.customId) },
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
topic: topic ? encrypt(topic) : null,
|
|
||||||
},
|
|
||||||
select,
|
|
||||||
where: { id: interaction.channel.id },
|
|
||||||
});
|
|
||||||
const getMessage = client.i18n.getLocale(ticket.guild.locale);
|
|
||||||
|
|
||||||
if (topic) await interaction.channel.setTopic(`<@${ticket.createdById}> | ${topic}`);
|
|
||||||
|
|
||||||
const opening = await interaction.channel.messages.fetch(ticket.openingMessageId);
|
|
||||||
if (opening && opening.embeds.length >= 2) {
|
|
||||||
const embeds = [...opening.embeds];
|
|
||||||
embeds[1] = new EmbedBuilder(embeds[1].data)
|
|
||||||
.setFields(
|
|
||||||
ticket.questionAnswers
|
|
||||||
.map(a => ({
|
|
||||||
name: a.question.label,
|
|
||||||
value: a.value ? decrypt(a.value) : getMessage('ticket.answers.no_value'),
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
await opening.edit({ embeds });
|
|
||||||
}
|
|
||||||
|
|
||||||
await interaction.editReply({
|
|
||||||
embeds: [
|
|
||||||
new ExtendedEmbedBuilder({
|
|
||||||
iconURL: interaction.guild.iconURL(),
|
|
||||||
text: ticket.guild.footer,
|
|
||||||
})
|
|
||||||
.setColor(ticket.guild.successColour)
|
|
||||||
.setTitle(getMessage('ticket.edited.title'))
|
|
||||||
.setDescription(getMessage('ticket.edited.description')),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
/** @param {ticket} ticket */
|
|
||||||
const makeDiff = ticket => {
|
|
||||||
const diff = {};
|
|
||||||
ticket.questionAnswers.forEach(a => {
|
|
||||||
diff[a.question.label] = a.value ? decrypt(a.value) : getMessage('ticket.answers.no_value');
|
|
||||||
});
|
});
|
||||||
return diff;
|
|
||||||
};
|
|
||||||
|
|
||||||
logTicketEvent(this.client, {
|
let topic;
|
||||||
action: 'update',
|
if (category.customTopic) {
|
||||||
diff: {
|
const customTopicAnswer = original.questionAnswers.find(a => a.question.id === category.customTopic);
|
||||||
original: makeDiff(original),
|
if (!customTopicAnswer) throw new Error('Custom topic answer not found');
|
||||||
updated: makeDiff(ticket),
|
topic = interaction.fields.getTextInputValue(String(customTopicAnswer.id));
|
||||||
},
|
}
|
||||||
target: {
|
|
||||||
id: ticket.id,
|
const ticket = await client.prisma.ticket.update({
|
||||||
name: `<#${ticket.id}>`,
|
data: {
|
||||||
},
|
questionAnswers: {
|
||||||
userId: interaction.user.id,
|
update: await Promise.all(
|
||||||
});
|
interaction.fields.fields
|
||||||
|
.map(async f => ({
|
||||||
|
data: { value: f.value ? await worker.encrypt(f.value) : '' },
|
||||||
|
where: { id: Number(f.customId) },
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
topic: topic ? await worker.encrypt(topic) : null,
|
||||||
|
},
|
||||||
|
select,
|
||||||
|
where: { id: interaction.channel.id },
|
||||||
|
});
|
||||||
|
const getMessage = client.i18n.getLocale(ticket.guild.locale);
|
||||||
|
|
||||||
|
if (topic) await interaction.channel.setTopic(`<@${ticket.createdById}> | ${topic}`);
|
||||||
|
|
||||||
|
const opening = await interaction.channel.messages.fetch(ticket.openingMessageId);
|
||||||
|
if (opening && opening.embeds.length >= 2) {
|
||||||
|
const embeds = [...opening.embeds];
|
||||||
|
embeds[1] = new EmbedBuilder(embeds[1].data)
|
||||||
|
.setFields(
|
||||||
|
await Promise.all(
|
||||||
|
ticket.questionAnswers
|
||||||
|
.map(async a => ({
|
||||||
|
name: a.question.label,
|
||||||
|
value: a.value ? await worker.decrypt(a.value) : getMessage('ticket.answers.no_value'),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await opening.edit({ embeds });
|
||||||
|
}
|
||||||
|
|
||||||
|
await interaction.editReply({
|
||||||
|
embeds: [
|
||||||
|
new ExtendedEmbedBuilder({
|
||||||
|
iconURL: interaction.guild.iconURL(),
|
||||||
|
text: ticket.guild.footer,
|
||||||
|
})
|
||||||
|
.setColor(ticket.guild.successColour)
|
||||||
|
.setTitle(getMessage('ticket.edited.title'))
|
||||||
|
.setDescription(getMessage('ticket.edited.description')),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
/** @param {ticket} ticket */
|
||||||
|
const makeDiff = async ticket => {
|
||||||
|
const diff = {};
|
||||||
|
for (const a of ticket.questionAnswers) {
|
||||||
|
diff[a.question.label] = a.value ? await worker.decrypt(a.value) : getMessage('ticket.answers.no_value');
|
||||||
|
}
|
||||||
|
return diff;
|
||||||
|
};
|
||||||
|
|
||||||
|
logTicketEvent(this.client, {
|
||||||
|
action: 'update',
|
||||||
|
diff: {
|
||||||
|
original: await makeDiff(original),
|
||||||
|
updated: await makeDiff(ticket),
|
||||||
|
},
|
||||||
|
target: {
|
||||||
|
id: ticket.id,
|
||||||
|
name: `<#${ticket.id}>`,
|
||||||
|
},
|
||||||
|
userId: interaction.user.id,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await worker.terminate();
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
await this.client.tickets.postQuestions({
|
await this.client.tickets.postQuestions({
|
||||||
...id,
|
...id,
|
||||||
|
@ -2,11 +2,7 @@ const { Modal } = require('@eartharoid/dbf');
|
|||||||
const { EmbedBuilder } = require('discord.js');
|
const { EmbedBuilder } = require('discord.js');
|
||||||
const ExtendedEmbedBuilder = require('../lib/embed');
|
const ExtendedEmbedBuilder = require('../lib/embed');
|
||||||
const { logTicketEvent } = require('../lib/logging');
|
const { logTicketEvent } = require('../lib/logging');
|
||||||
const Cryptr = require('cryptr');
|
const { reusable } = require('../lib/threads');
|
||||||
const {
|
|
||||||
encrypt,
|
|
||||||
decrypt,
|
|
||||||
} = new Cryptr(process.env.ENCRYPTION_KEY);
|
|
||||||
|
|
||||||
module.exports = class TopicModal extends Modal {
|
module.exports = class TopicModal extends Modal {
|
||||||
constructor(client, options) {
|
constructor(client, options) {
|
||||||
@ -21,76 +17,82 @@ module.exports = class TopicModal extends Modal {
|
|||||||
const client = this.client;
|
const client = this.client;
|
||||||
|
|
||||||
if (id.edit) {
|
if (id.edit) {
|
||||||
await interaction.deferReply({ ephemeral: true });
|
const worker = await reusable('crypto');
|
||||||
const topic = interaction.fields.getTextInputValue('topic');
|
try {
|
||||||
const select = {
|
await interaction.deferReply({ ephemeral: true });
|
||||||
createdById: true,
|
const topic = interaction.fields.getTextInputValue('topic');
|
||||||
guild: {
|
const select = {
|
||||||
select: {
|
createdById: true,
|
||||||
footer: true,
|
guild: {
|
||||||
locale: true,
|
select: {
|
||||||
successColour: true,
|
footer: true,
|
||||||
|
locale: true,
|
||||||
|
successColour: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
id: true,
|
||||||
id: true,
|
openingMessageId: true,
|
||||||
openingMessageId: true,
|
topic: true,
|
||||||
topic: true,
|
};
|
||||||
};
|
const original = await client.prisma.ticket.findUnique({
|
||||||
const original = await client.prisma.ticket.findUnique({
|
select,
|
||||||
select,
|
where: { id: interaction.channel.id },
|
||||||
where: { id: interaction.channel.id },
|
});
|
||||||
});
|
const ticket = await client.prisma.ticket.update({
|
||||||
const ticket = await client.prisma.ticket.update({
|
data: { topic: topic ? await worker.encrypt(topic) : null },
|
||||||
data: { topic: topic ? encrypt(topic) : null },
|
select,
|
||||||
select,
|
where: { id: interaction.channel.id },
|
||||||
where: { id: interaction.channel.id },
|
});
|
||||||
});
|
const getMessage = client.i18n.getLocale(ticket.guild.locale);
|
||||||
const getMessage = client.i18n.getLocale(ticket.guild.locale);
|
|
||||||
|
|
||||||
if (topic) interaction.channel.setTopic(`<@${ticket.createdById}> | ${topic}`);
|
if (topic) interaction.channel.setTopic(`<@${ticket.createdById}> | ${topic}`);
|
||||||
|
|
||||||
const opening = await interaction.channel.messages.fetch(ticket.openingMessageId);
|
const opening = await interaction.channel.messages.fetch(ticket.openingMessageId);
|
||||||
if (opening && opening.embeds.length >= 2) {
|
if (opening && opening.embeds.length >= 2) {
|
||||||
const embeds = [...opening.embeds];
|
const embeds = [...opening.embeds];
|
||||||
embeds[1] = new EmbedBuilder(embeds[1].data)
|
embeds[1] = new EmbedBuilder(embeds[1].data)
|
||||||
.setFields({
|
.setFields({
|
||||||
name: getMessage('ticket.opening_message.fields.topic'),
|
name: getMessage('ticket.opening_message.fields.topic'),
|
||||||
value: topic,
|
value: topic,
|
||||||
});
|
});
|
||||||
await opening.edit({ embeds });
|
await opening.edit({ embeds });
|
||||||
|
}
|
||||||
|
|
||||||
|
await interaction.editReply({
|
||||||
|
embeds: [
|
||||||
|
new ExtendedEmbedBuilder({
|
||||||
|
iconURL: interaction.guild.iconURL(),
|
||||||
|
text: ticket.guild.footer,
|
||||||
|
})
|
||||||
|
.setColor(ticket.guild.successColour)
|
||||||
|
.setTitle(getMessage('ticket.edited.title'))
|
||||||
|
.setDescription(getMessage('ticket.edited.description')),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
/** @param {ticket} ticket */
|
||||||
|
const makeDiff = async ticket => {
|
||||||
|
const diff = {};
|
||||||
|
diff[getMessage('ticket.opening_message.fields.topic')] = ticket.topic ? await worker.decrypt(ticket.topic) : ' ';
|
||||||
|
return diff;
|
||||||
|
};
|
||||||
|
|
||||||
|
logTicketEvent(this.client, {
|
||||||
|
action: 'update',
|
||||||
|
diff: {
|
||||||
|
original: await makeDiff(original),
|
||||||
|
updated: await makeDiff(ticket),
|
||||||
|
},
|
||||||
|
target: {
|
||||||
|
id: ticket.id,
|
||||||
|
name: `<#${ticket.id}>`,
|
||||||
|
},
|
||||||
|
userId: interaction.user.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
await worker.terminate();
|
||||||
}
|
}
|
||||||
|
|
||||||
await interaction.editReply({
|
|
||||||
embeds: [
|
|
||||||
new ExtendedEmbedBuilder({
|
|
||||||
iconURL: interaction.guild.iconURL(),
|
|
||||||
text: ticket.guild.footer,
|
|
||||||
})
|
|
||||||
.setColor(ticket.guild.successColour)
|
|
||||||
.setTitle(getMessage('ticket.edited.title'))
|
|
||||||
.setDescription(getMessage('ticket.edited.description')),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
/** @param {ticket} ticket */
|
|
||||||
const makeDiff = ticket => {
|
|
||||||
const diff = {};
|
|
||||||
diff[getMessage('ticket.opening_message.fields.topic')] = ticket.topic ? decrypt(ticket.topic) : ' ';
|
|
||||||
return diff;
|
|
||||||
};
|
|
||||||
|
|
||||||
logTicketEvent(this.client, {
|
|
||||||
action: 'update',
|
|
||||||
diff: {
|
|
||||||
original: makeDiff(original),
|
|
||||||
updated: makeDiff(ticket),
|
|
||||||
},
|
|
||||||
target: {
|
|
||||||
id: ticket.id,
|
|
||||||
name: `<#${ticket.id}>`,
|
|
||||||
},
|
|
||||||
userId: interaction.user.id,
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
await this.client.tickets.postQuestions({
|
await this.client.tickets.postQuestions({
|
||||||
...id,
|
...id,
|
||||||
@ -98,4 +100,4 @@ module.exports = class TopicModal extends Modal {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
Loading…
x
Reference in New Issue
Block a user