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
//! A simple IRC crate written in rust
//! ```no_run
//! use circe::*;
//! fn main() -> Result<(), std::io::Error> {
//!     let config = Config::from_toml("config.toml")?;
//!     let mut client = Client::new(config)?;
//!     client.identify()?;
//!
//!     loop {
//!         if let Ok(ref command) = client.read() {
//!             if let Command::OTHER(line) = command {
//!                 print!("{}", line);
//!             }
//!             if let Command::PRIVMSG(channel, message) = command {
//!                println!("PRIVMSG received: {} {}", channel, message);
//!             }
//!         }    
//!         # break;
//!     }
//!     
//!     # Ok(())
//! }

#![warn(missing_docs)]
use std::borrow::Cow;
use std::fs::File;
use std::io::{Error, Read, Write};
use std::net::TcpStream;
use std::path::Path;

use serde_derive::Deserialize;

/// An IRC client
pub struct Client {
    config: Config,
    stream: TcpStream,
}

/// Config for the IRC client
#[derive(Clone, Deserialize, Default)]
pub struct Config {
    channels: Box<[String]>,
    host: String,
    mode: Option<String>,
    nickname: Option<String>,
    port: u16,
    username: String,
}

#[doc(hidden)]
#[derive(Debug)]
pub enum CapMode {
    LS,
    END,
}

/// IRC commands
#[derive(Debug)]
pub enum Command {
    #[doc(hidden)]
    CAP(CapMode),
    /// Joins a channel
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.write_command(Command::JOIN("#main".to_string()))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    JOIN(
        /// Channel
        String,
    ),
    /// Sets the mode of the user
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.write_command(Command::MODE("#main".to_string(), Some("+B".to_string())))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    /// If the MODE is not given (e.g. None), then the client will send "MODE target"
    MODE(
        /// Channel
        String,
        /// Mode
        Option<String>,
    ),
    #[doc(hidden)]
    NICK(String),
    /// Everything that is not a command
    OTHER(String),
    /// Ping another user or the server
    PING(
        /// target
        String,
    ),
    #[doc(hidden)]
    PONG(String),
    /// Sends a message in a channel
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.write_command(Command::PRIVMSG("#main".to_string(), "This is an example message".to_string()))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    PRIVMSG(
        /// Channel
        String,
        /// Message
        String,
    ),
    #[doc(hidden)]
    USER(String, String, String, String),
}

impl Command {
    fn from_str(s: &str) -> Self {
        let new = s.trim();

        if new.starts_with("PING") {
            let command: String = String::from(new.split_whitespace().collect::<Vec<&str>>()[1]);
            return Self::PING(command);
        } else if new.contains("PRIVMSG") {
            let parts: Vec<&str> = new.split_whitespace().collect();

            let target = parts[2];
            let mut builder = String::new();
            for part in parts[3..].to_vec() {
                builder.push_str(&format!("{} ", part));
            }

            return Self::PRIVMSG(target.to_string(), (&builder[1..]).to_string());
        }

        Self::OTHER(new.to_string())
    }
}

impl Client {
    /// Creates a new client with a given config
    /// ```no_run
    /// # use circe::*;
    /// # let config = Config::from_toml("config.toml")?;
    /// let mut client = Client::new(config)?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// Errors if the client could not connect to the given host.
    pub fn new(config: Config) -> Result<Self, Error> {
        let stream = TcpStream::connect(format!("{}:{}", config.host, config.port))?;
        Ok(Self { stream, config })
    }

    /// Identify user and join the specified channels
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.identify()?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// Errors if the client could not write to the stream.
    pub fn identify(&mut self) -> Result<(), Error> {
        self.write_command(Command::CAP(CapMode::END))?;
        self.write_command(Command::USER(
            self.config.username.clone(),
            "*".into(),
            "*".into(),
            self.config.username.clone(),
        ))?;

        if let Some(nick) = self.config.nickname.clone() {
            self.write_command(Command::NICK(nick))?;
        } else {
            self.write_command(Command::NICK(self.config.username.clone()))?;
        }

        loop {
            if let Ok(ref command) = self.read() {
                match command {
                    Command::PING(code) => self.write_command(Command::PONG(code.to_string()))?,
                    Command::OTHER(line) => {
                        if line.contains("001") {
                            break;
                        }
                    }
                    _ => {}
                }
            }
        }

        let config = self.config.clone();
        self.write_command(Command::MODE(config.username, config.mode))?;
        for channel in config.channels.iter() {
            self.write_command(Command::JOIN(channel.to_string()))?;
        }

        Ok(())
    }

    fn read_string(&mut self) -> Option<String> {
        let mut buffer = [0u8; 512];

        match self.stream.read(&mut buffer) {
            Ok(_) => {}
            Err(_) => return None,
        };

        Some(String::from_utf8_lossy(&buffer).into())
    }

    /// Read data coming from the IRC as a [`Command`]
    /// ```no_run
    /// # use circe::*;
    /// # fn main() -> Result<(), std::io::Error> {
    /// # let config = Config::from_toml("config.toml")?;
    /// # let mut client = Client::new(config)?;
    /// if let Ok(ref command) = client.read() {
    ///     if let Command::OTHER(line) = command {
    ///         print!("{}", line);
    ///     }
    /// }
    /// # Ok::<(), std::io::Error>(())
    /// # }
    /// ```
    ///
    /// Errors if there are no new messages. This should not be taken as an actual Error, because nothing went wrong.
    pub fn read(&mut self) -> Result<Command, ()> {
        if let Some(string) = self.read_string() {
            return Ok(Command::from_str(&string));
        }

        Err(())
    }

