use clap::ArgMatches;
use ffsend_api::action::delete::{Delete as ApiDelete, Error as DeleteError};
use ffsend_api::file::remote_file::{FileParseError, RemoteFile};
use crate::client::create_config;
use crate::cmd::matcher::{delete::DeleteMatcher, main::MainMatcher, Matcher};
use crate::error::ActionError;
#[cfg(feature = "history")]
use crate::history_tool;
use crate::util::{ensure_owner_token, print_success};
pub struct Delete<'a> {
cmd_matches: &'a ArgMatches<'a>,
}
impl<'a> Delete<'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_delete = DeleteMatcher::with(self.cmd_matches).unwrap();
let url = matcher_delete.url();
let client_config = create_config(&matcher_main);
let client = client_config.client(false);
let mut file = RemoteFile::parse_url(url, matcher_delete.owner())?;
#[cfg(feature = "history")]
history_tool::derive_file_properties(&matcher_main, &mut file);
ensure_owner_token(file.owner_token_mut(), &matcher_main, false);
let result = ApiDelete::new(&file, None).invoke(&client);
if let Err(DeleteError::Expired) = result {
#[cfg(feature = "history")]
history_tool::remove(&matcher_main, &file);
}
result?;
#[cfg(feature = "history")]
history_tool::remove(&matcher_main, &file);
print_success("File deleted");
Ok(())
}
}
#[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "invalid share link")]
InvalidUrl(#[cause] FileParseError),
#[fail(display = "the file has expired or did never exist")]
Expired,
#[fail(display = "failed to delete the shared file")]
Delete(#[cause] DeleteError),
}
impl From<FileParseError> for Error {
fn from(err: FileParseError) -> Error {
Error::InvalidUrl(err)
}
}
impl From<DeleteError> for Error {
fn from(err: DeleteError) -> Error {
match err {
DeleteError::Expired => Error::Expired,
err => Error::Delete(err),
}
}
}