Socket.Io sort locked and unlocked rooms in a list

  javascript, node.js, socket.io, sockets, websocket

I’ve created a socket.io chat app with plain Javascript and i need to sort the rooms in a list on the welcome screen.

Display all the rooms in a sidebar to the left, like: Rooms: room1 room2, and another list: Locked rooms(rooms that use password): room1, room2.

Rigt now i have a list with all the rooms but not filtered if they have passwords or not. How can i do that?

Server side code:

  
const express = require("express");
const http = require("http");
const socketIO = require("socket.io");
const chalk = require("chalk");

const app = express();
const server = http.createServer(app);
const io = socketIO(server);
let rooms = [
    //room with password created for testing
    {
        id: "Livingroom",
        password: "password",
    },
];

console.log("rooms", rooms);

app.use(express.static("public"));

app.get("/rooms"),
    (req, res) => {
        res.json(rooms);
    };

//Client connection
io.on("connection", (socket) => {
    console.log("User connected: ", socket.id);
    //Broadcast all rooms to all clients
    io.emit("rooms", getAllRooms());

    // socket.on('create room', (data) => {
    //     socket.join(data.room, () => {
    //         rooms.push({
    //             name: data.room,
    //             password: data.password
    //         })
    //     })
    // })

    // data =  {name, room, password}
    socket.on("join room", (data) => {
        var index = rooms.findIndex((room) => room.id === data.room);

        // if room doesn't exists then index is -1,  create & join
        if (index === -1) {
            rooms.push({
                id: data.room,
                password: data.password,
            });
        } // room already exists check password
        else if (data.password !== rooms[index].password) {
            // if not correct password send error
            socket.emit("wrong password", "Uncorrect password");
            console.log("fel lösen");
            
            return; // then return
        }
        
        //if password is correct join, if not show error message
        socket.join(data.room, () => {
            io.emit("rooms", getAllRooms());
            // Respond that join was a success
            socket.emit("join success", "success");
            io.to(data.room).emit("new_message", {
                name: data.name,
                message: `has joined the room!`,
            });

            socket.on("new_message", (message) => {
                // Broadcast message to all clients in the room
                io.to(data.room).emit("new_message", { name: data.name, message });
            });
        });
    },

    socket.on("leave room", () => {
        socket.leaveAll();
          // sync rooms variable with socket.io rooms
        const socketRooms = getAllRooms();
         // exempel socketRooms = ["rum 1"] 
        // rooms = [{id: "rum 1", password: "123"}, {id: "rum 2", password: ""}] 
        rooms = rooms.filter(room => socketRooms.includes(room.id))

        //Broadcast all rooms to all clients
        io.emit("rooms", getAllRooms()); 
    })
  );


socket.on("disconnect", (data) => {
    console.log("User disconnected", socket.id);
    socket.leaveAll();
    // sync rooms variable with socket.io rooms
    const socketRooms = getAllRooms();
    rooms = rooms.filter(room => socketRooms.includes(room.id))

    //Broadcast all rooms to all clients
    io.emit("rooms", getAllRooms()); 
});
});

function getAllRooms() {
    const roomsAndSocketIds = Object.keys(io.sockets.adapter.rooms);
    const socketIds = Object.keys(io.sockets.sockets);
    const rooms = roomsAndSocketIds.filter(
        (roomOrId) => !socketIds.includes(roomOrId)
    );
    console.log(rooms);
    return rooms;
}

server.listen(3000, () =>
    console.log(chalk.blue("Server is running at: http://localhost:3000"))
);

Client Javascript code:

const socket = io()

window.addEventListener('load', () => {
  setupEventListeners()
})

function setupEventListeners() {
  // To Lobby on submit
  const joinLobby = document.querySelector('form.nic-name')
  joinLobby.addEventListener('submit', onJoinLobby)

  // Join room on submit
  const joinRoom = document.querySelector('form.join')
  joinRoom.addEventListener('submit', onJoinRoom)

  // Send messages on submit
  const messageChat = document.querySelector('.chat form')
  messageChat.addEventListener('submit', onSendMessage)

  // Leave chat on submit
  const leaveChat = document.querySelector('.chat-leave')
  leaveChat.addEventListener('submit', onLeaveRoom)

  // Socket io events
  socket.on('join success', joinChatRoom)
  socket.on('new_message', onReceivedMessage)
  socket.on('rooms', onGetRooms)
  socket.on('password', joinChatRoom)
  socket.on('wrong password', () => alert("Fel lösenord"))
}

