Skip to content

Commit

Permalink
Add unblock command
Browse files Browse the repository at this point in the history
  • Loading branch information
ah-naf committed Sep 1, 2024
1 parent b4b4a40 commit be959fd
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions server/internals/chatserver/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ func(cs *ChatServer) HandleCommand(conn net.Conn, command string) {
return
}
cs.BlockUser(conn, args[1])
case "unblock":
if len(args) < 2 {
conn.Write([]byte(utils.FormatErrorMessage("Usage: /unblock <username>\n")))
return
}
cs.UnblockUser(conn, args[1])

default:
conn.Write([]byte(utils.FormatWarningMessage("Invalid command. Type 'help' for more information.\n")))
Expand All @@ -50,7 +56,7 @@ func (cs *ChatServer) BlockUser(conn net.Conn, targetUsername string) {
}

if user == targetUsername {
conn.Write([]byte(utils.FormatErrorMessage("You cannot block yourself.\n")))
conn.Write([]byte(utils.FormatWarningMessage("You cannot block yourself.\n")))
return
}

Expand All @@ -65,4 +71,35 @@ func (cs *ChatServer) BlockUser(conn net.Conn, targetUsername string) {

cs.blockedBy[user][targetUsername] = true
conn.Write([]byte(utils.FormatSuccessMessage(fmt.Sprintf("User '%s' has been blocked.\n", targetUsername))))
}
}

func (cs *ChatServer) UnblockUser(conn net.Conn, targetUsername string) {
cs.mu.Lock()
defer cs.mu.Unlock()

user, exists := cs.globalClients[conn]
if !exists {
conn.Write([]byte(utils.FormatErrorMessage("Internal error: user not found.\n")))
return
}

if user == targetUsername {
conn.Write([]byte(utils.FormatWarningMessage("You cannot unblock yourself.\n")))
return
}

blockedUser, blocked := cs.blockedBy[user]
if !blocked {
conn.Write([]byte(utils.FormatWarningMessage(fmt.Sprintf("%s is not a blocked user.\n", targetUsername))))
return
}

if _, exists := blockedUser[targetUsername]; !exists {
conn.Write([]byte(utils.FormatWarningMessage(fmt.Sprintf("%s is not a blocked user.\n", targetUsername))))
return
}

// Unblock the user
delete(blockedUser, targetUsername)
conn.Write([]byte(utils.FormatSuccessMessage(fmt.Sprintf("User '%s' has been unblocked.\n", targetUsername))))
}

0 comments on commit be959fd

Please sign in to comment.