From 908b023f60ca2eec347f68bb4f0c8a9c778278ae Mon Sep 17 00:00:00 2001 From: WlodekM Date: Tue, 2 Jul 2024 20:55:17 +0300 Subject: make 1 global object instead of doing OOP --- commands.js | 42 +++++++++++++++++++++++++++++++----------- index.js | 56 ++++++++++++++++++++++++++++++++------------------------ 2 files changed, 63 insertions(+), 35 deletions(-) diff --git a/commands.js b/commands.js index 9a34409..8aa80a3 100644 --- a/commands.js +++ b/commands.js @@ -1,11 +1,13 @@ +import fs from "fs" + export const commands = { 'join': { name: 'join', aliases: [], - command: function({user, channels, args, sendInChannel}) { + command: function({user, server, args, sendInChannel}) { if(args.length < 1) return user.socket.send("Error: You need to specify a channel (example: /join #home)."); if(!args[0].startsWith("#")) return user.socket.send("Error: Channel not found, run /channels to see a list of channels."); - if(!channels.includes(args[0].replace("#", ""))) return user.socket.send("Error: Channel not found, run /channels to see a list of channels."); + if(!server.channels.includes(args[0].replace("#", ""))) return user.socket.send("Error: Channel not found, run /channels to see a list of channels."); sendInChannel(`${user.username} left #${user.channel}.`, user.channel) user.channel = args[0].replace("#", ""); sendInChannel(`${user.username} joined #${user.channel}!`, user.channel) @@ -14,33 +16,51 @@ export const commands = { 'channels': { name: 'channels', aliases: [], - command: function({user, channels}) { - user.socket.send(`Channels:\n${channels.map(ch => ` * #${ch}`).join("\n")}`) + command: function({user, server}) { + user.socket.send(`Channels:\n${server.channels.map(ch => ` * #${ch}`).join("\n")}`) } }, 'nick': { name: 'nick', aliases: ['nickname', 'name'], - command: function({user, users, args, sendInChannel}) { + command: function({user, server, args, sendInChannel}) { if(args.length < 1) return user.socket.send("Error: You need to specify a nick (example: /nick WlodekM)."); - if(args[0].length < 3 ) return user.socket.send("Error: Nick too long."); - if(args[0].length > 20) return user.socket.send("Error: Nick too short."); - if(Object.values(users).find(usr => usr.username == args[0])) return user.socket.send("Error: Nick already used."); + if(args[0].length < 3 ) return user.socket.send("Error: Nick too short."); + if(args[0].length > 20) return user.socket.send("Error: Nick too long."); + if(Object.values(server.users).find(usr => usr.username == args[0])) return user.socket.send("Error: Nick already used."); sendInChannel(`${user.username} changed their nick to ${args[0]}!`, user.channel) user.username = args[0]; } }, + 'about': { + name: 'about', + aliases: [], + command: function({user, args, sendInChannel}) { + user.socket.send(`wsChat v${JSON.parse(String(fs.readFileSync("package.json"))).version}\nGithub: https://github.com/WlodekM/wsChat`) + } + }, + 'whois': { + name: 'whois', + aliases: [], + command: function({user, server, args}) { + if(args.length < 1) return user.socket.send('Please provide username'); + if(Object.values(server.users).find(usr => usr.username == args[0])) return user.socket.send('User not found'); + let userFound = Object.values(server.users).find(usr => usr.username == args[0]) + userFound.id = Object.keys(server.users).find(usr => server.users[usr].username == args[0]) + user.socket.send(`${userFound.username}\nClient: ${userFound.client ?? ""}\nID: ${userFound.id}`) + } + }, 'users': { name: 'users', aliases: [], - command: function({user, users, args}) { - user.socket.send(`Users${args[0] != "global" ? ` in ${user.channel}` : ""}:\n${Object.values(users).filter(usr => (usr.channel == user.channel) || args[0] == "global").map(usr => ` * ${usr.username}`).join("\n")}`) + command: function({user, server, args}) { + user.socket.send(`Users${args[0] != "global" ? ` in ${user.channel}` : ""}:\n${Object.values(server.users).filter(usr => (usr.channel == user.channel) || args[0] == "global").map(usr => ` * ${usr.username}`).join("\n")}`) } }, 'help': { name: 'help', aliases: ['?'], - command: function({user, users, args, commands}) { + command: function({user, args, commands}) { user.socket.send(`Commands available:\n${Object.values(commands).map(cmd => `* /${cmd.name} (Aliases: ${(cmd.aliases.join(", ")) || ""})`).join("\n")}`) } }, diff --git a/index.js b/index.js index ea5ac55..ee03570 100644 --- a/index.js +++ b/index.js @@ -1,44 +1,44 @@ import { WebSocketServer } from "ws"; -import cuid from 'cuid'; import { getRandomInt } from "./lib.js" import { commands } from "./commands.js"; +import cuid from 'cuid'; import fs from 'fs'; -const config = JSON.parse(String(fs.readFileSync("config.json"))) - -const channels = ["home", "off-topic"] +const server = { + config: JSON.parse(String(fs.readFileSync("config.json"))), + channels: ["home", "off-topic"], + users: {}, +} const ws = new WebSocketServer({ port: 9933, }); -const users = {} - function sendInChannel(msg, channel) { - for (const userID in users) { - const user = users[userID]; + for (const userID in server.users) { + const user = server.users[userID]; if (user.channel == channel) user.socket.send(msg) } } function format(txt) { txt = String(txt) - txt = txt.replaceAll("$(serverName)$", config.name) - txt = txt.replaceAll("$(userCount)$", Object.keys(users).length) - txt = txt.replaceAll("$(max)$", config.max) + txt = txt.replaceAll("$(serverName)$", server.config.name) + txt = txt.replaceAll("$(userCount)$", Object.keys(server.users).length) + txt = txt.replaceAll("$(max)$", server.config.max) return txt } ws.on('connection', (socket, request) => { - if (config.max && Object.keys(users).length >= config.max) { - socket.send(format(config.fullMessage ?? "Sorry, but the server is full right now, come back later")) + if (server.config.max && Object.keys(server.users).length >= server.config.max) { + socket.send(format(server.config.fullMessage ?? "Sorry, but the server is full right now, come back later")) socket.close(1001, "Server full") } let userID = cuid() - socket.send(format(config.motd)) + socket.send(format(server.config.motd)) let anonID = getRandomInt(0, 99999) - users[userID] = { - username: `Anonymous${"0".repeat(5 - anonID.length) + anonID.toString()}`, + server.users[userID] = { + username: `Anonymous${"0".repeat(5 - anonID.toString().length) + anonID.toString()}`, socket: socket, joinReq: request, t: { @@ -48,30 +48,38 @@ ws.on('connection', (socket, request) => { }, channel: 'home' } - sendInChannel(`${users[userID].username} joined #${users[userID].channel}!`, users[userID].channel) + sendInChannel(`${server.users[userID].username} joined #${server.users[userID].channel}!`, server.users[userID].channel) socket.on('close', function (code, reason) { - sendInChannel(`${users[userID].username} left.`, users[userID].channel) - delete users[userID] + sendInChannel(`${server.users[userID].username} left.`, server.users[userID].channel) + delete server.users[userID] }) socket.on('message', function (rawData) { if (rawData.toString().startsWith("/")) { let args = String(rawData).replace("/", "").split(" "); let command = args.shift(); let commandObj = Object.values(commands).find(cmd => cmd.name == command || cmd.aliases.includes(command)) - console.log(`${users[userID].username} used /${command}`) + console.log(`${server.users[userID].username} used /${command}`) if (!commandObj) return socket.send(`Error: Command "${command}" not found!`); - let user = users[userID] + let user = server.users[userID] try { - commandObj.command({ user, command, args, sendInChannel, channels, users, commands }) + commandObj.command({ user, command, args, sendInChannel, server, commands }) } catch (error) { user.socket.send(`Unexpected error ocurred while running the command`) } return } + if (rawData.toString().startsWith(":client")) { + let client = String(rawData).replace(":client", ""); + if (!client) return socket.send("Error: client info missing!"); + if (client.length < 2) return socket.send("Error: client info too short!"); + if (client.length >= 100) return socket.send("Error: client info too long!"); + server.users[userID].client = client; + return + } if (rawData.length < 1) return socket.send("Error: message too short!") if (rawData.length >= 2000) return socket.send("Error: message too long!") - sendInChannel(`<${users[userID].username}> ${rawData}`, users[userID].channel) - console.log(`(#${users[userID].channel}) <${users[userID].username}> ${rawData}`) + sendInChannel(`<${server.users[userID].username}> ${rawData}`, server.users[userID].channel) + console.log(`(#${server.users[userID].channel}) <${server.users[userID].username}> ${rawData}`) }) }) -- cgit 1.4.1-2-gfad0