From 46797ef2e21c4d8cbbb8715a9025b458ba6d4f24 Mon Sep 17 00:00:00 2001 From: Piyush Mishra Date: Wed, 19 Jan 2022 16:58:37 +0530 Subject: [PATCH] beautify --- src/broker_messages/mod.rs | 4 +- src/broker_messages/pind.rs | 24 ++-- src/broker_messages/sansad.rs | 26 ++-- src/broker_messages/util.rs | 6 +- src/chat_pinnd/message.rs | 13 +- src/chat_pinnd/mod.rs | 35 +++-- src/chat_pinnd/user.rs | 216 ++++++++++++++++++++----------- src/config.rs | 101 ++++++++------- src/errors/kaksh_full_error.rs | 1 - src/errors/mod.rs | 2 +- src/errors/user_kunjika_error.rs | 6 +- src/main.rs | 132 +++++++++++-------- src/validator.rs | 3 +- src/ws_sansad/handlers.rs | 8 +- src/ws_sansad/messages.rs | 88 +++++++------ src/ws_sansad/mod.rs | 83 ++++++------ src/ws_sansad/users.rs | 208 +++++++++++++++++------------ 17 files changed, 562 insertions(+), 394 deletions(-) diff --git a/src/broker_messages/mod.rs b/src/broker_messages/mod.rs index f98b021..e2d7827 100644 --- a/src/broker_messages/mod.rs +++ b/src/broker_messages/mod.rs @@ -15,10 +15,10 @@ along with Lupt. If not, see */ +use crate::ws_sansad::WsSansad; use actix::prelude::*; use dev::{MessageResponse, ResponseChannel}; -use crate::ws_sansad::WsSansad; pub mod pind; pub mod sansad; -pub mod util; \ No newline at end of file +pub mod util; diff --git a/src/broker_messages/pind.rs b/src/broker_messages/pind.rs index da9d1f4..95b2410 100644 --- a/src/broker_messages/pind.rs +++ b/src/broker_messages/pind.rs @@ -16,8 +16,8 @@ */ //! Messages to be sent between Actors -use super::*; use super::util::Resp; +use super::*; //################################################## For ChatPinnd ################################################## /// Request to change information of vayakti to list of vayakti im ChatPind @@ -47,26 +47,26 @@ pub struct JoinRandom { #[rtype(result = "Resp")] pub struct JoinRandomNext { pub kaksh_kunjika: String, - pub kunjika: String + pub kunjika: String, } // Request to send list of users #[derive(Clone, Message)] #[rtype(result = "String")] pub struct List { - pub kaksh_kunjika: String + pub kaksh_kunjika: String, } /// Request to leave kaksh #[derive(Clone, Message)] #[rtype(result = "()")] -pub struct LeaveVayakti { +pub struct LeaveVayakti { pub kaksh_kunjika: Option, pub kunjika: String, - pub addr: Addr + pub addr: Addr, } -/// Request to send text +/// Request to send text #[derive(Clone, Message)] #[rtype(result = "()")] pub struct SendText { @@ -76,13 +76,13 @@ pub struct SendText { pub reply: Option, } -/// Request to send image +/// Request to send image #[derive(Clone, Message)] #[rtype(result = "()")] pub struct SendImage { pub kaksh_kunjika: String, pub kunjika: String, - pub src: String + pub src: String, } /// Request to reaction #[derive(Clone, Message)] @@ -91,7 +91,7 @@ pub struct SendReaction { pub kaksh_kunjika: String, pub kunjika: String, pub emoji: String, - pub msg_id: String + pub msg_id: String, } // Request to send status @@ -100,7 +100,7 @@ pub struct SendReaction { pub struct SendStatus { pub kaksh_kunjika: String, pub kunjika: String, - pub status: String + pub status: String, } // Request to delete messages @@ -109,7 +109,7 @@ pub struct SendStatus { pub struct DeleteMsg { pub kaksh_kunjika: String, pub kunjika: String, - pub msg_id: Vec + pub msg_id: Vec, } // Request to edit messages @@ -119,5 +119,5 @@ pub struct EditMsg { pub kaksh_kunjika: String, pub kunjika: String, pub text: String, - pub msg_id: String + pub msg_id: String, } diff --git a/src/broker_messages/sansad.rs b/src/broker_messages/sansad.rs index 9dd6075..af77331 100644 --- a/src/broker_messages/sansad.rs +++ b/src/broker_messages/sansad.rs @@ -25,7 +25,7 @@ use super::*; #[rtype(result = "()")] pub struct WsConnected { pub name: String, - pub kunjika: String + pub kunjika: String, } // Got connected to random vayakti @@ -34,21 +34,21 @@ pub struct WsConnected { pub struct WsConnectedRandom { pub name: String, pub kunjika: String, - pub kaksh_kunjika: String + pub kaksh_kunjika: String, } // Request to send hash calculated of kunjika #[derive(Clone, Message)] #[rtype(result = "()")] pub struct WsKunjikaHash { - pub kunjika: String + pub kunjika: String, } // Request to send list #[derive(Clone, Message)] #[rtype(result = "()")] pub struct WsList { - pub json: String + pub json: String, } // Notify someone disconnected @@ -56,10 +56,9 @@ pub struct WsList { #[rtype(result = "()")] pub struct WsDisconnected { pub kunjika: String, - pub name: String + pub name: String, } - // Request to send Text #[derive(Clone, Message)] #[rtype(result = "()")] @@ -67,7 +66,7 @@ pub struct WsText { pub text: String, pub reply: Option, pub sender_kunjika: String, - pub msg_id: u128 + pub msg_id: u128, } // Request to send Image @@ -76,7 +75,7 @@ pub struct WsText { pub struct WsImage { pub src: String, pub sender_kunjika: String, - pub msg_id: u128 + pub msg_id: u128, } // Request to send Reaction #[derive(Clone, Message)] @@ -84,16 +83,15 @@ pub struct WsImage { pub struct WsReaction { pub emoji: String, pub sender_kunjika: String, - pub msg_id: String + pub msg_id: String, } - // Request to send Status #[derive(Clone, Message)] #[rtype(result = "()")] pub struct WsStatus { pub status: String, - pub sender_kunjika: String + pub sender_kunjika: String, } // Request to delete messages @@ -101,7 +99,7 @@ pub struct WsStatus { #[rtype(result = "()")] pub struct WsDeleteMsg { pub msg_id: Vec, - pub sender_kunjika: String + pub sender_kunjika: String, } // Request to edit messages @@ -110,7 +108,7 @@ pub struct WsDeleteMsg { pub struct WsEditMsg { pub text: String, pub sender_kunjika: String, - pub msg_id: String + pub msg_id: String, } // Give response message @@ -118,5 +116,5 @@ pub struct WsEditMsg { #[rtype(result = "()")] pub struct WsResponse { pub result: String, - pub message: String + pub message: String, } diff --git a/src/broker_messages/util.rs b/src/broker_messages/util.rs index dea4341..b7cc558 100644 --- a/src/broker_messages/util.rs +++ b/src/broker_messages/util.rs @@ -21,8 +21,8 @@ use super::*; #[derive(Debug)] pub enum Resp { Ok, - Err(String), - None + Err(String), + None, } impl MessageResponse for Resp @@ -35,4 +35,4 @@ where tx.send(self); } } -} \ No newline at end of file +} diff --git a/src/chat_pinnd/message.rs b/src/chat_pinnd/message.rs index 2f19abf..c43ec61 100644 --- a/src/chat_pinnd/message.rs +++ b/src/chat_pinnd/message.rs @@ -30,7 +30,7 @@ impl Handler for ChatPinnd { sender_kunjika: msg.kunjika.to_owned(), text: msg.text.to_owned(), reply: msg.reply.to_owned(), - msg_id + msg_id, }); }); } @@ -49,7 +49,7 @@ impl Handler for ChatPinnd { c.addr.do_send(ms::sansad::WsImage { sender_kunjika: msg.kunjika.to_owned(), src: msg.src.to_owned(), - msg_id + msg_id, }); }); } @@ -66,7 +66,7 @@ impl Handler for ChatPinnd { c.addr.do_send(ms::sansad::WsReaction { sender_kunjika: msg.kunjika.to_owned(), emoji: msg.emoji.to_owned(), - msg_id: msg.msg_id.to_owned() + msg_id: msg.msg_id.to_owned(), }); }); } @@ -101,14 +101,13 @@ impl Handler for ChatPinnd { kaksh.loog.iter().for_each(|c| { c.addr.do_send(ms::sansad::WsDeleteMsg { sender_kunjika: msg.kunjika.to_owned(), - msg_id: msg.msg_id.clone() + msg_id: msg.msg_id.clone(), }); }); } } } - /// send edit messages for everyone impl Handler for ChatPinnd { type Result = (); @@ -119,9 +118,9 @@ impl Handler for ChatPinnd { c.addr.do_send(ms::sansad::WsEditMsg { sender_kunjika: msg.kunjika.to_owned(), msg_id: msg.msg_id.to_owned(), - text: msg.text.to_owned() + text: msg.text.to_owned(), }); }); } } -} \ No newline at end of file +} diff --git a/src/chat_pinnd/mod.rs b/src/chat_pinnd/mod.rs index 31bb5b2..50b093d 100644 --- a/src/chat_pinnd/mod.rs +++ b/src/chat_pinnd/mod.rs @@ -17,15 +17,15 @@ //! Chat Pinnd(पिण्ड) is Actor to manage Websocket Chat related action +mod message; mod user; -mod message; use std::{collections::HashMap, vec}; use actix::prelude::*; use actix_broker::BrokerSubscribe; -use crate::{ws_sansad, broker_messages as ms, broker_messages::util::Resp}; +use crate::{broker_messages as ms, broker_messages::util::Resp, ws_sansad}; #[allow(dead_code)] pub struct ChatPinnd { @@ -36,33 +36,33 @@ pub struct ChatPinnd { pub struct Kaksh { length: Option, last_message_id: u128, - loog: Vec + loog: Vec, } pub struct Loog { addr: Addr, kunjika: String, name: String, - tags: Option> + tags: Option>, } -#[derive(Debug, Clone)] -pub struct Vyakti { - name: String, - tags: Vec -} +// #[derive(Debug, Clone)] +// pub struct Vyakti { +// name: String, +// tags: Vec +// } pub struct VyaktiWatchlist { kunjika: String, name: String, tags: Vec, - addr: Addr + addr: Addr, } impl Actor for ChatPinnd { type Context = Context; fn started(&mut self, ctx: &mut Self::Context) { - // for actix broker + // for actix broker self.subscribe_system_async::(ctx); self.subscribe_system_async::(ctx); self.subscribe_system_async::(ctx); @@ -73,31 +73,30 @@ impl Actor for ChatPinnd { } } - impl Default for ChatPinnd { fn default() -> Self { ChatPinnd { kaksh: HashMap::new(), - vyaktigat_waitlist: Vec::new() + vyaktigat_waitlist: Vec::new(), } } } impl Loog { - fn new(addr: Addr, + fn new( + addr: Addr, kunjika: String, name: String, - tags: Option>) -> Self { - + tags: Option>, + ) -> Self { Loog { addr, kunjika, name, - tags + tags, } } } impl SystemService for ChatPinnd {} impl Supervised for ChatPinnd {} - diff --git a/src/chat_pinnd/user.rs b/src/chat_pinnd/user.rs index f97f670..37ec8f1 100644 --- a/src/chat_pinnd/user.rs +++ b/src/chat_pinnd/user.rs @@ -23,50 +23,60 @@ impl Handler for ChatPinnd { fn handle(&mut self, msg: ms::pind::JoinKaksh, _: &mut Self::Context) -> Self::Result { // check if user exist - if let Some(_) = self.vyaktigat_waitlist.iter().position(|vk| vk.kunjika == msg.kunjika) { + if let Some(_) = self + .vyaktigat_waitlist + .iter() + .position(|vk| vk.kunjika == msg.kunjika) + { return Resp::Err("Kunjika already exist".to_owned()); } - if let Some(_) = self.kaksh.iter().position(|(_,g)| { + if let Some(_) = self.kaksh.iter().position(|(_, g)| { match g.loog.iter().position(|a| a.kunjika == msg.kunjika) { Some(_) => true, - None => false + None => false, } }) { return Resp::Err("Kunjika already exist".to_owned()); } // check if kaksh exist and add user - match self.kaksh.get_mut(&msg.kaksh_kunjika) { - Some(kaksh) =>{ // exist + match self.kaksh.get_mut(&msg.kaksh_kunjika) { + Some(kaksh) => { + // exist // check if kaksh have no space left if let Some(n) = kaksh.length { if kaksh.loog.len() >= n { return Resp::Err("Kaksh have no space".to_owned()); - } + } } kaksh.loog.iter().for_each(|a: &Loog| { a.addr.do_send(ms::sansad::WsConnected { name: msg.name.to_owned(), - kunjika: msg.kunjika.to_owned() + kunjika: msg.kunjika.to_owned(), }) }); - kaksh.loog.push(Loog::new(msg.addr, msg.kunjika,msg.name, None)); - - - }, None => { // don't exist + kaksh + .loog + .push(Loog::new(msg.addr, msg.kunjika, msg.name, None)); + } + None => { + // don't exist // add kaksh and notify msg.addr.do_send(ms::sansad::WsConnected { name: msg.name.to_owned(), - kunjika: msg.kunjika.to_owned() - }); - self.kaksh.insert(msg.kaksh_kunjika, Kaksh { - length: msg.length, - last_message_id: 0, - loog: vec![Loog::new(msg.addr,msg.kunjika,msg.name, None)] + kunjika: msg.kunjika.to_owned(), }); + self.kaksh.insert( + msg.kaksh_kunjika, + Kaksh { + length: msg.length, + last_message_id: 0, + loog: vec![Loog::new(msg.addr, msg.kunjika, msg.name, None)], + }, + ); } } @@ -74,7 +84,7 @@ impl Handler for ChatPinnd { } } -/// Join random vayakti +/// Join random vayakti /// Works as: /// Check if watchlist is empty, if yes add the kunjika andaddr to watchlist /// if watchlist have people get 0th person an connect it @@ -82,14 +92,18 @@ impl Handler for ChatPinnd { type Result = Resp; fn handle(&mut self, msg: ms::pind::JoinRandom, _: &mut Self::Context) -> Self::Result { // check if user exist - if let Some(_) = self.vyaktigat_waitlist.iter().position(|vk| vk.kunjika == msg.kunjika) { + if let Some(_) = self + .vyaktigat_waitlist + .iter() + .position(|vk| vk.kunjika == msg.kunjika) + { return Resp::Err("Kunjika already exist".to_owned()); } - if let Some(_) = self.kaksh.iter().position(|(_,g)| { + if let Some(_) = self.kaksh.iter().position(|(_, g)| { match g.loog.iter().position(|a| a.kunjika == msg.kunjika) { Some(_) => true, - None => false + None => false, } }) { return Resp::Err("Kunjika already exist".to_owned()); @@ -101,17 +115,17 @@ impl Handler for ChatPinnd { kunjika: msg.kunjika, addr: msg.addr, name: msg.name, - tags: msg.tags + tags: msg.tags, }); return Resp::None; } - - // connect person with tag + + // connect person with tag let pos = if msg.tags.len() > 0 { match self.vyaktigat_waitlist.iter().position(|vk| { match vk.tags.iter().position(|t| msg.tags.contains(t)) { Some(_) => true, - None => false + None => false, } }) { Some(i) => i, @@ -120,33 +134,56 @@ impl Handler for ChatPinnd { kunjika: msg.kunjika, addr: msg.addr, name: msg.name, - tags: msg.tags + tags: msg.tags, }); return Resp::None; } } - } else { 0 }; + } else { + 0 + }; let vayakti_watchlist = self.vyaktigat_waitlist.remove(pos); - let group_kunjika = format!("gupt_{}>{}",msg.kunjika.to_owned(), vayakti_watchlist.kunjika); - self.kaksh.insert(group_kunjika.to_owned(), Kaksh { - length: Some(2), - last_message_id: 0, - loog: vec![Loog::new(msg.addr.clone(), msg.kunjika.to_owned(), msg.name.to_owned(), Some(msg.tags.clone())), - Loog::new(vayakti_watchlist.addr.clone(), vayakti_watchlist.kunjika.to_owned(), vayakti_watchlist.name.to_owned(), Some(vayakti_watchlist.tags.clone()))] - }); - + let group_kunjika = format!( + "gupt_{}>{}", + msg.kunjika.to_owned(), + vayakti_watchlist.kunjika + ); + self.kaksh.insert( + group_kunjika.to_owned(), + Kaksh { + length: Some(2), + last_message_id: 0, + loog: vec![ + Loog::new( + msg.addr.clone(), + msg.kunjika.to_owned(), + msg.name.to_owned(), + Some(msg.tags.clone()), + ), + Loog::new( + vayakti_watchlist.addr.clone(), + vayakti_watchlist.kunjika.to_owned(), + vayakti_watchlist.name.to_owned(), + Some(vayakti_watchlist.tags.clone()), + ), + ], + }, + ); + // notify about connection msg.addr.do_send(ms::sansad::WsConnectedRandom { name: vayakti_watchlist.name, kunjika: vayakti_watchlist.kunjika, - kaksh_kunjika: group_kunjika.to_owned() - }); - vayakti_watchlist.addr.do_send(ms::sansad::WsConnectedRandom { - name: msg.name, - kunjika: msg.kunjika.to_owned(), - kaksh_kunjika: group_kunjika + kaksh_kunjika: group_kunjika.to_owned(), }); + vayakti_watchlist + .addr + .do_send(ms::sansad::WsConnectedRandom { + name: msg.name, + kunjika: msg.kunjika.to_owned(), + kaksh_kunjika: group_kunjika, + }); Resp::Ok } @@ -156,16 +193,16 @@ impl Handler for ChatPinnd { impl Handler for ChatPinnd { type Result = Resp; fn handle(&mut self, msg: ms::pind::JoinRandomNext, _: &mut Self::Context) -> Self::Result { - let kaksh = match self.kaksh.get_mut(&msg.kaksh_kunjika) { + let kaksh = match self.kaksh.get_mut(&msg.kaksh_kunjika) { Some(v) => v, - None => return Resp::Err("Failed to join, check entries!".to_owned()) + None => return Resp::Err("Failed to join, check entries!".to_owned()), }; let loog_i = match kaksh.loog.iter().position(|a| a.kunjika == msg.kunjika) { Some(v) => v, - None => return Resp::Err("Failed to join, check entries!".to_owned()) + None => return Resp::Err("Failed to join, check entries!".to_owned()), }; - + let addr; let name; let tags; @@ -173,9 +210,9 @@ impl Handler for ChatPinnd { { let loog = match kaksh.loog.get(loog_i) { Some(v) => v, - None => return Resp::Err("Failed to join, check entries!".to_owned()) + None => return Resp::Err("Failed to join, check entries!".to_owned()), }; - + if let None = loog.tags { return Resp::Err("You are not a randome vyakti!".to_owned()); } @@ -184,16 +221,16 @@ impl Handler for ChatPinnd { name = loog.name.to_owned(); tags = match loog.tags.clone() { Some(v) => v, - None => return Resp::Err("Failed to join, check entries!".to_owned()) + None => return Resp::Err("Failed to join, check entries!".to_owned()), }; - } - + } + // remove from old kaksh kaksh.loog.remove(loog_i); kaksh.loog.iter().for_each(|a| { a.addr.do_send(ms::sansad::WsDisconnected { kunjika: msg.kunjika.to_owned(), - name: name.to_owned() + name: name.to_owned(), }) }); @@ -203,7 +240,7 @@ impl Handler for ChatPinnd { kunjika: msg.kunjika, addr, name, - tags + tags, }); return Resp::None; } @@ -212,7 +249,7 @@ impl Handler for ChatPinnd { match self.vyaktigat_waitlist.iter().position(|vk| { match vk.tags.iter().position(|t| tags.contains(t)) { Some(_) => true, - None => false + None => false, } }) { Some(i) => i, @@ -221,38 +258,61 @@ impl Handler for ChatPinnd { kunjika: msg.kunjika, addr, name, - tags + tags, }); return Resp::None; } } - } else { 0 }; + } else { + 0 + }; let vayakti_watchlist = self.vyaktigat_waitlist.remove(pos); - let group_kunjika = format!("gupt_{}>{}",msg.kunjika.to_owned(), vayakti_watchlist.kunjika); - + let group_kunjika = format!( + "gupt_{}>{}", + msg.kunjika.to_owned(), + vayakti_watchlist.kunjika + ); + let log_count = kaksh.loog.len(); drop(kaksh); if log_count == 0 { self.kaksh.remove(&msg.kaksh_kunjika); } - self.kaksh.insert(group_kunjika.to_owned(), Kaksh { - length: Some(2), - last_message_id: 0, - loog: vec![Loog::new(addr.clone(), msg.kunjika.to_owned(), name.to_owned(), Some(tags.clone())), - Loog::new(vayakti_watchlist.addr.clone(), vayakti_watchlist.kunjika.to_owned(), vayakti_watchlist.name.to_owned(), Some(vayakti_watchlist.tags.clone()))] - }); + self.kaksh.insert( + group_kunjika.to_owned(), + Kaksh { + length: Some(2), + last_message_id: 0, + loog: vec![ + Loog::new( + addr.clone(), + msg.kunjika.to_owned(), + name.to_owned(), + Some(tags.clone()), + ), + Loog::new( + vayakti_watchlist.addr.clone(), + vayakti_watchlist.kunjika.to_owned(), + vayakti_watchlist.name.to_owned(), + Some(vayakti_watchlist.tags.clone()), + ), + ], + }, + ); // notify about connection addr.do_send(ms::sansad::WsConnectedRandom { name: vayakti_watchlist.name, kunjika: vayakti_watchlist.kunjika, - kaksh_kunjika: group_kunjika.to_owned() + kaksh_kunjika: group_kunjika.to_owned(), }); - vayakti_watchlist.addr.do_send(ms::sansad::WsConnectedRandom { - name, - kunjika: msg.kunjika.to_owned(), - kaksh_kunjika: group_kunjika - }); + vayakti_watchlist + .addr + .do_send(ms::sansad::WsConnectedRandom { + name, + kunjika: msg.kunjika.to_owned(), + kaksh_kunjika: group_kunjika, + }); Resp::Ok } @@ -266,7 +326,7 @@ impl Handler for ChatPinnd { if let Some(kaksh) = self.kaksh.get(&msg.kaksh_kunjika) { let mut list = Vec::new(); for x in kaksh.loog.iter() { - list.push((x.kunjika.to_owned(),x.name.to_owned())); + list.push((x.kunjika.to_owned(), x.name.to_owned())); } serde_json::json!(list).to_string() } else { @@ -285,12 +345,14 @@ impl Handler for ChatPinnd { if kaksh.loog.len() > 1 { let name = if let Some(i) = kaksh.loog.iter().position(|x| x.addr == msg.addr) { kaksh.loog.remove(i).name - } else { "".to_owned() }; + } else { + "".to_owned() + }; kaksh.loog.iter().for_each(|a| { a.addr.do_send(ms::sansad::WsDisconnected { kunjika: msg.kunjika.to_owned(), - name: name.to_owned() + name: name.to_owned(), }) }); } else { @@ -298,9 +360,13 @@ impl Handler for ChatPinnd { } } } - - if let Some(i) = self.vyaktigat_waitlist.iter().position(|a| a.kunjika == msg.kunjika) { + + if let Some(i) = self + .vyaktigat_waitlist + .iter() + .position(|a| a.kunjika == msg.kunjika) + { self.vyaktigat_waitlist.remove(i); } } -} \ No newline at end of file +} diff --git a/src/config.rs b/src/config.rs index b584431..c96466d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -23,7 +23,7 @@ pub struct Config { pub bind_address: String, pub port: String, pub port_x: String, - pub config: ConfigFile + pub config: ConfigFile, } #[derive(Serialize, Deserialize)] @@ -32,7 +32,7 @@ pub struct ConfigFile { pub tenor_key: String, pub ssl_cert: String, pub ssl_key: String, - pub logger_pattern: String + pub logger_pattern: String, } impl Config { @@ -41,47 +41,58 @@ impl Config { .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(env!("CARGO_PKG_DESCRIPTION")) - .arg(Arg::with_name("bind_address") - .short("a") - .long("bind_address") - .value_name("ADDRESS") - .help("Address to bind for server") - .required(true) - .takes_value(true)) - .arg(Arg::with_name("port") - .short("p") - .long("port") - .value_name("PORT") - .help("Port to bind for server") - .required(true) - .takes_value(true)) - .arg(Arg::with_name("port_x") - .short("x") - .long("port_x") - .value_name("PORT") - .help("Port to bind for http if ssl is enabled to redirect to https") - .required(false) - .takes_value(true)) - .arg(Arg::with_name("static_path") - .short("s") - .long("static_path") - .value_name("DIR") - .help("Path of directory with index.html") - .required(true) - .takes_value(true)) - .arg(Arg::with_name("config") - .short("c") - .long("config") - .value_name("FILE") - .help("Path to config file") - .required(true) - .takes_value(true)) + .arg( + Arg::with_name("bind_address") + .short("a") + .long("bind_address") + .value_name("ADDRESS") + .help("Address to bind for server") + .required(true) + .takes_value(true), + ) + .arg( + Arg::with_name("port") + .short("p") + .long("port") + .value_name("PORT") + .help("Port to bind for server") + .required(true) + .takes_value(true), + ) + .arg( + Arg::with_name("port_x") + .short("x") + .long("port_x") + .value_name("PORT") + .help("Port to bind for http if ssl is enabled to redirect to https") + .required(false) + .takes_value(true), + ) + .arg( + Arg::with_name("static_path") + .short("s") + .long("static_path") + .value_name("DIR") + .help("Path of directory with index.html") + .required(true) + .takes_value(true), + ) + .arg( + Arg::with_name("config") + .short("c") + .long("config") + .value_name("FILE") + .help("Path to config file") + .required(true) + .takes_value(true), + ) .get_matches(); - let conf = matches.value_of("config").unwrap().to_owned(); - let conf = std::fs::read_to_string(conf).expect("Failed to read config"); - - let config = serde_json::from_str::(&conf).expect(r" + let conf = matches.value_of("config").unwrap().to_owned(); + let conf = std::fs::read_to_string(conf).expect("Failed to read config"); + + let config = serde_json::from_str::(&conf).expect( + r" Config File is corrupt. Config file must have following fields @@ -90,15 +101,15 @@ Config file must have following fields - ssl_cert: Path to certificate of ssl - ssl_key: Path to private key of ssl - logger_pattern: Pattern to make log according to Actix Logger -"); - +", + ); Config { static_path: matches.value_of("static_path").unwrap().to_owned(), bind_address: matches.value_of("bind_address").unwrap().to_owned(), port: matches.value_of("port").unwrap().to_owned(), port_x: matches.value_of("port_x").unwrap_or("").to_owned(), - config + config, } } -} \ No newline at end of file +} diff --git a/src/errors/kaksh_full_error.rs b/src/errors/kaksh_full_error.rs index fceeb9a..8a17e7c 100644 --- a/src/errors/kaksh_full_error.rs +++ b/src/errors/kaksh_full_error.rs @@ -24,4 +24,3 @@ impl fmt::Display for KakshFullError { write!(f, "No space left for more user!") } } - diff --git a/src/errors/mod.rs b/src/errors/mod.rs index 0ecea6e..9372e36 100644 --- a/src/errors/mod.rs +++ b/src/errors/mod.rs @@ -19,4 +19,4 @@ mod kaksh_full_error; mod user_kunjika_error; pub use kaksh_full_error::KakshFullError; -pub use user_kunjika_error::AlreadyExistError; \ No newline at end of file +pub use user_kunjika_error::AlreadyExistError; diff --git a/src/errors/user_kunjika_error.rs b/src/errors/user_kunjika_error.rs index 29550eb..50b546f 100644 --- a/src/errors/user_kunjika_error.rs +++ b/src/errors/user_kunjika_error.rs @@ -15,8 +15,8 @@ along with Lupt. If not, see */ -use std::fmt; use std::error::Error; +use std::fmt; #[derive(Debug, Clone)] pub struct AlreadyExistError; @@ -27,6 +27,4 @@ impl fmt::Display for AlreadyExistError { } } -impl Error for AlreadyExistError { - -} \ No newline at end of file +impl Error for AlreadyExistError {} diff --git a/src/main.rs b/src/main.rs index 257a468..492775f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,7 @@ //! Lupt chat //! Chat Website to have group chat and stranger's chat both -//! +//! //! Structure of how program work flow //! //! |--> ws_sansad1 <----\ @@ -27,23 +27,24 @@ #[macro_use] extern crate lazy_static; -use actix_web::{ - App, Error, HttpRequest, HttpResponse, HttpServer, middleware::Logger, web, - client::{Client, Connector} -}; use actix_files as fs; +use actix_ratelimit::{MemoryStore, MemoryStoreActor, RateLimiter}; +use actix_web::{ + client::{Client, Connector}, + middleware::Logger, + web, App, Error, HttpRequest, HttpResponse, HttpServer, +}; use actix_web_actors::ws; -use actix_ratelimit::{RateLimiter, MemoryStore, MemoryStoreActor}; use openssl::ssl::{SslAcceptor, SslAcceptorBuilder, SslConnector, SslFiletype, SslMethod}; -use ws_sansad::WsSansad; use std::sync::RwLock; +use ws_sansad::WsSansad; +mod broker_messages; +mod chat_pinnd; mod config; mod errors; -mod broker_messages; -mod ws_sansad; -mod chat_pinnd; mod validator; +mod ws_sansad; lazy_static! { pub static ref SALT: RwLock = RwLock::new(String::new()); @@ -67,45 +68,65 @@ async fn main() -> std::io::Result<()> { let port_x = config.port_x.clone(); let port = config.port.clone(); if ssl_builder.is_some() && config.port_x != "" { - redirect = Some(HttpServer::new(move || { - App::new() - .wrap( - RateLimiter::new( - MemoryStoreActor::from(MemoryStore::new().clone()).start()) - .with_interval(std::time::Duration::from_secs(60)) - .with_max_requests(100) - ) - .wrap(actix_web_middleware_redirect_https::RedirectHTTPS::with_replacements(&[(port_x.clone(), port.clone())])) - .route("/", web::get().to(|| HttpResponse::Ok() - .content_type("text/plain") - .body("Always HTTPS on non-default ports!"))) - }) - .bind(format!("{}:{}", config.bind_address, config.port_x))? - .run()); + redirect = Some( + HttpServer::new(move || { + App::new() + .wrap( + RateLimiter::new( + MemoryStoreActor::from(MemoryStore::new().clone()).start(), + ) + .with_interval(std::time::Duration::from_secs(60)) + .with_max_requests(100), + ) + .wrap( + actix_web_middleware_redirect_https::RedirectHTTPS::with_replacements(&[( + port_x.clone(), + port.clone(), + )]), + ) + .route( + "/", + web::get().to(|| { + HttpResponse::Ok() + .content_type("text/plain") + .body("Always HTTPS on non-default ports!") + }), + ) + }) + .bind(format!("{}:{}", config.bind_address, config.port_x))? + .run(), + ); } let server = HttpServer::new(move || { App::new() - .wrap( - RateLimiter::new( - MemoryStoreActor::from(MemoryStore::new().clone()).start()) - .with_interval(std::time::Duration::from_secs(60)) - .with_max_requests(200) - ) - .wrap(Logger::new(&logger_pattern)) - .service(web::resource("/ws/").route(web::get().to(ws_index))) - .service(web::resource("/gif/{pos}/").route(web::get().to(gif))) - .service(web::resource("/gif/{pos}/{query}").route(web::get().to(gif))) - .service(fs::Files::new("/", &static_path).index_file("index.html")) + .wrap( + RateLimiter::new(MemoryStoreActor::from(MemoryStore::new().clone()).start()) + .with_interval(std::time::Duration::from_secs(60)) + .with_max_requests(200), + ) + .wrap(Logger::new(&logger_pattern)) + .service(web::resource("/ws/").route(web::get().to(ws_index))) + .service(web::resource("/gif/{pos}/").route(web::get().to(gif))) + .service(web::resource("/gif/{pos}/{query}").route(web::get().to(gif))) + .service(fs::Files::new("/", &static_path).index_file("index.html")) }); - - if ssl_builder.is_some() && config.port_x != "" { - let srv = server.bind_openssl(format!("{}:{}", config.bind_address, config.port), ssl_builder.unwrap())?.run(); - tokio::try_join!(redirect.unwrap(), srv)?; + + if ssl_builder.is_some() && config.port_x != "" { + let srv = server + .bind_openssl( + format!("{}:{}", config.bind_address, config.port), + ssl_builder.unwrap(), + )? + .run(); + tokio::try_join!(redirect.unwrap(), srv)?; } else { - server.bind(format!("{}:{}", config.bind_address, config.port))?.run().await?; + server + .bind(format!("{}:{}", config.bind_address, config.port))? + .run() + .await?; } - + Ok(()) } @@ -116,34 +137,41 @@ async fn ws_index(req: HttpRequest, stream: web::Payload) -> Result Result { let name = req.match_info().get("query").unwrap_or(""); let mut pos = req.match_info().get("pos").unwrap_or(""); - if pos == "_" { pos = "" } + if pos == "_" { + pos = "" + } let builder = SslConnector::builder(SslMethod::tls()).unwrap(); let client = Client::builder() .connector(Connector::new().ssl(builder.build()).finish()) .finish(); - - let url = format!("https://g.tenor.com/v1/search?q={}&key={}&limit=20&media_filter=tinygif&pos={}", name.replace(" ", "+"), TENOR_API_KEY.read().unwrap(), pos); - let response = client.get(url) + let url = format!( + "https://g.tenor.com/v1/search?q={}&key={}&limit=20&media_filter=tinygif&pos={}", + name.replace(" ", "+"), + TENOR_API_KEY.read().unwrap(), + pos + ); + let response = client + .get(url) .header("User-Agent", "actix-web/3.0") - .send() + .send() .await? .body() .await?; - Ok(HttpResponse::Ok().content_type("application/json").body(response)) + Ok(HttpResponse::Ok() + .content_type("application/json") + .body(response)) } fn generate_ssl_builder(key: String, cert: String) -> Option { if key != "" && cert != "" { let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); - builder - .set_private_key_file(key, SslFiletype::PEM) - .unwrap(); + builder.set_private_key_file(key, SslFiletype::PEM).unwrap(); builder.set_certificate_chain_file(cert).unwrap(); Some(builder) } else { None } -} \ No newline at end of file +} diff --git a/src/validator.rs b/src/validator.rs index 811e459..d2db70b 100644 --- a/src/validator.rs +++ b/src/validator.rs @@ -71,7 +71,6 @@ fn no_hashtag(dat: &str, entry_name: &str) -> Option { } } - fn no_and_or_question(dat: &str, entry_name: &str) -> Option { if dat.contains("&") { Some(format!("{} shounld not have &", entry_name)) @@ -80,4 +79,4 @@ fn no_and_or_question(dat: &str, entry_name: &str) -> Option { } else { None } -} \ No newline at end of file +} diff --git a/src/ws_sansad/handlers.rs b/src/ws_sansad/handlers.rs index bb0002b..59a5d79 100644 --- a/src/ws_sansad/handlers.rs +++ b/src/ws_sansad/handlers.rs @@ -17,7 +17,6 @@ use super::*; - /// notify someone got connected impl Handler for WsSansad { type Result = (); @@ -34,7 +33,11 @@ impl Handler for WsSansad { /// notify got connected as random person impl Handler for WsSansad { type Result = (); - fn handle(&mut self, msg: ms::sansad::WsConnectedRandom, ctx: &mut Self::Context) -> Self::Result { + fn handle( + &mut self, + msg: ms::sansad::WsConnectedRandom, + ctx: &mut Self::Context, + ) -> Self::Result { self.isthiti = Isthiti::Kaksh(msg.kaksh_kunjika); let json = json!({ "cmd": "random", @@ -177,4 +180,3 @@ impl Handler for WsSansad { ctx.text(json.to_string()); } } - diff --git a/src/ws_sansad/messages.rs b/src/ws_sansad/messages.rs index 7893d19..c362018 100644 --- a/src/ws_sansad/messages.rs +++ b/src/ws_sansad/messages.rs @@ -18,7 +18,6 @@ use super::*; impl WsSansad { - /// send text to vayakti in kaksh pub async fn send_text(&mut self, val: Value) { // check if vayakti exist @@ -43,17 +42,19 @@ impl WsSansad { self.send_err_response("Invalid request"); return; } - }.as_str().unwrap().to_owned(); + } + .as_str() + .unwrap() + .to_owned(); let reply: Option = match val.get("reply") { Some(val) => Some(val.as_str().unwrap().to_owned()), - None => None + None => None, }; let kaksh_kunjika = match &self.isthiti { - Isthiti::Kaksh(kaksh_kunjika) => { - kaksh_kunjika.to_owned() - }, _ => { + Isthiti::Kaksh(kaksh_kunjika) => kaksh_kunjika.to_owned(), + _ => { return; } }; @@ -61,11 +62,10 @@ impl WsSansad { kaksh_kunjika, kunjika: self.kunjika.to_owned(), text, - reply + reply, }); } - /// send image to vayakti in kaksh pub async fn send_image(&mut self, val: Value) { // check if vayakti exist @@ -90,23 +90,24 @@ impl WsSansad { self.send_err_response("Invalid request"); return; } - }.as_str().unwrap().to_owned(); + } + .as_str() + .unwrap() + .to_owned(); let kaksh_kunjika = match &self.isthiti { - Isthiti::Kaksh(kaksh_kunjika) => { - kaksh_kunjika.to_owned() - }, _ => { + Isthiti::Kaksh(kaksh_kunjika) => kaksh_kunjika.to_owned(), + _ => { return; } }; Broker::::issue_async(ms::pind::SendImage { kaksh_kunjika, kunjika: self.kunjika.to_owned(), - src + src, }); } - /// send reaction to vayakti in kaksh pub async fn send_reaction(&mut self, val: Value) { // check if vayakti exist @@ -131,7 +132,10 @@ impl WsSansad { self.send_err_response("Invalid request"); return; } - }.as_str().unwrap().to_owned(); + } + .as_str() + .unwrap() + .to_owned(); // sent emoji let msg_id = match val.get("msg_id") { @@ -140,12 +144,14 @@ impl WsSansad { self.send_err_response("Invalid request"); return; } - }.as_str().unwrap().to_owned(); + } + .as_str() + .unwrap() + .to_owned(); let kaksh_kunjika = match &self.isthiti { - Isthiti::Kaksh(kaksh_kunjika) => { - kaksh_kunjika.to_owned() - }, _ => { + Isthiti::Kaksh(kaksh_kunjika) => kaksh_kunjika.to_owned(), + _ => { return; } }; @@ -153,7 +159,7 @@ impl WsSansad { kaksh_kunjika, kunjika: self.kunjika.to_owned(), emoji, - msg_id + msg_id, }); } @@ -181,18 +187,20 @@ impl WsSansad { self.send_err_response("Invalid request"); return; } - }.as_str().unwrap().to_owned(); + } + .as_str() + .unwrap() + .to_owned(); let kaksh_kunjika = match &self.isthiti { - Isthiti::Kaksh(kaksh_kunjika) => { - kaksh_kunjika.to_owned() - }, _ => { + Isthiti::Kaksh(kaksh_kunjika) => kaksh_kunjika.to_owned(), + _ => { return; } }; Broker::::issue_async(ms::pind::SendStatus { kaksh_kunjika, kunjika: self.kunjika.to_owned(), - status + status, }); } @@ -222,17 +230,18 @@ impl WsSansad { self.send_err_response("Invalid request"); return; } - }.as_array().unwrap(); - + } + .as_array() + .unwrap(); + for id in ids { msg_id.push(id.as_str().unwrap().to_owned()); } drop(ids); let kaksh_kunjika = match &self.isthiti { - Isthiti::Kaksh(kaksh_kunjika) => { - kaksh_kunjika.to_owned() - }, _ => { + Isthiti::Kaksh(kaksh_kunjika) => kaksh_kunjika.to_owned(), + _ => { return; } }; @@ -240,7 +249,7 @@ impl WsSansad { Broker::::issue_async(ms::pind::DeleteMsg { kaksh_kunjika, kunjika: self.kunjika.to_owned(), - msg_id + msg_id, }); } @@ -268,7 +277,10 @@ impl WsSansad { self.send_err_response("Invalid request"); return; } - }.as_str().unwrap().to_owned(); + } + .as_str() + .unwrap() + .to_owned(); // msg_id let msg_id = match val.get("msg_id") { @@ -277,12 +289,14 @@ impl WsSansad { self.send_err_response("Invalid request"); return; } - }.as_str().unwrap().to_owned(); + } + .as_str() + .unwrap() + .to_owned(); let kaksh_kunjika = match &self.isthiti { - Isthiti::Kaksh(kaksh_kunjika) => { - kaksh_kunjika.to_owned() - }, _ => { + Isthiti::Kaksh(kaksh_kunjika) => kaksh_kunjika.to_owned(), + _ => { return; } }; @@ -290,7 +304,7 @@ impl WsSansad { kaksh_kunjika, kunjika: self.kunjika.to_owned(), text, - msg_id + msg_id, }); } } diff --git a/src/ws_sansad/mod.rs b/src/ws_sansad/mod.rs index 210ab64..9672ace 100644 --- a/src/ws_sansad/mod.rs +++ b/src/ws_sansad/mod.rs @@ -18,8 +18,8 @@ //! Ws Sansad manage websocket of each client mod handlers; -mod users; mod messages; +mod users; use actix::prelude::*; use actix_broker::{Broker, SystemBroker}; @@ -27,7 +27,12 @@ use actix_web_actors::ws; use serde_json::{json, Value}; use std::time::{Duration, Instant}; -use crate::{chat_pinnd::ChatPinnd, broker_messages as ms, broker_messages::util::Resp, validator::{Validation as vl, validate}}; +use crate::{ + broker_messages as ms, + broker_messages::util::Resp, + chat_pinnd::ChatPinnd, + validator::{validate, Validation as vl}, +}; /// How often heartbeat pings are sent const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5); @@ -35,9 +40,9 @@ const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5); const CLIENT_TIMEOUT: Duration = Duration::from_secs(15); /// How often heartbeat pings are sent -const SPECIAL_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(3*60); +const SPECIAL_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(3 * 60); /// How long before lack of client response causes a timeout -const SPECIAL_CLIENT_TIMEOUT: Duration = Duration::from_secs(15*60); +const SPECIAL_CLIENT_TIMEOUT: Duration = Duration::from_secs(15 * 60); pub struct WsSansad { kunjika: String, @@ -51,13 +56,12 @@ pub struct WsSansad { enum Isthiti { None, Kaksh(String), - VraktigatWaitlist + VraktigatWaitlist, } - impl Actor for WsSansad { type Context = ws::WebsocketContext; - + fn started(&mut self, ctx: &mut Self::Context) { self.addr = Some(ctx.address().clone()); // own addr self.hb(ctx); @@ -65,36 +69,39 @@ impl Actor for WsSansad { } fn stopping(&mut self, _: &mut Self::Context) -> Running { - tokio::runtime::Runtime::new().unwrap() - .block_on(self.leave_kaksh());// notify leaving + tokio::runtime::Runtime::new() + .unwrap() + .block_on(self.leave_kaksh()); // notify leaving Running::Stop } } - /// manage stream impl StreamHandler> for WsSansad { fn handle(&mut self, msg: Result, ctx: &mut Self::Context) { match msg { - Ok(ws::Message::Ping(msg)) => { + Ok(ws::Message::Ping(msg)) => { ctx.ping(&msg); self.hb = Instant::now(); - }, Ok(ws::Message::Pong(_)) => { + } + Ok(ws::Message::Pong(_)) => { self.hb = Instant::now(); - }, Ok(ws::Message::Text(msg)) => { + } + Ok(ws::Message::Text(msg)) => { self.special_hb = Instant::now(); - tokio::runtime::Runtime::new().unwrap() + tokio::runtime::Runtime::new() + .unwrap() .block_on(self.parse_text_handle(msg)); - }, Ok(ws::Message::Close(msg)) => { + } + Ok(ws::Message::Close(msg)) => { ctx.close(msg); ctx.stop(); } - _ => ctx.stop() + _ => ctx.stop(), } } } - impl WsSansad { pub fn new() -> Self { WsSansad { @@ -102,7 +109,7 @@ impl WsSansad { isthiti: Isthiti::None, addr: None, hb: Instant::now(), - special_hb: Instant::now() + special_hb: Instant::now(), } } @@ -116,9 +123,10 @@ impl WsSansad { // heartbeat timed out // stop actor - tokio::runtime::Runtime::new().unwrap() + tokio::runtime::Runtime::new() + .unwrap() .block_on(act.leave_kaksh()); - ctx.stop(); + ctx.stop(); // don't try to send a ping return; } @@ -137,9 +145,10 @@ impl WsSansad { // heartbeat timed out // stop actor - tokio::runtime::Runtime::new().unwrap() + tokio::runtime::Runtime::new() + .unwrap() .block_on(act.leave_kaksh()); - ctx.stop(); + ctx.stop(); // don't try to send a ping return; } @@ -151,18 +160,18 @@ impl WsSansad { async fn parse_text_handle(&mut self, msg: String) { if let Ok(val) = serde_json::from_str::(&msg) { match val.get("cmd").unwrap().as_str().unwrap() { - "join" => { self.join_kaksh(val).await }, - "rand" => { self.join_random(val).await }, - "randnext" => { self.join_random_next().await }, - "text" => { self.send_text(val).await }, - "img" => { self.send_image(val).await }, - "react" => { self.send_reaction(val).await }, - "status" => { self.send_status(val).await }, - "del" => { self.delete_msg(val).await }, - "edit" => { self.edit_msg(val).await }, - "list" => { self.list().await }, - "leave" => { self.leave_kaksh().await }, - _ => () + "join" => self.join_kaksh(val).await, + "rand" => self.join_random(val).await, + "randnext" => self.join_random_next().await, + "text" => self.send_text(val).await, + "img" => self.send_image(val).await, + "react" => self.send_reaction(val).await, + "status" => self.send_status(val).await, + "del" => self.delete_msg(val).await, + "edit" => self.edit_msg(val).await, + "list" => self.list().await, + "leave" => self.leave_kaksh().await, + _ => (), } } } @@ -171,7 +180,7 @@ impl WsSansad { fn send_ok_response(&self, text: &str) { self.addr.clone().unwrap().do_send(ms::sansad::WsResponse { result: "Ok".to_owned(), - message: text.to_owned() + message: text.to_owned(), }); } @@ -179,7 +188,7 @@ impl WsSansad { fn send_err_response(&self, text: &str) { self.addr.clone().unwrap().do_send(ms::sansad::WsResponse { result: "Err".to_owned(), - message: text.to_owned() + message: text.to_owned(), }); } -} \ No newline at end of file +} diff --git a/src/ws_sansad/users.rs b/src/ws_sansad/users.rs index 8c59fcc..4488656 100644 --- a/src/ws_sansad/users.rs +++ b/src/ws_sansad/users.rs @@ -23,7 +23,7 @@ impl WsSansad { // Check is already joined match self.isthiti { Isthiti::None => (), - _ => return + _ => return, } // is vayakti in watch list @@ -33,76 +33,95 @@ impl WsSansad { } // Kunjika - let kunjika = match val.get("kunjika") { - Some(val ) => val.as_str().unwrap().to_owned(), + let kunjika = match val.get("kunjika") { + Some(val) => val.as_str().unwrap().to_owned(), None => { self.send_err_response("Invalid request"); return; } }; - if let Some(val ) = validate(vec![vl::NonEmpty, vl::NoSpace, vl::NoHashtag, vl::NoAndOrQuestion], &kunjika, "Kunjika") { + if let Some(val) = validate( + vec![ + vl::NonEmpty, + vl::NoSpace, + vl::NoHashtag, + vl::NoAndOrQuestion, + ], + &kunjika, + "Kunjika", + ) { self.send_err_response(&val); return; } let mut m = sha1::Sha1::new(); - m.update(format!("{}{}",kunjika, - crate::SALT.read().unwrap()).as_bytes()); + m.update(format!("{}{}", kunjika, crate::SALT.read().unwrap()).as_bytes()); let kunjika = base64::encode(m.digest().bytes())[..8].to_owned(); // Name - let name = match val.get("name") { - Some(val ) => val.as_str().unwrap().to_owned(), + let name = match val.get("name") { + Some(val) => val.as_str().unwrap().to_owned(), None => { self.send_err_response("Invalid request"); return; } }; - if let Some(val ) = validate(vec![vl::NonEmpty, vl::NoAndOrQuestion], &name, "Name") { + if let Some(val) = validate(vec![vl::NonEmpty, vl::NoAndOrQuestion], &name, "Name") { self.send_err_response(&val); return; } // Kaksh Kunjika let kaksh_kunjika = match val.get("kaksh_kunjika") { - Some(val ) => val.as_str().unwrap().to_owned(), + Some(val) => val.as_str().unwrap().to_owned(), None => { self.send_err_response("Invalid request"); return; } }; - if let Some(val ) = validate(vec![vl::NonEmpty, vl::NoGupt, vl::NoSpace, vl::NoAndOrQuestion], &kaksh_kunjika, "Kaksh Kunjika") { + if let Some(val) = validate( + vec![vl::NonEmpty, vl::NoGupt, vl::NoSpace, vl::NoAndOrQuestion], + &kaksh_kunjika, + "Kaksh Kunjika", + ) { self.send_err_response(&val); return; - } + } // Length let length: Option = match val.get("length") { - Some(val) => match val.as_i64(){ - Some(val) => Some(val as usize), - None => None - }, - None => None + Some(val) => match val.as_i64() { + Some(val) => Some(val as usize), + None => None, + }, + None => None, }; - - // request - let result: Resp = ChatPinnd::from_registry().send(ms::pind::JoinKaksh { - kaksh_kunjika: kaksh_kunjika.to_owned(), - length, - addr: self.addr.clone().unwrap(), - kunjika: kunjika.to_owned(), - name - }).await.unwrap(); + // request + let result: Resp = ChatPinnd::from_registry() + .send(ms::pind::JoinKaksh { + kaksh_kunjika: kaksh_kunjika.to_owned(), + length, + addr: self.addr.clone().unwrap(), + kunjika: kunjika.to_owned(), + name, + }) + .await + .unwrap(); match result { - Resp::Err(err) => self.send_err_response(&err), + Resp::Err(err) => self.send_err_response(&err), Resp::Ok => { self.isthiti = Isthiti::Kaksh(kaksh_kunjika); - self.addr.clone().unwrap().do_send(ms::sansad::WsKunjikaHash{ kunjika: kunjika.clone() }); + self.addr + .clone() + .unwrap() + .do_send(ms::sansad::WsKunjikaHash { + kunjika: kunjika.clone(), + }); self.kunjika = kunjika; self.send_ok_response("joined") } - _ => () + _ => (), } } @@ -114,74 +133,94 @@ impl WsSansad { Isthiti::VraktigatWaitlist => { self.send_ok_response("watchlist"); return; - }, Isthiti::Kaksh(_) => return + } + Isthiti::Kaksh(_) => return, } // Kunjika - let kunjika = match val.get("kunjika") { - Some(val ) => val.as_str().unwrap().to_owned(), + let kunjika = match val.get("kunjika") { + Some(val) => val.as_str().unwrap().to_owned(), None => { self.send_err_response("Invalid request"); return; } }; - if let Some(val ) = validate(vec![vl::NonEmpty, vl::NoSpace, vl::NoHashtag, vl::NoAndOrQuestion], &kunjika, "Kunjika") { + if let Some(val) = validate( + vec![ + vl::NonEmpty, + vl::NoSpace, + vl::NoHashtag, + vl::NoAndOrQuestion, + ], + &kunjika, + "Kunjika", + ) { self.send_err_response(&val); return; } let mut m = sha1::Sha1::new(); - m.update(format!("{}{}",kunjika, - crate::SALT.read().unwrap()).as_bytes()); + m.update(format!("{}{}", kunjika, crate::SALT.read().unwrap()).as_bytes()); let kunjika = base64::encode(m.digest().bytes())[..8].to_owned(); // Name - let name = match val.get("name") { - Some(val ) => val.as_str().unwrap().to_owned(), + let name = match val.get("name") { + Some(val) => val.as_str().unwrap().to_owned(), None => { self.send_err_response("Invalid request"); return; } }; - if let Some(val ) = validate(vec![vl::NonEmpty, vl::NoAndOrQuestion], &name, "Name") { + if let Some(val) = validate(vec![vl::NonEmpty, vl::NoAndOrQuestion], &name, "Name") { self.send_err_response(&val); return; } // Tags - let tags = match val.get("tags") { - Some(val ) => { + let tags = match val.get("tags") { + Some(val) => { let mut v = Vec::new(); for x in val.as_str().unwrap().split_ascii_whitespace() { v.push(x.to_owned()); } v - }, - None => { - Vec::new() } + None => Vec::new(), }; // request - let result: Resp = ChatPinnd::from_registry().send(ms::pind::JoinRandom{ - addr: self.addr.clone().unwrap(), - kunjika: kunjika.to_owned(), - name, - tags - }).await.unwrap(); + let result: Resp = ChatPinnd::from_registry() + .send(ms::pind::JoinRandom { + addr: self.addr.clone().unwrap(), + kunjika: kunjika.to_owned(), + name, + tags, + }) + .await + .unwrap(); match result { - Resp::Err(err) => self.send_err_response(&err), - Resp::Ok => { - self.addr.clone().unwrap().do_send(ms::sansad::WsKunjikaHash{ kunjika: kunjika.clone() }); + Resp::Err(err) => self.send_err_response(&err), + Resp::Ok => { + self.addr + .clone() + .unwrap() + .do_send(ms::sansad::WsKunjikaHash { + kunjika: kunjika.clone(), + }); self.kunjika = kunjika; - }, + } Resp::None => { - self.addr.clone().unwrap().do_send(ms::sansad::WsResponse{ - result: "watch".to_owned() , - message: "Watchlist".to_owned() - }); + self.addr.clone().unwrap().do_send(ms::sansad::WsResponse { + result: "watch".to_owned(), + message: "Watchlist".to_owned(), + }); self.isthiti = Isthiti::VraktigatWaitlist; - self.addr.clone().unwrap().do_send(ms::sansad::WsKunjikaHash{ kunjika: kunjika.clone() }); + self.addr + .clone() + .unwrap() + .do_send(ms::sansad::WsKunjikaHash { + kunjika: kunjika.clone(), + }); self.kunjika = kunjika } } @@ -194,7 +233,7 @@ impl WsSansad { Isthiti::VraktigatWaitlist => { self.send_ok_response("watchlist"); return; - }, + } Isthiti::Kaksh(kaksh_kunjika) => kaksh_kunjika, Isthiti::None => { self.send_ok_response("Not allowed"); @@ -203,22 +242,25 @@ impl WsSansad { }; // request - let result: Resp = ChatPinnd::from_registry().send(ms::pind::JoinRandomNext { - kunjika: self.kunjika.to_owned(), - kaksh_kunjika: kaksh_kunjika.to_owned(), - }).await.unwrap(); + let result: Resp = ChatPinnd::from_registry() + .send(ms::pind::JoinRandomNext { + kunjika: self.kunjika.to_owned(), + kaksh_kunjika: kaksh_kunjika.to_owned(), + }) + .await + .unwrap(); match result { - Resp::Err(err) => self.send_err_response(&err), + Resp::Err(err) => self.send_err_response(&err), Resp::None => { - self.addr.clone().unwrap().do_send(ms::sansad::WsResponse{ - result: "watch".to_owned() , - message: "Watchlist".to_owned() + self.addr.clone().unwrap().do_send(ms::sansad::WsResponse { + result: "watch".to_owned(), + message: "Watchlist".to_owned(), }); self.isthiti = Isthiti::VraktigatWaitlist; self.kunjika = self.kunjika.to_owned() } - _ => () + _ => (), } } @@ -233,14 +275,18 @@ impl WsSansad { // check if connected to any kaksh match &self.isthiti { Isthiti::Kaksh(kunjika) => { - let json: String = ChatPinnd::from_registry().send(ms::pind::List { - kaksh_kunjika: kunjika.to_owned() - }).await.unwrap(); + let json: String = ChatPinnd::from_registry() + .send(ms::pind::List { + kaksh_kunjika: kunjika.to_owned(), + }) + .await + .unwrap(); - self.addr.clone().unwrap().do_send(ms::sansad::WsList { - json - }) - }, + self.addr + .clone() + .unwrap() + .do_send(ms::sansad::WsList { json }) + } _ => { self.send_err_response("Kaksh not connected"); return; @@ -252,16 +298,16 @@ impl WsSansad { pub async fn leave_kaksh(&mut self) { let kaksh_kunjika = match &self.isthiti { Isthiti::Kaksh(val) => Some(val.to_owned()), - _ => None + _ => None, }; - + Broker::::issue_async(ms::pind::LeaveVayakti { kaksh_kunjika, kunjika: self.kunjika.to_owned(), - addr: self.addr.clone().unwrap() + addr: self.addr.clone().unwrap(), }); - - self.isthiti = Isthiti::None; + + self.isthiti = Isthiti::None; self.send_ok_response("left"); } -} \ No newline at end of file +}