This commit is contained in:
Hri7566 2023-03-31 10:43:24 -04:00
parent 183f2016c6
commit 1ef018fa1a
20 changed files with 15756 additions and 648 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ ssl/
.history
*.db/
.env
password.txt

2
.gitmodules vendored
View File

@ -1,3 +1,3 @@
[submodule "mpp.hri7566.info"]
path = mpp.hri7566.info
url = git@gitlab.com:Hri7566/mpp.hri7566.info.git
url = git@github.com:Hri7566/mpp.hri7566.info.git

6
.prettierrc Normal file
View File

@ -0,0 +1,6 @@
{
"arrowParens": "avoid",
"trailingComma": "none",
"semi": true,
"tabWidth": 4
}

@ -1 +1 @@
Subproject commit f8f618278d6677e4687bd73efb390f145e79c20d
Subproject commit 327c6775aceb4518437bf3f2c262c6e6f7423579

View File

@ -1,38 +1,38 @@
const createKeccakHash = require('keccak');
const Crown = require('./Crown.js');
const Database = require('./Database.js');
const Logger = require('./Logger.js');
const createKeccakHash = require("keccak");
const Crown = require("./Crown.js");
const Database = require("./Database.js");
const Logger = require("./Logger.js");
const Quota = require("./Quota.js");
const RoomSettings = require('./RoomSettings.js');
const ftc = require('fancy-text-converter');
const Notification = require('./Notification');
const Color = require('./Color');
const { getTimeColor } = require('./ColorEncoder.js');
const { InternalBot } = require('./InternalBot');
const RoomSettings = require("./RoomSettings.js");
const ftc = require("fancy-text-converter");
const Notification = require("./Notification");
const Color = require("./Color");
const { getTimeColor } = require("./ColorEncoder.js");
const { InternalBot } = require("./InternalBot");
function ansiRegex({onlyFirst = false} = {}) {
const pattern = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))'
].join('|');
function ansiRegex({ onlyFirst = false } = {}) {
const pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
].join("|");
return new RegExp(pattern, onlyFirst ? undefined : 'g');
return new RegExp(pattern, onlyFirst ? undefined : "g");
}
const LOGGER_PARTICIPANT = {
name: 'Logger',
color: '#72f1b8',
_id: 'logger',
id: 'logger'
}
name: "Logger",
color: "#72f1b8",
_id: "logger",
id: "logger"
};
const LOGGING_CHANNEL = 'lolwutsecretloggingchannel';
const BAN_CHANNEL = 'test/awkward';
const LOGGING_CHANNEL = "lolwutsecretloggingchannel";
const BAN_CHANNEL = "test/awkward";
class Channel extends EventEmitter {
static loggingChannel = LOGGING_CHANNEL;
static loggerParticipant = LOGGER_PARTICIPANT;
static banChannel = BAN_CHANNEL;
static loggingChannel = LOGGING_CHANNEL;
static loggerParticipant = LOGGER_PARTICIPANT;
static banChannel = BAN_CHANNEL;
constructor(server, _id, settings, cl) {
super();
@ -48,54 +48,63 @@ class Channel extends EventEmitter {
// this.settings.color = this.server.lobbySettings.color;
// this.settings.color2 = this.server.lobbySettings.color2;
} else {
this.settings = new RoomSettings(settings, 'user');
this.settings = new RoomSettings(settings, "user");
}
this.chatmsgs = [];
this.ppl = new Map();
this.connections = [];
this.bindEventListeners();
this.server.rooms.set(_id, this);
this.server.channels.set(_id, this);
this.bans = new Map();
this.flags = {}
this.flags = {};
this.destroyed = false;
this.logger.log('Created');
this.logger.log("Created");
if (this._id == this.loggingChannel) {
if (cl.user.hasFlag('admin')) {
if (this._id == LOGGING_CHANNEL) {
if (cl.user.hasFlag("admin")) {
delete this.crown;
Logger.buffer.forEach(str => {
this.chatmsgs.push({
m: 'a',
p: this.loggerParticipant,
a: str.replace(ansiRegex(), '')
m: "a",
p: LOGGER_PARTICIPANT,
a: str.replace(ansiRegex(), "")
});
});
Logger.on('buffer update', (str) => {
Logger.on("buffer update", str => {
this.chatmsgs.push({
m: 'a',
p: this.loggerParticipant,
a: str.replace(ansiRegex(), '')
m: "a",
p: LOGGER_PARTICIPANT,
a: str.replace(ansiRegex(), "")
});
this.sendChatArray();
});
this.emit('update');
let c = new Color(this.loggerParticipant.color);
this.emit("update");
let c = new Color(LOGGER_PARTICIPANT.color);
c.add(-0x40, -0x40, -0x40);
this.settings = RoomSettings.changeSettings({
color: c.toHexa(),
chat: true,
crownsolo: true,
lobby: false,
owner_id: this.loggerParticipant._id
}, true);
let c2 = new Color(c.toHexa());
c2.add(-0x40, -0x40, -0x40);
this.settings = RoomSettings.changeSettings(
{
color: c.toHexa(),
color2: c2.toHexa(),
chat: true,
crownsolo: true,
lobby: false,
owner_id: LOGGER_PARTICIPANT._id
},
true
);
} else {
cl.setChannel(Channel.banChannel);
cl.setChannel("test/awkward");
}
} else {
Database.getRoomSettings(this._id, (err, set) => {
@ -103,7 +112,10 @@ class Channel extends EventEmitter {
return;
}
this.settings = RoomSettings.changeSettings(this.settings, true);
this.settings = RoomSettings.changeSettings(
this.settings,
true
);
this.chatmsgs = set.chat;
this.sendChatArray();
this.setData();
@ -113,26 +125,30 @@ class Channel extends EventEmitter {
if (this.isLobby(this._id)) {
this.colorInterval = setInterval(() => {
this.setDefaultLobbyColorBasedOnDate();
}, 1000 * 60 * 5);
}, 500);
this.setDefaultLobbyColorBasedOnDate();
}
}
setChatArray(arr) {
this.chatmsgs = arr || [];
this.sendArray([{
m: 'c',
c: this.chatmsgs.slice(-1 * 32)
}]);
this.sendArray([
{
m: "c",
c: this.chatmsgs.slice(-1 * 32)
}
]);
this.setData();
}
sendChatArray() {
this.connections.forEach(cl => {
cl.sendArray([{
m: 'c',
c: this.chatmsgs.slice(-1 * 32)
}]);
cl.sendArray([
{
m: "c",
c: this.chatmsgs.slice(-1 * 32)
}
]);
});
}
@ -143,7 +159,7 @@ class Channel extends EventEmitter {
if (!this.settings) {
this.settings = new RoomSettings(this.server.lobbySettings);
}
this.settings.color = col.toHexa();
this.settings.color2 = col.toHexa();
@ -151,15 +167,19 @@ class Channel extends EventEmitter {
this.server.lobbySettings[key] = this.settings[key];
}
this.emit('update');
this.emit("update");
}
join(cl, set) { //this stuff is complicated
let otheruser = this.connections.find((a) => a.user._id == cl.user._id)
join(cl, set) {
//this stuff is complicated
let otheruser = this.connections.find(a => a.user._id == cl.user._id);
if (!otheruser) {
// we don't exist yet
// create id hash
let participantId = createKeccakHash('keccak256').update((Math.random().toString() + cl.ip)).digest('hex').substr(0, 24);
let participantId = createKeccakHash("keccak256")
.update(Math.random().toString() + cl.ip)
.digest("hex")
.substr(0, 24);
// set id
cl.user.id = participantId;
@ -169,7 +189,14 @@ class Channel extends EventEmitter {
cl.initParticipantQuotas();
// no users / already had crown? give crown
if (((this.connections.length == 0 && Array.from(this.ppl.values()).length == 0) && this.isLobby(this._id) == false) || this.crown && (this.crown.userId == cl.user._id || this.settings['owner_id'] == cl.user._id)) {
if (
(this.connections.length == 0 &&
Array.from(this.ppl.values()).length == 0 &&
this.isLobby(this._id) == false) ||
(this.crown &&
(this.crown.userId == cl.user._id ||
this.settings["owner_id"] == cl.user._id))
) {
// user owns the room
// we need to switch the crown to them
//cl.quotas.a.setParams(Quota.PARAMS_A_CROWNED);
@ -182,7 +209,7 @@ class Channel extends EventEmitter {
if (this.isLobby(this._id) && this.settings.lobby !== true) {
// fix lobby setting
this.settings.changeSettings({lobby: true});
this.settings.changeSettings({ lobby: true });
// this.settings.visible = true;
// this.settings.crownsolo = false;
// this.settings.lobby = true;
@ -190,14 +217,20 @@ class Channel extends EventEmitter {
// this.settings.color2 = this.server.lobbySettings.color2;
} else {
if (!this.isLobby) {
if (typeof(set) == 'undefined') {
if (typeof(this.settings) == 'undefined') {
this.settings = new RoomSettings(this.server.defaultRoomSettings, 'user');
if (typeof set == "undefined") {
if (typeof this.settings == "undefined") {
this.settings = new RoomSettings(
this.server.defaultRoomSettings,
"user"
);
} else {
this.settings = new RoomSettings(cl.channel.settings, 'user');
this.settings = new RoomSettings(
cl.channel.settings,
"user"
);
}
} else {
this.settings = new RoomSettings(set, 'user');
this.settings = new RoomSettings(set, "user");
}
}
}
@ -207,23 +240,31 @@ class Channel extends EventEmitter {
this.connections.push(cl);
cl.sendArray([{
m: "c",
c: this.chatmsgs.slice(-1 * 32)
}]);
cl.sendArray([
{
m: "c",
c: this.chatmsgs.slice(-1 * 32)
}
]);
// this.updateCh(cl, this.settings);
if (!cl.user.hasFlag("hidden", true)) {
this.sendArray([{
m: 'p',
_id: cl.user._id,
name: cl.user.name,
color: cl.user.color,
id: cl.participantId,
x: this.ppl.get(cl.participantId).x || 200,
y: this.ppl.get(cl.participantId).y || 100
}], cl, false);
this.sendArray(
[
{
m: "p",
_id: cl.user._id,
name: cl.user.name,
color: cl.user.color,
id: cl.participantId,
x: this.ppl.get(cl.participantId).x || 200,
y: this.ppl.get(cl.participantId).y || 100
}
],
cl,
false
);
}
this.updateCh(cl, this.settings);
@ -232,10 +273,12 @@ class Channel extends EventEmitter {
cl.participantId = otheruser.participantId;
cl.quotas = otheruser.quotas;
this.connections.push(cl);
cl.sendArray([{
m: "c",
c: this.chatmsgs.slice(-1 * 32)
}])
cl.sendArray([
{
m: "c",
c: this.chatmsgs.slice(-1 * 32)
}
]);
this.updateCh(cl, this.settings);
}
@ -244,10 +287,12 @@ class Channel extends EventEmitter {
}
}
spin(cl) { // speeeeeeen
spin(cl) {
// speeeeeeen
let id = cl.user._id;
if (!id) id = "room";
this.Notification(id,
this.Notification(
id,
"",
``,
`<script>$("#piano").addClass("spin")</script>`,
@ -260,7 +305,8 @@ class Channel extends EventEmitter {
stopSpin(cl) {
let id = cl.user._id;
if (!id) id = "room";
this.Notification(id,
this.Notification(
id,
"",
``,
`<script>$("#piano").removeClass("spin")</script>`,
@ -270,40 +316,58 @@ class Channel extends EventEmitter {
);
}
remove(p) { // remove user
remove(p) {
// remove user
if (!p) return;
let otheruser = this.connections.filter((a) => a.user._id == p.user._id);
if (!p.user) return;
let otheruser = this.connections.filter(a => a.user._id == p.user._id);
if (!(otheruser.length > 1)) {
this.ppl.delete(p.participantId);
this.connections.splice(this.connections.findIndex((a) => a.connectionid == p.connectionid), 1);
this.sendArray([{
m: "bye",
p: p.participantId
}], p, false);
this.connections.splice(
this.connections.findIndex(
a => a.connectionid == p.connectionid
),
1
);
this.sendArray(
[
{
m: "bye",
p: p.participantId
}
],
p,
false
);
if (this.crown)
if (this.crown.userId == p.user._id && !this.crowndropped) {
this.chown();
}
this.updateCh();
} else {
this.connections.splice(this.connections.findIndex((a) => a.connectionid == p.connectionid), 1);
this.connections.splice(
this.connections.findIndex(
a => a.connectionid == p.connectionid
),
1
);
}
}
updateCh(cl, set) { //update channel for all people in channel
updateCh(cl, set) {
//update channel for all people in channel
if (Array.from(this.ppl.values()).length <= 0) {
setTimeout(() => {
this.destroy();
}, 13000);
}
this.connections.forEach((usr) => {
this.connections.forEach(usr => {
let u = this.fetchChannelData(usr, cl);
this.server.connections.get(usr.connectionid).sendArray([u]);
});
this.server.updateRoom(this.fetchChannelData());
this.server.updateChannelList([this.fetchChannelData()]);
}
updateParticipant(pid, options) {
@ -313,32 +377,37 @@ class Channel extends EventEmitter {
if (rpg[1].user._id == pid) p = rpg[1];
});
if (typeof(p) == 'undefined') return;
if (typeof p == "undefined") return;
options.name ? p.user.name = options.name : {};
options._id ? p.user._id = options._id : {};
options.color ? p.user.color = options.color : {};
options.name ? (p.user.name = options.name) : {};
options._id ? (p.user._id = options._id) : {};
options.color ? (p.user.color = options.color) : {};
this.connections.filter((ofo) => ofo.participantId == p.participantId).forEach((usr) => {
options.name ? usr.user.name = options.name : {};
options._id ? usr.user._id = options._id : {};
options.color ? usr.user.color = options.color : {};
});
this.connections
.filter(ofo => ofo.participantId == p.participantId)
.forEach(usr => {
options.name ? (usr.user.name = options.name) : {};
options._id ? (usr.user._id = options._id) : {};
options.color ? (usr.user.color = options.color) : {};
});
if (!p.hidden) {
this.sendArray([{
color: p.user.color,
id: p.participantId,
m: "p",
name: p.user.name,
x: p.x || 200,
y: p.y || 100,
_id: p.user._id
}]);
this.sendArray([
{
color: p.user.color,
id: p.participantId,
m: "p",
name: p.user.name,
x: p.x || 200,
y: p.y || 100,
_id: p.user._id
}
]);
}
}
destroy() { //destroy room
destroy() {
//destroy room
if (this.destroyed) return;
if (this.ppl.size > 0) return;
if (this._id == "lobby") return;
@ -349,16 +418,23 @@ class Channel extends EventEmitter {
this.ppl;
this.connnections;
this.chatmsgs;
this.server.rooms.delete(this._id);
this.server.channels.delete(this._id);
}
sendArray(arr, not, onlythisparticipant) {
this.connections.forEach((usr) => {
if (!not || (usr.participantId != not.participantId && !onlythisparticipant) || (usr.connectionid != not.connectionid && onlythisparticipant)) {
this.connections.forEach(usr => {
if (
!not ||
(usr.participantId != not.participantId &&
!onlythisparticipant) ||
(usr.connectionid != not.connectionid && onlythisparticipant)
) {
try {
let cl = this.server.connections.get(usr.connectionid);
if (!cl) return;
this.server.connections.get(usr.connectionid).sendArray(arr)
this.server.connections
.get(usr.connectionid)
.sendArray(arr);
} catch (e) {
console.log(e);
}
@ -389,7 +465,7 @@ class Channel extends EventEmitter {
name: c.user.name,
color: c.user.color,
id: c.participantId
}
};
chppl.push(u);
});
@ -403,7 +479,7 @@ class Channel extends EventEmitter {
_id: this._id
},
ppl: chppl
}
};
if (cl) {
if (usr.connectionid == cl.connectionid) {
@ -418,7 +494,6 @@ class Channel extends EventEmitter {
if (data.ch.crown == null) {
delete data.ch.crown;
} else {
}
return data;
@ -449,7 +524,10 @@ class Channel extends EventEmitter {
return false;
}
}
} else if (_id.startsWith("test/") /* || _id.toLowerCase().includes("grant") */) {
} else if (
_id.startsWith("test/") ||
_id.toLowerCase().includes("grant")
) {
if (_id == "test/") {
return false;
} else {
@ -458,7 +536,6 @@ class Channel extends EventEmitter {
} else {
return false;
}
}
chown(id) {
@ -478,24 +555,26 @@ class Channel extends EventEmitter {
setCoords(p, x, y) {
if (p.participantId && this.ppl.get(p.participantId)) {
x ? this.ppl.get(p.participantId).x = x : {};
y ? this.ppl.get(p.participantId).y = y : {};
this.sendArray([{
m: "m",
id: p.participantId,
x: this.ppl.get(p.participantId).x,
y: this.ppl.get(p.participantId).y
}], p, false);
x ? (this.ppl.get(p.participantId).x = x) : {};
y ? (this.ppl.get(p.participantId).y = y) : {};
this.sendArray(
[
{
m: "m",
id: p.participantId,
x: this.ppl.get(p.participantId).x,
y: this.ppl.get(p.participantId).y
}
],
p,
false
);
}
}
chat(p, msg) {
if (msg.message.length > 512) return;
let filter = ["AMIGHTYWIND", "CHECKLYHQ"];
let regexp = new RegExp("\\b(" + filter.join("|") + ")\\b", "i");
if (regexp.test(msg.message.split(' ').join(''))) return;
if (p.participantId == 0) {
let message = {};
@ -503,32 +582,47 @@ class Channel extends EventEmitter {
message.t = Date.now();
message.a = msg.message;
message.p = {
color: "#ffffff",
id: "0",
name: "mpp",
_id: "0"
};
console.log("here:", p, msg);
console.log(message.length);
if (message.a.length > 0 && message.a.length <= 512) {
message.p = {
color: "#ffffff",
id: "0",
name: "mpp",
_id: "0"
};
this.sendArray([message]);
this.sendArray([message]);
this.chatmsgs.push(message);
this.setData();
return;
this.chatmsgs.push(message);
this.setData();
return;
}
}
let filter = ["AMIGHTYWIND", "CHECKLYHQ"];
let regexp = new RegExp("\\b(" + filter.join("|") + ")\\b", "i");
if (regexp.test(msg.message.split(" ").join(""))) return;
let prsn = this.ppl.get(p.participantId);
if (!prsn) return;
let message = {};
message.m = "a";
message.a = msg.message;
if (prsn.user.hasFlag('chat_curse_1')) {
if (prsn.user.flags['chat_curse_1'] != false) message.a = message.a.split(/[aeiou]/).join('o').split(/[AEIOU]/).join('O');
if (prsn.user.hasFlag("chat_curse_1")) {
if (prsn.user.flags["chat_curse_1"] != false)
message.a = message.a
.split(/[aeiou]/)
.join("o")
.split(/[AEIOU]/)
.join("O");
}
if (prsn.user.hasFlag('chat_curse_2')) {
if (prsn.user.hasFlag("chat_curse_2")) {
}
message.p = {
color: p.user.color,
id: p.participantId,
@ -542,40 +636,45 @@ class Channel extends EventEmitter {
this.chatmsgs.push(message);
this.setData();
InternalBot.emit('receive message', message, prsn, this);
InternalBot.emit("receive message", message, prsn, this);
}
adminChat(str) {
this.chat({
participantId: 0
}, {
message: str
});
this.chat(
{
participantId: 0
},
{
message: str
}
);
}
hasUser(id) {
return this.ppl.has(id);
// return this.ppl.has(id);
for (const p of this.ppl.values()) {
if (p.id == id) return true;
}
}
playNote(cl, note) {
if (cl.user.hasFlag('mute', true)) {
if (cl.user.hasFlag("mute", true)) {
return;
}
if (cl.user.hasFlag('mute')) {
if (Array.isArray(cl.user.flags['mute'])) {
if (cl.user.flags['mute'].includes(this._id)) return;
if (cl.user.hasFlag("mute")) {
if (Array.isArray(cl.user.flags["mute"])) {
if (cl.user.flags["mute"].includes(this._id)) return;
}
}
let vol;
if (cl.user.hasFlag('volume')) {
if (cl.user.hasFlag("volume")) {
vol = Math.round(cl.user.flags["volume"]) / 100;
}
if (typeof vol == 'number') {
if (typeof vol == "number") {
for (let no of note.n) {
if (no.v) {
if (vol == 0) {
@ -587,57 +686,74 @@ class Channel extends EventEmitter {
}
}
this.sendArray([{
m: "n",
n: note.n,
p: cl.participantId,
t: note.t
}], cl, true);
this.sendArray(
[
{
m: "n",
n: note.n,
p: cl.participantId,
t: note.t
}
],
cl,
true
);
}
kickban(_id, ms) {
ms = parseInt(ms);
if (ms >= (1000 * 60 * 60)) return;
if (ms >= 1000 * 60 * 60) return;
if (ms < 0) return;
ms = Math.round(ms / 1000) * 1000;
let user = this.connections.find((usr) => usr.user._id == _id);
let user = this.connections.find(usr => usr.user._id == _id);
if (!user) return;
let asd = true;
let pthatbanned = this.ppl.get(this.crown.participantId);
this.connections.filter((usr) => usr.participantId == user.participantId).forEach((u) => {
user.bantime = Math.floor(Math.floor(ms / 1000) / 60);
user.bannedtime = Date.now();
user.msbanned = ms;
this.connections
.filter(usr => usr.participantId == user.participantId)
.forEach(u => {
user.bantime = Math.floor(Math.floor(ms / 1000) / 60);
user.bannedtime = Date.now();
user.msbanned = ms;
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(Channel.banChannel, {});
if (asd)
this.Notification(user.user._id,
this.Notification(
user.user._id,
"Notice",
`Banned from \"${this._id}\" for ${Math.floor(Math.floor(ms / 1000) / 60)} minutes.`,
`Banned from \"${this._id}\" for ${Math.floor(
Math.floor(ms / 1000) / 60
)} minutes.`,
"",
7000,
"#room",
"short"
)
);
if (asd)
this.Notification("room",
this.Notification(
"room",
"Notice",
`${pthatbanned.user.name} banned ${user.user.name} from the channel for ${Math.floor(Math.floor(ms / 1000) / 60)} minutes.`,
`${pthatbanned.user.name} banned ${
user.user.name
} from the channel for ${Math.floor(
Math.floor(ms / 1000) / 60
)} minutes.`,
"",
7000,
"#room",
"short"
)
if (this.crown && (this.crown.userId == _id)) {
this.Notification("room",
);
if (this.crown && this.crown.userId == _id) {
this.Notification(
"room",
"Certificate of Award",
`Let it be known that ${user.user.name} kickbanned him/her self.`,
"",
@ -645,23 +761,22 @@ class Channel extends EventEmitter {
"#room"
);
}
//}
})
//}
});
}
unban(_id) {
let ban = this.bans.get(_id);
if (!ban) return;
if (ban.bantime) {
delete ban.bantime;
}
if (!ban) return;
if (ban.bantime) {
delete ban.bantime;
}
if (ban.bannedtime) {
delete ban.bannedtime;
}
if (ban.bannedtime) {
delete ban.bannedtime;
}
this.bans.delete(ban.user._id);
this.bans.delete(ban.user._id);
}
Notification(who, title, text, html, duration, target, klass, id) {
@ -700,7 +815,7 @@ class Channel extends EventEmitter {
this.on("remove crown", () => {
this.crown = undefined;
delete this.crown;
this.emit('update');
this.emit("update");
});
this.on("flag spin", spin => {
@ -725,17 +840,18 @@ class Channel extends EventEmitter {
}
verifySet(_id, msg) {
if(typeof(msg.set) !== 'object') {
if (typeof msg.set !== "object") {
msg.set = {
visible: true,
color: this.server.defaultSettings.color, chat:true,
crownsolo:false
}
color: this.server.defaultSettings.color,
chat: true,
crownsolo: false
};
}
msg.set = RoomSettings.changeSettings(msg.set);
if (typeof(msg.set.lobby) !== 'undefined') {
if (typeof msg.set.lobby !== "undefined") {
if (msg.set.lobby == true) {
if (!this.isLobby(_id)) delete msg.set.lobby; // keep it nice and clean
} else {
@ -757,7 +873,7 @@ class Channel extends EventEmitter {
async startAmongUs() {
if (!this.amongus) {
this.amongus = {}
this.amongus = {};
}
if (this.amongus.started) return;
@ -766,7 +882,10 @@ class Channel extends EventEmitter {
this.amongus.started = true;
}
let imposter = this.connections[Math.floor(Math.random() * this.connections.length)];
let imposter =
this.connections[
Math.floor(Math.random() * this.connections.length)
];
imposter.user.setFlag("freeze_name", true);
}

View File

@ -1,10 +1,10 @@
const Channel = require("./Channel.js");
const Quota = require ("./Quota.js");
const quotas = require('../Quotas');
const { RateLimit, RateLimitChain } = require('./Ratelimit.js');
const Quota = require("./Quota.js");
const quotas = require("../Quotas");
const { RateLimit, RateLimitChain } = require("./Ratelimit.js");
const User = require("./User.js");
const Database = require("./Database.js");
const { EventEmitter } = require('events');
const { EventEmitter } = require("events");
class Client extends EventEmitter {
/**
@ -30,14 +30,14 @@ class Client extends EventEmitter {
this.quotas = {};
this.ws = ws;
this.req = req;
this.ip = (req.connection.remoteAddress).replace("::ffff:", "");
this.ip = req.connection.remoteAddress.replace("::ffff:", "");
this.hidden = false;
Database.getUserData(this, server).then(data => {
this.user = new User(this, data);
this.destroied = false;
this.bindEventListeners();
require('./Message.js')(this);
require("./Message.js")(this);
});
}
@ -65,19 +65,29 @@ class Client extends EventEmitter {
*/
setChannel(_id, settings) {
if (this.channel && this.channel._id == _id) return;
if (this.server.rooms.get(_id)) {
let room = this.server.rooms.get(_id, settings);
let userbanned = room.bans.get(this.user._id);
if (this.server.channels.get(_id)) {
let ch = this.server.channels.get(_id, settings);
let userbanned = ch.bans.get(this.user._id);
if (userbanned && (Date.now() - userbanned.bannedtime >= userbanned.msbanned)) {
room.bans.delete(userbanned.user._id);
if (
userbanned &&
Date.now() - userbanned.bannedtime >= userbanned.msbanned
) {
ch.bans.delete(userbanned.user._id);
userbanned = undefined;
}
if (userbanned) {
room.Notification(this.user._id,
ch.Notification(
this.user._id,
"Notice",
`Currently banned from \"${_id}\" for ${Math.ceil(Math.floor((userbanned.msbanned - (Date.now() - userbanned.bannedtime)) / 1000) / 60)} minutes.`,
`Currently banned from \"${_id}\" for ${Math.ceil(
Math.floor(
(userbanned.msbanned -
(Date.now() - userbanned.bannedtime)) /
1000
) / 60
)} minutes.`,
7000,
"",
"#room",
@ -91,13 +101,13 @@ class Client extends EventEmitter {
if (channel) this.channel.emit("bye", this);
if (channel) this.channel.updateCh(this);
this.channel = this.server.rooms.get(_id);
this.channel = this.server.channels.get(_id);
this.channel.join(this);
} else {
let room = new Channel(this.server, _id, settings, this);
this.server.rooms.set(_id, room);
this.server.channels.set(_id, room);
if (this.channel) this.channel.emit("bye", this);
this.channel = this.server.rooms.get(_id);
this.channel = this.server.channels.get(_id);
this.channel.join(this, settings);
}
}
@ -121,17 +131,20 @@ class Client extends EventEmitter {
*/
userset(name, admin) {
if (name.length > 40 && !admin) return;
if (this.quotas.userset) {
if (!this.quotas.userset.attempt()) return;
}
if (!this.user.hasFlag('freeze_name', true) || admin) {
if (!this.user.hasFlag("freeze_name", true) || admin) {
this.user.name = name;
if (!this.user.hasFlag('freeze_name', true)) {
Database.getUserData(this, this.server).then((usr) => {
if (!this.user.hasFlag("freeze_name", true)) {
Database.getUserData(this, this.server).then(usr => {
Database.updateUser(this.user._id, this.user);
this.server.rooms.forEach((room) => {
room.updateParticipant(this.user._id, {
this.server.channels.forEach(channel => {
channel.updateParticipant(this.user._id, {
name: name
});
});
@ -147,27 +160,47 @@ class Client extends EventEmitter {
this.quotas = {
//"chat": new Quota(Quota.PARAMS_A_NORMAL),
chat: {
lobby: new RateLimitChain(quotas.chat.lobby.amount, quotas.chat.lobby.time),
normal: new RateLimitChain(quotas.chat.normal.amount, quotas.chat.normal.time),
insane: new RateLimitChain(quotas.chat.insane.amount, quotas.chat.insane.time)
lobby: new RateLimitChain(
quotas.chat.lobby.amount,
quotas.chat.lobby.time
),
normal: new RateLimitChain(
quotas.chat.normal.amount,
quotas.chat.normal.time
),
insane: new RateLimitChain(
quotas.chat.insane.amount,
quotas.chat.insane.time
)
},
cursor: new RateLimitChain(quotas.cursor.amount, quotas.cursor.time),
cursor: new RateLimitChain(
quotas.cursor.amount,
quotas.cursor.time
),
chown: new RateLimitChain(quotas.chown.amount, quotas.chown.time),
userset: new RateLimitChain(quotas.userset.amount, quotas.userset.time),
kickban: new RateLimitChain(quotas.kickban.amount, quotas.kickban.time),
userset: new RateLimitChain(
quotas.userset.amount,
quotas.userset.time
),
kickban: new RateLimitChain(
quotas.kickban.amount,
quotas.kickban.time
),
// note: new Quota(Quota.PARAMS_LOBBY),
note: new RateLimitChain(5, 5000),
chset: new Quota(Quota.PARAMS_USED_A_LOT),
"+ls": new Quota(Quota.PARAMS_USED_A_LOT),
"-ls": new Quota(Quota.PARAMS_USED_A_LOT)
}
};
}
/**
* Stop the client
*/
destroy() {
this.user.stopFlagEvents();
if (this.user) {
this.user.stopFlagEvents();
}
this.ws.close();
if (this.channel) {
this.channel.emit("bye", this);
@ -187,17 +220,18 @@ class Client extends EventEmitter {
bindEventListeners() {
this.ws.on("message", (evt, admin) => {
try {
if (typeof(evt) !== 'string') evt = evt.toJSON();
if (typeof evt !== "string") evt = evt.toJSON();
let transmission = JSON.parse(evt);
for (let msg of transmission) {
if (typeof(msg) !== 'object' || msg == null || msg == NaN) return;
if (typeof msg !== "object" || msg == null || msg == NaN)
return;
if (!msg.hasOwnProperty("m")) return;
if (!this.server.legit_m.includes(msg.m)) return;
this.emit(msg.m, msg, !!admin);
//console.log(`RECIEVE: `, JSON.colorStringify(msg));
}
} catch (e) {
console.log(e)
console.log(e);
// this.destroy();
}
});
@ -206,7 +240,7 @@ class Client extends EventEmitter {
this.destroy();
}
});
this.ws.addEventListener("error", (err) => {
this.ws.addEventListener("error", err => {
console.error(err);
if (!this.destroied) {
this.destroy();
@ -222,7 +256,7 @@ class Client extends EventEmitter {
data.m = "data";
let channels = [];
this.server.rooms.forEach(ch => {
this.server.channels.forEach(ch => {
let ppl = [];
for (let p of ch.fetchChannelData().ppl) {
ppl.push({
@ -236,7 +270,7 @@ class Client extends EventEmitter {
let users = [];
this.server.connections.forEach(cl => {
if (!cl.user) return;
if (!cl.user) return;
let u = {
p: {
_id: cl.user._id,
@ -245,30 +279,30 @@ class Client extends EventEmitter {
flags: cl.user.flags,
inventory: cl.user.inventory
},
id: cl.participantId,
}
id: cl.participantId
};
users.push(u);
});
data.channelManager = {
loggingChannel: Channel.loggingChannel,
loggerParticipant: Channel.loggerParticipant,
loggingChannel: Channel.loggingChannel,
loggerParticipant: Channel.loggerParticipant,
channels
};
data.clientManager = {
users
}
};
data.uptime = Date.now() - this.server.startTime;
data.uptime = Date.now() - this.server.startTime;
this.sendArray([data]);
}
/**
*
* @param {Channel} ch
*
* @param {Channel} ch
* @param {Client} cl If this is present, only this client's user data will be sent(?)
*/
sendChannelUpdate(ch, cl) {

View File

@ -1,17 +1,16 @@
const Color = require("./Color");
function hashCode(str) { // java String#hashCode
function hashCode(str) {
// java String#hashCode
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
}
function intToRGB(i){
var c = (i & 0x00FFFFFF)
.toString(16)
.toUpperCase();
function intToRGB(i) {
var c = (i & 0x00ffffff).toString(16).toUpperCase();
return "00000".substring(0, 6 - c.length) + c;
}
@ -27,26 +26,26 @@ function intToRGB(i){
* @param {number} l The lightness
* @return {Array} The RGB representation
*/
function hslToRgb(h, s, l){
function hslToRgb(h, s, l) {
var r, g, b;
if(s == 0){
if (s == 0) {
r = g = b = l; // achromatic
}else{
var hue2rgb = function hue2rgb(p, q, t){
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
} else {
var hue2rgb = function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
};
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
b = hue2rgb(p, q, h - 1 / 3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
@ -55,7 +54,12 @@ function intToRGB(i){
function getTimeColor(currentDate = new Date()) {
// get day of year as a number from 1-365
let newYearsDay = new Date(currentDate.getFullYear());
let differenceInTime = (currentDate - newYearsDay) + ((newYearsDay.getTimezoneOffset() - currentDate.getTimezoneOffset()) * 60 * 1000);
let differenceInTime =
currentDate -
newYearsDay +
(newYearsDay.getTimezoneOffset() - currentDate.getTimezoneOffset()) *
60 *
1000;
let oneDayInMS = 1000 * 60 * 60 * 24;
let dayOfYear = Math.ceil(differenceInTime / oneDayInMS);
dayOfYear %= 365;
@ -67,13 +71,17 @@ function getTimeColor(currentDate = new Date()) {
let seconds = currentDate.getSeconds();
// get a hue based on time of day and day of year
let h = Math.floor((dayOfYear / 365) * 100) / 10000;
let h = dayOfYear / 365;
let s = (hours + 1) / (24 / 3);
// let s = 1;
let l = 0.25 + Math.floor(((hours / 60)) * 1000) / 1000;
if (l > 0.5) l = 0.5;
if (s > 1) s = 1;
let l = 0.15 + Math.floor(((hours + 12) / 60) * 1000) / 1000;
if (l > 1 / 3) l = 1 / 3;
if (s > 0.75) s = 0.75;
// const h = (Date.now() % 360) / 360;
// const s = 1;
// const l = 0.5;
// convert to rgb
let [r, g, b] = hslToRgb(h, s, l);
@ -87,4 +95,4 @@ module.exports = {
intToRGB,
getTimeColor,
hslToRgb
}
};

View File

@ -1,10 +1,10 @@
const ung = require('unique-names-generator');
const ung = require("unique-names-generator");
const ung_config = {
dictionaries: [ung.adjectives, ung.colors],
separator: ' ',
length: 2
}
dictionaries: [ung.names],
separator: " ",
length: 1
};
class Cow {
static generateRandomName() {
@ -12,12 +12,18 @@ class Cow {
}
constructor() {
this['display_name'] = Cow.generateRandomName();
this['emoji'] = '🐄'
this['count'] = 1;
this["display_name"] = Cow.generateRandomName();
this["emoji"] = "🐄";
this["count"] = 1;
}
toString() {
return `${this.emoji}${this.display_name}${
this.count > 1 ? `(x${this.count})` : ""
}`;
}
}
module.exports = {
Cow
}
};

View File

@ -1,27 +1,34 @@
const fs = require('fs');
const { promisify } = require('util');
const createKeccakHash = require('keccak');
const ColorEncoder = require('./ColorEncoder');
const UserModel = require('./UserModel');
const mongoose = require('mongoose');
const level = require('level');
const { users } = require('./UserModel');
const { inventories } = require('./InventoryModel');
const Logger = require('./Logger');
const fs = require("fs");
const { promisify } = require("util");
const createKeccakHash = require("keccak");
const ColorEncoder = require("./ColorEncoder");
const UserModel = require("./UserModel");
const mongoose = require("mongoose");
const level = require("level");
const { db } = require("./UserModel");
const Logger = require("./Logger");
var logger = new Logger("Database");
mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
connectTimeoutMS: 1000
}, err => {
if (err) {
console.error(err);
logger.error("Unable to connect to database service");
process.exit(1);
mongoose.connect(
process.env.MONGO_URL,
{
useNewUrlParser: true,
useUnifiedTopology: true,
connectTimeoutMS: 1000
},
err => {
if (err) {
console.error(err);
logger.error("Unable to connect to database service");
process.exit(1);
}
logger.log("Connected");
}
logger.log("Connected");
);
fs.mkdirSync("db/", {
recursive: true
});
class Database {
@ -30,7 +37,7 @@ class Database {
static async load() {
this.userdb = mongoose.connection;
this.roomdb = level('db/rooms.db');
this.roomdb = level("db/rooms.db");
// const writeFile = promisify(fs.writeFile);
// const readdir = promisify(fs.readdir);
@ -47,12 +54,18 @@ class Database {
if (!this.userdb) {
await this.load();
}
let _id = createKeccakHash('keccak256').update((cl.server._id_Private_Key + cl.ip)).digest('hex').substr(0, 24);
let user = await UserModel.findOne({ _id: _id }).exec();
let _id = createKeccakHash("keccak256")
.update(cl.server._id_Private_Key + cl.ip)
.digest("hex")
.substr(0, 24);
let user = await UserModel.findById(_id).exec();
console.log("_id:", _id);
console.log("user:", user);
if (user == null) {
user = this.createUser(_id);
user = await this.createUser(_id);
}
return user;
@ -67,10 +80,9 @@ class Database {
name: "Anonymous",
_id: _id,
color: "#" + ColorEncoder.intToRGB(ColorEncoder.hashCode(_id)),
flags: {
}
flags: {}
});
user.save();
return user;
}
@ -80,8 +92,8 @@ class Database {
await this.load();
}
let user = await UserModel.findOne({_id: _id}).exec();
let user = await UserModel.findOne({ _id: _id }).exec();
user.name = data.name;
user._id = data._id;
user.flags = data.flags;
@ -94,7 +106,7 @@ class Database {
if (!this.userdb) {
await this.load();
}
await UserModel.find({}, (err, docs) => {
docs.forEach(doc => {
doc.remove();
@ -103,14 +115,17 @@ class Database {
}
static strMapToObj(strMap) {
return [...strMap.entries()].reduce((obj, [key, value]) => (obj[key] = value, obj), {});
return [...strMap.entries()].reduce(
(obj, [key, value]) => ((obj[key] = value), obj),
{}
);
}
static getRoomSettings(_id, cb) {
let key = "room~"+_id;
roomSettings
let key = "room~" + _id;
roomSettings;
this.roomdb.get(key, (err, value) => {
if (err || !value || value == "") {
cb(err, value);
@ -122,12 +137,12 @@ class Database {
static setRoomSettings(_id, roomSettings, chat) {
let roomData = new RoomDataModel(roomSettings, chat);
let key = "room~"+_id;
let key = "room~" + _id;
this.roomdb.put(key, JSON.stringify(roomData));
}
static getRoomSettings(_id, cb) {
let key = "room~"+_id;
let key = "room~" + _id;
this.roomdb.get(key, (err, value) => {
if (err) {
cb(err);
@ -139,12 +154,12 @@ class Database {
}
static deleteRoomSettings(_id) {
this.roomdb.del("room~"+_id);
this.roomdb.del("room~" + _id);
}
}
class RoomDataModel {
constructor (settings, chat) {
constructor(settings, chat) {
this.settings = settings;
this.chat = chat;
}

View File

@ -1,99 +1,195 @@
const Logger = require("../Logger");
const Color = require('../Color');
const Color = require("../Color");
const { Cow } = require("../Cow");
class Command {
static commands = [];
static commands = [];
static logger = new Logger("Command Handler");
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;
}
}
static handleCommand(cl, ch, c, usedPrefix, args, argcat, p, isAdmin) {
for (let cmd of this.commands) {
let aliasCheck = false;
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)}`);
aliasLoop: for (let alias of cmd.aliases) {
if (c.toLowerCase() == alias.toLowerCase()) {
aliasCheck = true;
break aliasLoop;
}
}
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.`);
}
}
}
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
)}`
);
static addCommand(cmd) {
this.commands.push(cmd);
}
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 getUsage(usa, pre) {
return usa.split('%P').join(pre);
}
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.aliases = aliases || [id];
this.desc = desc || 'no description'; // brandon-like words
this.usage = usage || 'no usage';
this.minargs = minargs;
this.desc = desc || "no description"; // brandon-like words
this.usage = usage || "no usage";
this.minargs = minargs;
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(
"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'));
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"
)
);
Command.addCommand(
new Command(
"chlist",
["chlist"],
undefined,
`%Pchlist`,
0,
(cl, ch, msg) => {
if (!msg.isAdmin) {
ch.adminChat("You do not have permission to use this command.");
return;
}
ch.adminChat("Channels:");
for (const cc of cl.server.channels.values()) {
ch.adminChat(`- ${cc._id}\n`);
}
},
"admin"
)
);
Command.addCommand(
new Command(
"cow",
["cow"],
undefined,
`%Pcow`,
0,
(cl, ch, msg) => {
const cow = new Cow();
return `Cow: ${cow.emoji}${cow.display_name}`;
},
"user"
)
);
module.exports = {
Command
}
};

View File

@ -1,6 +1,6 @@
const { EventEmitter } = require('events');
const { Command } = require('./Command');
const Color = require('../Color');
const { EventEmitter } = require("events");
const { Command } = require("./Command");
const Color = require("../Color");
class InternalBot {
static on = EventEmitter.prototype.on;
@ -8,14 +8,14 @@ class InternalBot {
static emit = EventEmitter.prototype.emit;
static once = EventEmitter.prototype.once;
static prefix = '!';
static commands = [];
static prefix = "!";
static commands = [];
static bindEventListeners() {
if (this.alreadyBound) return;
this.alreadyBound = true;
this.on('receive message', (msg, cl, ch) => {
this.on("receive message", (msg, cl, ch) => {
/**
* msg.a - chat message
* msg.p - participant
@ -23,19 +23,28 @@ class InternalBot {
*/
let isAdmin = false;
if (cl.user.hasFlag('admin')) {
if (cl.user.hasFlag("admin")) {
isAdmin = true;
}
let args = msg.a.split(' ');
let args = msg.a.split(" ");
let cmd = args[0].toLowerCase().substring(this.prefix.length);
let argcat = msg.a.substring(args[0].length).trim();
let p = cl;
if (!args[0].startsWith(this.prefix)) return;
let prefix = this.prefix;
Command.handleCommand(cl, ch, cmd, prefix, args, argcat, p, isAdmin);
let prefix = this.prefix;
Command.handleCommand(
cl,
ch,
cmd,
prefix,
args,
argcat,
p,
isAdmin
);
// switch (cmd) {
// case "ping":
// ch.adminChat('pong');
@ -89,7 +98,7 @@ class InternalBot {
// case "channellist":
// if (!isAdmin) return;
// ch.adminChat("Channels:");
// for (let [_id] of ch.server.rooms) {
// for (let [_id] of ch.server.channels) {
// ch.adminChat(`- ${_id}`);
// }
// break;
@ -103,14 +112,14 @@ class InternalBot {
// if (!isAdmin) return;
// cl.server.ev(argcat);
// 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;
// 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;
// }
});
}
@ -120,4 +129,4 @@ InternalBot.bindEventListeners();
module.exports = {
InternalBot
}
};

View File

@ -1,24 +1,27 @@
const Holidays = require('date-holidays');
const Holidays = require("date-holidays");
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'
]
"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 {
static getDay() {
let now = new Date();
let start = new Date(now.getFullYear(), 0, 0);
let diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
let diff =
now -
start +
(start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000;
let oneDay = 1000 * 60 * 60 * 24;
let day = Math.floor(diff / oneDay);
return day;
@ -31,12 +34,24 @@ class MOTDGenerator {
return `Happy ${h[0].name}!`;
} else {
// no holiday, get day
let day = new Date().getDay();
return dayOfTheWeekMOTD[day];
// let day = new Date().getDay();
let newYearsDay = new Date(new Date().getFullYear());
let differenceInTime =
new Date() -
newYearsDay +
(newYearsDay.getTimezoneOffset() -
new Date().getTimezoneOffset()) *
60 *
1000;
let oneDayInMS = 1000 * 60 * 60 * 24;
let dayOfYear = Math.ceil(differenceInTime / oneDayInMS);
dayOfYear %= 365;
return dayOfTheWeekMOTD[dayOfYear % dayOfTheWeekMOTD.length];
}
}
}
module.exports = {
MOTDGenerator
}
};

View File

@ -1,18 +1,20 @@
const Quota = require('./Quota');
const Quota = require("./Quota");
const User = require("./User.js");
const Channel = require("./Channel.js");
const RoomSettings = require('./RoomSettings');
const Database = require('./Database');
const { MOTDGenerator } = require('./MOTDGenerator');
const RoomSettings = require("./RoomSettings");
const Database = require("./Database");
const { MOTDGenerator } = require("./MOTDGenerator");
module.exports = (cl) => {
module.exports = cl => {
cl.once("hi", (msg, admin) => {
if (msg.hasOwnProperty("password")) {
if (msg.password == "hideme") {
cl.hidden = true;
}
}
console.log("hi");
let m = {};
m.m = "hi";
m.motd = MOTDGenerator.getCurrentMOTD();
@ -30,17 +32,19 @@ module.exports = (cl) => {
cl.on("t", msg => {
if (msg.hasOwnProperty("e") && !isNaN(msg.e))
cl.sendArray([{
m: "t",
t: Date.now(),
e: msg.e
}])
cl.sendArray([
{
m: "t",
t: Date.now(),
e: msg.e
}
]);
});
cl.on("ch", msg => {
if (typeof(msg.set) !== 'object') msg.set = {};
if (typeof msg.set !== "object") msg.set = {};
if (typeof(msg._id) == "string") {
if (typeof msg._id == "string") {
if (msg._id.length > 512) return;
if (!cl.staticQuotas.room.attempt()) return;
@ -58,7 +62,7 @@ module.exports = (cl) => {
param = Quota.N_PARAMS_RIDICULOUS;
}
}
param.m = "nq";
setTimeout(() => {
cl.sendArray([param]);
@ -68,7 +72,7 @@ module.exports = (cl) => {
cl.on("m", (msg, admin) => {
// nobody will see our cursor if we're not somewhere
if (!('channel' in cl)) return;
if (!("channel" in cl)) return;
// check against cursor rate limit
if (!cl.quotas.cursor.attempt() && !admin) return;
@ -86,7 +90,7 @@ module.exports = (cl) => {
p: cl.participantId,
x: msg.x,
y: msg.y
}
};
cl.channel.emit("m", m);
});
@ -99,16 +103,23 @@ module.exports = (cl) => {
//console.log(!(cl.channel.crown.userId != cl.user._id), !((Date.now() - cl.channel.crown.time) > 15000));
if (!cl.channel.crown && !admin) {
if (!(cl.channel.crown.userId == cl.user._id) && !((Date.now() - cl.channel.crown.time) > 15000)) return;
if (
!(cl.channel.crown.userId == cl.user._id) &&
!(Date.now() - cl.channel.crown.time > 15000)
)
return;
}
if (msg.hasOwnProperty("id")) {
// console.log(cl.channel.crown)
if (!admin) {
if (cl.user._id == cl.channel.crown.userId || cl.channel.crowndropped) {
if (
cl.user._id == cl.channel.crown.userId ||
cl.channel.crowndropped
) {
cl.channel.chown(msg.id);
if (msg.id == cl.user.id) {
param = Quota.N_PARAMS_RIDICULOUS;
param = Quota.N_PARAMS_RIDICULOUS;
param.m = "nq";
cl.sendArray([param]);
}
@ -116,22 +127,25 @@ module.exports = (cl) => {
} else {
cl.channel.chown(msg.id);
if (msg.id == cl.user.id) {
param = Quota.N_PARAMS_RIDICULOUS;
param = Quota.N_PARAMS_RIDICULOUS;
param.m = "nq";
cl.sendArray([param]);
}
}
} else {
if (!admin) {
if (cl.user._id == cl.channel.crown.userId || cl.channel.crowndropped) {
if (
cl.user._id == cl.channel.crown.userId ||
cl.channel.crowndropped
) {
cl.channel.chown();
param = Quota.N_PARAMS_NORMAL;
param = Quota.N_PARAMS_NORMAL;
param.m = "nq";
cl.sendArray([param]);
}
} else {
cl.channel.chown();
param = Quota.N_PARAMS_RIDICULOUS;
param = Quota.N_PARAMS_RIDICULOUS;
param.m = "nq";
cl.sendArray([param]);
}
@ -144,71 +158,93 @@ module.exports = (cl) => {
if (!admin) {
if (!(cl.user._id == cl.channel.crown.userId)) return;
}
if (!msg.hasOwnProperty("set") || !msg.set) msg.set = new RoomSettings(cl.channel.settings, 'user');
if (!msg.hasOwnProperty("set") || !msg.set)
msg.set = new RoomSettings(cl.channel.settings, "user");
cl.channel.settings.changeSettings(msg.set, admin);
// cl.channel.updateCh();
cl.channel.emit('update');
cl.channel.emit("update");
});
cl.on('a', (msg, admin) => {
cl.on("a", (msg, admin) => {
if (!(cl.channel && cl.participantId)) return;
if (!msg.hasOwnProperty('message')) return;
if (typeof(msg.message) !== 'string') return;
if (cl.user.flags["cant_chat"]) return;
if (!msg.hasOwnProperty("message")) return;
if (typeof msg.message !== "string") return;
if (cl.channel.settings.chat) {
if (admin && msg.admin == true) {
cl.channel.adminChat(msg.message);
} else {
if (cl.channel.isLobby(cl.channel._id)) {
if (!cl.quotas.chat.lobby.attempt() && !admin && !cl.user.hasFlag('no chat rate limit', true)) return;
} else {
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 {
if (!cl.quotas.chat.insane.attempt() && !admin && !cl.user.hasFlag('no chat rate limit', true)) return;
}
}
cl.channel.emit('a', cl, msg);
}
if (admin && msg.admin == true) {
cl.channel.adminChat(msg.message);
} else {
if (cl.channel.isLobby(cl.channel._id)) {
if (
!cl.quotas.chat.lobby.attempt() &&
!admin &&
!cl.user.hasFlag("no chat rate limit", true)
)
return;
} else {
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 {
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, admin) => {
cl.on("n", (msg, admin) => {
if (!(cl.channel && cl.participantId)) return;
if (!msg.hasOwnProperty('t') || !msg.hasOwnProperty('n')) return;
if (typeof msg.t != 'number' || typeof msg.n != 'object') return;
if (!msg.hasOwnProperty("t") || !msg.hasOwnProperty("n")) return;
if (typeof msg.t != "number" || typeof msg.n != "object") return;
// if (cl.quotas.note && !admin) {
// if (!cl.quotas.note.attempt()) return;
// }
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);
}
// if (cl.quotas.note && !admin) {
// if (!cl.quotas.note.attempt()) return;
// }
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 => {
if (!(cl.channel && cl.participantId)) return;
cl.server.roomlisteners.set(cl.connectionid, cl);
let rooms = [];
for (let room of Array.from(cl.server.rooms.values())) {
for (let room of Array.from(cl.server.channels.values())) {
let data = room.fetchChannelData().ch;
if (room.bans.get(cl.user._id)) {
data.banned = true;
}
if (room.settings.visible) rooms.push(data);
}
cl.sendArray([{
"m": "ls",
"c": true,
"u": rooms
}])
cl.sendArray([
{
m: "ls",
c: true,
u: rooms
}
]);
});
cl.on('-ls', msg => {
cl.on("-ls", msg => {
if (!(cl.channel && cl.participantId)) return;
cl.server.roomlisteners.delete(cl.connectionid);
});
@ -216,19 +252,19 @@ module.exports = (cl) => {
cl.on("userset", (msg, admin) => {
if (!(cl.channel && cl.participantId)) return;
if (!msg.hasOwnProperty("set") || !msg.set) msg.set = {};
if (msg.set.hasOwnProperty('name') && typeof msg.set.name == "string") {
if (msg.set.hasOwnProperty("name") && typeof msg.set.name == "string") {
cl.userset(msg.set.name, admin);
}
});
cl.on('kickban', (msg, admin) => {
cl.on("kickban", (msg, admin) => {
if (!admin) {
if (cl.channel.crown == null) return;
if (!(cl.channel && cl.participantId)) return;
if (!cl.channel.crown.userId) return;
if (!(cl.user._id == cl.channel.crown.userId)) return;
}
if (msg.hasOwnProperty('_id') && typeof msg._id == "string") {
if (msg.hasOwnProperty("_id") && typeof msg._id == "string") {
if (!cl.quotas.kickban.attempt() && !admin) return;
let _id = msg._id;
let ms = msg.ms || 36e5;
@ -236,14 +272,14 @@ module.exports = (cl) => {
}
});
cl.on('unban', (msg, admin) => {
cl.on("unban", (msg, admin) => {
if (!admin) {
if (cl.channel.crown == null) return;
if (!(cl.channel && cl.participantId)) return;
if (!cl.channel.crown.userId) return;
if (!(cl.user._id == cl.channel.crown.userId)) return;
}
if (msg.hasOwnProperty('_id') && typeof msg._id == "string") {
if (msg.hasOwnProperty("_id") && typeof msg._id == "string") {
if (!cl.quotas.kickban.attempt() && !admin) return;
let _id = msg._id;
cl.channel.unban(_id);
@ -257,19 +293,20 @@ module.exports = (cl) => {
cl.on("admin message", msg => {
// if (!(cl.channel && cl.participantId)) return;
if (!msg.hasOwnProperty('password') || !msg.hasOwnProperty('msg')) return;
if (typeof msg.msg != 'object') return;
if (!msg.hasOwnProperty("password") || !msg.hasOwnProperty("msg"))
return;
if (typeof msg.msg != "object") return;
if (msg.password !== cl.server.adminpass) return;
cl.ws.emit("message", JSON.stringify([msg.msg]), true);
});
//admin only stuff
// TODO move all admin messages to their own stream
cl.on('color', (msg, admin) => {
cl.on("color", (msg, admin) => {
if (!admin) return;
if (!msg.color) return;
// if (typeof cl.channel.verifyColor(msg.color) != 'string') return;
if (!msg.hasOwnProperty('id') && !msg.hasOwnProperty('_id')) return;
if (!msg.hasOwnProperty("id") && !msg.hasOwnProperty("_id")) return;
cl.server.connections.forEach(c => {
if (c.destroied) return;
if (c.user._id !== msg._id && c.participantId !== msg.id) return;
@ -280,16 +317,22 @@ module.exports = (cl) => {
});
});
cl.on('eval', (msg, admin) => {
cl.on("eval", (msg, admin) => {
if (!admin) return;
if (!msg.hasOwnProperty('str')) return;
if (!msg.hasOwnProperty("str")) return;
cl.server.ev(msg.str);
});
cl.on('notification', (msg, admin) => {
cl.on("notification", (msg, admin) => {
if (!admin) return;
if (!msg.hasOwnProperty("id") || (!msg.hasOwnProperty("targetChannel") && !msg.hasOwnProperty("targetUser"))
|| !msg.hasOwnProperty("target") || !msg.hasOwnProperty("duration")) return;
if (
!msg.hasOwnProperty("id") ||
(!msg.hasOwnProperty("targetChannel") &&
!msg.hasOwnProperty("targetUser")) ||
!msg.hasOwnProperty("target") ||
!msg.hasOwnProperty("duration")
)
return;
let id = msg.id;
let targetChannel = msg.targetChannel;
@ -306,23 +349,43 @@ module.exports = (cl) => {
}
if (!msg.hasOwnProperty("html")) {
if (!msg.hasOwnProperty("title") || !msg.hasOwnProperty("text")) return;
if (!msg.hasOwnProperty("title") || !msg.hasOwnProperty("text"))
return;
title = msg.title;
text = msg.text;
} else {
html = msg.html;
}
cl.channel.Notification(targetUser || targetChannel, title, text, html, duration, target, klass, id);
cl.channel.Notification(
targetUser || targetChannel,
title,
text,
html,
duration,
target,
klass,
id
);
});
cl.on('user_flag', (msg, admin) => {
cl.on("user_flag", (msg, admin) => {
if (!admin) return;
if (!msg.hasOwnProperty('_id') || !msg.hasOwnProperty('key') || !msg.hasOwnProperty('value')) return;
if (
!msg.hasOwnProperty("_id") ||
!msg.hasOwnProperty("key") ||
!msg.hasOwnProperty("value")
)
return;
cl.server.connections.forEach((usr) => {
if ((usr.channel && usr.participantId && usr.user) && (usr.user._id == msg._id || (usr.participantId == msg.id))) {
if (!usr.hasOwnProperty('user')) return;
cl.server.connections.forEach(usr => {
if (
usr.channel &&
usr.participantId &&
usr.user &&
(usr.user._id == msg._id || usr.participantId == msg.id)
) {
if (!usr.hasOwnProperty("user")) return;
if (msg.key == "remove") {
delete usr.user.flags[msg.key];
usr.user.flags[msg.key] = undefined;
@ -335,33 +398,38 @@ module.exports = (cl) => {
});
});
cl.on('channel_flag', (msg, admin) => {
cl.on("channel_flag", (msg, admin) => {
if (!admin) return;
if (!msg.hasOwnProperty('_id') || !msg.hasOwnProperty('key') || !msg.hasOwnProperty('value')) return;
if (
!msg.hasOwnProperty("_id") ||
!msg.hasOwnProperty("key") ||
!msg.hasOwnProperty("value")
)
return;
try {
let ch = cl.server.rooms.get(msg._id);
let ch = cl.server.channels.get(msg._id);
ch.flags[msg.key] = msg.value;
ch.emit('flag ' + msg.key, msg.value);
} catch(err) {
ch.emit("flag " + msg.key, msg.value);
} catch (err) {
console.error(err);
}
});
cl.on('room_flag', (msg, admin) => {
cl.on("room_flag", (msg, admin) => {
if (!admin) return;
cl.emit('channel_flag', msg, admin);
})
cl.emit("channel_flag", msg, admin);
});
cl.on('clear_chat', (msg, admin) => {
cl.on("clear_chat", (msg, admin) => {
if (!admin) return;
cl.channel.setChatArray([]);
});
cl.on('sudo', (msg, admin) => {
cl.on("sudo", (msg, admin) => {
if (!admin) return;
if (typeof msg._id !== 'string') return;
if (typeof msg.msg !== 'object') return;
if (typeof msg._id !== "string") return;
if (typeof msg.msg !== "object") return;
if (!msg.msg.m) return;
cl.server.connections.forEach(c => {
if (c.user._id !== msg._id) return;
@ -369,22 +437,22 @@ module.exports = (cl) => {
});
});
cl.on('subscribe to admin stream', (msg, admin) => {
cl.on("subscribe to admin stream", (msg, admin) => {
// if (!admin) return;
if (!('password' in msg)) return;
if (!("password" in msg)) return;
if (msg.password !== cl.server.adminpass) return;
cl.isSubscribedToAdminStream = true;
let interval = 8000;
if ('interval_ms' in msg) interval = msg['interval_ms'];
if ("interval_ms" in msg) interval = msg["interval_ms"];
cl.sendAdminData();
cl.adminStreamInterval = setInterval(() => {
if (cl.isSubscribedToAdminStream == true) cl.sendAdminData();
}, interval);
});
cl.on('unsubscribe from admin stream', (msg, admin) => {
cl.on("unsubscribe from admin stream", (msg, admin) => {
// if (!admin) return;
if (!('password' in msg)) return;
if (!("password" in msg)) return;
if (msg.password !== cl.server.adminpass) return;
cl.isSubscribedToAdminStream = false;
if (cl.adminStreamInterval) {
@ -396,27 +464,27 @@ module.exports = (cl) => {
}
});
cl.on('channel message', (msg, admin) => {
cl.on("channel message", (msg, admin) => {
if (!admin) return;
if (!msg.hasOwnProperty('msg')) return;
if (typeof msg.msg != 'object') return;
if (typeof msg.msg.m != 'string') return;
if (!msg.hasOwnProperty("msg")) return;
if (typeof msg.msg != "object") return;
if (typeof msg.msg.m != "string") return;
if (!cl.channel) return;
if (!msg.hasOwnProperty('_id')) msg._id = cl.channel._id;
if (!msg.hasOwnProperty("_id")) msg._id = cl.channel._id;
let ch = cl.server.rooms.get(msg._id);
let ch = cl.server.channels.get(msg._id);
if (!ch) return;
ch.emit(msg.msg.m, msg.msg);
});
cl.on('name', (msg, admin) => {
cl.on("name", (msg, admin) => {
if (!admin) return;
if (!msg.hasOwnProperty('_id')) return;
if (!msg.hasOwnProperty('name')) return;
if (!msg.hasOwnProperty("_id")) return;
if (!msg.hasOwnProperty("name")) return;
for (const [mapID, conn] of cl.server.connections) {
if (!conn.user) return;
if (conn.user._id == msg._id) {
@ -426,8 +494,8 @@ module.exports = (cl) => {
}
});
cl.on('restart', (msg, admin) => {
cl.on("restart", (msg, admin) => {
if (!admin) return;
cl.server.restart(msg.notification);
});
}
};

View File

@ -1,5 +1,5 @@
module.exports = class Notification {
constructor (data) {
constructor(data) {
this.id = data.id;
this.chat = data.chat;
this.refresh = data.refresh;
@ -30,10 +30,16 @@ module.exports = class Notification {
}
break;
default:
Array.from(room.server.connections.values()).filter((usr) => typeof(usr.user) !== 'undefined' ? usr.user._id == _id : null).forEach((p) => {
p.sendArray([msg]);
});
Array.from(room.server.connections.values())
.filter(usr =>
typeof usr.user !== "undefined"
? usr.user._id == _id
: null
)
.forEach(p => {
p.sendArray([msg]);
});
break;
}
}
}
};

View File

@ -1,11 +1,11 @@
const Client = require("./Client.js");
const banned = require('../banned.json');
const banned = require("../banned.json");
const https = require("https");
const http = require("http");
const fs = require('fs');
const RoomSettings = require('./RoomSettings');
const fs = require("fs");
const RoomSettings = require("./RoomSettings");
const Logger = require("./Logger.js");
const Notification = require('./Notification');
const Notification = require("./Notification");
class Server {
static on = EventEmitter.prototype.on;
@ -13,38 +13,50 @@ class Server {
static emit = EventEmitter.prototype.emit;
static once = EventEmitter.prototype.once;
static startTime = Date.now();
static startTime = Date.now();
static start(config) {
// super();
// EventEmitter.call(this);
this.logger = new Logger("Server");
if (config.ssl == "true") {
this.https_server = https.createServer({
key: fs.readFileSync('ssl/privkey.pem', 'utf8'),
cert: fs.readFileSync('ssl/cert.pem'),
ca: fs.readFileSync('ssl/chain.pem')
key: fs.readFileSync("ssl/privkey.pem", "utf8"),
cert: fs.readFileSync("ssl/cert.pem"),
ca: fs.readFileSync("ssl/chain.pem")
});
this.wss = new WebSocket.Server({
server: this.https_server,
backlog: 100,
verifyClient: (info) => {
const ip = (info.req.connection.remoteAddress).replace("::ffff:", "");
verifyClient: info => {
const ip = info.req.connection.remoteAddress.replace(
"::ffff:",
""
);
if (
!ip.match(
/^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]|)\d)$/gi
)
)
return false;
if (banned.includes(ip)) return false;
return true;
}
});
this.https_server.listen(config.port);
this.https_server.listen(config.port, "0.0.0.0");
} else {
this.wss = new WebSocket.Server({
port: config.port,
backlog: 100,
verifyClient: (info) => {
const ip = (info.req.connection.remoteAddress).replace("::ffff:", "");
verifyClient: info => {
const ip = info.req.connection.remoteAddress.replace(
"::ffff:",
""
);
if (banned.includes(ip)) return false;
return true;
}
@ -63,12 +75,16 @@ class Server {
this.connectionid = 0;
this.connections = new Map();
this.roomlisteners = new Map();
this.rooms = new Map();
this.channels = new Map();
this.specialIntervals = {};
this.wss.on('connection', (ws, req) => {
this.connections.set(++this.connectionid, new Client(ws, req, this));
this.wss.on("connection", (ws, req) => {
console.log("socket connected");
this.connections.set(
++this.connectionid,
new Client(ws, req, this)
);
});
this.legit_m = [
@ -111,8 +127,13 @@ class Server {
this.adminpass = config.adminpass || "123123sucks";
}
static updateRoom(data) {
if (!data.ch.settings.visible) return;
static updateChannelList(channelDataArray) {
const listData = [];
for (let chm of Object.values(channelDataArray)) {
if (!chm.ch.settings.visible) return;
listData.push(chm.ch);
}
for (let cl of Array.from(this.roomlisteners.values())) {
if (cl.destroied) {
@ -120,19 +141,19 @@ class Server {
return;
}
let newch = {
banned: typeof this.rooms.get(data.ch._id).bans.get(cl.user._id) !== 'undefined'
};
for (const ch of Object.values(listData)) {
const c = this.channels.get(ch._id);
if (!c) continue;
ch.banned = typeof c.bans.get(cl.user._id) !== "undefined";
}
for (let key of Object.keys(data)) {
newch[key] = data.ch[key];
}
cl.sendArray([{
"m": "ls",
"c": false,
"u": [newch]
}]);
cl.sendArray([
{
m: "ls",
c: false,
u: listData
}
]);
}
}
@ -140,7 +161,7 @@ class Server {
let out = "";
try {
out = eval(str);
} catch(err) {
} catch (err) {
out = err;
}
console.log(out);
@ -165,17 +186,19 @@ class Server {
return out;
}
static restart(notif = {
m: "notification",
id: "server-restart",
title: "Notice",
text: "The server will restart in a few moments.",
target: "#piano",
duration: 20000,
class: "classic",
}) {
static restart(
notif = {
m: "notification",
id: "server-restart",
title: "Notice",
text: "The server will restart in a few moments.",
target: "#piano",
duration: 20000,
class: "classic"
}
) {
let n = new Notification(notif);
n.send("all", this.rooms.get('lobby'));
n.send("all", this.channels.get("lobby"));
setTimeout(() => {
process.exit();

View File

@ -1,13 +1,15 @@
const Database = require("./Database");
const { Cow } = require('./Cow');
const { Cow } = require("./Cow");
function hslToHex(h, s, l) {
l /= 100;
const a = s * Math.min(l, 1 - l) / 100;
const a = (s * Math.min(l, 1 - l)) / 100;
const f = n => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color).toString(16).padStart(2, '0');
return Math.round(255 * color)
.toString(16)
.padStart(2, "0");
};
return `#${f(0)}${f(8)}${f(4)}`;
}
@ -18,13 +20,16 @@ class User {
this.cl = cl;
this._id = data._id;
this.color = data.color;
this.flags = typeof data.flags == "object" ? data.flags : {
volume: 100,
"no chat rate limit": false,
freeze_name: false
}
this.inventory = {};
this.flags =
typeof data.flags == "object"
? data.flags
: {
volume: 100,
"no chat rate limit": false,
freeze_name: false
};
this.inventory = {};
}
getPublicUser() {
@ -36,11 +41,15 @@ class User {
}
checkFlags() {
if (typeof(this.cl.server.specialIntervals[this._id]) == 'undefined') {
if (typeof this.cl.server.specialIntervals[this._id] == "undefined") {
this.cl.server.specialIntervals[this._id] = {};
}
if (this.hasFlag('rainbow', true)) {
if (!this.cl.server.specialIntervals[this._id].hasOwnProperty('rainbow')) {
if (this.hasFlag("rainbow", true)) {
if (
!this.cl.server.specialIntervals[this._id].hasOwnProperty(
"rainbow"
)
) {
let h = Math.floor(Math.random() * 360);
let s = 50;
let l = 50;
@ -49,28 +58,36 @@ class User {
let svel = 1;
let lvel = 0.5;
this.cl.server.specialIntervals[this._id].rainbow = setInterval(() => {
hvel = Math.floor(Math.random()*10);
h += hvel;
if (h > 360) h = 0;
this.cl.server.specialIntervals[this._id].rainbow = setInterval(
() => {
hvel = Math.floor(Math.random() * 10);
h += hvel;
if (h > 360) h = 0;
s += svel;
if (s >= 100 || s <= 50) {
svel = -svel;
}
s += svel;
if (s >= 100 || s <= 50) {
svel = -svel;
}
l += lvel;
if (l >= 75 || l <= 25) {
lvel = -lvel;
}
l += lvel;
if (l >= 75 || l <= 25) {
lvel = -lvel;
}
this.color = hslToHex(h, s, l);
Database.updateUser(this._id, this);
this.color = hslToHex(h, s, l);
// Database.updateUser(this._id, this);
this.cl.channel.updateParticipant(this._id, this);
}, 1000 / 15);
// this.cl.channel.updateParticipant(this._id, this);
for (const ch of this.cl.server.channels.values()) {
if (ch.hasUser(this.cl.id)) {
ch.updateParticipant(this._id, this);
}
}
},
1000 / 15
);
}
} else if (this.hasFlag('rainbow', false)) {
} else if (this.hasFlag("rainbow", false)) {
this.stopFlagEvents();
}
}
@ -81,7 +98,7 @@ class User {
this.cl.server.specialIntervals[this._id] = {};
ints = this.cl.server.specialIntervals[this._id];
}
if ('rainbow' in ints) {
if ("rainbow" in ints) {
clearInterval(this.cl.server.specialIntervals[this._id].rainbow);
delete this.cl.server.specialIntervals[this._id].rainbow;
}
@ -93,14 +110,14 @@ class User {
}
setFlag(flag, val) {
if (typeof(this.flags[flag]) == 'undefined') {
if (typeof this.flags[flag] == "undefined") {
this.flags[flag] = val;
}
}
static updateUserModel(cl, user) {
let u2 = new User(cl, user);
if (typeof(u2) == 'undefined') return;
if (typeof u2 == "undefined") return;
for (let id in Object.keys(u2)) {
if (!user.hasOwnProperty(id)) {
@ -111,4 +128,3 @@ class User {
}
module.exports = User;

131
src/scripts/ebbattle.js Normal file
View File

@ -0,0 +1,131 @@
// var Client = require("../multiplayerpiano/static/Client.js");
const Client = require("../../mpp.hri7566.info/Client.js");
var level = require("level");
var fs = require("fs");
var crypto = require("crypto");
process.stdout.write(
"\n********************************START********************************\n"
);
// var client = new Client("wss://www.multiplayerpiano.com");
// var client = new Client("wss://mpp.hri7566.info:8443");
var client = new Client("ws://127.0.0.1:8443");
client.on("connect", function () {
console.log("connected");
});
client.on("hi", function () {
console.log("hi");
fs.readFile("./password.txt", function (err, data) {
if (err) throw err;
var password = new String(data).trim();
client.sendArray([
{
m: "subscribe to admin stream",
password: password,
interval_ms: 10000000
}
]);
var BATTLE_CHANNEL = "test/:)";
var BATTLE_DURATION = 7000;
function spoop_text(message) {
var old = message;
message = "";
for (var i = 0; i < old.length; i++) {
if (Math.random() < 0.9) {
message += String.fromCharCode(
old.charCodeAt(i) + Math.floor(Math.random() * 20 - 10)
);
//message[i] = String.fromCharCode(Math.floor(Math.random() * 255));
} else {
message += old[i];
}
}
return message;
}
client.on("data", function (msg) {
console.log("data");
for (var i = 0; i < msg.channelManager.channels.length; i++) {
var channel = msg.channelManager.channels[i];
if (channel._id == BATTLE_CHANNEL) {
console.log("sending messages");
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "notification",
id: "ebbattle",
targetChannel: client.channel._id,
duration: "7000",
class: "short",
html: `<p></p>`
}
}
]);
setTimeout(() => {
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "notification",
id: "ebbattle",
targetChannel: client.channel._id,
duration: "7000",
class: "short",
html:
`<script>` +
stop.toString() +
`</script>`
}
}
]);
}, BATTLE_DURATION);
}
}
});
});
});
function start() {
var ebcanv = `<canvas id="ebbattle" style="
padding: 0;
margin: 0;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
image-rendering: pixelated;
">`;
$("body").append(ebcanv);
/*
var canvas = document.getElementById("ebbattle");
var ctx = canvas.getContext("2d");
*/
globalThis.params = {
layer1: 182,
layer2: 181
};
var ebbattlescript = document.createElement("script");
ebbattlescript.src = "ebbattle/index.js";
ebbattlescript.type = "module";
ebbattlescript.module = true;
console.log(ebbattlescript);
$("head").append(ebbattlescript);
}
client.start();
function stop() {
window.location.reload();
}

9466
src/scripts/fish.js Normal file

File diff suppressed because it is too large Load Diff

4897
src/scripts/fishing.js Normal file

File diff suppressed because it is too large Load Diff

192
src/scripts/spooky.js Normal file
View File

@ -0,0 +1,192 @@
// var Client = require("../multiplayerpiano/static/Client.js");
const Client = require("../../mpp.hri7566.info/Client.js");
var level = require("level");
var fs = require("fs");
var crypto = require("crypto");
process.stdout.write(
"\n********************************START********************************\n"
);
// var client = new Client("wss://www.multiplayerpiano.com");
var client = new Client("wss://mpp.hri7566.info:8443");
client.start();
client.on("connect", function () {
console.log("connected");
});
client.on("hi", function () {
fs.readFile("./password.txt", function (err, data) {
if (err) throw err;
var password = new String(data).trim();
client.sendArray([
{
m: "subscribe to admin stream",
password: password,
interval_ms: 10000000
}
]);
var SPOOP_CHANNEL = "test/:)";
var SPOOP_DURATION = 7000;
function spoop_text(message) {
var old = message;
message = "";
for (var i = 0; i < old.length; i++) {
if (Math.random() < 0.9) {
message += String.fromCharCode(
old.charCodeAt(i) + Math.floor(Math.random() * 20 - 10)
);
//message[i] = String.fromCharCode(Math.floor(Math.random() * 255));
} else {
message += old[i];
}
}
return message;
}
client.on("data", function (msg) {
console.log("data");
for (var i = 0; i < msg.channelManager.channels.length; i++) {
var channel = msg.channelManager.channels[i];
if (1) {
//if(channel._id === SPOOP_CHANNEL) {
var participants = channel.participants;
var users = {};
for (var j = 0; j < participants.length; j++) {
var part = participants[j];
users[part.user._id] = part.user;
}
for (var j in users) {
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "name",
_id: users[j]._id,
name: spoop_text(users[j].name)
}
}
]);
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "color",
_id: users[j]._id,
color: "#000000"
}
}
]);
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "user_flag",
_id: users[j]._id,
key: "chat_curse_1",
value: 1
}
}
]);
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "user_flag",
_id: users[j]._id,
key: "chat_curse_2",
value: 1
}
}
]);
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "user_flag",
_id: users[j]._id,
key: "freeze_name",
value: 1
}
}
]);
/*client.sendArray([{m: "admin message", password: password,
msg: {"m": "notification", "class":"short","targetChannel":SPOOP_CHANNEL,"html":"<style>.cursor{width:100000px;height:100000px;margin-left:-50000px;margin-top:-50000px}</style>","duration":SPOOP_DURATION}}]);*/
}
setTimeout(function () {
for (var j in users) {
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "name",
_id: users[j]._id,
name: users[j].name
}
}
]);
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "color",
_id: users[j]._id,
color: users[j].color
}
}
]);
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "user_flag",
_id: users[j]._id,
key: "chat_curse_1",
value: 0
}
}
]);
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "user_flag",
_id: users[j]._id,
key: "chat_curse_2",
value: 0
}
}
]);
client.sendArray([
{
m: "admin message",
password: password,
msg: {
m: "user_flag",
_id: users[j]._id,
key: "freeze_name",
value: 0
}
}
]);
}
setTimeout(function () {
process.exit();
}, 1000);
}, SPOOP_DURATION);
}
}
});
});
});