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 .history
*.db/ *.db/
.env .env
password.txt

2
.gitmodules vendored
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,24 +1,27 @@
const Holidays = require('date-holidays'); const Holidays = require("date-holidays");
let hd = new Holidays(); let hd = new Holidays();
hd.init('US'); hd.init("US");
let dayOfTheWeekMOTD = [ let dayOfTheWeekMOTD = [
'Happy Sunday!', "Happy Sunday!",
'You can chat with that thing.', "You can chat with that thing.",
'I\'m tired...', "I'm tired...",
'Don\'t forget to bring a towel!', "Don't forget to bring a towel!",
'Never lick a pole in winter.', "Never lick a pole in winter.",
'Everyone loves a potato monkey!', "Everyone loves a potato monkey!",
'Dear Mario: Please come to the castle. I\'ve baked a cake for you. Yours truly-- Princess Toadstool' "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();
let start = new Date(now.getFullYear(), 0, 0); 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 oneDay = 1000 * 60 * 60 * 24;
let day = Math.floor(diff / oneDay); let day = Math.floor(diff / oneDay);
return day; return day;
@ -31,12 +34,24 @@ class MOTDGenerator {
return `Happy ${h[0].name}!`; return `Happy ${h[0].name}!`;
} else { } else {
// no holiday, get day // no holiday, get day
let day = new Date().getDay(); // let day = new Date().getDay();
return dayOfTheWeekMOTD[day]; 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 = { module.exports = {
MOTDGenerator MOTDGenerator
} };

View File

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

View File

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

View File

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

View File

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