commented

This commit is contained in:
Piyush मिश्रः 2021-02-16 01:00:42 +05:30
parent e7f8217822
commit 3d34871ebd
4 changed files with 80 additions and 18 deletions

View File

@ -36,21 +36,24 @@ impl Actor for ChatPinnd {
type Context = Context<Self>; type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) { fn started(&mut self, ctx: &mut Self::Context) {
// for actix broker
self.subscribe_system_async::<ms::SendText>(ctx); self.subscribe_system_async::<ms::SendText>(ctx);
self.subscribe_system_async::<ms::LeaveUser>(ctx); self.subscribe_system_async::<ms::LeaveUser>(ctx);
} }
} }
// Set information of user
impl Handler<ms::SetInfoVyakti> for ChatPinnd { impl Handler<ms::SetInfoVyakti> for ChatPinnd {
type Result = Option<String>; type Result = Option<String>;
fn handle(&mut self, msg: ms::SetInfoVyakti, _: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: ms::SetInfoVyakti, _: &mut Self::Context) -> Self::Result {
// check if vayakti info is not modified and do key exist
if !msg.modify { if !msg.modify {
if self.vyakti.key_exist(&msg.kunjika) { if self.vyakti.key_exist(&msg.kunjika) {
return Some("Kunjika Exists".to_owned()); return Some("Kunjika Exists".to_owned());
} }
} }
// change value
self.vyakti.insert(msg.kunjika, Vyakti { self.vyakti.insert(msg.kunjika, Vyakti {
name: msg.name, name: msg.name,
tags: msg.tags tags: msg.tags
@ -60,12 +63,14 @@ impl Handler<ms::SetInfoVyakti> for ChatPinnd {
} }
} }
/// Join grih
impl Handler<ms::JoinGrih> for ChatPinnd { impl Handler<ms::JoinGrih> for ChatPinnd {
type Result = Result<(), errors::GrihFullError>; type Result = Result<(), errors::GrihFullError>;
fn handle(&mut self, msg: ms::JoinGrih, _: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: ms::JoinGrih, _: &mut Self::Context) -> Self::Result {
match self.grih.get_mut(&msg.grih_kunjika) { match self.grih.get_mut(&msg.grih_kunjika) { // check if group exist
Some(grih) =>{ Some(grih) =>{ // exist
// check if group have no space left
if let Some(n) = grih.length { if let Some(n) = grih.length {
if grih.loog.len() >= n { if grih.loog.len() >= n {
return Err(errors::GrihFullError); return Err(errors::GrihFullError);
@ -81,7 +86,8 @@ impl Handler<ms::JoinGrih> for ChatPinnd {
kunjika: kunjika.clone() kunjika: kunjika.clone()
}) })
}); });
}, None => { }, None => { // don't exist
// add group and notify
self.grih.insert(msg.grih_kunjika, Grih { self.grih.insert(msg.grih_kunjika, Grih {
length: msg.length, length: msg.length,
loog: vec![msg.addr.clone()] loog: vec![msg.addr.clone()]
@ -97,9 +103,14 @@ impl Handler<ms::JoinGrih> for ChatPinnd {
} }
} }
/// 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
impl Handler<ms::JoinRandom> for ChatPinnd { impl Handler<ms::JoinRandom> for ChatPinnd {
type Result = Option<()>; type Result = Option<()>;
fn handle(&mut self, msg: ms::JoinRandom, _: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: ms::JoinRandom, _: &mut Self::Context) -> Self::Result {
// Check if watch list is empty
if self.vyaktigat_waitlist.len() == 0 { if self.vyaktigat_waitlist.len() == 0 {
self.vyaktigat_waitlist.push(VyaktiWatchlist { self.vyaktigat_waitlist.push(VyaktiWatchlist {
kunjika: msg.kunjika, kunjika: msg.kunjika,
@ -108,6 +119,7 @@ impl Handler<ms::JoinRandom> for ChatPinnd {
return None; return None;
} }
// connect 0th person
let vayakti_watchlist = self.vyaktigat_waitlist.remove(0); let vayakti_watchlist = self.vyaktigat_waitlist.remove(0);
let vayakti1 = self.vyakti.get(&msg.kunjika).unwrap(); let vayakti1 = self.vyakti.get(&msg.kunjika).unwrap();
let vayakti2 = self.vyakti.get(&vayakti_watchlist.kunjika).unwrap(); let vayakti2 = self.vyakti.get(&vayakti_watchlist.kunjika).unwrap();
@ -117,6 +129,8 @@ impl Handler<ms::JoinRandom> for ChatPinnd {
loog: vec![msg.addr.clone(), vayakti_watchlist.addr.clone()] loog: vec![msg.addr.clone(), vayakti_watchlist.addr.clone()]
}); });
// notify about connection
msg.addr.do_send(ms::WsConnectedRandom { msg.addr.do_send(ms::WsConnectedRandom {
ajnyat_name: vayakti2.name.clone(), ajnyat_name: vayakti2.name.clone(),
grih_kunjika: group_kunjika.clone() grih_kunjika: group_kunjika.clone()
@ -131,6 +145,7 @@ impl Handler<ms::JoinRandom> for ChatPinnd {
} }
} }
/// send text to exryone
impl Handler<ms::SendText> for ChatPinnd { impl Handler<ms::SendText> for ChatPinnd {
type Result = (); type Result = ();
@ -146,6 +161,7 @@ impl Handler<ms::SendText> for ChatPinnd {
} }
} }
/// Notifiy a user disconnected and trim grih
impl Handler<ms::LeaveUser> for ChatPinnd { impl Handler<ms::LeaveUser> for ChatPinnd {
type Result = (); type Result = ();

View File

@ -1,3 +1,14 @@
//! Lupt chat
//! Chat Website to have group chat and stranger's chat both
//!
//! Structure of how program work flow
//!
//! |--> ws_sansad1 <----\
//! ws_index -|--> ws_sansad2 <---- \ chat_pind
//! |--> ws_sansad3 <---- /
//! |--> ws_sansad4 <----/
//!
use actix_web::{App, Error, HttpRequest, HttpResponse, HttpServer, web}; use actix_web::{App, Error, HttpRequest, HttpResponse, HttpServer, web};
use actix_files as fs; use actix_files as fs;
use actix_web_actors::ws; use actix_web_actors::ws;

View File

@ -4,8 +4,8 @@ use actix::prelude::*;
use crate::ws_sansad::WsSansad; use crate::ws_sansad::WsSansad;
use crate::errors; use crate::errors;
//################################################## For ChatPinnd ################################################## //################################################## For ChatPinnd ##################################################
/// Request to change information of vayakti to list of vayakti im ChatPind
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "Option<String>")] // None if no error #[rtype(result = "Option<String>")] // None if no error
pub struct SetInfoVyakti { pub struct SetInfoVyakti {
@ -15,6 +15,7 @@ pub struct SetInfoVyakti {
pub modify: bool pub modify: bool
} }
/// Request to Grih with its kunjika
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "Result<(), errors::GrihFullError>")] #[rtype(result = "Result<(), errors::GrihFullError>")]
pub struct JoinGrih { pub struct JoinGrih {
@ -24,6 +25,7 @@ pub struct JoinGrih {
pub kunjika: String pub kunjika: String
} }
/// Request to connect Random vayakti
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "Option<()>")] #[rtype(result = "Option<()>")]
pub struct JoinRandom { pub struct JoinRandom {
@ -31,6 +33,7 @@ pub struct JoinRandom {
pub kunjika: String pub kunjika: String
} }
/// Request to send text t
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct SendText { pub struct SendText {
@ -39,6 +42,7 @@ pub struct SendText {
pub text: String pub text: String
} }
/// Request to leave grih
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct LeaveUser { pub struct LeaveUser {
@ -48,6 +52,7 @@ pub struct LeaveUser {
} }
//################################################## For WsSansad ################################################## //################################################## For WsSansad ##################################################
// Request to send transfer text
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct WsMessage { pub struct WsMessage {
@ -55,6 +60,7 @@ pub struct WsMessage {
pub sender: String pub sender: String
} }
// Notify Someone connected
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct WsConnected { pub struct WsConnected {
@ -62,12 +68,14 @@ pub struct WsConnected {
pub kunjika: String pub kunjika: String
} }
// Notify someone disconnected
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct WsDisconnected { pub struct WsDisconnected {
pub kunjika: String pub kunjika: String
} }
// Give response message
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct WsResponse { pub struct WsResponse {
@ -75,7 +83,7 @@ pub struct WsResponse {
pub message: String pub message: String
} }
// Got connected to random vayakti
#[derive(Clone, Message)] #[derive(Clone, Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct WsConnectedRandom { pub struct WsConnectedRandom {

View File

@ -24,15 +24,16 @@ impl Actor for WsSansad {
type Context = ws::WebsocketContext<Self>; type Context = ws::WebsocketContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) { fn started(&mut self, ctx: &mut Self::Context) {
self.addr = Some(ctx.address().clone()); self.addr = Some(ctx.address().clone()); // own addr
} }
fn stopping(&mut self, _: &mut Self::Context) -> Running { fn stopping(&mut self, _: &mut Self::Context) -> Running {
futures::executor::block_on(self.leave_grih()); futures::executor::block_on(self.leave_grih()); // notify leaving
Running::Stop Running::Stop
} }
} }
/// manage stream
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsSansad { impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsSansad {
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) { fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
match msg { match msg {
@ -48,6 +49,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsSansad {
} }
} }
/// send text message
impl Handler<ms::WsMessage> for WsSansad { impl Handler<ms::WsMessage> for WsSansad {
type Result = (); type Result = ();
fn handle(&mut self, msg: ms::WsMessage, ctx: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: ms::WsMessage, ctx: &mut Self::Context) -> Self::Result {
@ -60,6 +62,7 @@ impl Handler<ms::WsMessage> for WsSansad {
} }
} }
/// send response ok, error
impl Handler<ms::WsResponse> for WsSansad { impl Handler<ms::WsResponse> for WsSansad {
type Result = (); type Result = ();
fn handle(&mut self, msg: ms::WsResponse, ctx: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: ms::WsResponse, ctx: &mut Self::Context) -> Self::Result {
@ -72,6 +75,7 @@ impl Handler<ms::WsResponse> for WsSansad {
} }
} }
/// notify someone got connected
impl Handler<ms::WsConnected> for WsSansad { impl Handler<ms::WsConnected> for WsSansad {
type Result = (); type Result = ();
fn handle(&mut self, msg: ms::WsConnected, ctx: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: ms::WsConnected, ctx: &mut Self::Context) -> Self::Result {
@ -84,6 +88,7 @@ impl Handler<ms::WsConnected> for WsSansad {
} }
} }
/// notify someone got disconnected
impl Handler<ms::WsDisconnected> for WsSansad { impl Handler<ms::WsDisconnected> for WsSansad {
type Result = (); type Result = ();
fn handle(&mut self, msg: ms::WsDisconnected, ctx: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: ms::WsDisconnected, ctx: &mut Self::Context) -> Self::Result {
@ -95,7 +100,7 @@ impl Handler<ms::WsDisconnected> for WsSansad {
} }
} }
/// notify got connected to random person
impl Handler<ms::WsConnectedRandom> for WsSansad { impl Handler<ms::WsConnectedRandom> for WsSansad {
type Result = (); type Result = ();
fn handle(&mut self, msg: ms::WsConnectedRandom, ctx: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: ms::WsConnectedRandom, ctx: &mut Self::Context) -> Self::Result {
@ -108,8 +113,6 @@ impl Handler<ms::WsConnectedRandom> for WsSansad {
} }
} }
impl WsSansad { impl WsSansad {
pub fn new() -> Self { pub fn new() -> Self {
WsSansad { WsSansad {
@ -119,6 +122,7 @@ impl WsSansad {
} }
} }
/// parse the request text from client
async fn parse_text_handle(&mut self, msg: String) { async fn parse_text_handle(&mut self, msg: String) {
if let Ok(val) = serde_json::from_str::<Value>(&msg) { if let Ok(val) = serde_json::from_str::<Value>(&msg) {
match val.get("cmd").unwrap().as_str().unwrap() { match val.get("cmd").unwrap().as_str().unwrap() {
@ -132,6 +136,7 @@ impl WsSansad {
} }
} }
/// send ok response
fn send_ok_response(&self) { fn send_ok_response(&self) {
self.addr.clone().unwrap().do_send(ms::WsResponse { self.addr.clone().unwrap().do_send(ms::WsResponse {
result: "Ok".to_owned(), result: "Ok".to_owned(),
@ -139,6 +144,7 @@ impl WsSansad {
}); });
} }
/// send error response
fn send_err_response(&self, text: &str) { fn send_err_response(&self, text: &str) {
self.addr.clone().unwrap().do_send(ms::WsResponse { self.addr.clone().unwrap().do_send(ms::WsResponse {
result: "Err".to_owned(), result: "Err".to_owned(),
@ -146,7 +152,9 @@ impl WsSansad {
}); });
} }
/// send info of user and modify if needed
async fn set_info(&mut self, val: Value) { async fn set_info(&mut self, val: Value) {
// parse parameters
let kunjika = match val.get("kunjika") { let kunjika = match val.get("kunjika") {
Some(val ) => val.as_str().unwrap().to_owned(), Some(val ) => val.as_str().unwrap().to_owned(),
None => { None => {
@ -175,8 +183,10 @@ impl WsSansad {
} }
}; };
// check if eing modified
let modify = self.kunjika == Some(kunjika.clone()); let modify = self.kunjika == Some(kunjika.clone());
//request
let result: Option<String> = ChatPinnd::from_registry().send(ms::SetInfoVyakti { let result: Option<String> = ChatPinnd::from_registry().send(ms::SetInfoVyakti {
kunjika: kunjika.clone(), kunjika: kunjika.clone(),
name, name,
@ -193,12 +203,15 @@ impl WsSansad {
self.send_ok_response(); self.send_ok_response();
} }
/// Request for joining to random person
async fn join_random(&mut self) { async fn join_random(&mut self) {
// check if vayakti exist
if let None = self.kunjika { if let None = self.kunjika {
self.send_err_response("No user kunjika set"); self.send_err_response("No vayakti kunjika set");
return; return;
} }
// is vayakti in watch list
if let Isthiti::VraktigatWaitlist = self.isthiti { if let Isthiti::VraktigatWaitlist = self.isthiti {
self.addr.clone().unwrap().do_send(ms::WsResponse { self.addr.clone().unwrap().do_send(ms::WsResponse {
result: "Ok".to_owned(), result: "Ok".to_owned(),
@ -207,6 +220,7 @@ impl WsSansad {
return; return;
} }
// request
let result: Option<()> = ChatPinnd::from_registry().send(ms::JoinRandom{ let result: Option<()> = ChatPinnd::from_registry().send(ms::JoinRandom{
addr: self.addr.clone().unwrap(), addr: self.addr.clone().unwrap(),
kunjika: self.kunjika.clone().unwrap() kunjika: self.kunjika.clone().unwrap()
@ -221,12 +235,15 @@ impl WsSansad {
} }
} }
/// Request to join to grih
async fn join_grih(&mut self, val: Value) { async fn join_grih(&mut self, val: Value) {
//echeck user exist
if let None = self.kunjika { if let None = self.kunjika {
self.send_err_response("No user kunjika set"); self.send_err_response("No vayakti kunjika set");
return; return;
} }
// parse parameter
let grih_kunjika = match val.get("kunjika") { let grih_kunjika = match val.get("kunjika") {
Some(val) => val, Some(val) => val,
None => { None => {
@ -235,6 +252,7 @@ impl WsSansad {
} }
}.as_str().unwrap().to_owned(); }.as_str().unwrap().to_owned();
// restrict place for vaktigat chat
if grih_kunjika.starts_with("gupt_") { if grih_kunjika.starts_with("gupt_") {
self.send_err_response("Such grih kunjika is restricted"); self.send_err_response("Such grih kunjika is restricted");
return; return;
@ -245,6 +263,7 @@ impl WsSansad {
None => None None => None
}; };
// requesy
let result: Result<(), errors::GrihFullError> = ChatPinnd::from_registry().send(ms::JoinGrih { let result: Result<(), errors::GrihFullError> = ChatPinnd::from_registry().send(ms::JoinGrih {
grih_kunjika: grih_kunjika.clone(), grih_kunjika: grih_kunjika.clone(),
length, length,
@ -261,17 +280,24 @@ impl WsSansad {
} }
} }
/// send text to vayakti in grih
async fn send_text(&mut self, val: Value) { async fn send_text(&mut self, val: Value) {
// check if vayakti exist
if let None = self.kunjika { if let None = self.kunjika {
self.send_err_response("No user kunjika set"); self.send_err_response("No vayakti kunjika set");
return; return;
} }
if let Isthiti::None = self.isthiti { // check if connected to any grih
match self.isthiti {
Isthiti::Grih(_) => (),
_ => {
self.send_err_response("Grih not connected"); self.send_err_response("Grih not connected");
return; return;
} }
}
// sent text
let text = match val.get("text") { let text = match val.get("text") {
Some(val) => val, Some(val) => val,
None => { None => {
@ -293,6 +319,7 @@ impl WsSansad {
}); });
} }
// notify leaving
async fn leave_grih(&mut self) { async fn leave_grih(&mut self) {
if let Isthiti::Grih(val) = &mut self.isthiti { if let Isthiti::Grih(val) = &mut self.isthiti {
Broker::<SystemBroker>::issue_async(ms::LeaveUser { Broker::<SystemBroker>::issue_async(ms::LeaveUser {