This commit is contained in:
Hri7566 2023-01-14 19:48:04 -05:00
parent f91aaf8561
commit 491624e492
14 changed files with 273 additions and 129 deletions

@ -1 +1 @@
Subproject commit b1dc90c9b890b6c0d2446ebf5d6c419cb75336a6 Subproject commit f8f618278d6677e4687bd73efb390f145e79c20d

View File

@ -1,6 +1,6 @@
{ {
"name": "mpp-server-master", "name": "mpp-server-master",
"version": "1.0.0", "version": "1.1.0",
"description": "Attempt at making a MPP Server.", "description": "Attempt at making a MPP Server.",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {

View File

@ -27,8 +27,13 @@ const LOGGER_PARTICIPANT = {
} }
const LOGGING_CHANNEL = 'lolwutsecretloggingchannel'; const LOGGING_CHANNEL = 'lolwutsecretloggingchannel';
const BAN_CHANNEL = 'test/awkward';
class Channel extends EventEmitter { class Channel extends EventEmitter {
static loggingChannel = LOGGING_CHANNEL;
static loggerParticipant = LOGGER_PARTICIPANT;
static banChannel = BAN_CHANNEL;
constructor(server, _id, settings, cl) { constructor(server, _id, settings, cl) {
super(); super();
this.logger = new Logger(`Room - ${_id}`); this.logger = new Logger(`Room - ${_id}`);
@ -57,14 +62,14 @@ class Channel extends EventEmitter {
this.logger.log('Created'); this.logger.log('Created');
if (this._id == LOGGING_CHANNEL) { if (this._id == this.loggingChannel) {
if (cl.user.hasFlag('admin')) { if (cl.user.hasFlag('admin')) {
delete this.crown; delete this.crown;
Logger.buffer.forEach(str => { Logger.buffer.forEach(str => {
this.chatmsgs.push({ this.chatmsgs.push({
m: 'a', m: 'a',
p: LOGGER_PARTICIPANT, p: this.loggerParticipant,
a: str.replace(ansiRegex(), '') a: str.replace(ansiRegex(), '')
}); });
}); });
@ -72,7 +77,7 @@ class Channel extends EventEmitter {
Logger.on('buffer update', (str) => { Logger.on('buffer update', (str) => {
this.chatmsgs.push({ this.chatmsgs.push({
m: 'a', m: 'a',
p: LOGGER_PARTICIPANT, p: this.loggerParticipant,
a: str.replace(ansiRegex(), '') a: str.replace(ansiRegex(), '')
}); });
@ -80,17 +85,17 @@ class Channel extends EventEmitter {
}); });
this.emit('update'); this.emit('update');
let c = new Color(LOGGER_PARTICIPANT.color); let c = new Color(this.loggerParticipant.color);
c.add(-0x40, -0x40, -0x40); c.add(-0x40, -0x40, -0x40);
this.settings = RoomSettings.changeSettings({ this.settings = RoomSettings.changeSettings({
color: c.toHexa(), color: c.toHexa(),
chat: true, chat: true,
crownsolo: true, crownsolo: true,
lobby: false, lobby: false,
owner_id: LOGGER_PARTICIPANT._id owner_id: this.loggerParticipant._id
}, true); }, true);
} else { } else {
cl.setChannel('test/awkward'); cl.setChannel(Channel.banChannel);
} }
} else { } else {
Database.getRoomSettings(this._id, (err, set) => { Database.getRoomSettings(this._id, (err, set) => {
@ -444,7 +449,7 @@ class Channel extends EventEmitter {
return false; return false;
} }
} }
} else if (_id.startsWith("test/") || _id.toLowerCase().includes("grant")) { } else if (_id.startsWith("test/") /* || _id.toLowerCase().includes("grant") */) {
if (_id == "test/") { if (_id == "test/") {
return false; return false;
} else { } else {
@ -611,7 +616,7 @@ class Channel extends EventEmitter {
this.bans.set(user.user._id, user); this.bans.set(user.user._id, user);
//if (this.crown && (this.crown.userId)) { //if (this.crown && (this.crown.userId)) {
u.setChannel("test/awkward", {}); u.setChannel(Channel.banChannel, {});
if (asd) if (asd)
this.Notification(user.user._id, this.Notification(user.user._id,
@ -646,17 +651,17 @@ class Channel extends EventEmitter {
} }
unban(_id) { unban(_id) {
this.connections.filter((usr) => usr.participantId == user.participantId).forEach(u => { let ban = this.bans.get(_id);
if (user.bantime) { if (!ban) return;
delete user.bantime; if (ban.bantime) {
} delete ban.bantime;
}
if (user.bannedtime) { if (ban.bannedtime) {
delete user.bannedtime; delete ban.bannedtime;
} }
this.bans.delete(user.user._id); this.bans.delete(ban.user._id);
});
} }
Notification(who, title, text, html, duration, target, klass, id) { Notification(who, title, text, html, duration, target, klass, id) {

View File

@ -83,7 +83,7 @@ class Client extends EventEmitter {
"#room", "#room",
"short" "short"
); );
this.setChannel("test/awkward", settings); this.setChannel(Channel.banChannel, settings);
return; return;
} }
@ -155,7 +155,8 @@ class Client extends EventEmitter {
chown: new RateLimitChain(quotas.chown.amount, quotas.chown.time), chown: new RateLimitChain(quotas.chown.amount, quotas.chown.time),
userset: new RateLimitChain(quotas.userset.amount, quotas.userset.time), userset: new RateLimitChain(quotas.userset.amount, quotas.userset.time),
kickban: new RateLimitChain(quotas.kickban.amount, quotas.kickban.time), kickban: new RateLimitChain(quotas.kickban.amount, quotas.kickban.time),
note: new Quota(Quota.PARAMS_LOBBY), // note: new Quota(Quota.PARAMS_LOBBY),
note: new RateLimitChain(5, 5000),
chset: new Quota(Quota.PARAMS_USED_A_LOT), chset: new Quota(Quota.PARAMS_USED_A_LOT),
"+ls": new Quota(Quota.PARAMS_USED_A_LOT), "+ls": new Quota(Quota.PARAMS_USED_A_LOT),
"-ls": new Quota(Quota.PARAMS_USED_A_LOT) "-ls": new Quota(Quota.PARAMS_USED_A_LOT)
@ -235,6 +236,7 @@ class Client extends EventEmitter {
let users = []; let users = [];
this.server.connections.forEach(cl => { this.server.connections.forEach(cl => {
if (!cl.user) return;
let u = { let u = {
p: { p: {
_id: cl.user._id, _id: cl.user._id,
@ -250,6 +252,8 @@ class Client extends EventEmitter {
}); });
data.channelManager = { data.channelManager = {
loggingChannel: Channel.loggingChannel,
loggerParticipant: Channel.loggerParticipant,
channels channels
}; };
@ -257,6 +261,8 @@ class Client extends EventEmitter {
users users
} }
data.uptime = Date.now() - this.server.startTime;
this.sendArray([data]); this.sendArray([data]);
} }

View File

@ -60,7 +60,7 @@ function getTimeColor(currentDate = new Date()) {
let dayOfYear = Math.ceil(differenceInTime / oneDayInMS); let dayOfYear = Math.ceil(differenceInTime / oneDayInMS);
dayOfYear %= 365; dayOfYear %= 365;
console.log(dayOfYear); // console.log(dayOfYear);
// get hour // get hour
let hours = currentDate.getHours(); let hours = currentDate.getHours();

View File

@ -12,7 +12,9 @@ class Cow {
} }
constructor() { constructor() {
this['🐄'] = Cow.generateRandomName(); this['display_name'] = Cow.generateRandomName();
this['emoji'] = '🐄'
this['count'] = 1;
} }
} }

View File

@ -5,7 +5,8 @@ const ColorEncoder = require('./ColorEncoder');
const UserModel = require('./UserModel'); const UserModel = require('./UserModel');
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const level = require('level'); const level = require('level');
const { db } = require('./UserModel'); const { users } = require('./UserModel');
const { inventories } = require('./InventoryModel');
const Logger = require('./Logger'); const Logger = require('./Logger');
var logger = new Logger("Database"); var logger = new Logger("Database");

View File

@ -1,14 +1,99 @@
const Logger = require("../Logger");
const Color = require('../Color');
class Command { class Command {
constructor(id, args, desc, usage, func, permLevel) { static commands = [];
static logger = new Logger("Command Handler");
static handleCommand(cl, ch, c, usedPrefix, args, argcat, p, isAdmin) {
for (let cmd of this.commands) {
let aliasCheck = false;
aliasLoop:
for (let alias of cmd.aliases) {
if (c.toLowerCase() == alias.toLowerCase()) {
aliasCheck = true;
break aliasLoop;
}
}
if (!aliasCheck) continue;
if (!isAdmin && cmd.permLevel == 'admin') return ch.adminChat(`You don't have permission to use this command.`);
if (args.length - 1 < cmd.minargs) return ch.adminChat(`Not enough arguments. Usage: ${this.getUsage(cmd.usage, usedPrefix)}`);
try {
const out = cmd.func(cl, ch, {
c, args, argcat, p, isAdmin, a: args.join(' ')
});
console.log(out);
if (!out) return;
if (out !== '') {
ch.adminChat(out);
}
} catch (err) {
this.logger.error(err);
ch.adminChat(`An error has occurred whilst performing this command.`);
}
}
}
static addCommand(cmd) {
this.commands.push(cmd);
}
static getUsage(usa, pre) {
return usa.split('%P').join(pre);
}
constructor(id, aliases, desc, usage, minargs, func, permLevel) {
this.id = id; this.id = id;
this.args = args || [id]; this.aliases = aliases || [id];
this.desc = desc || 'no description'; // brandon-like words this.desc = desc || 'no description'; // brandon-like words
this.usage = usage || 'no usage'; this.usage = usage || 'no usage';
this.minargs = minargs;
this.func = func; this.func = func;
this.permLevel = permLevel || 'admin'; // user / admin? this.permLevel = permLevel || 'admin'; // user / admin?
} }
} }
Command.addCommand(new Command('ping', ['ping'], undefined, `%Pping`, 0, (cl, ch, msg) => {
return `pong`;
}, 'user'));
Command.addCommand(new Command('color', ['color', 'setcolor', 'colorset'], undefined, `%Pcolor [color] [userid]`, 0, (cl, ch, msg) => {
if (!msg.isAdmin) {
ch.adminChat("You do not have permission to use this command.");
return;
}
let color = ch.verifyColor(msg.args[1]);
if (color) {
let c = new Color(color);
if (!msg.args[2]) {
cl.emit("color", {
color: c.toHexa(),
_id: cl.user._id
}, true);
ch.adminChat(`Your color is now ${c.getName().replace('A', 'a')} [${c.toHexa()}]`);
} else {
let winner = ch.server.getAllClientsByUserID(msg.args[2])[0];
if (winner) {
cl.emit("color", {
color: c.toHexa(),
_id: winner.user._id
}, true);
ch.adminChat(`Friend ${winner.user.name}'s color is now ${c.getName().replace('A', 'a')}.`);
} else {
ch.adminChat("The friend you are looking for (" + msg.args[2] + ") is not around.");
}
}
} else {
ch.adminChat("Invalid color.");
}
ch.updateCh();
}, 'user'));
module.exports = { module.exports = {
Command Command
} }

View File

@ -9,6 +9,7 @@ class InternalBot {
static once = EventEmitter.prototype.once; static once = EventEmitter.prototype.once;
static prefix = '!'; static prefix = '!';
static commands = [];
static bindEventListeners() { static bindEventListeners() {
if (this.alreadyBound) return; if (this.alreadyBound) return;
@ -32,75 +33,85 @@ class InternalBot {
let p = cl; let p = cl;
if (!args[0].startsWith(this.prefix)) return; if (!args[0].startsWith(this.prefix)) return;
let prefix = this.prefix;
Command.handleCommand(cl, ch, cmd, prefix, args, argcat, p, isAdmin);
switch (cmd) { // switch (cmd) {
case "ping": // case "ping":
ch.adminChat('pong'); // ch.adminChat('pong');
break; // break;
case "setcolor": // case "setcolor":
case "color": // case "color":
if (!isAdmin) { // if (!isAdmin) {
ch.adminChat("You do not have permission to use this command."); // ch.adminChat("You do not have permission to use this command.");
return; // return;
} // }
let color = ch.verifyColor(args[1]); // let color = ch.verifyColor(args[1]);
if (color) { // if (color) {
let c = new Color(color); // let c = new Color(color);
if (!args[2]) { // if (!args[2]) {
p.emit("color", { // p.emit("color", {
color: c.toHexa(), // color: c.toHexa(),
_id: p.user._id // _id: p.user._id
}, true); // }, true);
ch.adminChat(`Your color is now ${c.getName().replace('A', 'a')} [${c.toHexa()}]`); // ch.adminChat(`Your color is now ${c.getName().replace('A', 'a')} [${c.toHexa()}]`);
} else { // } else {
let winner = ch.server.getAllClientsByUserID(args[2])[0]; // let winner = ch.server.getAllClientsByUserID(args[2])[0];
if (winner) { // if (winner) {
p.emit("color", { // p.emit("color", {
color: c.toHexa(), // color: c.toHexa(),
_id: winner.user._id // _id: winner.user._id
}, true); // }, true);
ch.adminChat(`Friend ${winner.user.name}'s color is now ${c.getName().replace('A', 'a')}.`); // ch.adminChat(`Friend ${winner.user.name}'s color is now ${c.getName().replace('A', 'a')}.`);
} else { // } else {
ch.adminChat("The friend you are looking for (" + args[2] + ") is not around."); // ch.adminChat("The friend you are looking for (" + args[2] + ") is not around.");
} // }
} // }
} else { // } else {
ch.adminChat("Invalid color."); // ch.adminChat("Invalid color.");
} // }
ch.updateCh(); // ch.updateCh();
break; // break;
case "users": // case "users":
ch.adminChat(`There are ${ch.server.connections.size} users online.`); // ch.adminChat(`There are ${ch.server.connections.size} users online.`);
break; // break;
case "chown": // case "chown":
if (!isAdmin) return; // if (!isAdmin) return;
let id = p.participantId; // let id = p.participantId;
if (args[1]) { // if (args[1]) {
id = args[1]; // id = args[1];
} // }
if (ch.hasUser(id)) { // if (ch.hasUser(id)) {
ch.chown(id); // ch.chown(id);
} // }
break; // break;
case "chlist": // case "chlist":
case "channellist": // case "channellist":
if (!isAdmin) return; // if (!isAdmin) return;
ch.adminChat("Channels:"); // ch.adminChat("Channels:");
for (let [_id] of ch.server.rooms) { // for (let [_id] of ch.server.rooms) {
ch.adminChat(`- ${_id}`); // ch.adminChat(`- ${_id}`);
} // }
break; // break;
case "restart": // case "restart":
if (!isAdmin) return; // if (!isAdmin) return;
cl.server.restart(); // cl.server.restart();
break; // break;
case "eval": // case "eval":
case "javascript": // case "javascript":
case "js": // case "js":
if (!isAdmin) return; // if (!isAdmin) return;
cl.server.ev(argcat); // cl.server.ev(argcat);
break; // break;
} // case "inventory":
// case "inv":
// if (cl.user.inventory) {
// ch.adminChat(`Inventory: ${Object.values(cl.user.inventory).map(it => `${it.display_name} (x${it.count})`)}`);
// } else {
// ch.adminChat(`Inventory: (empty)`);
// }
// break;
// }
}); });
} }
} }

6
src/InventoryModel.js Normal file
View File

@ -0,0 +1,6 @@
const mongoose = require('mongoose');
module.exports = mongoose.model('Inventory', {
user_id: String,
items: Array
});

View File

@ -4,6 +4,16 @@ let hd = new Holidays();
hd.init('US'); hd.init('US');
let dayOfTheWeekMOTD = [
'Happy Sunday!',
'You can chat with that thing.',
'I\'m tired...',
'Don\'t forget to bring a towel!',
'Never lick a pole in winter.',
'Everyone loves a potato monkey!',
'Dear Mario: Please come to the castle. I\'ve baked a cake for you. Yours truly-- Princess Toadstool'
]
class MOTDGenerator { class MOTDGenerator {
static getDay() { static getDay() {
let now = new Date(); let now = new Date();
@ -18,10 +28,11 @@ class MOTDGenerator {
let h = hd.isHoliday(Date.now()); let h = hd.isHoliday(Date.now());
if (h) { if (h) {
// maybe holiday // maybe holiday
return `Happy ${h[0].name}`; return `Happy ${h[0].name}!`;
} else { } else {
// no holiday // no holiday, get day
return 'cotton-headed ninnymuggins' let day = new Date().getDay();
return dayOfTheWeekMOTD[day];
} }
} }
} }

View File

@ -110,7 +110,7 @@ module.exports = (cl) => {
if (msg.id == cl.user.id) { if (msg.id == cl.user.id) {
param = Quota.N_PARAMS_RIDICULOUS; param = Quota.N_PARAMS_RIDICULOUS;
param.m = "nq"; param.m = "nq";
cl.sendArray([param]) cl.sendArray([param]);
} }
} }
} else { } else {
@ -118,7 +118,7 @@ module.exports = (cl) => {
if (msg.id == cl.user.id) { if (msg.id == cl.user.id) {
param = Quota.N_PARAMS_RIDICULOUS; param = Quota.N_PARAMS_RIDICULOUS;
param.m = "nq"; param.m = "nq";
cl.sendArray([param]) cl.sendArray([param]);
} }
} }
} else { } else {
@ -127,11 +127,11 @@ module.exports = (cl) => {
cl.channel.chown(); cl.channel.chown();
param = Quota.N_PARAMS_NORMAL; param = Quota.N_PARAMS_NORMAL;
param.m = "nq"; param.m = "nq";
cl.sendArray([param]) cl.sendArray([param]);
} }
} else { } else {
cl.channel.chown(); cl.channel.chown();
param = Quota.N_PARAMS_NORMAL; param = Quota.N_PARAMS_RIDICULOUS;
param.m = "nq"; param.m = "nq";
cl.sendArray([param]); cl.sendArray([param]);
} }
@ -155,30 +155,39 @@ module.exports = (cl) => {
if (!msg.hasOwnProperty('message')) return; if (!msg.hasOwnProperty('message')) return;
if (typeof(msg.message) !== 'string') return; if (typeof(msg.message) !== 'string') return;
if (cl.channel.settings.chat) { if (cl.channel.settings.chat) {
if (cl.channel.isLobby(cl.channel._id)) { if (admin && msg.admin == true) {
if (!cl.quotas.chat.lobby.attempt() && !admin && !cl.user.hasFlag('no chat rate limit', true)) return; cl.channel.adminChat(msg.message);
} else { } else {
if (!(cl.user._id == cl.channel.crown.userId)) { if (cl.channel.isLobby(cl.channel._id)) {
if (!cl.quotas.chat.normal.attempt() && !admin && !cl.user.hasFlag('no chat rate limit', true)) return; if (!cl.quotas.chat.lobby.attempt() && !admin && !cl.user.hasFlag('no chat rate limit', true)) return;
} else { } else {
if (!cl.quotas.chat.insane.attempt() && !admin && !cl.user.hasFlag('no chat rate limit', true)) return; if (!(cl.user._id == cl.channel.crown.userId)) {
} if (!cl.quotas.chat.normal.attempt() && !admin && !cl.user.hasFlag('no chat rate limit', true)) return;
} } else {
cl.channel.emit('a', cl, msg); if (!cl.quotas.chat.insane.attempt() && !admin && !cl.user.hasFlag('no chat rate limit', true)) return;
}
}
cl.channel.emit('a', cl, msg);
}
} }
}); });
cl.on('n', msg => { cl.on('n', (msg, admin) => {
if (!(cl.channel && cl.participantId)) return; if (!(cl.channel && cl.participantId)) return;
if (!msg.hasOwnProperty('t') || !msg.hasOwnProperty('n')) return; if (!msg.hasOwnProperty('t') || !msg.hasOwnProperty('n')) return;
if (typeof msg.t != 'number' || typeof msg.n != 'object') return; if (typeof msg.t != 'number' || typeof msg.n != 'object') return;
if (cl.channel.settings.crownsolo) {
if ((cl.channel.crown.userId == cl.user._id) && !cl.channel.crowndropped) { if (cl.quotas.note && !admin) {
cl.channel.playNote(cl, msg); if (!cl.quotas.note.attempt()) return;
} }
} else {
cl.channel.playNote(cl, msg); if (cl.channel.settings.crownsolo) {
} if ((cl.channel.crown.userId == cl.user._id) && !cl.channel.crowndropped) {
cl.channel.playNote(cl, msg);
}
} else {
cl.channel.playNote(cl, msg);
}
}); });
cl.on('+ls', msg => { cl.on('+ls', msg => {
@ -212,7 +221,7 @@ module.exports = (cl) => {
} }
}); });
cl.on('kickban', msg => { cl.on('kickban', (msg, admin) => {
if (!admin) { if (!admin) {
if (cl.channel.crown == null) return; if (cl.channel.crown == null) return;
if (!(cl.channel && cl.participantId)) return; if (!(cl.channel && cl.participantId)) return;
@ -222,7 +231,7 @@ module.exports = (cl) => {
if (msg.hasOwnProperty('_id') && typeof msg._id == "string") { if (msg.hasOwnProperty('_id') && typeof msg._id == "string") {
if (!cl.quotas.kickban.attempt() && !admin) return; if (!cl.quotas.kickban.attempt() && !admin) return;
let _id = msg._id; let _id = msg._id;
let ms = msg.ms || 3600000; let ms = msg.ms || 36e5;
cl.channel.kickban(_id, ms); cl.channel.kickban(_id, ms);
} }
}); });

View File

@ -13,6 +13,8 @@ class Server {
static emit = EventEmitter.prototype.emit; static emit = EventEmitter.prototype.emit;
static once = EventEmitter.prototype.once; static once = EventEmitter.prototype.once;
static startTime = Date.now();
static start(config) { static start(config) {
// super(); // super();
// EventEmitter.call(this); // EventEmitter.call(this);
@ -84,6 +86,7 @@ class Server {
"userset", "userset",
"chown", "chown",
"kickban", "kickban",
"unban",
"admin message", "admin message",
"color", "color",
"eval", "eval",
@ -116,10 +119,19 @@ class Server {
cl = undefined; cl = undefined;
return; return;
} }
let newch = {
banned: typeof this.rooms.get(data.ch._id).bans.get(cl.user._id) !== 'undefined'
};
for (let key of Object.keys(data)) {
newch[key] = data.ch[key];
}
cl.sendArray([{ cl.sendArray([{
"m": "ls", "m": "ls",
"c": false, "c": false,
"u": [data.ch] "u": [newch]
}]); }]);
} }
} }

View File

@ -1,4 +1,5 @@
const Database = require("./Database"); const Database = require("./Database");
const { Cow } = require('./Cow');
function hslToHex(h, s, l) { function hslToHex(h, s, l) {
l /= 100; l /= 100;
@ -23,12 +24,7 @@ class User {
freeze_name: false freeze_name: false
} }
this.inventory = { this.inventory = {};
'test': {
display_name: 'Test',
count: 1
}
};
} }
getPublicUser() { getPublicUser() {