Skip to content
This repository has been archived by the owner on Oct 17, 2024. It is now read-only.

Commit

Permalink
Merge pull request #85 from takejohn/feature/75-loki
Browse files Browse the repository at this point in the history
LokiJS 対応 (#75)
  • Loading branch information
ringo360 authored Apr 5, 2024
2 parents c53df55 + 1563db7 commit 32d3e1d
Show file tree
Hide file tree
Showing 29 changed files with 734 additions and 260 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,6 @@ dist

# Font file
*.ttf

# LokiJS database file
database.json
68 changes: 68 additions & 0 deletions common/Feature.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Client } from 'discord.js';

/**
* 機能の1単位を表すオブジェクト
*/
export abstract class Feature {
private loading = false;

private unloading = false;

async load(client: Client<boolean>) {
if (!this.loading) {
this.loading = true;
const dependencies = this.dependencies;
// この機能をロードする前に依存先の機能をロードする
if (dependencies != null) {
await Promise.all(
dependencies.map((dependency) => {
dependency.usedBy.push(this);
return dependency.load(client);
}),
);
}
console.log(`Loading ${this.name} feature`);
await this.onLoad(client);
}
}

async unload() {
if (!this.unloading) {
this.unloading = true;
// 依存元の機能をアンロードした後にこの機能をアンロードする
await Promise.all(this.usedBy.map((dependency) => dependency.unload()));
console.log(`Unloading ${this.name} feature`);
await this.onUnload();
}
}

name: string;

/**
* この機能の依存先の機能
*/
dependencies?: Feature[];

private usedBy: Feature[] = [];

/**
* 読み込まれた時の処理
*/
onLoad(client: Client<boolean>): PromiseLike<void> | void {
// デフォルトでは何もしない
}

/**
* クライアントにログインしたときの処理
*/
onClientReady(client: Client<true>): PromiseLike<void> | void {
// デフォルトでは何もしない
}

/**
* 終了したときの処理
*/
onUnload(): PromiseLike<void> | void {
// デフォルトでは何もしない
}
}
1 change: 1 addition & 0 deletions config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"AdminRoleID": "00000000000",
"AdminUserIDs": ["1063527758292070591", "1126422758696427552"],
"replyCustomizeAllowedUsers": ["00000000000","16326412825651210244096"],
"database": "mongo",
"mongoDBhost": "127.0.0.1",
"mongoDBport": "27017",
"mongoDBuser": "admin",
Expand Down
19 changes: 5 additions & 14 deletions discordbot.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { teeWrite } from './internal/logger';
import { ClientMessageHandler } from './internal/messages';

//* Discord.js Bot - by ringoXD -
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '1';
Expand All @@ -13,14 +12,11 @@ process.env['FFMPEG_PATH'] = path.join(__dirname, 'ffmpeg');
//!Load Internal dir code
import { onShutdown } from './internal/schedules';
import activity from './internal/activity';
import mongodb from './internal/mongodb';

mongodb.connectMongoose();

import { LANG, strFormat } from './util/languages';
import { CommandManager } from './internal/commands';
import assert from 'assert';
import { Feature } from './util/types';
import { Feature } from './common/Feature';

