aboutsummaryrefslogtreecommitdiff
path: root/cmd_nick.go
blob: 0d844b868347e9b8cc1dcff2a50e9141e30be547 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main

import (
	"fmt"
	"log/slog"
)

func init() {
	commandHandlers["NICK"] = handleClientNick
}

func handleClientNick(msg RMsg, client *Client) error {
	if len(msg.Params) < 1 {
		return client.Send(MakeMsg(self, ERR_NEEDMOREPARAMS, "NICK", "Not enough parameters"))
	}
	already, exists := nickToClient.LoadOrStore(msg.Params[0], client)
	if exists {
		if already != client {
			err := client.Send(MakeMsg(self, ERR_NICKNAMEINUSE, client.Nick, msg.Params[0], "Nickname is already in use"))
			if err != nil {
				return err
			}
		}
	} else {
		if client.State == ClientStateRegistered {
			if !nickToClient.CompareAndDelete(client.Nick, client) {
				slog.Error("nick inconsistent", "nick", client.Nick, "client", client)
				return fmt.Errorf("%w: %v", ErrInconsistent, client)
			}
			err := client.Send(MakeMsg(client, "NICK", msg.Params[0]))
			if err != nil {
				return err
			}
		}
		client.Nick = msg.Params[0]
	}
	if client.State == ClientStatePreRegistration {
		err := client.checkRegistration()
		if err != nil {
			return err
		}
	}
	return nil
}