Private
Public Access
1
0
Files
Kordophone/kpcli/src/client/mod.rs

69 lines
1.8 KiB
Rust
Raw Normal View History

use kordophone::APIInterface;
use kordophone::api::http_client::HTTPAPIClient;
use kordophone::api::http_client::Credentials;
use dotenv;
2024-12-08 15:08:15 -08:00
use clap::Subcommand;
use crate::printers::ConversationPrinter;
2024-12-08 15:08:15 -08:00
#[derive(Subcommand)]
pub enum Commands {
/// Prints all known conversations on the server.
Conversations,
/// Prints the server Kordophone version.
Version,
}
impl Commands {
pub async fn run(cmd: Commands) -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClientCli::new();
match cmd {
Commands::Version => client.print_version().await,
Commands::Conversations => client.print_conversations().await,
}
}
}
struct ClientCli {
api: HTTPAPIClient,
}
impl ClientCli {
pub fn new() -> Self {
dotenv::dotenv().ok();
// read from env
let base_url = std::env::var("KORDOPHONE_API_URL")
.expect("KORDOPHONE_API_URL must be set");
let credentials = Credentials {
username: std::env::var("KORDOPHONE_USERNAME")
.expect("KORDOPHONE_USERNAME must be set"),
password: std::env::var("KORDOPHONE_PASSWORD")
.expect("KORDOPHONE_PASSWORD must be set"),
};
let api = HTTPAPIClient::new(base_url.parse().unwrap(), credentials.into());
Self { api: api }
}
pub async fn print_version(&mut self) -> Result<(), Box<dyn std::error::Error>> {
let version = self.api.get_version().await?;
println!("Version: {}", version);
Ok(())
}
pub async fn print_conversations(&mut self) -> Result<(), Box<dyn std::error::Error>> {
let conversations = self.api.get_conversations().await?;
for conversation in conversations {
println!("{}", ConversationPrinter::new(&conversation));
}
Ok(())
}
}