fix various clippy warnings to improve the code quality

This commit is contained in:
Bnyro 2023-07-18 20:04:13 +02:00
parent 1f54f431f8
commit 785118c6d9
18 changed files with 50 additions and 65 deletions

View File

@ -31,16 +31,16 @@ pub fn upload_image(image: std::path::PathBuf) -> Result<String, reqwest::Error>
let part = Part::bytes(data) let part = Part::bytes(data)
.file_name(file_name) .file_name(file_name)
.mime_str(&mime_type.unwrap().essence_str())?; .mime_str(mime_type.unwrap().essence_str())?;
let form = reqwest::blocking::multipart::Form::new().part("images[]", part); let form = reqwest::blocking::multipart::Form::new().part("images[]", part);
let account = settings::get_current_account(); let account = settings::get_current_account();
let base_url = account.instance_url; let base_url = account.instance_url;
let path = format!("{}/pictrs/image", base_url); let path = format!("{}/pictrs/image", base_url);
let res: UploadImageResponse = CLIENT let res: UploadImageResponse = CLIENT
.post(&path) .post(path)
.header( .header(
"cookie", "cookie",
format!("jwt={}", account.jwt.unwrap().to_string()), format!("jwt={}", account.jwt.unwrap().into_inner()),
) )
.multipart(form) .multipart(form)
.send()? .send()?

View File

@ -25,8 +25,7 @@ pub fn fetch_instances(query_filter: &str) -> std::result::Result<Vec<Instance>,
.filter(|instance| { .filter(|instance| {
instance.software == Some("lemmy".to_owned()) instance.software == Some("lemmy".to_owned())
&& instance.domain.clone().contains(&lowercase_query_filter) && instance.domain.clone().contains(&lowercase_query_filter)
}) }).cloned()
.map(|instance| instance.clone())
.collect::<Vec<Instance>>()), .collect::<Vec<Instance>>()),
None => Ok(vec![]), None => Ok(vec![]),
} }

View File

