aboutsummaryrefslogtreecommitdiff
path: root/src/server.rs
blob: 4c4479ab1d461f2b71900fea3b3805f0a8922a8f (plain)
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
use std::io::{
    BufferedReader,
    TcpStream,
    IoError
};

use std::sync::Arc;
use std::sync::Mutex;

use std::borrow::ToOwned;

use callback::Callback;
use event;
use event::Event;

#[deriving(Show, PartialEq, Eq, Clone)]
pub enum Failure {
    AlreadyConnected,
    NotConnected,
    Io(IoError)
}

#[deriving(Clone)]
pub struct Server {
    stream: Arc<Mutex<Option<TcpStream>>>,
    pub events: Arc<Mutex<Callback<(Server, Event)>>>,
}

impl Server {
    pub fn new() -> Server {
        Server {
            stream: Arc::new(Mutex::new(None)),
            events: {
                let mut c = Callback::new();
                c.register(&(Server::handle_event as fn((Server,Event))));
                Arc::new(Mutex::new(c))
            }
        }
    }

    fn handle_event(arg: (Server, Event)) {
        let (mut server, event) = arg;
        match event.command[] {
            event::PING => {
                server.sendraw(format!("PONG {}", event.content).as_slice(), true).unwrap();
            }
            _ => ()
        }
    }

    pub fn connect(&mut self, host: String, port: u16) -> Result<(), Failure> {
        let mut s = self.stream.lock();
        match *s { Some(_) => return Err(Failure::AlreadyConnected), _ => () };
        *s = match TcpStream::connect((host.as_slice(), port)) {
            Ok(tcp) => Some(tcp),
            Err(e) => return Err(Failure::Io(e))
        };

        Ok(())
    }

    #[inline]
    fn sendraw(&mut self, s: &str, newline: bool) -> Result<(), Failure> {
        info!("OUT: {}", s);
        let mut locked_stream = self.stream.lock();
        if locked_stream.is_some() {
            locked_stream.as_mut().map(|stream| {
                match stream.write_str(s) {
                    Ok(_) => match { if newline { stream.write_str("\r\n") } else { Ok(()) } } {
                        Ok(_) =>  match stream.flush() {
                            Ok(_) => Ok(()),
                            Err(e) => return Err(Failure::Io(e))
                        },
                        Err(e) => return Err(Failure::Io(e))
                    },
                    Err(e) => return Err(Failure::Io(e))
                }
            }).unwrap()
        } else {
            Err(Failure::NotConnected)
        }
    }

    pub fn join(&mut self, channel: &str) -> Result<(), Failure> {
        self.sendraw(format!("JOIN {}", channel).as_slice(), true)
    }

    pub fn nick(&mut self, nick: &str) -> Result<(), Failure> {
        self.sendraw(format!("NICK {}", nick).as_slice(), true)
    }

    pub fn user(&mut self, username: &str, hostname: &str, servername: &str, realname: &str) -> Result<(), Failure> {
        self.sendraw(format!("USER {} {} {} :{}", username, hostname, servername, realname).as_slice(), true)
    }

    pub fn password(&mut self, password: &str) -> Result<(), Failure> {
        self.sendraw(format!("PASS {}", password).as_slice(), true)
    }

    pub fn msg(&mut self, target: &str, message: &str) -> Result<(), Failure> {
        self.sendraw(format!("PRIVMSG {} :{}", target, message).as_slice(), true)
    }

    pub fn listen(&mut self) -> Result<(), Failure> {
        let stream = {
            let lock = self.stream.lock();
            match *lock {
                Some(ref s) => s.clone(),
                None => return Err(Failure::NotConnected)
            }
        };

        let mut reader = BufferedReader::new(stream);
        loop {
            let line = reader.read_line().unwrap();
            let mut parts = line.as_slice().split(' ').collect::<Vec<&str>>();

            info!("IN: {}", line);

            if parts.len() == 0 {
                continue;
            }

            // if message has a prefix
            let prefix = if parts[0].chars().next().unwrap() == ':' {
                parts.remove(0).unwrap()
            } else { "" };

            let cmd = parts.remove(0).unwrap();
            let event = Event {
                prefix: prefix.to_owned(),
                command: cmd.to_owned(),
                content: parts.into_iter().map(|s| s.to_owned()).collect()
            };

            self.events.lock().fire(&(self.clone(), event));
        }
    }
}