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_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>
, 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![];
match self.feeds.iter().map(|feed| {
@ -267,7 +267,7 @@ impl CommunitiesVector {
}
#[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 {
auth: Some(auth.clone()),
type_: Some(ListingType::Local),

View file

@ -10,7 +10,7 @@ use lemmy_db_schema::{
};
use once_cell::sync::Lazy;
use reqwest::{blocking::Client, StatusCode};
use std::{thread::sleep, time, collections::HashMap};
use std::{thread::sleep, time, collections::HashMap, error::Error};
mod config;
@ -50,7 +50,7 @@ impl Bot {
///
/// * `return` : Returns true if token was succesfully retrieved, false otherwise
#[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 {
username_or_email: self.secrets.lemmy.get_username(),
password: self.secrets.lemmy.get_password(),
@ -71,7 +71,7 @@ impl Bot {
return Ok(());
} else {
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
/// * `return` : Returns true if Post was succesful, false otherwise
#[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
.post(self.config.instance.clone() + "/api/v3/post")
.json(&post_data)
@ -92,7 +92,7 @@ impl Bot {
}
#[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 {
Some(id) => {
let remove_community_pin = FeaturePost {
@ -166,7 +166,7 @@ impl Bot {
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
.post(self.config.instance.clone() + "/api/v3/post/feature")
.json(&pin_data)
@ -177,7 +177,7 @@ impl Bot {
}
#[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);
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)?;
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);
let post_data: PostView;
let post_data = self.post(post.clone())?;
loop {
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");
}
self.pin_new(prev_idx, &post_data)?;
// Move current post to old post list
match prev_idx {
@ -228,7 +216,8 @@ impl Bot {
last_post_url: post.url.clone().unwrap().to_string(),
}),
}
});
Ok(())
}).collect::<Vec<_>>();
PrevPost::save(&self.post_history);
@ -296,15 +285,19 @@ fn run_bot() {
loop {
this.idle();
// 3 retries in case of connection issues
let mut loop_breaker: u8 = 0;
while !this.run_once(&mut old).is_ok() && loop_breaker <= 3 {
//let mut loop_breaker: u8 = 0; // DEBUG disabled for clearer crash finding
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");
if this.login().is_ok() {
let _ = this.community_ids.load(&this.auth, &this.config.instance);
}
sleep(time::Duration::from_secs(10));
loop_breaker += 1;
};
}; */
this.print_info();
this.idle();
}