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
use chrono::Local;
use crate::player::PlayerState;
use rocket::response::NamedFile;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::collections::VecDeque;
use std::fmt::{self, Debug, Formatter};
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::vec::Vec;
use std::{io, thread};
use ws::{CloseCode, Handler, Handshake, Message, Result};

pub trait Communication {
    // mut required for updating  FileSystemCommunication
    // WebSocketCommunication doesn't have mutability issue since everything is behind Arc Mutex
    fn read_message(&mut self) -> (u32, String);
    // Send message as THRUSTY
    fn send_message(&self, token: &u32, message: &str, state: &PlayerState);
    // Send message from a user
    fn send_message_from(&self, token: &u32, from: &str, bg: &str, fg: &str, message: &str, level: i32);
    fn send_messages(&self, token: &u32, messages: &Vec<String>, state: &PlayerState);
    fn disconnect(&mut self, token: &u32);

    // Yeah this is the only way I could easily get ip_address, not sure if I want to invest time into some generic route
    fn get_identifier(&self, token: &u32) -> String;
}

impl Debug for dyn Communication {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Debug required for RefCell")
    }
}

pub struct ChannelCommunication {
    send: mpsc::Sender<(u32, String)>,
    read: mpsc::Receiver<(u32, String)>,
    to_send: Option<mpsc::Sender<(u32, String)>>,
    messages: HashMap<u32, Vec<String>>,
    // expected is a counter that is incremented when a message is sent and decremented when a message is read
    // This is to help manage messages that could take a long time to process, e.g. DB inducing commands
    // It isn't perfect, as there are numerous examples of asynchronous messages that can be received, but it helps!!!
    expected: i32,
    can_log: bool,
}

impl ChannelCommunication {
    pub fn new(can_log: bool) -> ChannelCommunication {
        let (send, read) = mpsc::channel();
        ChannelCommunication {
            send,
            read,
            to_send: None,
            messages: HashMap::new(),
            can_log,
            expected: 0,
        }
    }

    pub fn bind(left: &mut ChannelCommunication, right: &mut ChannelCommunication) {
        right.to_send = Some(left.send.clone());
        left.to_send = Some(right.send.clone());
    }

    fn add_message(&mut self, token: u32, msg: String) {
        if !self.messages.contains_key(&token) {
            self.messages.insert(token, Vec::new());
        }
        let message = self.messages.get_mut(&token).unwrap();
        message.push(msg.clone());
    }

    pub fn read_all(&mut self) {
        while self.expected > 0 {
            // Pause for more messages
            thread::sleep(Duration::from_millis(500));

            // Keep on reading while you can and add messages
            while let Ok((token, msg)) = self.read.try_recv() {
                self.add_message(token.clone(), msg.clone());
                if self.can_log {
                    println!("client|{}|{}{}|{}", Local::now(), ">", &token, &msg);
                }
                self.expected -= 1;
            }
        }
    }

    pub fn last(&self, token: u32) -> String {
        let msg = self
            .messages
            .get(&token)
            .expect("Token does not exist for last")
            .last()
            .expect("Messages does not have last element");
        let json: Value = serde_json::from_str(&*msg).expect("Not valid JSON");
        let msg = json["message"]
            .as_str()
            .expect("Message is not string")
            .to_string();
        msg
    }

    pub fn last_bg(&self, token: u32) -> String {
        let msg = self
            .messages
            .get(&token)
            .expect("Token does not exist for last")
            .last()
            .expect("Messages does not have last element");
        let json: Value = serde_json::from_str(&*msg).expect("Not valid JSON");
        let bg = json["bg"]
            .as_str()
            .expect("Message is not string")
            .to_string();
        bg
    }

    pub fn last_fg(&self, token: u32) -> String {
        let msg = self
            .messages
            .get(&token)
            .expect("Token does not exist for last")
            .last()
            .expect("Messages does not have last element");
        let json: Value = serde_json::from_str(&*msg).expect("Not valid JSON");
        let fg = json["fg"]
            .as_str()
            .expect("Message is not string")
            .to_string();
        fg
    }

    pub fn last_from(&self, token: u32) -> String {
        let msg = self
            .messages
            .get(&token)
            .expect("Token does not exist for last")
            .last()
            .expect("Messages does not have last element");
        let json: Value = serde_json::from_str(&*msg).expect("Not valid JSON");
        let from = json["from"]
            .as_str()
            .expect("Message is not string")
            .to_string();
        from
    }

    pub fn last_state(&self, token: u32) -> String {
        let msg = self
            .messages
            .get(&token)
            .expect("Token does not exist for last")
            .last()
            .expect("Messages does not have last element");
        let json: Value = serde_json::from_str(&*msg).expect("Not valid JSON");
        let msg = json["state"]
            .as_str()
            .expect("State is not string")
            .to_string();
        msg
    }

