Formatting and cleanup

This commit is contained in:
Maxime Augier 2024-08-09 17:08:13 +02:00
parent dbbfbadf7f
commit 28fdd10e0a
3 changed files with 32 additions and 32 deletions

View File

@ -246,7 +246,7 @@ pub enum ApiError {
FormatError(#[from] chrono::ParseError),
#[error("Invalid ID: {0:?}")]
InvalidID(String)
InvalidID(String),
}
impl From<ureq::Error> for ApiError {
@ -268,7 +268,7 @@ impl JsonExplicitError for ureq::Response {
}
}
#[derive(Debug,Error)]
#[derive(Debug, Error)]
pub enum TokenParseError {
#[error("Bad line count")]
IncorrectLineCount,
@ -278,7 +278,6 @@ pub enum TokenParseError {
}
impl Context {
fn from_login_response(resp: LoginResponse) -> Self {
Self {
auth_header: format!("Bearer {}", &resp.access_token),
@ -288,12 +287,17 @@ impl Context {
}
}
pub fn from_saved(saved: &str) -> Result<Self,TokenParseError> {
pub fn from_saved(saved: &str) -> Result<Self, TokenParseError> {
let lines: Vec<&str> = saved.lines().collect();
let &[token, refresh, expire] = &*lines else { return Err(TokenParseError::IncorrectLineCount) };
let &[token, refresh, expire] = &*lines else {
return Err(TokenParseError::IncorrectLineCount);
};
let expire: u64 = expire.parse()?;
let token_expiration = Instant::now() + (UNIX_EPOCH + Duration::from_secs(expire)).duration_since(SystemTime::now()).unwrap_or_default();
let token_expiration = Instant::now()
+ (UNIX_EPOCH + Duration::from_secs(expire))
.duration_since(SystemTime::now())
.unwrap_or_default();
Ok(Self {
auth_header: format!("Bearer {}", token),
@ -309,9 +313,15 @@ impl Context {
}
pub fn save(&self) -> String {
let expiration = (SystemTime::now() + (self.token_expiration - Instant::now())).duration_since(UNIX_EPOCH)
let expiration = (SystemTime::now() + (self.token_expiration - Instant::now()))
.duration_since(UNIX_EPOCH)
.unwrap();
format!("{}\n{}\n{}\n", self.auth_token(), self.refresh_token, expiration.as_secs())
format!(
"{}\n{}\n{}\n",
self.auth_token(),
self.refresh_token,
expiration.as_secs()
)
}
/// Retrieve access tokens online, by logging in with the provided credentials
@ -382,7 +392,7 @@ impl Context {
pub fn charger(&mut self, id: &str) -> Result<Charger, ApiError> {
if !id.chars().all(char::is_alphanumeric) {
return Err(ApiError::InvalidID(id.to_owned()))
return Err(ApiError::InvalidID(id.to_owned()));
}
self.get(&format!("chargers/{}", id))
}
@ -512,7 +522,6 @@ impl Charger {
}
}
#[cfg(test)]
mod test {
use std::time::{Duration, Instant};
@ -532,7 +541,6 @@ mod test {
assert_eq!(&ctx.auth_header, &ctx2.auth_header);
assert_eq!(&ctx.refresh_token, &ctx2.refresh_token);
assert!( (ctx.token_expiration - ctx2.token_expiration) < Duration::from_secs(5))
assert!((ctx.token_expiration - ctx2.token_expiration) < Duration::from_secs(5))
}
}

View File

@ -122,4 +122,15 @@ impl Stream {
let json = self.buffer.pop().unwrap();
Ok(Message::from_json(json)?)
}
pub fn invoke(
&mut self,
target: &str,
args: serde_json::Value,
) -> Result<(), tungstenite::Error> {
self.ws.send(json!( { "arguments": args,
"invocationId": "0",
"target": target,
"type": 1} ))
}
}

View File

@ -45,31 +45,12 @@ pub struct Stream {
impl Stream {
pub fn open(ctx: &mut Context) -> Result<Stream, NegotiateError> {
let r: NegotiateResponse = ctx.post_raw(STREAM_API_NEGOTIATION_URL, &())?;
dbg!(&r);
let token = ctx.auth_token();
let wss_url = format!(
"{}?id={}&access_token={}",
WSS_URL, r.connection_token, token
);
dbg!(&wss_url);
/*
let req = tungstenite::http::Request::builder()
.uri(WSS_URL)
.header("Accept", "* / *")
.header("Host", "streams.easee.com")
.header("Origin", "https://portal.easee.com")
.header("Connection", "keep-alive, Upgrade")
.header("Upgrade", "websocket")
.header("Sec-WebSocket-Version", "13")
.header("Sec-WebSocket-Key", tungstenite::handshake::client::generate_key())
.header("Sec-Fetch-Dest", "websocket")
.header("Sec-Fetch-Mode", "websocket")
.header("Sec-Fetch-Site", "same-site")
.header("Cookie", format!("easee_skaat=\"{}\"", token))
.body(()).unwrap();
*/
let resp = tungstenite::client::connect(&wss_url);