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,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}; use tokio::sync::RwLock; use super::botmodules::bot_actions::actions_util::BotAR; fn adminvector() -> Vec { vec![String::from("ModulatingForce")] } // pub fn init(mgr:&mut ModulesManager) pub async fn init(mgr:Arc) { println!("Went into Identiy Module init"); // let a = actions_util::asyncbox(cmd_promote) ; let tempb = BotCommand { module : BotModule(String::from("identity")), command : String::from("promote"), // command call name alias : vec![], // String of alternative names exec_body : actions_util::asyncbox(cmd_promote) , help : String::from("promote"), required_roles : vec![ UserRole::Mod(ChType::Channel(String::new())), UserRole::SupMod(ChType::Channel(String::new())), UserRole::Broadcaster, UserRole::BotAdmin, ], }; tempb.add_to_modmgr(Arc::clone(&mgr)).await; async fn cmd_promote(bot:BotAR,msg:PrivmsgMessage) -> () { //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); println!("Called cmd promote"); // -- If the BotCommand.command was called (e.g., promote) & required roles were validated OUTSIDE of this call // , this is the current function body to execute /* - `promote` / `demote` - [ ] `SupMod` & `Broadcaster` & `BotAdmin` can run - [ ] `UserRole`s that can run, can - [ ] run `promote` on a regular `Chatter` to make them a `Mod` - [ ] run `demote` on a `Mod` to make them a `Chatter` - [ ] Only `BotAdmin` can : - [ ] target themselves to `promote` / `demote` , in the case that they want to make themselves either a `Mod` or `SupMod` for the channel temporarily - [ ] `promote admin ` to assign them `BotAdmin` role - `[ ] Broadcaster` & `BotAdmin` can `demote` a `SupMod` to make them a `Mod` */ /* Usage : promote demote promote admin */ println!("{}",msg.message_text); let mut argv = msg.message_text.split(" "); argv.next(); // Skip the command name let arg1 = argv.next(); let arg2 = argv.next(); let mut sender_badge:Option = None; for b in &msg.badges { if b.name == "moderator" { sender_badge = Some(ChatBadge::Mod); } else if b.name == "broadcaster" { sender_badge = Some(ChatBadge::Broadcaster); } } match arg1 { Some(a1) if a1 == String::from("admin") => { // - BotAdmins can promote admin to give BotAdmin UserRole let botlock = bot.read().await; 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"); { 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 { ChangeResult::Success(a) => println!("Succesfully promoted : {a} ;"), ChangeResult::Failed(a) => println!("Failed to promote : {a} ; "), ChangeResult::NoChange(a) => println!("No Changes Made : {a} ; "), } } } } // }, _ => (), } let arg2 = argv.next(); let targetchnl = arg2; } // BotCommand { // module : BotModule(String::from("identity")), // command : String::from("demote"), // command call name // alias : vec![], // String of alternative names // exec_body : actions_util::asyncbox(cmd_demote) , // help : String::from("demote"), // required_roles : vec![ // UserRole::Mod(ChType::Channel(String::new())), // UserRole::SupMod(ChType::Channel(String::new())), // UserRole::Broadcaster, // UserRole::BotAdmin, // ], // }.add_to_modmgr(Arc::clone(&mgr)); let tempb = BotCommand { module : BotModule(String::from("identity")), command : String::from("demote"), // command call name alias : vec![], // String of alternative names exec_body : actions_util::asyncbox(cmd_demote) , help : String::from("demote"), required_roles : vec![ UserRole::Mod(ChType::Channel(String::new())), UserRole::SupMod(ChType::Channel(String::new())), UserRole::Broadcaster, UserRole::BotAdmin, ], }; tempb.add_to_modmgr(Arc::clone(&mgr)).await; // async fn cmd_demote(mut _chat:Arc>,_msg:PrivmsgMessage) { async fn cmd_demote(mut _chat:BotAR,_msg:PrivmsgMessage) { println!("Called cmd demote"); } // 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 exec_body : actions_util::asyncbox(getroles) , help : String::from("getroles"), required_roles : vec![ UserRole::Mod(ChType::Channel(String::new())), UserRole::SupMod(ChType::Channel(String::new())), UserRole::Broadcaster, UserRole::BotAdmin, ], }; tempcomm.add_to_modmgr(Arc::clone(&mgr)).await; // async fn getroles(bot:Arc>,msg:PrivmsgMessage) { async fn getroles(bot:BotAR,msg:PrivmsgMessage) { println!("Called cmd getroles"); /* Usage getroles - If channel is provided, provide roles for that channel specifically */ // IN other code areas , I see this // ServerMessage::Privmsg(msg) => { // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); // println!("{}",msg.message_text); let mut argv = msg.message_text.split(" "); // for v in argv { // println!("args : {v}"); // } argv.next(); // Skip the command name let arg1 = argv.next(); // if arg == None { // return ; // Do nothing if no arguments // } let targetuser = match arg1 { None => return , // exit if no arguments Some(arg) => arg, }; // match String::from(arg1) { // a if a == String::from("admin") => (), // _ => (), // } // match argv[1] { // String::from("admin") => (), // } let arg2 = argv.next(); let targetchnl = arg2; // // let a = bot.read().ok().unwrap().get_identity(); // let a = bot.lock().await; // // let a = a.lock().await; // // let a = a.get_identity().await; // let a = a.botmgrs; // // let a = *(*a).lock().await; // let a = *a.lock().await; // let a = a.identity; // let a = *a.lock().await; // let a = bot.clone(); // let a = a.into_inner(); // let a = a.botmgrs; // let a = a.into_inner(); // let a = a.identity; // let a = a.into_inner(); // let a = bot.clone(); // let a = a.lock().await; // let a = a.get_identity(); // let a = a.lock().await; // let a = bot.get_identity(); let botlock = bot.read().await; println!("botlock read"); let idlock = botlock.get_identity(); 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); //let bot = Arc::clone(&bot); // let a = bot.botmgrs.identity.getspecialuserroles(String::from(targetuser),None); // let a = Arc::try_unwrap(bot).ok().unwrap().into_inner().ok().unwrap(); // let a = Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner(); // let a = a.botmgrs.identity.getspecialuserroles(String::from(targetuser),None); // let a = a.ok().getspecialuserroles(String::from(targetuser),None); // let a = bot.read().ok().unwrap().rIdentity().getspecialuserroles(String::from(targetuser),None); // println!("Retrieved User Roles >> {:?}",a); // let a = idlock.read().await; idlock.getspecialuserroles(String::from(targetuser),None).await }, Some(targetchnl) => { // let bot = Rc::clone(&bot); // let bot = Arc::clone(&bot); // let a = bot.botmgrs.identity.getspecialuserroles(String::from(targetuser), Some(ChType::Channel(String::from(targetchnl)))); // Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner() // let a = Arc::try_unwrap(bot).ok().unwrap().into_inner().ok().unwrap(); // let a = Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner(); // let a = a.botmgrs.identity.getspecialuserroles(String::from(targetuser), Some(ChType::Channel(String::from(targetchnl)))); // let a = bot.read().ok().unwrap().rIdentity().getspecialuserroles(String::from(targetuser),None); // println!("Retrieved User Roles >> {:?}",a); // bot.read().ok().unwrap().rIdentity().getspecialuserroles(String::from(targetuser),None) // let a = a.read().await; idlock.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); } println!("End of Init MOdule add"); } // #[derive(Debug, PartialEq, Eq, Hash, Clone)] // pub enum ChType { // Channel(String), // } #[derive(Debug, PartialEq, Eq , Clone)] pub enum UserRole { Chatter, Mod(ChType), // String specifies Channel SupMod(ChType), // String specifies Channel Broadcaster, BotAdmin, } pub enum Permissible { Allow, Block } #[derive(Clone)] pub struct IdentityManager { // special_roles_users : HashMap>, // # <-- (!) This must be String instead of ChType because we're checking a User not a Channel // special_roles_users : Arc>>>, // # <-- (!) This must be String instead of ChType because we're checking a User not a Channel // special_roles_users : Arc>>>, special_roles_users : Arc>>>>>, // parent_mgr : Box, //parent_mgr : Option>, } pub enum ChatBadge { Broadcaster, Mod, } enum ChangeResult { Success(String), Failed(String), NoChange(String), } impl IdentityManager { pub fn init() -> IdentityManager { let mut a = HashMap::new(); for admn in adminvector() { a.insert(admn.to_lowercase(),Arc::new(RwLock::new(vec![UserRole::BotAdmin]))); }; IdentityManager { special_roles_users : Arc::new(RwLock::new(a)), //parent_mgr : None, } } // [ ] Maybe I should create a can_user_run version that simply takes PrvMsg, but then calls can_user_run directly // pub fn can_user_run_PRVMSG(self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Result> // pub fn can_user_run_PRVMSG(&self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible // pub async fn can_user_run_PRVMSG(self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible pub async fn can_user_run_PRVMSG(&mut self,msg:&PrivmsgMessage,cmdreqroles:Vec) -> Permissible { // 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; for b in &msg.badges { if b.name == "moderator" { sender_badge = Some(ChatBadge::Mod); } else if b.name == "broadcaster" { sender_badge = Some(ChatBadge::Broadcaster); } } // if &msg.badges.contains(Badge{}) { // } if let Some(sender_badge) = sender_badge { // return &self.can_user_run(msg.sender.name.to_owned(), // ChType::Channel(msg.channel_login.to_owned()), // sender_badge, // cmdreqroles // return self.can_user_run(msg.sender.name.to_owned(), // let a = Arc::new(Mutex::new(self)); // let mut a = a.lock().await; // let a = **a; // let a = a.can_user_run(msg.sender.name.to_owned(), // ChType::Channel(msg.channel_login.to_owned()), // sender_badge, // cmdreqroles // ) ; // let a = *self; // let a = Arc::new(Mutex::new(a)); // let a = a.lock().await.can_user_run(msg.sender.name.to_owned(), // ChType::Channel(msg.channel_login.to_owned()), // sender_badge, // cmdreqroles // ) ; // return a; return self.can_user_run(msg.sender.name.to_owned(), ChType::Channel(msg.channel_login.to_owned()), sender_badge, cmdreqroles ).await } // [ ] Call can_user_run() // (self,Permissible::Block) Permissible::Block } 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 - Input : usr:String, channelname:ChType, chat_badge:ChatBadge, cmdreqroles:Vec Output : Result> Some Possible outcomes : Ok(Permissible::Allow) , Ok(Permissible::Block) Description For a Given Chatter (with any special ChatBadge) who ran the Command at a Given Channel , check if that user can run the command based on the given cmdreqroles required by the command Inputs and business logic determine if the user can run the command based on the command's required roles */ // Requirements /* [x] If cmdreqroles is empty vector , automatically assume Ok(Permissible::Allow) [x] If chatBadge::Broadcaster ... [x] and cmdreqroles includes UserRole::Broadcaster , Ok(Permissible::Allow) [x] and cmdreqroles includes UserRole::Mod("") OR UserRole::SupMod("") , Ok(Permissible::Allow) [x] If chatBadge::Mod ... [x] Check if they have either UserRole::Mod(channelname::ChType) or UserRole::SupMod(channelname::ChType) [x] If not, assign them UserRole::Mod(channelname::ChType) [x] If cmdreqroles includes UserRole::Mod("") , checks if chatter has UserRole::Mod(channelname::ChType) or UserRole::SupMod(channelname::ChType) to determine if Ok(Permissible::Allow) [x] If cmdreqroles includes UserRole::SupMod("") , checks if chatter has UserRole::SupMod(channelname::ChType) to determine if Ok(Permissible::Allow) [x] If cmdreqroles includes UserRole::BotAdmin and chatter has UserRole::BotAdmin , Ok(Permissible::Allow) [x] Otherwise, Ok(Permissible::Block) */ // [x] If cmdreqroles is empty vector , automatically assume Ok(Permissible::Allow) // let idar = Arc::new(RwLock::new(self)); if cmdreqroles.len() == 0 { // return Ok(Permissible::Allow) return Permissible::Allow } match chat_badge { // [x] If chatBadge::Broadcaster ... // [x] and cmdreqroles includes UserRole::Broadcaster , Ok(Permissible::Allow) // [x] and cmdreqroles includes UserRole::Mod("") OR UserRole::SupMod("") , Ok(Permissible::Allow) ChatBadge::Broadcaster => { if cmdreqroles.contains(&UserRole::Broadcaster) || cmdreqroles.contains(&UserRole::Mod(ChType::Channel(String::new()))) || cmdreqroles.contains(&UserRole::SupMod(ChType::Channel(String::new()))) { // return Ok(Permissible::Allow) return Permissible::Allow } }, // [x] If chatBadge::Mod ... // [x] Check if they have either UserRole::Mod(channelname::ChType) or UserRole::SupMod(channelname::ChType) // [x] If not, assign them UserRole::Mod(channelname::ChType) ChatBadge::Mod => { println!("Mod Chatbadge detected"); // println!("debug special roles : {:?}",self.special_roles_users); // println!("debug usr : {}",&usr.to_lowercase()); // let Some((k,v)) = self.special_roles_users.get_key_value(usr); // match self.special_roles_users.get_mut(&usr.to_lowercase()) { // match self.special_roles_users.get(&usr.to_lowercase()) { println!("Creating clone"); 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())); 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); } }, _ => { 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())); }// <-- I'm assuming problem got to here } }, // _ => (), } // [x] If cmdreqroles includes UserRole::Mod("") , checks if chatter has UserRole::Mod(channelname::ChType) or UserRole::SupMod(channelname::ChType) to determine if Ok(Permissible::Allow) println!("cmd required roles : {:?}",cmdreqroles); if cmdreqroles.contains(&UserRole::Mod(ChType::Channel(String::new()))) { // match self.special_roles_users.get(&channelname) { // Some(usrroles) => {}, // None => (), // } println!("Mod Role required"); 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 } } } // [x] If cmdreqroles includes UserRole::SupMod("") , checks if chatter has UserRole::SupMod(channelname::ChType) to determine if Ok(Permissible::Allow) if cmdreqroles.contains(&UserRole::SupMod(ChType::Channel(String::new()))) { if let Some(a) = (&*self).special_roles_users.read().await.get(&usr.to_lowercase()) { if a.read().await.contains(&UserRole::SupMod(channelname.clone())) { // return Ok(Permissible::Allow); return Permissible::Allow } } } // [x] If cmdreqroles includes UserRole::BotAdmin and chatter has UserRole::BotAdmin , Ok(Permissible::Allow) println!("Eval cmdreqroles with botadmin : {}",cmdreqroles.contains(&UserRole::BotAdmin)); if cmdreqroles.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 } } } Permissible::Block } // 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 // let chatterroles = self.getspecialuserroles(trgchatter, channel); // 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 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 = chatterroles.unwrap(); let chatterroles = chatterroles.read().await; let rolemap = &(*chatterroles); match trg_role { Some(UserRole::Mod(a)) => { if let Some(trg_chnl) = channel { // 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 .write().await .get_mut(&trgchatter) .expect("Error getting roles") .write().await .push(UserRole::Mod(trg_chnl)); return ChangeResult::Success(String::from("Promotion Successful")); } }, Some(UserRole::SupMod(a)) => (), Some(UserRole::BotAdmin) => (), Some(_) => (), None => (), } // match chatterroles { // Some(chatterroles) => { // // [x] chatter already has the target role // if chatterroles.contains(&trg_role) { // return ChangeResult::NoChange(String::from("Target User already has Target Role")); // } // // By this point, chatteroles does not contain target role // // match trgRole { // // Some(trgRole) => { // // match trgRole { // // UserRole::Mod(a) => { // // }, // // UserRole::SupMod(a) => (), // // UserRole::BotAdmin => (), // // _ => (), // <-- do nothing with al other options // // } // // }, // // None => { // // /* // // - If trgRole is None , then promote by implicit rules . For example, // // - For UserRoles without Mod or SupMod & Caller is SupMod | Broadcaster | BotAdmin > To Mod // // - For Mod & Caller is SupMod | Broadcaster | BotAdmin > To SupMod // // - For UserRoles without BotAdmin & Caller is BotAdmin > To BotAdmin // // */ // // }, // // } // // let trgRole = match trgRole { // // Some(UserRole::Mod(a)) => a, // // Some(UserRole::SupMod(a)) => a, // // Some(UserRole::BotAdmin) => UserRole::BotAdmin, // // None => { // // /* // // - If trgRole is None , then promote by implicit rules . For example, // // - For UserRoles without Mod or SupMod & Caller is SupMod | Broadcaster | BotAdmin > To Mod // // - For Mod & Caller is SupMod | Broadcaster | BotAdmin > To SupMod // // - For UserRoles without BotAdmin & Caller is BotAdmin > To BotAdmin // // */ // // }, // // }; // // if let Some(trgRole) = trgRole { // // // [x] chatter already has the target role // // if chatterroles.contains(&trgRole) { // // return ChangeResult::NoChange(String::from("Target User already has Target Role")); // // } // // // [ ] trgRole should be assigned based on the input channel // // let roletoassign = UserRole:: // // } // }, // _ => (), // } ChangeResult::Success(String::from("TEST > Promotion Successful")) } pub fn demote(self,trgchatter:String,channel:Option,trgRole:Option) -> ChangeResult { ChangeResult::Success(String::from("TEST > Promotion Successful")) } pub async fn getspecialuserroles(&self,chattername:String,channel:Option) -> Option>>> { /* Note : Ideally this be called for a given chatter name ? */ let chattername = chattername.to_lowercase(); 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, } } }