Removed usage of loops to better detect where errors originate

This commit is contained in:
Neshura 2023-08-14 22:52:34 +02:00
parent 8c58088321
commit a549c89c33
Signed by: Neshura
GPG key ID: B6983AAA6B9A7A6C
2 changed files with 22 additions and 29 deletions

View file

@ -1,4 +1,4 @@
use std::{fs::{self, OpenOptions}, path::Path, io::Write, thread::sleep, time}; use std::{fs::{self, OpenOptions}, path::Path, io::Write, thread::sleep, time, error::Error};
use lemmy_api_common::{sensitive::Sensitive, post::CreatePost, community::{ListCommunities, ListCommunitiesResponse}}; use lemmy_api_common::{sensitive::Sensitive, post::CreatePost, community::{ListCommunities, ListCommunitiesResponse}};
use lemmy_db_schema::{newtypes::{LanguageId, CommunityId, PostId}, ListingType}; use lemmy_db_schema::{newtypes::{LanguageId, CommunityId, PostId}, ListingType};
@ -98,7 +98,7 @@ impl Config {
} }
pub(crate) fn check_feeds(&mut self, post_history: &mut Vec<PrevPost> pub(crate) fn check_feeds(&mut self, post_history: &mut Vec<PrevPost>
, community_ids: &CommunitiesVector, auth: &Sensitive<String>) -> Result<Vec<(CreatePost, (Option<usize>, usize, String))>, reqwest::Error> { , community_ids: &CommunitiesVector, auth: &Sensitive<String>) -> Result<Vec<(CreatePost, (Option<usize>, usize, String))>, Box<dyn Error>> {
let mut post_queue: Vec<(CreatePost, (Option<usize>, usize, String))> = vec![]; let mut post_queue: Vec<(CreatePost, (Option<usize>, usize, String))> = vec![];
match self.feeds.iter().map(|feed| { match self.feeds.iter().map(|feed| {
@ -267,7 +267,7 @@ impl CommunitiesVector {
} }
#[warn(unused_results)] #[warn(unused_results)]
pub(crate) fn load(&mut self, auth: &Sensitive<String>, base: &String) -> Result<(), reqwest::Error> { pub(crate) fn load(&mut self, auth: &Sensitive<String>, base: &String) -> Result<(), Box<dyn Error>> {
let params = ListCommunities { let params = ListCommunities {
auth: Some(auth.clone()), auth: Some(auth.clone()),
type_: Some(ListingType::Local), type_: Some(ListingType::Local),

View file

@ -10,7 +10,7 @@ use lemmy_db_schema::{
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use reqwest::{blocking::Client, StatusCode}; use reqwest::{blocking::Client, StatusCode};
use std::{thread::sleep, time, collections::HashMap}; use std::{thread::sleep, time, collections::HashMap, error::Error};
mod config; mod config;
@ -50,7 +50,7 @@ impl Bot {
/// ///
/// * `return` : Returns true if token was succesfully retrieved, false otherwise /// * `return` : Returns true if token was succesfully retrieved, false otherwise
#[warn(unused_results)] #[warn(unused_results)]
pub(crate) fn login(&mut self) -> Result<(), reqwest::Error> { pub(crate) fn login(&mut self) -> Result<(), Box<dyn Error>> {
let login_params = Login { let login_params = Login {
username_or_email: self.secrets.lemmy.get_username(), username_or_email: self.secrets.lemmy.get_username(),
password: self.secrets.lemmy.get_password(), password: self.secrets.lemmy.get_password(),
@ -71,7 +71,7 @@ impl Bot {
return Ok(()); return Ok(());
} else { } else {
println!("Error Code: {:?}", res.status()); println!("Error Code: {:?}", res.status());
return Err(res.error_for_status().unwrap_err()); return Err(Box::new(res.error_for_status().unwrap_err()));
} }
} }
@ -80,7 +80,7 @@ impl Bot {
/// * `post_data` : Object of type [CreatePost] containing post info /// * `post_data` : Object of type [CreatePost] containing post info
/// * `return` : Returns true if Post was succesful, false otherwise /// * `return` : Returns true if Post was succesful, false otherwise
#[warn(unused_results)] #[warn(unused_results)]
pub(crate) fn post(&mut self, post_data: CreatePost) -> Result<PostView, reqwest::Error> { pub(crate) fn post(&mut self, post_data: CreatePost) -> Result<PostView, Box<dyn Error>> {
let res = CLIENT let res = CLIENT
.post(self.config.instance.clone() + "/api/v3/post") .post(self.config.instance.clone() + "/api/v3/post")
.json(&post_data) .json(&post_data)
@ -92,7 +92,7 @@ impl Bot {
} }
#[warn(unused_results)] #[warn(unused_results)]
pub(crate) fn pin_new(&mut self, old_post: &Option<usize>, new_post: &PostView) -> Result<(), reqwest::Error> { pub(crate) fn pin_new(&mut self, old_post: &Option<usize>, new_post: &PostView) -> Result<(), Box<dyn Error>> {
match old_post { match old_post {
Some(id) => { Some(id) => {
let remove_community_pin = FeaturePost { let remove_community_pin = FeaturePost {
@ -166,7 +166,7 @@ impl Bot {
return Ok(()); return Ok(());
} }
pub(crate) fn pin (&mut self, pin_data: FeaturePost) -> Result<bool, reqwest::Error> { pub(crate) fn pin (&mut self, pin_data: FeaturePost) -> Result<bool, Box<dyn Error>> {
let res = CLIENT let res = CLIENT
.post(self.config.instance.clone() + "/api/v3/post/feature") .post(self.config.instance.clone() + "/api/v3/post/feature")
.json(&pin_data) .json(&pin_data)
@ -177,7 +177,7 @@ impl Bot {
} }
#[warn(unused_results)] #[warn(unused_results)]
pub(crate) fn run_once(&mut self, prev_time: &mut NaiveDateTime) -> Result<(), reqwest::Error> { pub(crate) fn run_once(&mut self, prev_time: &mut NaiveDateTime) -> Result<(), Box<dyn Error>> {
println!("{:#<1$}", "", 30); println!("{:#<1$}", "", 30);
self.start_time = Utc::now().naive_local(); self.start_time = Utc::now().naive_local();
@ -195,24 +195,12 @@ impl Bot {
let post_queue: Vec<(CreatePost, (Option<usize>, usize, String))> = self.config.check_feeds(&mut self.post_history, &self.community_ids, &self.auth)?; let post_queue: Vec<(CreatePost, (Option<usize>, usize, String))> = self.config.check_feeds(&mut self.post_history, &self.community_ids, &self.auth)?;
println!("Done!"); println!("Done!");
post_queue.iter().for_each(|(post, (prev_idx, feed_id, feed_title))| { let _ = post_queue.iter().map(|(post, (prev_idx, feed_id, feed_title))| -> Result<(), Box<dyn Error>> {
println!("Posting: {}", post.name); println!("Posting: {}", post.name);
let post_data: PostView; let post_data = self.post(post.clone())?;
loop { self.pin_new(prev_idx, &post_data)?;
let post_res = self.post(post.clone());
if post_res.is_ok() {
post_data = post_res.unwrap();
break
};
println!("Post attempt failed, retrying");
}
loop {
if self.pin_new(prev_idx, &post_data).is_ok() {break};
println!("Pin attempt failed, retrying");
}
// Move current post to old post list // Move current post to old post list
match prev_idx { match prev_idx {
@ -228,7 +216,8 @@ impl Bot {
last_post_url: post.url.clone().unwrap().to_string(), last_post_url: post.url.clone().unwrap().to_string(),
}), }),
} }
}); Ok(())
}).collect::<Vec<_>>();
PrevPost::save(&self.post_history); PrevPost::save(&self.post_history);
@ -296,15 +285,19 @@ fn run_bot() {
loop { loop {
this.idle(); this.idle();
// 3 retries in case of connection issues // 3 retries in case of connection issues
let mut loop_breaker: u8 = 0; //let mut loop_breaker: u8 = 0; // DEBUG disabled for clearer crash finding
while !this.run_once(&mut old).is_ok() && loop_breaker <= 3 { match this.run_once(&mut old) {
Ok(_) => {},
Err(e) => panic!("{:#?}", e)
};
/* while !this.run_once(&mut old).is_ok() && loop_breaker <= 3 {
println!("Unable to complete Bot cycle, retrying with fresh login credentials"); println!("Unable to complete Bot cycle, retrying with fresh login credentials");
if this.login().is_ok() { if this.login().is_ok() {
let _ = this.community_ids.load(&this.auth, &this.config.instance); let _ = this.community_ids.load(&this.auth, &this.config.instance);
} }
sleep(time::Duration::from_secs(10)); sleep(time::Duration::from_secs(10));
loop_breaker += 1; loop_breaker += 1;
}; }; */
this.print_info(); this.print_info();
this.idle(); this.idle();
} }