const creset = '\x1b[0m';
const cgreen = '\x1b[32m';
Expand Down Expand Up @@ -54,20 +50,19 @@ console.log(
const client = new Client(options);
console.log(LANG.discordbot.main.setupActivityCalling);
activity.setupActivity(client);
let messageHandler: ClientMessageHandler | undefined;

const featuresLoadPromise = fs
.readdir(path.join(__dirname, 'packages'))
.then((files) =>
Promise.all(
files.map(async (file) => {
console.log(`loading ${file} feature`);
const module = await import(file);
const feature: Feature = module.feature;
if (feature == null) {
console.log(module);
throw new TypeError(`${file} feature is undefined`);
}
await feature.onLoad?.(client);
await feature.load(client);
return feature;
}),
),
Expand All @@ -76,7 +71,7 @@ const featuresLoadPromise = fs
client.on('ready', async (readyClient) => {
const features = await featuresLoadPromise;
await Promise.all(
features.map((feature) => feature.onClientReady?.(readyClient)),
features.map((feature) => feature.onClientReady(readyClient)),
);
console.log(
strFormat(LANG.discordbot.ready.loggedIn, {
Expand Down Expand Up @@ -106,29 +101,25 @@ client.on('ready', async (readyClient) => {
const SyslogChannel = client.channels.cache.get(syslogChannel);
assert(SyslogChannel.isTextBased());
SyslogChannel.send(LANG.discordbot.ready.sysLog);
messageHandler = new ClientMessageHandler(readyClient);
});

onShutdown(async () => {
const SyslogChannel = client.channels.cache.get(syslogChannel);
assert(SyslogChannel.isTextBased());
await SyslogChannel.send(LANG.discordbot.shutdown.sysLog);
const features = await featuresLoadPromise;
await Promise.all(features.map((feature) => feature.onUnload?.()));
await Promise.all(features.map((feature) => feature.unload()));
await Promise.all([
client
.destroy()
.then(() =>
console.log(cgreen + LANG.discordbot.shutdown.loggedOut + creset),
),
mongodb.connection.close(),
]);
});

client.login(token);

client.on('messageCreate', (message) => messageHandler?.handleMessage(message));

//!EVENTS

process.on('uncaughtException', function (err) {
Expand Down
20 changes: 15 additions & 5 deletions internal/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ const internalLinkConfigSchema = z.object({
linkPort: z.string(),
});

const mongoDBConfigSchema = z.object({
database: z.literal('mongo').optional(),
mongoDBhost: z.string(),
mongoDBport: z.string(),
mongoDBuser: z.string(),
mongoDBpass: z.string(),
mongoDBdatabase: z.string(),
});

const lokiJSConfigSchema = z.object({
database: z.literal('loki'),
lokiJSfile: z.string().optional(),
});

const configSchema = z
.object({
token: z.string(),
Expand All @@ -24,17 +38,13 @@ const configSchema = z
cfPurgeUrl: z.string().optional(),
AdminUserIDs: z.array(z.string()),
replyCustomizeAllowedUsers: z.array(z.string()).optional(),
mongoDBhost: z.string(),
mongoDBport: z.string(),
mongoDBuser: z.string(),
mongoDBpass: z.string(),
mongoDBdatabase: z.string(),
syslogChannel: z.string(),
notificationChannel: z.string(),
language: z.string().optional(),
fontFile: z.string().optional(),
fontFamily: z.string().optional(),
})
.and(mongoDBConfigSchema.or(lokiJSConfigSchema))
.and(tempLinkSrvConfigSchema.or(internalLinkConfigSchema));

function loadJson(path: string) {
Expand Down
34 changes: 0 additions & 34 deletions internal/mongodb.js

This file was deleted.

22 changes: 21 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
"ip-range-check": "^0.2.0",
"libsodium-wrappers": "^0.7.13",
"mediaplex": "^0.0.9",
"mongoose": "^8.2.1",
"path": "^0.12.7",
"rcon-client": "^4.2.4",
"ytdl-core": "^4.11.5",
Expand Down
16 changes: 7 additions & 9 deletions packages/admin/commands/globalban.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { report } from 'process';

const {
SlashCommandBuilder,
PermissionsBitField,
Expand All @@ -8,7 +6,7 @@ const {
TextInputStyle,
ActionRowBuilder,
} = require('discord.js');
const mongodb = require('../../../internal/mongodb'); //*MongoDB
const { feature: db } = require('db'); //*MongoDB
const { AdminUserIDs } = require('../../../config.json');
const Pager = require('../../../util/pager');
const { LANG, strFormat } = require('../../../util/languages');
Expand Down Expand Up @@ -96,7 +94,7 @@ module.exports = {
}
try {
// データベースから全てのユーザーを取得
const userCollection = mongodb.connection.collection('globalBans');
const userCollection = db.connection.collection('globalBans');
const allUsers = await userCollection.find({}).toArray();

// ユーザー情報をログに表示
Expand Down Expand Up @@ -175,7 +173,7 @@ module.exports = {
//*add/rm
if (subcommand === LANG.commands.globalban.subcommands.add.name) {
try {
const existingBan = await mongodb.connection
const existingBan = await db.connection
.collection('globalBans')
.findOne({ userId: user.id });
if (existingBan) {
Expand All @@ -185,7 +183,7 @@ module.exports = {
]),
);
}
await mongodb.connection.collection('globalBans').insertOne({
await db.connection.collection('globalBans').insertOne({
userId: user.id,
userName: user.tag,
reason: reason,
Expand Down Expand Up @@ -239,7 +237,7 @@ module.exports = {
}
} else if (subcommand === LANG.commands.globalban.subcommands.remove.name) {
try {
const existingBan = await mongodb.connection
const existingBan = await db.connection
.collection('globalBans')
.findOne({ userId: user.id });
if (!existingBan) {
Expand All @@ -250,7 +248,7 @@ module.exports = {
);
}

await mongodb.connection
await db.connection
.collection('globalBans')
.deleteOne({ userId: user.id });
let done = 0;
Expand Down Expand Up @@ -303,7 +301,7 @@ module.exports = {
//*LIST
} else if (subcommand === LANG.commands.globalban.subcommands.list.name) {
try {
const userCollection = mongodb.connection.collection('globalBans');
const userCollection = db.connection.collection('globalBans');
const bans = await userCollection.find({}).toArray();
const pager = new Pager(
bans.map((ban) =>
Expand Down
8 changes: 7 additions & 1 deletion packages/admin/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
const { Feature } = require('../../common/Feature');
const { CommandManager } = require('../../internal/commands');
const db = require('db');

class AdminFeature extends Feature {
name = 'admin';

dependencies = [db.feature];

class AdminFeature {
onLoad() {
CommandManager.default.addCommands([
require('./commands/globalban'),
Expand Down
5 changes: 4 additions & 1 deletion packages/cdn/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { Feature } from '../../common/Feature';
import { CommandManager } from '../../internal/commands';
import upload from './upload';

class CdnFeature {
class CdnFeature extends Feature {
name = 'cdn';

onLoad() {
CommandManager.default.addCommands(upload);
}
Expand Down
Loading

0 comments on commit 32d3e1d

Please sign in to comment.