use lemmy_api_common::{ community::{GetCommunity, GetCommunityResponse}, lemmy_db_schema::newtypes::CommunityId, person::{Login, LoginResponse}, sensitive::Sensitive, }; use reqwest::Client; use std::fmt; static API_VERSION: i32 = 3; pub fn lemmy_password() -> Result, std::env::VarError> { Ok(Sensitive::new(std::env::var("LEMMY_PASSWORD")?)) } pub fn lemmy_user() -> Sensitive { Sensitive::new(std::env::var("LEMMY_USER").unwrap_or_else(|_| "wordlebot".to_string())) } pub fn lemmy_server() -> String { std::env::var("LEMMY_SERVER").unwrap_or_else(|_| "https://enterprise.lemmy.ml".to_string()) } pub fn lemmy_community() -> String { std::env::var("LEMMY_COMMUNITY").unwrap_or_else(|_| "wordle".to_string()) } pub fn api_url(suffix: &str) -> String { format!("{}/api/v{}/{}", lemmy_server(), API_VERSION, suffix) } #[derive(Debug)] struct LoginFailedError; impl std::error::Error for LoginFailedError {} impl fmt::Display for LoginFailedError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Login failed.") } } pub async fn get_community_id( client: &Client, community_name: String, ) -> Result> { let params = GetCommunity { name: Some(community_name), ..Default::default() }; let response = client .get(api_url("community")) .query(¶ms) .send() .await?; let data = response.json::().await?; Ok(data.community_view.community.id) } pub async fn lemmy_login(client: &Client) -> Result, Box> { println!("Logging in"); let params = Login { username_or_email: lemmy_user(), password: lemmy_password()?, ..Default::default() }; let response = client .post(api_url("user/login")) .json(¶ms) .send() .await?; response.error_for_status_ref()?; let data = response.json::().await?; if let Some(jwt) = data.jwt { return Ok(jwt); } Err(Box::new(LoginFailedError)) }