cowirc 0.2.0

Asychronous IRCv3 library for Rust
Documentation
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/*
 * This file is part of CowIRC.
 *
 * CowIRC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CowIRC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with CowIRC. If not, see <http://www.gnu.org/licenses/>.
 */

use crate::event_handler::IncomingIrcEventError;
use std::collections::HashMap;

/// Represents possible errors parsing an input.
#[derive(Debug)]
pub enum Error {
    /// Indicates no command can be found in the input.
    EmptyCommand,
    /// indicates no mandatory seperator was found in the input.
    NoSeparator,
    /// Indicates a tag value is missing a key in the input.
    MissingKey,
    /// Indicates a trailing semicolon for a tag string in the input.
    TrailingSemicolon,
    /// Indicates a parameter that is not the final one contains a space in the input.
    NonLastParamSpaces,
    /// Indicates that a parameter that is not the last one starts with a colon in the input.
    NonLastParamColon,
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EmptyCommand => write!(f, "Cannot parse command-less line!"),
            Self::NoSeparator => write!(f, "Cannot split line without separator!"),
            Self::MissingKey => write!(f, "Cannot parse tags with missing key!"),
            Self::TrailingSemicolon => write!(f, "Cannot parse tags with trailing semicolon!"),
            Self::NonLastParamSpaces => write!(f, "Non last params cannot have spaces!"),
            Self::NonLastParamColon => write!(f, "Non last params cannot start with colon!"),
        }
    }
}

/// Represent the source component of a valid IRC message.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Source {
    pub nickname: String,
    pub username: String,
    pub hostmask: String,
}

impl Source {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
    #[must_use]
    pub const fn from(nickname: String, username: String, hostmask: String) -> Self {
        Self {
            nickname,
            username,
            hostmask,
        }
    }
}

/// Represents a valid `IRCv3` compliant message.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Message {
    pub tags: HashMap<String, String>,
    pub source: Option<Source>,
    pub command: String,
    params: Vec<String>,
}

/// Escapes the required characters of a tag value.
///
/// # Arguments
///
/// * `value` - The IRC message tag value to be unescaped.
///
/// # Returns
///
/// * A string with the required characters unescaped.
///
/// # Examples
///
/// ```
/// use cowirc::parser::unescape_tag;
///
/// let escaped_value = r"\\:test\\s\\\\";
/// let unescaped_value = unescape_tag(escaped_value);
/// assert_eq!(unescaped_value, ";test \\\\");
/// ```
#[must_use]
pub fn unescape_tag(value: &str) -> String {
    value
        .replace("\\\\", "\\")
        .replace("\\:", ";")
        .replace("\\s", " ")
        .replace("\\r", "\r")
        .replace("\\n", "\n")
}

fn check_params(params: &Vec<String>) -> Result<(), Error> {
    for i in 0..params.len() - 1 {
        if let Some(param) = params.get(i) {
            if param.contains(' ') {
                return Err(Error::NonLastParamSpaces);
            } else if param.starts_with(':') {
                return Err(Error::NonLastParamColon);
            }
        }
    }
    Ok(())
}

impl Message {
    /// Creates a new instance of Message.
    ///
    /// # Arguments
    ///
    /// * `tags` - `HashMap`<String, String> containing the tags for the `IRCv3` message.
    /// * `source`- Option<Source> containing optionally an instance of the `Source` struct for the
    /// source component of the `IRCv3` message.
    /// * `command` - String containing the non-optional command for the `IRCv3` message.
    /// * `params` - Vec<String> containing the parameters for the `IRCv3` message.
    ///
    /// # Returns
    ///
    /// * `Result<Self, Error>` - A result containing either an instantiated Message struct, or on
    /// failure an error of type Error with more details.
    ///
    /// # Errors
    ///
    /// Will return `Error` if a parameter is invalid as defined by the `check_param` function.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cowirc::parser::{Message, Source};
    /// use std::collections::HashMap;
    ///
    /// let mut tags: HashMap<String, String> = HashMap::new();
    /// tags.insert(String::from("tag1"), String::from("value1"));
    /// tags.insert(String::from("tag2"), String::from("value2"));
    /// let source = Source { username: String::from("nick"), nickname: String::from("ident"), hostmask: String::from("host") };
    /// let command = String::from("PRIVMSG");
    /// let params = vec![String::from("#channel"), String::from("Hello, world!")];
    ///     let response = Message::new(tags, Some(source), command, params);
    ///     match response {
    ///         Ok(response) => println!("Constructed Message struct: {:?}", response),
    ///         Err(e) => eprintln!("error: could not construct Message struct: {e}"),
    ///     };
    /// ```
    pub fn new(
        tags: HashMap<String, String>,
        source: Option<Source>,
        command: String,
        params: Vec<String>,
    ) -> Result<Self, Error> {
        match check_params(&params) {
            Ok(()) => Ok(Self {
                tags,
                source,
                command,
                params,
            }),
            Err(e) => Err(e),
        }
    }

