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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::fmt::{self};

use crate::command::IRCCommand;
use crate::error::{MessageError, MessageErrorDetails};

#[derive(Debug)]
pub struct Message {
    pub source: Option<String>,
    pub command: IRCCommand,
    pub params: Vec<String>,
}
impl fmt::Display for Message {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", String::from_utf8_lossy(self.serialize().as_ref()))
    }
}

static CR: u8 = 13;
static LF: u8 = 10;

impl Message {
    /// Returns the serialize of this [`Message`].
    ///
    /// Will truncate output to 510 characters and then include CR (13) and LF (10) suffix as per RFC 2812
    pub fn serialize(&self) -> Vec<u8> {
        let mut ret_val: Vec<u8> = vec![];
        if self.source.is_some() {
            ret_val = [
                ":".as_bytes().to_vec(),
                self.source.as_ref().unwrap().as_bytes().to_vec(),
                " ".as_bytes().to_vec(),
            ]
            .concat();
        }

        let mut params = self.params.join(" ");
        if self.needs_colon() {
            let mut modified_params = self.params.clone();
            modified_params[self.params.len() - 1] =
                format!(":{}", modified_params[modified_params.len() - 1]);
            params = modified_params.join(" ");
        }

        ret_val = [
            ret_val,
            self.command.command_text().as_bytes().to_vec(),
            " ".as_bytes().to_vec(),
            params.into(),
        ]
        .concat();

        ret_val.truncate(510);

        ret_val = [ret_val, vec![CR], vec![LF]].concat();

        ret_val
    }
    /// From a u8 vector representing an IRC message will return a [`Message`], will not validate presence of CRLF but will strip them before processing. An optional client prefix can be provided to override or represent the source of the IRC message.
    ///
    /// # Errors
    ///
    /// This function will return an error if the provided message is not a valid IRC message as per RFC 2812, including presence of no data, invalid commands and missing mandatory parameters.
    pub fn parse(
        mut raw_input: Vec<u8>,
        source_client: Option<String>,
    ) -> Result<Self, MessageError> {
        if raw_input.len() < 1 {
            return Err(MessageError {
                detail: MessageErrorDetails::NoData,
            });
        }
        if raw_input[raw_input.len() - 1] == LF {
            raw_input.pop();
        }
        if raw_input[raw_input.len() - 1] == CR {
            raw_input.pop();
        }

        let split_message: Vec<Vec<u8>> = raw_input.into_iter().fold(Vec::new(), |mut acc, x| {
            if x == 32 || acc.is_empty() {
                acc.push(Vec::new());
            }
            if x != 32 {
                acc.last_mut().unwrap().push(x);
            }
            acc
        });

        let mut source = source_client.clone();

        let mut command_index = 0;
        if split_message[0][0] == 58 {
            command_index = 1;
            let parsed_source = match Message::parse_prefix(split_message[0].clone()) {
                Ok(x) => x,
                Err(y) => return Err(y),
            };
            source = source_client.or_else(|| Some(parsed_source));
        }

        if split_message.len() < command_index + 1 {
            return Err(MessageError {
                detail: MessageErrorDetails::NoCommand,
            });
        }

        let irc_command = match Message::parse_command(split_message[command_index].clone()) {
            Ok(x) => x,
            Err(y) => return Err(y),
        };

        let params = match irc_command.parse_params(split_message[command_index + 1..].to_vec()) {
            Ok(x) => x,
            Err(y) => return Err(y),
        };

        Ok(Message {
            source: source,
            command: irc_command,
            params: params
                .iter()
                .map(|p| String::from_utf8_lossy(p).into_owned())
                .collect(),
        })
    }

