From 1b14c96a76336ba2d58d7b8fc122204b047c2e3d Mon Sep 17 00:00:00 2001 From: ModulatingForce <116608425+modulatingforce@users.noreply.github.com> Date: Sun, 4 Feb 2024 14:28:37 -0500 Subject: [PATCH 1/5] 2024.02.04 - LATEST PROBLEM --- Cargo.lock | 111 +++++++--- Cargo.toml | 2 + src/core/botinstance.rs | 403 +++++++++++++++++++++++++++++++++---- src/core/botmodules.rs | 125 +++++++++--- src/core/identity.rs | 274 ++++++++++++++++++++----- src/main.rs | 6 +- src/modules.rs | 6 +- src/modules/experiments.rs | 58 +++++- 8 files changed, 838 insertions(+), 147 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0708382..8cb4571 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,9 +19,9 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "async-trait" -version = "0.1.74" +version = "0.1.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" +checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" dependencies = [ "proc-macro2", "quote", @@ -151,7 +151,9 @@ checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" name = "forcebot_rs" version = "0.1.0" dependencies = [ + "async-trait", "dotenv", + "futures", "rand", "tokio", "twitch-irc", @@ -173,32 +175,89 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] -name = "futures-core" -version = "0.3.29" +name = "futures" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" +checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] [[package]] -name = "futures-sink" -version = "0.3.29" +name = "futures-channel" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817" - -[[package]] -name = "futures-task" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2" - -[[package]] -name = "futures-util" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" 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", @@ -432,18 +491,18 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" -version = "1.0.70" +version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" +checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.33" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] @@ -580,9 +639,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.41" +version = "2.0.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c8b28c477cc3bf0e7966561e3460130e1255f7a1cf71931075f1c5e7a7e269" +checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 417031d..0043332 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,3 +10,5 @@ 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" \ No newline at end of file diff --git a/src/core/botinstance.rs b/src/core/botinstance.rs index 568d4e6..5f9561d 100644 --- a/src/core/botinstance.rs +++ b/src/core/botinstance.rs @@ -1,4 +1,5 @@ +use futures::lock::Mutex; use tokio::sync::mpsc::UnboundedReceiver; use twitch_irc::login::StaticLoginCredentials; use twitch_irc::ClientConfig; @@ -8,6 +9,10 @@ use twitch_irc::message::PrivmsgMessage; use twitch_irc::message::ServerMessage; use twitch_irc::transport::tcp::TCPTransport; use twitch_irc::transport::tcp::TLS; +// use std::borrow::Borrow; +use std::borrow::BorrowMut; +use std::boxed; +use std::cell::Ref; use std::env; use dotenv::dotenv; @@ -21,9 +26,19 @@ use crate::core::ratelimiter::RateLimiter; use crate::core::ratelimiter; use crate::core::botmodules; -use crate::core::botmodules::ModulesManager; +use crate::core::botmodules::{ModulesManager,BotAction}; use crate::core::identity::{IdentityManager,Permissible}; +use std::rc::Rc; +use std::cell::RefCell; +use std::sync::{Arc, RwLock}; +// use futures::lock::Mutex; + +use std::pin::Pin; + +//use std::borrow::Borrow; +use core::borrow::Borrow; + #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub enum ChType { @@ -41,7 +56,8 @@ pub use ModType::BotModule; #[derive(Clone)] pub struct Chat { - pub ratelimiters : HashMap, // used to limit messages sent per channel + // pub ratelimiters : HashMap, // used to limit messages sent per channel + pub ratelimiters : Arc>>, // used to limit messages sent per channel pub client : TwitchIRCClient,StaticLoginCredentials>, } @@ -51,19 +67,21 @@ impl Chat { pub fn init(ratelimiters:HashMap, client:TwitchIRCClient, StaticLoginCredentials>) -> Chat { Chat{ - ratelimiters : ratelimiters, + ratelimiters : Arc::new(Mutex::new(ratelimiters)), client : client, } } - pub fn init_channel(&mut self, chnl:ChType) -> () { + // 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 @@ -76,7 +94,12 @@ impl Chat { // 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 = self.ratelimiters + 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"); @@ -140,7 +163,7 @@ impl Chat { #[derive(Clone)] pub struct BotManagers { // pub botmodules : ModulesManager, - pub identity : IdentityManager, + pub identity : Arc>, pub chat : Chat, } @@ -148,29 +171,49 @@ impl BotManagers { pub fn init(ratelimiters:HashMap, client:TwitchIRCClient, StaticLoginCredentials>) - -> BotManagers { - BotManagers { + -> Arc> { + let a = Arc::new(Mutex::new(BotManagers { // botmodules : ModulesManager::init(), - identity : IdentityManager::init(), + identity : Arc::new(Mutex::new(IdentityManager::init())), chat : Chat::init(ratelimiters,client), - } - + })); + a + + } + pub fn rIdentity(self) -> Arc> { + self.identity + } + pub fn rChat(&self) -> Arc> { + Arc::new(Mutex::new(self.chat)) } } + +pub struct ArcBox(pub Arc>); + +impl ArcBox{ + pub fn inst(&self) -> &Mutex { + &self.0 + } + +} + +//#[derive(Clone)] +// #[derive(Copy)] // <-- Cannot be derived pub struct BotInstance { - prefix : char, - bot_channel : ChType, + pub prefix : char, + pub bot_channel : ChType, pub incoming_messages : UnboundedReceiver, + // pub incoming_messages : RefCell>, // pub chat : Chat, - pub botmodules : ModulesManager, - twitch_oauth : String, + pub botmodules : Arc>, + pub twitch_oauth : String, pub bot_channels : Vec, // pub identity : IdentityManager, - pub botmgrs : BotManagers, + pub botmgrs : Arc>, } @@ -179,7 +222,8 @@ impl BotInstance { - pub fn init() -> BotInstance + // pub fn init() -> BotInstance + pub fn init() -> Arc { dotenv().ok(); @@ -242,19 +286,113 @@ impl BotInstance }; - println!("{:?}",b.botmgrs.chat.ratelimiters); + //println!("{:?}",b.botmgrs.chat.ratelimiters); - b + Arc::new(b) } - pub async fn runner(mut self) -> () { + // async fn rcv_helper(self) -> Option { + // // self.incoming_messages.get_mut().recv().await + // let mut a = self.incoming_messages; + // a.get_mut().recv().await + // } + + // pub async fn runner(mut self) -> () { + pub async fn runner(mut self) -> () { + + + // let mut boxed_bot = Arc::new(RefCell::new(self)); // <-- [ERROR] Future cannot be handled safely + 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 + // let boxed_bot = Arc::new(Mutex::new(self)); + // let mut boxed_bot = Arc::new(self); + // let bot = Rc::new(RefCell::new(self)); + // let mut bot = Rc::new(RefCell::new(&self)); + //let bot = Arc::new(Mutex::new(&self)); + // let mut boxed_bot = Arc::new(RefCell::new(self)); + let mut boxed_bot = Arc::new(Mutex::new(self)); + + // while let Some(message) = bot.borrow_mut().incoming_messages.recv().await { + + // let bot = Arc::clone(&botinit); + + // while let Some(message) = bot.lock().unwrap().incoming_messages.recv().await { + //let b = Arc::clone(&bot); + + // let mut bot = RefCell::new(&self); + + // let mut bota = bot.clone().borrow(); + + // let boxed_bot = Rc::new(RefCell::new(self)); + // let boxed_bot = Rc::new(self); + // let boxed_bot = Pin::new(Rc::new(self)); + //let mut boxed_bot = Rc::new(RefCell::new(self)); + // let mut a = (*boxed_bot).clone().into_inner(); + // let mut a = Rc::clone(&boxed_bot).borrow_mut(); + //let mut a = Rc::>>::Borrow(Rc::clone(&boxed_bot)); + + + // while let Some(message) = Rc::clone(&boxed_bot).into_inner().incoming_messages.recv().await { + // while let Some(message) = Rc::::borrow(Rc::::as_ref(boxed_bot)) { + + // let a = boxed_bot.borrow(); + + // let boxed_bota = boxed_bot.borrow_mut(); + + // let a = Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner(); + + // let boxed_bot = RefCell::new(Rc::new(self)); + //let boxed_bot = Rc::new(RefCell::new(self)); + // Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner().incoming_messages.recv().await; + + // let a:Borrowed = boxed_bot.borrow(); + // while let Some(message) = Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner().incoming_messages.recv().await { + // while let Some(message) = RefCell::new(self).borrow_mut().incoming_messages.recv().await { + // while let Some(message) = Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner().incoming_messages.recv().await { + // while let Some(message) = Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().rcv_helper().await { + // while let Some(message) = Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().incoming_messages.recv().await { + // let mut a = Arc::try_unwrap(boxed_bot.clone()) + // .ok().unwrap() + // .into_inner() + // .ok().unwrap(); + // let a = Arc::clone(&boxed_bot).into_inner().unwrap().incoming_messages; + // .into_inner() + // .try_into(). + // .ok().unwrap(); + // while let Some(message) = a.lock().unwrap().incoming_messages.recv().await { + // while let Some(message) = a.recv().await { + // let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap(); + // let mut a = Arc::try_unwrap(boxed_bot.clone()) + // .ok() + // .unwrap(); + // .into_inner() + // .get_mut() + // .ok(); + // .unwrap(); + //let mut a = a.lock().unwrap(); + // let a = *a; + // while let Some(message) = a.lock().ok().unwrap().incoming_messages.recv().await { + // while let Some(message) = a.get_mut().expect("Error").incoming_messages.recv().await { + //let tempbot = boxed_bot.clone(); + // while let Some(message) = Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().ok().unwrap().incoming_messages.recv().await { + // while let Some(message) = Arc::try_unwrap(tempbot.clone()).ok().unwrap().incoming_messages.recv().await { + // while let Some(message) = boxed_bot.to_owned().incoming_messages.recv().await { + // while let Some(message) = self.incoming_messages.recv().await { + // let a:Arc> = Arc::clone(&boxed_bot); + // while let Some(message) = a.incoming_messages.recv().await { + // let a = Arc::clone(&boxed_bot).into_inner(); + // while let Some(message) = a.incoming_messages.recv().await { + let tempbot = boxed_bot.clone(); + while let Some(message) = Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().incoming_messages.recv().await { + // while let Some(message) = tempbot.into_inner().incoming_messages.recv().await { + //while let Some(message) = boxed_bot.borrow().incoming_messages.recv().await { + // // Below can be used to debug if I want to capture all messages // println!("Received message: {:?}", message); + + // let boxed_bot = Arc::new(self); match message { ServerMessage::Notice(msg) => { @@ -272,7 +410,35 @@ impl BotInstance println!("Privmsg section"); // b.listener_main_prvmsg(&msg); - self.listener_main_prvmsg(&msg).await; + // self.listener_main_prvmsg(&msg).await; + // bot.into_inner().listener_main_prvmsg(&msg).await; + //let bot = Rc::>::clone(&bot); + + // bot.borrow().listener_main_prvmsg(&msg).await; + // let mut a = Rc::Clone(&bot); + // a.borrow_mut().listener_main_prvmsg(&msg).await; + // bot.borrow_mut().into_inner().listener_main_prvmsg(&msg).await; + // bot.listener_main_prvmsg(&msg).await; + // bot.lock().unwrap().listener_main_prvmsg(&msg).await; + // bot.borrow_mut().listener_main_prvmsg(&msg).await; + // Rc::clone(&boxed_bot).into_inner().listener_main_prvmsg(&msg).await; + // boxed_bot.borrow().listener_main_prvmsg(&msg).await; + // let bottemp = boxed_bot.borrow_mut(); + // let a = **bottemp; + // Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner().listener_main_prvmsg(&msg).await; + // Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().listener_main_prvmsg(&msg).await; + // Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().ok().unwrap().listener_main_prvmsg(&msg).await; + // let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap(); + // let mut a = a.lock().unwrap(); + // let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap(); + // a.listener_main_prvmsg(&msg).await; + + // (*a).listener_main_prvmsg(&msg).await; + // let a:Arc> = Arc::clone(&boxed_bot); + // a.into_inner().listener_main_prvmsg(&msg).await; + let tempbot = boxed_bot.clone(); + Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().listener_main_prvmsg(&msg).await ; + // - BotCommand listener should likely need to be called within the above @@ -296,24 +462,103 @@ impl BotInstance join_handle.await.unwrap(); + + } + + pub fn get_botmodules(self) -> Arc> { + // let a = self.botmodules; + // Arc::clone(&Arc::new(Mutex::new(self.botmodules))) + self.botmodules + + } + + pub fn get_botactions(&self) -> &HashMap> { + self.get_botactions() + } + + pub async fn get_botmgrs(self) -> Arc> { + // Arc::new(self.botmgrs) + // Arc::clone(&Arc::new(Mutex::new(self.botmgrs))) + let a = self.botmgrs; + // let a = *a.lock().await; + // let a = a.rIdentity(); + a + } + + pub async fn get_identity(self) -> Arc> { + // let a = self.botmgrs; + // Arc::clone(&Arc::new(Mutex::new(a.rIdentity()))) + // let a = self.botmgrs; + // Arc::clone(&Arc::new(Mutex::new(a.rIdentity()))) + let a = self.get_botmgrs().await; + let a = a.lock().await; + // let a = a.rIdentity(); + let a = a.clone().identity; + a.clone() + } + + pub fn get_prefix(&self) -> String { + self.prefix.to_string() + } + // ----------------- // PRIVATE FUNCTIONS // async fn listener_main_prvmsg(&mut self,msg:PrivmsgMessage) -> () { - async fn listener_main_prvmsg(&self,msg:&PrivmsgMessage) -> () { + async fn listener_main_prvmsg(self,msg:&PrivmsgMessage) -> () { // 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 botmgr = Rc::new(&self.botmgrs); + + // let mut boxedbot = Rc::new(RefCell::new(self)); + // let boxed_bot = Rc::new(RefCell::new(self)); + // let boxed_bot = Arc::new(Mutex::new(self)); + // let boxed_bot = Arc::new(self); + //let boxed_bot = Arc::clone(self); + // let mut boxed_bot = Arc::new(RefCell::new(self)); + // let mut boxed_bot = Arc::new(RwLock::new(self)); + // let boxed_bot = Arc::new(RwLock::new(self)); + // let boxed_bot = Arc::new(Mutex::new(self)); + let boxed_bot = Arc::new(Mutex::new(self)); + + + // for (_m,acts) in &self.botmodules.botactions { + // for (_m,acts) in &self.botmodules.botactions { + // for (_m,acts) in bot.into_inner().botmodules.botactions { + // let mut bot = Rc::clone(&bot); + // for (_m,acts) in bot.into_inner().botmodules.botactions { + // for (_m,acts) in bot.into_inner().botmodules.botactions { + // for (_m,acts) in Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().botmodules.botactions { + // for (_m,acts) in Arc::try_unwrap(boxed_bot.clone()).ok() .unwrap().into_inner().ok().unwrap().botmodules.botactions { + // for (_m,acts) in Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().botmodules.botactions { + // for (_m,acts) in Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().botmodules.botactions { + // let a = Arc::try_unwrap(boxed_bot).ok().unwrap().read().unwrap().botmodules.botactions + // let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap(); + // let b = a.read().unwrap(); + // for (_m,acts) in a.read().unwrap().botmodules.botactions { + // for (_m,acts) in b.rbotmodules().botactions { + // for (_m,acts) in b.rbotactions() { + // for (_m,acts) in (*Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().read().unwrap()).rbotactions() { + // let a = boxed_bot.clone().into_inner(); + let a = boxed_bot.lock().await; + //let a = a.lock().in + // for (_m,acts) in self.rbotactions() { + // for (_m,acts) in a.read().ok().unwrap().rbotactions() { + // for (_m,acts) in a.into_inner().ok().unwrap().rbotactions() { + for (_m,acts) in a.get_botactions() { + for a in acts { - match a { + + + let _act = match a { crate::core::botmodules::BotAction::C(c) => { /* @@ -340,13 +585,43 @@ impl BotInstance // [x] prefix + command let mut confirmed_bot_command = false; - if inpt == self.prefix.to_string() + c.command.as_str() { + + // if inpt == self.prefix.to_string() + c.command.as_str() { + // if inpt == Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().prefix.to_string() + c.command.as_str() { + // let a = Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().prefix.to_string(); + // let a = Arc::try_unwrap(boxed_bot.clone()).ok() .unwrap().into_inner().ok().unwrap().prefix.to_string(); + // let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().prefix.to_string(); + // let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().prefix.to_string(); + // let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap(); + // let a = (*Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().read().unwrap()); + // let a = (*Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().read().unwrap()).prefix.to_string(); + // let a = self.prefix.to_string(); + // let a = boxed_bot.clone(); + + // if inpt == a.into_inner().ok().unwrap().prefix.to_string() + c.command.as_str() { + // if inpt == a.into_inner().ok().unwrap().prefix.to_string() + c.command.as_str() + let a = boxed_bot.lock().await; + // + // if inpt == a.into_inner().prefix.to_string() + c.command.as_str() { + if inpt == a.get_prefix() + 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() { + // if inpt == self.prefix.to_string() + alias.as_str() { + // if inpt == Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().prefix.to_string() + alias.as_str() { + // + // if inpt == Arc::try_unwrap(boxed_bot.clone()).ok() .unwrap().into_inner().ok().unwrap().prefix.to_string() + alias.as_str() { + // Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner() + // if inpt == Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().prefix.to_string() + alias.as_str() { + // if inpt == Arc::try_unwrap(boxed_bot).ok().unwrap().read().unwrap().prefix.to_string() + alias.as_str() { + // if inpt == self.prefix.to_string() + alias.as_str() { + // let a = boxed_bot.clone(); + let a = boxed_bot.lock().await; + // if inpt == a.into_inner().ok().unwrap().prefix.to_string() + alias.as_str() { + // if inpt == a.into_inner().prefix.to_string() + alias.as_str() { + if inpt == a.get_prefix() + alias.as_str() { confirmed_bot_command = true; } } @@ -364,24 +639,80 @@ impl BotInstance // match self.botmgrs.identity.to_owned().can_user_run_PRVMSG(&msg, c.required_roles.clone()) { // match self.botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) { - match self.botmgrs.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + // match self.botmgrs.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + + // let botref = Rc::clone(&botmgr); + // if let Rc(botmgr) = botref { + // () + // } + + // match self.botmgrs.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + // match boxed_bot.clone().into_inner().botmgrs.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + // match Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + //let boxed_bot1 = Arc::clone(&boxed_bot); + //let a = boxed_bot1.into_inner().ok().unwrap(); + // match boxed_bot1.into_inner().ok().unwrap().botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + // match Arc::try_unwrap(boxed_bot.clone()) + // .ok() + // .unwrap().into_inner().ok().unwrap().botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + // let a = Arc::try_unwrap(boxed_bot.clone()).ok() .unwrap().into_inner(); + // let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap(); + // Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner() + // match a.botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + // match Arc::try_unwrap(boxed_bot).ok().unwrap().read().unwrap().botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + // match self.botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + // match (boxed_bot.clone().into_inner().ok().unwrap()).botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) { + // let a = boxed_bot.clone(); + // let a = boxed_bot.lock().await; + // // let a = a.read().ok().unwrap().botmgrs.identity; + // let a = a.get_identity(); + // // let a = a.lock().await.can_user_run_PRVMSG(&msg, c.required_roles.clone()) ; + + // match a.lock().await.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await { + + { + let le = boxed_bot.lock().await; + // let le = le.lock().await; + let le = le.get_identity().await; + let le = *le; + let le = le.lock().await; + let le = le.clone(); + let le = le.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await; + match le { // Ok(Permissible::Allow) => (), Permissible::Allow => { println!("Executed as permissible"); - c.execute(self.botmgrs.clone(), msg.clone()).await; + // c.execute(bot, msg.clone()).await; + // if let bot = Rc::>::clone(*bot) { + // c.execute(bot, msg.clone()).await; + // } + // let boxed_bot = Arc::new(RwLock::new(self)); + c.execute(boxed_bot.clone(), msg.clone()).await; + } - Permissible::Block => println!("User Not allowed to run command"), + Permissible::Block => { + println!("User Not allowed to run command") + }, // _ => (), - } + }; // c.execute(self.chat.clone(), msg.clone()).await; + } } }, - crate::core::botmodules::BotAction::L(l) => l.execute(self.botmgrs.clone(), msg.clone()).await, + crate::core::botmodules::BotAction::L(l) => { + // if let bot = Rc::clone(&bot) { + // l.into_inner().execute(bot, msg.clone()).await + // } + //let bot = Rc::clone(&bot).into_inner(); + // l.execute(boxed_bot.clone(), msg.clone()).await + // let boxed_bot = Arc::new(RwLock::new(self)); + l.execute(boxed_bot.clone(), msg.clone()).await; + }, _ => (), - } + }; } }; diff --git a/src/core/botmodules.rs b/src/core/botmodules.rs index ab52696..a05db7d 100644 --- a/src/core/botmodules.rs +++ b/src/core/botmodules.rs @@ -5,6 +5,18 @@ use std::collections::HashMap; use crate::core::identity; +use std::cell::RefCell; +use std::sync::{Arc, RwLock}; + +use std::future::Future; +use futures::lock::Mutex; + + + +use crate::core::botinstance::{self, BotInstance}; +use std::rc::Rc; + +use async_trait::async_trait; /* @@ -43,8 +55,6 @@ pub enum ChType { pub use ChType::Channel; use twitch_irc::message::PrivmsgMessage; -use crate::core::botinstance::{self, BotInstance}; - #[derive(Debug)] enum StatusLvl { @@ -57,7 +67,8 @@ pub enum ModStatusType { Enabled(StatusLvl), Disabled(StatusLvl), } - + +// #[derive(Clone)] pub enum BotAction { C(BotCommand), @@ -66,7 +77,8 @@ pub enum BotAction } impl BotAction { - pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ + // pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ + pub async fn execute(&self,m:Arc>,n:PrivmsgMessage){ match self { BotAction::L(a) => a.execute(m,n).await, @@ -77,13 +89,14 @@ impl BotAction { } } +#[async_trait] pub trait BotActionTrait { - fn add_to_bot(self, bot:BotInstance); - fn add_to_modmgr(self,modmgr:&mut ModulesManager); + 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 @@ -96,20 +109,26 @@ pub struct BotCommand { impl BotCommand { - pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ + // pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ + // pub async fn execute(&self,m:Rc<&botinstance::BotManagers>,n:PrivmsgMessage){ + pub async fn execute(&self,m:Arc>,n:PrivmsgMessage){ (self.exec_body)(m,n).await; } } - +#[async_trait] impl BotActionTrait for BotCommand { - fn add_to_bot(self, mut bot:BotInstance) { - let mgr = &mut bot.botmodules; - self.add_to_modmgr(mgr); + async fn add_to_bot(&self, mut bot:BotInstance) { + // let mgr = &mut bot.botmodules; + // let mut mgr = *mgr.lock().await; + // let mut mgr = &mut mgr; + self.add_to_modmgr(bot.botmodules); } - fn add_to_modmgr(self, modmgr:&mut ModulesManager) { + async fn add_to_modmgr(self, modmgr:Arc>) { + // modmgr.add_botaction(self.module.clone(), BotAction::C(self)) + let modmgr = *modmgr.lock().await; modmgr.add_botaction(self.module.clone(), BotAction::C(self)) } @@ -125,18 +144,53 @@ pub mod bot_actions { use std::boxed::Box; use std::pin::Pin; - use crate::core::botinstance::{BotManagers, Chat}; + use std::rc::Rc; + + use crate::core::botinstance::{BotInstance, BotManagers, Chat}; use twitch_irc::message::PrivmsgMessage; + use std::cell::RefCell; + use std::sync::{Arc, RwLock}; + use futures::lock::Mutex; + // pub type ExecBody = Box Pin + Send>> + Send + Sync>; //pub type ExecBody = Box Pin + Send>> + Send + Sync>; - pub type ExecBody = Box Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + + // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + + //pub fn asyncbox(f: fn(Chat,PrivmsgMessage) -> T) -> ExecBody // pub fn asyncbox(f: fn(Chat,PrivmsgMessage) -> T) -> ExecBody - pub fn asyncbox(f: fn(BotManagers,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(BotManagers,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Rc<&BotManagers>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Rc>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Rc>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Arc<&BotInstance>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Arc>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Rc>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Arc>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Arc,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Arc>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Arc>,PrivmsgMessage) -> T) -> ExecBody + pub fn asyncbox(f: fn(Arc>,PrivmsgMessage) -> T) -> ExecBody where - T: Future + Send + 'static, + //T: Future + Send + 'static + T: Future + Send + 'static { Box::new(move |a,b| Box::pin(f(a,b))) } @@ -157,21 +211,24 @@ pub struct Listener impl Listener { - pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ + pub async fn execute(&self,m:Arc>,n:PrivmsgMessage){ (self.exec_body)(m,n).await; } } +#[async_trait] impl BotActionTrait for Listener { - fn add_to_bot(self, mut bot:BotInstance) { - - let mgr = &mut bot.botmodules; + async fn add_to_bot(&self, mut bot:BotInstance) { + // let mgr = &mut bot.botmodules; + let mgr = bot.botmodules; self.add_to_modmgr(mgr); } - fn add_to_modmgr(self, modmgr:&mut ModulesManager) { + // fn add_to_modmgr(self, modmgr:&mut ModulesManager) { + async fn add_to_modmgr(self, modmgr:Arc>) { + let modmgr = *modmgr.lock().await; modmgr.add_botaction(self.module.clone(), BotAction::L(self)) } @@ -182,6 +239,8 @@ impl BotActionTrait for Listener #[derive(Debug)] struct Routine {} +// #[derive(Clone)] + pub struct ModulesManager { statusdb: HashMap>, @@ -191,7 +250,7 @@ pub struct ModulesManager impl ModulesManager { - pub fn init() -> ModulesManager + pub fn init() -> Arc> { @@ -203,19 +262,31 @@ impl ModulesManager botactions : act, }; - // initialize core modules - crate::core::identity::init(&mut mgr); + // :: [x] initialize core modules + // crate::core::identity::init(&mut mgr); + + let a = Arc::new(Mutex::new(mgr)); + // let a = a.clone(); + crate::core::identity::init(a.clone()); // initialize custom crate modules - crate::modules::init(&mut mgr); + // crate::modules::init(&mut mgr); + // let a = a.clone(); + crate::modules::init(a.clone()); println!(">> Modules Manager : End of Init"); - mgr + // mgr + a } + pub fn rbotactions(self) -> HashMap> { + self.botactions + } + + pub fn modstatus(&self, _:ModType, _:ChType) -> ModStatusType { // Example usage : botmanager.modstatus( // BotModule("GambaCore"), diff --git a/src/core/identity.rs b/src/core/identity.rs index a6c6337..224aa20 100644 --- a/src/core/identity.rs +++ b/src/core/identity.rs @@ -1,21 +1,32 @@ +use std::borrow::Borrow; use std::collections::HashMap; use std::error::Error; use crate::core::botmodules::{ModulesManager,Listener,BotModule,BotActionTrait, BotCommand}; use crate::core::botmodules::bot_actions::actions_util; -use crate::core::botinstance::{self}; +use crate::core::botinstance::{self,BotInstance}; +use futures::lock::Mutex; use twitch_irc::message::{Badge, PrivmsgMessage}; use crate::core::botmodules::ChType; +use crate::core::botinstance::ArcBox; + + +use std::rc::Rc; +use std::cell::RefCell; + +use std::sync::{Arc, RwLock}; + fn adminvector() -> Vec { vec![String::from("ModulatingForce")] } -pub fn init(mgr:&mut ModulesManager) +// pub fn init(mgr:&mut ModulesManager) +pub fn init(mgr:Arc>) { BotCommand { @@ -32,7 +43,8 @@ pub fn init(mgr:&mut ModulesManager) ], }.add_to_modmgr(mgr); - async fn cmd_promote(bot:botinstance::BotManagers,msg:PrivmsgMessage) { + async fn cmd_promote(mut bot:Arc>,msg:PrivmsgMessage) + { //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); println!("Called cmd promote"); @@ -63,6 +75,8 @@ pub fn init(mgr:&mut ModulesManager) */ + //let bot = Rcbot; + println!("{}",msg.message_text); let mut argv = msg.message_text.split(" "); @@ -84,21 +98,104 @@ pub fn init(mgr:&mut ModulesManager) match arg1 { - Some(a) if a == String::from("admin") => { + Some(a1) if a1 == String::from("admin") => { // - BotAdmins can promote admin to give BotAdmin UserRole - let a = bot.identity.getspecialuserroles(msg.sender.name.to_lowercase(), Some(ChType::Channel(msg.channel_login.to_lowercase()))); + //let mut bot = Rc::clone(&bot); + // let a = bot.botmgrs.identity.getspecialuserroles(msg.sender.name.to_lowercase(), Some(ChType::Channel(msg.channel_login.to_lowercase()))); + // let a = Rc::try_unwrap(bot).ok().unwrap().into_inner().botmgrs.identity.getspecialuserroles(msg.sender.name.to_lowercase(), Some(ChType::Channel(msg.channel_login.to_lowercase()))); + // let a = Rc::try_unwrap(bot.clone()).ok().unwrap().into_inner().botmgrs.identity.getspecialuserroles(msg.sender.name.to_lowercase(), Some(ChType::Channel(msg.channel_login.to_lowercase()))); + + // let a = Rc::try_unwrap(bot).ok().unwrap() + // // .borrow_mut() + // .into_inner() + // .botmgrs + // .identity + // .getspecialuserroles(msg.sender.name.to_lowercase(), + // Some(ChType::Channel(msg.channel_login.to_lowercase()))); + // let p = Rc::try_unwrap(bot.clone()) + // let p = Arc::try_unwrap(bot.clone()) + // .ok() + // .unwrap() + // //.into_inner() + // //.to_owned() + // // .get_mut() + // .into_inner(); + // // .ok() + // // .unwrap(); + // // let p = p.ok().unwrap(); + + // let p = bot.lock().await.get_identity(); + // let p = p.lock().await; + // let ta = p.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; + // // let ta = *ta.await; + // let ta = *ta.lock().await; + + // if let Some(a) = ta { + + + let p = bot.lock().await.get_identity(); + let mut p = p.lock().await; + let ta = p.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; + + if let Some(a) = ta { - if let Some(a) = a { if a.contains(&UserRole::BotAdmin) { println!("BotAdmin allowed to promote admin"); - match bot.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { - // Success(_) => { - // ; - // }, - ChangeResult::Success(a) => println!("Succesfully promoted : {a} ;"), - ChangeResult::Failed(a) => println!("Failed to promote : {a} ; "), - ChangeResult::NoChange(a) => println!("No Changes Made : {a} ; "), + // let bota = Rc::clone(&bot); + // let bota = Rc::get_mut(&bota); + // match bota.botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { + //let mut bot = Rc::clone(&bot); + // let bot = Rc::<&botinstance::BotInstance>::get_mut(&mut bot); + // let mut bot = Rc::make_mut(&mut bot); + // let mut bot = Rc::make_mut(&bot); + // match Rc::<&botinstance::BotInstance>::get_mut(bot) { + // Some(bot) => { + // match bot.botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { + // // Success(_) => { + // // ; + // // }, + // ChangeResult::Success(a) => println!("Succesfully promoted : {a} ;"), + // ChangeResult::Failed(a) => println!("Failed to promote : {a} ; "), + // ChangeResult::NoChange(a) => println!("No Changes Made : {a} ; "), + + // } + // }, + // None => (), + // } + //let bot = Rc::::make_mut(bot); + // match Rc::::make_mut(&mut Rc::new(bot.botmgrs.identity)).promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { + // match Rc::try_unwrap(bot.clone()).ok().unwrap().into_inner().botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { + // match Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner().ok().unwrap().botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { + // match Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner().botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { + // match bot.read().ok().unwrap().get_identity().promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { + // let a = bot.get_mut(); + // match a.get_identity().promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { + // let a = (*bot).clone(); + { + // let a = bot.lock().await.get_botmgrs().clone(); + // let a = bot.lock().await; + // let mut mutex = Arc::clone(&bot); + // match mutex.get_mut().get_identity().promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { + // slet ee = ArcBox(bot); + // println!("tester: {:?}",(*bot).lock().await.get_prefix()); + // let mutex = Arc::clone(&bot); + // let mut mutex2 = Arc::new(*mutex).into_inner().get_identity(); + // let mut mutex2 = Arc::clone(&mutex).into_inner().get_identity(); + // let a = (*bot).lock().await.get_identity(); + // let mut a = a.lock().await; + let p = bot.lock().await.get_identity(); + let mut p = p.lock().await; + let ta = p.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)).await; + match ta { + // Success(_) => { + // ; + // }, + ChangeResult::Success(a) => println!("Succesfully promoted : {a} ;"), + ChangeResult::Failed(a) => println!("Failed to promote : {a} ; "), + ChangeResult::NoChange(a) => println!("No Changes Made : {a} ; "), + + } } } } @@ -151,7 +248,7 @@ pub fn init(mgr:&mut ModulesManager) }.add_to_modmgr(mgr); - async fn cmd_demote(mut _chat:botinstance::BotManagers,_msg:PrivmsgMessage) { + async fn cmd_demote(mut _chat:Arc>,_msg:PrivmsgMessage) { println!("Called cmd demote"); } @@ -172,7 +269,7 @@ pub fn init(mgr:&mut ModulesManager) }.add_to_modmgr(mgr); - async fn getroles(bot:botinstance::BotManagers,msg:PrivmsgMessage) { + async fn getroles(bot:Arc>,msg:PrivmsgMessage) { println!("Called cmd getroles"); /* @@ -224,17 +321,57 @@ pub fn init(mgr:&mut ModulesManager) let targetchnl = arg2; - match targetchnl { + // // 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().await; + // let a = a.lock().await; + let sproles = match targetchnl { None => { - let a = bot.identity.getspecialuserroles(String::from(targetuser),None); - println!("Retrieved User Roles >> {:?}",a); + // 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); + a.lock().await.getspecialuserroles(String::from(targetuser),None).await }, Some(targetchnl) => { - let a = bot.identity.getspecialuserroles(String::from(targetuser), Some(ChType::Channel(String::from(targetchnl)))); - println!("Retrieved User Roles >> {:?}",a); - }, - } + // 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) + a.lock().await.getspecialuserroles(String::from(targetuser),None).await + }, + }; + + + println!("Retrieved User Roles >> {:?}",sproles); // let a = bot.identity.getuserroles(String::from("ModulatingForce"), Some(ChType::Channel(String::from("ModulatingForcebot")))); // println!("{:?}",a); @@ -271,7 +408,8 @@ pub enum Permissible { #[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 : 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 // parent_mgr : Box, //parent_mgr : Option>, } @@ -298,7 +436,7 @@ impl IdentityManager { }; IdentityManager { - special_roles_users : a, + special_roles_users : Arc::new(Mutex::new(a)), //parent_mgr : None, } } @@ -306,7 +444,8 @@ impl IdentityManager { // [ ] 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 fn can_user_run_PRVMSG(&self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible + pub async fn can_user_run_PRVMSG(self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible { // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); @@ -331,11 +470,28 @@ impl IdentityManager { // ChType::Channel(msg.channel_login.to_owned()), // sender_badge, // cmdreqroles - 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; + self.can_user_run(msg.sender.name.to_owned(), + ChType::Channel(msg.channel_login.to_owned()), + sender_badge, + cmdreqroles + ) ; } @@ -344,7 +500,7 @@ impl IdentityManager { Permissible::Block } - pub fn can_user_run(mut self, + pub async fn can_user_run(&self, usr:String, channelname:ChType, chat_badge:ChatBadge, @@ -424,7 +580,8 @@ impl IdentityManager { // 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()) { + // match self.special_roles_users.get(&usr.to_lowercase()) { + match self.special_roles_users.lock().await.get(&usr.to_lowercase()) { Some(usrroles) => { // println!("contains mod : {}", usrroles.contains(&UserRole::Mod(channelname.clone()))); // println!("contains supmod : {}", usrroles.contains(&UserRole::SupMod(channelname.clone()))); @@ -437,6 +594,7 @@ impl IdentityManager { // usrroles.push(UserRole::Mod(channelname.clone())); // a.push(UserRole::Mod(channelname.clone())); self.special_roles_users + .lock().await .get_mut(&usr.to_lowercase()) .expect("ERROR") .push(UserRole::Mod(channelname.clone())); @@ -463,7 +621,7 @@ impl IdentityManager { println!("Mod Role required"); - if let Some(a) = self.special_roles_users.get(&usr.to_lowercase()) { + if let Some(a) = self.special_roles_users.lock().await.get(&usr.to_lowercase()) { if a.contains(&UserRole::Mod(channelname.clone())) || a.contains(&UserRole::SupMod(channelname.clone())){ // return Ok(Permissible::Allow); return Permissible::Allow @@ -476,7 +634,7 @@ impl IdentityManager { if cmdreqroles.contains(&UserRole::SupMod(ChType::Channel(String::new()))) { - if let Some(a) = self.special_roles_users.get(&usr.to_lowercase()) { + if let Some(a) = self.special_roles_users.lock().await.get(&usr.to_lowercase()) { if a.contains(&UserRole::SupMod(channelname.clone())) { // return Ok(Permissible::Allow); return Permissible::Allow @@ -490,8 +648,8 @@ impl IdentityManager { println!("Eval cmdreqroles with botadmin : {}",cmdreqroles.contains(&UserRole::BotAdmin)); if cmdreqroles.contains(&UserRole::BotAdmin) { - println!("special roles get : {:?}",self.special_roles_users.get(&usr.to_lowercase())); - if let Some(a) = self.special_roles_users.get(&usr.to_lowercase()) { + println!("special roles get : {:?}",self.special_roles_users.lock().await.get(&usr.to_lowercase())); + if let Some(a) = self.special_roles_users.lock().await.get(&usr.to_lowercase()) { println!("special roles contains BotAdmin: {}",a.contains(&UserRole::BotAdmin)); if a.contains(&UserRole::BotAdmin) { // return Ok(Permissible::Allow); @@ -503,20 +661,31 @@ impl IdentityManager { Permissible::Block } - pub fn promote(mut self,trgchatter:String,channel:Option,trg_role:Option) -> ChangeResult { + pub async fn promote(&mut self,trgchatter:String,channel:Option,trg_role:Option) -> ChangeResult { // Note : If channel is none, getspecialuserroles() returns all roles for the user // let chatterroles = self.getspecialuserroles(trgchatter, channel); - let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()); + // let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()); + // let chatterroles = *self.getspecialuserroles(trgchatter.clone(), channel.clone()).await; + // let chatterroles = chatterroles.lock().await; + // // let chatterroles = *chatterroles; + // let chatterroles = chatterroles.unwrap(); - let emptyvec = vec![]; - let chatterroles = match chatterroles { - Some(a) => a, - _ => &(emptyvec), - }; + let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()).await; + // let chatterroles = chatterroles.lock().await; + // let chatterroles = *chatterroles; + let chatterroles = chatterroles.unwrap(); + + + // let emptyvec = vec![]; + + // let chatterroles = match chatterroles { + // Some(a) => a, + // _ => &(emptyvec), + // }; match trg_role { @@ -528,6 +697,7 @@ impl IdentityManager { // # otherwise, trg_role for the given chnl is not assigned to the trgchatter // chatterroles.push(UserRole::Mod(trg_chnl.clone())); self.special_roles_users + .lock().await .get_mut(&trgchatter) .expect("Error getting roles") .push(UserRole::Mod(trg_chnl)); @@ -615,7 +785,7 @@ impl IdentityManager { ChangeResult::Success(String::from("TEST > Promotion Successful")) } - pub fn getspecialuserroles(&self,chattername:String,channel:Option) -> Option<&Vec> { + pub async fn getspecialuserroles(&self,chattername:String,channel:Option) -> Option> { // let a = chattername.to_lowercase(); @@ -637,7 +807,21 @@ impl IdentityManager { // println!("{a}"); - self.special_roles_users.get(&a) + // let b = self.special_roles_users.lock().await.get(&a); + // match b + // { + // Some(b) => Some(*b), + // None => None, + // } + + let b = self.special_roles_users.lock().await.remove(&a); + let outp = b; + // let b = Arc::new(Mutex::new(outp)); + outp + + + // let b = Arc::new(Mutex::new(b)); + // b diff --git a/src/main.rs b/src/main.rs index cd71f0f..3ef7654 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,8 @@ pub mod core; pub mod modules; use std::process::Output; +use crate::core::botinstance::ArcBox; + use crate::core::botinstance::BotInstance; #[tokio::main] @@ -11,6 +13,8 @@ pub async fn main() { let bot = BotInstance::init(); - bot.runner().await; + bot.clone().runner().await; + + println!("ERROR : EXIT Game loop"); } \ No newline at end of file diff --git a/src/modules.rs b/src/modules.rs index 5fbaa8a..13e39ae 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -10,7 +10,8 @@ pub use crate::core::botmodules::ModulesManager; // use crate::core::botinstance; pub use crate::core::botinstance::BotInstance; - +use std::sync::Arc; +use futures::lock::Mutex; // [ ] Load submodules @@ -25,7 +26,8 @@ mod experiments; // // F: std::future::Future + Send, // // F : Send, // F : Send + ?Sized, -pub fn init(mgr:&mut ModulesManager) +// pub fn init(mgr:&mut ModulesManager) +pub fn init(mgr:Arc>) { // Modules initializer loads modules into the bot // this is achieved by calling submodules that also have fn init() defined diff --git a/src/modules/experiments.rs b/src/modules/experiments.rs index 0c3709b..828d9f2 100644 --- a/src/modules/experiments.rs +++ b/src/modules/experiments.rs @@ -17,7 +17,8 @@ use std::future::Future; use crate::core::botmodules::{ModulesManager,Listener,BotModule,BotActionTrait, BotCommand,ChType}; use crate::core::botmodules::bot_actions::actions_util; -use crate::core::botinstance::{self}; +use crate::core::botinstance::{self,BotInstance}; +use futures::lock::Mutex; use twitch_irc::message::PrivmsgMessage; use crate::core::identity; @@ -25,8 +26,13 @@ use crate::core::identity; use rand::Rng; +use std::rc::Rc; -pub fn init(mgr:&mut ModulesManager) +use std::sync::{Arc, RwLock}; + + +// pub fn init(mgr:&mut ModulesManager) +pub fn init(mgr:Arc>) { @@ -69,7 +75,7 @@ pub fn init(mgr:&mut ModulesManager) } -async fn good_girl(mut bot:botinstance::BotManagers,msg:PrivmsgMessage) +async fn good_girl(mut bot:Arc>,msg:PrivmsgMessage) { println!("In GoodGirl() Listener"); //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); @@ -82,6 +88,13 @@ async fn good_girl(mut bot:botinstance::BotManagers,msg:PrivmsgMessage) // let roll = rand::thread_rng().gen_range(1..=5); + // let mut bot = Rc::clone(&bot); + // let mut bot = Rc::get_mut(&mut bot); + // let bot = match bot { + // Some(bot) => bot, + // None => (), + // } + if msg.sender.name == "ModulatingForce" // && msg.message_text.contains("GoodGirl") @@ -92,17 +105,42 @@ async fn good_girl(mut bot:botinstance::BotManagers,msg:PrivmsgMessage) let rollwin = rand::thread_rng().gen_ratio(1,5); if rollwin { println!("In GoodGirl() > Win"); - bot.chat.say_in_reply_to(&msg,String::from("GoodGirl xdd ")).await; + // let bot = Rc::get_mut(&bot).expect("Error"); + // bot.botmgrs.chat.say_in_reply_to(&msg,String::from("GoodGirl xdd ")).await; + // Rc::::get_mut(mut bot) + // if let Some(bot) = Rc::<&botinstance::BotInstance>::get_mut(bot) { + + // match bot{ + // Some(bot) => { + // bot + // .botmgrs + // .chat + // .say_in_reply_to(&msg,String::from("GoodGirl xdd ")).await; + // } + // None => (), + // } + // Arc::try_unwrap(bot).ok().unwrap().botmgrs.chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; + let a = bot.clone(); + // let a = a.read().ok().unwrap(); + // let a = a.lock().await.get_botmgrs(); + // let a = a.lock().await.rChat(); + + let a = (*bot).lock().await.get_botmgrs(); + let a = a.lock().await.rChat(); + let mut a = (*a).lock().await; + + // a.rbotmgrs().chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; + // a.lock().await.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; + a.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; } - + + } - - - - + } -async fn testy(mut _chat:botinstance::BotManagers,_msg:PrivmsgMessage) + +async fn testy(mut _chat:Arc>,_msg:PrivmsgMessage) { println!("testy triggered!") From eedf90907ee420667e9629cfbc881fc23aa0009b Mon Sep 17 00:00:00 2001 From: ModulatingForce <116608425+modulatingforce@users.noreply.github.com> Date: Mon, 12 Feb 2024 01:25:12 -0500 Subject: [PATCH 2/5] 2024.02.12 - WORKS --- src/core/botinstance.rs | 292 +++++++++++++++++++++++++++++-------- src/core/botmodules.rs | 169 +++++++++++++++------ src/core/identity.rs | 67 ++++++--- src/main.rs | 5 +- src/modules.rs | 2 +- src/modules/experiments.rs | 30 ++-- 6 files changed, 422 insertions(+), 143 deletions(-) diff --git a/src/core/botinstance.rs b/src/core/botinstance.rs index 5f9561d..090b0d5 100644 --- a/src/core/botinstance.rs +++ b/src/core/botinstance.rs @@ -1,6 +1,7 @@ -use futures::lock::Mutex; +// 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; @@ -20,6 +21,9 @@ 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; @@ -31,7 +35,7 @@ use crate::core::identity::{IdentityManager,Permissible}; use std::rc::Rc; use std::cell::RefCell; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; // use futures::lock::Mutex; use std::pin::Pin; @@ -39,6 +43,9 @@ use std::pin::Pin; //use std::borrow::Borrow; use core::borrow::Borrow; +// pub type BotAR = Arc>; +use super::botmodules::bot_actions::actions_util::BotAR; + #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub enum ChType { @@ -48,11 +55,14 @@ pub enum ChType { pub use ChType::Channel; -pub enum ModType { - BotModule(String), -} -pub use ModType::BotModule; + +// pub enum ModType { +// BotModule(String), +// } + +// pub use ModType::BotModule; + #[derive(Clone)] pub struct Chat { @@ -163,7 +173,7 @@ impl Chat { #[derive(Clone)] pub struct BotManagers { // pub botmodules : ModulesManager, - pub identity : Arc>, + pub identity : Arc>, pub chat : Chat, } @@ -171,23 +181,27 @@ impl BotManagers { pub fn init(ratelimiters:HashMap, client:TwitchIRCClient, StaticLoginCredentials>) - -> Arc> { - let a = Arc::new(Mutex::new(BotManagers { + -> BotManagers { + // let a = Arc::new(Mutex::new(BotManagers { + // // botmodules : ModulesManager::init(), + // identity : Arc::new(Mutex::new(IdentityManager::init())), + // chat : Chat::init(ratelimiters,client), + // })); + // a + BotManagers { // botmodules : ModulesManager::init(), - identity : Arc::new(Mutex::new(IdentityManager::init())), + identity : Arc::new(RwLock::new(IdentityManager::init())), chat : Chat::init(ratelimiters,client), - })); - a - + } } - pub fn rIdentity(self) -> Arc> { + pub fn rIdentity(self) -> Arc> { self.identity } - pub fn rChat(&self) -> Arc> { - Arc::new(Mutex::new(self.chat)) - } + // pub fn rChat(&self) -> Arc> { + // Arc::new(Mutex::new(self.chat)) + // } } @@ -206,14 +220,16 @@ pub struct BotInstance { pub prefix : char, pub bot_channel : ChType, - pub incoming_messages : UnboundedReceiver, + // pub incoming_messages : UnboundedReceiver, + pub incoming_messages : Arc>>, // pub incoming_messages : RefCell>, // pub chat : Chat, - pub botmodules : Arc>, + pub botmodules : Arc, pub twitch_oauth : String, pub bot_channels : Vec, // pub identity : IdentityManager, - pub botmgrs : Arc>, + // pub botmgrs : Arc>, + pub botmgrs : BotManagers, } @@ -223,7 +239,8 @@ impl BotInstance // pub fn init() -> BotInstance - pub fn init() -> Arc + // pub fn init() -> Arc + pub fn init() -> BotInstance { dotenv().ok(); @@ -272,7 +289,7 @@ impl BotInstance let b = BotInstance { prefix : prefix, bot_channel : Channel(login_name) , - incoming_messages : incoming_messages, + incoming_messages : Arc::new(RwLock::new(incoming_messages)), //client : client, // chat : Chat { // ratelimiters : ratelimiters, @@ -289,7 +306,9 @@ impl BotInstance //println!("{:?}",b.botmgrs.chat.ratelimiters); - Arc::new(b) + // Arc::new(b) + //Arc::new(RwLock::new(b)) + b } // async fn rcv_helper(self) -> Option { @@ -299,10 +318,14 @@ impl BotInstance // } // pub async fn runner(mut self) -> () { - pub async fn runner(mut self) -> () { + // pub async fn runner(&'static mut self) -> () { + pub async fn runner(self) -> () { + // let bot_am = Arc::new(Mutex::new(self)); // let mut boxed_bot = Arc::new(RefCell::new(self)); // <-- [ERROR] Future cannot be handled safely + + let bot = Arc::new(RwLock::new(self)); let join_handle = tokio::spawn(async move { @@ -313,7 +336,7 @@ impl BotInstance // let mut bot = Rc::new(RefCell::new(&self)); //let bot = Arc::new(Mutex::new(&self)); // let mut boxed_bot = Arc::new(RefCell::new(self)); - let mut boxed_bot = Arc::new(Mutex::new(self)); + // let mut boxed_bot = Arc::new(Mutex::new(self)); // while let Some(message) = bot.borrow_mut().incoming_messages.recv().await { @@ -385,8 +408,16 @@ impl BotInstance // while let Some(message) = a.incoming_messages.recv().await { // let a = Arc::clone(&boxed_bot).into_inner(); // while let Some(message) = a.incoming_messages.recv().await { - let tempbot = boxed_bot.clone(); - while let Some(message) = Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().incoming_messages.recv().await { + // let tempbot = boxed_bot.clone(); + // while let Some(message) = Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().incoming_messages.recv().await { + + // let tempbot = Arc::clone(&boxed_bot); + + // while let Some(message) = tempbot.lock().await.incoming_messages.recv().await { + let a = bot.read().await; + let mut a = a.incoming_messages.write().await; + while let Some(message) = a.recv().await { + // while let Some(message) = tempbot.into_inner().incoming_messages.recv().await { //while let Some(message) = boxed_bot.borrow().incoming_messages.recv().await { // // Below can be used to debug if I want to capture all messages @@ -436,8 +467,28 @@ impl BotInstance // (*a).listener_main_prvmsg(&msg).await; // let a:Arc> = Arc::clone(&boxed_bot); // a.into_inner().listener_main_prvmsg(&msg).await; - let tempbot = boxed_bot.clone(); - Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().listener_main_prvmsg(&msg).await ; + // let tempbot = boxed_bot.clone(); + // Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().listener_main_prvmsg(&msg).await ; + + // let tempbot = Arc::clone(&tempbot); + // // let a = tempbot.lock().await; + // tempbot.lock().await.listener_main_prvmsg(&msg).await; + // self.listener_main_prvmsg(&msg).await; + // bot.read().await.listener_main_prvmsg(&msg).await; + + // let a = bot.read().await; + // a.listener_main_prvmsg(&msg).await; + // a.listener_main_prvmsg(&msg).await; + // let a = bot.read().await; + BotInstance::listener_main_prvmsg(Arc::clone(&bot), &msg).await; + // let a = bot.read().await; + // a.lis + + + + + + //self.listener_main_prvmsg(&msg).await; // - BotCommand listener should likely need to be called within the above @@ -468,18 +519,32 @@ impl BotInstance - pub fn get_botmodules(self) -> Arc> { + pub fn get_botmodules(self) -> Arc { // let a = self.botmodules; // Arc::clone(&Arc::new(Mutex::new(self.botmodules))) + // *self.botmodules self.botmodules } - pub fn get_botactions(&self) -> &HashMap> { - self.get_botactions() - } + // pub fn get_botactions(self:&Self) -> (Self,HashMap>) { + // // self.get_botactions() + // // (*self,(*self).botmodules.rbotactions()) + // (Self { bot_channel},(*self).botmodules.rbotactions()) + // } - pub async fn get_botmgrs(self) -> Arc> { + // pub fn get_botactions(&self) -> (Self,HashMap>) { + // pub fn get_botactions(&self) -> HashMap> { + // // self.get_botactions() + // // (*self,(*self).botmodules.rbotactions()) + // // (self,self.botmodules.rbotactions()) + // // (*self).botmodules.rbotactions() + // // let a = (*self).botmodules.rbotactions(); + // let a = + // a + // } + + pub async fn get_botmgrs(self) -> BotManagers { // Arc::new(self.botmgrs) // Arc::clone(&Arc::new(Mutex::new(self.botmgrs))) let a = self.botmgrs; @@ -488,29 +553,75 @@ impl BotInstance a } - pub async fn get_identity(self) -> Arc> { - // let a = self.botmgrs; - // Arc::clone(&Arc::new(Mutex::new(a.rIdentity()))) - // let a = self.botmgrs; - // Arc::clone(&Arc::new(Mutex::new(a.rIdentity()))) - let a = self.get_botmgrs().await; - let a = a.lock().await; - // let a = a.rIdentity(); - let a = a.clone().identity; - a.clone() + // pub fn get_identity(self:&Self) -> (Self,IdentityManager) { + pub fn get_identity(&self) -> Arc> { + // // let a = self.botmgrs; + // // Arc::clone(&Arc::new(Mutex::new(a.rIdentity()))) + // // let a = self.botmgrs; + // // Arc::clone(&Arc::new(Mutex::new(a.rIdentity()))) + // let a = self.get_botmgrs().await; + // let a = a.lock().await; + // // let a = a.rIdentity(); + // let a = a.clone().identity; + // a.clone() + // let id = (*self).botmgrs.identity; + // id + Arc::clone(&self.botmgrs.identity) } - pub fn get_prefix(&self) -> String { - self.prefix.to_string() + + // pub fn get_prefix(self) -> (Self,char) { + pub fn get_prefix(&self) -> char { + // self.prefix.to_string() + // let a = self.prefix; + // a.clone().to_string() + // (self,self.prefix) + + (*self).prefix } + // pub fn get_prefix(self:&Self) -> (Self,String) { + // (*self,(*self).prefix.to_string()) + // } + // pub fn get_prefix(self:Self) -> (Self,String) { + // let str1 = self.prefix.to_string(); + // (self,str1) + // } + + // pub fn get_prefix(&self) -> String { + // // self.prefix.to_string() + // let a = self.prefix; + // a.clone().to_string() + // } + + // pub fn get_prefix(self) -> (Self,String) { + // // self.prefix.to_string() + // // let a = self.prefix; + // // a.clone().to_string() + // (Self { + // prefix : self.prefix , + // bot_channel : self.bot_channel , + // incoming_messages : self.incoming_messages , + // botmodules : self.botmodules, + // twitch_oauth : self.twitch_oauth, + // bot_channels : self.bot_channels , + // // identity : IdentityManager::init(), + // botmgrs: self.botmgrs , + // }, + // self.prefix.to_string()) + // } + // ----------------- // PRIVATE FUNCTIONS // async fn listener_main_prvmsg(&mut self,msg:PrivmsgMessage) -> () { - async fn listener_main_prvmsg(self,msg:&PrivmsgMessage) -> () { + // async fn listener_main_prvmsg(&mut self,msg:&PrivmsgMessage) -> () { + // async fn listener_main_prvmsg(self,msg:&PrivmsgMessage) -> () { + // async fn listener_main_prvmsg(self:Arc,msg:&PrivmsgMessage) -> () { + pub async fn listener_main_prvmsg(bot:BotAR,msg:&PrivmsgMessage) -> () { + // 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) @@ -526,7 +637,8 @@ impl BotInstance // let mut boxed_bot = Arc::new(RwLock::new(self)); // let boxed_bot = Arc::new(RwLock::new(self)); // let boxed_bot = Arc::new(Mutex::new(self)); - let boxed_bot = Arc::new(Mutex::new(self)); + //let boxed_bot = Arc::new(Mutex::new(self)); + // let bot = Arc::new(RwLock::new(self)); // for (_m,acts) in &self.botmodules.botactions { @@ -547,12 +659,27 @@ impl BotInstance // for (_m,acts) in b.rbotactions() { // for (_m,acts) in (*Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().read().unwrap()).rbotactions() { // let a = boxed_bot.clone().into_inner(); - let a = boxed_bot.lock().await; + // let a = boxed_bot.lock().await; //let a = a.lock().in // for (_m,acts) in self.rbotactions() { // for (_m,acts) in a.read().ok().unwrap().rbotactions() { // for (_m,acts) in a.into_inner().ok().unwrap().rbotactions() { - for (_m,acts) in a.get_botactions() { + + // let bot = self; + // let mut instr:char; + + // let hacts = self.get_botactions(); + // let hacts = boxed_bot.clone().lock().await.get_botactions(); + // let hacts = bot.read().await.get_botactions(); + let botlock = bot.read().await; + let hacts = botlock.botmodules.botactions.read().await; + // let hacts = hacts + for (_m,acts) in &(*hacts) { + + + + + // let bot = bot; for a in acts { @@ -600,10 +727,16 @@ impl BotInstance // if inpt == a.into_inner().ok().unwrap().prefix.to_string() + c.command.as_str() { // if inpt == a.into_inner().ok().unwrap().prefix.to_string() + c.command.as_str() - let a = boxed_bot.lock().await; + // let a = boxed_bot.lock().await; // // if inpt == a.into_inner().prefix.to_string() + c.command.as_str() { - if inpt == a.get_prefix() + c.command.as_str() { + // if inpt == a.get_prefix() + c.command.as_str() { + // if inpt == self.get_prefix() + c.command.as_str() { + // let instr = self.get_prefix(); + // let instr = boxed_bot.clone().lock().await.get_prefix(); + // let instr = bot.read().await.get_prefix(); + let instr = bot.read().await.get_prefix(); + if inpt == String::from(instr) + c.command.as_str() { confirmed_bot_command = true; } @@ -618,10 +751,16 @@ impl BotInstance // if inpt == Arc::try_unwrap(boxed_bot).ok().unwrap().read().unwrap().prefix.to_string() + alias.as_str() { // if inpt == self.prefix.to_string() + alias.as_str() { // let a = boxed_bot.clone(); - let a = boxed_bot.lock().await; + // let a = boxed_bot.lock().await; // if inpt == a.into_inner().ok().unwrap().prefix.to_string() + alias.as_str() { // if inpt == a.into_inner().prefix.to_string() + alias.as_str() { - if inpt == a.get_prefix() + alias.as_str() { + // if inpt == a.get_prefix() + alias.as_str() { + // if inpt == self.get_prefix() + alias.as_str() { + // let instr = self.get_prefix(); + // let instr = boxed_bot.clone().lock().await.get_prefix(); + // let instr = bot.read().await.get_prefix(); + let instr = bot.read().await.get_prefix(); + if inpt == String::from(instr) + alias.as_str() { confirmed_bot_command = true; } } @@ -671,14 +810,27 @@ impl BotInstance // match a.lock().await.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await { { - let le = boxed_bot.lock().await; + // let le = boxed_bot.lock().await; + // // let le = le.lock().await; + // let le = le.get_identity().await; + // let le = *le; // let le = le.lock().await; - let le = le.get_identity().await; - let le = *le; - let le = le.lock().await; - let le = le.clone(); - let le = le.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await; - match le { + // let le = le.clone(); + // let le = le.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await; + // let le = self.get_identity().await.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await; + // let le = self.botmgrs; + // let le = le.identity; + // let (bot,id) = self.get_identity(); + // let id = boxed_bot.clone().lock().await.get_identity(); + // let id = bot.read().await.get_identity(); + // let id = Arc::clone(&self.botmgrs.identity); + // let id = id.write().await; + // let id = &(*self.get_identity()); + let botlock = bot.read().await; + let id = botlock.get_identity(); + let id = id.read().await; + let eval= id.can_user_run_PRVMSG(&msg, c.required_roles.clone()); + match eval { // Ok(Permissible::Allow) => (), Permissible::Allow => { println!("Executed as permissible"); @@ -687,7 +839,15 @@ impl BotInstance // c.execute(bot, msg.clone()).await; // } // let boxed_bot = Arc::new(RwLock::new(self)); - c.execute(boxed_bot.clone(), msg.clone()).await; + // c.execute(boxed_bot.clone(), msg.clone()).await; + // c.execute(self, msg.clone()).await; + //let mut a = *self; + // c.execute(self, msg.clone()); + // let a = self; + // let a = Arc::clone(&self); + let a = Arc::clone(&bot); + // let a = Arc::clone(&bot); + c.execute(a, msg.clone()); } Permissible::Block => { @@ -708,7 +868,10 @@ impl BotInstance //let bot = Rc::clone(&bot).into_inner(); // l.execute(boxed_bot.clone(), msg.clone()).await // let boxed_bot = Arc::new(RwLock::new(self)); - l.execute(boxed_bot.clone(), msg.clone()).await; + // l.execute(boxed_bot.clone(), msg.clone()).await; + // let a = Arc::clone(&self); + let a = Arc::clone(&bot); + l.execute(a, msg.clone()); }, _ => (), @@ -720,6 +883,9 @@ impl BotInstance println!("End of Separate Listener Main prvmsg"); + // self + // bot + } diff --git a/src/core/botmodules.rs b/src/core/botmodules.rs index a05db7d..38f1fc6 100644 --- a/src/core/botmodules.rs +++ b/src/core/botmodules.rs @@ -6,16 +6,24 @@ use std::collections::HashMap; use crate::core::identity; use std::cell::RefCell; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use tokio::sync::RwLock; use std::future::Future; -use futures::lock::Mutex; +// 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, BotInstance}; use std::rc::Rc; +// use tokio::sync::RwLock; + + + use async_trait::async_trait; /* @@ -55,6 +63,9 @@ pub enum ChType { pub use ChType::Channel; use twitch_irc::message::PrivmsgMessage; +use self::bot_actions::actions_util; +use self::bot_actions::actions_util::BotAR; + #[derive(Debug)] enum StatusLvl { @@ -78,11 +89,12 @@ pub enum BotAction impl BotAction { // pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ - pub async fn execute(&self,m:Arc>,n:PrivmsgMessage){ + pub 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), + BotAction::C(a) => a.execute(m,n), _ => (), } @@ -92,8 +104,9 @@ impl BotAction { #[async_trait] pub trait BotActionTrait { - async fn add_to_bot(&self, bot:BotInstance); - async fn add_to_modmgr(self,modmgr:Arc>); + async fn add_to_bot(self, bot:BotInstance); + // async fn add_to_modmgr(self,modmgr:&'static ModulesManager); + async fn add_to_modmgr(self,modmgr:Arc); } // #[derive(Clone)] @@ -111,25 +124,38 @@ impl BotCommand { // pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ // pub async fn execute(&self,m:Rc<&botinstance::BotManagers>,n:PrivmsgMessage){ - pub async fn execute(&self,m:Arc>,n:PrivmsgMessage){ - (self.exec_body)(m,n).await; + // pub async fn execute(&self,m:BotInstance,n:PrivmsgMessage){ + // (self.exec_body)(m,n).await; + // } + // pub fn execute(&self,m:&mut BotInstance,n:PrivmsgMessage) -> () { + // pub fn execute(&self,m:actions_util::BotAR,n:PrivmsgMessage) -> () { + pub fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () { + // ((*self).exec_body)(m,n); + // ((*self).exec_body)(*m,n); + // m + // ((*self).exec_body)( + ((*self).exec_body)(m,n); + // m } } #[async_trait] impl BotActionTrait for BotCommand { - async fn add_to_bot(&self, mut bot:BotInstance) { + async fn add_to_bot(self, bot:BotInstance) { // let mgr = &mut bot.botmodules; // let mut mgr = *mgr.lock().await; // let mut mgr = &mut mgr; + // (*self).add_to_modmgr(bot.botmodules); self.add_to_modmgr(bot.botmodules); } - async fn add_to_modmgr(self, modmgr:Arc>) { + // 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)) - let modmgr = *modmgr.lock().await; - modmgr.add_botaction(self.module.clone(), BotAction::C(self)) + // let modmgr = *modmgr.lock().await; + // modmgr.add_botaction(self.module.clone(), BotAction::C(self)) + modmgr.add_botaction(self.module.clone(), BotAction::C(self)).await } } @@ -149,8 +175,13 @@ pub mod bot_actions { use crate::core::botinstance::{BotInstance, BotManagers, Chat}; use twitch_irc::message::PrivmsgMessage; use std::cell::RefCell; - use std::sync::{Arc, RwLock}; - use futures::lock::Mutex; + use std::sync::{Arc}; + // 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 Pin + Send>> + Send + Sync>; @@ -170,8 +201,14 @@ pub mod bot_actions { // pub type ExecBody = Box,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; - pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; - + // pub type ExecBody = Box>,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box Pin + Send>> + Send + Sync>; + pub type ExecBody = Box Pin + Send>> + Send + Sync>; + // pub type ExecBody = Box,PrivmsgMessage) -> Pin + Send>> + Send + Sync>; + //pub fn asyncbox(f: fn(Chat,PrivmsgMessage) -> T) -> ExecBody @@ -187,9 +224,14 @@ pub mod bot_actions { // pub fn asyncbox(f: fn(Arc,PrivmsgMessage) -> T) -> ExecBody // pub fn asyncbox(f: fn(Arc>,PrivmsgMessage) -> T) -> ExecBody // pub fn asyncbox(f: fn(Arc>,PrivmsgMessage) -> T) -> ExecBody - pub fn asyncbox(f: fn(Arc>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(Arc>,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(BotInstance,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(&'static BotInstance,PrivmsgMessage) -> T) -> ExecBody + // pub fn asyncbox(f: fn(&mut BotInstance,PrivmsgMessage) -> T) -> ExecBody + pub fn asyncbox(f: fn(BotAR,PrivmsgMessage) -> T) -> ExecBody where //T: Future + Send + 'static + // T: Future + Send + 'static T: Future + Send + 'static { Box::new(move |a,b| Box::pin(f(a,b))) @@ -211,25 +253,41 @@ pub struct Listener impl Listener { - pub async fn execute(&self,m:Arc>,n:PrivmsgMessage){ - (self.exec_body)(m,n).await; + // pub async fn execute(&self,m:BotInstance,n:PrivmsgMessage){ + // (self.exec_body)(m,n).await; + // } + // pub fn execute(&self,m:BotInstance,n:PrivmsgMessage){ + // (self.exec_body)(m,n); + // } + // pub fn execute(&self,m:&BotInstance,n:PrivmsgMessage) -> &BotInstance { + // pub fn execute(&self,m:actions_util::BotAR,n:PrivmsgMessage) -> () { + pub fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () { + // let mut m = Arc::*m; + ((*self).exec_body)(m,n); + // *self + // &m } } #[async_trait] impl BotActionTrait for Listener { - async fn add_to_bot(&self, mut bot:BotInstance) { + async fn add_to_bot(self, bot:BotInstance) { // let mgr = &mut bot.botmodules; - let mgr = bot.botmodules; - self.add_to_modmgr(mgr); + // let mgr = bot.botmodules; + // self.add_to_modmgr(Arc::new(*mgr)); + self.add_to_modmgr(bot.botmodules); } // fn add_to_modmgr(self, modmgr:&mut ModulesManager) { - async fn add_to_modmgr(self, modmgr:Arc>) { - let modmgr = *modmgr.lock().await; - modmgr.add_botaction(self.module.clone(), BotAction::L(self)) + // async fn add_to_modmgr(self, modmgr:Arc>) { + // async fn add_to_modmgr(self, modmgr:&'static ModulesManager) { + // async fn add_to_modmgr(self, modmgr:&'static ModulesManager) { + async fn add_to_modmgr(self, modmgr:Arc) { + // let modmgr = *modmgr.lock().await; + modmgr.add_botaction(self.module.clone(), BotAction::L(self)).await; + // modmgr.add_botaction(self.module.clone(), BotAction:L(self)) } } @@ -243,14 +301,17 @@ struct Routine {} pub struct ModulesManager { - statusdb: HashMap>, - pub botactions: HashMap>, + // statusdb: HashMap>, + statusdb: Arc>>>, + // pub botactions: HashMap>, + pub botactions: Arc>>>, } impl ModulesManager { - pub fn init() -> Arc> + // pub fn init() -> Arc> + pub fn init() -> Arc { @@ -258,33 +319,40 @@ impl ModulesManager 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 // crate::core::identity::init(&mut mgr); - let a = Arc::new(Mutex::new(mgr)); - // let a = a.clone(); - crate::core::identity::init(a.clone()); + // let a = Arc::new(Mutex::new(mgr)); + // // let a = a.clone(); + // crate::core::identity::init(a.clone()); + + // crate::core::identity::init(&mgr); + let mgra = Arc::new(mgr); + crate::core::identity::init(Arc::clone(&mgra)); // initialize custom crate modules // crate::modules::init(&mut mgr); // let a = a.clone(); - crate::modules::init(a.clone()); + // crate::modules::init(a.clone()); + crate::modules::init(Arc::clone(&mgra)); println!(">> Modules Manager : End of Init"); // mgr - a + mgra } - pub fn rbotactions(self) -> HashMap> { - self.botactions - } + // pub async fn rbotactions(&self) -> HashMap> { + // // (*self).botactions + // let a = self.botactions.read().await; + // *a + // } pub fn modstatus(&self, _:ModType, _:ChType) -> ModStatusType { @@ -314,7 +382,7 @@ impl 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 ) -> 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 ) { /* adds a BotAction to the Modules Manager - This will require a BotModule passed as well This will including the logic of a valid add @@ -342,7 +410,7 @@ impl ModulesManager // - 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"))) @@ -360,7 +428,8 @@ impl ModulesManager // let n = & mgr.botactions; - let d = &mgr.botactions; + let d = mgr.botactions.read().await; + let d = &(*d); for (module,moduleactions) in d { @@ -431,20 +500,30 @@ impl ModulesManager // // () // 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 ), None => (), } - let statusvector = self.statusdb + // { + // let mut lala = self; + // let statusvector = (*lala).statusdb + // // .entry(BotModule(String::from("experiments"))) + // .entry(in_module.clone()) + // .or_insert(Vec::new()); + // } + + 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()) .or_insert(Vec::new()); diff --git a/src/core/identity.rs b/src/core/identity.rs index 224aa20..7026835 100644 --- a/src/core/identity.rs +++ b/src/core/identity.rs @@ -20,15 +20,20 @@ use std::cell::RefCell; use std::sync::{Arc, RwLock}; +use super::botmodules::bot_actions::actions_util::BotAR; + + fn adminvector() -> Vec { vec![String::from("ModulatingForce")] } // pub fn init(mgr:&mut ModulesManager) -pub fn init(mgr:Arc>) +pub fn init(mgr:Arc) { + let a = actions_util::asyncbox(cmd_promote) ; + BotCommand { module : BotModule(String::from("identity")), command : String::from("promote"), // command call name @@ -41,9 +46,11 @@ pub fn init(mgr:Arc>) UserRole::Broadcaster, UserRole::BotAdmin, ], - }.add_to_modmgr(mgr); + }.add_to_modmgr(Arc::clone(&mgr)); - async fn cmd_promote(mut bot:Arc>,msg:PrivmsgMessage) + // async fn cmd_promote(mut bot:Arc>,msg:PrivmsgMessage) + // async fn cmd_promote(mut bot:&BotInstance,msg:PrivmsgMessage) -> &BotInstance + async fn cmd_promote(bot:BotAR,msg:PrivmsgMessage) -> () { //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); println!("Called cmd promote"); @@ -133,9 +140,11 @@ pub fn init(mgr:Arc>) // if let Some(a) = ta { - let p = bot.lock().await.get_identity(); - let mut p = p.lock().await; - let ta = p.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; + // let p = bot.lock().await.get_identity(); + // let mut p = p.lock().await; + // let ta = p.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; + let botlock = bot.read().await; + let ta = botlock.get_identity().read().await.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; if let Some(a) = ta { @@ -183,9 +192,13 @@ pub fn init(mgr:Arc>) // let mut mutex2 = Arc::clone(&mutex).into_inner().get_identity(); // let a = (*bot).lock().await.get_identity(); // let mut a = a.lock().await; - let p = bot.lock().await.get_identity(); - let mut p = p.lock().await; - let ta = p.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)).await; + // let p = bot.lock().await.get_identity(); + // let mut p = p.lock().await; + // let ta = p.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)).await; + let botlock = Arc::clone(&bot.read().await.get_identity()); + let idlock = botlock.write().await; + // let mut idlock = *idlock; + let ta = idlock.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)).await; match ta { // Success(_) => { @@ -227,7 +240,7 @@ pub fn init(mgr:Arc>) - + // bot @@ -245,10 +258,11 @@ pub fn init(mgr:Arc>) UserRole::Broadcaster, UserRole::BotAdmin, ], - }.add_to_modmgr(mgr); + }.add_to_modmgr(Arc::clone(&mgr)); - async fn cmd_demote(mut _chat:Arc>,_msg:PrivmsgMessage) { + // async fn cmd_demote(mut _chat:Arc>,_msg:PrivmsgMessage) { + async fn cmd_demote(mut _chat:BotAR,_msg:PrivmsgMessage) { println!("Called cmd demote"); } @@ -266,10 +280,11 @@ pub fn init(mgr:Arc>) UserRole::Broadcaster, UserRole::BotAdmin, ], - }.add_to_modmgr(mgr); + }.add_to_modmgr(Arc::clone(&mgr)); - async fn getroles(bot:Arc>,msg:PrivmsgMessage) { + // async fn getroles(bot:Arc>,msg:PrivmsgMessage) { + async fn getroles(bot:BotAR,msg:PrivmsgMessage) { println!("Called cmd getroles"); /* @@ -337,10 +352,14 @@ pub fn init(mgr:Arc>) // 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().await; + // 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; + let idlock = botlock.get_identity(); + let idlock = idlock.read().await; let sproles = match targetchnl { None => { // let bot = Rc::clone(&bot); @@ -352,7 +371,8 @@ pub fn init(mgr:Arc>) // 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); - a.lock().await.getspecialuserroles(String::from(targetuser),None).await + // let a = idlock.read().await; + idlock.getspecialuserroles(String::from(targetuser),None).await }, Some(targetchnl) => { // let bot = Rc::clone(&bot); @@ -365,7 +385,8 @@ pub fn init(mgr:Arc>) // 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) - a.lock().await.getspecialuserroles(String::from(targetuser),None).await + // let a = a.read().await; + idlock.getspecialuserroles(String::from(targetuser),None).await }, }; @@ -445,7 +466,8 @@ impl IdentityManager { // 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(self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible + pub fn can_user_run_PRVMSG(&self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible { // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); @@ -497,9 +519,11 @@ impl IdentityManager { // [ ] Call can_user_run() + // (self,Permissible::Block) Permissible::Block } + pub async fn can_user_run(&self, usr:String, channelname:ChType, @@ -661,7 +685,8 @@ impl IdentityManager { Permissible::Block } - pub async fn promote(&mut self,trgchatter:String,channel:Option,trg_role:Option) -> ChangeResult { + // pub async fn promote(&mut self,trgchatter:String,channel:Option,trg_role:Option) -> ChangeResult { + pub async fn promote(&self,trgchatter:String,channel:Option,trg_role:Option) -> ChangeResult { // Note : If channel is none, getspecialuserroles() returns all roles for the user diff --git a/src/main.rs b/src/main.rs index 3ef7654..4278813 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,13 +7,16 @@ use std::process::Output; use crate::core::botinstance::ArcBox; use crate::core::botinstance::BotInstance; +use tokio::sync::RwLock; +use std::sync::Arc; +pub type BotAR = Arc>; #[tokio::main] pub async fn main() { let bot = BotInstance::init(); - bot.clone().runner().await; + bot.runner().await; println!("ERROR : EXIT Game loop"); diff --git a/src/modules.rs b/src/modules.rs index 13e39ae..5d533c6 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -27,7 +27,7 @@ mod experiments; // // F : Send, // F : Send + ?Sized, // pub fn init(mgr:&mut ModulesManager) -pub fn init(mgr:Arc>) +pub fn init(mgr:Arc) { // Modules initializer loads modules into the bot // this is achieved by calling submodules that also have fn init() defined diff --git a/src/modules/experiments.rs b/src/modules/experiments.rs index 828d9f2..6548320 100644 --- a/src/modules/experiments.rs +++ b/src/modules/experiments.rs @@ -15,7 +15,7 @@ use std::future::Future; use crate::core::botmodules::{ModulesManager,Listener,BotModule,BotActionTrait, BotCommand,ChType}; -use crate::core::botmodules::bot_actions::actions_util; +use crate::core::botmodules::bot_actions::actions_util::{self, BotAR}; use crate::core::botinstance::{self,BotInstance}; use futures::lock::Mutex; @@ -32,7 +32,7 @@ use std::sync::{Arc, RwLock}; // pub fn init(mgr:&mut ModulesManager) -pub fn init(mgr:Arc>) +pub fn init(mgr:Arc) { @@ -49,7 +49,7 @@ pub fn init(mgr:Arc>) // }.add_to_modmgr(mgr); - BotCommand { + 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 @@ -58,7 +58,9 @@ pub fn init(mgr:Arc>) required_roles : vec![ identity::UserRole::BotAdmin ], - }.add_to_modmgr(mgr); + }; + + botc1.add_to_modmgr(Arc::clone(&mgr)); @@ -69,13 +71,13 @@ pub fn init(mgr:Arc>) help : String::from("") }; - list1.add_to_modmgr(mgr); + list1.add_to_modmgr(Arc::clone(&mgr)); } -async fn good_girl(mut bot:Arc>,msg:PrivmsgMessage) +async fn good_girl(mut bot:BotAR,msg:PrivmsgMessage) { println!("In GoodGirl() Listener"); //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); @@ -120,18 +122,22 @@ async fn good_girl(mut bot:Arc>,msg:PrivmsgMessage) // None => (), // } // Arc::try_unwrap(bot).ok().unwrap().botmgrs.chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; - let a = bot.clone(); + // let a = bot.clone(); + let a = Arc::clone(&bot); // let a = a.read().ok().unwrap(); // let a = a.lock().await.get_botmgrs(); // let a = a.lock().await.rChat(); - let a = (*bot).lock().await.get_botmgrs(); - let a = a.lock().await.rChat(); - let mut a = (*a).lock().await; + // let a = (*bot).lock().await.get_botmgrs(); + // let a = a.lock().await.rChat(); + // let mut a = (*a).lock().await; + // let a = a.botmgrs.chat.say_in_reply_to(&msg, outmsg) // a.rbotmgrs().chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; // a.lock().await.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; - a.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; + // a.botmgrs.chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; + let botlock = a.read().await; + botlock.botmgrs.chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; } @@ -140,7 +146,7 @@ async fn good_girl(mut bot:Arc>,msg:PrivmsgMessage) } -async fn testy(mut _chat:Arc>,_msg:PrivmsgMessage) +async fn testy(mut _chat:BotAR,_msg:PrivmsgMessage) { println!("testy triggered!") From d6139664e1ff6f43e4348a973a3b804431e615a5 Mon Sep 17 00:00:00 2001 From: ModulatingForce <116608425+modulatingforce@users.noreply.github.com> Date: Mon, 12 Feb 2024 02:34:32 -0500 Subject: [PATCH 3/5] 2024.02.12 - GetRole() Works --- src/core/botinstance.rs | 26 ++++++++++++------ src/core/botmodules.rs | 12 ++++++--- src/core/identity.rs | 59 ++++++++++++++++++++++++++++++++--------- src/main.rs | 19 ++++++++++++- 4 files changed, 91 insertions(+), 25 deletions(-) diff --git a/src/core/botinstance.rs b/src/core/botinstance.rs index 090b0d5..03b68a4 100644 --- a/src/core/botinstance.rs +++ b/src/core/botinstance.rs @@ -240,7 +240,7 @@ impl BotInstance // pub fn init() -> BotInstance // pub fn init() -> Arc - pub fn init() -> BotInstance + pub async fn init() -> BotInstance { dotenv().ok(); @@ -295,7 +295,7 @@ impl BotInstance // ratelimiters : ratelimiters, // client : client, // } , - botmodules : ModulesManager::init(), + botmodules : ModulesManager::init().await, twitch_oauth : oauth_token, bot_channels : botchannels, // identity : IdentityManager::init(), @@ -620,6 +620,7 @@ impl BotInstance // async fn listener_main_prvmsg(self,msg:&PrivmsgMessage) -> () { // async fn listener_main_prvmsg(self:Arc,msg:&PrivmsgMessage) -> () { pub async fn listener_main_prvmsg(bot:BotAR,msg:&PrivmsgMessage) -> () { + println!(">> Inner listenermain_prvmsg()"); // let a = a; // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); @@ -672,18 +673,25 @@ impl BotInstance // let hacts = boxed_bot.clone().lock().await.get_botactions(); // let hacts = bot.read().await.get_botactions(); let botlock = bot.read().await; - let hacts = botlock.botmodules.botactions.read().await; - // let hacts = hacts - for (_m,acts) in &(*hacts) { - + let hacts = Arc::clone(&botlock.botmodules.botactions); + // let hacts = hacts.read().await; + let a = hacts.read().await; + println!("hacts size : {}",(*a).len()); + println!(">> Inner listenermain_prvmsg() >> before for loop of bot actions"); + // println!(">> Inner listenermain_prvmsg() >> before for loop of bot actions : {:?}",*hacts); + // let hacts = hacts + // let l = *hacts; + for (_m,acts) in &*hacts.read().await { + + println!(">> Inner listenermain_prvmsg() >> checking bot actions"); // let bot = bot; for a in acts { - + println!(">> Inner listenermain_prvmsg() >> checking bot actions >> 2"); let _act = match a { @@ -702,6 +710,8 @@ impl BotInstance // println!("args : {v}"); // } + println!("Reviewing internal commands"); + let inpt = msg.message_text.split("\n").next().expect("ERROR during BotCommand"); let inpt = msg.message_text.split(" ").next().expect("ERROR during BotCommand"); @@ -829,7 +839,7 @@ impl BotInstance let botlock = bot.read().await; let id = botlock.get_identity(); let id = id.read().await; - let eval= id.can_user_run_PRVMSG(&msg, c.required_roles.clone()); + let eval= id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await; match eval { // Ok(Permissible::Allow) => (), Permissible::Allow => { diff --git a/src/core/botmodules.rs b/src/core/botmodules.rs index 38f1fc6..3d55f3c 100644 --- a/src/core/botmodules.rs +++ b/src/core/botmodules.rs @@ -277,7 +277,8 @@ impl BotActionTrait for Listener // let mgr = &mut bot.botmodules; // let mgr = bot.botmodules; // self.add_to_modmgr(Arc::new(*mgr)); - self.add_to_modmgr(bot.botmodules); + println!("Adding action to bot"); + self.add_to_modmgr(bot.botmodules).await; } // fn add_to_modmgr(self, modmgr:&mut ModulesManager) { @@ -286,6 +287,7 @@ impl BotActionTrait for Listener // async fn add_to_modmgr(self, modmgr:&'static ModulesManager) { async fn add_to_modmgr(self, modmgr:Arc) { // let modmgr = *modmgr.lock().await; + println!("Adding action to module manager"); modmgr.add_botaction(self.module.clone(), BotAction::L(self)).await; // modmgr.add_botaction(self.module.clone(), BotAction:L(self)) } @@ -311,7 +313,7 @@ impl ModulesManager { // pub fn init() -> Arc> - pub fn init() -> Arc + pub async fn init() -> Arc { @@ -331,8 +333,9 @@ impl ModulesManager // crate::core::identity::init(a.clone()); // crate::core::identity::init(&mgr); + println!("ModulesManager > init() > Adding modules"); let mgra = Arc::new(mgr); - crate::core::identity::init(Arc::clone(&mgra)); + crate::core::identity::init(Arc::clone(&mgra)).await; // initialize custom crate modules // crate::modules::init(&mut mgr); @@ -340,7 +343,7 @@ impl ModulesManager // crate::modules::init(a.clone()); crate::modules::init(Arc::clone(&mgra)); - + println!(">> Modules Manager : End of Init"); @@ -383,6 +386,7 @@ impl 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 async fn add_botaction(&self, in_module:ModType, in_action:BotAction ) { + println!("Add botaction called"); /* adds a BotAction to the Modules Manager - This will require a BotModule passed as well This will including the logic of a valid add diff --git a/src/core/identity.rs b/src/core/identity.rs index 7026835..70d9508 100644 --- a/src/core/identity.rs +++ b/src/core/identity.rs @@ -29,12 +29,14 @@ fn adminvector() -> Vec { // pub fn init(mgr:&mut ModulesManager) -pub fn init(mgr:Arc) +pub async fn init(mgr:Arc) { - let a = actions_util::asyncbox(cmd_promote) ; + println!("Went into Identiy Module init"); - BotCommand { + // 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 @@ -46,7 +48,9 @@ pub fn init(mgr:Arc) UserRole::Broadcaster, UserRole::BotAdmin, ], - }.add_to_modmgr(Arc::clone(&mgr)); + }; + + tempb.add_to_modmgr(Arc::clone(&mgr)); // async fn cmd_promote(mut bot:Arc>,msg:PrivmsgMessage) // async fn cmd_promote(mut bot:&BotInstance,msg:PrivmsgMessage) -> &BotInstance @@ -246,7 +250,21 @@ pub fn init(mgr:Arc) } - BotCommand { + // 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 @@ -258,8 +276,9 @@ pub fn init(mgr:Arc) UserRole::Broadcaster, UserRole::BotAdmin, ], - }.add_to_modmgr(Arc::clone(&mgr)); - + }; + + tempb.add_to_modmgr(Arc::clone(&mgr)).await; // async fn cmd_demote(mut _chat:Arc>,_msg:PrivmsgMessage) { async fn cmd_demote(mut _chat:BotAR,_msg:PrivmsgMessage) { @@ -268,7 +287,21 @@ pub fn init(mgr:Arc) - BotCommand { + // 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, + // ], + // }.add_to_modmgr(Arc::clone(&mgr)); + + let tempcomm = BotCommand { module : BotModule(String::from("identity")), command : String::from("getroles"), // command call name alias : vec![], // String of alternative names @@ -280,7 +313,9 @@ pub fn init(mgr:Arc) UserRole::Broadcaster, UserRole::BotAdmin, ], - }.add_to_modmgr(Arc::clone(&mgr)); + }; + + tempcomm.add_to_modmgr(Arc::clone(&mgr)).await; // async fn getroles(bot:Arc>,msg:PrivmsgMessage) { @@ -401,7 +436,7 @@ pub fn init(mgr:Arc) - + println!("End of Init MOdule add"); } @@ -467,7 +502,7 @@ impl IdentityManager { // 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 fn can_user_run_PRVMSG(&self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible + pub async fn can_user_run_PRVMSG(&self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible { // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); @@ -513,7 +548,7 @@ impl IdentityManager { ChType::Channel(msg.channel_login.to_owned()), sender_badge, cmdreqroles - ) ; + ).await ; } diff --git a/src/main.rs b/src/main.rs index 4278813..7847da3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,7 +14,24 @@ pub type BotAR = Arc>; #[tokio::main] pub async fn main() { - let bot = BotInstance::init(); + let bot = BotInstance::init().await; + + 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 { + crate::core::botmodules::BotAction::C(b) => println!("bot actiions: {}",b.command), + crate::core::botmodules::BotAction::L(l) => println!("bot actiions: {}",l.name), + _ => println!("Not a valid match??"), + } + + } + }; + + println!("Starting runner.."); bot.runner().await; From 680a335e7b576af46edd89f0790f7c15a8f5f5bc Mon Sep 17 00:00:00 2001 From: ModulatingForce <116608425+modulatingforce@users.noreply.github.com> Date: Mon, 12 Feb 2024 05:25:38 -0500 Subject: [PATCH 4/5] 2024.02.12 - Working getuserroles --- src/core/botinstance.rs | 24 +++++-- src/core/botmodules.rs | 16 ++--- src/core/identity.rs | 151 +++++++++++++++++++++++++++------------- 3 files changed, 128 insertions(+), 63 deletions(-) diff --git a/src/core/botinstance.rs b/src/core/botinstance.rs index 03b68a4..bb1ec78 100644 --- a/src/core/botinstance.rs +++ b/src/core/botinstance.rs @@ -776,7 +776,7 @@ impl BotInstance } if confirmed_bot_command { - + println!("Confirmed bot command"); // self.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()); // [ ] Around here, validate if permissable before executing @@ -819,7 +819,7 @@ impl BotInstance // match a.lock().await.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await { - { + // let le = boxed_bot.lock().await; // // let le = le.lock().await; // let le = le.get_identity().await; @@ -836,10 +836,19 @@ impl BotInstance // let id = Arc::clone(&self.botmgrs.identity); // let id = id.write().await; // let id = &(*self.get_identity()); + println!("Going for botlock"); let botlock = bot.read().await; + println!("Going for identity"); let id = botlock.get_identity(); - let id = id.read().await; - let eval= id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await; + // let mut id = id.write().await; + // println!("Unlocking identity"); + // let eval= id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await; + let eval = { + let mut id = id.write().await; + println!("Unlocking identity"); + id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await + }; + println!("Checking if permissible"); match eval { // Ok(Permissible::Allow) => (), Permissible::Allow => { @@ -857,7 +866,8 @@ impl BotInstance // let a = Arc::clone(&self); let a = Arc::clone(&bot); // let a = Arc::clone(&bot); - c.execute(a, msg.clone()); + c.execute(a, msg.clone()).await; + println!("exit out of execution"); } Permissible::Block => { @@ -867,7 +877,7 @@ impl BotInstance }; // c.execute(self.chat.clone(), msg.clone()).await; - } + } }, @@ -881,7 +891,7 @@ impl BotInstance // l.execute(boxed_bot.clone(), msg.clone()).await; // let a = Arc::clone(&self); let a = Arc::clone(&bot); - l.execute(a, msg.clone()); + l.execute(a, msg.clone()).await; }, _ => (), diff --git a/src/core/botmodules.rs b/src/core/botmodules.rs index 3d55f3c..a46b479 100644 --- a/src/core/botmodules.rs +++ b/src/core/botmodules.rs @@ -89,12 +89,12 @@ pub enum BotAction impl BotAction { // pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ - pub fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () + pub async fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () { match self { - BotAction::L(a) => a.execute(m,n), - BotAction::C(a) => a.execute(m,n), + BotAction::L(a) => a.execute(m,n).await, + BotAction::C(a) => a.execute(m,n).await, _ => (), } @@ -129,12 +129,12 @@ impl BotCommand // } // pub fn execute(&self,m:&mut BotInstance,n:PrivmsgMessage) -> () { // pub fn execute(&self,m:actions_util::BotAR,n:PrivmsgMessage) -> () { - pub fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () { + pub async fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () { // ((*self).exec_body)(m,n); // ((*self).exec_body)(*m,n); // m // ((*self).exec_body)( - ((*self).exec_body)(m,n); + ((*self).exec_body)(m,n).await; // m } } @@ -147,7 +147,7 @@ impl BotActionTrait for BotCommand // let mut mgr = *mgr.lock().await; // let mut mgr = &mut mgr; // (*self).add_to_modmgr(bot.botmodules); - self.add_to_modmgr(bot.botmodules); + self.add_to_modmgr(bot.botmodules).await; } // async fn add_to_modmgr(self, modmgr:Arc>) { @@ -261,9 +261,9 @@ impl Listener // } // pub fn execute(&self,m:&BotInstance,n:PrivmsgMessage) -> &BotInstance { // pub fn execute(&self,m:actions_util::BotAR,n:PrivmsgMessage) -> () { - pub fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () { + pub async fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () { // let mut m = Arc::*m; - ((*self).exec_body)(m,n); + ((*self).exec_body)(m,n).await; // *self // &m } diff --git a/src/core/identity.rs b/src/core/identity.rs index 70d9508..8bc3ce6 100644 --- a/src/core/identity.rs +++ b/src/core/identity.rs @@ -18,7 +18,9 @@ use crate::core::botinstance::ArcBox; use std::rc::Rc; use std::cell::RefCell; -use std::sync::{Arc, RwLock}; +use std::sync::{Arc}; +use tokio::sync::RwLock; + use super::botmodules::bot_actions::actions_util::BotAR; @@ -50,7 +52,7 @@ pub async fn init(mgr:Arc) ], }; - tempb.add_to_modmgr(Arc::clone(&mgr)); + tempb.add_to_modmgr(Arc::clone(&mgr)).await; // async fn cmd_promote(mut bot:Arc>,msg:PrivmsgMessage) // async fn cmd_promote(mut bot:&BotInstance,msg:PrivmsgMessage) -> &BotInstance @@ -148,9 +150,14 @@ pub async fn init(mgr:Arc) // let mut p = p.lock().await; // let ta = p.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; let botlock = bot.read().await; - let ta = botlock.get_identity().read().await.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; - - if let Some(a) = ta { + let ta = botlock.get_identity(); + let ta = ta.read().await; + let ta = ta.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await; + let ta = ta.unwrap(); + let a = ta.read().await; + // let ta = *ta; + // let ta = *ta; + // if let Some(a) = *ta { if a.contains(&UserRole::BotAdmin) { println!("BotAdmin allowed to promote admin"); @@ -217,12 +224,12 @@ pub async fn init(mgr:Arc) } } - }, - Some(_) => { - // - + // }, + // Some(_) => { + // // - - }, - _ => (), + // }, + _ => (), } @@ -318,6 +325,7 @@ pub async fn init(mgr:Arc) 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"); @@ -393,8 +401,11 @@ pub async fn init(mgr:Arc) // let a = a.lock().await; // let a = bot.get_identity(); let botlock = bot.read().await; + println!("botlock read"); let idlock = botlock.get_identity(); - let idlock = idlock.read().await; + println!("got identity"); + let idlock = idlock.read().await; // <-- 02.12 - Latest where it gest stuck - before or at this point + println!("id lock"); let sproles = match targetchnl { None => { // let bot = Rc::clone(&bot); @@ -465,7 +476,9 @@ pub enum Permissible { #[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>>>, // # <-- (!) 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>, } @@ -488,11 +501,11 @@ impl IdentityManager { pub fn init() -> IdentityManager { let mut a = HashMap::new(); for admn in adminvector() { - a.insert(admn.to_lowercase(),vec![UserRole::BotAdmin]); + a.insert(admn.to_lowercase(),Arc::new(RwLock::new(vec![UserRole::BotAdmin]))); }; IdentityManager { - special_roles_users : Arc::new(Mutex::new(a)), + special_roles_users : Arc::new(RwLock::new(a)), //parent_mgr : None, } } @@ -502,11 +515,12 @@ impl IdentityManager { // 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(&self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible + pub async fn can_user_run_PRVMSG(&mut self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible { // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); // [ ] Check what Badges in PrivmsgMessage + println!{"Checking within PRVMSG"}; let mut sender_badge:Option = None; @@ -544,11 +558,11 @@ impl IdentityManager { // cmdreqroles // ) ; // return a; - self.can_user_run(msg.sender.name.to_owned(), + return self.can_user_run(msg.sender.name.to_owned(), ChType::Channel(msg.channel_login.to_owned()), sender_badge, cmdreqroles - ).await ; + ).await } @@ -559,13 +573,14 @@ impl IdentityManager { } - pub async fn can_user_run(&self, + pub async fn can_user_run(&mut self, usr:String, channelname:ChType, chat_badge:ChatBadge, cmdreqroles:Vec // ) -> Result> { ) -> Permissible { + println!{"Checking within can_user_run()"}; /* canUserRun - @@ -604,6 +619,8 @@ impl IdentityManager { // [x] If cmdreqroles is empty vector , automatically assume Ok(Permissible::Allow) + // let idar = Arc::new(RwLock::new(self)); + if cmdreqroles.len() == 0 { // return Ok(Permissible::Allow) return Permissible::Allow @@ -632,7 +649,7 @@ impl IdentityManager { ChatBadge::Mod => { - // println!("Mod Chatbadge detected"); + println!("Mod Chatbadge detected"); // println!("debug special roles : {:?}",self.special_roles_users); // println!("debug usr : {}",&usr.to_lowercase()); @@ -640,27 +657,39 @@ impl IdentityManager { // 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()) { - match self.special_roles_users.lock().await.get(&usr.to_lowercase()) { - Some(usrroles) => { - // println!("contains mod : {}", usrroles.contains(&UserRole::Mod(channelname.clone()))); - // println!("contains supmod : {}", usrroles.contains(&UserRole::SupMod(channelname.clone()))); - if usrroles.contains(&UserRole::Mod(channelname.clone())) || - usrroles.contains(&UserRole::SupMod(channelname.clone())) { + println!("Creating clone"); + let roleslock = Arc::clone(&(*self).special_roles_users); + println!("Read lock on : Special_Roles_User"); // <-- after this is slightly different between working and problem + let mut roleslock = roleslock.write().await; + match (*roleslock).get(&usr.to_lowercase()) { + Some(usrroles) => { // <-- 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()))); + if usrroles.read().await.contains(&UserRole::Mod(channelname.clone())) || + usrroles.read().await.contains(&UserRole::SupMod(channelname.clone())) { // Do nothing - this is expected + println!("Already a mod in roles"); } else { // in this case, they have a ChatBadge::Mod but should have this for the channel // let mut a = usrroles; // usrroles.push(UserRole::Mod(channelname.clone())); // a.push(UserRole::Mod(channelname.clone())); - self.special_roles_users - .lock().await - .get_mut(&usr.to_lowercase()) - .expect("ERROR") - .push(UserRole::Mod(channelname.clone())); + println!("Was in the else loop"); + + // let a = &*self; + // let mut lock = a.special_roles_users.write().await; + println!("lock created > adding with a mod role o7"); + roleslock.get_mut(&usr.to_lowercase()) + // .expect("ERROR") + .unwrap() + .write().await + // .get_mut() + .push(UserRole::Mod(channelname.clone())); // println!("debug special roles : {:?}",self.special_roles_users); + } }, - _ => () + _ => ( ) // <-- I'm assuming problem got to here } }, @@ -680,9 +709,11 @@ impl IdentityManager { println!("Mod Role required"); - if let Some(a) = self.special_roles_users.lock().await.get(&usr.to_lowercase()) { - if a.contains(&UserRole::Mod(channelname.clone())) || a.contains(&UserRole::SupMod(channelname.clone())){ + if let Some(a) = (&*self).special_roles_users.read().await.get(&usr.to_lowercase()) { + println!("Special roles found for user"); + 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 "); return Permissible::Allow } } @@ -693,8 +724,8 @@ impl IdentityManager { if cmdreqroles.contains(&UserRole::SupMod(ChType::Channel(String::new()))) { - if let Some(a) = self.special_roles_users.lock().await.get(&usr.to_lowercase()) { - if a.contains(&UserRole::SupMod(channelname.clone())) { + 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 } @@ -707,10 +738,10 @@ impl IdentityManager { println!("Eval cmdreqroles with botadmin : {}",cmdreqroles.contains(&UserRole::BotAdmin)); if cmdreqroles.contains(&UserRole::BotAdmin) { - println!("special roles get : {:?}",self.special_roles_users.lock().await.get(&usr.to_lowercase())); - if let Some(a) = self.special_roles_users.lock().await.get(&usr.to_lowercase()) { - println!("special roles contains BotAdmin: {}",a.contains(&UserRole::BotAdmin)); - if a.contains(&UserRole::BotAdmin) { + println!("special roles get : {:?}",(&*self).special_roles_users.read().await.get(&usr.to_lowercase())); + 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)); + if a.read().await.contains(&UserRole::BotAdmin) { // return Ok(Permissible::Allow); return Permissible::Allow } @@ -737,7 +768,7 @@ impl IdentityManager { let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()).await; // let chatterroles = chatterroles.lock().await; // let chatterroles = *chatterroles; - let chatterroles = chatterroles.unwrap(); + // let chatterroles = chatterroles.unwrap(); // let emptyvec = vec![]; @@ -747,19 +778,26 @@ impl IdentityManager { // _ => &(emptyvec), // }; + let chatterroles = chatterroles.unwrap(); + let chatterroles = chatterroles.read().await; + let rolemap = &(*chatterroles); + + match trg_role { Some(UserRole::Mod(a)) => { if let Some(trg_chnl) = channel { - if chatterroles.contains(&UserRole::Mod(trg_chnl.clone())) { + // let rolemap = rolemap.unwrap(); + if rolemap.contains(&UserRole::Mod(trg_chnl.clone())) { 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())); self.special_roles_users - .lock().await + .write().await .get_mut(&trgchatter) .expect("Error getting roles") + .write().await .push(UserRole::Mod(trg_chnl)); return ChangeResult::Success(String::from("Promotion Successful")); @@ -845,7 +883,10 @@ impl IdentityManager { ChangeResult::Success(String::from("TEST > Promotion Successful")) } - pub async fn getspecialuserroles(&self,chattername:String,channel:Option) -> Option> { + pub async fn getspecialuserroles(&self,chattername:String,channel:Option) -> Option>>> { + /* + Note : Ideally this be called for a given chatter name ? + */ // let a = chattername.to_lowercase(); @@ -863,7 +904,7 @@ impl IdentityManager { // println!("> Roles : {:?}",v); // } - let a = chattername.to_lowercase(); + let chattername = chattername.to_lowercase(); // println!("{a}"); @@ -873,12 +914,26 @@ impl IdentityManager { // Some(b) => Some(*b), // None => None, // } + // println!("Write Lock on Special Roles @ Getspecialuserroles()"); + // let b = self.special_roles_users.write().await.remove(&a); + // let outp = b; + // // let b = Arc::new(Mutex::new(outp)); + // outp - let b = self.special_roles_users.lock().await.remove(&a); - let outp = b; - // let b = Arc::new(Mutex::new(outp)); - outp + let rolesa = Arc::clone(&self.special_roles_users); + let a = rolesa.read().await; + // let a = Arc::clone(a) + let a = a; + let outr = &(*a); + let outr = outr.get(&chattername); + match outr { + Some(a) => Some(Arc::clone(a)), + None => None, + + } + + // Arc::new(RwLock::new(outr)) // let b = Arc::new(Mutex::new(b)); // b From 41eede6e0384848fd09cd4404d0df0b3f813b19b Mon Sep 17 00:00:00 2001 From: ModulatingForce <116608425+modulatingforce@users.noreply.github.com> Date: Mon, 12 Feb 2024 06:18:57 -0500 Subject: [PATCH 5/5] smol add awaits --- src/core/botmodules.rs | 3 ++- src/modules.rs | 4 ++-- src/modules/experiments.rs | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/core/botmodules.rs b/src/core/botmodules.rs index a46b479..bbc9f66 100644 --- a/src/core/botmodules.rs +++ b/src/core/botmodules.rs @@ -341,7 +341,7 @@ impl ModulesManager // crate::modules::init(&mut mgr); // let a = a.clone(); // crate::modules::init(a.clone()); - crate::modules::init(Arc::clone(&mgra)); + crate::modules::init(Arc::clone(&mgra)).await; @@ -536,6 +536,7 @@ impl ModulesManager modactions.push(in_action); println!(">> Modules Manager : Called Add bot Action"); + println!("add_botaction - botactions size : {}",modactions.len()); //println!(">> Modules Manager : {:?}",&self); //(); diff --git a/src/modules.rs b/src/modules.rs index 5d533c6..651ea38 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -27,12 +27,12 @@ mod experiments; // // F : Send, // F : Send + ?Sized, // pub fn init(mgr:&mut ModulesManager) -pub fn init(mgr:Arc) +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 6548320..f7968c9 100644 --- a/src/modules/experiments.rs +++ b/src/modules/experiments.rs @@ -32,7 +32,7 @@ use std::sync::{Arc, RwLock}; // pub fn init(mgr:&mut ModulesManager) -pub fn init(mgr:Arc) +pub async fn init(mgr:Arc) { @@ -60,7 +60,7 @@ pub fn init(mgr:Arc) ], }; - botc1.add_to_modmgr(Arc::clone(&mgr)); + botc1.add_to_modmgr(Arc::clone(&mgr)).await; @@ -71,7 +71,7 @@ pub fn init(mgr:Arc) help : String::from("") }; - list1.add_to_modmgr(Arc::clone(&mgr)); + list1.add_to_modmgr(Arc::clone(&mgr)).await; }