use reqwest::{Client,Response}; use std::error::Error; // TODO: implement dry-run logic pub struct HedgeDoc { server_url : String, is_dry_run : bool, client : Client, } impl HedgeDoc { pub fn new( server_url: &str, is_dry_run: bool ) -> Self { Self { server_url: server_url.to_string(), is_dry_run, client: Client::new() } } pub fn format_url( &self, pad_name: &str ) -> String { format!( "{}/{}", self.server_url, pad_name ) } fn format_action( &self, pad_name: &str, verb: &str ) -> String { format!( "{}/{}/{}", self.server_url, pad_name, verb ) } async fn do_request( &self, url : &str ) -> Result> { Ok(self.client.get( url ).send().await?) } fn get_id_from_response( &self, res : Response ) -> String { res.url().to_string().trim_start_matches( &format!( "{}/", self.server_url ) ).to_string() } pub async fn download( &self, pad_name: &str ) -> Result> { Ok(self.do_request( &self.format_action(pad_name, "download") ).await?.text().await?) } pub async fn create_pad( &self ) -> Result> { let res = self.do_request( &format!( "{}/new", self.server_url ) ).await?; if res.status().is_success() { Ok(self.get_id_from_response(res)) } else { Err( format!("Failed to create pad {}\n{}", res.status(), res.text().await?).into() ) } } pub async fn import_note( &self, id: Option<&str>, content: String ) -> Result> { let url = match id { Some(id) => self.format_url( &format!( "new/{id}" ) ), None => self.format_url("new"), }; let res = self.client.post(&url) .header( "Content-Type", "text/markdown" ) .body(content) .send() .await?; if res.status().is_success() { Ok(self.get_id_from_response(res)) } else { Err( format!("Failed to import note: {}\n{}", res.status(), res.text().await?).into() ) } } }