Skip to content

Commit

Permalink
Completed bot service migration
Browse files Browse the repository at this point in the history
  • Loading branch information
nickheyer committed Feb 18, 2024
1 parent 8856159 commit 2267350
Show file tree
Hide file tree
Showing 15 changed files with 110 additions and 112 deletions.
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
21 changes: 18 additions & 3 deletions 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 Down Expand Up @@ -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/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
10 changes: 3 additions & 7 deletions src/core/bot/managers/events/ready.js
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;
}
}
}
};
30 changes: 25 additions & 5 deletions src/core/methods/discord/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
const botMethods = require('./botMethods');
const botController = require('./botController');
const _ = require('lodash');

module.exports = {
...botMethods,
...botController,

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;
},
};
20 changes: 5 additions & 15 deletions src/core/methods/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
const discord = require('./discord');
const websocket = require('./websocket');
const server = require('./server');
const rendering = require('./rendering');


function bindMethods(methods, cls) {
for (let [name, method] of Object.entries(methods)) {
cls[name] = method;
}
}
const _ = require('lodash');

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

module.exports = {
...serverBarRendering,
...templateCompiler,
}
...require('./serverBarRendering'),
...require('./templateCompiler')
};

6 changes: 2 additions & 4 deletions src/core/methods/server/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const processTerminator = require('./processTerminator.js');

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


module.exports = {
generateTerminator() {
const serverTerminator = createHttpTerminator({ server: this.server })
const logger = this.logger;

async function cleanup() {
logger.info('IN CLEANUP');
try {
await serverTerminator.terminate();
} catch (error) {
logger.error('Failed to terminate server:', error);
}
}

async function uncaught(signal, e) {
logger.error(`Uncaught exception encountered\n...CHECK LOGS.`, signal, e);
console.trace(signal, e);
}

async function shutdownServer(signal, e) {
logger.silly(`Received ${signal}\n${e}\n...Shutting down gracefully.`);
await cleanup();
process.exit();
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);
}

// SETTING EVENT HANDLERS FOR ON SHUTDOWN
process.on('SIGINT', (e) => shutdownServer('SIGNINT', e));
process.on('SIGTERM', (e) => shutdownServer('SIGTERM', e));
process.on('uncaughtException', (e) => uncaught('uncaughtException', e));

return shutdownServer;
process.exit();
}
};
5 changes: 2 additions & 3 deletions src/core/methods/websocket/connections.js
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);
}
}
};
7 changes: 3 additions & 4 deletions src/core/methods/websocket/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const connections = require('./connections');

module.exports = {
...connections,
}
...require('./connections'),
};

0 comments on commit 2267350

Please sign in to comment.