lockbook 26.7.23

CLI for interacting with your lockbook.net. Use your favorite text editor to edit your notes!
use std::io;
use std::str::FromStr;

use arboard::Clipboard;
use chrono::{TimeZone, Utc};
use cli_rs::cli_error::{CliError, CliResult};

use is_terminal::IsTerminal;
use lb_rs::DEFAULT_API_LOCATION;
use lb_rs::Lb;
use lb_rs::model::api::{PaymentMethod, PaymentPlatform, StripeAccountTier};

use crate::{core, ensure_account, input};

#[tokio::main]
pub async fn new(username: String, api_url: ApiUrl) -> CliResult<()> {
    let lb = core().await?;
    println!("generating keys and checking for username availability...");
    lb.create_account(&username, &api_url.0, true).await?;
    println!("account created!");

    Ok(())
}

#[tokio::main]
pub async fn import(api_url: ApiUrl) -> CliResult<()> {
    let lb = &core().await?;

    // if being piped, read from stdin
    if !io::stdin().is_terminal() {
        let mut account_string = String::new();
        io::stdin()
            .read_line(&mut account_string)
            .map_err(|e| CliError::from(format!("failed to read from stdin: {e}")))?;
        return import_key(lb, account_string.trim(), &api_url.0).await;
    }

    // try clipboard first
    if let Some(clip) = try_clipboard() {
        println!("trying clipboard...");
        if import_key(lb, &clip, &api_url.0).await.is_ok() {
            return Ok(());
        }
        println!("clipboard did not contain a valid key.");
    }

    // fall back to prompting
    let config = rpassword::ConfigBuilder::new()
        .password_feedback_mask('*')
        .build();
    let account_string = rpassword::prompt_password_with_config("paste your private key: ", config)
        .map_err(|e| CliError::from(format!("failed to read from stdin: {e}")))?;
    import_key(lb, account_string.trim(), &api_url.0).await
}

fn try_clipboard() -> Option<String> {
    Clipboard::new().ok()?.get_text().ok()
}

async fn import_key(lb: &Lb, key: &str, api_url: &str) -> CliResult<()> {
    println!("importing account...");
    lb.import_account(key, Some(api_url)).await?;
    println!("account imported! next, try to sync by running: lockbook sync");
    Ok(())
}

#[tokio::main]
pub async fn export(skip_check: bool) -> CliResult<()> {
    let lb = &core().await?;
    ensure_account(lb)?;

    // skip confirmation if piped or flag is set
    let interactive = io::stdout().is_terminal();
    let should_ask = interactive && !skip_check;

    if should_ask {
        let answer: String = input::std_in(
            "your private key is about to be visible. do you want to proceed? [y/n]: ",
        )?;
        if answer != "y" && answer != "Y" {
            return Ok(());
        }
    }

    print!("{}", lb.export_account_private_key()?);
    Ok(())
}

#[tokio::main]
pub async fn subscribe() -> Result<(), CliError> {
    let lb = &core().await?;
    ensure_account(lb)?;

    println!("checking for existing payment methods...");
    let existing_card =
        lb.get_subscription_info()
            .await?
            .and_then(|info| match info.payment_platform {
                PaymentPlatform::Stripe { card_last_4_digits } => Some(card_last_4_digits),
                PaymentPlatform::GooglePlay { .. } => None,
                PaymentPlatform::AppStore { .. } => None,
            });

    let mut use_old_card = false;
    if let Some(card) = existing_card {
        let answer: String = input::std_in(format!("do you want use *{card}? [y/n]: "))?;
        if answer == "y" || answer == "Y" {
            use_old_card = true;
        }
    } else {
        println!("no existing cards found...");
    }

    let payment_method = if use_old_card {
        PaymentMethod::OldCard
    } else {
        PaymentMethod::NewCard {
            number: input::std_in("enter your card number: ")?,
            exp_year: input::std_in("expiration year: ")?,
            exp_month: input::std_in("expiration month: ")?,
            cvc: input::std_in("cvc: ")?,
        }
    };

    lb.upgrade_account_stripe(StripeAccountTier::Premium(payment_method))
        .await?;
    println!("subscribed!");
    Ok(())
}

#[tokio::main]
pub async fn unsubscribe() -> Result<(), CliError> {
    let lb = &core().await?;
    ensure_account(lb)?;

    let answer: String =
        input::std_in("are you sure you would like to cancel your subscription? [y/n]: ")?;
    if answer == "y" || answer == "Y" {
        println!("cancelling subscription... ");
        lb.cancel_subscription().await?;
    }
    Ok(())
}

#[tokio::main]
pub async fn status() -> Result<(), CliError> {
    let lb = &core().await?;
    ensure_account(lb)?;

    let last_synced = lb.get_last_synced_human().await?;
    println!("files last synced: {last_synced}");

    // todo: consider having some way to communicate the status of files on the server

    let cap = lb.get_usage().await?;
    let pct = (cap.server_usage.exact * 100) / cap.data_cap.exact;

    if let Some(info) = lb.get_subscription_info().await? {
        match info.payment_platform {
            PaymentPlatform::Stripe { card_last_4_digits } => {
                println!("type: Stripe, *{card_last_4_digits}")
            }
            PaymentPlatform::GooglePlay { account_state } => {
                println!("type: Google Play");
                println!("state: {account_state:?}");
            }
            PaymentPlatform::AppStore { account_state } => {
                println!("type: App Store");
                println!("state: {account_state:?}");
            }
        }
        let renewal_date = Utc
            .timestamp_millis_opt(info.period_end as i64)
            .single()
            .map(|dt| dt.format("%B %d, %Y").to_string())
            .unwrap_or_else(|| info.period_end.to_string());
        println!("renews on: {}", renewal_date);
    } else {
        println!("trial tier");
    }
    println!("data cap: {}, {}% utilized", cap.data_cap.readable, pct);
    Ok(())
}

#[derive(Clone)]
pub struct ApiUrl(String);

impl Default for ApiUrl {
    fn default() -> Self {
        Self(std::env::var("API_URL").unwrap_or(DEFAULT_API_LOCATION.to_string()))
    }
}

impl FromStr for ApiUrl {
    type Err = core::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(String::from_str(s)?))
    }
}