Merge pull request #1 from PiyushXCoder/dev

Merging Dev in Main
This commit is contained in:
Piyush मिश्रः 2023-06-25 22:01:24 +05:30 committed by GitHub
commit e07f93fd68
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 628 additions and 1344 deletions

1742
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -13,26 +13,25 @@ keywords = ["chat", "Chatting", "Talk", "Stranger"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix = "0.10"
actix-web = { version = "3", features = ["rustls"] }
actix-web-actors = "3"
actix-broker = "0.3"
actix-files = "0.5"
actix-ratelimit = "0.3"
env_logger = "0.9"
actix = "0.13"
actix-web = { version = "4", features = ["rustls"] }
actix-web-actors = "4"
actix-broker = "0.4"
actix-files = "0.6"
awc = "3.1"
env_logger = "0.10"
openssl = "0.10"
clap = { version = "4", features = ["derive"] }
lazy_static = "1.4"
serde = "1.0"
serde = { version = "1.0", features = ["serde_derive"] }
serde_json = "1.0"
rand = "0.8"
tokio = { version = "1.5", features = ['rt', 'rt-multi-thread', 'macros'] }
futures = "0.3"
sha2 = "0.10"
base64 = "0.13"
log = "0.4.17"
rustls = "0.18.0"
base64 = "0.21"
log = "0.4"
rustls = "0.20"
rustls-pemfile = "1.0.2"
anyhow = { version = "1.0.71", features = ["backtrace"] }

View File

@ -17,8 +17,7 @@
use crate::ws_sansad::WsSansad;
use actix::prelude::*;
use dev::{MessageResponse, ResponseChannel};
pub mod pind;
pub mod responses;
pub mod sansad;
pub mod util;

View File

@ -16,7 +16,7 @@
*/
//! Messages to be sent between Actors
use super::util::Resp;
use super::responses::ResultResponse;
use super::*;
//################################################## For ChatPinnd ##################################################
@ -24,7 +24,7 @@ use super::*;
/// Request to Kaksh with its kunjika
#[derive(Clone, Message)]
#[rtype(result = "Resp")]
#[rtype(result = "ResultResponse")]
pub struct JoinKaksh {
pub kaksh_kunjika: String,
pub length: Option<usize>,
@ -35,7 +35,7 @@ pub struct JoinKaksh {
/// Request to connect Random vayakti
#[derive(Clone, Message)]
#[rtype(result = "Resp")]
#[rtype(result = "ResultResponse")]
pub struct JoinRandom {
pub addr: Addr<WsSansad>,
pub kunjika: String,
@ -44,7 +44,7 @@ pub struct JoinRandom {
}
/// Request to connect Random Next vayakti
#[derive(Clone, Message)]
#[rtype(result = "Resp")]
#[rtype(result = "ResultResponse")]
pub struct JoinRandomNext {
pub kaksh_kunjika: String,
pub kunjika: String,

View File

@ -15,24 +15,10 @@
along with Lupt. If not, see <https://www.gnu.org/licenses/>
*/
use super::*;
//################################################## Helper ##################################################
// //################################################## Helper ##################################################
#[derive(Debug)]
pub enum Resp {
pub enum ResultResponse {
Ok,
Err(String),
None,
}
impl<A, M> MessageResponse<A, M> for Resp
where
A: Actor,
M: Message<Result = Resp>,
{
fn handle<R: ResponseChannel<M>>(self, _: &mut A::Context, tx: Option<R>) {
if let Some(tx) = tx {
tx.send(self);
}
}
}

View File

@ -25,7 +25,7 @@ use std::{collections::HashMap, vec};
use actix::prelude::*;
use actix_broker::BrokerSubscribe;
use crate::{broker_messages as ms, broker_messages::util::Resp, ws_sansad};
use crate::{broker_messages as ms, broker_messages::responses::ResultResponse, ws_sansad};
#[allow(dead_code)]
pub struct ChatPinnd {

View File

@ -19,7 +19,7 @@ use super::*;
/// Join kaksh
impl Handler<ms::pind::JoinKaksh> for ChatPinnd {
type Result = Resp;
type Result = MessageResult<ms::pind::JoinKaksh>;
fn handle(&mut self, msg: ms::pind::JoinKaksh, _: &mut Self::Context) -> Self::Result {
// check if user exist
@ -28,7 +28,7 @@ impl Handler<ms::pind::JoinKaksh> for ChatPinnd {
.iter()
.position(|vk| vk.kunjika == msg.kunjika)
{
return Resp::Err("Kunjika already exist".to_owned());
return MessageResult(ResultResponse::Err("Kunjika already exist".to_owned()));
}
if let Some(_) = self.kaksh.iter().position(|(_, g)| {
@ -37,7 +37,7 @@ impl Handler<ms::pind::JoinKaksh> for ChatPinnd {
None => false,
}
}) {
return Resp::Err("Kunjika already exist".to_owned());
return MessageResult(ResultResponse::Err("Kunjika already exist".to_owned()));
}
// check if kaksh exist and add user
@ -47,7 +47,9 @@ impl Handler<ms::pind::JoinKaksh> for ChatPinnd {
// 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());
return MessageResult(ResultResponse::Err(
"Kaksh have no space".to_owned(),
));
}
}
@ -80,7 +82,7 @@ impl Handler<ms::pind::JoinKaksh> for ChatPinnd {
}
}
Resp::Ok
MessageResult(ResultResponse::Ok)
}
}
@ -89,7 +91,7 @@ impl Handler<ms::pind::JoinKaksh> for ChatPinnd {
/// 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::pind::JoinRandom> for ChatPinnd {
type Result = Resp;
type Result = MessageResult<ms::pind::JoinRandom>;
fn handle(&mut self, msg: ms::pind::JoinRandom, _: &mut Self::Context) -> Self::Result {
// check if user exist
if let Some(_) = self
@ -97,7 +99,7 @@ impl Handler<ms::pind::JoinRandom> for ChatPinnd {
.iter()
.position(|vk| vk.kunjika == msg.kunjika)
{
return Resp::Err("Kunjika already exist".to_owned());
return MessageResult(ResultResponse::Err("Kunjika already exist".to_owned()));
}
if let Some(_) = self.kaksh.iter().position(|(_, g)| {
@ -106,7 +108,7 @@ impl Handler<ms::pind::JoinRandom> for ChatPinnd {
None => false,
}
}) {
return Resp::Err("Kunjika already exist".to_owned());
return MessageResult(ResultResponse::Err("Kunjika already exist".to_owned()));
}
// Check if watch list is empty
@ -117,7 +119,7 @@ impl Handler<ms::pind::JoinRandom> for ChatPinnd {
name: msg.name,
tags: msg.tags,
});
return Resp::None;
return MessageResult(ResultResponse::None);
}
// connect person with tag
@ -136,7 +138,7 @@ impl Handler<ms::pind::JoinRandom> for ChatPinnd {
name: msg.name,
tags: msg.tags,
});
return Resp::None;
return MessageResult(ResultResponse::None);
}
}
} else {
@ -185,22 +187,30 @@ impl Handler<ms::pind::JoinRandom> for ChatPinnd {
kaksh_kunjika: group_kunjika,
});
Resp::Ok
MessageResult(ResultResponse::Ok)
}
}
/// Next Random next vayakti
impl Handler<ms::pind::JoinRandomNext> for ChatPinnd {
type Result = Resp;
type Result = MessageResult<ms::pind::JoinRandomNext>;
fn handle(&mut self, msg: ms::pind::JoinRandomNext, _: &mut Self::Context) -> Self::Result {
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 MessageResult(ResultResponse::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 MessageResult(ResultResponse::Err(
"Failed to join, check entries!".to_owned(),
))
}
};
let addr;
@ -210,18 +220,28 @@ impl Handler<ms::pind::JoinRandomNext> 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 MessageResult(ResultResponse::Err(
"Failed to join, check entries!".to_owned(),
))
}
};
if let None = loog.tags {
return Resp::Err("You are not a randome vyakti!".to_owned());
return MessageResult(ResultResponse::Err(
"You are not a randome vyakti!".to_owned(),
));
}
addr = loog.addr.clone();
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 MessageResult(ResultResponse::Err(
"Failed to join, check entries!".to_owned(),
))
}
};
}
@ -242,7 +262,7 @@ impl Handler<ms::pind::JoinRandomNext> for ChatPinnd {
name,
tags,
});
return Resp::None;
return MessageResult(ResultResponse::None);
}
// connect person with tag or to zero
let pos = if tags.len() > 0 {
@ -260,7 +280,7 @@ impl Handler<ms::pind::JoinRandomNext> for ChatPinnd {
name,
tags,
});
return Resp::None;
return MessageResult(ResultResponse::None);
}
}
} else {
@ -314,7 +334,7 @@ impl Handler<ms::pind::JoinRandomNext> for ChatPinnd {
kaksh_kunjika: group_kunjika,
});
Resp::Ok
MessageResult(ResultResponse::Ok)
}
}

