Compare commits

..

5 commits

16 changed files with 142 additions and 110 deletions

View file

@ -6,10 +6,9 @@ use log::{debug, warn};
use crate::{
cachefile::CacheFile,
cli::Cli,
error,
file::{Chunk, FileTrait},
output::new_progressbar,
sharry::Client,
sharry::{Client, ShareID},
};
pub struct AppState {
@ -33,7 +32,7 @@ fn new_http(args: &Cli) -> ureq::Agent {
.into()
}
fn new_share(args: &Cli) -> error::Result<String> {
fn new_share(args: &Cli) -> crate::Result<ShareID> {
new_http(args).share_create(&args.get_uri(), &args.alias, args.get_share_request())
}
@ -46,11 +45,11 @@ impl AppState {
}
}
pub fn try_resume(args: &Cli) -> error::Result<Self> {
pub fn try_resume(args: &Cli) -> crate::Result<Self> {
Ok(Self::new(new_http(args), CacheFile::try_resume(args)?))
}
pub fn from_args(args: &Cli) -> error::Result<Self> {
pub fn from_args(args: &Cli) -> crate::Result<Self> {
Ok(Self::new(
new_http(args),
CacheFile::from_args(args, new_share)?,
@ -87,7 +86,7 @@ impl AppState {
self.with_progressbar(f, true);
}
fn next_chunk<'t>(&mut self, buffer: &'t mut [u8]) -> error::Result<Option<Chunk<'t>>> {
fn next_chunk<'t>(&mut self, buffer: &'t mut [u8]) -> crate::Result<Option<Chunk<'t>>> {
if self.inner.get_uploading(&self.http)?.is_none() {
return Ok(None);
}
@ -103,7 +102,7 @@ impl AppState {
Ok(Some(chunk))
}
pub fn upload_chunk(&mut self, buffer: &mut [u8]) -> error::Result<bool> {
pub fn upload_chunk(&mut self, buffer: &mut [u8]) -> crate::Result<bool> {
let Some(chunk) = self.next_chunk(buffer)? else {
self.inner
.share_notify(&self.http)
@ -136,7 +135,7 @@ impl AppState {
self.drop_progressbar(ProgressBar::abandon);
}
pub fn rebuild_share(self, args: &Cli) -> error::Result<Self> {
pub fn rebuild_share(self, args: &Cli) -> crate::Result<Self> {
Ok(Self::new(self.http, CacheFile::from_args(args, new_share)?))
}

View file

@ -11,7 +11,7 @@ use console::{StyledObject, style};
use log::{info, trace};
use shrupl::{
AppState, Cli, error,
AppState, Cli,
output::{self, Log, SHRUPL},
};
@ -86,16 +86,16 @@ fn main() {
Err(e) => {
Log::handle(&e);
if let error::Error::InvalidParameter(p) = e {
if let shrupl::Error::InvalidParameter(p) = e {
match p {
// Error 404 (File not found)
error::Parameter::FileID(fid) => {
shrupl::Parameter::FileID(fid) => {
info!("retrying file {fid:?}");
state.abort_upload();
}
// Error 404 (Share not found)
error::Parameter::ShareID(sid) => {
shrupl::Parameter::ShareID(sid) => {
output::prompt_rebuild_share();
info!("rebuilding share {sid:?}");

View file

@ -12,10 +12,9 @@ use serde::{Deserialize, Serialize};
use crate::{
cli::Cli,
error,
file::{self, Chunk, FileTrait},
output::new_progressbar,
sharry::{Client, Uri},
sharry::{AliasID, Client, ShareID, Uri},
};
#[derive(Serialize, Deserialize, Debug)]
@ -24,8 +23,8 @@ pub struct CacheFile {
file_name: PathBuf,
uri: Uri,
alias_id: String,
share_id: String,
alias_id: AliasID,
share_id: ShareID,
uploading: Option<file::Uploading>,
files: VecDeque<file::Checked>,
@ -48,7 +47,7 @@ impl CacheFile {
file_name
}
pub fn try_resume(args: &Cli) -> error::Result<Self> {
pub fn try_resume(args: &Cli) -> crate::Result<Self> {
let file_name = Self::cache_file(args);
let state: Self = {
@ -61,7 +60,7 @@ impl CacheFile {
fn check_hash<'a>(
file: &'a impl FileTrait<'a>,
bar: &ProgressBar,
) -> error::Result<()> {
) -> crate::Result<()> {
bar.set_message(format!("checking {:?}", file.get_name()));
file.check_hash(|bytes| bar.inc(bytes))
}
@ -98,8 +97,8 @@ impl CacheFile {
pub fn from_args(
args: &Cli,
new_share: impl FnOnce(&Cli) -> error::Result<String>,
) -> error::Result<Self> {
new_share: impl FnOnce(&Cli) -> crate::Result<ShareID>,
) -> crate::Result<Self> {
let mut files = args.files.clone();
if args.should_hash() {
@ -135,7 +134,7 @@ impl CacheFile {
pub fn get_uploading(
&mut self,
client: &impl Client,
) -> error::Result<Option<&mut file::Uploading>> {
) -> crate::Result<Option<&mut file::Uploading>> {
if self.uploading.is_some() {
Ok(self.uploading.as_mut())
} else if let Some(chk) = self.files.pop_front() {
@ -189,11 +188,11 @@ impl CacheFile {
);
}
pub fn share_notify(&self, client: &impl Client) -> error::Result<()> {
pub fn share_notify(&self, client: &impl Client) -> crate::Result<()> {
client.share_notify(&self.uri, &self.alias_id, &self.share_id)
}
pub fn file_patch(&self, client: &impl Client, chunk: &Chunk) -> error::Result<()> {
pub fn file_patch(&self, client: &impl Client, chunk: &Chunk) -> crate::Result<()> {
client.file_patch(&self.uri, &self.alias_id, &self.share_id, chunk)
}

View file

@ -11,7 +11,7 @@ use log::LevelFilter;
use crate::{
file::{Checked, FileTrait},
sharry::{NewShareRequest, Uri},
sharry::{AliasID, NewShareRequest, Uri},
};
#[derive(Parser)]
@ -69,7 +69,7 @@ pub struct Cli {
url: String,
/// ID of a public alias to use
pub alias: String,
pub alias: AliasID,
/// Files to upload to the new share
#[arg(value_name = "FILE", required = true, value_parser = parse_sharry_file)]
@ -159,7 +159,7 @@ impl Cli {
let mut hasher = Blake2b::new().hash_length(16).to_state();
hasher.update(self.get_uri().as_ref());
hasher.update(self.alias.as_bytes());
hasher.update(self.alias.as_ref());
for chk in sorted(&self.files) {
hasher.update(chk.as_ref());

View file

@ -8,10 +8,10 @@ pub enum Parameter {
Uri(String),
#[error("given Alias ID {0:?}")]
AliasID(String),
AliasID(sharry::AliasID),
#[error("stored Share ID {0:?}")]
ShareID(String),
ShareID(sharry::ShareID),
#[error("stored {0:?}")]
FileID(sharry::FileID),
@ -75,8 +75,7 @@ impl Error {
pub fn is_fatal(&self) -> bool {
match self {
Self::InvalidParameter(p) => p.is_fatal(),
Self::Mismatch { .. } => true,
Self::Unknown(_) => true,
Self::Mismatch { .. } | Self::Unknown(_) => true,
_ => false,
}
}

View file

@ -5,7 +5,7 @@ use std::{
use serde::{Deserialize, Serialize};
use crate::{error, sharry};
use crate::sharry;
use super::{FileTrait, Uploading};
@ -53,9 +53,9 @@ impl Checked {
}
}
pub fn hash(&mut self, f: impl Fn(u64)) -> error::Result<()> {
pub fn hash(&mut self, f: impl Fn(u64)) -> crate::Result<()> {
if self.hash.is_some() {
return Err(error::Error::mismatch("unhashed file", self.path.display()));
return Err(crate::Error::mismatch("unhashed file", self.path.display()));
}
self.hash = Some(super::compute_file_hash(&self.path, self.size, f)?);
@ -76,9 +76,9 @@ impl Checked {
self,
client: &impl sharry::Client,
uri: &sharry::Uri,
alias_id: &str,
share_id: &str,
) -> error::Result<Uploading> {
alias_id: &sharry::AliasID,
share_id: &sharry::ShareID,
) -> crate::Result<Uploading> {
let file_id = client.file_create(uri, alias_id, share_id, &self)?;
Ok(Uploading::new(self.path, self.size, self.hash, file_id))
@ -98,7 +98,7 @@ impl<'t> FileTrait<'t> for Checked {
self.size
}
fn check_hash(&self, on_progress: impl Fn(u64)) -> error::Result<()> {
fn check_hash(&self, on_progress: impl Fn(u64)) -> crate::Result<()> {
super::check_file_hash(&self.path, self.size, self.hash.as_ref(), on_progress)
}
}

View file

@ -12,9 +12,8 @@ pub use chunk::Chunk;
use log::{debug, warn};
pub use uploading::Uploading;
use crate::error;
fn compute_file_hash(path: &Path, size: u64, on_progress: impl Fn(u64)) -> error::Result<String> {
fn compute_file_hash(path: &Path, size: u64, on_progress: impl Fn(u64)) -> crate::Result<String> {
let mut file = fs::File::open(path)?;
let mut hasher = Blake2b::new().hash_length(64).to_state();
@ -33,7 +32,7 @@ fn compute_file_hash(path: &Path, size: u64, on_progress: impl Fn(u64)) -> error
}
if bytes_read != size {
return Err(error::Error::mismatch(size, bytes_read));
return Err(crate::Error::mismatch(size, bytes_read));
}
let result = Base64::encode_string(hasher.finalize().as_bytes());
@ -46,9 +45,9 @@ fn check_file_hash(
size: u64,
hash: Option<&String>,
on_progress: impl Fn(u64),
) -> error::Result<()> {
) -> crate::Result<()> {
let Some(expected) = hash else {
return Err(error::Error::mismatch("hash", path.display()));
return Err(crate::Error::mismatch("hash", path.display()));
};
let actual = &compute_file_hash(path, size, on_progress)?;
@ -58,7 +57,7 @@ fn check_file_hash(
Ok(())
} else {
warn!("hash mismatch for file {:?}", path.display());
Err(error::Error::mismatch(expected, actual))
Err(crate::Error::mismatch(expected, actual))
}
}
@ -80,5 +79,5 @@ pub trait FileTrait<'t> {
/// get the file's size
fn get_size(&self) -> u64;
fn check_hash(&self, on_progress: impl Fn(u64)) -> error::Result<()>;
fn check_hash(&self, on_progress: impl Fn(u64)) -> crate::Result<()>;
}

View file

@ -7,7 +7,7 @@ use std::{
use log::warn;
use serde::{Deserialize, Serialize};
use crate::{error, sharry};
use crate::sharry;
use super::{Checked, Chunk, FileTrait};
@ -108,7 +108,7 @@ impl<'t> FileTrait<'t> for Uploading {
self.size
}
fn check_hash(&self, on_progress: impl Fn(u64)) -> error::Result<()> {
fn check_hash(&self, on_progress: impl Fn(u64)) -> crate::Result<()> {
super::check_file_hash(&self.path, self.size, self.hash.as_ref(), on_progress)
}
}

View file

@ -1,32 +1,31 @@
use log::{debug, trace};
use crate::{
error,
file::{self, FileTrait},
sharry::{self, FileID, Uri},
sharry::{self, AliasID, FileID, ShareID, Uri},
};
fn find_cause(
uri: &Uri,
alias_id: &str,
share_id: Option<&str>,
alias_id: &AliasID,
share_id: Option<&ShareID>,
file_id: Option<&FileID>,
) -> impl FnOnce(ureq::Error) -> error::Error {
) -> impl FnOnce(ureq::Error) -> crate::Error {
move |error| match error {
ureq::Error::StatusCode(403) => {
trace!("HTTP Error 403: Alias not found!");
error::Error::InvalidParameter(error::Parameter::AliasID(alias_id.to_owned()))
crate::Error::InvalidParameter(crate::Parameter::AliasID(alias_id.to_owned()))
}
ureq::Error::StatusCode(404) => {
trace!("HTTP Error 404: Share and/or file may have been deleted!");
if let Some(file_id) = file_id {
error::Error::InvalidParameter(error::Parameter::FileID(file_id.clone()))
crate::Error::InvalidParameter(crate::Parameter::FileID(file_id.to_owned()))
} else if let Some(share_id) = share_id {
error::Error::InvalidParameter(error::Parameter::ShareID(share_id.to_owned()))
crate::Error::InvalidParameter(crate::Parameter::ShareID(share_id.to_owned()))
} else {
error::Error::InvalidParameter(error::Parameter::Uri(uri.to_string()))
crate::Error::InvalidParameter(crate::Parameter::Uri(uri.to_string()))
}
}
ureq::Error::Io(error) => {
@ -34,7 +33,7 @@ fn find_cause(
if let Some(msg) = error.get_ref().map(ToString::to_string) {
if msg.starts_with("failed to lookup address information") {
error::Error::InvalidParameter(error::Parameter::Uri(uri.to_string()))
crate::Error::InvalidParameter(crate::Parameter::Uri(uri.to_string()))
} else {
error.into()
}
@ -42,7 +41,7 @@ fn find_cause(
error.into()
}
}
error => error::Error::Unknown(error.to_string()),
error => crate::Error::Unknown(error.to_string()),
}
}
@ -50,24 +49,24 @@ impl sharry::Client for ureq::Agent {
fn share_create(
&self,
uri: &Uri,
alias_id: &str,
alias_id: &AliasID,
data: sharry::NewShareRequest,
) -> error::Result<String> {
) -> crate::Result<ShareID> {
let res = {
let endpoint = uri.share_create();
let mut res = self
.post(&endpoint)
.header("Sharry-Alias", alias_id)
.header("Sharry-Alias", alias_id.as_ref())
.send_json(data)
.map_err(find_cause(uri, alias_id, None, None))?;
trace!("{endpoint:?} response: {res:?}");
error::Error::res_status_check(res.status(), ureq::http::StatusCode::OK)?;
crate::Error::res_status_check(res.status(), ureq::http::StatusCode::OK)?;
res.body_mut()
.read_json::<sharry::NewShareResponse>()
.map_err(error::Error::response)?
.map_err(crate::Error::response)?
};
debug!("{res:?}");
@ -75,28 +74,28 @@ impl sharry::Client for ureq::Agent {
if res.success && (res.message == "Share created.") {
trace!("new share id: {:?}", res.id);
Ok(res.id)
Ok(res.id.into())
} else {
Err(error::Error::response(format!("{res:?}")))
Err(crate::Error::response(format!("{res:?}")))
}
}
fn share_notify(&self, uri: &Uri, alias_id: &str, share_id: &str) -> error::Result<()> {
fn share_notify(&self, uri: &Uri, alias_id: &AliasID, share_id: &ShareID) -> crate::Result<()> {
let res = {
let endpoint = uri.share_notify(share_id);
let mut res = self
.post(&endpoint)
.header("Sharry-Alias", alias_id)
.header("Sharry-Alias", alias_id.as_ref())
.send_empty()
.map_err(find_cause(uri, alias_id, Some(share_id), None))?;
trace!("{endpoint:?} response: {res:?}");
error::Error::res_status_check(res.status(), ureq::http::StatusCode::OK)?;
crate::Error::res_status_check(res.status(), ureq::http::StatusCode::OK)?;
res.body_mut()
.read_json::<sharry::NotifyShareResponse>()
.map_err(error::Error::response)?
.map_err(crate::Error::response)?
};
debug!("{res:?}");
@ -107,30 +106,30 @@ impl sharry::Client for ureq::Agent {
fn file_create(
&self,
uri: &Uri,
alias_id: &str,
share_id: &str,
alias_id: &AliasID,
share_id: &ShareID,
file: &file::Checked,
) -> error::Result<FileID> {
) -> crate::Result<FileID> {
let res = {
let endpoint = uri.file_create(share_id);
let res = self
.post(&endpoint)
.header("Sharry-Alias", alias_id)
.header("Sharry-Alias", alias_id.as_ref())
.header("Sharry-File-Name", file.get_name())
.header("Upload-Length", file.get_size())
.send_empty()
.map_err(find_cause(uri, alias_id, Some(share_id), None))?;
trace!("{endpoint:?} response: {res:?}");
error::Error::res_status_check(res.status(), ureq::http::StatusCode::CREATED)?;
crate::Error::res_status_check(res.status(), ureq::http::StatusCode::CREATED)?;
res
};
let location = (res.headers().get("Location"))
.ok_or_else(|| error::Error::response("Location header not found"))?
.ok_or_else(|| crate::Error::response("Location header not found"))?
.to_str()
.map_err(error::Error::response)?
.map_err(crate::Error::response)?
.to_string();
FileID::try_from(location)
@ -139,16 +138,16 @@ impl sharry::Client for ureq::Agent {
fn file_patch(
&self,
uri: &Uri,
alias_id: &str,
share_id: &str,
alias_id: &AliasID,
share_id: &ShareID,
chunk: &file::Chunk,
) -> error::Result<()> {
) -> crate::Result<()> {
let res = {
let endpoint = uri.file_patch(share_id, chunk.get_file_id());
let res = self
.patch(&endpoint)
.header("Sharry-Alias", alias_id)
.header("Sharry-Alias", alias_id.as_ref())
.header("Upload-Offset", chunk.get_offset())
.send(chunk.get_data())
.map_err(find_cause(
@ -159,21 +158,21 @@ impl sharry::Client for ureq::Agent {
))?;
trace!("{endpoint:?} response: {res:?}");
error::Error::res_status_check(res.status(), ureq::http::StatusCode::NO_CONTENT)?;
crate::Error::res_status_check(res.status(), ureq::http::StatusCode::NO_CONTENT)?;
res
};
let res_offset = (res.headers().get("Upload-Offset"))
.ok_or_else(|| error::Error::response("Upload-Offset header not found"))?
.ok_or_else(|| crate::Error::response("Upload-Offset header not found"))?
.to_str()
.map_err(error::Error::response)?
.map_err(crate::Error::response)?
.parse::<u64>()
.map_err(error::Error::response)?;
.map_err(crate::Error::response)?;
if chunk.get_behind() == res_offset {
Ok(())
} else {
Err(error::Error::response(format!(
Err(crate::Error::response(format!(
"Unexpected Upload-Offset: {} (expected {})",
res_offset,
chunk.get_behind()

View file

@ -4,7 +4,7 @@
mod appstate;
mod cachefile;
mod cli;
pub mod error;
mod error;
mod file;
mod impl_ureq;
pub mod output;
@ -12,3 +12,4 @@ mod sharry;
pub use appstate::AppState;
pub use cli::Cli;
pub use error::{Error, Parameter, Result};

View file

@ -48,7 +48,7 @@ pub fn prompt_rebuild_share() {
.interact()
.unwrap_or(false);
if selection == false {
if !selection {
process::exit(0);
}
}
@ -92,7 +92,7 @@ impl Log {
process::exit(1);
}
pub fn handle(e: &crate::error::Error) {
pub fn handle(e: &crate::Error) {
if e.is_fatal() {
// react to fatal error
warn!("fatal error: {e:?}");

View file

@ -4,10 +4,41 @@ use log::{debug, trace};
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::error;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AliasID(String);
// pub struct AliasID(String);
// pub struct ShareID(String);
impl fmt::Display for AliasID {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<[u8]> for AliasID {
fn as_ref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl From<String> for AliasID {
fn from(value: String) -> Self {
Self(value)
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ShareID(String);
impl fmt::Display for ShareID {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<String> for ShareID {
fn from(value: String) -> Self {
Self(value)
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct FileID(String);
@ -19,9 +50,9 @@ impl fmt::Display for FileID {
}
impl TryFrom<String> for FileID {
type Error = error::Error;
type Error = crate::Error;
fn try_from(value: String) -> error::Result<Self> {
fn try_from(value: String) -> crate::Result<Self> {
/// Pattern breakdown:
/// - `^([^:/?#]+)://` scheme (anything but `:/?#`) + `"://"`
/// - `([^/?#]+)` authority/host (anything but `/?#`)
@ -50,7 +81,7 @@ impl TryFrom<String> for FileID {
Ok(result)
} else {
Err(error::Error::mismatch(
Err(crate::Error::mismatch(
"<proto>://<base>/api/v2/alias/upload/<share>/files/tus/<file>",
value,
))
@ -110,7 +141,7 @@ mod tests {
let err = FileID::try_from(bad.to_string()).expect_err("URL should not parse");
// make sure it's the Mismatch variant, and that it contains the original input
match err {
error::Error::Mismatch { expected, actual } => {
crate::Error::Mismatch { expected, actual } => {
assert_eq!(
expected, "<proto>://<base>/api/v2/alias/upload/<share>/files/tus/<file>",
"Error should output expected format"

View file

@ -2,6 +2,6 @@ mod id;
mod json;
mod uri;
pub use id::FileID;
pub use id::{AliasID, FileID, ShareID};
pub use json::{NewShareRequest, NewShareResponse, NotifyShareResponse};
pub use uri::Uri;

View file

@ -33,15 +33,15 @@ impl Uri {
self.endpoint(format_args!("alias/upload/new"))
}
pub fn share_notify(&self, share_id: &str) -> String {
pub fn share_notify(&self, share_id: &super::ShareID) -> String {
self.endpoint(format_args!("alias/mail/notify/{share_id}"))
}
pub fn file_create(&self, share_id: &str) -> String {
pub fn file_create(&self, share_id: &super::ShareID) -> String {
self.endpoint(format_args!("alias/upload/{share_id}/files/tus"))
}
pub fn file_patch(&self, share_id: &str, file_id: &super::FileID) -> String {
pub fn file_patch(&self, share_id: &super::ShareID, file_id: &super::FileID) -> String {
self.endpoint(format_args!("alias/upload/{share_id}/files/tus/{file_id}"))
}
}

View file

@ -1,30 +1,33 @@
use crate::{error, file};
use crate::file;
use super::api::{FileID, NewShareRequest, Uri};
use super::{
AliasID, ShareID,
api::{FileID, NewShareRequest, Uri},
};
pub trait Client {
fn share_create(
&self,
uri: &Uri,
alias_id: &str,
alias_id: &AliasID,
data: NewShareRequest,
) -> error::Result<String>;
) -> crate::Result<ShareID>;
fn share_notify(&self, uri: &Uri, alias_id: &str, share_id: &str) -> error::Result<()>;
fn share_notify(&self, uri: &Uri, alias_id: &AliasID, share_id: &ShareID) -> crate::Result<()>;
fn file_create(
&self,
uri: &Uri,
alias_id: &str,
share_id: &str,
alias_id: &AliasID,
share_id: &ShareID,
file: &file::Checked,
) -> error::Result<FileID>;
) -> crate::Result<FileID>;
fn file_patch(
&self,
uri: &Uri,
alias_id: &str,
share_id: &str,
alias_id: &AliasID,
share_id: &ShareID,
chunk: &file::Chunk,
) -> error::Result<()>;
) -> crate::Result<()>;
}

View file

@ -1,5 +1,7 @@
mod api;
mod client;
pub use api::{FileID, NewShareRequest, NewShareResponse, NotifyShareResponse, Uri};
pub use api::{
AliasID, FileID, NewShareRequest, NewShareResponse, NotifyShareResponse, ShareID, Uri,
};
pub use client::Client;