    // Since THRUSTS are randomized, we aren't really sure how many THRUSTS we need
    // This will take care of default possibilities...
    pub fn thrust(&mut self, token: u32) {
        self.send(token.clone(), ".t 1");
        self.send(token.clone(), ".t 1 1");
        self.send(token.clone(), ".t 1 1 1");
        self.send(token.clone(), ".t 1 1 1 1");
        self.send(token.clone(), ".t 1 1 1 1 1");
    }

    pub fn send(&mut self, token: u32, msg: &str) {
        // It doesn't matter what state this send() function provides
        // This is used by a client to send messages to the server
        self.send_message(&token, msg, &PlayerState::ChooseName);
        if self.can_log {
            println!("client|{}|{}{}|{}", Local::now(), &token, ">", &msg);
        }
        // read_all() may be more than send
        // this can occur if messages have been asynchronously sent to the client
        if self.expected < 0 {
            self.expected = 0;
        }
        self.expected += 1;
    }
}

impl Communication for ChannelCommunication {
    fn read_message(&mut self) -> (u32, String) {
        let (token, msg) = self.read.recv().expect("Failed to send message.");
        let json: Value = serde_json::from_str(&*msg).expect("Not valid JSON");
        let msg = json["message"]
            .as_str()
            .expect("Received message is not string")
            .to_string();
        (token, msg)
    }

    fn send_message(&self, token: &u32, message: &str, state: &PlayerState) {
        let msg = json!({
            "bg": "000",
            "fg": "b7410e",
            "from": "THRUSTY",
            "message": message,
            "state": state.to_string()
        })
        .to_string();
        self.to_send
            .as_ref()
            .expect("to_send not set")
            .send((token.clone(), msg))
            .expect("Failed to send message.");
    }

    fn send_message_from(&self, token: &u32, from: &str, bg: &str, fg: &str, message: &str, level: i32) {
        let msg = json!({
            "bg": bg,
            "fg": fg,
            "from": from,
            "message": message,
			"level": level
        })
        .to_string();
        self.to_send
            .as_ref()
            .expect("to_send not set")
            .send((token.clone(), msg))
            .expect("Failed to send message.");
    }

    fn send_messages(&self, token: &u32, messages: &Vec<String>, state: &PlayerState) {
        let message = messages.join("<br/>");
        self.send_message(token, &message, state);
    }

    fn get_identifier(&self, token: &u32) -> String {
        token.to_string()
    }

    fn disconnect(&mut self, _token: &u32) {
        self.to_send = None;
    }
}

// Returns main site file
#[get("/")]
fn index() -> io::Result<NamedFile> {
    NamedFile::open("../frontend/build/index.html")
}

// Allows access to static folder for grabbing CSS/JavaScript files
#[get("/<file..>")]
fn file(file: PathBuf) -> Option<NamedFile> {
    NamedFile::open(Path::new("../frontend/build/").join(file)).ok()
}

// Specifies handler for processing an incoming websocket connection
struct WebSocketListener {
    out: ws::Sender,
    connections: Arc<Mutex<HashMap<u32, (String, ws::Sender)>>>,
    send: mpsc::Sender<(u32, String)>,
    uuid: u32,
}

impl Handler for WebSocketListener {
    // Adds new connection to global connections
    fn on_open(&mut self, handshake: Handshake) -> Result<()> {
        let mut ip_addr = String::new();
        if let Ok(remote_addr) = handshake.remote_addr() {
            if let Some(remote_addr) = remote_addr {
                ip_addr = remote_addr
            }
        }

        let mut connections_lock = self.connections.lock().unwrap();
        connections_lock.insert(self.uuid, (ip_addr, self.out.clone()));
        Ok(())
    }

    // Adds message to queue for processing
    fn on_message(&mut self, msg: Message) -> Result<()> {
        self.send
            .send((self.uuid, msg.to_string()))
            .expect("Unable to send on message");
        Ok(())
    }

    // Notifies of disconnected client
    fn on_close(&mut self, code: CloseCode, reason: &str) {
        let mut connections_lock = self.connections.lock().unwrap();
        connections_lock.remove(&self.uuid).unwrap();

        match code {
            CloseCode::Normal => self
                .send
                .send((
                    self.uuid,
                    format!(".disconnect CloseCode::Normal {}", reason),
                ))
                .expect("Unable to sent disconnect Normal"),

            CloseCode::Away => self
                .send
                .send((self.uuid, format!(".disconnect CloseCode::Away {}", reason)))
                .expect("Unable to send disconnect Away"),
            _ => self
                .send
                .send((self.uuid, format!(".disconnect Error {}", reason)))
                .expect("Unable to send disconnect Error"),
        };
    }
}

