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

89 lines
2.4 KiB
Rust
Raw Normal View History

use kordophone::APIInterface;
use kordophone::api::http_client::HTTPAPIClient;
use kordophone::api::http_client::Credentials;
2025-04-27 14:01:19 -07:00
use kordophone::api::InMemoryTokenStore;
use dotenv;
use anyhow::Result;
2024-12-08 15:08:15 -08:00
use clap::Subcommand;
2025-01-20 19:43:21 -08:00
use crate::printers::{ConversationPrinter, MessagePrinter};
2025-04-27 14:01:19 -07:00
pub fn make_api_client_from_env() -> HTTPAPIClient<InMemoryTokenStore> {
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"),
};
2025-04-27 14:01:19 -07:00
HTTPAPIClient::new(base_url.parse().unwrap(), credentials.into(), InMemoryTokenStore::new())
}
2024-12-08 15:08:15 -08:00
#[derive(Subcommand)]
pub enum Commands {
/// Prints all known conversations on the server.
Conversations,
2025-01-20 19:43:21 -08:00
/// Prints all messages in a conversation.
Messages {
conversation_id: String,
},
2024-12-08 15:08:15 -08:00
/// Prints the server Kordophone version.
Version,
}
impl Commands {
pub async fn run(cmd: Commands) -> Result<()> {
2024-12-08 15:08:15 -08:00
let mut client = ClientCli::new();
match cmd {
Commands::Version => client.print_version().await,
Commands::Conversations => client.print_conversations().await,
2025-01-20 19:43:21 -08:00
Commands::Messages { conversation_id } => client.print_messages(conversation_id).await,
2024-12-08 15:08:15 -08:00
}
}
}
struct ClientCli {
2025-04-27 14:01:19 -07:00
api: HTTPAPIClient<InMemoryTokenStore>,
}
impl ClientCli {
pub fn new() -> Self {
let api = make_api_client_from_env();
Self { api: api }
}
pub async fn print_version(&mut self) -> Result<()> {
let version = self.api.get_version().await?;
println!("Version: {}", version);
Ok(())
}
pub async fn print_conversations(&mut self) -> Result<()> {
let conversations = self.api.get_conversations().await?;
for conversation in conversations {
println!("{}", ConversationPrinter::new(&conversation.into()));
}
Ok(())
}
2025-01-20 19:43:21 -08:00
pub async fn print_messages(&mut self, conversation_id: String) -> Result<()> {
let messages = self.api.get_messages(&conversation_id).await?;
for message in messages {
println!("{}", MessagePrinter::new(&message.into()));
}
Ok(())
}
}