From be04fb276aa4777f5477c579fc82f1cef9b18d65 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Fri, 12 Jan 2024 17:27:29 +0100 Subject: Make channel_stream return error on auth failure Also reenables the relevant tests. --- src/error.rs | 30 +++++++++++++++++++++++++++++- src/lib.rs | 1 + src/zotapi.rs | 15 ++++++++++++--- 3 files changed, 42 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/error.rs b/src/error.rs index 2954bea..23cc452 100644 --- a/src/error.rs +++ b/src/error.rs @@ -15,7 +15,7 @@ // along with this program. If not, see . use reqwest; -use std; +use std::fmt::Display; #[derive(Debug)] pub enum Error { @@ -29,12 +29,40 @@ pub enum Error { Unknown, } +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::APIError(s) => write!(f, "APIError: {}", s)?, + Self::Http(e) => write!(f, "Http: {}", e.to_string())?, + Self::Io(e) => write!(f, "Io: {}", e.to_string())?, + Self::Json(e) => write!(f, "Json: {}", e.to_string())?, + Self::ParseError(e) => write!(f, "URL: {}", e.to_string())?, + Self::Qs(e) => write!(f, "Qs: {}", e.to_string())?, + Self::Unauthorized => write!(f, "unauthorized")?, + _ => write!(f, "unknown error")?, + }; + + Ok(()) + } +} + +impl std::error::Error for Error {} + impl From for Error { fn from(e: reqwest::Error) -> Error { Error::Http(e) } } +impl From for Error { + fn from(s: reqwest::StatusCode) -> Error { + match s { + reqwest::StatusCode::UNAUTHORIZED => Error::Unauthorized, + _ => Error::Unknown, + } + } +} + impl From for Error { fn from(e: std::io::Error) -> Error { Error::Io(e) diff --git a/src/lib.rs b/src/lib.rs index d1df0ad..8f94a8d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,6 +42,7 @@ pub use verify::Channel; pub use xchan::XChan; // pub use zotapi::ZotAPI; pub use zotapi::new; +pub use zotapi::ZotApi; #[cfg(test)] mod tests { diff --git a/src/zotapi.rs b/src/zotapi.rs index 5a2f5cc..0a5c317 100644 --- a/src/zotapi.rs +++ b/src/zotapi.rs @@ -14,7 +14,10 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use crate::Channel; +use crate::{ + Channel, + Error, +}; use url::Url; use reqwest::{ self, @@ -73,8 +76,14 @@ impl ZotApi { /** * Return the channel stream as json. */ - pub async fn channel_stream(&self) -> Result> { - Ok(self.get("channel/stream").send().await?.text().await?) + pub async fn channel_stream(&self) -> Result { + let response = self.get("channel/stream").send().await?; + + if response.status().is_success() { + Ok(response.text().await?) + } else { + Err(response.status().into()) + } } /** -- cgit v1.2.3