    fn parse_command(command_input: Vec<u8>) -> Result<IRCCommand, MessageError> {
        let raw_command = match String::from_utf8(command_input) {
            Ok(x) => x,
            Err(_) => {
                return Err(MessageError {
                    detail: MessageErrorDetails::FailedCommandParse,
                })
            }
        };

        match raw_command.as_str() {
            "NAMES" => return Ok(IRCCommand::NAMES),
            "NICK" => return Ok(IRCCommand::NICK),
            "PRIVMSG" => return Ok(IRCCommand::PRIVMSG),
            "001" => return Ok(IRCCommand::RPL_WELCOME),
            "353" => return Ok(IRCCommand::RPL_NAMREPLY),
            "366" => return Ok(IRCCommand::RPL_ENDOFNAMES),
            "PING" => return Ok(IRCCommand::PING),
            "PONG" => return Ok(IRCCommand::PONG),
            "USER" => return Ok(IRCCommand::USER),
            "QUIT" => return Ok(IRCCommand::QUIT),
            "NOTICE" => return Ok(IRCCommand::NOTICE),
            "MOTD" => return Ok(IRCCommand::MOTD),
            "LUSERS" => return Ok(IRCCommand::LUSERS),
            "WHOIS" => return Ok(IRCCommand::WHOIS),
            "002" => return Ok(IRCCommand::RPL_YOURHOST),
            "003" => return Ok(IRCCommand::RPL_CREATED),
            "004" => return Ok(IRCCommand::RPL_MYINFO),
            "251" => return Ok(IRCCommand::RPL_LUSERCLIENT),
            "252" => return Ok(IRCCommand::RPL_LUSEROP),
            "253" => return Ok(IRCCommand::RPL_LUSERUNKNOWN),
            "254" => return Ok(IRCCommand::RPL_LUSERCHANNELS),
            "255" => return Ok(IRCCommand::RPL_LUSERME),
            "311" => return Ok(IRCCommand::RPL_WHOISUSER),
            "312" => return Ok(IRCCommand::RPL_WHOISSERVER),
            "318" => return Ok(IRCCommand::RPL_ENDOFWHOIS),
            "431" => return Ok(IRCCommand::ERR_NONICKNAMEGIVEN),
            "433" => return Ok(IRCCommand::ERR_NICKNAMEINUSE),
            "462" => return Ok(IRCCommand::ERR_ALREADYREGISTRED),
            "461" => return Ok(IRCCommand::ERR_NEEDMOREPARAMS),
            "451" => return Ok(IRCCommand::ERR_NOTREGISTERED),
            "421" => return Ok(IRCCommand::ERR_UNKNOWNCOMMAND),
            "411" => return Ok(IRCCommand::ERR_NORECIPIENT),
            "412" => return Ok(IRCCommand::ERR_NOTEXTTOSEND),
            "401" => return Ok(IRCCommand::ERR_NOSUCHNICK),
            "422" => return Ok(IRCCommand::ERR_NOMOTD),
            _ => {
                return Err(MessageError {
                    detail: MessageErrorDetails::InvalidCommand,
                })
            }
        }
    }

    fn parse_prefix(prefix_input: Vec<u8>) -> Result<String, MessageError> {
        if prefix_input.len() < 2 {
            return Err(MessageError {
                detail: MessageErrorDetails::NoClient,
            });
        }

        if prefix_input[0] == 58 {
            match String::from_utf8(prefix_input.clone().split_off(1)) {
                Ok(x) => return Ok(x),
                Err(_) => {
                    return Err(MessageError {
                        detail: MessageErrorDetails::FailedPrefixParse,
                    });
                }
            }
        } else {
            return Err(MessageError {
                detail: MessageErrorDetails::NoPrefix,
            });
        }
    }

    fn needs_colon(&self) -> bool {
        match self.command {
            IRCCommand::USER => true,
            _ => false,
        }
    }
}

#[test]
fn test_valid_command() {
    let message = "NAMES".as_bytes().to_vec();
    let command = Message::parse_command(message);
    assert_eq!(command, Ok(IRCCommand::NAMES));
}

#[test]
fn test_invalid_command() {
    let message = "NAMES2".as_bytes().to_vec();
    let command = Message::parse_command(message);
    assert!(command.is_err());
}

#[test]
fn test_blank_command() {
    let message = "".as_bytes().to_vec();
    let command = Message::parse_command(message);
    assert!(command.is_err());
}

#[test]
fn test_valid_source() {
    let message = ":TestClient".as_bytes().to_vec();
    let source = Message::parse_prefix(message);
    let source_string = match source {
        Ok(x) => x,
        Err(_) => "None".to_string(),
    };
    assert_eq!(source_string, "TestClient");
}
#[test]
fn test_invalid_source() {
    let message = ":".as_bytes().to_vec();
    let source = Message::parse_prefix(message);
    let source_string = match source {
        Ok(x) => x,
        Err(y) => y.detail.error_text().to_string(),
    };
    assert_eq!(source_string, "No client identifier");
}
#[test]
fn test_empty_source() {
    let message = Vec::new();
    let source = Message::parse_prefix(message);
    let source_string = match source {
        Ok(x) => x,
        Err(y) => y.detail.error_text().to_string(),
    };
    assert_eq!(source_string, "No client identifier");
}

#[test]
fn test_format_source() {
    let message = "TestClient".as_bytes().to_vec();
    let source = Message::parse_prefix(message);
    let source_string = match source {
        Ok(x) => x,
        Err(y) => y.detail.error_text().to_string(),
    };
    assert_eq!(source_string, "Missing : character");
}

#[test]
fn test_serialize() {
    let message = Message {
        source: Some("Anon".to_string()),
        command: IRCCommand::NICK,
        params: vec!["nonA".to_string()],
    };
    let output = message.serialize();
    println!("{:?}", output);
    assert_eq!(output.len(), 17);
    assert_eq!(output[output.len() - 3], 65);

    let message = Message {
        source: None,
        command: IRCCommand::NICK,
        params: vec!["nonA".to_string()],
    };
    let output = message.serialize();
    println!("{:?}", output);
    assert_eq!(output.len(), 11);
    assert_eq!(output[output.len() - 3], 65);
}

#[test]
fn test_user() {
    let message = Message {
        source: None,
        command: IRCCommand::USER,
        params: vec![
            "Anon".to_string(),
            "0".to_string(),
            "*".to_string(),
            "Anon".to_string(),
        ],
    };
    println!("{:?}", message);
    let output = message.serialize();
    println!("{:?}", output);
    assert_eq!(output.len(), 21);
    assert_eq!(output[14], 58);
}