// Enter nic and go to Lobby
function onJoinLobby(event) {
  event.preventDefault()
  const [nameInput] = document.querySelectorAll('.join-lobby input')
  const message = document.querySelector('.welcome-lobby')
  const name = nameInput.value
  const welcome = "Welcome to the Lobby "
  const h2 = document.createElement('h2')
  
  document.querySelector('.join-lobby').classList.add('hidden')
  document.querySelector('.aside').classList.remove('hidden')
  document.querySelector('.join-room').classList.remove('hidden')

  h2.innerText = `${welcome} ${name}!`
  message.appendChild(h2)
 
  socket.emit('rooms', { name })
}

// Create room
function onJoinRoom(event) {
  event.preventDefault()
  const [nameInput] = document.querySelectorAll('.join-lobby input')
  const [roomInput] = document.querySelectorAll('.join input')
  const [passwordInput] = document.querySelectorAll('.password')
  const room = roomInput.value
  const name = nameInput.value
  const password = passwordInput.value

  socket.emit('join room', { name, room, password })
}

// Leave Chat
function onLeaveRoom(event) {
  event.preventDefault()
  location.reload()
  socket.emit('leave room')
}

// Send messages in the room
function onSendMessage(event) {
  event.preventDefault()
  const input = document.querySelector('.chat form input')
  socket.emit('new_message', input.value)
  input.value = ''
}

// Receive messages un the room
function onReceivedMessage({ name, message }) {
  const ul = document.querySelector('.chat ul')
  const li = document.createElement('li')
  li.innerText = `${name}: ${message}`
  ul.append(li)
}

// Remove hidden from chatroom
function joinChatRoom(data) {
  console.log(data)
  document.querySelector('.join-room').classList.add('hidden')
  document.querySelector('.chat').classList.remove('hidden')
}

// Get all rooms
function onGetRooms(rooms) {
  
  const open = document.querySelector('#openRooms')
  const locked = document.querySelector('#lockedRooms')

  rooms.forEach((room) => {
    if (room.password) {
    const lockedRoom = document.createElement('li')
    locked.innerText = room
    locked.innerText = ''
    locked.append(lockedRoom)
    console.log(rooms)
    return lockedRoom

    } else {
      const openRoom = document.createElement('li')
      openRoom.innerText = room
      open.innerText = ''
      open.append(openRoom)
      console.log(rooms)
      return openRoom
      
    }
  })
 }

// Password
function usePassword() {
  let checkBox = document.querySelector('#checkbox')
  let input = document.querySelector('#password')
  if (checkBox.checked == true) {
    input.classList.remove('hidden')
  } else {
    input.classList.add('hidden')
  }
}

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="./script.js"></script>
    <link rel="stylesheet" href="style.css">
    <title>chat-app</title>
</head>

<body>
    <aside class="aside hidden">
        <div class="open-rooms">
            <h2>Open Rooms</h2>
            <ul id="openRooms">
                <!-- Open Rooms -->
            </ul>
        </div>
        <div class="locked-rooms">
            <h2>Locked Rooms</h2>
            <ul id="lockedRooms">
                <!-- Locked Rooms -->
            </ul>
        </div>
    </aside>    

    </aside>
    <main>
        <div class="join-lobby">
            <div class="welcome">
                <h1>Welcome</h1>
                <h3>Enter your nic and go to the Lobby!</h3>
            </div>
            <form class="nic-name">
                <input id="name" type="text" placeholder="Enter your nic">
                <button>To Lobby</button>
            </form>
        </div>
        <div class="join-room hidden">
            <div class="welcome-lobby">
                <!-- Welcome -->
            </div>
            <form class="join">
            <input id="room" type="text" placeholder="Enter a room">
            <label for="checkbox">Use password?</label>
            <input type="checkbox" name="checkbox" id="checkbox" onclick="usePassword()">
            <input id="password" class="password hidden" type="password" placeholder="enter the password">
            <label name="password" id="password" for="password">Show password</label>
              <input type="checkbox" class="password"
                onchange="document.getElementById('password').type = this.checked ? 'text' : 'password'">
                <button>Join Room</button>
            </form>
        </div>

        <div class="chat hidden">
            <ul>
                <!-- Messages from users -->
            </ul>
            <form class="chat-room">
                <input id="message" type="text" placeholder="Type your message">
                <button id="send_message">Send</button>
            </form>
            <form class="chat-leave">
                <button id="leave">Leave Chat</button>
            </form>
        </div>
    </main>
</body>

</html>

Source: Ask Javascript Questions

LEAVE A COMMENT