summaryrefslogtreecommitdiff
path: root/src/user_int.rs
blob: 4b6f4c80b5bc683e80082760fb34f6c2e2fe3ec7 (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
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
use std::net::TcpStream;
use std::io::{self,Write,BufWriter};
use std::sync::{Arc,Mutex};
use std::{thread,time};

use server_int::{Message,Server};
use ui::UI;

pub struct SessionBuilder {
    chan: String,
    nick: String,
}

impl SessionBuilder {
    pub fn new() -> SessionBuilder {
        SessionBuilder {
            chan: String::new(),
            nick: String::new(),
        }
    }

    pub fn chan(&mut self, chan: &str) -> &mut SessionBuilder {
        self.chan = chan.to_string();
        self
    }

    pub fn nick(&mut self, nick: &str) -> &mut SessionBuilder {
        self.nick = nick.to_string();
        self
    }

    pub fn finalize(&self) -> Session {
        Session {
            chan: self.chan.clone(),
            nick: self.nick.clone(),
            conn: None,
            ui: None,
        }
    }
}

#[derive(Debug)]
pub struct Session {
    pub chan: String,
    pub nick: String,
    conn: Option<TcpStream>,
    ui: Option<Arc<Mutex<UI>>>,
}

impl Session {
    pub fn attach(&mut self, server: &Server) ->
        io::Result<thread::JoinHandle<io::Result<Session>>> {
        let conn = if let Some(ref conn) = server.conn {
            conn.try_clone()?
        } else {
            return Err(io::Error::new(io::ErrorKind::NotConnected, "Server must be connected"));
        };
        self.conn = Some(conn);
        self.ui = server.ui.clone();
        let session = self.try_clone()?;
        Ok(thread::spawn(move || session.handle()))
    }

    pub fn handle(mut self) -> io::Result<Session> {
        let conn = if let Some(ref conn) = self.conn {
            conn.try_clone()?
        } else {
            return Err(io::Error::new(io::ErrorKind::NotConnected, "Must be attached"));
        };
        let mut writer = BufWriter::new(conn);
        loop {
            let buf = if let Some(ref ui) = self.ui {
                let mut ui = ui.lock().unwrap();
                ui.read_line()
            } else { None };

            if buf.is_none() {
                thread::sleep(time::Duration::from_millis(10));
                continue;
            }

            let buf = buf.unwrap();

            let message: Option<Message> = self.create_message(&buf);
            if message.is_none() {
                continue;
            }

            let message = message.unwrap();

            if let Some(ref ui) = self.ui {
                let mut ui = ui.lock().unwrap();
                ui.print_message(&message);
            }

            writer.write(message.to_string().as_bytes())?;
            writer.flush()?;

            if &message.command == "QUIT" {
                break;
            }

            /*
            if let Some(m) = self.create_message(&buf) {
                writer.write(m.to_string().as_bytes())?;
                writer.flush()?;
            }
            */
        }

        Ok(self)
    }

    pub fn create_message(&mut self, line: &str) -> Option<Message> {
        let mut line = line.to_string();
        if line.starts_with("/") {
            line.remove(0);
            let mut m = Message::from_str(&line);
            match m.command.as_str() {
                "NICK" => {
                    self.nick = m.params.get(0).unwrap_or(&String::new()).clone();
                    if let Some(ref ui) = self.ui {
                        let mut ui = ui.lock().unwrap();
                        ui.nick(&self.nick);
                    }
                    Some(m)
                },
                "BUFFER" => {
                    self.chan = m.params.get(0).unwrap_or(&String::new()).clone();
                    None
                },
                "JOIN" => {
                    self.chan = m.params.get(0).unwrap_or(&String::new()).clone();
                    Some(m)
                },
                "PART" => {
                    m.params.push(self.chan.clone());
                    self.chan = String::new();
                    Some(m)
                },
                "QUOTE" => {
                    m.command = m.params.remove(0);
                    Some(m)
                },
                "MSG" => {
                    m.command = "PRIVMSG".to_string();
                    m.params = vec![m.params[0].clone(),
                    m.params.iter().skip(1).fold(String::new(), |acc, x| {
                        let mut ret = String::new();
                        ret.push_str(&acc);
                        ret.push_str(&x);
                        ret.push(' ');
                        ret
                    })];
                    Some(m)
                },
                "" => None,
                _ =>  Some(m),
            }
        } else if &self.chan == "" {
            if let Some(ref ui) = self.ui {
                let mut ui = ui.lock().unwrap();
                ui.put_str("Not connected to any buffer\n");
            }
            None
        } else if &line == "" {
            None
        } else {
            let reply = Message {
                prefix: Some(self.nick.clone()),
                command: "PRIVMSG".to_string(),
                params: vec![self.chan.clone(), line.clone()],
            };
            Some(reply)
        }
    }

    pub fn try_clone(&self) -> io::Result<Session> {
        let conn = if let Some(ref conn) = self.conn {
            conn.try_clone()?
        } else {
            return Err(io::Error::new(io::ErrorKind::NotConnected, "Must be attached"));
        };
        Ok(Session {
            chan: self.chan.clone(),
            nick: self.nick.clone(),
            conn: Some(conn),
            ui: self.ui.clone(),
        })
    }
}