General code cleanup

This commit is contained in:
tgpethan 2021-01-26 12:26:46 +00:00
parent 9489dfe2ea
commit 4d062101f0
14 changed files with 134 additions and 121 deletions

View file

@ -2,8 +2,6 @@ console.clear();
const app = require("express")(),
fs = require("fs"),
busboy = require("connect-busboy"),
osu = require("osu-packet"),
config = require("./config.json");
const debugMode = true;
@ -12,8 +10,6 @@ global.consoleHelper = require("./consoleHelper.js");
const serverHandler = require("./server/serverHandler.js");
app.use(busboy());
app.use((req, res) => {
req.packet = new Buffer.alloc(0);
req.on("data", (chunk) => req.packet = Buffer.concat([req.packet, chunk], req.packet.length + chunk.length));
@ -35,6 +31,8 @@ app.use((req, res) => {
// Just looking for the first character being "c" *should* be enough
if (req.headers["host"].split(".")[0][0] == "c")
serverHandler(req, res);
else
res.status(400).send("400 | Bad Request!<br>Binato only accepts post request on bancho subdomains.<hr>Binato");
break;
default:
@ -44,6 +42,4 @@ app.use((req, res) => {
});
});
// TODO: Not have a predefined port,
// doesn't matter for me so not top priority
app.listen(5001, () => global.consoleHelper.printBancho("Binato is up! Listening at port 5001"));
app.listen(config.port, () => global.consoleHelper.printBancho("Binato is up! Listening at port 5001"));

View file

@ -10,13 +10,14 @@
"author": "",
"license": "ISC",
"dependencies": {
"aes256": "^1.0.4",
"chalk": "^4.0.0",
"connect-busboy": "0.0.2",
"express": "^4.17.1",
"fs": "0.0.1-security",
"osu-packet": "^4.1.2",
"request": "^2.88.2",
"sync-request": "^6.1.0",
"tcp-netx": "^1.2.11",
"uuid": "^7.0.3"
}
}

View file

@ -0,0 +1,15 @@
const osu = require("osu-packet");
module.exports = function(CurrentUser, channelName = "") {
// Make sure the user is not already in the channel
if (global.StreamsHandler.isUserInStream(channelName, CurrentUser.id))
return global.consoleHelper.printBancho(`Did not add user to channel ${channelName} because they are already in it`);
const osuPacketWriter = new osu.Bancho.Writer;
osuPacketWriter.ChannelJoinSuccess(channelName);
if (!global.StreamsHandler.isUserInStream(channelName, CurrentUser.id))
global.StreamsHandler.addUserToStream(channelName, CurrentUser.id);
CurrentUser.addActionToQueue(osuPacketWriter.toBuffer);
}

View file

@ -1,5 +1,5 @@
module.exports = function(userClass, data) {
module.exports = function(CurrentUser, data) {
if (data == "#multiplayer") return; // Ignore requests for multiplayer
global.StreamsHandler.removeUserFromStream(data, userClass.id);
global.StreamsHandler.removeUserFromStream(data, CurrentUser.id);
}

View file

@ -1,7 +1,7 @@
const osu = require("osu-packet"),
getUserByUsername = require("../util/getUserByUsername.js");
module.exports = function(CurrentPacket, CurrentUser) {
module.exports = function(CurrentUser, CurrentPacket) {
const osuPacketWriter = new osu.Bancho.Writer;
osuPacketWriter.SendMessage({

View file

@ -1,7 +1,7 @@
const osu = require("osu-packet"),
botCommandHandler = require("../BotCommandHandler.js");
module.exports = function(CurrentPacket, CurrentUser) {
module.exports = function(CurrentUser, CurrentPacket) {
let isSendingChannelLocked = false;
for (let i = 0; i < global.channels.length; i++) {
if (!CurrentPacket.data.target.includes("#")) break;
@ -36,8 +36,8 @@ module.exports = function(CurrentPacket, CurrentUser) {
});
if (CurrentPacket.data.target == "#multiplayer") {
global.StreamsHandler.sendToStream(global.matches[CurrentUser.currentMatch][0], osuPacketWriter.toBuffer, CurrentUser.id);
botCommandHandler(CurrentUser, CurrentPacket.data.message, global.matches[CurrentUser.currentMatch][0], true);
global.StreamsHandler.sendToStream(CurrentUser.currentMatch.matchStreamName, osuPacketWriter.toBuffer, CurrentUser.id);
botCommandHandler(CurrentUser, CurrentPacket.data.message, CurrentUser.currentMatch.matchStreamName, true);
return;
}
@ -46,6 +46,8 @@ module.exports = function(CurrentPacket, CurrentUser) {
// Write chat message to stream asociated with chat channel
global.StreamsHandler.sendToStream(CurrentPacket.data.target, osuPacketWriter.toBuffer, CurrentUser.id);
if (CurrentPacket.data.target == "#osu")
global.addChatMessage(`${CurrentUser.username}: ${CurrentPacket.data.message}`);
botCommandHandler(CurrentUser, CurrentPacket.data.message, CurrentPacket.data.target);
return;
}

View file

@ -1,7 +1,7 @@
const osu = require("osu-packet"),
getUserById = require("../util/getUserById.js");
module.exports = function(currentUser, id, sendImmidiate = true) {
module.exports = function(currentUser, id = 0, sendImmidiate = true) {
if (id == 3) return; // Ignore Bot
// Create new osu packet writer

View file

@ -1,14 +1,14 @@
const osu = require("osu-packet"),
getUserById = require("../util/getUserById.js");
module.exports = function(currentUser, id) {
module.exports = function(currentUser, id = 0, sendImmidiate = true) {
const osuPacketWriter = new osu.Bancho.Writer;
const User = getUserById(id);
if (User == null) return;
let UserPresenceObject = {
osuPacketWriter.UserPresence({
userId: id,
username: User.username,
timezone: 0,
@ -17,9 +17,8 @@ module.exports = function(currentUser, id) {
longitude: User.location[1],
latitude: User.location[0],
rank: User.rank
};
});
osuPacketWriter.UserPresence(UserPresenceObject);
currentUser.addActionToQueue(osuPacketWriter.toBuffer);
if (sendImmidiate) currentUser.addActionToQueue(osuPacketWriter.toBuffer);
else return osuPacketWriter.toBuffer;
}

View file

@ -1,6 +1,6 @@
const osu = require("osu-packet");
module.exports = function(currentUser) {
module.exports = function(currentUser, sendImmidiate = true) {
const osuPacketWriter = new osu.Bancho.Writer;
let userIds = [];
@ -11,5 +11,6 @@ module.exports = function(currentUser) {
osuPacketWriter.UserPresenceBundle(userIds);
currentUser.addActionToQueue(osuPacketWriter.toBuffer);
if (sendImmidiate) currentUser.addActionToQueue(osuPacketWriter.toBuffer);
else return osuPacketWriter.toBuffer;
}

View file

@ -2,7 +2,7 @@ const UserPresenceBundle = require("./UserPresenceBundle.js"),
UserPresence = require("./UserPresence.js"),
StatusUpdate = require("./StatusUpdate.js");
module.exports = function (currentUser, data) {
module.exports = function (currentUser, data = [0]) {
UserPresenceBundle(currentUser);
for (let i1 = 0; i1 < data.length; i1++) {

View file

@ -2,7 +2,7 @@ const osu = require("osu-packet"),
getUserById = require("./util/getUserById.js");
module.exports = {
startSpectatingUser:function(spectatedId, currentUser) {
startSpectatingUser:function(currentUser, spectatedId) {
// Get the user this user is trying to spectate
const User = getUserById(spectatedId);
if (global.StreamsHandler.doesStreamExist(`sp_${User.username}`)) {

View file

@ -254,9 +254,9 @@ const countryCodes = {
module.exports.countryCodes = countryCodes;
module.exports = {
getCountryID:function(code) {
getCountryID:function(code = "") {
// Get id of a country from a 2 char code
const s = `${code}`.toUpperCase();
const s = code.toUpperCase();
if (countryCodes[s] != null) return countryCodes[s];
else return 0;
},

View file

@ -6,7 +6,10 @@ const osu = require("osu-packet"),
getUserByUsername = require("./util/getUserByUsername.js"),
getUserByToken = require("./util/getUserByToken.js"),
countryHelper = require("./countryHelper.js"),
loginHelper = require("./loginHelper.js");
loginHelper = require("./loginHelper.js"),
UserPresenceBundle = require("./Packets/UserPresenceBundle.js"),
UserPresence = require("./Packets/UserPresence.js"),
StatusUpdate = require("./Packets/StatusUpdate.js");
module.exports = function(req, res, loginInfo) {
// Get time at the start of login
@ -63,83 +66,59 @@ module.exports = function(req, res, loginInfo) {
global.users.push(new User(userDB.id, loginInfo.username, newClientToken, new Date().getTime()));
// Retreive the newly created user
const userClass = getUserByToken(newClientToken);
const NewUser = getUserByToken(newClientToken);
// Get user's data from the database
userClass.getNewUserInformationFromDatabase();
NewUser.getNewUserInformationFromDatabase();
try {
// Save the user's location to their class for later use
userClass.location[0] = parseFloat(userLocation[0]);
userClass.location[1] = parseFloat(userLocation[1]);
NewUser.location[0] = parseFloat(userLocation[0]);
NewUser.location[1] = parseFloat(userLocation[1]);
// Save the country id for the same reason as above
userClass.countryID = countryHelper.getCountryID(userLocationData.country);
NewUser.countryID = countryHelper.getCountryID(userLocationData.country);
// We're ready to start putting together a login packet
// Create an osu! Packet writer
let osuPacketWriter = new osu.Bancho.Writer;
// The reply id is the user's id in any other case than an error in which case negative numbers are used
osuPacketWriter.LoginReply(userClass.id);
osuPacketWriter.LoginReply(NewUser.id);
// Current bancho protocol version is 19
osuPacketWriter.ProtocolNegotiation(19);
// Permission level 4 is osu!supporter
osuPacketWriter.LoginPermissions(4);
// Construct user's friends list
const userFriends = global.DatabaseHelper.getFromDB(`SELECT friendsWith FROM friends WHERE user = ${userClass.id}`);
const userFriends = global.DatabaseHelper.getFromDB(`SELECT friendsWith FROM friends WHERE user = ${NewUser.id}`);
let friendsArray = [];
for (let i = 0; i < userFriends.length; i++) {
friendsArray.push(userFriends[i].friendsWith);
}
// Send user's friends list
osuPacketWriter.FriendsList(friendsArray);
// After sending the user their friends list send them the online users
UserPresenceBundle(NewUser);
// Set title screen image
osuPacketWriter.TitleUpdate("http://puu.sh/jh7t7/20c04029ad.png|https://osu.ppy.sh/news/123912240253");
// Construct user panel data
const presenceObject = {
userId: userClass.id,
username: userClass.username,
timezone: 0,
countryId: userClass.countryID,
permissions: 4,
longitude: userClass.location[1],
latitude: userClass.location[0],
rank: userClass.rank
};
const statusObject = {
userId: userClass.id,
status: userClass.actionID,
statusText: userClass.actionText,
beatmapChecksum: userClass.beatmapChecksum,
currentMods: userClass.currentMods,
playMode: userClass.playMode,
beatmapId: userClass.beatmapID,
rankedScore: userClass.rankedScore,
accuracy: userClass.accuracy / 100, // Scale of 0 to 1
playCount: userClass.playCount,
totalScore: userClass.totalScore,
rank: userClass.rank,
performance: userClass.pp
};
//osuPacketWriter.TitleUpdate("http://puu.sh/jh7t7/20c04029ad.png|https://osu.ppy.sh/news/123912240253");
// Add user panel data packets
osuPacketWriter.UserPresence(presenceObject);
osuPacketWriter.HandleOsuUpdate(statusObject);
UserPresence(NewUser, NewUser.id);
StatusUpdate(NewUser, NewUser.id);
// peppy pls, why
osuPacketWriter.ChannelListingComplete();
// Add user to chat channels
osuPacketWriter.ChannelJoinSuccess("#osu");
if (!global.StreamsHandler.isUserInStream("#osu", userClass.id))
global.StreamsHandler.addUserToStream("#osu", userClass.id);
if (!global.StreamsHandler.isUserInStream("#osu", NewUser.id))
global.StreamsHandler.addUserToStream("#osu", NewUser.id);
osuPacketWriter.ChannelJoinSuccess("#userlog");
if (!global.StreamsHandler.isUserInStream("#userlog", userClass.id))
global.StreamsHandler.addUserToStream("#userlog", userClass.id);
if (!global.StreamsHandler.isUserInStream("#userlog", NewUser.id))
global.StreamsHandler.addUserToStream("#userlog", NewUser.id);
// List all channels out to the client
for (let i = 0; i < global.channels.length; i++) {
@ -154,7 +133,7 @@ module.exports = function(req, res, loginInfo) {
// Complete login
res.writeHead(200, {
"cho-token": userClass.uuid,
"cho-token": NewUser.uuid,
"cho-protocol": 19,
"Connection": "keep-alive",
"Keep-Alive": "timeout=5, max=100",

View file

@ -35,11 +35,18 @@ setInterval(() => {
}
}, 10000);
// An array containing all currently active multiplayer matches
global.matches = [];
// An array containing the last 15 messages in chat
// TODO: Bother making this
global.chatHistory = [];
global.addChatMessage = function(msg) {
if (global.chatHistory.length == 15) {
global.chatHistory.splice(0, 1);
global.chatHistory.push(msg);
} else {
global.chatHistory.push(msg);
}
}
global.StreamsHandler = new Streams();
// An array containing all chat channels
@ -72,7 +79,7 @@ const logInterval = 10; // Secs
setInterval(() => {
global.usersOnline = (global.users.length - 1);
global.multiplayerMatches = [global.matches.length, 0]; // TODO: Respect private matches
global.multiplayerMatches = [global.MultiplayerManager.matches.length, 0]; // TODO: Respect private matches
fs.appendFile(
"server-stats.log",
@ -80,18 +87,25 @@ setInterval(() => {
() => { }
);
global.usersOnline = 0;
global.multiplayerMatches = [0, 0];
global.httpRequestsPerLogInterval = 0;
}, logInterval * 1000);
if (!fs.existsSync("tHMM.ds")) fs.writeFileSync("tHMM.ds", "0");
global.totalHistoricalMultiplayerMatches = parseInt(fs.readFileSync("tHMM.ds").toString());
global.getAndAddToHistoricalMultiplayerMatches = function() {
global.totalHistoricalMultiplayerMatches++;
fs.writeFile("tHMM.ds", global.totalHistoricalMultiplayerMatches, (e) => {});
return global.totalHistoricalMultiplayerMatches;
}
// Include packets
const ChangeAction = require("./Packets/ChangeAction.js"),
SendPublicMessage = require("./Packets/SendPublicMessage.js"),
Logout = require("./Packets/Logout.js"),
Spectator = require("./Spectator.js"),
SendPrivateMessage = require("./Packets/SendPrivateMessage.js"),
Multiplayer = require("./Multiplayer.js"),
MultiplayerManager = require("./MultiplayerManager.js"),
ChannelJoin = require("./Packets/ChannelJoin.js"),
ChannelPart = require("./Packets/ChannelPart.js"),
AddFriend = require("./Packets/AddFriend.js"),
RemoveFriend = require("./Packets/RemoveFriend.js"),
@ -100,6 +114,9 @@ const ChangeAction = require("./Packets/ChangeAction.js"),
UserStatsRequest = require("./Packets/UserStatsRequest.js"),
MultiplayerInvite = require("./Packets/MultiplayerInvite.js");
// A class for managing everything multiplayer
global.MultiplayerManager = new MultiplayerManager();
module.exports = function(req, res) {
// Add to requests for logging
global.httpRequestsPerLogInterval++;
@ -122,10 +139,10 @@ module.exports = function(req, res) {
// Client has a token, let's see what they want.
try {
// Get the current user
const userClass = getUserFromToken(requestTokenString);
const PacketUser = getUserFromToken(requestTokenString);
// Make sure the client's token isn't invalid
if (userClass != null) {
if (PacketUser != null) {
// Create a new osu! packet reader
const osuPacketReader = new osu.Client.Reader(requestData);
// Parse current bancho packet
@ -134,150 +151,153 @@ module.exports = function(req, res) {
for (let i = 0; i < PacketData.length; i++) {
// Get current packet
let CurrentPacket = PacketData[i];
// This is getting a little big, swap this out for mapped functions?
// Would require some standardisation
switch (CurrentPacket.id) {
case packetIDs.client_changeAction:
ChangeAction(userClass, CurrentPacket.data);
ChangeAction(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_sendPublicMessage:
SendPublicMessage(CurrentPacket, userClass);
SendPublicMessage(PacketUser, CurrentPacket);
break;
case packetIDs.client_logout:
Logout(userClass);
Logout(PacketUser);
break;
case packetIDs.client_requestStatusUpdate:
UserPresenceBundle(userClass);
UserPresenceBundle(PacketUser);
break;
case packetIDs.client_pong: // Pretty sure this is just a client ping
// so we probably don't do anything here
break;
break; // It's probably just the client wanting to pull data down.
case packetIDs.client_startSpectating:
Spectator.startSpectatingUser(CurrentPacket.data, userClass);
Spectator.startSpectatingUser(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_spectateFrames:
Spectator.sendSpectatorFrames(userClass, CurrentPacket.data);
Spectator.sendSpectatorFrames(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_stopSpectating:
Spectator.stopSpectatingUser(userClass);
Spectator.stopSpectatingUser(PacketUser);
break;
case packetIDs.client_sendPrivateMessage:
SendPrivateMessage(CurrentPacket, userClass);
SendPrivateMessage(PacketUser, CurrentPacket);
break;
case packetIDs.client_joinLobby:
Multiplayer.userEnterLobby(userClass);
global.MultiplayerManager.userEnterLobby(PacketUser);
break;
case packetIDs.client_partLobby:
Multiplayer.userLeaveLobby(userClass);
global.MultiplayerManager.userLeaveLobby(PacketUser);
break;
case packetIDs.client_createMatch:
Multiplayer.createMultiplayerMatch(userClass, CurrentPacket.data);
global.MultiplayerManager.createMultiplayerMatch(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_joinMatch:
Multiplayer.joinMultiplayerMatch(userClass, CurrentPacket.data);
global.MultiplayerManager.joinMultiplayerMatch(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_matchChangeSlot:
Multiplayer.moveToSlot(userClass, CurrentPacket.data);
PacketUser.currentMatch.moveToSlot(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_matchReady:
Multiplayer.setReadyState(userClass, true);
PacketUser.currentMatch.setReadyState(PacketUser, true);
break;
case packetIDs.client_matchChangeSettings:
Multiplayer.updateMatch(userClass, CurrentPacket.data);
PacketUser.currentMatch.updateMatch(CurrentPacket.data);
break;
case packetIDs.client_matchNotReady:
Multiplayer.setReadyState(userClass, false);
PacketUser.currentMatch.setReadyState(PacketUser, false);
break;
case packetIDs.client_partMatch:
Multiplayer.leaveMatch(userClass);
global.MultiplayerManager.leaveMultiplayerMatch(PacketUser);
break;
case packetIDs.client_matchLock: // Also handles user kick
Multiplayer.kickPlayer(userClass, CurrentPacket.data);
// Also handles user kick if the slot has a user
case packetIDs.client_matchLock:
PacketUser.currentMatch.lockMatchSlot(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_matchNoBeatmap:
Multiplayer.missingBeatmap(userClass, true);
PacketUser.currentMatch.missingBeatmap(PacketUser);
break;
case packetIDs.client_matchSkipRequest:
Multiplayer.matchSkip(userClass);
PacketUser.currentMatch.matchSkip(PacketUser);
break;
case packetIDs.client_matchHasBeatmap:
Multiplayer.missingBeatmap(userClass, false);
PacketUser.currentMatch.notMissingBeatmap(PacketUser);
break;
case packetIDs.client_matchTransferHost:
Multiplayer.transferHost(userClass, CurrentPacket.data);
PacketUser.currentMatch.transferHost(CurrentPacket.data);
break;
case packetIDs.client_matchChangeMods:
Multiplayer.updateMods(userClass, CurrentPacket.data);
PacketUser.currentMatch.updateMods(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_matchStart:
Multiplayer.startMatch(userClass);
PacketUser.currentMatch.startMatch();
break;
case packetIDs.client_matchLoadComplete:
Multiplayer.setPlayerLoaded(userClass);
PacketUser.currentMatch.matchPlayerLoaded(PacketUser);
break;
case packetIDs.client_matchComplete:
Multiplayer.onPlayerFinishMatch(userClass);
PacketUser.currentMatch.onPlayerFinishMatch(PacketUser);
break;
case packetIDs.client_matchScoreUpdate:
Multiplayer.updatePlayerScore(userClass, CurrentPacket.data);
PacketUser.currentMatch.updatePlayerScore(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_matchFailed:
PacketUser.currentMatch.matchFailed(PacketUser);
break;
case packetIDs.client_channelJoin:
// TODO: Implement user channel joining
// Auto channel joining is already complete
ChannelJoin(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_channelPart:
ChannelPart(userClass, CurrentPacket.data);
ChannelPart(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_friendAdd:
AddFriend(userClass, CurrentPacket.data);
AddFriend(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_friendRemove:
RemoveFriend(userClass, CurrentPacket.data);
RemoveFriend(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_userStatsRequest:
UserStatsRequest(userClass, CurrentPacket.data);
UserStatsRequest(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_invite:
MultiplayerInvite(userClass, CurrentPacket.data);
MultiplayerInvite(PacketUser, CurrentPacket.data);
break;
case packetIDs.client_userPresenceRequest:
UserPresence(userClass, userClass.id);
UserPresence(PacketUser, PacketUser.id);
break;
default:
@ -288,9 +308,9 @@ module.exports = function(req, res) {
break;
}
// Put current user queue into response data
responseData = Buffer.concat([responseData, userClass.queue], responseData.length + userClass.queue.length);
userClass.clearQueue();
// Concat current user queue into response data
responseData = Buffer.concat([responseData, PacketUser.queue], responseData.length + PacketUser.queue.length);
PacketUser.clearQueue();
}
} else {
// User's token is invlid, force a reconnect
@ -310,4 +330,4 @@ module.exports = function(req, res) {
res.end(responseData);
}
}
};
};