gamenight/gamenight-cli/src/flows/view_gamenight.rs

90 lines
2.6 KiB
Rust

use gamenight_api_client_rs::{apis::default_api::{participants_get, user_get}, models::{GamenightId, UserId}};
use inquire::Select;
use jsonwebtoken::{decode, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{domain::{gamenight::Gamenight, participants::Participants, user::User}, flows::{exit::Exit, join::Join, leave::Leave}};
use super::*;
#[derive(Clone)]
pub struct ViewGamenight {
gamenight: Gamenight
}
impl ViewGamenight {
pub fn new(gamenight: Gamenight) -> Self {
Self {
gamenight
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
exp: i64,
uid: Uuid
}
impl From<jsonwebtoken::errors::Error> for FlowError {
fn from(value: jsonwebtoken::errors::Error) -> Self {
Self {
error: value.to_string()
}
}
}
#[async_trait]
impl<'a> Flow<'a> for ViewGamenight {
async fn run(&self, state: &'a mut GamenightState) -> FlowResult<'a> {
let participants = participants_get(&state.api_configuration, Some(GamenightId{gamenight_id: self.gamenight.id.to_string()})).await?;
let mut users = vec![];
for participant in participants.participants.iter() {
let user = user_get(&state.api_configuration, Some(UserId{user_id: participant.clone()})).await?;
users.push(User {
id: Uuid::parse_str(&user.id)?,
username: user.username
});
}
println!("{}\nwho: {}", self.gamenight, Participants(&users));
let decoding_key = DecodingKey::from_secret(b"");
let mut validation = Validation::default();
validation.insecure_disable_signature_validation();
let claims = decode::<Claims>(
&state.api_configuration.bearer_access_token.as_ref().unwrap(),
&decoding_key,
&validation)?.claims;
let join_or_leave: Box<dyn Flow<'a> + Send> =
if users.iter().map(|x| {x.id}).find(|x| *x == claims.uid) != None {
Box::new(Leave::new(self.gamenight.id))
}
else {
Box::new(Join::new(self.gamenight.id))
};
let options: Vec<Box<dyn Flow<'a> + Send>> = vec![
join_or_leave,
Box::new(Exit::new())
];
let choice = Select::new("What do you want to do:", options)
.prompt_skippable()?;
self.continue_choice(state, &choice).await
}
}
impl Display for ViewGamenight {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {}", self.gamenight.name, self.gamenight.start_time.format("%d-%m-%Y %H:%M"))
}
}