perf: Merge develop into main (#36)

* Update dockerfile for standalone deployment (#23)

* Add files via upload

* Update Docker image for pluralflux service

* removing unnecessary network and container name definitions

---------

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* Converting ES6 back to CJS (#25)

converting back to cjs

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* Fix: Further converting ES6 to CJS - Making exports named instead of default (#26)

* adding to git ignore

* making imports named not default to not break all my tests

* adjusted setup for memberhelper test

---------

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* feat: add db migrations with typeORM (#28)

* adding typescript packages for typeORM

* add typeORM initial files

* updating package scripts

* updating compose.yaml to have an exposed port for the postgres

* modifying setup for typeORM

* update database stuff and and package.json to help generate migrations

* made models and migrations in typeORM

* delete unneeded database.js

* made database pattern ignored by jest

* remove sequelize

* separate member repo from member helper

* not sure why i made everything numbers in the model but it's fixed now

* edited package.json script

* remove unused index.ts

* adjusted files to reference repository correctly and appdatasource

* made appdatasource export as named

* removed start-db script

* added init to appdatasource in bot.js

* migrations finally!

* new migration matching model names I want

* updating tests

* removing testpathignore patterns since it seems to be unecessary?

* adjusting migrations to match current schema

* removed reference to secrets file

* delete old migration

* Revert "delete old migration"

This reverts commit db1efa39a7a80d8976878856250ccaac6a753ab2.

* Revert "adjusting migrations to match current schema"

This reverts commit ef89a83f6a2ef0643d6ace0a3fcf9c40f4bc6dd6.

* just deleted system creation since it's got nothing in it anyway

* renamed memberRepository to memberRepo for consistency

* added await back to parseMemberCommand call to memberArgumentHandler

* changed call to memberHelper.getMembersByAuthor to memberRepo

* renamed repo updateMemberValue to updateMemberField

* removed throw references in repo docstrings

* remove unneeded subscriber directory ref

* changed createdAt and updatedAt columns to be auto-generated

made member table have timezone

* changed casing of isInitialized in mock for bot.js

* removed % from ILike query so that it doesn't match substrings/wildcard

* renamed some stray updateMemberValue in mocks -> updateMemberField

---------

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* feat: Add migration to migrate existing data to new member table (#29)

added migration to fill new Member table with data from Members

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* fix: update message helper reference hotfix (#30)

* forgot to update a reference in messageHelper to memberRepo instead of memberHelper

* turned off data-source logging

---------

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* fix: update dockerfile to run npm start (#31)

fix: update dockerfile to run npm start (which runs ts-node) instead of node

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* added .env with examples, updated data-source to be access a docker container instead of relying on loopback

* i forgot to git add data-source.ts 🤦

* fix: changed property reference for createMember in repo (#32)

fix for createMember object references (was referencing non-existent properties)

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* fix: memberRepo methods syntax (#35)

* rearranged update member field and remove member to match expected structure in typeORM

* update docstring

* change insert to save in memberRepo

* added command in package.json

---------

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* Delete duplicate members migration (#33)

* add migration to delete duplicates that currently exist in the db

* added a name attribute for consistency

---------

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* Add unique index migration (#34)

* add migration to delete duplicates that currently exist in the db

* change model and migration to add a unique index constraint to id and name

* renamed unique index name to be readable

* redid model and migration to use @Unique instead of @Index

* remove //Here comment

---------

Co-authored-by: Aster Fialla <asterfialla@gmail.com>

* why wont these workflows stay up gahdamn

---------

Co-authored-by: Laika Bozhko <63646916+LaikaBzko@users.noreply.github.com>
Co-authored-by: Aster Fialla <asterfialla@gmail.com>
Co-authored-by: laika <laika@sanya.gay>
This commit is contained in:
2026-03-09 09:00:15 -04:00
committed by GitHub
parent df80eca0ec
commit 2b31cc2ae9
29 changed files with 2127 additions and 778 deletions

View File

@@ -1,12 +1,13 @@
import { Client, Events, Message } from '@fluxerjs/core';
import { messageHelper } from "./helpers/messageHelper.js";
import {enums} from "./enums.js";
import {commands} from "./commands.js";
import {webhookHelper} from "./helpers/webhookHelper.js";
import env from 'dotenv';
import {utils} from "./helpers/utils.js";
const {Client, Events, Message} = require('@fluxerjs/core');
const {messageHelper} = require("./helpers/messageHelper.js");
const {enums} = require("./enums.js");
const {commands} = require("./commands.js");
const {webhookHelper} = require("./helpers/webhookHelper.js");
const env = require('dotenv');
const {utils} = require("./helpers/utils.js");
const { AppDataSource } = require("../database/data-source");
env.config({path: './.env'});
env.config();
const token = process.env.FLUXER_BOT_TOKEN;
@@ -15,10 +16,12 @@ if (!token) {
process.exit(1);
}
export const client = new Client({ intents: 0 });
client = new Client({ intents: 0 });
module.exports.client = client;
client.on(Events.MessageCreate, async (message) => {
await handleMessageCreate(message);
await module.exports.handleMessageCreate(message);
});
/**
@@ -28,7 +31,7 @@ client.on(Events.MessageCreate, async (message) => {
* @param {Message} message - The message object
*
**/
export const handleMessageCreate = async function(message) {
module.exports.handleMessageCreate = async function(message) {
try {
// Ignore bots
if (message.author.bot) return;
@@ -79,12 +82,14 @@ function printGuilds() {
}
const debouncePrintGuilds = utils.debounce(printGuilds, 2000);
export const debounceLogin = utils.debounce(client.login, 60000);
// export const debounceLogin = utils.debounce(client.login, 60000);
export const login = async function() {
module.exports.login = async function() {
try {
if (!AppDataSource.isInitialized) {
await AppDataSource.initialize();
}
await client.login(token);
// await db.check_connection();
} catch (err) {
console.error('Login failed:', err);
process.exit(1);
@@ -93,7 +98,7 @@ export const login = async function() {
function main()
{
login();
exports.login();
}
main();

View File

@@ -1,20 +1,20 @@
import {messageHelper} from "./helpers/messageHelper.js";
import {enums} from "./enums.js";
import {memberHelper} from "./helpers/memberHelper.js";
import {EmbedBuilder} from "@fluxerjs/core";
import {importHelper} from "./helpers/importHelper.js";
const {messageHelper} = require("./helpers/messageHelper.js");
const {enums} = require("./enums.js");
const {memberHelper} = require("./helpers/memberHelper.js");
const {EmbedBuilder} = require("@fluxerjs/core");
const {importHelper} = require("./helpers/importHelper.js");
const cmds = {
const commands = {
commandsMap: new Map(),
aliasesMap: new Map()
};
cmds.aliasesMap.set('m', {command: 'member'})
commands.aliasesMap.set('m', {command: 'member'})
cmds.commandsMap.set('member', {
commands.commandsMap.set('member', {
description: enums.help.SHORT_DESC_MEMBER,
async execute(message, args) {
await cmds.memberCommand(message, args)
await commands.memberCommand(message, args)
}
})
@@ -26,7 +26,7 @@ cmds.commandsMap.set('member', {
* @param {string[]} args - The parsed arguments
*
**/
cmds.memberCommand = async function (message, args) {
commands.memberCommand = async function (message, args) {
const authorFull = `${message.author.username}#${message.author.discriminator}`
const attachmentUrl = message.attachments.size > 0 ? message.attachments.first().url : null;
const attachmentExpires = message.attachments.size > 0 ? message.attachments.first().expires_at : null;
@@ -53,10 +53,10 @@ cmds.memberCommand = async function (message, args) {
}
cmds.commandsMap.set('help', {
commands.commandsMap.set('help', {
description: enums.help.SHORT_DESC_HELP,
async execute(message) {
const fields = [...cmds.commandsMap.entries()].map(([name, cmd]) => ({
const fields = [...commands.commandsMap.entries()].map(([name, cmd]) => ({
name: `${messageHelper.prefix}${name}`,
value: cmd.description,
inline: true,
@@ -73,10 +73,10 @@ cmds.commandsMap.set('help', {
},
})
cmds.commandsMap.set('import', {
commands.commandsMap.set('import', {
description: enums.help.SHORT_DESC_IMPORT,
async execute(message, args) {
await cmds.importCommand(message, args);
await commands.importCommand(message, args);
}
})
@@ -88,7 +88,7 @@ cmds.commandsMap.set('import', {
* @param {string[]} args - The parsed arguments
*
**/
cmds.importCommand = async function (message, args) {
commands.importCommand = async function (message, args) {
const attachmentUrl = message.attachments.size > 0 ? message.attachments.first().url : null;
if ((message.content.includes('--help') || (args[0] === '' && args.length === 1)) && !attachmentUrl) {
return await message.reply(enums.help.IMPORT);
@@ -119,4 +119,4 @@ cmds.importCommand = async function (message, args) {
}
export const commands = cmds;
module.exports.commands = commands;

View File

@@ -1,86 +0,0 @@
import {DataTypes, Sequelize} from 'sequelize';
import * as env from 'dotenv';
env.config();
const password = process.env.POSTGRES_PASSWORD;
if (!password) {
console.error("Missing POSTGRES_PASSWORD environment variable.");
process.exit(1);
}
const db = {};
const sequelize = new Sequelize('postgres', 'postgres', password, {
host: 'localhost',
logging: false,
dialect: 'postgres'
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.members = sequelize.define('Member', {
userid: {
type: DataTypes.STRING,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
displayname: {
type: DataTypes.STRING,
},
propic: {
type: DataTypes.STRING,
},
proxy: {
type: DataTypes.STRING,
}
});
db.systems = sequelize.define('System', {
userid: {
type: DataTypes.STRING,
},
fronter: {
type: DataTypes.STRING
},
grouptag: {
type: DataTypes.STRING
},
autoproxy: {
type: DataTypes.BOOLEAN,
}
})
/**
* Checks Sequelize database connection.
*/
db.check_connection = async function () {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
await syncModels();
} catch (err) {
console.error('Unable to connect to the database:', err);
process.exit(1);
}
}
/**
* Syncs Sequelize models.
*/
async function syncModels() {
try {
await sequelize.sync()
console.log('Models synced successfully.');
} catch(err) {
console.error('Syncing models did not work', err);
process.exit(1);
}
}
export const database = db;

View File

@@ -1,6 +1,6 @@
const helperEnums = {};
const enums = {};
helperEnums.err = {
enums.err = {
NO_MEMBER: "No such member was found.",
NO_NAME_PROVIDED: "No member name was provided for",
NO_VALUE: "has not been set for this member.",
@@ -26,7 +26,7 @@ helperEnums.err = {
CANNOT_FETCH_RESOURCE: "Could not download the file at this time."
}
helperEnums.help = {
enums.help = {
SHORT_DESC_HELP: "Lists available commands.",
SHORT_DESC_MEMBER: "Accesses subcommands related to proxy members.",
SHORT_DESC_IMPORT: "Imports from PluralKit.",
@@ -43,11 +43,11 @@ helperEnums.help = {
IMPORT: "Imports from PluralKit using the JSON file provided by their export command. Importing from other proxy bots is TBD. `pf;import` and attach your JSON file to the message. This will only save the fields that are present in the bot currently, not anything else like birthdays or system handles (yet?). **Only one proxy can be set per member currently.**\n\n**PRO TIP**: For privacy reasons, try DMing the bot with this command and your JSON file--it should still work the same."
}
helperEnums.misc = {
enums.misc = {
ATTACHMENT_SENT_BY: "Attachment sent by:",
ATTACHMENT_EXPIRATION_WARNING: "**NOTE:** Because this profile picture is hosted on Fluxer, it will expire. To avoid this, upload the picture to another website like <https://imgbb.com/> and link to it directly.",
FLUXER_ATTACHMENT_URL: "https://fluxerusercontent.com/attachments/"
}
export const enums = helperEnums;
module.exports.enums = enums;

View File

@@ -1,7 +1,7 @@
import {enums} from "../enums.js";
import {memberHelper} from "./memberHelper.js";
const {enums} = require("../enums.js");
const {memberHelper} = require("./memberHelper.js");
const ih = {};
const importHelper = {};
/**
* Tries to import from Pluralkit.
@@ -12,7 +12,7 @@ const ih = {};
* @returns {Promise<string>} A successful addition of all members.
* @throws {Error} When the member exists, or creating a member doesn't work.
*/
ih.pluralKitImport = async function (authorId, attachmentUrl= null) {
importHelper.pluralKitImport = async function (authorId, attachmentUrl= null) {
let fetchResult, pkData;
if (!attachmentUrl) {
throw new Error(enums.err.NOT_JSON_FILE);
@@ -55,4 +55,4 @@ ih.pluralKitImport = async function (authorId, attachmentUrl= null) {
return aggregatedText;
}
export const importHelper = ih;
exports.importHelper = importHelper;

View File

@@ -1,10 +1,9 @@
import {database} from '../database.js';
import {enums} from "../enums.js";
import {Op} from "sequelize";
import {EmbedBuilder} from "@fluxerjs/core";
import {utils} from "./utils.js";
const {enums} = require("../enums.js");
const {EmbedBuilder} = require("@fluxerjs/core");
const {utils} = require("./utils.js");
const {memberRepo} = require("../repositories/memberRepo.js");
const mh = {};
const memberHelper = {};
const commandList = ['new', 'remove', 'name', 'list', 'displayname', 'proxy', 'propic'];
const newAndRemoveCommands = ['new', 'remove'];
@@ -23,14 +22,14 @@ const newAndRemoveCommands = ['new', 'remove'];
* @returns {Promise <EmbedBuilder>} A list of member commands and descriptions.
* @returns {Promise<{EmbedBuilder, string[], string}>} A member info embed + info/errors.
*/
mh.parseMemberCommand = async function (authorId, authorFull, args, attachmentUrl = null, attachmentExpiration = null) {
memberHelper.parseMemberCommand = async function (authorId, authorFull, args, attachmentUrl = null, attachmentExpiration = null) {
let memberName, command, isHelp = false;
// checks whether command is in list, otherwise assumes it's a name
// ex: pf;member remove, pf;member remove --help
// ex: pf;member, pf;member --help
if (args.length === 0 || args[0] === '--help' || args[0] === '') {
return mh.getMemberCommandInfo();
return memberHelper.getMemberCommandInfo();
}
// ex: pf;member remove somePerson
if (commandList.includes(args[0])) {
@@ -52,7 +51,7 @@ mh.parseMemberCommand = async function (authorId, authorFull, args, attachmentUr
isHelp = true;
}
return await mh.memberArgumentHandler(authorId, authorFull, isHelp, command, memberName, args, attachmentUrl, attachmentExpiration)
return await memberHelper.memberArgumentHandler(authorId, authorFull, isHelp, command, memberName, args, attachmentUrl, attachmentExpiration);
}
/**
@@ -71,17 +70,18 @@ mh.parseMemberCommand = async function (authorId, authorFull, args, attachmentUr
* @returns {Promise <EmbedBuilder>} A list of 25 members as an embed.
* @returns {Promise <EmbedBuilder>} A list of member commands and descriptions.
* @returns {Promise<{EmbedBuilder, [string], string}>} A member info embed + info/errors.
* @returns {Promise<string>} - A help message
* @throws {Error} When there's no member or a command is not recognized.
*/
mh.memberArgumentHandler = async function(authorId, authorFull, isHelp, command = null, memberName = null, args = [], attachmentUrl = null, attachmentExpiration = null) {
memberHelper.memberArgumentHandler = async function(authorId, authorFull, isHelp, command = null, memberName = null, args = [], attachmentUrl = null, attachmentExpiration = null) {
if (!command && !memberName && !isHelp) {
throw new Error(enums.err.COMMAND_NOT_RECOGNIZED);
}
else if (isHelp) {
return mh.sendHelpEnum(command);
return memberHelper.sendHelpEnum(command);
}
else if (command === "list") {
return await mh.getAllMembersInfo(authorId, authorFull);
return await memberHelper.getAllMembersInfo(authorId, authorFull);
}
else if (!memberName && !isHelp) {
throw new Error(enums.err.NO_MEMBER);
@@ -92,10 +92,10 @@ mh.memberArgumentHandler = async function(authorId, authorFull, isHelp, command
// ex: pf;member blah blah
if (command && memberName && (values.length > 0 || newAndRemoveCommands.includes(command) || attachmentUrl)) {
return await mh.memberCommandHandler(authorId, command, memberName, values, attachmentUrl, attachmentExpiration);
return await memberHelper.memberCommandHandler(authorId, command, memberName, values, attachmentUrl, attachmentExpiration);
}
else if (memberName && values.length === 0) {
return await mh.sendCurrentValue(authorId, memberName, command);
return await memberHelper.sendCurrentValue(authorId, memberName, command);
}
}
@@ -112,12 +112,12 @@ mh.memberArgumentHandler = async function(authorId, authorFull, isHelp, command
* @returns {Promise<{EmbedBuilder, string[], string}>} A member info embed + info/errors.
* @throws {Error} When there's no member
*/
mh.sendCurrentValue = async function(authorId, memberName, command= null) {
const member = await mh.getMemberByName(authorId, memberName);
memberHelper.sendCurrentValue = async function(authorId, memberName, command= null) {
const member = await memberRepo.getMemberByName(authorId, memberName);
if (!member) throw new Error(enums.err.NO_MEMBER);
if (!command) {
return mh.getMemberInfo(member);
return memberHelper.getMemberInfo(member);
}
switch (command) {
@@ -138,7 +138,7 @@ mh.sendCurrentValue = async function(authorId, memberName, command= null) {
* @param {string} command - The command being called.
* @returns {string} - The help text associated with a command.
*/
mh.sendHelpEnum = function(command) {
memberHelper.sendHelpEnum = function(command) {
switch (command) {
case 'new':
return enums.help.NEW;
@@ -167,25 +167,22 @@ mh.sendHelpEnum = function(command) {
* @param {string[]} values - The values to be passed in. Only includes the values after member name and command name.
* @param {string | null} attachmentUrl - The attachment URL, if any
* @param {string | null} attachmentExpiration - The attachment expiry date, if any
* @returns {Promise<string>} A success message.
* @returns {Promise <EmbedBuilder>} A list of 25 members as an embed.
* @returns {Promise <EmbedBuilder>} A list of member commands and descriptions.
* @returns {Promise<{EmbedBuilder, [string], string}>} A member info embed + info/errors.
* @returns {Promise<string> | Promise <EmbedBuilder> | Promise<{EmbedBuilder, [string], string}>}
*/
mh.memberCommandHandler = async function(authorId, command, memberName, values, attachmentUrl = null, attachmentExpiration = null) {
memberHelper.memberCommandHandler = async function(authorId, command, memberName, values, attachmentUrl = null, attachmentExpiration = null) {
switch (command) {
case 'new':
return await mh.addNewMember(authorId, memberName, values, attachmentUrl, attachmentExpiration);
return await memberHelper.addNewMember(authorId, memberName, values, attachmentUrl, attachmentExpiration);
case 'remove':
return await mh.removeMember(authorId, memberName);
return await memberHelper.removeMember(authorId, memberName);
case 'name':
return await mh.updateName(authorId, memberName, values[0]);
return await memberHelper.updateName(authorId, memberName, values[0]);
case 'displayname':
return await mh.updateDisplayName(authorId, memberName, values[0]);
return await memberHelper.updateDisplayName(authorId, memberName, values[0]);
case 'proxy':
return await mh.updateProxy(authorId, memberName, values[0]);
return await memberHelper.updateProxy(authorId, memberName, values[0]);
case 'propic':
return await mh.updatePropic(authorId, memberName, values[0], attachmentUrl, attachmentExpiration);
return await memberHelper.updatePropic(authorId, memberName, values[0], attachmentUrl, attachmentExpiration);
default:
throw new Error(enums.err.COMMAND_NOT_RECOGNIZED);
}
@@ -202,13 +199,13 @@ mh.memberCommandHandler = async function(authorId, command, memberName, values,
* @param {string | null} [attachmentExpiration] - The attachment expiry date, if any
* @returns {Promise<{EmbedBuilder, string[], string}>} A successful addition.
*/
mh.addNewMember = async function (authorId, memberName, values, attachmentUrl = null, attachmentExpiration = null) {
memberHelper.addNewMember = async function (authorId, memberName, values, attachmentUrl = null, attachmentExpiration = null) {
const displayName = values[0];
const proxy = values[1];
const propic = values[2] ?? attachmentUrl;
const memberObj = await mh.addFullMember(authorId, memberName, displayName, proxy, propic, attachmentExpiration);
const memberInfoEmbed = mh.getMemberInfo(memberObj.member);
const memberObj = await memberHelper.addFullMember(authorId, memberName, displayName, proxy, propic, attachmentExpiration);
const memberInfoEmbed = memberHelper.getMemberInfo(memberObj.member);
return {embed: memberInfoEmbed, errors: memberObj.errors, success: `${memberName} has been added successfully.`}
}
@@ -222,12 +219,12 @@ mh.addNewMember = async function (authorId, memberName, values, attachmentUrl =
* @returns {Promise<string>} A successful update.
* @throws {RangeError} When the name doesn't exist.
*/
mh.updateName = async function (authorId, memberName, name) {
memberHelper.updateName = async function (authorId, memberName, name) {
const trimmedName = name.trim();
if (trimmedName === '') {
throw new RangeError(`Name ${enums.err.NO_VALUE}`);
}
return await mh.updateMemberField(authorId, memberName, "name", trimmedName);
return await memberHelper.updateMemberField(authorId, memberName, "name", trimmedName);
}
/**
@@ -240,7 +237,7 @@ mh.updateName = async function (authorId, memberName, name) {
* @returns {Promise<string>} A successful update.
* @throws {RangeError} When the display name is too long or doesn't exist.
*/
mh.updateDisplayName = async function (authorId, membername, displayname) {
memberHelper.updateDisplayName = async function (authorId, membername, displayname) {
const trimmedName = displayname.trim();
if (trimmedName.length > 32) {
@@ -249,7 +246,7 @@ mh.updateDisplayName = async function (authorId, membername, displayname) {
else if (trimmedName === '') {
throw new RangeError(`Display name ${enums.err.NO_VALUE}`);
}
return await mh.updateMemberField(authorId, membername, "displayname", trimmedName);
return await memberHelper.updateMemberField(authorId, membername, "displayname", trimmedName);
}
/**
@@ -261,11 +258,11 @@ mh.updateDisplayName = async function (authorId, membername, displayname) {
* @param {string} proxy - The proxy to set
* @returns {Promise<string> } A successful update.
*/
mh.updateProxy = async function (authorId, memberName, proxy) {
memberHelper.updateProxy = async function (authorId, memberName, proxy) {
// Throws error if exists
await mh.checkIfProxyExists(authorId, proxy);
await memberHelper.checkIfProxyExists(authorId, proxy);
return await mh.updateMemberField(authorId, memberName, "proxy", proxy);
return await memberHelper.updateMemberField(authorId, memberName, "proxy", proxy);
}
/**
@@ -279,12 +276,12 @@ mh.updateProxy = async function (authorId, memberName, proxy) {
* @param {string | null} attachmentExpiration - The attachment expiry date, if any
* @returns {Promise<string>} A successful update.
*/
mh.updatePropic = async function (authorId, memberName, values, attachmentUrl = null, attachmentExpiration = null) {
memberHelper.updatePropic = async function (authorId, memberName, values, attachmentUrl = null, attachmentExpiration = null) {
const imgUrl = values ?? attachmentUrl;
// Throws error if invalid
await utils.checkImageFormatValidity(imgUrl);
const expirationWarning = utils.setExpirationWarning(imgUrl, attachmentExpiration);
return await mh.updateMemberField(authorId, memberName, "propic", imgUrl, expirationWarning);
return await memberHelper.updateMemberField(authorId, memberName, "propic", imgUrl, expirationWarning);
}
/**
@@ -296,13 +293,8 @@ mh.updatePropic = async function (authorId, memberName, values, attachmentUrl =
* @returns {Promise<string>} A successful removal.
* @throws {Error} When there is no member to remove.
*/
mh.removeMember = async function (authorId, memberName) {
const destroyed = await database.members.destroy({
where: {
name: {[Op.iLike]: memberName},
userid: authorId
}
})
memberHelper.removeMember = async function (authorId, memberName) {
const destroyed = await memberRepo.removeMember(authorId, memberName);
if (destroyed > 0) {
return `Member "${memberName}" has been deleted.`;
} else {
@@ -322,11 +314,11 @@ mh.removeMember = async function (authorId, memberName) {
* @param {string | null} [proxy] - The proxy tag of the member.
* @param {string | null} [propic] - The profile picture URL of the member.
* @param {string | null} [attachmentExpiration] - The expiration date of an uploaded profile picture.
* @returns {Promise<{model, string[]}>} A successful addition object, including errors if there are any.
* @returns {Promise<{Members, string[]}>} A successful addition object, including errors if there are any.
* @throws {Error} When the member already exists, there are validation errors, or adding a member doesn't work.
*/
mh.addFullMember = async function (authorId, memberName, displayName = null, proxy = null, propic = null, attachmentExpiration = null) {
const existingMember = await mh.getMemberByName(authorId, memberName);
memberHelper.addFullMember = async function (authorId, memberName, displayName = null, proxy = null, propic = null, attachmentExpiration = null) {
const existingMember = await memberRepo.getMemberByName(authorId, memberName);
if (existingMember) {
throw new Error(`Can't add ${memberName}. ${enums.err.MEMBER_EXISTS}`);
}
@@ -356,7 +348,7 @@ mh.addFullMember = async function (authorId, memberName, displayName = null, pro
let isValidProxy;
if (proxy && proxy.length > 0) {
try {
const proxyExists = await mh.checkIfProxyExists(authorId, proxy);
const proxyExists = await memberHelper.checkIfProxyExists(authorId, proxy);
isValidProxy = !proxyExists;
}
catch(e) {
@@ -365,21 +357,22 @@ mh.addFullMember = async function (authorId, memberName, displayName = null, pro
}
}
let isValidPropic;
let isValidPropic, expirationWarning;
if (propic && propic.length > 0) {
try {
isValidPropic = await utils.checkImageFormatValidity(propic);
expirationWarning = utils.setExpirationWarning(propic, attachmentExpiration);
if (expirationWarning) {
errors.push(expirationWarning);
}
}
catch(e) {
errors.push(`Tried to set profile picture to \"${propic}\". ${e.message}. ${enums.err.SET_TO_NULL}`);
isValidPropic = false;
}
}
const expirationWarning = utils.setExpirationWarning(propic, attachmentExpiration);
if (expirationWarning) {
errors.push(expirationWarning);
}
const member = await database.members.create({
const member = await memberRepo.createMember({
name: memberName, userid: authorId, displayname: isValidDisplayName ? displayName : null, proxy: isValidProxy ? proxy : null, propic: isValidPropic ? propic : null
});
@@ -398,14 +391,9 @@ mh.addFullMember = async function (authorId, memberName, displayName = null, pro
* @returns {Promise<string>} A successful update.
* @throws {Error} When no member row was updated.
*/
mh.updateMemberField = async function (authorId, memberName, columnName, value, expirationWarning = null) {
const res = await database.members.update({[columnName]: value}, {
where: {
name: {[Op.iLike]: memberName},
userid: authorId
}
})
if (res[0] === 0) {
memberHelper.updateMemberField = async function (authorId, memberName, columnName, value, expirationWarning = null) {
const res = await memberRepo.updateMemberField(authorId, memberName, columnName, value);
if (res === 0) {
throw new Error(`Can't update ${memberName}. ${enums.err.NO_MEMBER}.`);
} else {
return `Updated ${columnName} for ${memberName} to ${value}${expirationWarning ? `. ${expirationWarning}.` : '.'}`;
@@ -415,10 +403,10 @@ mh.updateMemberField = async function (authorId, memberName, columnName, value,
/**
* Gets the details for a member.
*
* @param {model} member - The member object
* @param {{Member, string[]}} member - The member object
* @returns {EmbedBuilder} The member's info.
*/
mh.getMemberInfo = function (member) {
memberHelper.getMemberInfo = function (member) {
return new EmbedBuilder()
.setTitle(member.name)
.setDescription(`Details for ${member.name}`)
@@ -439,8 +427,8 @@ mh.getMemberInfo = function (member) {
* @returns {Promise<EmbedBuilder>} The info for all members.
* @throws {Error} When there are no members for an author.
*/
mh.getAllMembersInfo = async function (authorId, authorName) {
const members = await mh.getMembersByAuthor(authorId);
memberHelper.getAllMembersInfo = async function (authorId, authorName) {
const members = await memberRepo.getMembersByAuthor(authorId);
if (members.length === 0) throw Error(enums.err.USER_NO_MEMBERS);
const fields = [...members.entries()].map(([index, member]) => ({
name: member.name, value: `(Proxy: \`${member.proxy ?? "unset"}\`)`, inline: true,
@@ -450,29 +438,6 @@ mh.getAllMembersInfo = async function (authorId, authorName) {
.addFields(...fields);
}
/**
* Gets a member based on the author and proxy tag.
*
* @async
* @param {string} authorId - The author of the message.
* @param {string} memberName - The member's name.
* @returns {Promise<model>} The member object.
*/
mh.getMemberByName = async function (authorId, memberName) {
return await database.members.findOne({where: {userid: authorId, name: {[Op.iLike]: memberName}}});
}
/**
* Gets all members belonging to the author.
*
* @async
* @param {string} authorId - The author of the message
* @returns {Promise<model[] | null>} The member object array.
*/
mh.getMembersByAuthor = async function (authorId) {
return await database.members.findAll({where: {userid: authorId}});
}
/**
* Checks if proxy exists for a member.
*
@@ -481,12 +446,12 @@ mh.getMembersByAuthor = async function (authorId) {
* @returns {Promise<boolean> } Whether the proxy exists.
* @throws {Error} When an empty proxy was provided, or no proxy exists.
*/
mh.checkIfProxyExists = async function (authorId, proxy) {
memberHelper.checkIfProxyExists = async function (authorId, proxy) {
const splitProxy = proxy.trim().split("text");
if (splitProxy.length < 2) throw new Error(enums.err.NO_TEXT_FOR_PROXY);
if (!splitProxy[0] && !splitProxy[1]) throw new Error(enums.err.NO_PROXY_WRAPPER);
const memberList = await mh.getMembersByAuthor(authorId);
const memberList = await memberRepo.getMembersByAuthor(authorId);
const proxyExists = memberList.some(member => member.proxy === proxy);
if (proxyExists) {
throw new Error(enums.err.PROXY_EXISTS);
@@ -499,7 +464,7 @@ mh.checkIfProxyExists = async function (authorId, proxy) {
*
* @returns {EmbedBuilder } An embed of member commands.
*/
mh.getMemberCommandInfo = function() {
memberHelper.getMemberCommandInfo = function() {
const fields = [
{name: `**new**`, value: enums.help.NEW, inline: false},
{name: `**remove**`, value: enums.help.REMOVE, inline: false},
@@ -516,4 +481,4 @@ mh.getMemberCommandInfo = function() {
}
export const memberHelper = mh;
module.exports.memberHelper = memberHelper;

View File

@@ -1,4 +1,4 @@
import {memberHelper} from "./memberHelper.js";
const {memberRepo} = require('../repositories/memberRepo.js');
const msgh = {};
@@ -39,7 +39,7 @@ msgh.parseCommandArgs = function(content, commandName) {
* @returns {Promise<{model, string, bool}>} The proxy message object.
*/
msgh.parseProxyTags = async function (authorId, content, attachmentUrl = null){
const members = await memberHelper.getMembersByAuthor(authorId);
const members = await memberRepo.getMembersByAuthor(authorId);
// If an author has no members, no sense in searching for proxy
if (members.length === 0) {
return;
@@ -80,4 +80,4 @@ msgh.returnBufferFromText = function (text) {
return {text: text, file: undefined}
}
export const messageHelper = msgh;
module.exports.messageHelper = msgh;

View File

@@ -1,8 +1,8 @@
import {enums} from '../enums.js'
const {enums} = require('../enums');
const u = {};
const utils = {};
u.debounce = function(func, delay) {
utils.debounce = function(func, delay) {
let timeout = null;
return function (...args) {
clearTimeout(timeout);
@@ -18,7 +18,7 @@ u.debounce = function(func, delay) {
* @returns {bool} - Whether the image is in a valid format
* @throws {Error} When loading the profile picture from a URL doesn't work, or it fails requirements.
*/
u.checkImageFormatValidity = async function (imageUrl) {
utils.checkImageFormatValidity = async function (imageUrl) {
const acceptableImages = ['image/png', 'image/jpg', 'image/jpeg', 'image/webp'];
let response, blobFile;
try {
@@ -41,7 +41,7 @@ u.checkImageFormatValidity = async function (imageUrl) {
* @param {string | null} [expirationString] - An expiration date string.
* @returns {string | null} A description of the expiration, or null.
*/
u.setExpirationWarning = function (imgUrl = null, expirationString = null) {
utils.setExpirationWarning = function (imgUrl = null, expirationString = null) {
if (imgUrl && imgUrl.startsWith(enums.misc.FLUXER_ATTACHMENT_URL)) {
return enums.misc.ATTACHMENT_EXPIRATION_WARNING;
}
@@ -54,4 +54,4 @@ u.setExpirationWarning = function (imgUrl = null, expirationString = null) {
return null;
}
export const utils = u;
module.exports.utils = utils;

View File

@@ -1,8 +1,8 @@
import {messageHelper} from "./messageHelper.js";
import {Webhook, Channel, Message, Client} from '@fluxerjs/core';
import {enums} from "../enums.js";
const {messageHelper} = require("./messageHelper.js");
const {Webhook, Channel, Message, Client} = require('@fluxerjs/core');
const {enums} = require("../enums.js");
const wh = {};
const webhookHelper = {};
const name = 'PluralFlux Proxy Webhook';
@@ -13,7 +13,7 @@ const name = 'PluralFlux Proxy Webhook';
* @param {Message} message - The full message object.
* @throws {Error} When the proxy message is not in a server.
*/
wh.sendMessageAsMember = async function(client, message) {
webhookHelper.sendMessageAsMember = async function(client, message) {
const attachmentUrl = message.attachments.size > 0 ? message.attachments.first().url : null;
const proxyMatch = await messageHelper.parseProxyTags(message.author.id, message.content, attachmentUrl);
// If the message doesn't match a proxy, just return.
@@ -27,7 +27,7 @@ wh.sendMessageAsMember = async function(client, message) {
if (proxyMatch.hasAttachment) {
return await message.reply(`${enums.misc.ATTACHMENT_SENT_BY} ${proxyMatch.member.displayname ?? proxyMatch.member.name}`)
}
await wh.replaceMessage(client, message, proxyMatch.message, proxyMatch.member);
await webhookHelper.replaceMessage(client, message, proxyMatch.message, proxyMatch.member);
}
/**
@@ -39,11 +39,11 @@ wh.sendMessageAsMember = async function(client, message) {
* @param {model} member - A member object from the database.
* @throws {Error} When there's no message to send.
*/
wh.replaceMessage = async function(client, message, text, member) {
webhookHelper.replaceMessage = async function(client, message, text, member) {
// attachment logic is not relevant yet, text length will always be over 0 right now
if (text.length > 0 || message.attachments.size > 0) {
const channel = client.channels.get(message.channelId);
const webhook = await wh.getOrCreateWebhook(client, channel);
const webhook = await webhookHelper.getOrCreateWebhook(client, channel);
const username = member.displayname ?? member.name;
if (text.length <= 2000) {
await webhook.send({content: text, username: username, avatar_url: member.propic})
@@ -68,10 +68,10 @@ wh.replaceMessage = async function(client, message, text, member) {
* @returns {Webhook} A webhook object.
* @throws {Error} When no webhooks are allowed in the channel.
*/
wh.getOrCreateWebhook = async function(client, channel) {
webhookHelper.getOrCreateWebhook = async function(client, channel) {
// If channel doesn't allow webhooks
if (!channel?.createWebhook) throw new Error(enums.err.NO_WEBHOOKS_ALLOWED);
let webhook = await wh.getWebhook(client, channel)
let webhook = await webhookHelper.getWebhook(client, channel)
if (!webhook) {
webhook = await channel.createWebhook({name: name});
}
@@ -85,7 +85,7 @@ wh.getOrCreateWebhook = async function(client, channel) {
* @param {Channel} channel - The channel the message was sent in.
* @returns {Webhook} A webhook object.
*/
wh.getWebhook = async function(client, channel) {
webhookHelper.getWebhook = async function(client, channel) {
const channelWebhooks = await channel?.fetchWebhooks() ?? [];
if (channelWebhooks.length === 0) {
return;
@@ -93,4 +93,4 @@ wh.getWebhook = async function(client, channel) {
return channelWebhooks.find((webhook) => webhook.name === name);
}
export const webhookHelper = wh;
module.exports.webhookHelper = webhookHelper;

View File

@@ -0,0 +1,74 @@
const Member = require("../../database/entity/Member");
const { AppDataSource } = require("../../database/data-source");
const {ILike} = require("typeorm");
const members = AppDataSource.getRepository(Member.Member)
const memberRepo = {};
/**
* Gets a member based on the author and proxy tag.
*
* @async
* @param {string} authorId - The author of the message.
* @param {string} memberName - The member's name.
* @returns {Promise<Member | null>} The member object or null if not found.
*/
memberRepo.getMemberByName = async function (authorId, memberName) {
return await members.findOne({where: {userid: authorId, name: ILike(memberName)}});
}
/**
* Gets all members belonging to the author.
*
* @async
* @param {string} authorId - The author of the message
* @returns {Promise<Member[]>} The member object array.
*/
memberRepo.getMembersByAuthor = async function (authorId) {
return await members.findBy({userid: authorId});
}
/**
* Removes a member.
*
* @async
* @param {string} authorId - The author of the message
* @param {string} memberName - The name of the member to remove
* @returns {Promise<number>} Number of results removed.
*/
memberRepo.removeMember = async function (authorId, memberName) {
const deleted = await members.delete({ name: ILike(memberName), userid: authorId })
return deleted.affected;
}
/**
* Adds a member with full details.
*
* @async
* @param {{name: string, userid: string, displayname: (string|null), proxy: (string|null), propic: (string|null)}} createObj - Object with parameters in it
* @returns {Promise<Member>} A successful inserted object.
*/
memberRepo.createMember = async function (createObj) {
return await members.save({
name: createObj.name, userid: createObj.userid, displayname: createObj.displayname, proxy: createObj.proxy, propic: createObj.propic
});
}
/**
* Updates one fields for a member in the database.
*
* @async
* @param {string} authorId - The author of the message
* @param {string} memberName - The member to update
* @param {string} columnName - The column name to update.
* @param {string} value - The value to update to.
* @returns {Promise<number>} A successful update.
*/
memberRepo.updateMemberField = async function (authorId, memberName, columnName, value) {
const updated = await members.update({
name: ILike(memberName),
userid: authorId
}, {[columnName]: value})
return updated.affected;
}
module.exports.memberRepo = memberRepo;