diff --git a/.gitignore b/.gitignore index 188c46a..5c5e6b4 100644 --- a/.gitignore +++ b/.gitignore @@ -14,5 +14,12 @@ target/ /target # env -.envrc -.env \ No newline at end of file +*.envrc +*.env + + +# log +*.log + +# debug +.vscode/ \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 6a76afd..56bc71f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,30 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +[[package]] +name = "aho-corasick" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" +dependencies = [ + "memchr", +] + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + [[package]] name = "async-trait" version = "0.1.77" @@ -61,12 +85,29 @@ version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" +[[package]] +name = "bumpalo" +version = "3.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" + [[package]] name = "bytes" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" +[[package]] +name = "casual_logger" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77d02b2f025328b7f0a232815634c840e206350cf7c8e8fb36ab7095e264f59c" +dependencies = [ + "chrono", + "lazy_static", + "regex", +] + [[package]] name = "cc" version = "1.0.83" @@ -88,7 +129,12 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5bc015644b92d5890fab7489e49d21f879d5c990186827d42ec511919404f38b" dependencies = [ + "android-tzdata", + "iana-time-zone", + "js-sys", "num-traits", + "wasm-bindgen", + "windows-targets 0.48.5", ] [[package]] @@ -151,7 +197,10 @@ checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" name = "forcebot_rs" version = "0.1.0" dependencies = [ + "async-trait", + "casual_logger", "dotenv", + "futures", "rand", "tokio", "twitch-irc", @@ -198,7 +247,67 @@ checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-core", "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" + +[[package]] +name = "futures-executor" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" +dependencies = [ + "futures-core", "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" + +[[package]] +name = "futures-macro" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" + +[[package]] +name = "futures-task" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" + +[[package]] +name = "futures-util" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", "pin-project-lite", "pin-utils", "slab", @@ -227,6 +336,38 @@ version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd5256b483761cd23699d0da46cc6fd2ee3be420bbe6d020ae4a091e70b7e9fd" +[[package]] +name = "iana-time-zone" +version = "0.1.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "js-sys" +version = "0.3.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406cda4b368d531c842222cf9d2600a9a4acce8d29423695379c6868a143a9ee" +dependencies = [ + "wasm-bindgen", +] + [[package]] name = "lazy_static" version = "1.4.0" @@ -487,6 +628,35 @@ dependencies = [ "bitflags 1.3.2", ] +[[package]] +name = "regex" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bb987efffd3c6d0d8f5f89510bb458559eab11e4f869acb20bf845e016259cd" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" + [[package]] name = "rustc-demangle" version = "0.1.23" @@ -756,6 +926,69 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "wasm-bindgen" +version = "0.2.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1e124130aee3fb58c5bdd6b639a0509486b0338acaaae0c84a5124b0f588b7f" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9e7e1900c352b609c8488ad12639a311045f40a35491fb69ba8c12f758af70b" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b30af9e2d358182b5c7449424f017eba305ed32a7010509ede96cdc4696c46ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "642f325be6301eb8107a83d12a8ac6c1e1c54345a7ef1a9261962dfefda09e66" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f186bd2dcf04330886ce82d6f33dd75a7bfcf69ecf5763b89fcde53b6ac9838" + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.0", +] + [[package]] name = "windows-sys" version = "0.48.0" diff --git a/Cargo.toml b/Cargo.toml index 417031d..70c9e9c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,3 +10,11 @@ dotenv = "0.15.0" tokio = { version = "1.33.0", features = ["full"] } twitch-irc = "5.0.1" rand = { version = "0.8.5", features = [] } +futures = "0.3" +async-trait = "0.1.77" +casual_logger = "0.6.5" + + +[lib] +name = "botLib" +path = "src/lib.rs" \ No newline at end of file diff --git a/src/core.rs b/src/core.rs index 320ee73..7027176 100644 --- a/src/core.rs +++ b/src/core.rs @@ -1,6 +1,7 @@ pub mod botinstance; -pub mod ratelimiter; pub mod botmodules; +pub mod identity; +pub mod ratelimiter; // pub fn init() -> () // { diff --git a/src/core/botinstance.rs b/src/core/botinstance.rs index c2bff7a..05cc69f 100644 --- a/src/core/botinstance.rs +++ b/src/core/botinstance.rs @@ -1,157 +1,406 @@ - +// use futures::lock::Mutex; use tokio::sync::mpsc::UnboundedReceiver; +use tokio::sync::RwLock; use twitch_irc::login::StaticLoginCredentials; -use twitch_irc::ClientConfig; -use twitch_irc::SecureTCPTransport; -use twitch_irc::TwitchIRCClient; use twitch_irc::message::PrivmsgMessage; use twitch_irc::message::ServerMessage; use twitch_irc::transport::tcp::TCPTransport; use twitch_irc::transport::tcp::TLS; -use std::env; +use twitch_irc::ClientConfig; +use twitch_irc::SecureTCPTransport; +use twitch_irc::TwitchIRCClient; +// use std::borrow::Borrow; use dotenv::dotenv; +use std::borrow::BorrowMut; +use std::boxed; +use std::cell::Ref; +use std::env; use std::collections::HashMap; use rand::Rng; +// Important to use tokios Mutex here since std Mutex doesn't work with async functions +use tokio::sync::Mutex; -use crate::core::ratelimiter::RateLimiter; + +use crate::core::botmodules::BotAction; use crate::core::ratelimiter; +use crate::core::ratelimiter::RateLimiter; use crate::core::botmodules; use crate::core::botmodules::ModulesManager; +use crate::core::identity::{ChangeResult, IdentityManager, Permissible}; + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; +// use futures::lock::Mutex; + +use std::pin::Pin; + +//use std::borrow::Borrow; +use core::borrow::Borrow; + +// pub type BotAR = Arc>; +use super::botmodules::bot_actions::actions_util::BotAR; + +use casual_logger::{Level, Log}; + +pub mod botlog { + + /* + Module intends to add some layers to logging with the module user only requiring to pass : + - String Log message + - Option - Code_Module + - Option - this is used to parse out Chatter & Channel into the logs + */ + + use casual_logger::{Level, Log}; + use twitch_irc::message::PrivmsgMessage; + + // trace, debug, info, notice, warn, error, fatal + + /* + + in main : Log::debug("Checking bot actions", Some("main()".to_string()), None); + + in log : + [blalba@timestmp] + debug = "Checking bot actions", + + */ + + pub fn trace( + in_msg: &str, + in_module: Option, + in_prvmsg: Option<&PrivmsgMessage>, + ) -> () { + let (chnl, chatter) = match in_prvmsg { + Some(prvmsg) => { + //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); + ( + Some(prvmsg.channel_login.clone()), + Some(prvmsg.sender.name.clone()), + ) // <-- Clone fine atm while we're just working with Strings + } + None => (None, None), + }; + + Log::trace_t( + in_msg, + casual_logger::Table::default() // + .str("Channel", &format!("{:?}", chnl)) + .str("Chatter", &format!("{:?}", chatter)) + .str("Code_Module", &format!("{:?}", in_module)), + ); + } + + pub fn debug( + in_msg: &str, + in_module: Option, + in_prvmsg: Option<&PrivmsgMessage>, + ) -> () { + let (chnl, chatter) = match in_prvmsg { + Some(prvmsg) => { + //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); + ( + Some(prvmsg.channel_login.clone()), + Some(prvmsg.sender.name.clone()), + ) // <-- Clone fine atm while we're just working with Strings + } + None => (None, None), + }; + + Log::debug_t( + in_msg, + casual_logger::Table::default() // + .str("Channel", &format!("{:?}", chnl)) + .str("Chatter", &format!("{:?}", chatter)) + .str("Code_Module", &format!("{:?}", in_module)), + ); + } + + pub fn info(in_msg: &str, in_module: Option, in_prvmsg: Option<&PrivmsgMessage>) -> () { + let (chnl, chatter) = match in_prvmsg { + Some(prvmsg) => { + //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); + ( + Some(prvmsg.channel_login.clone()), + Some(prvmsg.sender.name.clone()), + ) // <-- Clone fine atm while we're just working with Strings + } + None => (None, None), + }; + + Log::info_t( + in_msg, + casual_logger::Table::default() // + .str("Channel", &format!("{:?}", chnl)) + .str("Chatter", &format!("{:?}", chatter)) + .str("Code_Module", &format!("{:?}", in_module)), + ); + } + + pub fn notice( + in_msg: &str, + in_module: Option, + in_prvmsg: Option<&PrivmsgMessage>, + ) -> () { + let (chnl, chatter) = match in_prvmsg { + Some(prvmsg) => { + //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); + ( + Some(prvmsg.channel_login.clone()), + Some(prvmsg.sender.name.clone()), + ) // <-- Clone fine atm while we're just working with Strings + } + None => (None, None), + }; + + Log::notice_t( + in_msg, + casual_logger::Table::default() // + .str("Channel", &format!("{:?}", chnl)) + .str("Chatter", &format!("{:?}", chatter)) + .str("Code_Module", &format!("{:?}", in_module)), + ); + } + + pub fn warn(in_msg: &str, in_module: Option, in_prvmsg: Option<&PrivmsgMessage>) -> () { + let (chnl, chatter) = match in_prvmsg { + Some(prvmsg) => { + //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); + ( + Some(prvmsg.channel_login.clone()), + Some(prvmsg.sender.name.clone()), + ) // <-- Clone fine atm while we're just working with Strings + } + None => (None, None), + }; + + Log::warn_t( + in_msg, + casual_logger::Table::default() // + .str("Channel", &format!("{:?}", chnl)) + .str("Chatter", &format!("{:?}", chatter)) + .str("Code_Module", &format!("{:?}", in_module)), + ); + } + + pub fn error( + in_msg: &str, + in_module: Option, + in_prvmsg: Option<&PrivmsgMessage>, + ) -> () { + let (chnl, chatter) = match in_prvmsg { + Some(prvmsg) => { + //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); + ( + Some(prvmsg.channel_login.clone()), + Some(prvmsg.sender.name.clone()), + ) // <-- Clone fine atm while we're just working with Strings + } + None => (None, None), + }; + + Log::error_t( + in_msg, + casual_logger::Table::default() // + .str("Channel", &format!("{:?}", chnl)) + .str("Chatter", &format!("{:?}", chatter)) + .str("Code_Module", &format!("{:?}", in_module)), + ); + } + + pub fn fatal<'a>( + in_msg: &'a str, + in_module: Option, + in_prvmsg: Option<&PrivmsgMessage>, + ) -> &'a str { + let (chnl, chatter) = match in_prvmsg { + Some(prvmsg) => { + //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); + ( + Some(prvmsg.channel_login.clone()), + Some(prvmsg.sender.name.clone()), + ) // <-- Clone fine atm while we're just working with Strings + } + None => (None, None), + }; + + Log::fatal_t( + in_msg, + casual_logger::Table::default() // + .str("Channel", &format!("{:?}", chnl)) + .str("Chatter", &format!("{:?}", chatter)) + .str("Code_Module", &format!("{:?}", in_module)), + ); + + in_msg + } +} #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub enum ChType { Channel(String), } - pub use ChType::Channel; -pub enum ModType { - BotModule(String), -} - -pub use ModType::BotModule; - #[derive(Clone)] pub struct Chat { - pub ratelimiters : HashMap, // used to limit messages sent per channel - pub client : TwitchIRCClient,StaticLoginCredentials>, + pub ratelimiters: Arc>>, // used to limit messages sent per channel + pub client: TwitchIRCClient, StaticLoginCredentials>, } impl Chat { + pub fn init( + ratelimiters: HashMap, + client: TwitchIRCClient, StaticLoginCredentials>, + ) -> Chat { + Chat { + ratelimiters: Arc::new(Mutex::new(ratelimiters)), + client: client, + } + } - - pub fn init_channel(&mut self, chnl:ChType) -> () { + pub async fn init_channel(&mut self, chnl: ChType) -> () { let n = RateLimiter::new(); - self.ratelimiters.insert(chnl,n); - } + self.ratelimiters.lock().await.insert(chnl, n); + } - - - pub async fn say_in_reply_to(&mut self, msg:& PrivmsgMessage , mut outmsg:String) -> () { + // pub async fn say_in_reply_to(&mut self, msg:& PrivmsgMessage , mut outmsg:String) -> () { + pub async fn say_in_reply_to(&self, msg: &PrivmsgMessage, mut outmsg: String) -> () { /* - formats message before sending to TwitchIRC + formats message before sending to TwitchIRC - [x] Custom String Formatting (e.g., adding random black spaces) - [x] Ratelimiter Handling - [ ] Checkf if BotActions is Enabled & Caller is Allowed to Run */ - - // self.client.say_in_reply_to(msg,outmsg).await.unwrap(); - // // let contextratelimiter = ratelimiters.get_mut(&msg.channel_login).expect("ERROR: Issue with Rate limiters"); - let contextratelimiter = self.ratelimiters + let a = Arc::clone(&self.ratelimiters); + let mut a = a.lock().await; + + let contextratelimiter = a + // .get_mut() .get_mut(&Channel(String::from(&msg.channel_login))) .expect("ERROR: Issue with Rate limiters"); - // let contextratelimiter = self.ratelimiters.get(&msg.channel_login).expect("ERROR: Issue with Rate limiters"); - + match contextratelimiter.check_limiter() { ratelimiter::LimiterResp::Allow => { let maxblanks = rand::thread_rng().gen_range(1..=20); - //let mut outmsg = "GotTrolled ".to_owned(); - // let mut outmsg = "annytfLurk ".to_owned(); - + for _i in 1..maxblanks { let blankspace: &str = "󠀀"; outmsg.push_str(blankspace); } - - // client.say_in_reply_to(&msg,outmsg).await.unwrap(); - self.client.say_in_reply_to(msg,outmsg).await.unwrap(); - println!("(#{}) > {}", msg.channel_login, "rate limit counter increase"); + + self.client.say_in_reply_to(msg, outmsg).await.unwrap(); + // println!("(#{}) > {}", msg.channel_login, "rate limit counter increase"); + // Log::trace(&format!("(#{}) > {}", msg.channel_login, "rate limit counter increase")); + botlog::trace( + &format!( + "(#{}) > {}", + msg.channel_login, "rate limit counter increase" + ), + Some("Chat > say_in_reply_to".to_string()), + Some(&msg), + ); contextratelimiter.increment_counter(); - println!("{:?}",self.ratelimiters); - }, + // println!("{:?}",self.ratelimiters); + // Log::trace(&format!("{:?}",self.ratelimiters)); + botlog::trace( + &format!("{:?}", self.ratelimiters), + Some("Chat > say_in_reply_to".to_string()), + Some(&msg), + ); + } ratelimiter::LimiterResp::Skip => { (); // do nothing otherwise } - - } + } + Log::flush(); } - - async fn say(&self, _:String, _:String) -> () { - // more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say - - - // self.client.say(msg,outmsg).await.unwrap(); - - - } - - - async fn me(&self, _:String, _:String) -> () { - // more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say - - - // self.client.me(msg,outmsg).await.unwrap(); - - - } - - async fn me_in_reply_to(&self, _:String, _:String) -> () { - // more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say - - - // self.client.me(msg,outmsg).await.unwrap(); - - - } + async fn say(&self, _: String, _: String) -> () { + // more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say + // self.client.say(msg,outmsg).await.unwrap(); + } + + async fn me(&self, _: String, _: String) -> () { + // more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say + + // self.client.me(msg,outmsg).await.unwrap(); + } + + async fn me_in_reply_to(&self, _: String, _: String) -> () { + // more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say + + // self.client.me(msg,outmsg).await.unwrap(); + } } - - -pub struct BotInstance -{ - prefix : char, - bot_channel : ChType, - pub incoming_messages : UnboundedReceiver, - pub chat : Chat, - pub botmodules : ModulesManager, - twitch_oauth : String, - pub bot_channels : Vec, +#[derive(Clone)] +pub struct BotManagers { + // pub botmodules : ModulesManager, + pub identity: Arc>, + pub chat: Chat, } +impl BotManagers { + pub fn init( + ratelimiters: HashMap, + client: TwitchIRCClient, StaticLoginCredentials>, + ) -> BotManagers { + BotManagers { + identity: Arc::new(RwLock::new(IdentityManager::init())), + chat: Chat::init(ratelimiters, client), + } + } + pub fn rIdentity(self) -> Arc> { + self.identity + } +} -impl BotInstance -{ +pub struct ArcBox(pub Arc>); +impl ArcBox { + pub fn inst(&self) -> &Mutex { + &self.0 + } +} - pub fn init() -> BotInstance - { +//#[derive(Clone)] +// #[derive(Copy)] // <-- Cannot be derived +pub struct BotInstance { + pub prefix: char, + pub bot_channel: ChType, + pub incoming_messages: Arc>>, + pub botmodules: Arc, + pub twitch_oauth: String, + pub bot_channels: Vec, + pub botmgrs: BotManagers, + //modesmgr : ModesManager, // Silent/Quiet , uwu , frisky/horny +} + +impl BotInstance { + pub async fn init() -> BotInstance { dotenv().ok(); let login_name = env::var("login_name").unwrap().to_owned(); let oauth_token = env::var("access_token").unwrap().to_owned(); - let prefix = env::var("prefix").unwrap().to_owned().chars().next().expect("ERROR : when defining prefix"); + let prefix = env::var("prefix") + .unwrap() + .to_owned() + .chars() + .next() + .expect("ERROR : when defining prefix"); /* Vector of channels to join @@ -164,12 +413,13 @@ impl BotInstance botchannels.push(Channel(String::from(chnl))); } - let config = ClientConfig::new_simple( - StaticLoginCredentials::new(login_name.to_owned(), Some(oauth_token.to_owned())) - ); + let config = ClientConfig::new_simple(StaticLoginCredentials::new( + login_name.to_owned(), + Some(oauth_token.to_owned()), + )); let (incoming_messages, client) = - TwitchIRCClient::::new(config); + TwitchIRCClient::::new(config); // hashmap for channels and their associated ratelimiters let mut ratelimiters = HashMap::new(); @@ -179,148 +429,390 @@ impl BotInstance client.join(chnl.to_owned()).unwrap(); - // ratelimiters are a hashmap of channel and a corresponding rate limiter + // ratelimiters are a hashmap of channel and a corresponding rate limiter let n = RateLimiter::new(); - ratelimiters.insert(Channel(String::from(chnl)),n); + ratelimiters.insert(Channel(String::from(chnl)), n); //self.chat.ratelimiters.insert(Channel(String::from(chnl)),n); } + // let b = BotInstance { + // prefix : prefix, + // bot_channel : Channel(login_name) , + // incoming_messages : Arc::new(RwLock::new(incoming_messages)), + // botmodules : ModulesManager::init().await, + // twitch_oauth : oauth_token, + // bot_channels : botchannels, + // botmgrs : BotManagers::init(ratelimiters,client), + // }; + BotInstance { + prefix: prefix, + bot_channel: Channel(login_name), + incoming_messages: Arc::new(RwLock::new(incoming_messages)), + botmodules: ModulesManager::init().await, + twitch_oauth: oauth_token, + bot_channels: botchannels, + botmgrs: BotManagers::init(ratelimiters, client), + } - // let bm = &mut ModulesManager::init(); - - - - let b = BotInstance { - prefix : prefix, - bot_channel : Channel(login_name) , - incoming_messages : incoming_messages, - //client : client, - chat : Chat { - ratelimiters : ratelimiters, - client : client, - } , - botmodules : ModulesManager::init(), - twitch_oauth : oauth_token, - bot_channels : botchannels, - }; - - - println!("{:?}",b.chat.ratelimiters); - - - b + // b } - pub async fn runner(mut self) -> () { + pub async fn runner(self) -> () { + let bot = Arc::new(RwLock::new(self)); let join_handle = tokio::spawn(async move { - - while let Some(message) = self.incoming_messages.recv().await { - // Below can be used to debug if I want to capture all messages - //println!("Received message: {:?}", message); - + let a = bot.read().await; + let mut a = a.incoming_messages.write().await; + while let Some(message) = a.recv().await { match message { ServerMessage::Notice(msg) => { - // if let Some(chnl) = msg.channel_login { - // println!("NOTICE : (#{}) {}", chnl, msg.message_text); - // } - match msg.channel_login { - Some(chnl) => println!("NOTICE : (#{}) {}", chnl, msg.message_text), - None => println!("NOTICE : {}", msg.message_text), + match &msg.channel_login { + Some(chnl) => { + // println!("NOTICE : (#{}) {}", chnl, msg.message_text) + // Log::notice(&format!("NOTICE : (#{}) {}", chnl, msg.message_text)); + botlog::notice( + &format!("NOTICE : (#{}) {}", chnl, msg.message_text), + Some("BotInstance > runner()".to_string()), + None, + ); + } + None => { + // println!("NOTICE : {}", msg.message_text); + // Log::notice(&format!("NOTICE : {}", msg.message_text)); + botlog::notice( + &format!("NOTICE : {}", msg.message_text), + Some("BotInstance > runner()".to_string()), + None, + ); + } } } ServerMessage::Privmsg(msg) => { - println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); + // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); + // Log::trace(&format!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text)); + botlog::debug( + &format!( + "Twitch Chat > {} @ #{}: {}", + msg.channel_login, msg.sender.name, msg.message_text + ), + Some("BotInstance > runner()".to_string()), + Some(&msg), + ); - println!("Privmsg section"); + // println!("Privmsg section"); + // Log::debug(&format!("Privmsg section")); + botlog::trace( + &format!("Privmsg section"), + Some("BotInstance > runner()".to_string()), + Some(&msg), + ); - // b.listener_main_prvmsg(&msg); - self.listener_main_prvmsg(msg).await; - // - BotCommand listener should likely need to be called within the above - - - }, + BotInstance::listener_main_prvmsg(Arc::clone(&bot), &msg).await; + } ServerMessage::Whisper(msg) => { - println!("(w) {}: {}", msg.sender.name, msg.message_text); - }, + // println!("(w) {}: {}", msg.sender.name, msg.message_text); + // Log::trace(&format!("(w) {}: {}", msg.sender.name, msg.message_text)); + botlog::trace( + &format!("(w) {}: {}", msg.sender.name, msg.message_text), + Some("BotInstance > runner()".to_string()), + None, + ); + } ServerMessage::Join(msg) => { - println!("JOINED: {}", msg.channel_login); - }, + // println!("JOINED: {}", msg.channel_login); + // Log::notice(&format!("JOINED: {}", msg.channel_login)); + botlog::notice( + &format!("JOINED: {}", msg.channel_login), + Some("BotInstance > runner()".to_string()), + None, + ); + } ServerMessage::Part(msg) => { - println!("PARTED: {}", msg.channel_login); - }, + // println!("PARTED: {}", msg.channel_login); + // Log::notice(&format!("PARTED: {}", msg.channel_login)); + botlog::notice( + &format!("PARTED: {}", msg.channel_login), + Some("BotInstance > runner()".to_string()), + None, + ); + } _ => {} - } + }; + Log::flush(); } }); - - - - - + join_handle.await.unwrap(); } + pub fn get_botmodules(self) -> Arc { + self.botmodules + } -// ----------------- -// PRIVATE FUNCTIONS + pub async fn get_botmgrs(self) -> BotManagers { + let a = self.botmgrs; + a + } + pub fn get_identity(&self) -> Arc> { + Arc::clone(&self.botmgrs.identity) + } - async fn listener_main_prvmsg(&mut self,msg:PrivmsgMessage) -> () { + pub fn get_prefix(&self) -> char { + (*self).prefix + } + // ----------------- + // PRIVATE FUNCTIONS + + pub async fn listener_main_prvmsg(bot: BotAR, msg: &PrivmsgMessage) -> () { + // println!(">> Inner listenermain_prvmsg()"); + // Log::trace(">> Inner listenermain_prvmsg()"); + botlog::trace( + ">> Inner listenermain_prvmsg()", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + // let a = a; // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); - + // // [ ] Need to run through all Listener Bodies for Enabled Modules for the context of the message (e.g., ModStatus is Enabled in the context for the channel) - for (_m,acts) in &self.botmodules.botactions { + let botlock = bot.read().await; + let hacts = Arc::clone(&botlock.botmodules.botactions); + // let hacts = hacts.read().await; + let a = hacts.read().await; + // println!("hacts size : {}",(*a).len()); + // Log::debug(&format!("hacts size : {}",(*a).len())); + botlog::trace( + &format!("hacts size : {}", (*a).len()), + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + // println!(">> Inner listenermain_prvmsg() >> before for loop of bot actions"); + // Log::trace(">> Inner listenermain_prvmsg() >> before for loop of bot actions"); + botlog::trace( + ">> Inner listenermain_prvmsg() >> before for loop of bot actions", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + for (_m, acts) in &*hacts.read().await { + // println!(">> Inner listenermain_prvmsg() >> checking bot actions"); + // Log::trace(">> Inner listenermain_prvmsg() >> checking bot actions"); + botlog::trace( + ">> Inner listenermain_prvmsg() >> checking bot actions", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + // let bot = bot; + for a in acts { + // println!(">> Inner listenermain_prvmsg() >> checking bot actions >> 2"); + // Log::trace(">> Inner listenermain_prvmsg() >> checking bot actions >> 2"); + botlog::trace( + ">> Inner listenermain_prvmsg() >> checking bot actions >> 2", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); - match a { - + let _act = match a { crate::core::botmodules::BotAction::C(c) => { - /* + /* BotCommand handling - - [x] Checks if the input message is a prefix with command name or alias + - [ ] Validate User can run based on identityModule(From_Bot)::can_user_run( + _usr:String, + _channelname:ChType, + _chat_badge:ChatBadge, + _cmdreqroles:Vec) */ - let inpt = msg.message_text.split("\n").next().expect("ERROR during BotCommand"); + // for v in msg.message_text.split(" ") { + // println!("args : {v}"); + // } + + // println!("Reviewing internal commands"); + // Log::trace("Reviewing internal commands"); + botlog::trace( + "Reviewing internal commands", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + // let inpt = msg.message_text.split("\n").next().expect("ERROR during BotCommand"); + let inpt = msg + .message_text + .split(" ") + .next() + .expect("ERROR during BotCommand"); // [x] Check if a bot command based on ... // [x] prefix + command - if inpt == self.prefix.to_string() + c.command.as_str() { - c.execute(self.chat.clone(), msg.clone()).await; - } + + let mut confirmed_bot_command = false; + + let instr = bot.read().await.get_prefix(); + if inpt == String::from(instr) + c.command.as_str() { + confirmed_bot_command = true; + } // [x] prefix + alias for alias in &c.alias { - if inpt == self.prefix.to_string() + alias.as_str() { - c.execute(self.chat.clone(), msg.clone()).await; - } + let instr = bot.read().await.get_prefix(); + if inpt == String::from(instr) + alias.as_str() { + confirmed_bot_command = true; + } } - }, - crate::core::botmodules::BotAction::L(l) => l.execute(self.chat.clone(), msg.clone()).await, + if confirmed_bot_command { + // println!("Confirmed bot command"); + // Log::debug("Confirmed bot command"); + botlog::debug( + "Confirmed bot command", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + // println!("Going for botlock"); + // Log::trace("Going for botlock"); + botlog::trace( + "Going for botlock", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + let botlock = bot.read().await; + // println!("Going for identity"); + // Log::trace("Going for identity"); + botlog::trace( + "Going for identity", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + let id = botlock.get_identity(); + + let eval = { + let mut id = id.write().await; + // println!("Unlocking identity"); + // Log::trace("Unlocking identity"); + botlog::trace( + "Unpacking identity", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + let (a, b) = + id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await; + // // [-] #todo : need ot add functionality around here to do an o7 when a mod has been promoted => Preferring to do this outside the mutex + // if let ChangeResult::Success(b) = b { + // // let b = b.to_lowercase(); + // // let b = b.contains(&"Auto Promoted Mod".to_lowercase()); + // if b.to_lowercase().contains(&"Auto Promoted Mod".to_lowercase()) { + // let chat = + // } + // } + (a, b) + }; + // println!("Checking if permissible"); + Log::trace("Checking if permissible"); + botlog::trace( + "Checking if permissible", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + let (eval, rolechange) = eval; + + if let ChangeResult::Success(b) = rolechange { + if b.to_lowercase() + .contains(&"Auto Promoted Mod".to_lowercase()) + { + botlog::notice( + "Assigning Mod UserRole to Mod", + Some("botinstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + // println!("Read() lock Bot"); + // Log::trace("Read() lock Bot"); + botlog::trace( + "Read() lock Bot", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + + let botlock = bot.read().await; + let outstr = + "o7 a Mod. I kneel to serve! pepeKneel ".to_string(); + (*botlock).botmgrs.chat.say_in_reply_to(msg, outstr).await; + } + } + + match eval { + Permissible::Allow => { + // println!("Executed as permissible"); + // Log::debug("Executed as permissible"); + botlog::debug( + "Executed as permissible", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + let a = Arc::clone(&bot); + c.execute(a, msg.clone()).await; + // println!("exit out of execution"); + // Log::trace("exit out of execution"); + botlog::trace( + "exit out of execution", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + } + Permissible::Block => { + // println!("User Not allowed to run command"); + // Log::info("User Not allowed to run command"); + botlog::info( + "User Not allowed to run command", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + } // _ => (), + }; + } + } + + crate::core::botmodules::BotAction::L(l) => { + let a = Arc::clone(&bot); + l.execute(a, msg.clone()).await; + } + _ => (), - } + }; } - }; + } // // [ ] There should be a BotCommand Listener to check for prefixes ran - println!("End of Separate Listener Main prvmsg"); + // println!("End of Separate Listener Main prvmsg"); + // Log::trace("End of Separate Listener Main prvmsg"); + botlog::trace( + "End of Separate Listener Main prvmsg", + Some("BotInstance > listener_main_prvmsg()".to_string()), + Some(&msg), + ); + // self + // bot + + Log::flush(); } - - - } - - - - - // ====================================== // ====================================== // ====================================== @@ -328,13 +820,9 @@ impl BotInstance // UNIT TEST MODULES - - - - #[cfg(test)] mod tests { fn always() { - assert_eq!(1,1); + assert_eq!(1, 1); } } diff --git a/src/core/botmodules.rs b/src/core/botmodules.rs index aab2cf2..2a38523 100644 --- a/src/core/botmodules.rs +++ b/src/core/botmodules.rs @@ -1,25 +1,44 @@ -use core::{panic}; +use core::panic; use std::error::Error; use std::collections::HashMap; +use crate::core::identity; + +use std::cell::RefCell; +use std::sync::Arc; +use tokio::sync::RwLock; + +use std::future::Future; +// use futures::lock::Mutex; + +// Important to use tokios Mutex here since std Mutex doesn't work with async functions +use tokio::sync::Mutex; + +use crate::core::botinstance::{self, botlog, BotInstance}; +use std::rc::Rc; + +// use tokio::sync::RwLock; + +use async_trait::async_trait; +use casual_logger::{Level, Log}; /* -ModulesManager is used to manage Modules and BotActions associated with those modules +ModulesManager is used to manage Modules and BotActions associated with those modules pub struct ModulesManager { statusdb: HashMap>, - botactions: HashMap>, + botactions: HashMap>, } - statusdb: HashMap> - Defines Modules and their ModStatusType (e.g., Enabled at an Instance level, Disabled at a Channel Level) -- botactions: HashMap> - Defines Modules and their BotActions (e.g., BotCommand , Listener, Routine) +- botactions: HashMap> - Defines Modules and their BotActions (e.g., BotCommand , Listener, Routine) Example { - ModulesManager { - statusdb: {BotModule("experiments 004"): [Enabled(Instance)]}, + ModulesManager { + statusdb: {BotModule("experiments 004"): [Enabled(Instance)]}, botactions: {BotModule("experiments 004"): [C(BotCommand { module: BotModule("experiments 004"), command: "DUPCMD4", alias: ["DUPALIAS4A", "DUPALIAS4B"], help: "DUPCMD4 tester" })]} } } @@ -29,20 +48,21 @@ Example pub enum ModType { BotModule(String), } - + pub use ModType::BotModule; -#[derive(Debug, PartialEq, Eq, Hash)] -pub enum ChType { - Channel(String), -} +// #[derive(Debug, PartialEq, Eq, Hash, Clone)] +// pub enum ChType { +// Channel(String), +// } +use botinstance::ChType; -pub use ChType::Channel; use twitch_irc::message::PrivmsgMessage; +pub use ChType::Channel; -use crate::core::botinstance::{self, BotInstance}; - +use self::bot_actions::actions_util; +use self::bot_actions::actions_util::BotAR; #[derive(Debug)] enum StatusLvl { @@ -55,186 +75,225 @@ pub enum ModStatusType { Enabled(StatusLvl), Disabled(StatusLvl), } - -pub enum BotAction -{ - C(BotCommand), + +// #[derive(Clone)] +pub enum BotAction { + C(BotCommand), L(Listener), - R(Routine), + R(Routine), } impl BotAction { - pub async fn execute(&self,m:botinstance::Chat,n:PrivmsgMessage){ - + pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) -> () { match self { - BotAction::L(a) => a.execute(m,n).await, - BotAction::C(a) => a.execute(m,n).await, + BotAction::L(a) => a.execute(m, n).await, + BotAction::C(a) => a.execute(m, n).await, _ => (), } - } } -pub trait BotActionTrait -{ - fn add_to_bot(self, bot:BotInstance); - fn add_to_modmgr(self,modmgr:&mut ModulesManager); +#[async_trait] +pub trait BotActionTrait { + async fn add_to_bot(self, bot: BotInstance); + async fn add_to_modmgr(self, modmgr: Arc); } - +// #[derive(Clone)] pub struct BotCommand { - pub module : ModType, - pub command : String, // command call name - pub alias : Vec, // String of alternative names + pub module: ModType, + pub command: String, // command call name + pub alias: Vec, // String of alternative names // bot_prefix : char, // although should be global? - pub exec_body : bot_actions::actions_util::ExecBody, - pub help : String, + pub exec_body: bot_actions::actions_util::ExecBody, + pub help: String, + pub required_roles: Vec, } -impl BotCommand -{ - pub async fn execute(&self,m:botinstance::Chat,n:PrivmsgMessage){ - (self.exec_body)(m,n).await; +impl BotCommand { + pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) -> () { + ((*self).exec_body)(m, n).await; } } - -impl BotActionTrait for BotCommand -{ - fn add_to_bot(self, mut bot:BotInstance) { - let mgr = &mut bot.botmodules; - self.add_to_modmgr(mgr); +#[async_trait] +impl BotActionTrait for BotCommand { + async fn add_to_bot(self, bot: BotInstance) { + self.add_to_modmgr(bot.botmodules).await; } - fn add_to_modmgr(self, modmgr:&mut ModulesManager) { - modmgr.add_botaction(self.module.clone(), BotAction::C(self)) + // async fn add_to_modmgr(self, modmgr:Arc>) { + async fn add_to_modmgr(self, modmgr: Arc) { + modmgr + .add_botaction(self.module.clone(), BotAction::C(self)) + .await } - } - - pub mod bot_actions { pub mod actions_util { - - use std::future::Future; + use std::boxed::Box; + use std::future::Future; use std::pin::Pin; - use crate::core::botinstance::Chat; - use twitch_irc::message::PrivmsgMessage; - - pub type ExecBody = Box Pin + Send>> + Send + Sync>; + use std::rc::Rc; - pub fn asyncbox(f: fn(Chat,PrivmsgMessage) -> T) -> ExecBody + use crate::core::botinstance::{BotInstance, BotManagers, Chat}; + use std::cell::RefCell; + use std::sync::Arc; + use twitch_irc::message::PrivmsgMessage; + // use futures::lock::Mutex; + // Important to use tokios Mutex here since std Mutex doesn't work with async functions + use tokio::sync::{Mutex, RwLock}; + + pub type BotAM = Arc>; + pub type BotAR = Arc>; + + pub type ExecBody = Box< + dyn Fn(BotAR, PrivmsgMessage) -> Pin + Send>> + Send + Sync, + >; + + pub fn asyncbox(f: fn(BotAR, PrivmsgMessage) -> T) -> ExecBody where - T: Future + Send + 'static, + T: Future + Send + 'static, { - Box::new(move |a,b| Box::pin(f(a,b))) + Box::new(move |a, b| Box::pin(f(a, b))) } } - - } - - -pub struct Listener -{ - pub module : ModType, - pub name : String, - pub exec_body : bot_actions::actions_util::ExecBody, - pub help : String +pub struct Listener { + pub module: ModType, + pub name: String, + pub exec_body: bot_actions::actions_util::ExecBody, + pub help: String, } -impl Listener -{ - pub async fn execute(&self,m:botinstance::Chat,n:PrivmsgMessage){ - (self.exec_body)(m,n).await; +impl Listener { + pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) -> () { + ((*self).exec_body)(m, n).await; } } -impl BotActionTrait for Listener -{ - fn add_to_bot(self, mut bot:BotInstance) { - - let mgr = &mut bot.botmodules; - - self.add_to_modmgr(mgr); +#[async_trait] +impl BotActionTrait for Listener { + async fn add_to_bot(self, bot: BotInstance) { + // println!("Adding action to bot"); + // Log::trace("Adding action to bot"); + botinstance::botlog::trace( + "Adding action to bot", + Some("BotModules > BotActionTrait > add_to_bot()".to_string()), + None, + ); + self.add_to_modmgr(bot.botmodules).await; } - fn add_to_modmgr(self, modmgr:&mut ModulesManager) { - modmgr.add_botaction(self.module.clone(), BotAction::L(self)) - } + async fn add_to_modmgr(self, modmgr: Arc) { + // let modmgr = *modmgr.lock().await; + // println!("Adding action to module manager"); + // Log::trace("Adding action to module manager"); + botinstance::botlog::trace( + "Adding action to module manager", + Some("BotModules > BotActionTrait > add_to_bot()".to_string()), + None, + ); + modmgr + .add_botaction(self.module.clone(), BotAction::L(self)) + .await; + } } - - #[derive(Debug)] struct Routine {} -pub struct ModulesManager -{ - statusdb: HashMap>, - pub botactions: HashMap>, +// #[derive(Clone)] + +pub struct ModulesManager { + statusdb: Arc>>>, + pub botactions: Arc>>>, } -impl ModulesManager -{ +/* - pub fn init() -> ModulesManager - { +statusdb + <-- shows Enabled/Disabled per Status level +botactions + HashMap< + ModType, <-- e.g., BotModule(String::from("experiments001")) + Vec> BotCommand, Listener +*/ + +impl ModulesManager { + pub async fn init() -> Arc { let m = HashMap::new(); let act = HashMap::new(); let mut mgr = ModulesManager { - statusdb : m, - botactions : act, + statusdb: Arc::new(RwLock::new(m)), + botactions: Arc::new(RwLock::new(act)), }; + // :: [x] initialize core modules - // initialize custom crate modules - crate::modules::init(&mut mgr); + // println!("ModulesManager > init() > Adding modules"); + botlog::debug( + "ModulesManager > init() > Adding modules", + Some("ModulesManager > init()".to_string()), + None, + ); + let mgra = Arc::new(mgr); + crate::core::identity::init(Arc::clone(&mgra)).await; + crate::modules::init(Arc::clone(&mgra)).await; + // println!(">> Modules Manager : End of Init"); + botlog::trace( + ">> Modules Manager : End of Init", + Some("ModulesManager > init()".to_string()), + None, + ); - println!(">> Modules Manager : End of Init"); + mgra + } - mgr - } - - pub fn modstatus(&self, _:ModType, _:ChType) -> ModStatusType { + pub fn modstatus(&self, _: ModType, _: ChType) -> ModStatusType { // Example usage : botmanager.modstatus( // BotModule("GambaCore"), // Channel("modulatingforce") - // ) - // - The ModStatusType checks in the context of the given channel , + // ) + // - The ModStatusType checks in the context of the given channel , // but also validates based on wheher the module is disabled at a bot instance // level as well ModStatusType::Enabled(StatusLvl::Instance) } - - pub fn togglestatus(&self, _:ModType, _:ChType) -> ModStatusType { + pub fn togglestatus(&self, _: ModType, _: ChType) -> ModStatusType { // enables or disables based on current status ModStatusType::Enabled(StatusLvl::Instance) } - - pub fn setstatus(&self, _:ModType, _:ModStatusType) -> Result<&str,Box> { + pub fn setstatus(&self, _: ModType, _: ModStatusType) -> Result<&str, Box> { // sets the status based given ModSatusType // e.g., b.setstatus(BodModule("GambaCore"), Enabled(Channel("modulatingforce"))).expect("ERROR") Ok("") } - //pub fn add_botaction(mut self, in_module:ModType, in_action:BotAction ) -> ModulesManager { - // pub fn add_botaction(mut self, in_module:ModType, in_action:BotAction ) -> ModulesManager { - //pub fn add_botaction(&mut self, in_module:ModType, in_action:BotAction ) -> () { - pub fn add_botaction(&mut self, in_module:ModType, in_action:BotAction ) { + pub async fn add_botaction(&self, in_module: ModType, in_action: BotAction) { + // println!("Add botaction called"); + + botlog::trace( + "Add botaction called", + Some("ModulesManager > init()".to_string()), + None, + ); + /* adds a BotAction to the Modules Manager - This will require a BotModule passed as well This will including the logic of a valid add @@ -244,7 +303,7 @@ impl ModulesManager -- In particular to BotCommands, which must have Unique command call names and aliases that to not conflict with any other already BotCommand added name or alias Other types might be fine? For example, if 2 modules have their own listeners but each have the name "targetchatter" , - both would be called separately, even if they both have the same or different logic + both would be called separately, even if they both have the same or different logic */ // let newlistener = Listener { @@ -254,20 +313,15 @@ impl ModulesManager // help : String::from("This will listen and react to sock randomly"), // }; - // As a Demonstration, the listener's Module is added and Enabled at Instance level - - // [x] Before Adding, validate the following : - // - If BotAction to Add is a BotCommand , In Module Manager DB (botactions), + // [x] Before Adding, validate the following : + // - If BotAction to Add is a BotCommand , In Module Manager DB (botactions), // Check All Other BotAction Command Names & Aliases to ensure they don't conflict - fn find_conflict_module(mgr:& ModulesManager, act:& BotAction) -> Option - { - + async fn find_conflict_module(mgr: &ModulesManager, act: &BotAction) -> Option { // Some(BotModule(String::from("GambaCore"))) - // match act { // BotAction::C(c) => { // Some(BotModule(String::from("GambaCore"))) @@ -276,118 +330,110 @@ impl ModulesManager // BotAction::R(r) => None, // } - // if let BotAction::C(incmd) = act { + if let BotAction::C(incmd) = act { + // let n = & mgr.botactions; - // // let n = & mgr.botactions; + let d = mgr.botactions.read().await; + let d = &(*d); - // let d = &mgr.botactions; + for (module, moduleactions) in d { + for modact in moduleactions.iter() { + if let BotAction::C(dbcmd) = &modact { + // At this point, there is an command incmd and looked up dbcmd - // for (module,moduleactions) in d { - - - // for modact in moduleactions.iter() { - // if let BotAction::C(dbcmd) = &modact { - // // At this point, there is an command incmd and looked up dbcmd + // [x] check if given botcommand c.command:String conflicts with any in botactions - // // [x] check if given botcommand c.command:String conflicts with any in botactions + if incmd.command.to_lowercase() == dbcmd.command.to_lowercase() { + // Returning State - with the identified module + // return Some((module.clone(),BotAction::C(*dbcmd.clone()))); + // return Some(incmd); // for some reason I keep getting issues + //return Some(BotModule(String::from("GambaCore"))); // works + return Some(module.clone()); // works + // return Some(dbcmd.clone()); + } - // if incmd.command.to_lowercase() == dbcmd.command.to_lowercase() { - // // Returning State - with the identified module - // // return Some((module.clone(),BotAction::C(*dbcmd.clone()))); - // // return Some(incmd); // for some reason I keep getting issues - // //return Some(BotModule(String::from("GambaCore"))); // works - // return Some(module.clone()); // works - // // return Some(dbcmd.clone()); - // } + for a in &dbcmd.alias { + if incmd.command.to_lowercase() == a.to_lowercase() { + // Returning State - with the identified module + // return Some((module.clone(),BotAction::C(dbcmd))); + return Some(module.clone()); // works + } + } - // for a in &dbcmd.alias { - // if incmd.command.to_lowercase() == a.to_lowercase() { - // // Returning State - with the identified module - // // return Some((module.clone(),BotAction::C(dbcmd))); - // return Some(module.clone()); // works + // [x] Then do the same check except for each c.alias - // } - // } + for inalias in &incmd.alias { + if inalias.to_lowercase() == dbcmd.command.to_lowercase() { + // Returning State - with the identified module + // return Some((module.clone(),BotAction::C(dbcmd))); + return Some(module.clone()); // works + } + for a in &dbcmd.alias { + if inalias.to_lowercase() == a.to_lowercase() { + // Returning State - with the identified module + // return Some((module.clone(),BotAction::C(dbcmd))); + return Some(module.clone()); // works + } + } + } + } + } + } - // // [x] Then do the same check except for each c.alias - - // for inalias in &incmd.alias { - - // if inalias.to_lowercase() == dbcmd.command.to_lowercase() { - // // Returning State - with the identified module - // // return Some((module.clone(),BotAction::C(dbcmd))); - // return Some(module.clone()); // works - - // } - - // for a in &dbcmd.alias { - // if inalias.to_lowercase() == a.to_lowercase() { - // // Returning State - with the identified module - // // return Some((module.clone(),BotAction::C(dbcmd))); - // return Some(module.clone()); // works - - // } - // } - - // } - - - // } - // } - - // } - - // // return Some(BotModule(String::from("GambaCore"))) - // } - + // return Some(BotModule(String::from("GambaCore"))) + } // for all other scenarios (e.g., Listener, Routine), find no conflicts None - } // if let probmod = find_conflict_module(&self, &in_action) { // // () // return because there was a conflict? // panic!("ERROR: Could not add {:?} ; there was a conflict with existing module {:?}", in_action , probmod ); // } - match find_conflict_module(&self, &in_action) { + match find_conflict_module(&self, &in_action).await { // Some(c) => panic!("ERROR: Could not add {:?} ; there was a conflict with existing module {:?}", in_action , c ), - Some(c) => panic!("ERROR: Could not add module; there was a conflict with existing module {:?}", c ), + Some(c) => panic!( + "ERROR: Could not add module; there was a conflict with existing module {:?}", + c + ), None => (), } - let statusvector = self.statusdb + let mut dbt = self.statusdb.write().await; + let statusvector = dbt // .entry(BotModule(String::from("experiments"))) .entry(in_module.clone()) .or_insert(Vec::new()); statusvector.push(ModStatusType::Enabled(StatusLvl::Instance)); // Pushes the Module as Enabled at Instance Level - let modactions = self.botactions + let mut a = self.botactions.write().await; + let modactions = a //.entry( BotModule(String::from("experiments"))) - .entry( in_module.clone()) + .entry(in_module.clone()) .or_insert(Vec::new()); // modactions.push(BotAction::L(newlistener)); modactions.push(in_action); - println!(">> Modules Manager : Called Add bot Action"); - //println!(">> Modules Manager : {:?}",&self); - - //(); - //let mgr = self; - - //mgr - - //self + // println!(">> Modules Manager : Called Add bot Action"); + botlog::trace( + ">> Modules Manager : Called Add bot Action", + Some("ModulesManager > init()".to_string()), + None, + ); + // println!("add_botaction - botactions size : {}",modactions.len()); + botlog::trace( + &format!("add_botaction - botactions size : {}", modactions.len()), + Some("ModulesManager > init()".to_string()), + None, + ); } - - - - fn statuscleanup(&self,_:Option) -> () { - // internal cleans up statusdb . For example : + fn statuscleanup(&self, _: Option) -> () { + // internal cleans up statusdb . For example : // - remove redudancies . If we see several Enabled("m"), only keep 1x // - Clarify Conflict. If we see Enabled("m") and Disabled("m") , we remove Enabled("m") and keep Disabled("m") // the IDEAL is that this is ran before every read/update operation to ensure quality @@ -395,7 +441,4 @@ impl ModulesManager // Passing None to chnl may be a heavy operation, as this will review and look at the whole table () } - - - -} \ No newline at end of file +} diff --git a/src/core/identity.rs b/src/core/identity.rs new file mode 100644 index 0000000..0c59879 --- /dev/null +++ b/src/core/identity.rs @@ -0,0 +1,2900 @@ +use std::borrow::Borrow; +use std::collections::HashMap; +use std::error::Error; + +use crate::core::botmodules::bot_actions::actions_util; +use crate::core::botmodules::{BotActionTrait, BotCommand, BotModule, Listener, ModulesManager}; + +use crate::core::botinstance::{self, botlog, BotInstance, ChType}; +use futures::lock::Mutex; +use twitch_irc::message::{Badge, PrivmsgMessage}; + +// use crate::core::botmodules::ChType; + +use crate::core::botinstance::ArcBox; + +use std::cell::RefCell; +use std::rc::Rc; + +use std::sync::Arc; +use tokio::sync::RwLock; + +use casual_logger::{Level, Log}; + +use super::botmodules::bot_actions::actions_util::BotAR; + +fn adminvector() -> Vec { + vec![String::from("ModulatingForce")] + //vec![] +} + +// pub fn init(mgr:&mut ModulesManager) +pub async fn init(mgr: Arc) { + // println!("Went into Identiy Module init"); + botinstance::botlog::trace( + "Went into Identiy Module init", + Some("identity.rs > init()".to_string()), + None, + ); + + // let a = actions_util::asyncbox(cmd_promote) ; + + let tempb = BotCommand { + module: BotModule(String::from("identity")), + command: String::from("promote"), // command call name + alias: vec![], // String of alternative names + exec_body: actions_util::asyncbox(cmd_promote), + help: String::from("promote"), + required_roles: vec![ + UserRole::Mod(ChType::Channel(String::new())), + UserRole::SupMod(ChType::Channel(String::new())), + UserRole::Broadcaster, + UserRole::BotAdmin, + ], + }; + + tempb.add_to_modmgr(Arc::clone(&mgr)).await; + + async fn cmd_promote(bot: BotAR, msg: PrivmsgMessage) -> () { + //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); + // println!("Called cmd promote"); + botinstance::botlog::trace( + "Called cmd promote", + Some("identity.rs > cmd_prommote()".to_string()), + Some(&msg), + ); + + // -- If the BotCommand.command was called (e.g., promote) & required roles were validated OUTSIDE of this call + // , this is the current function body to execute + + /* + - `promote` / `demote` + - [ ] `SupMod` & `Broadcaster` & `BotAdmin` can run + - [ ] `UserRole`s that can run, can + - [ ] run `promote` on a regular `Chatter` to make them a `Mod` + - [ ] run `demote` on a `Mod` to make them a `Chatter` + - [ ] Only `BotAdmin` can : + - [ ] target themselves to `promote` / `demote` , in the case that they want to make themselves either a `Mod` or `SupMod` for the channel temporarily + - [ ] `promote admin ` to assign them `BotAdmin` role + - `[ ] Broadcaster` & `BotAdmin` can `demote` a `SupMod` to make them a `Mod` or `promote` the other way + */ + + /* + Usage : + + promote + + demote + + promote -admin + + */ + + // println!("{}",msg.message_text); + botinstance::botlog::trace( + &format!("Twich Message > {}", msg.message_text), + Some("identity.rs > cmd_promote()".to_string()), + None, + ); + + let sendername = msg.clone().sender.name; + + let mut argv = msg.message_text.split(" "); + + argv.next(); // Skip the command name + + let arg1 = argv.next(); + + let arg2 = argv.next(); + + let mut sender_badge: Option = None; + + for b in &msg.badges { + if b.name == "moderator" { + sender_badge = Some(ChatBadge::Mod); + } else if b.name == "broadcaster" { + sender_badge = Some(ChatBadge::Broadcaster); + } + } + + let targetchnl = msg.channel_login.to_lowercase(); + + /* + + [x] 1. Get trgusr (regardless of -admin flag) + [x] 2. promote trguser + [x] 3. Output resulting change + + */ + + // [x] 1. Get trgusr (regardless of -admin flag) + + let targetusr = if arg1 == Some("-admin") { arg2 } else { arg1 }; + + // [x] 2. promote trguser + + // [x] Get a required lock first + + let botlock = bot.read().await; + let id = botlock.get_identity(); + let idlock = id.read().await; + + let rslt = match targetusr { + Some(targetusr) => { + botinstance::botlog::debug( + &format!("running promote()"), + Some("identity.rs > cmd_promote()".to_string()), + None, + ); + Log::flush(); + + let target_bot_admin_role = if arg1 == Some("-admin") { + Some(UserRole::BotAdmin) + } else { + None + }; + + idlock + .promote( + sendername.clone(), + &sender_badge, + targetusr.to_string(), + Some(ChType::Channel(targetchnl.clone())), + target_bot_admin_role, + ) + .await + } + + None => { + botinstance::botlog::debug( + &format!("No Targer User argument"), + Some("identity.rs > cmd_demote()".to_string()), + None, + ); + Log::flush(); + + ChangeResult::NoChange("No Targer User".to_string()) + } + }; + + // [x] 3. Output resulting change + + match rslt { + ChangeResult::Success(a) => { + // println!("Succesfully promoted : {a} ;"); + let outmsg = &format!("o7 Successfully promoted : {a}"); + botinstance::botlog::debug( + outmsg, + Some("identity.rs > cmd_prommote()".to_string()), + Some(&msg), + ); + // let outmsg = "o7 Successfully promoted : ".to_string(); + botlock + .botmgrs + .chat + .say_in_reply_to(&msg, outmsg.to_string()) + .await; + } + ChangeResult::Failed(a) => { + // println!("Failed to promote : {a} ; "); + let outmsg = &format!("PoroSad failed to promote : {a}"); + botinstance::botlog::debug( + outmsg, + Some("identity.rs > cmd_prommote()".to_string()), + Some(&msg), + ); + // let outmsg = "PoroSad failed to promote : ".to_string(); + botlock + .botmgrs + .chat + .say_in_reply_to(&msg, outmsg.to_string()) + .await; + } + ChangeResult::NoChange(a) => { + // println!("No Changes Made : {a} ; "); + let outmsg = &format!("uuh No Promotion Change : {a}"); + botinstance::botlog::debug( + outmsg, + Some("identity.rs > cmd_prommote()".to_string()), + Some(&msg), + ); + // let outmsg = "uuh No Promotion Change : ".to_string(); + botlock + .botmgrs + .chat + .say_in_reply_to(&msg, outmsg.to_string()) + .await; + } + } + + /* + match arg1 { + Some(a1) if a1 == String::from("-admin") => { + // - [x] BotAdmins can promote admin to give BotAdmin UserRole + + let botlock = bot.read().await; + let idlock = botlock.get_identity(); + let id = idlock.read().await; + // let ta = ta.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))); + // let ta = ta.getspecialuserroles(arg2.unwrap().to_string(), Some(ChType::Channel(msg.channel_login.to_lowercase()))); + let rolesfut = id.getspecialuserroles( + msg.sender.name.to_lowercase(), + Some(ChType::Channel(msg.channel_login.to_lowercase()))); + let usrroles = rolesfut.await; + // let ta = ta.unwrap(); + // let a = ta.read().await; + // let ta = *ta; + // let ta = *ta; + // if let Some(a) = *ta { + + if usrroles.contains(&UserRole::BotAdmin) { + // println!("BotAdmin allowed to promote admin"); + botinstance::botlog::debug("BotAdmin allowed to promote admin", + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + + { + + let idlock = Arc::clone(&bot.read().await.get_identity()); + // let idlock = idlock.write().await; + let idlock = idlock.read().await; + // let mut idlock = *idlock; + // let ta = idlock.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)).await; + let ta = idlock.promote(arg2.unwrap().to_string().to_lowercase(), None, Some(UserRole::BotAdmin)).await; + + match ta { + ChangeResult::Success(a) => { + // println!("Succesfully promoted : {a} ;"); + let outmsg = &format!("o7 Successfully promoted : {a}"); + botinstance::botlog::debug(outmsg, + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + // let outmsg = "o7 Successfully promoted : ".to_string(); + botlock.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + ChangeResult::Failed(a) => { + // println!("Failed to promote : {a} ; "); + let outmsg = &format!("PoroSad failed to promote : {a}"); + botinstance::botlog::debug(outmsg, + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + // let outmsg = "PoroSad failed to promote : ".to_string(); + botlock.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + ChangeResult::NoChange(a) => { + // println!("No Changes Made : {a} ; "); + let outmsg = &format!("uuh No Promotion Change : {a}"); + botinstance::botlog::debug(outmsg, + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + // let outmsg = "uuh No Promotion Change : ".to_string(); + botlock.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + + } + } + } // if usrroles.contains(&UserRole::BotAdmin) + } + + // }, + Some(arg1) => { + // In the case of promoting another chatter + // Check caller's roles + // Check targer chatter's roles + // - Also check if target chatter alread has target roles + // if caller's role is Broadcaster, SupMod, BotAdmin , they can Promote target Chatters to become Mod (i.e., the target user is not a Mod,SupMod,BotAdmin) + // if caller is BotAdmin, they can promote BotAdmins to Mod + // if caller's role is Broadcaster, BotAdmin, they can Promote target Mod to SupMod + botinstance::botlog::debug(&format!("Evaluating arg1: {arg1}"), + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + + let idlock = Arc::clone(&bot.read().await.get_identity()); + let idlock = idlock.read().await; + // let ta = idlock.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)).await; + + let senderroles = idlock.getspecialuserroles( + msg.sender.name.to_lowercase(), + Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; + + let trgusrroles = idlock.getspecialuserroles( + arg1.to_lowercase(), + Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; + + botinstance::botlog::debug(&format!("Ready to evaluate sender and targer user roles"), + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + + botinstance::botlog::trace(&format!("Related Vars : sender roles : {:?} ; targer usr roles : {:?}" , + senderroles,trgusrroles), + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + + if ( senderroles.contains(&UserRole::Broadcaster) || + senderroles.contains(&UserRole::SupMod(ChType::Channel(msg.channel_login.to_lowercase()))) || + senderroles.contains(&UserRole::BotAdmin) ) && + ( !trgusrroles.contains(&UserRole::Broadcaster) && + // !trgusrroles.contains(&UserRole::BotAdmin) && // target users that are BotAdmins can promote themselves to Mod or SupMod + !trgusrroles.contains(&UserRole::SupMod(ChType::Channel(msg.channel_login.to_lowercase()))) && + !trgusrroles.contains(&UserRole::Mod(ChType::Channel(msg.channel_login.to_lowercase()))) + ) + { + // if caller's role is Broadcaster, SupMod, BotAdmin , they can Promote target Chatters to become Mod (i.e., the target user is not a Mod,SupMod,BotAdmin) + botinstance::botlog::trace(&format!("Attempting promote..."), + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + let ta = idlock.promote(arg1.to_string().to_lowercase(), + Some(ChType::Channel(msg.channel_login.to_lowercase())), + Some(UserRole::Mod(ChType::Channel(msg.channel_login.to_lowercase())))).await; + + match ta { + ChangeResult::Success(a) => { + // println!("Succesfully promoted : {a} ;"); + let outmsg = &format!("Successful Promotion : {a}"); + botinstance::botlog::debug(&format!("Successful Promotion : {a}"), + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + // let outmsg = "o7 Successfully promoted : ".to_string(); + bot.read().await.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + ChangeResult::Failed(a) => { + // println!("Failed to promote : {a} ; "); + let outmsg = &format!("PoroSad failed to promote : {a}"); + botinstance::botlog::debug(outmsg, + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + // Log::flush(); + // let outmsg = "PoroSad failed to promote : ".to_string(); + bot.read().await.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + ChangeResult::NoChange(a) => { + // println!("No Changes Made : {a} ; "); + let outmsg = &format!("uuh Not making any changes : {a}"); + botinstance::botlog::debug(outmsg, + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + // let outmsg = "uuh No Promotion Change : ".to_string(); + bot.read().await.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + + } + + } else if trgusrroles.contains(&UserRole::Mod(ChType::Channel(msg.channel_login.to_lowercase()))) && + ( senderroles.contains(&UserRole::Broadcaster) || + senderroles.contains(&UserRole::BotAdmin) ) + { + botinstance::botlog::trace(&format!("Attempting promote..."), + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + + // broadcaster & botadmins can make mods into SupMod + let ta = idlock.promote(arg1.to_string().to_lowercase(), + Some(ChType::Channel(msg.channel_login.to_lowercase())), + Some(UserRole::SupMod(ChType::Channel(msg.channel_login.to_lowercase())))).await; + + match ta { + ChangeResult::Success(a) => { + // println!("Succesfully promoted : {a} ;"); + let outmsg = &format!("Successful Promotion : {a}"); + botinstance::botlog::debug(&format!("Successful Promotion : {a}"), + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + // let outmsg = "o7 Successfully promoted : ".to_string(); + bot.read().await.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + ChangeResult::Failed(a) => { + // println!("Failed to promote : {a} ; "); + let outmsg = &format!("PoroSad failed to promote : {a}"); + botinstance::botlog::debug(outmsg, + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + // Log::flush(); + // let outmsg = "PoroSad failed to promote : ".to_string(); + bot.read().await.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + ChangeResult::NoChange(a) => { + // println!("No Changes Made : {a} ; "); + let outmsg = &format!("uuh No Change in Promotion : {a}"); + botinstance::botlog::debug(outmsg, + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + // let outmsg = "uuh No Promotion Change : ".to_string(); + bot.read().await.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + + } + + } else if trgusrroles.contains(&UserRole::Broadcaster) // This should always be NoChange + { + botinstance::botlog::trace(&format!("Attempting promote..."), + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + + // broadcaster & botadmins can make mods into superadmins + let ta = idlock.promote(arg1.to_string().to_lowercase(), + Some(ChType::Channel(msg.channel_login.to_lowercase())), + Some(UserRole::Mod(ChType::Channel(msg.channel_login.to_lowercase())))).await; + + match ta { + ChangeResult::Success(a) => { + // println!("Succesfully promoted : {a} ;"); + let outmsg = &format!("Successful Promotion : {a}"); + botinstance::botlog::debug(&format!("Successful Promotion : {a}"), + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + // let outmsg = "o7 Successfully promoted : ".to_string(); + bot.read().await.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + ChangeResult::Failed(a) => { + // println!("Failed to promote : {a} ; "); + let outmsg = &format!("PoroSad failed to promote : {a}"); + botinstance::botlog::debug(outmsg, + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + // Log::flush(); + // let outmsg = "PoroSad failed to promote : ".to_string(); + bot.read().await.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + ChangeResult::NoChange(a) => { + // println!("No Changes Made : {a} ; "); + let outmsg = &format!("uuh No Change in Promotion : {a}"); + botinstance::botlog::debug(outmsg, + Some("identity.rs > cmd_prommote()".to_string()), Some(&msg)); + Log::flush(); + // let outmsg = "uuh No Promotion Change : ".to_string(); + bot.read().await.botmgrs.chat.say_in_reply_to(&msg, outmsg.to_string()).await; + }, + + } + } + + else { + let s = botlog::fatal("Reached unreachable else", + Some("identity > cmd_promote()".to_string()), Some(&msg)); + panic!("{}",s); + }; + + Log::flush(); + + } + _ => (), + } + + + + let arg2 = argv.next(); + + let targetchnl = arg2; + + */ + + botinstance::botlog::trace( + &format!("End of cmd_promote()"), + Some("identity.rs > cmd_prommote()".to_string()), + None, + ); + } + + // BotCommand { + // module : BotModule(String::from("identity")), + // command : String::from("demote"), // command call name + // alias : vec![], // String of alternative names + // exec_body : actions_util::asyncbox(cmd_demote) , + // help : String::from("demote"), + // required_roles : vec![ + // UserRole::Mod(ChType::Channel(String::new())), + // UserRole::SupMod(ChType::Channel(String::new())), + // UserRole::Broadcaster, + // UserRole::BotAdmin, + // ], + // }.add_to_modmgr(Arc::clone(&mgr)); + + let tempb = BotCommand { + module: BotModule(String::from("identity")), + command: String::from("demote"), // command call name + alias: vec![], // String of alternative names + exec_body: actions_util::asyncbox(cmd_demote), + help: String::from("demote"), + required_roles: vec![ + UserRole::Mod(ChType::Channel(String::new())), + UserRole::SupMod(ChType::Channel(String::new())), + UserRole::Broadcaster, + UserRole::BotAdmin, + ], + }; + + tempb.add_to_modmgr(Arc::clone(&mgr)).await; + + // async fn cmd_demote(mut _chat:Arc>,_msg:PrivmsgMessage) { + async fn cmd_demote(mut bot: BotAR, msg: PrivmsgMessage) { + // println!("Called cmd demote"); + botinstance::botlog::debug( + "Called cmd demote", + Some("identity.rs > cmd_demote()".to_string()), + Some(&msg), + ); + Log::flush(); + + // -- If the BotCommand.command was called (e.g., demote) & required roles were validated OUTSIDE of this call + // , this is the current function body to execute + + /* + - `promote` / `demote` + - [ ] `SupMod` & `Broadcaster` & `BotAdmin` can run + - [ ] `UserRole`s that can run, can + - [ ] run `promote` on a regular `Chatter` to make them a `Mod` + - [ ] run `demote` on a `Mod` to make them a `Chatter` + - [ ] Only `BotAdmin` can : + - [ ] target themselves to `promote` / `demote` , in the case that they want to make themselves either a `Mod` or `SupMod` for the channel temporarily + - [ ] `promote admin ` to assign them `BotAdmin` role + - `[ ] Broadcaster` & `BotAdmin` can `demote` a `SupMod` to make them a `Mod` or `promote` the other way + */ + + /* + Usage : + + promote + + demote + + promote -admin + + */ + + // [ ] #TODO : Need to define the body that calls demote() + + // [x] Unwraps arguments from message + + // let mut argv = msg.message_text.split(" "); + + // argv.next(); // Skip the command name + + // let arg1 = argv.next(); + + // let arg2 = argv.next(); + + let (arg1, arg2) = { + let mut argv = msg.message_text.split(" "); + + argv.next(); // Skip the command name + + let arg1 = argv.next(); + + let arg2 = argv.next(); + + (arg1, arg2) + }; + + /* + let mut sender_badge:Option = None; + + for b in &msg.badges { + if b.name == "moderator" { + sender_badge = Some(ChatBadge::Mod); + } else if b.name == "broadcaster" { + sender_badge = Some(ChatBadge::Broadcaster); + } + } + */ + + // --- + + /* + => 2024.02.15 - The business logic seems embeded straight into demote() with the following in mind : + - demote() atm doesn't take sender ChatBadge <-- the assumption is canuserrun() was done + for this user, and automatically assigned any roles that should get auto assigned + - demote() returns a ChangeResult + + - [ ] So I think all I need to do here is parse out and pass input args to demote(), and output quirky messages based on ChangeResult + + - [x] 1. Parse out the following + - Sender (e.g., Name & Badge) + - Target User (arg1) + - Target Channel (current channel) + - Msg or Msg.Message_Text (for later) + + - [x] 2. Run Demote() + - within demote(), getspecialuserroles() is called on both the sender and the target + - getspecialuserroles() only sends current db , while canuserrun() may change db depending on the most current state of the sender + - getspecialuserroles also borrows the sender's badge to evaluate + + - [ ] 3. Take ChangeResult and output response + + + */ + + /* + + + - [x] 1. Parse out the following + - Sender (e.g., Name & Badge) + - Target User (arg1) + - Target Channel (current channel) + - (no need) Msg or Msg.Message_Text (for later) + + */ + + let sendername = msg.clone().sender.name; + + let mut sender_badge_mut: Option = None; + + for b in &msg.badges { + if b.name == "moderator" { + sender_badge_mut = Some(ChatBadge::Mod); + } else if b.name == "broadcaster" { + sender_badge_mut = Some(ChatBadge::Broadcaster); + } + } + + let sender_badge = sender_badge_mut; + + let targetusr = arg1; + + let targetchnl = msg.channel_login.to_lowercase(); + + /* + + - [x] 2. Run Demote() + - within demote(), getspecialuserroles() is called on both the sender and the target + - getspecialuserroles() only sends current db , while canuserrun() may change db depending on the most current state of the sender + - getspecialuserroles also borrows the sender's badge to evaluate + + + */ + + // [x] Get a required lock first + + let botlock = bot.read().await; + let id = botlock.get_identity(); + let idlock = id.read().await; + + let rslt = match targetusr { + Some(targetusr) => { + botinstance::botlog::debug( + &format!("running demote()"), + Some("identity.rs > cmd_demote()".to_string()), + None, + ); + Log::flush(); + + idlock + .demote( + sendername.clone(), + &sender_badge, + targetusr.to_string(), + Some(ChType::Channel(targetchnl.clone())), + ) + .await + } + + None => { + botinstance::botlog::debug( + &format!("No Targer User argument"), + Some("identity.rs > cmd_demote()".to_string()), + None, + ); + Log::flush(); + + ChangeResult::NoChange("No Targer User".to_string()) + } + }; + + /* + + - [x] 3. Take ChangeResult and output response + + */ + + // let senderUserRole = { + + // // note : getspecialuserroles will cover : + // // - Internal roles stored at db for Mod & SupMod & BotAdmin + // // - Broadcaster (based on target hchatter & channel) + // // It MAY NOT COVER sutations where Sender has a Mod Badge, but not in DB yet as Mod + // // - So ideally this covers that (at least returns that they're a mod and go ahead and run for now) + // // - [ ] #TODO : This should also go ahead and add that mod to DB if possible as channel mod + + // // let evalroles = vec![]; + + // let evalroles = match sender_badge { + + // Some(ChatBadge::Mod) => { + + // let mut rslroles = idlock.getspecialuserroles( + // sendername.clone(), + // Some(ChType::Channel(targetchnl.clone()))).await; + + // rslroles.push(UserRole::Mod(ChType::Channel(targetchnl))); + + // rslroles + // }, + // _ => { + // idlock.getspecialuserroles( + // sendername, + // Some(ChType::Channel(targetchnl.clone()))).await + // } + // }; + + // // => 02.16 - I think better would just migrate over the logic within demote + // // - If there's business reqs to evaluate , better to keep the ChangeResult + // // consistent and also pass ChatBadge + + // }; // senderUserRole + + match rslt { + ChangeResult::Success(a) => { + // println!("Succesfully promoted : {a} ;"); + let outmsg = &format!("o7 Successfully demoted : {a}"); + botinstance::botlog::debug( + outmsg, + Some("identity.rs > cmd_demote()".to_string()), + Some(&msg), + ); + // let outmsg = "o7 Successfully promoted : ".to_string(); + botlock + .botmgrs + .chat + .say_in_reply_to(&msg, outmsg.to_string()) + .await; + } + ChangeResult::Failed(a) => { + // println!("Failed to promote : {a} ; "); + let outmsg = &format!("PoroSad failed to demote : {a}"); + botinstance::botlog::debug( + outmsg, + Some("identity.rs > cmd_demote()".to_string()), + Some(&msg), + ); + // let outmsg = "PoroSad failed to promote : ".to_string(); + botlock + .botmgrs + .chat + .say_in_reply_to(&msg, outmsg.to_string()) + .await; + } + ChangeResult::NoChange(a) => { + // println!("No Changes Made : {a} ; "); + let outmsg = &format!("uuh No Demotion Change : {a}"); + botinstance::botlog::debug( + outmsg, + Some("identity.rs > cmd_demote()".to_string()), + Some(&msg), + ); + // let outmsg = "uuh No Promotion Change : ".to_string(); + botlock + .botmgrs + .chat + .say_in_reply_to(&msg, outmsg.to_string()) + .await; + } + } + + // println!("tester"); + // println!("tester2"); + } + + let tempcomm = BotCommand { + module: BotModule(String::from("identity")), + command: String::from("getroles"), // command call name + alias: vec![], // String of alternative names + exec_body: actions_util::asyncbox(getroles), + help: String::from("getroles"), + required_roles: vec![ + UserRole::Mod(ChType::Channel(String::new())), + UserRole::SupMod(ChType::Channel(String::new())), + UserRole::Broadcaster, + UserRole::BotAdmin, + ], + }; + + tempcomm.add_to_modmgr(Arc::clone(&mgr)).await; + + // async fn getroles(bot:Arc>,msg:PrivmsgMessage) { + async fn getroles(bot: BotAR, msg: PrivmsgMessage) { + // println!("Called cmd getroles"); + botinstance::botlog::debug( + "Called cmd getroles", + Some("identity.rs > cmd_getroles()".to_string()), + Some(&msg), + ); + + /* + Usage + + getroles + - If channel is provided, provide roles for that channel specifically + + */ + + // IN other code areas , I see this + // ServerMessage::Privmsg(msg) => { + // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); + + // println!("{}",msg.message_text); + let mut argv = msg.message_text.split(" "); + + // for v in argv { + // println!("args : {v}"); + // } + + argv.next(); // Skip the command name + + let arg1 = argv.next(); + + // if arg == None { + // return ; // Do nothing if no arguments + // } + + let targetuser = match arg1 { + None => return, // exit if no arguments + Some(arg) => arg, + }; + + // match String::from(arg1) { + // a if a == String::from("admin") => (), + // _ => (), + // } + + // match argv[1] { + // String::from("admin") => (), + + // } + + let arg2 = argv.next(); + + let targetchnl = arg2; + + // // let a = bot.read().ok().unwrap().get_identity(); + // let a = bot.lock().await; + // // let a = a.lock().await; + // // let a = a.get_identity().await; + // let a = a.botmgrs; + // // let a = *(*a).lock().await; + // let a = *a.lock().await; + // let a = a.identity; + // let a = *a.lock().await; + + // let a = bot.clone(); + // let a = a.into_inner(); + // let a = a.botmgrs; + // let a = a.into_inner(); + // let a = a.identity; + // let a = a.into_inner(); + // let a = bot.clone(); + // let a = a.lock().await; + // let a = a.get_identity(); + // let a = a.lock().await; + // let a = bot.get_identity(); + let botlock = bot.read().await; + // println!("botlock read"); + botinstance::botlog::trace( + "botlock read", + Some("identity.rs > init > getroles()".to_string()), + Some(&msg), + ); + let idlock = botlock.get_identity(); + // println!("got identity"); + botinstance::botlog::trace( + "got identity", + Some("identity.rs > init > getroles()".to_string()), + Some(&msg), + ); + let idlock = idlock.read().await; // <-- 02.12 - Latest where it gest stuck - before or at this point + // println!("id lock"); + botinstance::botlog::trace( + "id lock", + Some("identity.rs > init > getroles()".to_string()), + Some(&msg), + ); + let sproles = match targetchnl { + None => { + // let bot = Rc::clone(&bot); + //let bot = Arc::clone(&bot); + // let a = bot.botmgrs.identity.getspecialuserroles(String::from(targetuser),None); + // let a = Arc::try_unwrap(bot).ok().unwrap().into_inner().ok().unwrap(); + // let a = Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner(); + // let a = a.botmgrs.identity.getspecialuserroles(String::from(targetuser),None); + // let a = a.ok().getspecialuserroles(String::from(targetuser),None); + // let a = bot.read().ok().unwrap().rIdentity().getspecialuserroles(String::from(targetuser),None); + // println!("Retrieved User Roles >> {:?}",a); + // let a = idlock.read().await; + // idlock.getspecialuserroles(String::from(targetuser),None).await + + // [ ] If targetchnl is not provided, default to pulling the current channel + idlock + .getspecialuserroles( + String::from(targetuser), + Some(ChType::Channel(msg.channel_login.to_lowercase())), + ) + .await + } + Some(targetchnl) => { + // let bot = Rc::clone(&bot); + // let bot = Arc::clone(&bot); + // let a = bot.botmgrs.identity.getspecialuserroles(String::from(targetuser), Some(ChType::Channel(String::from(targetchnl)))); + // Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner() + // let a = Arc::try_unwrap(bot).ok().unwrap().into_inner().ok().unwrap(); + // let a = Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner(); + // let a = a.botmgrs.identity.getspecialuserroles(String::from(targetuser), Some(ChType::Channel(String::from(targetchnl)))); + // let a = bot.read().ok().unwrap().rIdentity().getspecialuserroles(String::from(targetuser),None); + // println!("Retrieved User Roles >> {:?}",a); + // bot.read().ok().unwrap().rIdentity().getspecialuserroles(String::from(targetuser),None) + // let a = a.read().await; + + // [ ] If caller is not a BotAdmin, they can only pull those related to the current channel for the target user + // [ ] If caller is a BotAdmin, allow & return for target channel + // let mut sender_badge:Option = None; + + // for b in &msg.badges { + // if b.name == "moderator" { + // sender_badge = Some(ChatBadge::Mod); + // } else if b.name == "broadcaster" { + // sender_badge = Some(ChatBadge::Broadcaster); + // } + // } + + // match sender_badge { + // Some(ChatBadge::Mod) => { + + // } , + // Some(ChatBadge::Broadcaster) => { + + // } + // _ => { + + // } + // } + + // [x]gets special roles for caller + let callersproles = idlock + .getspecialuserroles( + msg.sender.name.to_lowercase(), + Some(ChType::Channel(targetchnl.to_lowercase().to_string())), + ) + .await; + // idlock.getspecialuserroles(String::from(targetuser),Some(ChType::Channel(targetchnl.to_lowercase().to_string()))).await + // let a = callersproles.contains(&UserRole::Mod(ChType::Channel(targetchnl.to_lowercase().to_string()))); + if callersproles.contains(&UserRole::Mod(ChType::Channel( + targetchnl.to_lowercase().to_string(), + ))) || callersproles.contains(&UserRole::SupMod(ChType::Channel( + targetchnl.to_lowercase().to_string(), + ))) || callersproles.contains(&&UserRole::Broadcaster) + { + idlock + .getspecialuserroles( + String::from(targetuser), + Some(ChType::Channel(targetchnl.to_lowercase())), + ) + .await + // callersproles + } else { + // Otherwise, don't get the target channel, return the current channel instead + idlock + .getspecialuserroles( + String::from(targetuser), + Some(ChType::Channel(msg.channel_login.to_lowercase())), + ) + .await + } + } + }; + + // let sproles = idlock.getspecialuserroles(String::from(targetuser),).await; + + // println!("Retrieved User Roles >> {:?}",sproles); + botinstance::botlog::debug( + &format!("User roles of Target Chatter >> {:?}", sproles), + Some("identity.rs > init > getroles()".to_string()), + Some(&msg), + ); + + // # I believe at this stage I still have botlock active + + botinstance::botlog::debug( + &format!("Evaluating special roles"), + Some("identity.rs > init > getroles()".to_string()), + Some(&msg), + ); + + // let mut outmsg = String::new(); + + let sproles = sproles; + // let arg2 = arg2.unwrap(); + + let outmsg = if ((targetuser.to_lowercase() == msg.channel_login.to_lowercase()) + && arg2.is_none()) + || (arg2.is_some() && arg2.unwrap() == targetuser.to_lowercase()) + { + // First evaluates if they're broadcaster + let mut outmsg = format!("FeelsWowMan they're the broadcaster. "); + if sproles.contains(&UserRole::Mod(ChType::Channel( + msg.channel_login.to_lowercase(), + ))) || sproles.contains(&UserRole::SupMod(ChType::Channel( + msg.channel_login.to_lowercase(), + ))) || sproles.contains(&UserRole::BotAdmin) + { + outmsg = outmsg + &format!("Target chatter's user roles are : {:?}", sproles); + } + outmsg + } else if sproles.contains(&UserRole::Mod(ChType::Channel( + msg.channel_login.to_lowercase(), + ))) || sproles.contains(&UserRole::SupMod(ChType::Channel( + msg.channel_login.to_lowercase(), + ))) || sproles.contains(&UserRole::BotAdmin) + { + format!("Target chatter's user roles are : {:?}", sproles) + } else { + format!("Target chatter has no special roles LULE ") + }; + + // if sproles.contains(&UserRole::Mod(msg.channel_login.to_lowercase())) { + + // } else if sproles.contains(&UserRole::Mod(msg.channel_login.to_lowercase())) { + + // } + + // let outmsg = match sproles + // { + + // // let mut outmsg = String::new(); + // Some(sproles) => { + + // let sproles = sproles.read().await; + + // format!("Target chatter's user roles are : {:?}",sproles) + + // } + // None => { + // // # NOTE : Broadcaster could be included in this + + // // # below is checking if the provided text includes the username + // // let msg = msg.message_text.to_lowercase().contains(&msg.channel_login.to_lowercase()); + // botinstance::botlog::debug(&format!("Evaluating special roles > channel login : {} ; message text : {} ; ",&msg.channel_login,&msg.message_text), + // Some("identity.rs > init > getroles()".to_string()), Some(&msg)); + // botinstance::botlog::debug(&format!("Evaluating special roles > bool evaluation : {} ", + // msg.message_text.to_lowercase().contains(&msg.channel_login.to_lowercase())), + // Some("identity.rs > init > getroles()".to_string()), Some(&msg)); + + // if msg.message_text.to_lowercase().contains(&msg.channel_login.to_lowercase()) { + // format!("FeelsWowMan they're the broadcaster ") + // } else { + // format!("Target chatter has no special roles LULE ") + // } + + // } + + // }; + // let a = bot.identity.getuserroles(String::from("ModulatingForce"), Some(ChType::Channel(String::from("ModulatingForcebot")))); + // println!("{:?}",a); + + botinstance::botlog::debug( + &format!("Chat Say Reply message : {:?}", outmsg), + Some("identity.rs > init > getroles()".to_string()), + Some(&msg), + ); + botlock.botmgrs.chat.say_in_reply_to(&msg, outmsg).await; + + // [ ] NOTE : After the above, I should receive only the roles in the context of the current channel I received this ideally and maybe BotAdmin ; not outside + } + + // println!("End of Init MOdule add"); + botinstance::botlog::trace( + "End of Init MOdule add", + Some("identity.rs > init ".to_string()), + None, + ); + + Log::flush(); +} + +// #[derive(Debug, PartialEq, Eq, Hash, Clone)] +// pub enum ChType { +// Channel(String), +// } + +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum UserRole { + Chatter, + Mod(ChType), // String specifies Channel + SupMod(ChType), // String specifies Channel + Broadcaster, + BotAdmin, +} + +pub enum Permissible { + Allow, + Block, +} + +#[derive(Clone)] +pub struct IdentityManager { + // special_roles_users : HashMap>, // # <-- (!) This must be String instead of ChType because we're checking a User not a Channel + // special_roles_users : Arc>>>, // # <-- (!) This must be String instead of ChType because we're checking a User not a Channel + // special_roles_users : Arc>>>, + special_roles_users: Arc>>>>>, + // parent_mgr : Box, + //parent_mgr : Option>, +} +/* + HashMap< + String, <-- Chatter / Username + Vec -- <-- Vectors are basically arrays + > + + -- [ ] + let a = vec![] + + modulatingforce : vec![UserRole::BotAdmin, + UserRole::Mod(ChType::Channel("modulatingforcebot"))] + modulatingforce : vec![UserRole::BotAdmin, + UserRole::Mod(ChType::Channel("modulatingforcebot"))] + +*/ + +#[derive(Debug)] +pub enum ChatBadge { + Broadcaster, + Mod, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum ChangeResult { + Success(String), + Failed(String), + NoChange(String), +} + +impl IdentityManager { + pub fn init() -> IdentityManager { + let mut a = HashMap::new(); + for admn in adminvector() { + a.insert( + admn.to_lowercase(), + Arc::new(RwLock::new(vec![UserRole::BotAdmin])), + ); + } + + IdentityManager { + special_roles_users: Arc::new(RwLock::new(a)), + //parent_mgr : None, + } + } + + async fn add_role(&self, trgchatter: String, trg_role: UserRole) { + let mut srulock = self.special_roles_users.write().await; + let mut usrrolelock = srulock + .get_mut(&trgchatter) + .expect("Error retrieving roles") + .write() + .await; + usrrolelock.push(trg_role); + } + + async fn remove_role(&self, trgchatter: String, trg_role: UserRole) { + let mut srulock = self.special_roles_users.write().await; + let mut usrrolelock = srulock + .get_mut(&trgchatter) + .expect("Error retrieving roles") + .write() + .await; + if let Some(indx) = usrrolelock.iter().position(|value| *value == trg_role) { + usrrolelock.swap_remove(indx); + //return ChangeResult::Success("Demoted successfully".to_string()) + } + } + + async fn affirm_chatter_in_db(&self, trgchatter: String) { + let mut srulock = self.special_roles_users.write().await; + srulock + .entry(trgchatter.clone()) + .or_insert(Arc::new(RwLock::new(vec![]))); + botinstance::botlog::trace( + &format!( + "Ensuring User in Roles {:?}", + srulock.entry(trgchatter.clone()) + ), + Some("IdentityManager > affirm_chatter_in_db()".to_string()), + None, + ); + Log::flush(); + } + + // [ ] Maybe I should create a can_user_run version that simply takes PrvMsg, but then calls can_user_run directly + + // pub fn can_user_run_PRVMSG(self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Result> + // pub fn can_user_run_PRVMSG(&self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible + // pub async fn can_user_run_PRVMSG(self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible + pub async fn can_user_run_PRVMSG( + &mut self, + msg: &PrivmsgMessage, + cmdreqroles: Vec, + ) -> (Permissible, ChangeResult) { + // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); + + // [ ] Check what Badges in PrivmsgMessage + // println!{"Checking within PRVMSG"}; + botinstance::botlog::debug( + "Checking within PRVMSG", + Some("identity.rs > can_user_run_PRVMSG()".to_string()), + Some(&msg), + ); + + let mut sender_badge: Option = None; + + for b in &msg.badges { + if b.name == "moderator" { + sender_badge = Some(ChatBadge::Mod); + } else if b.name == "broadcaster" { + sender_badge = Some(ChatBadge::Broadcaster); + } + } + + // if &msg.badges.contains(Badge{}) { + + // } + + // if let Some(sender_badge) = sender_badge { + // match sender_badge { + // Some(sender_badge) => { + // return &self.can_user_run(msg.sender.name.to_owned(), + // ChType::Channel(msg.channel_login.to_owned()), + // sender_badge, + // cmdreqroles + // return self.can_user_run(msg.sender.name.to_owned(), + // let a = Arc::new(Mutex::new(self)); + // let mut a = a.lock().await; + // let a = **a; + // let a = a.can_user_run(msg.sender.name.to_owned(), + // ChType::Channel(msg.channel_login.to_owned()), + // sender_badge, + // cmdreqroles + // ) ; + // let a = *self; + // let a = Arc::new(Mutex::new(a)); + // let a = a.lock().await.can_user_run(msg.sender.name.to_owned(), + // ChType::Channel(msg.channel_login.to_owned()), + // sender_badge, + // cmdreqroles + // ) ; + // return a; + // return self.can_user_run(msg.sender.name.to_owned(), + // ChType::Channel(msg.channel_login.to_owned()), + // sender_badge, + // cmdreqroles + // ).await + + // * NOTE : We're preferring to pass the ChangeResult up , where we have access to Chat via BotInstance + // that have more strained chatting rules + // let evalpermissible = self.can_user_run(msg.sender.name.to_owned(), + // ChType::Channel(msg.channel_login.to_owned()), + // sender_badge, + // cmdreqroles + // ).await ; + // evalpermissible + // // } + // None => { + + // } + // here , sender_badge is likely None + // This could be a regular chatter, BotAdmin,SupserMod + + // [ ] Call can_user_run() + // (self,Permissible::Block) + // (Permissible::Block,ChangeResult::NoChange("".to_string())) + + self.can_user_run( + msg.sender.name.to_owned(), + ChType::Channel(msg.channel_login.to_owned()), + sender_badge, + cmdreqroles, + ) + .await + } + + pub async fn can_user_run( + &mut self, + usr: String, + channelname: ChType, + chat_badge: Option, + cmdreqroles: Vec, // ) -> Result> { + ) -> (Permissible, ChangeResult) { + // println!{"Checking within can_user_run()"}; + botinstance::botlog::debug( + &format!( + "Checking within can_user_run() : + usr : {} ; channel : {:?} ; badge : {:?} ; cmdreqroles : {:?}", + usr, channelname, chat_badge, cmdreqroles + ), + Some("identity.rs > can_user_run()".to_string()), + None, + ); + /* + canUserRun - + + Input : + usr:String, + channelname:ChType, + chat_badge:ChatBadge, + cmdreqroles:Vec + + Output : Result> + Some Possible outcomes : Ok(Permissible::Allow) , Ok(Permissible::Block) + + + Description + For a Given Chatter (with any special ChatBadge) who ran the Command at a Given Channel , check if that user can + run the command based on the given cmdreqroles required by the command + + Inputs and business logic determine if the user can run the command based on the command's required roles + */ + + // Requirements + /* + [x] If cmdreqroles is empty vector , automatically assume Ok(Permissible::Allow) + [x] If chatBadge::Broadcaster ... + [x] and cmdreqroles includes UserRole::Broadcaster , Ok(Permissible::Allow) + [x] and cmdreqroles includes UserRole::Mod("") OR UserRole::SupMod("") , Ok(Permissible::Allow) + [x] If chatBadge::Mod ... + [x] Check if they have either UserRole::Mod(channelname::ChType) or UserRole::SupMod(channelname::ChType) + [x] If not, assign them UserRole::Mod(channelname::ChType) + [x] If cmdreqroles includes UserRole::Mod("") , checks if chatter has UserRole::Mod(channelname::ChType) or UserRole::SupMod(channelname::ChType) to determine if Ok(Permissible::Allow) + [x] If cmdreqroles includes UserRole::SupMod("") , checks if chatter has UserRole::SupMod(channelname::ChType) to determine if Ok(Permissible::Allow) + [x] If cmdreqroles includes UserRole::BotAdmin and chatter has UserRole::BotAdmin , Ok(Permissible::Allow) + [x] Otherwise, Ok(Permissible::Block) + */ + + // [x] If cmdreqroles is empty vector , automatically assume Ok(Permissible::Allow) + + // let idar = Arc::new(RwLock::new(self)); + + let usr = usr.to_lowercase(); + + if cmdreqroles.len() == 0 { + // return Ok(Permissible::Allow) + return ( + Permissible::Allow, + ChangeResult::NoChange("Command has no required cmdreqroles".to_string()), + ); + } + + let mut modrolechange = ChangeResult::NoChange("".to_string()); + + match chat_badge { + // [x] If chatBadge::Broadcaster ... + // [x] and cmdreqroles includes UserRole::Broadcaster , Ok(Permissible::Allow) + // [x] and cmdreqroles includes UserRole::Mod("") OR UserRole::SupMod("") , Ok(Permissible::Allow) + Some(ChatBadge::Broadcaster) => { + if cmdreqroles.contains(&UserRole::Broadcaster) + || cmdreqroles.contains(&UserRole::Mod(ChType::Channel(String::new()))) + || cmdreqroles.contains(&UserRole::SupMod(ChType::Channel(String::new()))) + { + // return Ok(Permissible::Allow) + return ( + Permissible::Allow, + ChangeResult::NoChange("Broadcaster Role".to_string()), + ); + } + } + + // [x] If chatBadge::Mod ... + // [x] Check if they have either UserRole::Mod(channelname::ChType) or UserRole::SupMod(channelname::ChType) + // [x] If not, assign them UserRole::Mod(channelname::ChType) + Some(ChatBadge::Mod) => { + // println!("Mod Chatbadge detected"); + botinstance::botlog::info( + "Mod Chatbadge detected", + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + // println!("debug special roles : {:?}",self.special_roles_users); + // println!("debug usr : {}",&usr.to_lowercase()); + + // let Some((k,v)) = self.special_roles_users.get_key_value(usr); + // match self.special_roles_users.get_mut(&usr.to_lowercase()) { + // match self.special_roles_users.get(&usr.to_lowercase()) { + // println!("Creating clone"); + botinstance::botlog::trace( + "Creating arc clone", + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + let roleslock = Arc::clone(&(*self).special_roles_users); + + // println!("Read lock on : Special_Roles_User"); // <-- after this is slightly different between working and problem + botinstance::botlog::trace( + "Read lock on : Special_Roles_User", + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + // { + + // // If target user doesn't exist in special_roles_users , add with blank vector roles + // let mut srulock = self.special_roles_users.write().await; + // srulock.entry(usr.clone()).or_insert(Arc::new(RwLock::new(vec![]))); + // botinstance::botlog::trace(&format!("Ensuring Chatter in Roles {:?}",srulock.entry(usr.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + self.affirm_chatter_in_db(usr.clone()).await; + + let mut roleslock = roleslock.write().await; + match (*roleslock).get(&usr.to_lowercase()) { + Some(usrroles) + if usrroles + .read() + .await + .contains(&UserRole::Mod(channelname.clone())) + || usrroles + .read() + .await + .contains(&UserRole::SupMod(channelname.clone())) => + { + // <-- working got to this point + // println!("contains mod : {}", usrroles.read().await.contains(&UserRole::Mod(channelname.clone()))); + // println!("contains supmod : {}", usrroles.read().await.contains(&UserRole::SupMod(channelname.clone()))); + + // Do nothing when theh have a mod badge and have either a supmod or mod badge for the channel + // println!("Already a mod in roles"); + botinstance::botlog::trace( + "Already a mod in roles", + Some("identity.rs > can_user_run()".to_string()), + None, + ); + } + _ => { + // In the event they have a mod badge , are running a bot command, but don't have a channel mod role yet... + // println!("lock created > adding with a mod role o7"); + botinstance::botlog::trace( + "lock created > adding with a mod role o7", + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + // botinstance::botlog::notice("Assigning ModRole to Chatter", + // Some("identity.rs > can_user_run()".to_string()), None); + + let mut roleslock = roleslock; + let mut a = roleslock.get_mut(&usr.to_lowercase()).unwrap(); + let mut alock = a.write().await; + + alock.push(UserRole::Mod(channelname.clone())); + + modrolechange = ChangeResult::Success("Auto Promoted Mod".to_string()); + + // alock.get_mut(&usr.to_lowercase()) + // .get_or_insert_with(|| UserRole::Mod(channelname.clone())) + // // .expect("ERROR") + // .unwrap() + // .write().await + // // .get_mut() + // .push(UserRole::Mod(channelname.clone())); + } // <-- I'm assuming problem got to here + } + } + _ => (), // Don't handle other roles here + } + + // [x] If cmdreqroles includes UserRole::Mod("") , checks if chatter has UserRole::Mod(channelname::ChType) or UserRole::SupMod(channelname::ChType) to determine if Ok(Permissible::Allow) + + // println!("cmd required roles : {:?}",cmdreqroles); + botinstance::botlog::trace( + &format!("cmd required roles : {:?}", cmdreqroles), + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + if cmdreqroles.contains(&UserRole::Mod(ChType::Channel(String::new()))) { + // match self.special_roles_users.get(&channelname) { + // Some(usrroles) => {}, + // None => (), + + // } + + // println!("Command requires Mod Role"); + botinstance::botlog::trace( + "Command requires Mod Role", + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + if let Some(a) = (&*self) + .special_roles_users + .read() + .await + .get(&usr.to_lowercase()) + { + // println!("Special roles found for user"); + botinstance::botlog::trace( + "Special roles found for user", + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + if a.read().await.contains(&UserRole::Mod(channelname.clone())) + || a.read() + .await + .contains(&UserRole::SupMod(channelname.clone())) + { + // return Ok(Permissible::Allow); + // println!("Special roles found for user : A mod idenfified "); + botinstance::botlog::trace( + "> Special Role Identified : Mod ", + Some("identity.rs > can_user_run()".to_string()), + None, + ); + return (Permissible::Allow, modrolechange); + } + } + } + + // [x] If cmdreqroles includes UserRole::SupMod("") , checks if chatter has UserRole::SupMod(channelname::ChType) to determine if Ok(Permissible::Allow) + + if cmdreqroles.contains(&UserRole::SupMod(ChType::Channel(String::new()))) { + if let Some(a) = (&*self) + .special_roles_users + .read() + .await + .get(&usr.to_lowercase()) + { + if a.read() + .await + .contains(&UserRole::SupMod(channelname.clone())) + { + // return Ok(Permissible::Allow); + return (Permissible::Allow, modrolechange); + } + } + } + + // [x] If cmdreqroles includes UserRole::BotAdmin and chatter has UserRole::BotAdmin , Ok(Permissible::Allow) + + // println!("Eval cmdreqroles with botadmin : {}",cmdreqroles.contains(&UserRole::BotAdmin)); + botinstance::botlog::trace( + &format!( + "Eval cmdreqroles with botadmin : {}", + cmdreqroles.contains(&UserRole::BotAdmin) + ), + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + if cmdreqroles.contains(&UserRole::BotAdmin) { + // println!("special roles get : {:?}",(&*self).special_roles_users.read().await.get(&usr.to_lowercase())); + botinstance::botlog::trace( + &format!( + "special roles get : {:?}", + (&*self) + .special_roles_users + .read() + .await + .get(&usr.to_lowercase()) + ), + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + if let Some(a) = (&*self) + .special_roles_users + .read() + .await + .get(&usr.to_lowercase()) + { + println!( + "special roles contains BotAdmin: {}", + a.read().await.contains(&UserRole::BotAdmin) + ); + botinstance::botlog::trace( + &format!( + "special roles contains BotAdmin: {}", + a.read().await.contains(&UserRole::BotAdmin) + ), + Some("identity.rs > can_user_run()".to_string()), + None, + ); + + if a.read().await.contains(&UserRole::BotAdmin) { + // return Ok(Permissible::Allow); + return (Permissible::Allow, modrolechange); + } + } + } + + ( + Permissible::Block, + ChangeResult::NoChange("Not any permissiable condition".to_string()), + ) + } + + // pub async fn promote(&mut self,trgchatter:String,channel:Option,trg_role:Option) -> ChangeResult { + pub async fn promote( + &self, + authorizer: String, + authorizer_badge: &Option, + trgchatter: String, + channel: Option, + trg_role: Option, + ) -> ChangeResult { + botinstance::botlog::trace( + &format!( + "IN VARS for promote() : auth : {} ; authbadge : {:?} ; trg : {} ; Channel {:?} ; {:?}", + authorizer,authorizer_badge,trgchatter,channel,trg_role), + Some("identity.rs > promote()".to_string()), + None, + ); + Log::flush(); + + /* + [x] 1. Check if Authorizer Mod Badge then Auto Promote to Mod if not Mod + [x] 2. Get Authorizer & Target Chatter Roles with a Given Channel + [x] 3. If the authorizer & Target Chatters are the same, and the Authorizer is not a Admin, return no change + [x] 4a. If Authorizer is BotAdmin & trg_role is Some(BotAdmin) , set Target as BotAdmin and return + [x] 4b. If target is Broadcaster, return NoChange + [ ] 4c. If Authorizer is a SupMod,Broadcaster,BotAdmin , can Promote Target Chatter > Mod + - NOTE : We do not validate trg_role here - app logic requires you to promote 1 to Mod and 1 more to SupMod + [ ] 4d. If Authorizer is a Broadcaster,BotAdmin , can Promote a Target Mod > SupMod + - NOTE : We do not validate trg_role here - app logic requires you to promote 1 to Mod and 1 more to SupMod + + + */ + + // [x] 1. Check if Authorizer Mod Badge then Auto Promote to Mod if not Mod + + let trgchatter = trgchatter.to_lowercase(); + + let (authusrroles, trgusrroles) = if let Some(channel) = channel.clone() { + let mut authusrroles = self + .getspecialuserroles(authorizer.to_lowercase().clone(), Some(channel.clone())) + .await; + + { + // mut block + + // let authusrroles_mut = &mut authusrroles; + // [x] Add Mod(channel) to authusrroles + // [x] #TODO also add to DB if possible? + match *authorizer_badge { + Some(ChatBadge::Mod) + if (!authusrroles.contains(&UserRole::Mod(channel.clone())) + && !authusrroles.contains(&UserRole::SupMod(channel.clone()))) => + { + // (*authusrroles_mut).push(UserRole::Mod(channel.clone())); + authusrroles.push(UserRole::Mod(channel.clone())); + + // let mut srulock = self.special_roles_users.write().await; + // srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + // .write().await + // .push(UserRole::Mod(channel.clone())); + + self.affirm_chatter_in_db(authorizer.clone()).await; + self.add_role(authorizer.clone(), UserRole::Mod(channel.clone())) + .await; + } + + _ => (), + } + } // mut block + + // [x] 2. Get Authorizer & Target Chatter Roles + + let trgusrroles = self + .getspecialuserroles(trgchatter.to_lowercase().clone(), Some(channel.clone())) + .await; + + (authusrroles, trgusrroles) + } else { + let mut authusrroles = self + .getspecialuserroles(authorizer.to_lowercase().clone(), None) + .await; + let trgusrroles = self + .getspecialuserroles(trgchatter.to_lowercase().clone(), None) + .await; + (authusrroles, trgusrroles) + }; + + // [x] 3. If the authorizer & Target Chatters are the same, and the Authorizer is not a Admin, return no change + if trgchatter == authorizer && !authusrroles.contains(&UserRole::BotAdmin) { + return ChangeResult::NoChange("Can't target yourself".to_string()); + } + + // [x] 4a. If Authorizer is BotAdmin & trg_role is Some(BotAdmin) , set Target as BotAdmin and return + if authusrroles.contains(&UserRole::BotAdmin) && trg_role == Some(UserRole::BotAdmin) { + if trgusrroles.contains(&UserRole::BotAdmin) { + return ChangeResult::NoChange("Already has the role".to_string()); + } else { + // { + // let mut srulock = self.special_roles_users.write().await; + + // srulock.entry(trgchatter.clone()).or_insert(Arc::new(RwLock::new(vec![]))); + // botinstance::botlog::trace(&format!("Ensuring Target Chatter in Roles > {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + self.affirm_chatter_in_db(trgchatter.clone()).await; + + // { + + // let mut srulock = self.special_roles_users.write().await; + + // srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles for the user") + // .write().await + // .push(UserRole::BotAdmin); // <-- Adds the specific role + // botinstance::botlog::trace(&format!("Inserting Role > {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + self.add_role(trgchatter.clone(), UserRole::BotAdmin).await; + + return ChangeResult::Success("Promotion Successful".to_string()); + } + } + + // [x] 4b. If target is Broadcaster, return NoChange + + if trgusrroles.contains(&UserRole::Broadcaster) { + return ChangeResult::NoChange("Can't target broadcaster".to_string()); + } + + /* + [ ] 4c. If Authorizer is a SupMod,Broadcaster,BotAdmin , can Promote Target Chatter > Mod + - NOTE : We do not validate trg_role here - app logic requires you to promote 1 to Mod and 1 more to SupMod + [ ] 4d. If Authorizer is a Broadcaster,BotAdmin , can Promote a Target Mod > SupMod + - NOTE : We do not validate trg_role here - app logic requires you to promote 1 to Mod and 1 more to SupMod + */ + + // let authhasnsreqroles = match channel.clone() { + + // Some(channel) => authusrroles.contains(&UserRole::SupMod(channel.clone())) || + // authusrroles.contains(&UserRole::BotAdmin) || + // authusrroles.contains(&UserRole::Broadcaster) , + // None => authusrroles.contains(&UserRole::BotAdmin), + // }; + + if let Some(trg_chnl) = channel.clone() { + if !trgusrroles.contains(&UserRole::Broadcaster) + && !trgusrroles.contains(&UserRole::Mod(trg_chnl.clone())) + && !trgusrroles.contains(&UserRole::SupMod(trg_chnl.clone())) + { + // target user is neither Mod nor SupMod && not broadcaster + // target's Next Role would be Mod + // Authorizer must be SupMod,Broadcaster,BotAdmin + // > Promote target to Mod + if authusrroles.contains(&UserRole::SupMod(trg_chnl.clone())) + || authusrroles.contains(&UserRole::Broadcaster) + || authusrroles.contains(&UserRole::BotAdmin) + { + // { + + // // If target user doesn't exist in special_roles_users , add with blank vector roles + // let mut srulock = self.special_roles_users.write().await; + // srulock.entry(trgchatter.clone()).or_insert(Arc::new(RwLock::new(vec![]))); + // botinstance::botlog::trace(&format!("Ensuring Chatter in Roles {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + self.affirm_chatter_in_db(trgchatter.clone()).await; + + // { + // // promote target after + // let mut srulock = self.special_roles_users.write().await; + // srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // .write().await + // .push(UserRole::Mod(trg_chnl.clone())); // Role to Add + // botinstance::botlog::trace(&format!("Adding Roles to Chatter {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + self.add_role(trgchatter.clone(), UserRole::Mod(trg_chnl.clone())) + .await; + + return ChangeResult::Success(String::from("Promotion Successful")); + } + // Other else conditions would be mostly spcecial responses like ChangeResult::NoChange or ChangeResult::Fail + // related to authusrroles + else { + return ChangeResult::Failed(String::from("You're not permitted to do that")); + } + } else if !trgusrroles.contains(&UserRole::Broadcaster) + && trgusrroles.contains(&UserRole::Mod(trg_chnl.clone())) + && !trgusrroles.contains(&UserRole::SupMod(trg_chnl.clone())) + // + { + // target user is a Mod && not broadcaster + // target's Next Role would be SupMod + // [ ] #todo Check first if target have SupMod - Optional but could be done to cleanup first + // Authorizer must be Broadcaster,BotAdmin + // > Promote target to SupMod + + if authusrroles.contains(&UserRole::Broadcaster) + || authusrroles.contains(&UserRole::BotAdmin) + { + // { // Inserts user if doesn't exist + // let mut srulock = self.special_roles_users.write().await; + // srulock.entry(trgchatter.clone()).or_insert(Arc::new(RwLock::new(vec![]))); + // botinstance::botlog::trace(&format!("Ensuring User in Roles {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + self.affirm_chatter_in_db(trgchatter.clone()).await; + + // { // Adds the requested role for the user + // let mut srulock = self.special_roles_users.write().await; + // srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + // .write().await + // .push(UserRole::SupMod(trg_chnl.clone())); + // botinstance::botlog::trace(&format!("Adding Required Role > {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + + self.add_role(trgchatter.clone(), UserRole::SupMod(trg_chnl.clone())) + .await; + + // { // Removes the lower role (mod) from the user + // let mut srulock = self.special_roles_users.write().await; + // let mut uroleslock = srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // .write().await; + // if let Some(indx) = uroleslock.iter().position(|value| *value == UserRole::Mod(trg_chnl.clone())){ + // uroleslock.swap_remove(indx); + // } + + // botinstance::botlog::trace(&format!("Removing lower role > {:?}",uroleslock), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + + self.remove_role(trgchatter, UserRole::Mod(trg_chnl.clone())) + .await; + + return ChangeResult::Success(String::from("Promotion Successful")); + } else { + return ChangeResult::Failed(String::from("You're not permitted to do that")); + } + } else if !trgusrroles.contains(&UserRole::Broadcaster) + && trgusrroles.contains(&UserRole::SupMod(trg_chnl.clone())) + { + // target user is a SuMod && not broadcaster + // No Change + return ChangeResult::Failed(String::from("Already highest available role")); + } else { + // since handling for channel is already done, will be handling other trguserroles situations here + // other situations includes : + /* + [-] targetuser is broadcaster >> no need - this was done earlier in the function + [?] ? + */ + + // At the moment, without any new roles, this should not be reached + + botinstance::botlog::warn( + &format!("Code Warning : add handing for other trgusrroles"), + Some("identity.rs > promote()".to_string()), + None, + ); + return ChangeResult::Failed(String::from("Code Warning")); + } + + // let trghasreqroles = + + // { + + // // If target user doesn't exist in special_roles_users , add with blank vector roles + // let mut srulock = self.special_roles_users.write().await; + // srulock.entry(trgchatter.clone()).or_insert(Arc::new(RwLock::new(vec![]))); + // botinstance::botlog::trace(&format!("Ensuring Chatter in Roles {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + // { + // // promote target after + // let mut srulock = self.special_roles_users.write().await; + // srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + // .write().await + // .push(UserRole::Mod(trg_chnl.clone())); // Role to Add + // botinstance::botlog::trace(&format!("Adding Roles to Chatter {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + + // return ChangeResult::Success(String::from("Promotion Successful")); + }; + + // if authhasnsreqroles { + + // { + + // // If target user doesn't exist in special_roles_users , add with blank vector roles + // let mut srulock = self.special_roles_users.write().await; + // srulock.entry(trgchatter.clone()).or_insert(Arc::new(RwLock::new(vec![]))); + // botinstance::botlog::trace(&format!("SRLOCK - 1st write > {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + // { + // // promote target after + // let mut srulock = self.special_roles_users.write().await; + // srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + // .write().await + // .push(UserRole::Mod(trg_chnl)); + // botinstance::botlog::trace(&format!("SRLOCK - 2st write > {:?}",srulock.entry(trgchatter.clone())), + // Some("identity.rs > promote()".to_string()), None); + // Log::flush(); + // } + + // return ChangeResult::Success(String::from("Promotion Successful")); + + // } + + // authusrroles.contains(&UserRole::Mod(())) + + /* + + + let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()).await; + + + let rolemap = chatterroles; + + match trg_role { + Some(UserRole::Mod(_)) => { + + + if let Some(trg_chnl) = channel.clone() { + + // [ ] 1. If trg_role & trgchatter is a Mod or SupMod of the target channel, return NoChange + + let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()).await; + let rolemap = chatterroles; + // let rolemap = rolemap.unwrap(); + if rolemap.contains(&UserRole::Mod(trg_chnl.clone())) { + return ChangeResult::NoChange(String::from("Target User already has Target Role")); + } else if rolemap.contains(&UserRole::Broadcaster) { + return ChangeResult::NoChange(String::from("No need to do that for broadcaster")); + } + + // # otherwise, trg_role for the given chnl is not assigned to the trgchatter + // chatterroles.push(UserRole::Mod(trg_chnl.clone())); + // let a = self.special_roles_users; + // let b = a.write().await; + // // let c = b.get_mut(&trgchatter); + // let c = (*b).; + + // [ ] 2. Ensure an entry in Special_Roles_user for trgchatter, and push Mod(Channel) for the Target User + + // [x] (!!) AROUND HERE - check if the user exists first, and at least add the user as we're promoting anyway + + { + + // If target user doesn't exist in special_roles_users , add with blank vector roles + let mut srulock = self.special_roles_users.write().await; + srulock.entry(trgchatter.clone()).or_insert(Arc::new(RwLock::new(vec![]))); + botinstance::botlog::trace(&format!("SRLOCK - 1st write > {:?}",srulock.entry(trgchatter.clone())), + Some("identity.rs > promote()".to_string()), None); + Log::flush(); + } + { + // promote target after + let mut srulock = self.special_roles_users.write().await; + srulock + .get_mut(&trgchatter) + .expect("Error getting roles") + // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + .write().await + .push(UserRole::Mod(trg_chnl)); + botinstance::botlog::trace(&format!("SRLOCK - 2st write > {:?}",srulock.entry(trgchatter.clone())), + Some("identity.rs > promote()".to_string()), None); + Log::flush(); + } + + return ChangeResult::Success(String::from("Promotion Successful")); + } + + + }, + Some(UserRole::SupMod(_)) => + { + if let Some(trg_chnl) = channel.clone() { + + // [ ] 1. If trg_role & trgchatter is a Mod or SupMod of the target channel, return NoChange + + let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()).await; + let rolemap = chatterroles; + // let rolemap = rolemap.unwrap(); + if rolemap.contains(&UserRole::SupMod(trg_chnl.clone())) { + return ChangeResult::NoChange(String::from("Target User already has Target Role")); + } else if rolemap.contains(&UserRole::Broadcaster) { + return ChangeResult::NoChange(String::from("No need to do that for broadcaster")); + } + // # otherwise, trg_role for the given chnl is not assigned to the trgchatter + // chatterroles.push(UserRole::Mod(trg_chnl.clone())); + // let a = self.special_roles_users; + // let b = a.write().await; + // // let c = b.get_mut(&trgchatter); + // let c = (*b).; + + + // [ ] 2. Ensure an entry in Special_Roles_user for trgchatter, and push SupMod(Channel) for the Target User + + // [x] (!!) AROUND HERE - check if the user exists first, and at least add the user as we're promoting anyway + + { + let mut srulock = self.special_roles_users.write().await; + srulock.entry(trgchatter.clone()).or_insert(Arc::new(RwLock::new(vec![]))); + botinstance::botlog::trace(&format!("SRLOCK - 1st write > {:?}",srulock.entry(trgchatter.clone())), + Some("identity.rs > promote()".to_string()), None); + Log::flush(); + } + { + let mut srulock = self.special_roles_users.write().await; + srulock + .get_mut(&trgchatter) + .expect("Error getting roles") + // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + .write().await + .push(UserRole::SupMod(trg_chnl.clone())); + botinstance::botlog::trace(&format!("SRLOCK - 2st write > {:?}",srulock.entry(trgchatter.clone())), + Some("identity.rs > promote()".to_string()), None); + Log::flush(); + } + { + let mut srulock = self.special_roles_users.write().await; + // srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + // .write().await + // .(UserRole::Mod(trg_chnl)); + // let indx = srulock.iter().position() + let mut uroleslock = srulock + .get_mut(&trgchatter) + .expect("Error getting roles") + // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + .write().await; + if let Some(indx) = uroleslock.iter().position(|value| *value == UserRole::Mod(trg_chnl.clone())){ + uroleslock.swap_remove(indx); + } + + botinstance::botlog::trace(&format!("SRLOCK - 2st write > {:?}",uroleslock), + Some("identity.rs > promote()".to_string()), None); + Log::flush(); + } + + return ChangeResult::Success(String::from("Promotion Successful")); + } + } , + Some(UserRole::BotAdmin) => { + + + + let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()).await; + let rolemap = chatterroles; + + botinstance::botlog::trace(&format!("Target Role : BotAdmin"), + Some("identity.rs > promote()".to_string()), None); + + // [x] 1. Check their roles first if they already have botadmin + // [x] 2. Know that prior to promote() , BotAdmins should have been validated before being able to pass the BotAdmin target + + // [x] 1. Check target chatter's roles first if they already have botadmin + botinstance::botlog::trace(&format!("Eval rolemap.contains(BotAdmin) : {}",rolemap.contains(&UserRole::BotAdmin)), + Some("identity.rs > promote()".to_string()), None); + + botinstance::botlog::trace(&format!("Eval rolemap.contains(BotAdmin) > Rolemap : {:?}",rolemap), + Some("identity.rs > promote()".to_string()), None); + + // [ ] (!) This seems to be an issue - rolemap by this point is blank + if rolemap.contains(&UserRole::BotAdmin) { + return ChangeResult::NoChange(String::from("Target User already has Target Role")); + } + // # otherwise, trg_role for the given chnl is not assigned to the trgchatter + // chatterroles.push(UserRole::Mod(trg_chnl.clone())); + + // [x] (!!) AROUND HERE - check if the user exists first, and at least add the user as we're promoting anyway + + { + let mut srulock = self.special_roles_users.write().await; + + srulock.entry(trgchatter.clone()).or_insert(Arc::new(RwLock::new(vec![]))); + botinstance::botlog::trace(&format!("SRLOCK - 1st write > {:?}",srulock.entry(trgchatter.clone())), + Some("identity.rs > promote()".to_string()), None); + Log::flush(); + } + + { + + let mut srulock = self.special_roles_users.write().await; + + srulock + .get_mut(&trgchatter) + // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + .expect("Error getting roles") + .write().await + .push(UserRole::BotAdmin); + botinstance::botlog::trace(&format!("SRLOCK - 2nd write > {:?}",srulock.entry(trgchatter.clone())), + Some("identity.rs > promote()".to_string()), None); + Log::flush(); + } + botinstance::botlog::trace(&format!("Target Role : BotAdmin >> Successful"), + Some("identity.rs > promote()".to_string()), None); + + return ChangeResult::Success(String::from("Promotion Successful")); + }, + Some(_) => { + botinstance::botlog::warn(&format!("Runtime reached undeveloped code"), + Some("identity.rs > promote()".to_string()), None); + }, + None => { + botinstance::botlog::warn(&format!("Runtime reached undeveloped code"), + Some("identity.rs > promote()".to_string()), None); + }, + } + + */ + + // match chatterroles { + // Some(chatterroles) => { + + // // [x] chatter already has the target role + // if chatterroles.contains(&trg_role) { + // return ChangeResult::NoChange(String::from("Target User already has Target Role")); + // } + + // // By this point, chatteroles does not contain target role + // // match trgRole { + // // Some(trgRole) => { + // // match trgRole { + // // UserRole::Mod(a) => { + + // // }, + // // UserRole::SupMod(a) => (), + // // UserRole::BotAdmin => (), + // // _ => (), // <-- do nothing with al other options + // // } + // // }, + // // None => { + // // /* + // // - If trgRole is None , then promote by implicit rules . For example, + // // - For UserRoles without Mod or SupMod & Caller is SupMod | Broadcaster | BotAdmin > To Mod + // // - For Mod & Caller is SupMod | Broadcaster | BotAdmin > To SupMod + // // - For UserRoles without BotAdmin & Caller is BotAdmin > To BotAdmin + // // */ + // // }, + + // // } + + // // let trgRole = match trgRole { + // // Some(UserRole::Mod(a)) => a, + // // Some(UserRole::SupMod(a)) => a, + // // Some(UserRole::BotAdmin) => UserRole::BotAdmin, + // // None => { + // // /* + // // - If trgRole is None , then promote by implicit rules . For example, + // // - For UserRoles without Mod or SupMod & Caller is SupMod | Broadcaster | BotAdmin > To Mod + // // - For Mod & Caller is SupMod | Broadcaster | BotAdmin > To SupMod + // // - For UserRoles without BotAdmin & Caller is BotAdmin > To BotAdmin + // // */ + // // }, + + // // }; + + // // if let Some(trgRole) = trgRole { + + // // // [x] chatter already has the target role + // // if chatterroles.contains(&trgRole) { + // // return ChangeResult::NoChange(String::from("Target User already has Target Role")); + // // } + + // // // [ ] trgRole should be assigned based on the input channel + // // let roletoassign = UserRole:: + // // } + + // }, + // _ => (), + // } + botinstance::botlog::warn( + &format!("Runtime reached undeveloped code"), + Some("identity.rs > promote()".to_string()), + None, + ); + ChangeResult::Failed(String::from("ERROR")) + } + + pub async fn demote( + &self, + authorizer: String, + authorizer_badge: &Option, + trgchatter: String, + channel: Option, + // trg_role:Option + ) -> ChangeResult { + // botinstance::botlog::trace(&format!("IN VARS for demote() : Authorizer : {:?} ; Target Chatter : {} ; Target Channel : {:?} ; Targer Role {:?}", + // authorizer,trgchatter,channel,trg_role), + botinstance::botlog::trace(&format!("IN VARS for demote() : Authorizer : {:?} ; Target Chatter : {} ; Target Channel : {:?}", + authorizer,trgchatter,channel), Some("identity.rs > demote()".to_string()), None); + Log::flush(); + + /* + Check authorizer roles (if any) for the target channel + Check Targer User's roles (if any) for the target channel + Target Channel may be NONE in the case of Non-Channel related roles (FUTURE ENH) + + Use the roles of the above to determine whether the authorizer can demote the target user or not + */ + + // [x] 1. If Authorizer's Badge is Mod, ensuring Sender is in DB as Mod(Channel) + + let trgchatter = trgchatter.to_lowercase(); + + if let Some(channel) = channel { + let mut authusrroles = self + .getspecialuserroles(authorizer.to_lowercase().clone(), Some(channel.clone())) + .await; + // let authusrroles = authusrroles; + { + // let authusrroles_mut = &mut authusrroles; + // [x] Add Mod(channel) to authusrroles + // [x] #TODO also add to DB if possible? + match *authorizer_badge { + Some(ChatBadge::Mod) + if (!authusrroles.contains(&UserRole::Mod(channel.clone())) + && !authusrroles.contains(&UserRole::SupMod(channel.clone()))) => + { + // (*authusrroles_mut).push(UserRole::Mod(channel.clone())); + authusrroles.push(UserRole::Mod(channel.clone())); + + // [ ] below pushes mod to authorizer + // let mut srulock = self.special_roles_users.write().await; + // srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // // !! [ ] Unsure what happens if promoting a chatter that doesn't exist at + // .write().await + // .push(UserRole::Mod(channel.clone())); + + self.add_role(authorizer.clone(), UserRole::Mod(channel.clone())) + .await; + } + _ => (), + } + } + + // [x] 2. Targer User's Vec + + let trgusrroles = self + .getspecialuserroles(trgchatter.to_lowercase().clone(), Some(channel.clone())) + .await; + + // [x] 3. Return if Authorizer & Target are same chatter and Authorizer is not a BotAdmin + if trgchatter == authorizer && !authusrroles.contains(&UserRole::BotAdmin) { + return ChangeResult::NoChange("Can't target yourself".to_string()); + } + + // [x] 4a. Authorizers who are BotAdmin, Broadcaster or Supermod can demote a Mod + + if (authusrroles.contains(&UserRole::BotAdmin) + || authusrroles.contains(&UserRole::Broadcaster) + || authusrroles.contains(&UserRole::SupMod(channel.clone()))) + && trgusrroles.contains(&UserRole::Mod(channel.clone())) + { + // // [ ] Below removes Mod from trgchatter + // let mut srulock = self.special_roles_users.write().await; + // let mut usrrolelock = srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // .write().await; + // if let Some(indx) = usrrolelock.iter().position(|value| *value == UserRole::Mod(channel.clone())){ + // usrrolelock.swap_remove(indx); + // return ChangeResult::Success("Demoted successfully".to_string()) + // } + self.remove_role(trgchatter.clone(), UserRole::Mod(channel.clone())) + .await; + return ChangeResult::Success("Demoted successfully".to_string()); + } + // [x] 4b. Authorizers who are BotAdmin, Broadcaster can demote a SupMod + else if (authusrroles.contains(&UserRole::BotAdmin) + || authusrroles.contains(&UserRole::Broadcaster)) + && trgusrroles.contains(&UserRole::SupMod(channel.clone())) + { + // [ ] For Trgchatter, below pushes Mod UserRole and removes SupMod + // let mut srulock = self.special_roles_users.write().await; + // let mut usrrolelock = srulock + // .get_mut(&trgchatter) + // .expect("Error getting roles") + // .write().await; + // usrrolelock.push(UserRole::Mod(channel.clone())); // pushes Mod , and removes SupMod + // if let Some(indx) = usrrolelock.iter().position(|value| *value == UserRole::SupMod(channel.clone())){ + // usrrolelock.swap_remove(indx); + // return ChangeResult::Success("Demoted successfully".to_string()) + // } + + self.add_role(trgchatter.clone(), UserRole::Mod(channel.clone())) + .await; + self.remove_role(trgchatter.clone(), UserRole::SupMod(channel.clone())) + .await; + return ChangeResult::Success("Demoted successfully".to_string()); + } + // [x] 4c. When Target chatter isnt a Mod or SupMod to demote + else if !trgusrroles.contains(&UserRole::Mod(channel.clone())) + && !trgusrroles.contains(&UserRole::SupMod(channel.clone())) + { + return ChangeResult::Failed( + "Target chatter does not have a role that can be demoted".to_string(), + ); + } + // [x] 4d. When they're only a Mod + else if authusrroles.contains(&UserRole::Mod(channel.clone())) { + return ChangeResult::Failed("You're not permitted to do that".to_string()); + } + } + + botinstance::botlog::warn(&format!("Potential Unhandled Demotion Condition : Consider explicitely adding in for better handling"), + Some("identity.rs > demote()".to_string()), None); + Log::flush(); + ChangeResult::Failed(String::from("Did not meet criteria to demote succesfully")) + } + + // pub async fn getspecialuserroles(&self,chattername:String,channel:Option) -> Option>>> { + pub async fn getspecialuserroles( + &self, + chattername: String, + channel: Option, + ) -> Vec { + /* + Note : Ideally this be called for a given chatter name ? + */ + + // [ ] !!! TODO: I don't think below is evaluating by given channel + botinstance::botlog::debug( + &format!( + "IN VARS > chattername {} ; channel {:?}", + chattername, channel + ), + Some("IdentityManager > getspecialuserroles()".to_string()), + None, + ); + + // resulting vector + let mut evalsproles = vec![]; + + let chattername = chattername.to_lowercase(); + + // Checks if broadcaster + let channel_out = match channel { + Some(channel_tmp) => { + match channel_tmp { + ChType::Channel(channel_tmp) => { + // In this block, Some input channel is given + // We're comparing the channel name with chattername to determine if they're a broadcaster + if chattername == channel_tmp.to_lowercase() { + evalsproles.push(UserRole::Broadcaster); + } + + Some(ChType::Channel(channel_tmp)) + } // _ => () + } + } + None => None, + }; + + let rolesa = Arc::clone(&self.special_roles_users); + + let a = rolesa.read().await; + // let a = Arc::clone(a) + let a = a; + let vecroles = &(*a); + let vecroles = vecroles.get(&chattername); + match vecroles { + Some(a) => { + // [ ] This needs to take the user roles for the user, then yield only the one for the channel if channel is explicitely provided + // Some(Arc::clone(a)) + match channel_out { + Some(channel) => { + // let eval = a.read().await.contains(&UserRole::Mod(channel)); + // let eval = a.read().await.contains(&UserRole::SupMod(channel)); + botinstance::botlog::debug( + &format!("INTERNAL > All Roles found {:?}", &a), + Some("IdentityManager > getspecialuserroles()".to_string()), + None, + ); + + // a.read().await.contains(&UserRole::BotAdmin) + botinstance::botlog::trace( + &format!( + "INTERNAL > eval special roles contains botadmin : {:?}", + a.read().await.contains(&UserRole::BotAdmin) + ), + Some("IdentityManager > getspecialuserroles()".to_string()), + None, + ); + + if a.read().await.contains(&UserRole::BotAdmin) { + evalsproles.push(UserRole::BotAdmin); + } + if a.read().await.contains(&UserRole::Mod(channel.clone())) { + evalsproles.push(UserRole::Mod(channel.clone())); + } + if a.read().await.contains(&UserRole::SupMod(channel.clone())) { + evalsproles.push(UserRole::SupMod(channel.clone())); + } + // else {}; + } + None => { + // here , do nothing if the channel not provided + // [ ] TODO : Future is to provide all maybe ? + // ... no I think missing this is an issue for when the flag is -admin and channel is None? + // + // => 02.13 - Decided That None is provided as a Channel, we can output non-channel related roles like BotAdmin + if a.read().await.contains(&UserRole::BotAdmin) { + evalsproles.push(UserRole::BotAdmin); + } + } + } + } + None => { + // here, the user has no special listed roles. Note though Broadcaster is not stored in special roles + // Do nothing in this case + // There may be an issue if the chattername does not exist at the moment in special_roles_users + // In this case, evalsproles would only contain Broadcaster flags if any + } + } + + botinstance::botlog::debug( + &format!("OUT > evalsproles {:?}", &evalsproles), + Some("IdentityManager > getspecialuserroles()".to_string()), + None, + ); + + return evalsproles; + } +} + +#[cfg(test)] +mod core_identity { + + use casual_logger::Extension; + + use super::*; + + #[test] + fn user_role_identity() { + Log::set_file_ext(Extension::Log); + // Log::set_level(Level::Trace); + // let result = 2 + 2; + // assert_eq!(result, 4); + assert_eq!( + UserRole::SupMod(ChType::Channel("strong".to_string())), + UserRole::SupMod(ChType::Channel("Strong".to_lowercase())) + ); + } + + #[tokio::test] + async fn promote_workflow_01() { + Log::set_file_ext(Extension::Log); + // Log::set_level(Level::Trace); + + let test_id_mgr = IdentityManager::init(); + + // [x] Mod Attempts to Promote User + let channel = Some(ChType::Channel("twitchchanneltest".to_string())); + let trgchatter = "regularChatter".to_string(); + let authorizer_badge = &Some(ChatBadge::Mod); + let authorizer = "chatMod".to_string(); + let trg_role = None; + + let rslt = test_id_mgr + .promote( + authorizer, + authorizer_badge, + trgchatter.clone(), + channel.clone(), + trg_role, + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Failed(String::from("You're not permitted to do that")) + ); + } + + #[tokio::test] + async fn promote_workflow_02() { + Log::set_file_ext(Extension::Log); + // Log::set_level(Level::Trace); + + let test_id_mgr = IdentityManager::init(); + + // [x] Broadcaster Promotes Chatter to SupMod + let channel = Some(ChType::Channel("broadcasterer".to_string())); + let trgchatter = "regularChatter".to_string(); + let authorizer_badge = &Some(ChatBadge::Broadcaster); + let authorizer = "broadcasterer".to_string(); + let trg_role = None; + + let rslt = test_id_mgr + .promote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Success("Promotion Successful".to_string()) + ); + + let rslt = test_id_mgr + .getspecialuserroles(trgchatter.clone(), channel.clone()) + .await; + + assert!(rslt.contains(&UserRole::Mod(ChType::Channel("broadcasterer".to_string())))); + + let rslt = test_id_mgr + .promote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Success("Promotion Successful".to_string()) + ); + + let rslt = test_id_mgr + .getspecialuserroles(trgchatter.clone(), channel.clone()) + .await; + + assert!(rslt.contains(&UserRole::SupMod(ChType::Channel( + "broadcasterer".to_string() + )))); + + let rslt = test_id_mgr + .promote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Failed(String::from("Already highest available role")) + ); + } + + #[tokio::test] + async fn promote_workflow_03() { + Log::set_file_ext(Extension::Log); + // Log::set_level(Level::Trace); + + let test_id_mgr = IdentityManager::init(); + + // [x] SupMod Promotes Chatter to SupMod + + // [x] Broadcaster first promotes a SupMod + + let broadcaster = "broadcasterer".to_string(); + let broadcaster_badge = &Some(ChatBadge::Broadcaster); + let channel = Some(ChType::Channel(broadcaster.clone())); + let supchatter = "superModerator".to_string(); + let trg_role = None; + + let rslt = test_id_mgr + .promote( + broadcaster.clone(), + broadcaster_badge, + supchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Success("Promotion Successful".to_string()) + ); + + let rslt = test_id_mgr + .promote( + broadcaster.clone(), + broadcaster_badge, + supchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Success("Promotion Successful".to_string()) + ); + + let rslt = test_id_mgr + .getspecialuserroles(supchatter.clone(), channel.clone()) + .await; + + assert!(rslt.contains(&UserRole::SupMod(channel.unwrap()))); + + // [x] SupMod Attempts to Promote Chatter to SupMod + + // let broadcaster = "broadcasterer".to_string(); + let authorizer = supchatter; + let authorizer_badge = &Some(ChatBadge::Broadcaster); + let channel = Some(ChType::Channel(broadcaster.clone())); + let trgchatter = "regularChatter".to_string(); + let trg_role = None; + + let rslt = test_id_mgr + .promote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Success("Promotion Successful".to_string()) + ); + + let rslt = test_id_mgr + .getspecialuserroles(trgchatter.clone(), channel.clone()) + .await; + + // assert!(rslt.contains(&UserRole::Mod(ChType::Channel("broadcasterer".to_string())))); + assert!(rslt.contains(&UserRole::Mod(channel.clone().unwrap()))); + + let rslt = test_id_mgr + .promote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + // assert_eq!(rslt, ChangeResult::Success("Promotion Successful".to_string())); + assert_eq!( + rslt, + ChangeResult::Failed("You're not permitted to do that".to_string()) + ); + } + + #[tokio::test] + async fn promote_workflow_04() { + Log::set_file_ext(Extension::Log); + // Log::set_level(Level::Trace); + + let test_id_mgr = IdentityManager::init(); + + // [x] BotAdmin Promotes Chatter to SupMod + + // [x] Create BotAdmin first + + let botadmin = "botadministrator".to_string(); + let botadmin_badge = &None; + + test_id_mgr.affirm_chatter_in_db(botadmin.clone()).await; + test_id_mgr + .add_role(botadmin.clone(), UserRole::BotAdmin) + .await; + + let rslt = test_id_mgr + .getspecialuserroles(botadmin.clone(), None) + .await; + + assert!(rslt.contains(&UserRole::BotAdmin)); + + // [x] SupMod Attempts to Promote Chatter to SupMod + + // let broadcaster = "broadcasterer".to_string(); + let authorizer = botadmin; + let authorizer_badge = botadmin_badge; + let channel = Some(ChType::Channel("somechannel".to_string())); + let trgchatter = "regularChatter".to_string(); + let trg_role = None; + + let rslt = test_id_mgr + .promote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Success("Promotion Successful".to_string()) + ); + + let rslt = test_id_mgr + .getspecialuserroles(trgchatter.clone(), channel.clone()) + .await; + + assert!(rslt.contains(&UserRole::Mod(channel.clone().unwrap()))); + + let rslt = test_id_mgr + .promote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + // assert_eq!(rslt, ChangeResult::Success("Promotion Successful".to_string())); + assert_eq!( + rslt, + ChangeResult::Success("Promotion Successful".to_string()) + ); + + let rslt = test_id_mgr + .getspecialuserroles(trgchatter.clone(), channel.clone()) + .await; + + assert!(rslt.contains(&UserRole::SupMod(channel.clone().unwrap()))); + + let rslt = test_id_mgr + .promote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + trg_role.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Failed(String::from("Already highest available role")) + ); + } + + #[tokio::test] + async fn demote_workflow_01() { + Log::set_file_ext(Extension::Log); + // Log::set_level(Level::Trace); + + // [x] SupMod demotes a mod + + // [x] create a SupMod first + + let test_id_mgr = IdentityManager::init(); + + let supmod = "supmoder".to_string(); + // let supmod_badge = &None; + let channel = Some(ChType::Channel("somechannel".to_string())); + + test_id_mgr.affirm_chatter_in_db(supmod.clone()).await; + test_id_mgr + .add_role(supmod.clone(), UserRole::SupMod(channel.clone().unwrap())) + .await; + + let rslt = test_id_mgr + .getspecialuserroles(supmod.clone(), channel.clone()) + .await; + + assert!(rslt.contains(&UserRole::SupMod(channel.clone().unwrap()))); + + // [x] Create regular mod + + let regmod = "moder".to_string(); + // let supmod_badge = &None; + // let channel = Some(ChType::Channel("somechannel".to_string())); + + test_id_mgr.affirm_chatter_in_db(regmod.clone()).await; + test_id_mgr + .add_role(regmod.clone(), UserRole::Mod(channel.clone().unwrap())) + .await; + + let rslt = test_id_mgr + .getspecialuserroles(regmod.clone(), channel.clone()) + .await; + + assert!(rslt.contains(&UserRole::Mod(channel.clone().unwrap()))); + + // [x] Regular mod attempts to demote a supmod + + let authorizer = regmod.clone(); + let authorizer_badge = &None; + let trgchatter = supmod.clone(); + + let rslt = test_id_mgr + .demote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Failed("You're not permitted to do that".to_string()) + ); + + // [x] SupMod demotes regular mod + + let authorizer = supmod; + let authorizer_badge = &None; + let trgchatter = regmod; + + let rslt = test_id_mgr + .demote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Success("Demoted successfully".to_string()) + ); + + let rslt = test_id_mgr + .demote( + authorizer.clone(), + authorizer_badge, + trgchatter.clone(), + channel.clone(), + ) + .await; + + assert_eq!( + rslt, + ChangeResult::Failed( + "Target chatter does not have a role that can be demoted".to_string() + ) + ); + } +} diff --git a/src/core/ratelimiter.rs b/src/core/ratelimiter.rs index a25871c..f87b2b9 100644 --- a/src/core/ratelimiter.rs +++ b/src/core/ratelimiter.rs @@ -1,10 +1,8 @@ - use std::time::Instant; const TIME_THRESHOLD_S: u64 = 30; const MSG_THRESHOLD: u32 = 20; - #[derive(Debug, Clone)] pub struct RateLimiter { timer: Instant, @@ -13,10 +11,9 @@ pub struct RateLimiter { pub enum LimiterResp { Allow, // when it's evaluated to be within limits - Skip, // as outside of rate limits + Skip, // as outside of rate limits } - impl RateLimiter { pub fn new() -> Self { Self { @@ -25,24 +22,23 @@ impl RateLimiter { } } -pub fn check_limiter(&mut self) -> LimiterResp { - - if self.timer.elapsed().as_secs() >= TIME_THRESHOLD_S { -// # [x] elapsed >= TIME_THRESHOLD_S - self.timer = Instant::now(); - self.msgcounter = 0; - LimiterResp::Allow - } else if self.msgcounter < MSG_THRESHOLD { -// # [x] elapsed < TIME_THRESHOLD_S && msgcounter < MSG_THRESHOLD - LimiterResp::Allow - // } else if self.msgcounter >= MSG_THRESHOLD { - } else { -// # [x] elapsed < TIME_THRESHOLD_S && msgcounter >= MSG_THRESHOLD - LimiterResp::Skip + pub fn check_limiter(&mut self) -> LimiterResp { + if self.timer.elapsed().as_secs() >= TIME_THRESHOLD_S { + // # [x] elapsed >= TIME_THRESHOLD_S + self.timer = Instant::now(); + self.msgcounter = 0; + LimiterResp::Allow + } else if self.msgcounter < MSG_THRESHOLD { + // # [x] elapsed < TIME_THRESHOLD_S && msgcounter < MSG_THRESHOLD + LimiterResp::Allow + // } else if self.msgcounter >= MSG_THRESHOLD { + } else { + // # [x] elapsed < TIME_THRESHOLD_S && msgcounter >= MSG_THRESHOLD + LimiterResp::Skip + } } -} pub fn increment_counter(&mut self) -> () { - self.msgcounter += 1; + self.msgcounter += 1; } -} \ No newline at end of file +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..650ed26 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,2 @@ +pub mod core; +pub mod modules; diff --git a/src/main.rs b/src/main.rs index cd71f0f..d00584f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,82 @@ - - -pub mod core; -pub mod modules; +// pub mod core; +// pub mod modules; +//use myLib; +//pub mod lib; use std::process::Output; -use crate::core::botinstance::BotInstance; +// use crate::core::botinstance::ArcBox; +use botLib::core::botinstance::ArcBox; + +use botLib::core::botinstance::{self, BotInstance}; +// use core::botinstance::{self,BotInstance}; + +use casual_logger::Extension; +use std::sync::Arc; +use tokio::sync::RwLock; +pub type BotAR = Arc>; + +use casual_logger::{Level, Log}; #[tokio::main] pub async fn main() { + Log::set_file_ext(Extension::Log); + Log::set_level(Level::Trace); + // Log::set_level(Level::Notice); - let bot = BotInstance::init(); + let bot = BotInstance::init().await; + + // Log::debug("Checking bot actions"); + botinstance::botlog::debug("Checking bot actions", Some("main()".to_string()), None); + let a = Arc::clone(&bot.botmodules.botactions); + let a = a.read().await; + // let a = *a; + + for (_, acts) in &*a { + for act in acts { + match act { + botLib::core::botmodules::BotAction::C(b) => { + // println!("bot actiions: {}",b.command) + // Log::info(&format!("bot actions: {}",b.command)); + botinstance::botlog::info( + &format!("bot actions: {}", b.command), + Some("main()".to_string()), + None, + ); + } + botLib::core::botmodules::BotAction::L(l) => { + // println!("bot actiions: {}",l.name) + // Log::info(&format!("bot actions: {}",l.name)); + botinstance::botlog::info( + &format!("bot actions: {}", l.name), + Some("main()".to_string()), + None, + ); + } + _ => { + // println!("Not a valid match??") + // Log::info("Not a valid match??"); + botinstance::botlog::info( + "Not a valid match??", + Some("main()".to_string()), + None, + ); + } + } + } + } + + // println!("Starting runner.."); + // Log::notice("Starting Bot Runner"); + botinstance::botlog::notice("Starting Bot Runner", Some("main()".to_string()), None); + println!("Starting Bot Runner"); + + Log::flush(); bot.runner().await; -} \ No newline at end of file + // println!("ERROR : EXIT Game loop"); + // let msg = Log::fatal("ERROR : EXIT Game loop"); + // panic!("{}",Log::fatal("ERROR : EXIT Game loop")); + let a = botinstance::botlog::fatal("ERROR : EXIT Game loop", Some("main()".to_string()), None); + panic!("{}", a); +} diff --git a/src/modules.rs b/src/modules.rs index 5fbaa8a..08cb49b 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -10,27 +10,20 @@ pub use crate::core::botmodules::ModulesManager; // use crate::core::botinstance; pub use crate::core::botinstance::BotInstance; - +use futures::lock::Mutex; +use std::sync::Arc; // [ ] Load submodules mod experiments; - // [ ] init() function that accepts bot instance - this is passed to init() on submodules -// pub fn init(mgr:ModulesManager) -> ModulesManager -// pub fn init(mgr:ModulesManager) -// where -// // F: std::future::Future + Send, -// // F : Send, -// F : Send + ?Sized, -pub fn init(mgr:&mut ModulesManager) -{ +pub async fn init(mgr: Arc) { // Modules initializer loads modules into the bot // this is achieved by calling submodules that also have fn init() defined - experiments::init(mgr) + experiments::init(mgr).await //(); -} \ No newline at end of file +} diff --git a/src/modules/experiments.rs b/src/modules/experiments.rs index 11f1b94..e61d296 100644 --- a/src/modules/experiments.rs +++ b/src/modules/experiments.rs @@ -1,9 +1,8 @@ - /* Submodules - - should have definitions of BotAction that will be added to a bit - - therefore, will be defined in modules.rs file + - therefore, will be defined in modules.rs file - will define one init(&BotInstance) take within the module that will contain : - BotAction definitions that each call &BotInstance module manager to add itself @@ -14,52 +13,107 @@ use std::future::Future; -use crate::core::botmodules::{ModulesManager,Listener,BotModule,BotActionTrait, BotCommand}; -use crate::core::botmodules::bot_actions::actions_util; +use crate::core::botmodules::bot_actions::actions_util::{self, BotAR}; +use crate::core::botmodules::{BotActionTrait, BotCommand, BotModule, Listener, ModulesManager}; -use crate::core::botinstance::{self}; +use crate::core::botinstance::{self, BotInstance, ChType}; +use futures::lock::Mutex; use twitch_irc::message::PrivmsgMessage; -pub fn init(mgr:&mut ModulesManager) -{ +use crate::core::identity; +use rand::Rng; - BotCommand { - module : BotModule(String::from("experiments 004")), - command : String::from("test"), // command call name - alias : vec![String::from("tester"),String::from("testy")], // String of alternative names - exec_body : actions_util::asyncbox(testy) , - help : String::from("DUPCMD4 tester"), - }.add_to_modmgr(mgr); +use std::rc::Rc; +use std::sync::{Arc, RwLock}; - let list1 = Listener { - module : BotModule(String::from("experiments 004")), - name : String::from("GoodGirl Listener"), - exec_body : actions_util::asyncbox(good_girl) , - help : String::from("") +// pub fn init(mgr:&mut ModulesManager) +pub async fn init(mgr: Arc) { + // BotCommand { + // module : BotModule(String::from("experiments 004")), + // command : String::from("test1"), // command call name + // alias : vec![String::from("tester1"),String::from("testy1")], // String of alternative names + // exec_body : actions_util::asyncbox(testy) , + // help : String::from("DUPCMD4 tester"), + // required_roles : vec![ + // //identity::UserRole::Mod(ChType::Channel(String::new())), + // identity::UserRole::SupMod(ChType::Channel(String::new())) + // ], + // }.add_to_modmgr(mgr); + + let botc1 = BotCommand { + module: BotModule(String::from("experiments001")), + command: String::from("test1"), // command call name + alias: vec![String::from("tester1"), String::from("testy1")], // String of alternative names + exec_body: actions_util::asyncbox(testy), + help: String::from("Test Command tester"), + required_roles: vec![identity::UserRole::BotAdmin], }; - list1.add_to_modmgr(mgr); + botc1.add_to_modmgr(Arc::clone(&mgr)).await; + let list1 = Listener { + module: BotModule(String::from("experiments001")), + name: String::from("GoodGirl Listener"), + exec_body: actions_util::asyncbox(good_girl), + help: String::from(""), + }; + list1.add_to_modmgr(Arc::clone(&mgr)).await; } +async fn good_girl(mut bot: BotAR, msg: PrivmsgMessage) { + // println!("In GoodGirl() Listener"); + // Change below from debug to trace if required later + botinstance::botlog::debug( + "In GoodGirl() Listener", + Some("experiments > goodgirl()".to_string()), + Some(&msg), + ); -async fn good_girl(mut chat:botinstance::Chat,msg:PrivmsgMessage) -{ - println!("In GoodGirl()"); //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); - if msg.sender.name == "ModulatingForce" && msg.message_text.contains("GoodGirl") { - chat.say_in_reply_to(&msg,String::from("GoodGirl")).await; - } + // [ ] Uses gen_ratio() to output bool based on a ratio probability . + // - For example gen_ratio(2,3) is 2 out of 3 or 0.67% (numerator,denomitator) + // - More Info : https://rust-random.github.io/rand/rand/trait.Rng.html#method.gen_ratio - + if msg.sender.name.to_lowercase() == "ModulatingForce".to_lowercase() + || msg.sender.name.to_lowercase() == "mzNToRi".to_lowercase() + // && msg.message_text.contains("GoodGirl") + { + // chat.say_in_reply_to(&msg,String::from("GoodGirl")).await; + //if rng.gen_ratio(1,5) { + // println!("In GoodGirl() > Pausechamp"); + botinstance::botlog::debug( + "In GoodGirl() > Pausechamp", + Some("experiments > goodgirl()".to_string()), + Some(&msg), + ); + let rollwin = rand::thread_rng().gen_ratio(1, 8); + if rollwin { + // println!("In GoodGirl() > Win"); + botinstance::botlog::debug( + "In GoodGirl() > Win", + Some("experiments > goodgirl()".to_string()), + Some(&msg), + ); + let a = Arc::clone(&bot); + let botlock = a.read().await; + botlock + .botmgrs + .chat + .say_in_reply_to(&msg, String::from("GoodGirl xdd ")) + .await; + } + } } -async fn testy(mut _chat:botinstance::Chat,_msg:PrivmsgMessage) -{ - println!("testy triggered!") - -} \ No newline at end of file +async fn testy(mut _chat: BotAR, msg: PrivmsgMessage) { + println!("testy triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call + botinstance::botlog::debug( + "testy triggered!", + Some("experiments > testy()".to_string()), + Some(&msg), + ); +}