Added missing get error handling

This commit is contained in:
Neshura 2023-07-30 21:10:36 +02:00
parent 5740d83d11
commit 890e6baef5
Signed by: Neshura
GPG key ID: B6983AAA6B9A7A6C
2 changed files with 41 additions and 17 deletions

View file

@ -98,16 +98,17 @@ 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>) -> Vec<CreatePost> { , community_ids: &CommunitiesVector, auth: &Sensitive<String>) -> Result<Vec<CreatePost>, ()> {
let mut post_queue: Vec<CreatePost> = vec![]; let mut post_queue: Vec<CreatePost> = vec![];
self.feeds.iter().for_each(|feed| { self.feeds.iter().for_each(|feed| {
let res = CLIENT let res = match CLIENT
.get(feed.feed_url.clone()) .get(feed.feed_url.clone())
.send() .send() {
.unwrap() Ok(data) => data.text().unwrap(),
.text() Err(_) => return ()
.unwrap(); };
let data: FeedData = serde_json::from_str(&res).unwrap(); let data: FeedData = serde_json::from_str(&res).unwrap();
let mut prev_post_idx: Option<usize> = None; let mut prev_post_idx: Option<usize> = None;
@ -154,7 +155,7 @@ impl Config {
}); });
PrevPost::save(&post_history); PrevPost::save(&post_history);
return post_queue; return Ok(post_queue);
} }
} }
@ -268,20 +269,23 @@ impl CommunitiesVector {
CommunitiesVector{ids: vec![]} CommunitiesVector{ids: vec![]}
} }
pub(crate) fn load(&mut self, auth: &Sensitive<String>, base: &String) { #[warn(unused_results)]
pub(crate) fn load(&mut self, auth: &Sensitive<String>, base: &String) -> bool {
let params = ListCommunities { let params = ListCommunities {
auth: Some(auth.clone()), auth: Some(auth.clone()),
type_: Some(ListingType::Local), type_: Some(ListingType::Local),
..Default::default() ..Default::default()
}; };
let res = CLIENT let res = match CLIENT
.get(base.clone() + "/api/v3/community/list") .get(base.clone() + "/api/v3/community/list")
.query(&params) .query(&params)
.send() .send() {
.unwrap() Ok(data) => {
.text() data.text().unwrap()
.unwrap(); }
Err(_) => return false
};
let site_data: ListCommunitiesResponse = serde_json::from_str(&res).unwrap(); let site_data: ListCommunitiesResponse = serde_json::from_str(&res).unwrap();
@ -293,6 +297,7 @@ impl CommunitiesVector {
}); });
self.ids = ids; self.ids = ids;
return true;
} }
pub(crate) fn find(&self, name: &LemmyCommunities) -> CommunityId { pub(crate) fn find(&self, name: &LemmyCommunities) -> CommunityId {

View file

@ -14,6 +14,8 @@ use std::{thread::sleep, time, io};
mod config; mod config;
pub static CLIENT: Lazy<Client> = Lazy::new(|| { pub static CLIENT: Lazy<Client> = Lazy::new(|| {
let client = Client::builder() let client = Client::builder()
.timeout(time::Duration::from_secs(30)) .timeout(time::Duration::from_secs(30))
@ -47,6 +49,7 @@ impl Bot {
/// Get JWT Token /// Get JWT Token
/// ///
/// * `return` : Returns true if token was succesfully retrieved, false otherwise /// * `return` : Returns true if token was succesfully retrieved, false otherwise
#[warn(unused_results)]
pub(crate) fn login(&mut self) -> bool { pub(crate) fn login(&mut self) -> bool {
let login_params = Login { let login_params = Login {
username_or_email: self.secrets.lemmy.get_username(), username_or_email: self.secrets.lemmy.get_username(),
@ -79,6 +82,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)]
pub(crate) fn post(&mut self, post_data: CreatePost) -> bool { pub(crate) fn post(&mut self, post_data: CreatePost) -> bool {
let res = match CLIENT let res = match CLIENT
.post(self.config.instance.clone() + "/api/v3/post") .post(self.config.instance.clone() + "/api/v3/post")
@ -93,18 +97,22 @@ impl Bot {
return true; return true;
} }
pub(crate) fn run_once(&mut self, mut prev_time: NaiveTime) { #[warn(unused_results)]
pub(crate) fn run_once(&mut self, mut prev_time: NaiveTime) -> bool {
self.start_time = Utc::now(); self.start_time = Utc::now();
if self.start_time.time() - prev_time > chrono::Duration::seconds(6) { // Prod should use hours, add command line switch later and read duration from config if self.start_time.time() - prev_time > chrono::Duration::seconds(6) { // Prod should use hours, add command line switch later and read duration from config
prev_time = self.start_time.time(); prev_time = self.start_time.time();
self.config.load(); self.config.load();
self.community_ids.load(&self.auth, &self.config.instance); if !self.community_ids.load(&self.auth, &self.config.instance) {return false}; // Return early if community id's cannot be loaded
} }
// Start the polling process // Start the polling process
// Get all feed URLs (use cache) // Get all feed URLs (use cache)
let post_queue: Vec<CreatePost> = self.config.check_feeds(&mut self.post_history, &self.community_ids, &self.auth); let post_queue: Vec<CreatePost> = match self.config.check_feeds(&mut self.post_history, &self.community_ids, &self.auth) {
Ok(data) => data,
Err(_) => return false
};
post_queue.iter().for_each(|post| { post_queue.iter().for_each(|post| {
println!("Posting: {}", post.name); println!("Posting: {}", post.name);
@ -113,6 +121,8 @@ impl Bot {
println!("Post attempt failed, retrying"); println!("Post attempt failed, retrying");
} }
}); });
return true;
} }
pub(crate) fn idle(&self) { pub(crate) fn idle(&self) {
@ -168,7 +178,16 @@ fn run_bot() {
// Enter a loop (not for debugging) // Enter a loop (not for debugging)
loop { loop {
this.idle(); this.idle();
this.run_once(old); // 3 retries in case of connection issues
let mut loop_breaker: u8 = 0;
while !this.run_once(old) && loop_breaker <= 3 {
println!("Unable to complete Bot cycle, retrying with fresh login credentials");
if this.login() {
this.community_ids.load(&this.auth, &this.config.instance);
}
sleep(time::Duration::from_secs(10));
loop_breaker += 1;
};
this.print_info(); this.print_info();
this.idle(); this.idle();
} }