use clap::ArgMatches;
use ffsend_api::action::password::{Error as PasswordError, Password as ApiPassword};
use ffsend_api::file::remote_file::RemoteFile;
use prettytable::{format::FormatBuilder, Cell, Row, Table};
use crate::client::create_config;
use crate::cmd::matcher::{main::MainMatcher, password::PasswordMatcher, Matcher};
use crate::error::ActionError;
#[cfg(feature = "history")]
use crate::history_tool;
use crate::util::{ensure_owner_token, print_success};
pub struct Password<'a> {
cmd_matches: &'a ArgMatches<'a>,
}
impl<'a> Password<'a> {
pub fn new(cmd_matches: &'a ArgMatches<'a>) -> Self {
Self { cmd_matches }
}
pub fn invoke(&self) -> Result<(), ActionError> {
let matcher_main = MainMatcher::with(self.cmd_matches).unwrap();
let matcher_password = PasswordMatcher::with(self.cmd_matches).unwrap();
let url = matcher_password.url();
let client_config = create_config(&matcher_main);
let client = client_config.client(false);
let mut file = RemoteFile::parse_url(url, matcher_password.owner())?;
#[cfg(feature = "history")]
history_tool::derive_file_properties(&matcher_main, &mut file);
ensure_owner_token(file.owner_token_mut(), &matcher_main, false);
let (password, password_generated) = matcher_password.password();
let result = ApiPassword::new(&file, &password, None).invoke(&client);
if let Err(PasswordError::Expired) = result {
#[cfg(feature = "history")]
history_tool::remove(&matcher_main, &file);
}
result?;
#[cfg(feature = "history")]
history_tool::add(&matcher_main, file, true);
if password_generated {
let mut table = Table::new();
table.set_format(FormatBuilder::new().padding(0, 2).build());
table.add_row(Row::new(vec![
Cell::new("Passphrase:"),
Cell::new(&password),
]));
table.printstd();
}
print_success("Password set");
Ok(())
}
}