Skip to content

Commit

Permalink
Refactor cli code structure
Browse files Browse the repository at this point in the history
  • Loading branch information
tangxianyun committed Sep 8, 2024
1 parent 2793a3d commit 4c5f66e
Show file tree
Hide file tree
Showing 9 changed files with 362 additions and 299 deletions.
1 change: 1 addition & 0 deletions cli/src/infrastructure/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod settings;
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use serde_json::json;
use std::path::Path;
use tokio::fs;
use url::Url;

#[derive(Serialize, Deserialize, Debug)]
pub struct Credential {
Expand All @@ -11,12 +12,13 @@ pub struct Credential {
}

pub struct Settings {
pub server: Url,
path: String,
credentials: Vec<Credential>,
}

impl Settings {
pub async fn new() -> Self {
pub async fn new(server: &str) -> Self {
let path = format!(
"{}/.subway/.settings.json",
dirs::home_dir().unwrap().to_str().unwrap()
Expand All @@ -39,32 +41,33 @@ impl Settings {
serde_json::from_str(&String::from_utf8(credential_string).unwrap()).unwrap();

Self {
credentials,
server: Url::parse(server).unwrap(),
path: settings_path.to_str().unwrap().to_string(),
credentials,
}
}

pub async fn read_token(&self, server: String) -> String {
pub async fn read_token(&self) -> String {
let access_token = self
.credentials
.iter()
.find(|credential| credential.name == server)
.find(|credential| credential.name == self.server.as_str())
.map(|credential| credential.access_token.to_string())
.unwrap_or_else(|| return "".to_string());
.unwrap_or("".to_string());

access_token
}

pub async fn write_token(&mut self, server: &str, access_token: &str) -> Result<()> {
pub async fn write_token(&mut self, access_token: &str) -> Result<()> {
if let Some(exist_credential) = self
.credentials
.iter_mut()
.find(|credential| credential.name == server)
.find(|credential| credential.name == self.server.as_str())
{
exist_credential.access_token = access_token.to_string();
} else {
let new_credential = Credential {
name: server.to_string(),
name: self.server.to_string(),
access_token: access_token.to_string(),
};
self.credentials.push(new_credential);
Expand Down
65 changes: 38 additions & 27 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
mod infrastructure;
mod services;

use crate::services::api::ApiService;
use crate::services::settings::Settings;
use crate::infrastructure::settings::Settings;
use crate::services::api_client::ApiService;
use clap::{Parser, Subcommand};
use std::process;
use std::sync::Arc;
use tokio::signal;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Cli {
#[clap(short, long, default_value = "pysubway.com")]
#[clap(short, long, default_value = "https://pysubway.com")]
server: String,

#[clap(short, long, default_value = "false")]
use_ssl: bool,

#[command(subcommand)]
command: Commands,
}
Expand All @@ -32,38 +33,48 @@ async fn main() {
tracing_subscriber::fmt().init();

let cli = Cli::parse();
let settings = Settings::new().await;
let settings = Settings::new(&cli.server).await;

let mut api_service = ApiService::new(settings, &cli.server, cli.use_ssl);
let mut api_service = ApiService::new(settings);

match api_service.health_check().await {
Ok(response) => response,
Err(..) => {
tracing::error!("Cannot connect to server {}", &cli.server);
panic!()
}
if api_service.health_check().await.is_err() {
tracing::error!("Cannot connect to server {}", &cli.server);
panic!()
};

match &cli.command {
Commands::Http {
endpoint,
subdomain,
} => {
match api_service.acquire_proxy(subdomain).await {
Ok(response) => response,
Err(err) => {
tracing::error!("{:#?}", err.to_string());
panic!()
}
};
if api_service.sign_in().await.is_err() {
tracing::error!("Sign in failed.");
panic!()
}

if api_service.acquire_proxy(subdomain).await.is_err() {
tracing::error!("Acquire proxy failed.");
panic!()
}

let api_service = Arc::new(api_service);
{
let api_service_arc = Arc::clone(&api_service);
tokio::spawn(async move {
signal::ctrl_c().await.unwrap();
println!("Received Ctrl+C, cleaning up...");

api_service_arc.release_proxy().await.unwrap();

process::exit(0);
});
let api_service_arc = Arc::clone(&api_service);

match api_service.start_proxy(endpoint).await {
Ok(response) => response,
Err(err) => {
tracing::error!("{:#?}", err.to_string());
if let Err(err) = api_service_arc.start_proxy(endpoint).await {
tracing::error!("Start proxy failed. {err:#?}");
panic!()
}
};
};
}
}
}
}
Loading

0 comments on commit 4c5f66e

Please sign in to comment.