Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#23: Reorg Discord Service Bindings/Structure #32

Merged
merged 2 commits into from
Feb 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
},
"scripts": {
"start": "node src/server/server.js",
"inspect": "node --inspect src/server/server.js",
"test": "echo \"Error: no test specified\" && exit 1",
"migrate": "npx prisma migrate dev && npx prisma generate",
"reset": "rm -rf ./prisma/disco.db* ./prisma/migrations && npx prisma migrate dev --name init"
Expand Down
23 changes: 19 additions & 4 deletions src/shared/CoreService.js → src/core/CoreService.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class CoreService {
}
CoreService._instance = this;
this._bindLogging();
this._prisma = new PrismaClient();
this._prisma = null;
this._app = null;
this._server = null;
this._client = null;
Expand All @@ -22,7 +22,7 @@ class CoreService {
this._bindModels();
this._bindMethods();
this._bindSockets();
this.shutdownServer = this.generateTerminator()
this._initDiscordClient();
}

static get instance() {
Expand All @@ -35,7 +35,7 @@ class CoreService {
get client() {
if (!this._client) {
this.logger.info('Attaching DiscordJS to core-service');
this._client = require('../bot/bot')(this);
this._client = require('./bot/bot')(this);
}
return this._client;
}
Expand All @@ -52,11 +52,20 @@ class CoreService {
if (!this._server) {
this.logger.info('Attaching Http Server to core-service');
this._server = http.createServer(this.app.callback());

// SETTING EVENT HANDLERS FOR ON SHUTDOWN
process.on('SIGINT', (e) => this.shutdownServer('SIGNINT', e));
process.on('SIGTERM', (e) => this.shutdownServer('SIGTERM', e,));
process.on('uncaughtException', (e) => this.uncaughtShutdown('uncaughtException', e));
}
return this._server;
}

get prisma() {
if (!this._prisma) {
this.logger.info('Generating Prisma Cli Instance');
this._prisma = new PrismaClient();
}
return this._prisma;
}

Expand All @@ -78,9 +87,15 @@ class CoreService {
ctx.core = this;
await next();
});
this.autoStartBot();
return app;
}

_initDiscordClient() {
this.logger.info('Initializing Discord Bot');
const clientInstance = this.client;
this.autoStartBot();
return clientInstance;
}

_bindModels() {
require('./models')(this);
Expand Down
4 changes: 2 additions & 2 deletions src/bot/bot.js → src/core/bot/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ const { Client } = require('discord.js');
const intentManager = require('./managers/intentManager');
const eventManager = require('./managers/eventManager');

function generateClient(coreService) {
function generateClient(core) {
const client = new Client(intentManager());
client.core = coreService;
client.core = core;
eventManager(client);
return client;
}
Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
const { Events } = require('discord.js');


async function registerBotOnReady(client) {
await client.core.refreshBotInfo(true);
await client.core.updateServerSortOrder();
}

module.exports = {
name: Events.ClientReady,
once: false,
async execute(client) {
await registerBotOnReady(client);
const core = client.core;
await core.refreshBotInfo(true);
await core.updateServerSortOrder();
global.logger.info(`Logged in as ${client.user.tag}!`);
},
};
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
module.exports = {
async getDiscordServers() {
const servers = [];
const isReady = this.client.isReady();
if (isReady) {
const foundServers = await this.client.guilds.fetch();
this.logger.debug('Discord servers found: ', foundServers.toJSON());
foundServers.each(async (foundServer) => {
const guildInfo = {
server_name: foundServer.name,
server_id: foundServer.id,
server_avatar_url: foundServer.iconURL()
};
this.logger.debug('PUSHING SERVER TO UPSERT: ', guildInfo);
servers.push(guildInfo);
});
}
const foundServers = await this.client.guilds.fetch();
foundServers.each(async (foundServer) => {
const guildInfo = {
server_name: foundServer.name,
server_id: foundServer.id,
server_avatar_url: foundServer.iconURL()
};
logger.debug('Fetch Discord Servers, Upserting to DB: ', guildInfo);
servers.push(guildInfo);
});
return servers;
},

Expand All @@ -41,12 +37,6 @@ module.exports = {
await this.updatePowerState(powerOn, discordBot)
},

async getInviteLink() {
const discordBot = await this.discordBot.get();
const inviteLink = discordBot.bot_invite_link;
return inviteLink;
},

async setInviteLink() {
const inviteLink = this.client.generateInvite({ scopes: ['bot'] });
return await this.discordBot.update({ bot_invite_link: inviteLink });
Expand All @@ -61,16 +51,4 @@ module.exports = {
});
},

async updatePowerState(powerOn, discordBotInst = null) {
const discordBot = discordBotInst || await this.discordBot.get();
this.logger.debug('Changing Discord Bot Power State: ', discordBot);
await this.emitCompiled([
'nav/user/buttons/botPowerButton.pug',
'nav/user/userBoxInfo.pug',
'nav/servers/addServer.pug'
], {
discordBot,
state: await this.state.update({ discord_state: powerOn })
});
}
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,4 @@ module.exports = {
return false;
}
}
}
};
27 changes: 27 additions & 0 deletions src/core/methods/discord/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const _ = require('lodash');