    /// Gets the value for the private `params` field.
    ///
    /// # Returns
    ///
    /// * `Vec<String>` - the current value of the params field in the struct.
    #[must_use]
    pub fn params(&self) -> Vec<String> {
        self.params.clone()
    }

    /// Builds an IRC message token from a `Message` struct.
    ///
    /// # Arguments
    ///
    /// * `message` - A `Message` struct containing the IRC message.
    ///
    /// # Returns
    ///
    /// * `Result<String, Error>` - A result containing either a valid IRC message, or
    /// on failure an error of type Error with more details.
    ///
    /// # Errors
    ///
    /// Will return `Error` if params are invalid as defined by `IRCv3`.
    ///
    /// # Examples
    ///
    /// ```
    /// use cowirc::parser::{Message, Source};
    /// use std::collections::HashMap;
    ///
    /// let mut tags: HashMap<String, String> = HashMap::new();
    /// tags.insert(String::from("tag1"), String::from("value1"));
    /// tags.insert(String::from("tag2"), String::from("value2"));
    ///
    /// let source = Some(Source {
    ///     nickname: String::from("nick"),
    ///     username: String::from("ident"),
    ///     hostmask: String::from("host"),
    /// });
    ///
    /// let command = String::from("PRIVMSG");
    /// let params = vec![String::from("#channel"), String::from("Hello, world!")];
    ///
    /// let message = Message::new(tags, source, command, params);
    ///
    /// match Message::build_token(message.unwrap()) {
    ///     Ok(irc_message) => {
    ///         println!("Valid IRC message: {irc_message}")
    ///     }
    ///     Err(e) => {
    ///         eprintln!("error: invalid IRC message struct provided: {e}")
    ///     }
    /// }
    /// ```
    pub fn build_token(message: Self) -> Result<String, Error> {
        let mut tags_str = Vec::new();
        let mut outs: Vec<String> = Vec::new();
        if !message.tags.is_empty() {
            for (key, value) in message.tags {
                if value.is_empty() {
                    tags_str.push(key.to_string());
                } else {
                    tags_str.push(format!("{}={}", key, unescape_tag(&value)));
                }
            }
            outs.push(format!("@{}", tags_str.join(";")));
        }
        if let Some(source) = message.source {
            outs.push(format!(
                ":{}!{}@{}",
                source.nickname, source.username, source.hostmask
            ));
        }
        outs.push(message.command);

        let mut params = message.params.clone();
        if let Some(last) = params.pop() {
            for param in &params {
                if param.contains(' ') {
                    return Err(Error::NonLastParamSpaces);
                } else if param.starts_with(':') {
                    return Err(Error::NonLastParamColon);
                }
            }
            outs.extend(params);

            let last = if last.is_empty() || last.contains(' ') || last.starts_with(':') {
                format!(":{last}")
            } else {
                last
            };
            outs.push(last);
        }
        Ok(outs.join(" "))
    }

    /// Retrieves a parameter at a specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the parameter to retrieve.
    ///
    /// # Returns
    ///
    /// * `Result<&str, IncomingIrcEventError>` - A result containing either a reference to the
    /// parameter if it exists or an error of type `IncomingIrcEventError` with more details.
    ///
    /// # Errors
    ///
    /// Will return `IncomingIrcEventError` if the parameter attempting to be accessed does not
    /// exist.
    ///
    /// # Examples
    ///
    /// ```
    /// use cowirc::Message;
    /// use std::collections::HashMap;
    /// use cowirc::parser::Source;
    ///
    /// let mut tags: HashMap<String, String> = HashMap::new();
    /// tags.insert(String::from("tag1"), String::from("value1"));
    /// tags.insert(String::from("tag2"), String::from("value2"));
    ///
    /// let source = Some(Source {
    ///     nickname: String::from("nick"),
    ///     username: String::from("ident"),
    ///     hostmask: String::from("host"),
    /// });
    ///
    /// let command = String::from("PRIVMSG");
    /// let params = vec![String::from("#channel"), String::from("Hello, world!")];
    ///
    /// let response = Message::new(tags, source, command, params);
    ///
    /// match response.unwrap().get_param(0) {
    ///     Ok(param) => {
    ///         println!("First parameter: {param}")
    ///     }
    ///     Err(e) => {
    ///         eprintln!("error: could not get first parameter: {e}")
    ///     }
    /// }
    /// ```
    pub fn get_param(&self, index: usize) -> Result<&str, IncomingIrcEventError> {
        self.params
            .get(index)
            .ok_or_else(|| IncomingIrcEventError::MissingParameter(index.to_string()))
            .map(std::string::String::as_str)
    }