// Main Networking component that public can use
#[derive(Debug)]
pub struct WebSocketCommunication {
    commands: Arc<Mutex<VecDeque<(u32, String)>>>,
    connections: Arc<Mutex<HashMap<u32, (String, ws::Sender)>>>,
    send: mpsc::Sender<(u32, String)>,
    recv: mpsc::Receiver<(u32, String)>,
    uuid: Arc<Mutex<u32>>,
}

impl WebSocketCommunication {
    pub fn new() -> WebSocketCommunication {
        let (sender, receiver) = std::sync::mpsc::channel();
        let communication = WebSocketCommunication {
            commands: Arc::new(Mutex::new(VecDeque::new())),
            connections: Arc::new(Mutex::new(HashMap::new())),
            send: sender,
            recv: receiver,
            // Start at 1 so endless can be 0
            uuid: Arc::new(Mutex::new(1)),
        };
        communication.spawn();
        communication
    }

    // Spawn threads for web server use
    fn spawn(&self) {
        // Only ` rocket on development build
        // Production will have NGINX return static files rather than rocket
        if cfg!(debug_assertions) {
            // Serve static files for client website
            thread::spawn(|| {
                rocket::ignite().mount("/", routes![index, file]).launch();
            });
        }

        // Websockets
        let connections_clone = Arc::clone(&self.connections);
        let send_clone = self.send.clone();
        let uuid_clone = Arc::clone(&self.uuid);
        thread::spawn(move || {
            ws::listen("0.0.0.0:3012", |out| WebSocketListener {
                out: out,
                connections: connections_clone.clone(),
                send: send_clone.clone(),
                uuid: {
                    let mut uuid_lock = uuid_clone.lock().unwrap();
                    let uuid = uuid_lock.clone();
                    // Increment uuid
                    *uuid_lock += 1;
                    uuid
                },
            })
            .unwrap()
        });
    }
}

impl Communication for WebSocketCommunication {
    // Block and read from queue
    fn read_message(&mut self) -> (u32, String) {
        match self.recv.recv() {
            Ok((token, message)) => {
                let connections_lock = self.connections.lock().unwrap();
                // May disconnect ?
                if let Some((ip_addr, _)) = connections_lock.get(&token) {
                    println!(
                        "{}|{}|{}{}|{}",
                        Local::now(),
                        ip_addr,
                        &token,
                        ">",
                        &message
                    );
                }
                // This block will run if connection has already been disconnected
                else {
                    println!("{}|_|{}{}|{}", Local::now(), &token, ">", &message);
                }
                (token, message)
            }
            Err(_) => {
                println!("{}|_|_|{}|_", Local::now(), ">");
                println!("Catastrophic failure if this fails probably.");
                (0, "".to_string())
            }
        }
    }

    // Send message to client with the corresponding token
    fn send_message(&self, token: &u32, message: &str, state: &PlayerState) {
        let msg = json!({
            "bg": "000",
            "fg": "b7410e",
            "from": "THRUSTY",
            "message": message,
            "state": state.to_string()
        })
        .to_string();
        let connections_lock = self.connections.lock().unwrap();
        // Handle case for missing connection - This is possible for disconnects
        if let Some((ip_addr, sender)) = connections_lock.get(&token) {
            // Log server response for troubleshooting and FBI-ing
            sender.send(&*msg).unwrap();
            println!("{}|{}|{}{}|{}", Local::now(), ip_addr, ">", token, msg);
        }
    }

    // Send message with from
    fn send_message_from(&self, token: &u32, from: &str, bg: &str, fg: &str, message: &str, level: i32) {
        let msg = json!({
            "bg": bg,
            "fg": fg,
            "from": from,
            "message": message,
			"level": level
        })
        .to_string();
        let connections_lock = self.connections.lock().unwrap();
        // Handle case for missing connection - This is possible for disconnects
        if let Some((ip_addr, sender)) = connections_lock.get(&token) {
            // Log server response for troubleshooting and FBI-ing
            sender.send(&*msg).unwrap();
            println!("{}|{}|{}{}|{}", Local::now(), ip_addr, ">", token, msg);
        }
    }

    fn send_messages(&self, token: &u32, messages: &Vec<String>, state: &PlayerState) {
        let message = messages.join("<br/>");
        self.send_message(token, &message, state);
    }

    fn get_identifier(&self, token: &u32) -> String {
        let connections_lock = self.connections.lock().unwrap();
        if let Some((ip_addr, _)) = connections_lock.get(&token) {
            ip_addr.clone()
        } else {
            String::new()
        }
    }

    fn disconnect(&mut self, token: &u32) {
        let connections_lock = self.connections.lock().unwrap();
        if let Some((_ip_addr, sender)) = connections_lock.get(&token) {
            // Don't do anything if close succeeds or fails
            match sender.close(CloseCode::Normal) {
                _ => {}
            };
        }
    }
}