function rejectInvocation(method) {
this.logger.warn('CALLING CLIENT METHODS BEFORE LOGIN');
console.trace(method);
return {};
}

function requireClientLogin(modulePath) {
const moduleObj = require(modulePath);
return _.mapValues(moduleObj, (method) => {
return function(...args) {
if (this.client && this.client.isReady()) {
return method.apply(this, args);
} else {
return rejectInvocation(method);
}
};
});
}

module.exports = {
...require('./methods'),
...require('./controller'),
...requireClientLogin('./afterAuth')
};
20 changes: 20 additions & 0 deletions src/core/methods/discord/methods.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module.exports = {
async updatePowerState(powerOn, discordBotInst = null) {
this.logger.debug('Changing Discord Bot Power State: ', discordBot);
const discordBot = discordBotInst || await this.discordBot.get();
await this.emitCompiled([
'nav/user/buttons/botPowerButton.pug',
'nav/user/userBoxInfo.pug',
'nav/servers/addServer.pug'
], {
discordBot,
state: await this.state.update({ discord_state: powerOn })
});
},

async getInviteLink() {
const discordBot = await this.discordBot.get();
const inviteLink = discordBot.bot_invite_link;
return inviteLink;
},
};
8 changes: 8 additions & 0 deletions src/core/methods/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const _ = require('lodash');

module.exports = (core) => {
_.mixin(core, require('./websocket'));
_.mixin(core, require('./server'));
_.mixin(core, require('./rendering'));
_.mixin(core, require('./discord'));
}
5 changes: 5 additions & 0 deletions src/core/methods/rendering/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
...require('./serverBarRendering'),
...require('./templateCompiler')
};

3 changes: 3 additions & 0 deletions src/core/methods/server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
...require('./processTerminator.js')
};
19 changes: 19 additions & 0 deletions src/core/methods/server/processTerminator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const { createHttpTerminator } = require('http-terminator');
const logger = global.logger;


module.exports = {
async uncaughtShutdown(signal, e) {
logger.error(`Uncaught exception encountered\n...CHECK LOGS.`, signal, e);
console.trace(signal, e);
},
async shutdownServer(signal, e) {
logger.silly(`Received ${signal}\n${e}\n...Shutting down gracefully.`);
try {
const serverTerminator = createHttpTerminator({ server: this.server }).terminate();
} catch (error) {
logger.error('Failed to terminate server:', error);
}
process.exit();
}
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const uuid = require('uuid');


module.exports = {
module.exports = {
addClientWS(ws) {
const id = uuid.v4();
const color = Math.floor(Math.random() * 360);
Expand All @@ -22,4 +21,4 @@ module.exports = {
this.logger.debug(compiledTemplate);
await this.emit(compiledTemplate);
}
}
};
4 changes: 4 additions & 0 deletions src/core/methods/websocket/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
...require('./connections'),
};

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 1 addition & 2 deletions src/server/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const { app, server, logger } = require('../shared/CoreService');
const { app, server } = require('../core/CoreService');
const serve = require('koa-static');
const views = require('koa-views');
const bodyParser = require('koa-bodyparser');
const errorHandler = require('./middlewares/errorHandler');
const debugHandler = require('./middlewares/debugHandler');
Expand Down
7 changes: 0 additions & 7 deletions src/shared/methods/discord/index.js

This file was deleted.

18 changes: 0 additions & 18 deletions src/shared/methods/index.js

This file was deleted.

7 changes: 0 additions & 7 deletions src/shared/methods/rendering/index.js

This file was deleted.

5 changes: 0 additions & 5 deletions src/shared/methods/server/index.js

This file was deleted.

35 changes: 0 additions & 35 deletions src/shared/methods/server/processTerminator.js

This file was deleted.

5 changes: 0 additions & 5 deletions src/shared/methods/websocket/index.js

This file was deleted.