De-duplicate Code

This commit is contained in:
Neshura 2024-05-06 20:53:50 +02:00
parent 962d90fe1d
commit c8d7053b87
Signed by: Neshura
GPG key ID: B6983AAA6B9A7A6C

View file

@ -9,6 +9,7 @@ use lemmy_db_schema::newtypes::{CommunityId, PostId};
use lemmy_db_schema::{ListingType, PostFeatureType}; use lemmy_db_schema::{ListingType, PostFeatureType};
use reqwest::StatusCode; use reqwest::StatusCode;
use std::collections::HashMap; use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use url::Url; use url::Url;
use systemd_journal_logger::connected_to_journal; use systemd_journal_logger::connected_to_journal;
@ -88,68 +89,21 @@ pub(crate) async fn login(config: &Config) -> Result<Lemmy, ()> {
impl Lemmy { impl Lemmy {
pub(crate) async fn post(&self, post: CreatePost) -> Result<PostId, ()> { pub(crate) async fn post(&self, post: CreatePost) -> Result<PostId, ()> {
let response = match HTTP_CLIENT let response = self.fetch_data_json("/api/v3/post", &post).await?;
.post(format!("{}/api/v3/post", &self.instance))
.bearer_auth(&self.jwt_token.to_string())
.json(&post)
.send()
.await
{
Ok(data) => match data.text().await {
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
},
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
};
let json_data = match serde_json::from_str::<HashMap<&str, PostView>>(&response) { let json_data: PostView = self.parse_json(&response).await?;
Ok(mut data) => data.remove("post_view").expect("Element should be present"),
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
};
Ok(json_data.post.id) Ok(json_data.post.id)
} }
async fn feature(&self, params: FeaturePost) -> Result<PostView, ()> { async fn feature(&self, params: FeaturePost) -> Result<PostView, ()> {
let response = match HTTP_CLIENT let response = self.fetch_data_json("/api/v3/post/feature", &params).await?;
.post(format!("{}/api/v3/post/feature", &self.instance))
.bearer_auth(&self.jwt_token.to_string())
.json(&params)
.send()
.await
{
Ok(data) => match data.text().await {
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
},
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
};
let json_data = match serde_json::from_str::<HashMap<&str, PostView>>(&response) { let json_data = match serde_json::from_str::<HashMap<&str, PostView>>(&response) {
Ok(mut data) => data.remove("post_view").expect("Element should be present"), Ok(mut data) => data.remove("post_view").expect("Element should be present"),
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); return Err(());
} }
}; };
@ -182,36 +136,9 @@ impl Lemmy {
..Default::default() ..Default::default()
}; };
let response = match HTTP_CLIENT let response = self.fetch_data_query("/api/v3/post/list", &list_params).await?;
.get(format!("{}/api/v3/post/list", &self.instance))
.bearer_auth(&self.jwt_token.to_string())
.query(&list_params)
.send()
.await
{
Ok(data) => match data.text().await {
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
},
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
};
let json_data: GetPostsResponse = match serde_json::from_str(&response) { let json_data: GetPostsResponse = self.parse_json(&response).await?;
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
};
Ok(json_data Ok(json_data
.posts .posts
@ -227,36 +154,9 @@ impl Lemmy {
..Default::default() ..Default::default()
}; };
let response = match HTTP_CLIENT let response = self.fetch_data_query("/api/v3/post/list", &list_params).await?;
.get(format!("{}/api/v3/post/list", &self.instance))
.bearer_auth(&self.jwt_token.to_string())
.query(&list_params)
.send()
.await
{
Ok(data) => match data.text().await {
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
},
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
};
let json_data: GetPostsResponse = match serde_json::from_str(&response) { let json_data: GetPostsResponse = self.parse_json(&response).await?;
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
}
};
Ok(json_data Ok(json_data
.posts .posts
@ -272,15 +172,43 @@ impl Lemmy {
..Default::default() ..Default::default()
}; };
let response = match HTTP_CLIENT let response = self.fetch_data_query("/api/v3/community/list", &list_params).await?;
.get(format!("{}/api/v3/community/list", &self.instance))
let json_data: ListCommunitiesResponse = self.parse_json(&response).await?;
let mut communities: HashMap<String, CommunityId> = HashMap::new();
for community_view in json_data.communities {
let community = community_view.community;
communities.insert(community.name, community.id);
}
Ok(communities)
}
async fn fetch_data_json<T: Serialize>(&self, route: &str, json: &T ) -> Result<String,()> {
let res = HTTP_CLIENT
.post(format!("{}{route}", self.instance))
.bearer_auth(&self.jwt_token.to_string()) .bearer_auth(&self.jwt_token.to_string())
.query(&list_params) .json(&json)
.send() .send()
.await .await;
{ self.extract_data(res).await
}
async fn fetch_data_query<T: Serialize>(&self, route: &str, json: &T ) -> Result<String,()> {
let res = HTTP_CLIENT
.post(format!("{}{route}", self.instance))
.bearer_auth(&self.jwt_token.to_string())
.query(&json)
.send()
.await;
self.extract_data(res).await
}
async fn extract_data(&self, response: Result<reqwest::Response, reqwest::Error>) -> Result<String,()> {
match response {
Ok(data) => match data.text().await { Ok(data) => match data.text().await {
Ok(data) => data, Ok(data) => Ok(data),
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
error!(err_msg); error!(err_msg);
@ -292,23 +220,17 @@ impl Lemmy {
error!(err_msg); error!(err_msg);
Err(()) Err(())
} }
}; }
}
let json_data: ListCommunitiesResponse = match serde_json::from_str(&response) { async fn parse_json<'a, T: Deserialize<'a>>(&self, response: &'a str) -> Result<T,()> {
Ok(data) => data, match serde_json::from_str::<HashMap<&str, T>>(response) {
Ok(mut data) => Ok(data.remove("post_view").expect("Element should be present")),
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
error!(err_msg); error!(err_msg);
Err(()) Err(())
} }
};
let mut communities: HashMap<String, CommunityId> = HashMap::new();
for community_view in json_data.communities {
let community = community_view.community;
communities.insert(community.name, community.id);
} }
Ok(communities)
} }
} }