@ -30,7 +30,7 @@ pub static CLIENT: Lazy<Client> = Lazy::new(|| {
}); });
fn get_api_url() -> String { fn get_api_url() -> String {
format!("{}/api/{}", get_current_account().instance_url, API_VERSION).to_string() format!("{}/api/{}", get_current_account().instance_url, API_VERSION)
} }
fn get_url(path: &str) -> String { fn get_url(path: &str) -> String {
@ -42,7 +42,7 @@ where
T: DeserializeOwned, T: DeserializeOwned,
Params: Serialize + std::fmt::Debug, Params: Serialize + std::fmt::Debug,
{ {
CLIENT.get(&get_url(path)).query(&params).send()?.json() CLIENT.get(get_url(path)).query(&params).send()?.json()
} }
fn post<T, Params>(path: &str, params: &Params) -> Result<T, reqwest::Error> fn post<T, Params>(path: &str, params: &Params) -> Result<T, reqwest::Error>
@ -50,7 +50,7 @@ where
T: DeserializeOwned, T: DeserializeOwned,
Params: Serialize + std::fmt::Debug, Params: Serialize + std::fmt::Debug,
{ {
CLIENT.post(&get_url(path)).json(&params).send()?.json() CLIENT.post(get_url(path)).json(&params).send()?.json()
} }
fn put<T, Params>(path: &str, params: &Params) -> Result<T, reqwest::Error> fn put<T, Params>(path: &str, params: &Params) -> Result<T, reqwest::Error>
@ -58,5 +58,5 @@ where
T: DeserializeOwned, T: DeserializeOwned,
Params: Serialize + std::fmt::Debug, Params: Serialize + std::fmt::Debug,
{ {
CLIENT.put(&get_url(path)).json(&params).send()?.json() CLIENT.put(get_url(path)).json(&params).send()?.json()
} }

View File

@ -43,7 +43,7 @@ pub fn get_comments(post_id: PostId) -> Result<Vec<CommentView>, reqwest::Error>
let mut grouped_comments: Vec<CommentView> = vec![]; let mut grouped_comments: Vec<CommentView> = vec![];
for (_, comments_group) in &comments for (_, comments_group) in &comments
.iter() .iter()
.group_by(|a| a.comment.path.split(".").collect::<Vec<&str>>()[1].to_owned()) .group_by(|a| a.comment.path.split('.').collect::<Vec<&str>>()[1].to_owned())
{ {
let mut group = comments_group.collect::<Vec<&CommentView>>(); let mut group = comments_group.collect::<Vec<&CommentView>>();
group.sort_by(|a, b| a.comment.path.partial_cmp(&b.comment.path).unwrap()); group.sort_by(|a, b| a.comment.path.partial_cmp(&b.comment.path).unwrap());

View File

@ -168,7 +168,7 @@ impl FactoryComponent for CommentRow {
fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) { fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) {
match message { match message {
CommentRowMsg::OpenPerson => { CommentRowMsg::OpenPerson => {
sender.output(crate::AppMsg::OpenPerson(self.comment.creator.id.clone())); sender.output(crate::AppMsg::OpenPerson(self.comment.creator.id));
} }
CommentRowMsg::DeleteComment => { CommentRowMsg::DeleteComment => {
let comment_id = self.comment.comment.id; let comment_id = self.comment.comment.id;
@ -201,7 +201,7 @@ impl FactoryComponent for CommentRow {
let message = match api::comment::edit_comment(data.body, id) { let message = match api::comment::edit_comment(data.body, id) {
Ok(comment) => Some(CommentRowMsg::UpdateComment(comment.comment_view)), Ok(comment) => Some(CommentRowMsg::UpdateComment(comment.comment_view)),
Err(err) => { Err(err) => {
println!("{}", err.to_string()); println!("{}", err);
None None
} }
}; };
@ -219,7 +219,7 @@ impl FactoryComponent for CommentRow {
// TODO sender.output_sender().emit(PostPageInput::CreatedComment(comment.comment_view)); // TODO sender.output_sender().emit(PostPageInput::CreatedComment(comment.comment_view));
} }
Err(err) => { Err(err) => {
println!("{}", err.to_string()); println!("{}", err);
} }
}; };
}); });

View File

@ -203,12 +203,12 @@ impl SimpleComponent for CommunityPage {
self.posts.guard().push_front(post); self.posts.guard().push_front(post);
} }
CommunityInput::CreatePostRequest(post) => { CommunityInput::CreatePostRequest(post) => {
let id = self.info.community.id.0.clone(); let id = self.info.community.id.0;
std::thread::spawn(move || { std::thread::spawn(move || {
let message = match api::post::create_post(post.name, post.body, post.url, id) { let message = match api::post::create_post(post.name, post.body, post.url, id) {
Ok(post) => Some(CommunityInput::CreatedPost(post.post_view)), Ok(post) => Some(CommunityInput::CreatedPost(post.post_view)),
Err(err) => { Err(err) => {
println!("{}", err.to_string()); println!("{}", err);
None None
} }
}; };
@ -219,22 +219,19 @@ impl SimpleComponent for CommunityPage {
} }
CommunityInput::ToggleSubscription => { CommunityInput::ToggleSubscription => {
let community_id = self.info.community.id.0; let community_id = self.info.community.id.0;
let new_state = match self.info.subscribed { let new_state = matches!(self.info.subscribed, SubscribedType::NotSubscribed);
SubscribedType::NotSubscribed => true,
_ => false,
};
std::thread::spawn(move || { std::thread::spawn(move || {
let message = match api::community::follow_community(community_id, new_state) { let message = match api::community::follow_community(community_id, new_state) {
Ok(community) => Some(CommunityInput::UpdateSubscriptionState( Ok(community) => Some(CommunityInput::UpdateSubscriptionState(
community.community_view.subscribed, community.community_view.subscribed,
)), )),
Err(err) => { Err(err) => {
println!("{}", err.to_string()); println!("{}", err);
None None
} }
}; };
if message.is_some() { if let Some(message) = message {
sender.input(message.unwrap()) sender.input(message)
}; };
}); });
} }

View File

@ -96,7 +96,7 @@ impl FactoryComponent for CommunityRow {
fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) { fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) {
match message { match message {
CommunityRowMsg::OpenCommunity => sender.output(crate::AppMsg::OpenCommunity( CommunityRowMsg::OpenCommunity => sender.output(crate::AppMsg::OpenCommunity(
self.community.community.id.clone(), self.community.community.id,
)), )),
} }
} }

View File

@ -126,8 +126,8 @@ impl SimpleComponent for InboxPage {
match message { match message {
InboxInput::FetchInbox => { InboxInput::FetchInbox => {
let type_ = self.type_.clone(); let type_ = self.type_.clone();
let page = self.page.clone(); let page = self.page;
let unread_only = self.unread_only.clone(); let unread_only = self.unread_only;
std::thread::spawn(move || { std::thread::spawn(move || {
let message = match type_ { let message = match type_ {
InboxType::Mentions => { InboxType::Mentions => {
@ -135,11 +135,7 @@ impl SimpleComponent for InboxPage {
// It's just a different object, but its contents are exactly the same // It's just a different object, but its contents are exactly the same
let serialised = serde_json::to_string(&response.mentions).unwrap(); let serialised = serde_json::to_string(&response.mentions).unwrap();
let mentions = serde_json::from_str(&serialised).ok(); let mentions = serde_json::from_str(&serialised).ok();
if let Some(mentions) = mentions { mentions.map(InboxInput::UpdateInbox)
Some(InboxInput::UpdateInbox(mentions))
} else {
None
}
} else { } else {
None None
} }
@ -187,7 +183,7 @@ impl SimpleComponent for InboxPage {
} }
} }
InboxInput::MarkAllAsRead => { InboxInput::MarkAllAsRead => {
let show_unread_only = self.unread_only.clone(); let show_unread_only = self.unread_only;
std::thread::spawn(move || { std::thread::spawn(move || {
if api::user::mark_all_as_read().is_ok() && show_unread_only { if api::user::mark_all_as_read().is_ok() && show_unread_only {
sender.input(InboxInput::UpdateInbox(vec![])); sender.input(InboxInput::UpdateInbox(vec![]));

View File

@ -79,7 +79,7 @@ impl FactoryComponent for InstanceRow {
match message { match message {
InstanceRowMsg::OpenInstance => { InstanceRowMsg::OpenInstance => {
let instance_address = format!("https://{}", self.instance.domain); let instance_address = format!("https://{}", self.instance.domain);
sender.output(InstancesPageInput::SetInstance(instance_address.clone())) sender.output(InstancesPageInput::SetInstance(instance_address))
} }
} }
} }

View File

@ -154,14 +154,14 @@ impl FactoryComponent for MentionRow {
fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) { fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) {
match message { match message {
MentionRowMsg::OpenPerson => { MentionRowMsg::OpenPerson => {
sender.output(crate::AppMsg::OpenPerson(self.comment.creator.id.clone())); sender.output(crate::AppMsg::OpenPerson(self.comment.creator.id));
} }
MentionRowMsg::OpenPost => { MentionRowMsg::OpenPost => {
sender.output(crate::AppMsg::OpenPost(self.comment.post.id.clone())); sender.output(crate::AppMsg::OpenPost(self.comment.post.id));
} }
MentionRowMsg::OpenCommunity => { MentionRowMsg::OpenCommunity => {
sender.output(crate::AppMsg::OpenCommunity( sender.output(crate::AppMsg::OpenCommunity(
self.comment.community.id.clone(), self.comment.community.id,
)); ));
} }
} }

View File

@ -107,7 +107,7 @@ impl FactoryComponent for ModeratesRow {
fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) { fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) {
match message { match message {
ModeratesRowMsg::OpenCommunity => sender.output(crate::AppMsg::OpenCommunity( ModeratesRowMsg::OpenCommunity => sender.output(crate::AppMsg::OpenCommunity(
self.community.community.id.clone(), self.community.community.id,
)), )),
} }
} }

View File

@ -273,13 +273,13 @@ impl SimpleComponent for PostPage {
} }
} }
PostPageInput::OpenPerson => { PostPageInput::OpenPerson => {
let person_id = self.info.post_view.creator.id.clone(); let person_id = self.info.post_view.creator.id;
sender sender
.output_sender() .output_sender()
.emit(crate::AppMsg::OpenPerson(person_id)); .emit(crate::AppMsg::OpenPerson(person_id));
} }
PostPageInput::OpenCommunity => { PostPageInput::OpenCommunity => {
let community_id = self.info.community_view.community.id.clone(); let community_id = self.info.community_view.community.id;
sender sender
.output_sender() .output_sender()
.emit(crate::AppMsg::OpenCommunity(community_id)); .emit(crate::AppMsg::OpenCommunity(community_id));
@ -314,7 +314,7 @@ impl SimpleComponent for PostPage {
let message = match api::comment::create_comment(id, post.body, None) { let message = match api::comment::create_comment(id, post.body, None) {
Ok(comment) => Some(PostPageInput::CreatedComment(comment.comment_view)), Ok(comment) => Some(PostPageInput::CreatedComment(comment.comment_view)),
Err(err) => { Err(err) => {
println!("{}", err.to_string()); println!("{}", err);
None None
} }
}; };
@ -368,7 +368,7 @@ impl SimpleComponent for PostPage {
let message = match api::post::edit_post(post.name, post.url, post.body, id) { let message = match api::post::edit_post(post.name, post.url, post.body, id) {
Ok(post) => Some(PostPageInput::DoneEditPost(post.post_view)), Ok(post) => Some(PostPageInput::DoneEditPost(post.post_view)),
Err(err) => { Err(err) => {
println!("{}", err.to_string()); println!("{}", err);
None None
} }
}; };

View File

@ -189,13 +189,13 @@ impl FactoryComponent for PostRow {
fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) { fn update(&mut self, message: Self::Input, sender: FactorySender<Self>) {
match message { match message {
PostRowMsg::OpenCommunity => { PostRowMsg::OpenCommunity => {
sender.output(crate::AppMsg::OpenCommunity(self.post.community.id.clone())) sender.output(crate::AppMsg::OpenCommunity(self.post.community.id))
} }
PostRowMsg::OpenPerson => { PostRowMsg::OpenPerson => {
sender.output(crate::AppMsg::OpenPerson(self.post.creator.id.clone())) sender.output(crate::AppMsg::OpenPerson(self.post.creator.id))
} }
PostRowMsg::OpenPost => { PostRowMsg::OpenPost => {
sender.output(crate::AppMsg::OpenPost(self.post.post.id.clone())) sender.output(crate::AppMsg::OpenPost(self.post.post.id))
} }
PostRowMsg::ToggleSaved => { PostRowMsg::ToggleSaved => {
let post_id = self.post.post.id; let post_id = self.post.post.id;

View File

@ -106,9 +106,7 @@ impl SimpleComponent for VotingRowModel {
match message { match message {
VotingRowInput::Vote(vote) => { VotingRowInput::Vote(vote) => {
let mut score = self.stats.own_vote.unwrap_or(0) + vote; let mut score = self.stats.own_vote.unwrap_or(0) + vote;
if score < -1 || score > 1 { if !(-1..=1).contains(&score) { score = 0 };
score = 0
};
if settings::get_current_account().jwt.is_none() { if settings::get_current_account().jwt.is_none() {
return; return;
} }
@ -116,9 +114,7 @@ impl SimpleComponent for VotingRowModel {
std::thread::spawn(move || { std::thread::spawn(move || {
let info = if stats.post_id.is_some() { let info = if stats.post_id.is_some() {
let response = api::post::like_post( let response = api::post::like_post(
PostId { PostId(stats.post_id.unwrap()),
0: stats.post_id.unwrap(),
},
score, score,
); );
match response { match response {
@ -127,15 +123,13 @@ impl SimpleComponent for VotingRowModel {
post.post_view.my_vote, post.post_view.my_vote,
)), )),
Err(err) => { Err(err) => {
println!("{}", err.to_string()); println!("{}", err);
None None
} }
} }
} else { } else {
let response = api::comment::like_comment( let response = api::comment::like_comment(
CommentId { CommentId(stats.comment_id.unwrap()),
0: stats.comment_id.unwrap(),
},
score, score,
); );
match response { match response {
@ -144,7 +138,7 @@ impl SimpleComponent for VotingRowModel {
comment.comment_view.my_vote, comment.comment_view.my_vote,
)), )),
Err(err) => { Err(err) => {
println!("{}", err.to_string()); println!("{}", err);
None None
} }
} }

View File

@ -207,7 +207,7 @@ impl SimpleComponent for EditorDialog {
if let Some(url) = data.url { if let Some(url) = data.url {
self.url_buffer.set_text(url.to_string()); self.url_buffer.set_text(url.to_string());
} }
self.body_buffer.set_text(&data.body.clone()); self.body_buffer.set_text(&data.body);
} }
DialogMsg::ChooseImage => { DialogMsg::ChooseImage => {
let buttons = [ let buttons = [

View File

@ -333,9 +333,8 @@ impl SimpleComponent for App {
profile_sender.input(AppMsg::OpenPerson(PersonId(person.id))); profile_sender.input(AppMsg::OpenPerson(PersonId(person.id)));
} }
}); });
let login_sender = sender.clone();
let login_action: RelmAction<LoginAction> = RelmAction::new_stateless(move |_| { let login_action: RelmAction<LoginAction> = RelmAction::new_stateless(move |_| {
login_sender.input(AppMsg::UpdateState(AppState::Login)); sender.input(AppMsg::UpdateState(AppState::Login));
}); });
let about_action = { let about_action = {
let sender = model.about_dialog.sender().clone(); let sender = model.about_dialog.sender().clone();

View File

@ -35,16 +35,16 @@ pub fn get_prefs() -> Preferences {
if let Ok(file) = File::open(data_path()) { if let Ok(file) = File::open(data_path()) {
// Deserialize data from file to vector // Deserialize data from file to vector
let prefs: Result<Preferences, serde_json::Error> = serde_json::from_reader(file); let prefs: Result<Preferences, serde_json::Error> = serde_json::from_reader(file);
if prefs.is_ok() { if let Ok(prefs) = prefs {
return prefs.unwrap(); return prefs;
} }
} }
return Preferences::default(); Preferences::default()
} }
pub fn get_current_account() -> Account { pub fn get_current_account() -> Account {
let mut prefs = get_prefs(); let mut prefs = get_prefs();
if prefs.accounts.len() == 0 { if prefs.accounts.is_empty() {
prefs = create_account(true); prefs = create_account(true);
} }
prefs.accounts[prefs.current_account_index as usize].clone() prefs.accounts[prefs.current_account_index as usize].clone()
@ -66,7 +66,7 @@ pub fn remove_account(index: usize) {
settings.accounts.remove(index); settings.accounts.remove(index);
// if the deleted account has been before the current one, the current index needs to decreased too // if the deleted account has been before the current one, the current index needs to decreased too
if index < settings.current_account_index as usize { if index < settings.current_account_index as usize {
settings.current_account_index = settings.current_account_index - 1; settings.current_account_index -= 1;
} }
save_prefs(&settings); save_prefs(&settings);
} }

View File

@ -2,11 +2,11 @@ use lemmy_api_common::lemmy_db_schema::newtypes::DbUrl;
use relm4_components::web_image::WebImageMsg; use relm4_components::web_image::WebImageMsg;
pub fn get_web_image_msg(url: Option<DbUrl>) -> WebImageMsg { pub fn get_web_image_msg(url: Option<DbUrl>) -> WebImageMsg {
return if let Some(url) = url { if let Some(url) = url {
WebImageMsg::LoadImage(url.to_string()) WebImageMsg::LoadImage(url.to_string())
} else { } else {
WebImageMsg::Unload WebImageMsg::Unload
}; }
} }
pub fn get_web_image_url(url: Option<DbUrl>) -> String { pub fn get_web_image_url(url: Option<DbUrl>) -> String {
@ -18,7 +18,7 @@ pub fn get_web_image_url(url: Option<DbUrl>) -> String {
} }
pub fn markdown_to_pango_markup(text: String) -> String { pub fn markdown_to_pango_markup(text: String) -> String {
return html2pango::markup_html(&markdown::to_html(&text)).unwrap_or(text); html2pango::markup_html(&markdown::to_html(&text)).unwrap_or(text)
} }
pub fn format_elapsed_time(time: chrono::NaiveDateTime) -> String { pub fn format_elapsed_time(time: chrono::NaiveDateTime) -> String {