    /// Parse an IRC message and return a struct containing the parsed message data.
    ///
    /// # Arguments
    ///
    /// * `response` - A string containing the IRC message to be parsed.
    ///
    /// # Returns
    ///
    /// * `Result<Self, Error>` - A result containing either the parsed message as a (`Message`)
    /// struct or on failure an error of type Error with more details.
    ///
    /// # Errors
    ///
    /// Will return `Error` if the provided input `response` is deemed invalid by the parser, as
    /// defined by `IRCv3`.
    ///
    /// # Examples
    ///
    /// ```
    /// use cowirc::parser::{Message, Source};
    /// use std::collections::HashMap;
    ///
    /// let response = "@tag1=value1;tag2=value2 :nick!ident@host PRIVMSG #channel :Hello, world!";
    /// match Message::from(response.to_string()) {
    ///     Ok(parsed_message) => {
    ///         let mut tags: HashMap<String, String> = HashMap::new();
    ///         tags.insert(String::from("tag1"), String::from("value1"));
    ///         tags.insert(String::from("tag2"), String::from("value2"));
    ///         let source = Some(Source {
    ///             nickname: String::from("nick"),
    ///             username: String::from("ident"),
    ///             hostmask: String::from("host"),
    ///         });
    ///         let command = String::from("PRIVMSG");
    ///         let params = vec![String::from("#channel"), String::from("Hello, world!")];
    ///
    ///         let expected_message = Message::new(
    ///             tags,
    ///             source,
    ///             command,
    ///             params,
    ///         );
    ///
    ///         assert_eq!(parsed_message, expected_message.unwrap());
    ///     }
    ///     Err(e) => {
    ///         eprintln!("error: response \"{response}\" is invalid: {e}")
    ///     }
    /// }
    /// ```
    pub fn from(mut response: String) -> Result<Self, Error> {
        let mut params: Vec<String> = vec![];

        let line: String;
        let mut trailing: Option<String> = None;
        let mut nickname: String = String::new();
        let mut username: String = String::new();
        let mut hostmask: String = String::new();
        let mut tags: HashMap<String, String> = HashMap::new();

        // Tag Parsing
        // https://Ircv3.net/specs/extensions/message-tags.html
        if response.starts_with('@') {
            let mut tokens = response.splitn(2, ' ');
            let tags_split: String;
            if let (Some(head), Some(tail)) = (tokens.next(), tokens.next()) {
                tags_split = head.to_string();
                response = tail.to_string();
            } else {
                return Err(Error::EmptyCommand);
            }
            let parts = tags_split[1..].split(';');
            for part in parts {
                if part.is_empty() {
                    return Err(Error::TrailingSemicolon);
                }
                let (key, value) = if let Some(index) = part.find('=') {
                    let (key, value) = part.split_at(index);
                    if key.is_empty() {
                        return Err(Error::MissingKey);
                    }
                    (key, &value[1..])
                } else {
                    (part, "")
                };
                tags.insert(key.to_string(), unescape_tag(value));
            }
        }

        let mut tokens = response.splitn(2, " :");

        if let (Some(head), Some(tail)) = (tokens.next(), tokens.next()) {
            line = head.to_string();
            trailing = Some(tail.to_string());
        } else {
            line = response;
        }

        for sub in line.split(' ') {
            let sub = sub.to_string();
            if !sub.is_empty() {
                params.push(sub);
            }
        }

        if params.is_empty() {
            return Err(Error::EmptyCommand); // Error if command-less line
        }

        if params[0].as_bytes()[0] == b':' {
            params[0].remove(0); // Remove the first char of the string in the first index of params

            let source: String = params[0].clone(); // Set source to string in first index of params
            params.remove(0); // Remove the source from params

            if params.is_empty() {
                return Err(Error::EmptyCommand); // Error if command-less line
            }

            let mut tokens = source.splitn(2, '@');

            if let (Some(head), Some(tail)) = (tokens.next(), tokens.next()) {
                username = head.to_string();
                hostmask = tail.to_string();
            } else {
                username = source;
            }

            let mut tokens = username.splitn(2, '!');

            if let (Some(head), Some(tail)) = (tokens.next(), tokens.next()) {
                nickname = head.to_string();
                username = tail.to_string();
            } else {
                nickname = username.clone();
                username.clear();
            }
        }

        let command = params[0].clone();
        params.remove(0);

        if let Some(trailing) = trailing {
            params.push(trailing);
        }

        Ok(Self {
            tags,
            source: Some(Source {
                nickname,
                username,
                hostmask,
            }),
            command,
            params,
        })
    }
}