    fn write(&mut self, data: &str) -> Result<(), Error> {
        let formatted = {
            let new = format!("{}\r\n", data);

            Cow::Owned(new) as Cow<str>
        };
        self.stream.write(formatted.as_bytes())?;

        Ok(())
    }

    /// Send a [`Command`] to the IRC
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.write_command(Command::PRIVMSG("#main".to_string(), "Hello".to_string()))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// Errors if the stream could not write.
    pub fn write_command(&mut self, command: Command) -> Result<(), Error> {
        use Command::*;
        let computed = match command {
            CAP(mode) => {
                use CapMode::*;
                Cow::Borrowed(match mode {
                    LS => "CAP LS 302",
                    END => "CAP END",
                }) as Cow<str>
            }
            JOIN(channel) => {
                let formatted = format!("JOIN {}", channel);
                Cow::Owned(formatted) as Cow<str>
            }
            NICK(nickname) => {
                let formatted = format!("NICK {}", nickname);
                Cow::Owned(formatted) as Cow<str>
            }
            MODE(target, mode) => {
                let formatted = {
                    if let Some(mode) = mode {
                        format!("MODE {} {}", target, mode)
                    } else {
                        format!("MODE {}", target)
                    }
                };

                Cow::Owned(formatted) as Cow<str>
            }
            OTHER(_) => {
                return Err(Error::new(
                    std::io::ErrorKind::Other,
                    "Cannot write commands of type OTHER",
                ));
            }
            PING(code) => {
                let formatted = format!("PING {}", code);
                Cow::Owned(formatted) as Cow<str>
            }
            PONG(code) => {
                let formatted = format!("PONG {}", code);
                Cow::Owned(formatted) as Cow<str>
            }
            PRIVMSG(target, message) => {
                let formatted = format!("PRIVMSG {} {}", target, message);
                Cow::Owned(formatted) as Cow<str>
            }
            USER(username, s1, s2, realname) => {
                let formatted = format!("USER {} {} {} :{}", username, s1, s2, realname);
                Cow::Owned(formatted) as Cow<str>
            }
        };

        self.write(&computed)?;
        Ok(())
    }

    // Utility functions!

    /// Helper function for sending PRIVMSGs.
    /// This makes
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.send_privmsg("#main", "Hello")?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// equivalent to
    ///
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.write_command(Command::PRIVMSG("#main".to_string(), "Hello".to_string()))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn send_privmsg(&mut self, channel: &str, message: &str) -> Result<(), Error> {
        self.write_command(Command::PRIVMSG(channel.to_string(), message.to_string()))?;
        Ok(())
    }

    /// Helper function for sending JOINs.
    /// This makes
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.send_join("#main")?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// equivalent to
    ///
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.write_command(Command::JOIN("#main".to_string()))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn send_join(&mut self, channel: &str) -> Result<(), Error> {
        self.write_command(Command::JOIN(channel.to_string()))?;
        Ok(())
    }

    /// Helper function for sending MODEs.
    /// This makes
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.send_mode("test", Some("+B"))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// equivalent to
    ///
    /// ```no_run
    /// # use circe::*;
    /// # let mut client = Client::new(Config::from_toml("config.toml")?)?;
    /// client.write_command(Command::MODE("test".to_string(), Some("+B".to_string())))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn send_mode(&mut self, target: &str, mode: Option<&str>) -> Result<(), Error> {
        if let Some(mode) = mode {
            self.write_command(Command::MODE(target.to_string(), Some(mode.to_string())))?;
        } else {
            self.write_command(Command::MODE(target.to_string(), None))?;
        }
        Ok(())
    }
}

impl Config {
    /// Create a new config for the client<br>
    /// <br>
    /// channels: Channels to join on the IRC<br>
    /// host: IP or domain of the IRC server<br>
    /// mode: Mode to join the IRC with (optional)<br>
    /// nickname: Nickname to join the IRC with (optional, defaults to the given username)<br>
    /// port: Port of the IRC server<br>
    /// username: Username to join the IRC with<br>
    /// ```rust
    /// # use circe::*;
    /// let config = Config::new(
    ///    Box::new(["#main".to_string(), "#main2".to_string()]),
    ///    "192.168.178.100",
    ///    Some("+B".to_string()),
    ///    Some("IRSC".to_string()),
    ///    6667,
    ///    "IRSC",
    /// );
    /// ```
    pub fn new(
        channels: Box<[String]>,
        host: &str,
        mode: Option<String>,
        nickname: Option<String>,
        port: u16,
        username: &str,
    ) -> Self {
        Self {
            channels,
            host: host.into(),
            mode,
            nickname,
            port,
            username: username.into(),
        }
    }

    /// Create a config from a toml file
    /// ```no_run
    /// # use circe::*;
    /// let config = Config::from_toml("config.toml")?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// ```toml
    /// channels = ["#main", "#main2"]
    /// host = "192.168.178.100"
    /// mode = "+B"
    /// nickname = "IRSC"
    /// port = 6667
    /// username = "IRSC"
    /// ```
    ///
    /// Returns an Error if the file cannot be opened or if the TOML is invalid
    pub fn from_toml<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
        let mut file = File::open(&path)?;
        let mut data = String::new();
        file.read_to_string(&mut data)?;

        toml::from_str(&data).map_err(|e| {
            use std::io::ErrorKind;
            Error::new(ErrorKind::Other, format!("Invalid TOML: {}", e))
        })
    }
}