View File

@ -31,15 +31,11 @@ extern crate lazy_static;
extern crate anyhow;
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::{middleware::Logger, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
use awc::Client;
use config::CONFIG;
use rustls::{Certificate, NoClientAuth, PrivateKey, ServerConfig};
use rustls::{Certificate, PrivateKey, ServerConfig};
use std::fs::File;
use ws_sansad::WsSansad;
@ -59,11 +55,6 @@ async fn main() -> std::io::Result<()> {
let main_server = HttpServer::new(move || {
let mut app = 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(&CONFIG.logger_pattern))
.service(web::resource("/ws/").route(web::get().to(ws_index)));
@ -114,8 +105,16 @@ fn gen_rustls_server_config(key: String, cert: String) -> ServerConfig {
let private_key = PrivateKey(private_key.to_owned());
let mut config = ServerConfig::new(NoClientAuth::new());
config.set_single_cert(certs, private_key).unwrap();
let config = ServerConfig::builder()
.with_safe_default_cipher_suites()
.with_safe_default_kx_groups()
.with_safe_default_protocol_versions()
.map_err(|e| anyhow!(e))
.expect("Build TLS!")
.with_no_client_auth()
.with_single_cert(certs, private_key)
.map_err(|e| anyhow!(e))
.expect("Add TLS certificates!");
config
}
@ -130,9 +129,7 @@ async fn gif(req: HttpRequest) -> Result<HttpResponse, Error> {
pos = ""
}
let client = Client::builder()
.connector(Connector::new().finish())
.finish();
let client = Client::default();
let tenor_key = CONFIG.tenor_key.clone().unwrap();
@ -152,11 +149,13 @@ async fn gif(req: HttpRequest) -> Result<HttpResponse, Error> {
let response = client
.get(url)
.header("User-Agent", "actix-web/3.0")
.insert_header(("User-Agent", "actix-web/3.0"))
.send()
.await?
.await
.unwrap()
.body()
.await?;
.await
.unwrap(); // need handle errors
Ok(HttpResponse::Ok()
.content_type("application/json")

View File

@ -29,7 +29,7 @@ use std::time::{Duration, Instant};
use crate::{
broker_messages as ms,
broker_messages::util::Resp,
broker_messages::responses::ResultResponse,
chat_pinnd::ChatPinnd,
validator::{validate, Validation as vl},
};
@ -39,17 +39,11 @@ const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(15);
/// How often heartbeat pings are sent
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);
pub struct WsSansad {
kunjika: String,
isthiti: Isthiti,
addr: Option<Addr<Self>>,
hb: Instant,
special_hb: Instant,
}
#[derive(Debug)]
@ -65,13 +59,11 @@ impl Actor for WsSansad {
fn started(&mut self, ctx: &mut Self::Context) {
self.addr = Some(ctx.address().clone()); // own addr
self.hb(ctx);
self.special_hb(ctx);
}
fn stopping(&mut self, _: &mut Self::Context) -> Running {
tokio::runtime::Runtime::new()
.unwrap()
.block_on(self.leave_kaksh()); // notify leaving
futures::executor::block_on(self.leave_kaksh());
Running::Stop
}
}
@ -88,10 +80,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsSansad {
self.hb = Instant::now();
}
Ok(ws::Message::Text(msg)) => {
self.special_hb = Instant::now();
tokio::runtime::Runtime::new()
.unwrap()
.block_on(self.parse_text_handle(msg));
futures::executor::block_on(self.parse_text_handle(msg.to_string()));
}
Ok(ws::Message::Close(msg)) => {
ctx.close(msg);
@ -109,7 +98,6 @@ impl WsSansad {
isthiti: Isthiti::None,
addr: None,
hb: Instant::now(),
special_hb: Instant::now(),
}
}
@ -123,9 +111,7 @@ impl WsSansad {
// heartbeat timed out
// stop actor
tokio::runtime::Runtime::new()
.unwrap()
.block_on(act.leave_kaksh());
futures::executor::block_on(act.leave_kaksh());
ctx.stop();
// don't try to send a ping
return;
@ -135,27 +121,6 @@ impl WsSansad {
});
}
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn special_hb(&self, ctx: &mut <Self as Actor>::Context) {
ctx.run_interval(SPECIAL_HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.special_hb) > SPECIAL_CLIENT_TIMEOUT {
// heartbeat timed out
// stop actor
tokio::runtime::Runtime::new()
.unwrap()
.block_on(act.leave_kaksh());
ctx.stop();
// don't try to send a ping
return;
}
ctx.ping(b"");
});
}
/// parse the request text from client
async fn parse_text_handle(&mut self, msg: String) {
if let Ok(val) = serde_json::from_str::<Value>(&msg) {

View File

@ -17,7 +17,9 @@
use super::*;
use crate::config::CONFIG;
use base64::Engine;
use sha2::{Digest, Sha224};
impl WsSansad {
/// Request to join to kaksh
pub async fn join_kaksh(&mut self, val: Value) {
@ -56,7 +58,9 @@ impl WsSansad {
}
let mut hasher = Sha224::new();
hasher.update(format!("{}{}", kunjika, CONFIG.salt).as_bytes());
let kunjika = base64::encode(hasher.finalize())[..8].to_owned();
let kunjika = base64::engine::general_purpose::STANDARD_NO_PAD.encode(hasher.finalize())
[..8]
.to_owned();
// Name
let name = match val.get("name") {
@ -98,7 +102,7 @@ impl WsSansad {
};
// request
let result: Resp = ChatPinnd::from_registry()
let result: ResultResponse = ChatPinnd::from_registry()
.send(ms::pind::JoinKaksh {
kaksh_kunjika: kaksh_kunjika.to_owned(),
length,
@ -110,8 +114,8 @@ impl WsSansad {
.unwrap();
match result {
Resp::Err(err) => self.send_err_response(&err),
Resp::Ok => {
ResultResponse::Err(err) => self.send_err_response(&err),
ResultResponse::Ok => {
self.isthiti = Isthiti::Kaksh(kaksh_kunjika);
self.addr
.clone()
@ -161,7 +165,9 @@ impl WsSansad {
}
let mut hasher = Sha224::new();
hasher.update(format!("{}{}", kunjika, &CONFIG.salt).as_bytes());
let kunjika = base64::encode(hasher.finalize())[..8].to_owned();
let kunjika = base64::engine::general_purpose::STANDARD_NO_PAD.encode(hasher.finalize())
[..8]
.to_owned();
// Name
let name = match val.get("name") {
@ -189,7 +195,7 @@ impl WsSansad {
};
// request
let result: Resp = ChatPinnd::from_registry()
let result: ResultResponse = ChatPinnd::from_registry()
.send(ms::pind::JoinRandom {
addr: self.addr.clone().unwrap(),
kunjika: kunjika.to_owned(),
@ -200,8 +206,8 @@ impl WsSansad {
.unwrap();
match result {
Resp::Err(err) => self.send_err_response(&err),
Resp::Ok => {
ResultResponse::Err(err) => self.send_err_response(&err),
ResultResponse::Ok => {
self.addr
.clone()
.unwrap()
@ -210,7 +216,7 @@ impl WsSansad {
});
self.kunjika = kunjika;
}
Resp::None => {
ResultResponse::None => {
self.addr.clone().unwrap().do_send(ms::sansad::WsResponse {
result: "watch".to_owned(),
message: "Watchlist".to_owned(),
@ -243,7 +249,7 @@ impl WsSansad {
};
// request
let result: Resp = ChatPinnd::from_registry()
let result: ResultResponse = ChatPinnd::from_registry()
.send(ms::pind::JoinRandomNext {
kunjika: self.kunjika.to_owned(),
kaksh_kunjika: kaksh_kunjika.to_owned(),
@ -252,8 +258,8 @@ impl WsSansad {
.unwrap();
match result {
Resp::Err(err) => self.send_err_response(&err),
Resp::None => {
ResultResponse::Err(err) => self.send_err_response(&err),
ResultResponse::None => {
self.addr.clone().unwrap().do_send(ms::sansad::WsResponse {
result: "watch".to_owned(),
message: "Watchlist".to_owned(),