From 14e01792e33631d134fe895018d3bef5ea74a958 Mon Sep 17 00:00:00 2001 From: metamuffin Date: Wed, 2 Aug 2023 01:03:16 +0200 Subject: move client code to its own crate --- client/src/lib.rs | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 client/src/lib.rs (limited to 'client/src/lib.rs') diff --git a/client/src/lib.rs b/client/src/lib.rs new file mode 100644 index 0000000..a4d0b01 --- /dev/null +++ b/client/src/lib.rs @@ -0,0 +1,70 @@ +use reqwest::Client; +use serde_json::json; +use std::time::Duration; + +pub struct Instance { + pub host: String, + pub tls: bool, +} +pub struct Session(pub String); + +impl Instance { + pub fn base(&self) -> String { + format!( + "{}://{}", + if self.tls { "https" } else { "http" }, + self.host + ) + } +} +impl Session { + pub fn session_param(&self) -> String { + format!("session={}", self.0) + } +} + +pub fn stream( + instance: &Instance, + session: &Session, + id: &str, + tracks: &[usize], + webm: bool, +) -> String { + format!( + "{}/n/{}/stream?tracks={}&webm={}&{}", + instance.base(), + id, + tracks + .iter() + .map(|v| format!("{v}")) + .collect::>() + .join(","), + if webm { "1" } else { "0" }, + session.session_param() + ) +} + +pub async fn login( + instance: &Instance, + username: String, + password: String, + expire: Duration, +) -> anyhow::Result { + let p = serde_json::to_string(&json!({ + "expire": expire.as_secs(), + "password": password, + "username": username, + })) + .unwrap(); + + let r = Client::builder() + .build()? + .post(format!("{}/api/account/login", instance.base())) + .body(p) + .send() + .await? + .json() + .await?; + + Ok(Session(r)) +} -- cgit v1.2.3-70-g09d2