summaryrefslogtreecommitdiffstats
path: root/src/client.rs
blob: 0e7407f69e184134157cf62ce6c42faa2c841087 (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
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
use std::{io, str};
use std::collections::hashmap::HashMap;

use constants::{MessageType, Nick, Pass, Ping, Pong, User};
use message::Message;

type Callback<'a, 'b> = Box<Fn<(&'a mut Client<'a, 'b>, &'b Message), ()> + 'static>;

#[deriving(PartialEq, Eq, Hash, Clone)]
pub enum CallbackEvent {
    MessageEvent(MessageType),
    AnyMessageEvent,
    // XXX timer? connect/disconnect?
}

// XXX these lifetime parameters make no sense at all, but appear to be
// necessary for now...
pub struct ClientBuilder<'a, 'b> {
    nick: String,
    pass: Option<String>,
    realname: String,
    username: String,

    hostname: Option<String>,

    servername: String,
    port: u16,

    callbacks: HashMap<CallbackEvent, Vec<Callback<'a, 'b>>>,
}

pub struct Client<'a, 'b> {
    conn: io::BufferedStream<io::TcpStream>,
    callbacks: HashMap<CallbackEvent, Vec<Callback<'a, 'b>>>,
}

impl<'a, 'b> ClientBuilder<'a, 'b> {
    pub fn new (nick: &str, servername: &str) -> ClientBuilder<'a, 'b> {
        let mut callbacks = HashMap::new();

        callbacks.insert(
            MessageEvent(Ping),
            vec![
                box () (|&: client: &mut Client, m: &Message| {
                    client.write(Message::new(None, Pong, m.params().clone()));
                }) as Callback
            ]
        );

        ClientBuilder {
            nick: nick.to_string(),
            pass: None,
            realname: nick.to_string(),
            username: nick.to_string(),

            hostname: None,

            servername: servername.to_string(),
            port: 6667,

            callbacks: callbacks,
        }
    }

    pub fn set_pass (&mut self, pass: &str) -> &mut ClientBuilder<'a, 'b> {
        self.pass = Some(pass.to_string());
        self
    }

    pub fn set_username (&mut self, username: &str) -> &mut ClientBuilder<'a, 'b> {
        self.username = username.to_string();
        self
    }

    pub fn set_realname (&mut self, realname: &str) -> &mut ClientBuilder<'a, 'b> {
        self.realname = realname.to_string();
        self
    }

    pub fn set_hostname (&mut self, hostname: &str) -> &mut ClientBuilder<'a, 'b> {
        self.hostname = Some(hostname.to_string());
        self
    }

    pub fn set_port (&mut self, port: u16) -> &mut ClientBuilder<'a, 'b> {
        self.port = port;
        self
    }

    pub fn remove_all_callbacks (&mut self) -> &mut ClientBuilder<'a, 'b> {
        self.callbacks.clear();
        self
    }

    pub fn add_callback (&mut self, cb_type: CallbackEvent, cb: Callback<'a, 'b>) -> &mut ClientBuilder<'a, 'b> {
        self.callbacks.find_or_insert(cb_type.clone(), vec![]);
        self.callbacks.get_mut(&cb_type).push(cb);
        self
    }

    pub fn connect (self) -> Client<'a, 'b> {
        let nick = self.nick.clone();
        let pass = self.pass.clone();
        let hostname = match self.hostname {
            Some(ref host) => host.clone(),
            None => {
                // XXX get the name of the local end of the connection
                "localhost".to_string()
            },
        };
        let username = self.username.clone();
        let servername = self.servername.clone();
        let realname = self.realname.clone();

        let mut client = self.connect_raw();

        match pass {
            Some(pass) => {
                client.write(Message::new(None, Pass, vec![pass]));
            },
            None => {},
        }

        client.write(Message::new(None, Nick, vec![nick]));

        client.write(
            Message::new(
                None, User, vec![ username, hostname, servername, realname ],
            )
        );
        client
    }

    pub fn connect_raw (self) -> Client<'a, 'b> {
        let mut stream = io::TcpStream::connect(self.servername.as_slice(), self.port);
        Client {
            conn: io::BufferedStream::new(stream.unwrap()),
            callbacks: self.callbacks,
        }
    }
}

impl<'a, 'b> Client<'a, 'b> {
    pub fn read (&mut self) -> Message {
        // \n isn't valid inside a message, so this should be fine. if the \n
        // we find isn't preceded by a \r, this will be caught by the message
        // parser.
        let buf = self.conn.read_until(b'\n');
        // XXX handle different encodings
        // XXX proper error handling
        Message::parse(str::from_utf8(buf.unwrap().as_slice()).unwrap()).unwrap()
    }

    pub fn write (&mut self, msg: Message) {
        msg.write_protocol_string(&mut self.conn);
    }

    pub fn run_loop (&'a mut self) {
        loop {
            let res = self.read();
            match self.callbacks.find(&AnyMessageEvent) {
                Some(cbs) => {
                    for cb in cbs.iter() {
                        (*cb).call((self, &res));
                    }
                },
                None => {},
            }
            match self.callbacks.find(&MessageEvent(res.message_type().clone())) {
                Some(cbs) => {
                    for cb in cbs.iter() {
                        (*cb).call((self, &res));
                    }
                },
                None => {},
            }
        }
    }
}