From 890e6baef54e770d93cf0a1a42ded6ca6030a2e8 Mon Sep 17 00:00:00 2001 From: Neshura Date: Sun, 30 Jul 2023 21:10:36 +0200 Subject: [PATCH] Added missing get error handling --- src/config/mod.rs | 31 ++++++++++++++++++------------- src/main.rs | 27 +++++++++++++++++++++++---- 2 files changed, 41 insertions(+), 17 deletions(-) diff --git a/src/config/mod.rs b/src/config/mod.rs index 205c987..dd09292 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -98,16 +98,17 @@ impl Config { } pub(crate) fn check_feeds(&mut self, post_history: &mut Vec - , community_ids: &CommunitiesVector, auth: &Sensitive) -> Vec { + , community_ids: &CommunitiesVector, auth: &Sensitive) -> Result, ()> { let mut post_queue: Vec = vec![]; self.feeds.iter().for_each(|feed| { - let res = CLIENT + let res = match CLIENT .get(feed.feed_url.clone()) - .send() - .unwrap() - .text() - .unwrap(); + .send() { + Ok(data) => data.text().unwrap(), + Err(_) => return () + }; + let data: FeedData = serde_json::from_str(&res).unwrap(); let mut prev_post_idx: Option = None; @@ -154,7 +155,7 @@ impl Config { }); PrevPost::save(&post_history); - return post_queue; + return Ok(post_queue); } } @@ -268,20 +269,23 @@ impl CommunitiesVector { CommunitiesVector{ids: vec![]} } - pub(crate) fn load(&mut self, auth: &Sensitive, base: &String) { + #[warn(unused_results)] + pub(crate) fn load(&mut self, auth: &Sensitive, base: &String) -> bool { let params = ListCommunities { auth: Some(auth.clone()), type_: Some(ListingType::Local), ..Default::default() }; - let res = CLIENT + let res = match CLIENT .get(base.clone() + "/api/v3/community/list") .query(¶ms) - .send() - .unwrap() - .text() - .unwrap(); + .send() { + Ok(data) => { + data.text().unwrap() + } + Err(_) => return false + }; let site_data: ListCommunitiesResponse = serde_json::from_str(&res).unwrap(); @@ -293,6 +297,7 @@ impl CommunitiesVector { }); self.ids = ids; + return true; } pub(crate) fn find(&self, name: &LemmyCommunities) -> CommunityId { diff --git a/src/main.rs b/src/main.rs index 386666b..f3849f8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,8 @@ use std::{thread::sleep, time, io}; mod config; + + pub static CLIENT: Lazy = Lazy::new(|| { let client = Client::builder() .timeout(time::Duration::from_secs(30)) @@ -47,6 +49,7 @@ impl Bot { /// Get JWT Token /// /// * `return` : Returns true if token was succesfully retrieved, false otherwise + #[warn(unused_results)] pub(crate) fn login(&mut self) -> bool { let login_params = Login { username_or_email: self.secrets.lemmy.get_username(), @@ -79,6 +82,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) -> bool { let res = match CLIENT .post(self.config.instance.clone() + "/api/v3/post") @@ -93,18 +97,22 @@ impl Bot { 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(); 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(); 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 // Get all feed URLs (use cache) - let post_queue: Vec = self.config.check_feeds(&mut self.post_history, &self.community_ids, &self.auth); + let post_queue: Vec = 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| { println!("Posting: {}", post.name); @@ -113,6 +121,8 @@ impl Bot { println!("Post attempt failed, retrying"); } }); + + return true; } pub(crate) fn idle(&self) { @@ -168,7 +178,16 @@ fn run_bot() { // Enter a loop (not for debugging) loop { 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.idle(); }