2023-07-30 18:34:05 +00:00
|
|
|
use chrono::{Utc, DateTime, NaiveTime};
|
2023-06-22 20:08:10 +00:00
|
|
|
use config::{Config, PrevPost, Secrets, CommunitiesVector};
|
2023-06-18 22:26:50 +00:00
|
|
|
use lemmy_api_common::{
|
|
|
|
person::{Login, LoginResponse},
|
|
|
|
post::{CreatePost, GetPosts, GetPostsResponse},
|
2023-06-22 20:08:10 +00:00
|
|
|
sensitive::Sensitive,
|
2023-06-18 22:26:50 +00:00
|
|
|
};
|
|
|
|
use lemmy_db_schema::{
|
|
|
|
ListingType, SortType,
|
|
|
|
};
|
|
|
|
use once_cell::sync::Lazy;
|
|
|
|
use reqwest::{blocking::Client, StatusCode};
|
2023-07-31 17:50:22 +00:00
|
|
|
use std::{thread::sleep, time, io, error::Error};
|
2023-06-18 22:26:50 +00:00
|
|
|
|
|
|
|
mod config;
|
|
|
|
|
2023-07-30 19:10:36 +00:00
|
|
|
|
|
|
|
|
2023-06-18 22:26:50 +00:00
|
|
|
pub static CLIENT: Lazy<Client> = Lazy::new(|| {
|
|
|
|
let client = Client::builder()
|
|
|
|
.timeout(time::Duration::from_secs(30))
|
|
|
|
.connect_timeout(time::Duration::from_secs(30))
|
|
|
|
.build()
|
|
|
|
.expect("build client");
|
|
|
|
client
|
|
|
|
});
|
|
|
|
|
|
|
|
struct Bot {
|
|
|
|
secrets: Secrets,
|
|
|
|
config: Config,
|
|
|
|
post_history: Vec<PrevPost>,
|
2023-06-19 17:21:28 +00:00
|
|
|
community_ids: CommunitiesVector,
|
2023-06-18 22:26:50 +00:00
|
|
|
auth: Sensitive<String>,
|
2023-06-22 20:08:10 +00:00
|
|
|
start_time: DateTime<Utc>,
|
2023-06-18 22:26:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Bot {
|
|
|
|
pub(crate) fn new() -> Bot {
|
|
|
|
Bot {
|
2023-06-22 20:08:10 +00:00
|
|
|
secrets: Secrets::init(),
|
|
|
|
config: Config::init(),
|
2023-06-18 22:26:50 +00:00
|
|
|
post_history: PrevPost::load(),
|
2023-06-19 17:21:28 +00:00
|
|
|
community_ids: CommunitiesVector::new(),
|
2023-06-18 22:26:50 +00:00
|
|
|
auth: Sensitive::new("".to_string()),
|
2023-06-22 20:08:10 +00:00
|
|
|
start_time: Utc::now(),
|
2023-06-18 22:26:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-30 18:34:24 +00:00
|
|
|
/// Get JWT Token
|
|
|
|
///
|
|
|
|
/// * `return` : Returns true if token was succesfully retrieved, false otherwise
|
2023-07-30 19:10:36 +00:00
|
|
|
#[warn(unused_results)]
|
2023-07-31 17:50:22 +00:00
|
|
|
pub(crate) fn login(&mut self) -> Result<(), reqwest::Error> {
|
2023-06-18 22:26:50 +00:00
|
|
|
let login_params = Login {
|
|
|
|
username_or_email: self.secrets.lemmy.get_username(),
|
|
|
|
password: self.secrets.lemmy.get_password(),
|
2023-07-09 08:18:51 +00:00
|
|
|
totp_2fa_token: None,
|
2023-06-18 22:26:50 +00:00
|
|
|
};
|
|
|
|
|
2023-07-30 18:34:24 +00:00
|
|
|
let res = match CLIENT
|
2023-06-19 20:10:28 +00:00
|
|
|
.post(self.config.instance.clone() + "/api/v3/user/login")
|
2023-06-18 22:26:50 +00:00
|
|
|
.json(&login_params)
|
2023-07-30 18:34:24 +00:00
|
|
|
.send() {
|
|
|
|
Ok(data) => data,
|
2023-07-31 17:50:22 +00:00
|
|
|
Err(e) => return Err(e),
|
2023-07-30 18:34:24 +00:00
|
|
|
};
|
|
|
|
|
2023-06-18 22:26:50 +00:00
|
|
|
|
|
|
|
if res.status() == StatusCode::OK {
|
|
|
|
let data: &LoginResponse = &res.json().unwrap();
|
|
|
|
|
|
|
|
let jwt = data.jwt.clone().expect("JWT Token could not be acquired");
|
|
|
|
self.auth = jwt;
|
2023-07-31 17:50:22 +00:00
|
|
|
return Ok(());
|
2023-06-18 22:26:50 +00:00
|
|
|
} else {
|
|
|
|
println!("Error Code: {:?}", res.status());
|
2023-07-31 17:50:22 +00:00
|
|
|
return Err(res.error_for_status().unwrap_err());
|
2023-06-18 22:26:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-30 18:34:24 +00:00
|
|
|
/// Make Post to Lemmy Instance
|
|
|
|
///
|
|
|
|
/// * `post_data` : Object of type [CreatePost] containing post info
|
|
|
|
/// * `return` : Returns true if Post was succesful, false otherwise
|
2023-07-30 19:10:36 +00:00
|
|
|
#[warn(unused_results)]
|
2023-07-31 17:50:22 +00:00
|
|
|
pub(crate) fn post(&mut self, post_data: CreatePost) -> Result<(), reqwest::Error> {
|
2023-07-30 18:34:24 +00:00
|
|
|
let res = match CLIENT
|
2023-06-19 20:10:28 +00:00
|
|
|
.post(self.config.instance.clone() + "/api/v3/post")
|
2023-06-18 22:26:50 +00:00
|
|
|
.json(&post_data)
|
2023-07-30 18:34:24 +00:00
|
|
|
.send() {
|
|
|
|
Ok(data) => data,
|
2023-07-31 17:50:22 +00:00
|
|
|
Err(e) => return Err(e)
|
2023-07-30 18:34:24 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// TODO: process res to get info about if post was successfuly (mostly if jwt token was valid)
|
|
|
|
|
2023-07-31 17:50:22 +00:00
|
|
|
return Ok(());
|
2023-06-18 22:26:50 +00:00
|
|
|
}
|
2023-06-22 20:08:10 +00:00
|
|
|
|
2023-07-30 19:10:36 +00:00
|
|
|
#[warn(unused_results)]
|
2023-08-02 22:04:19 +00:00
|
|
|
pub(crate) fn run_once(&mut self, prev_time: &mut NaiveTime) -> Result<(), reqwest::Error> {
|
2023-07-31 17:22:28 +00:00
|
|
|
println!("{:#<1$}", "", 30);
|
2023-06-22 20:08:10 +00:00
|
|
|
self.start_time = Utc::now();
|
|
|
|
|
2023-08-02 22:04:19 +00:00
|
|
|
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
|
2023-07-31 17:22:28 +00:00
|
|
|
println!("Reloading Config");
|
2023-08-02 22:04:19 +00:00
|
|
|
*prev_time = self.start_time.time();
|
2023-06-22 20:08:10 +00:00
|
|
|
self.config.load();
|
2023-07-31 17:50:22 +00:00
|
|
|
match self.community_ids.load(&self.auth, &self.config.instance) {
|
|
|
|
Ok(_) => {},
|
|
|
|
Err(e) => return Err(e)
|
|
|
|
};
|
2023-07-31 17:22:28 +00:00
|
|
|
println!("Done!");
|
2023-06-22 20:08:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start the polling process
|
|
|
|
// Get all feed URLs (use cache)
|
2023-07-31 17:22:28 +00:00
|
|
|
println!("Checking Feeds");
|
2023-07-30 19:10:36 +00:00
|
|
|
let post_queue: Vec<CreatePost> = match self.config.check_feeds(&mut self.post_history, &self.community_ids, &self.auth) {
|
|
|
|
Ok(data) => data,
|
2023-07-31 17:50:22 +00:00
|
|
|
Err(e) => return Err(e)
|
2023-07-30 19:10:36 +00:00
|
|
|
};
|
2023-07-31 17:22:28 +00:00
|
|
|
println!("Done!");
|
2023-06-22 20:08:10 +00:00
|
|
|
|
|
|
|
post_queue.iter().for_each(|post| {
|
|
|
|
println!("Posting: {}", post.name);
|
2023-07-30 18:34:24 +00:00
|
|
|
loop {
|
2023-07-31 17:50:22 +00:00
|
|
|
if self.post(post.clone()).is_ok() {break};
|
2023-07-30 18:34:24 +00:00
|
|
|
println!("Post attempt failed, retrying");
|
|
|
|
}
|
2023-06-22 20:08:10 +00:00
|
|
|
});
|
2023-07-30 19:10:36 +00:00
|
|
|
|
2023-07-31 17:50:22 +00:00
|
|
|
return Ok(());
|
2023-06-26 22:33:00 +00:00
|
|
|
}
|
2023-06-22 20:08:10 +00:00
|
|
|
|
2023-06-26 22:33:00 +00:00
|
|
|
pub(crate) fn idle(&self) {
|
2023-07-31 20:50:48 +00:00
|
|
|
let mut sleep_duration = chrono::Duration::seconds(30);
|
2023-07-31 20:55:50 +00:00
|
|
|
if Utc::now().time() - self.start_time.time() > sleep_duration {
|
2023-07-31 20:50:48 +00:00
|
|
|
sleep_duration = chrono::Duration::seconds(60);
|
|
|
|
}
|
2023-07-31 21:01:52 +00:00
|
|
|
|
2023-07-31 20:50:48 +00:00
|
|
|
while Utc::now().time() - self.start_time.time() < sleep_duration {
|
2023-07-31 21:01:52 +00:00
|
|
|
sleep(time::Duration::from_secs(1));
|
2023-06-22 20:08:10 +00:00
|
|
|
}
|
2023-08-02 21:39:35 +00:00
|
|
|
|
2023-07-30 18:34:24 +00:00
|
|
|
match reqwest::blocking::get("https://status.neshweb.net/api/push/7s1CjPPzrV?status=up&msg=OK&ping=") {
|
|
|
|
Ok(_) => {},
|
|
|
|
Err(err) => println!("{}", err)
|
|
|
|
};
|
2023-06-26 22:33:00 +00:00
|
|
|
}
|
2023-07-29 00:32:58 +00:00
|
|
|
|
|
|
|
pub(crate) fn print_info(&self) {
|
|
|
|
print!("\x1B[2J\x1B[1;1H");
|
|
|
|
println!("##[Ascendance of a Bookworm Bot]##");
|
|
|
|
println!("Instance: {}", &self.config.instance);
|
|
|
|
println!("Ran Last: {}", &self.start_time.format("%d/%m/%Y %H:%M:%S"));
|
|
|
|
println!("{:#<1$}", "", 30);
|
|
|
|
self.post_history.iter().for_each(|post| {
|
|
|
|
print!("{} ", post.title);
|
|
|
|
print!("{:<1$}: ", "", 60 - post.title.len());
|
|
|
|
println!("{}", post.last_post_url);
|
|
|
|
})
|
|
|
|
}
|
2023-06-18 22:26:50 +00:00
|
|
|
}
|
|
|
|
|
2023-06-19 20:10:28 +00:00
|
|
|
fn list_posts(auth: &Sensitive<String>, base: String) -> GetPostsResponse {
|
2023-06-18 22:26:50 +00:00
|
|
|
let params = GetPosts {
|
|
|
|
type_: Some(ListingType::Local),
|
|
|
|
sort: Some(SortType::New),
|
|
|
|
auth: Some(auth.clone()),
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
|
|
|
|
let res = CLIENT
|
2023-06-19 20:10:28 +00:00
|
|
|
.get(base + "/api/v3/post/list")
|
2023-06-18 22:26:50 +00:00
|
|
|
.query(¶ms)
|
|
|
|
.send()
|
|
|
|
.unwrap()
|
|
|
|
.text()
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
return serde_json::from_str(&res).unwrap();
|
|
|
|
}
|
|
|
|
|
2023-07-29 00:32:58 +00:00
|
|
|
fn run_bot() {
|
2023-07-30 18:34:24 +00:00
|
|
|
// Get all needed auth tokens at the start
|
|
|
|
let mut old = Utc::now().time();
|
|
|
|
let mut this = Bot::new();
|
2023-07-31 17:50:22 +00:00
|
|
|
match this.login() {
|
|
|
|
Ok(_) => {
|
|
|
|
this.community_ids.load(&this.auth, &this.config.instance);
|
|
|
|
|
|
|
|
// Enter a loop (not for debugging)
|
|
|
|
loop {
|
2023-08-02 21:39:35 +00:00
|
|
|
println!("Start Time: {}", this.start_time.time());
|
|
|
|
println!("Previous Time: {}", old);
|
2023-08-02 21:42:25 +00:00
|
|
|
println!("Difference Start - Old: {}", this.start_time.time() - old);
|
|
|
|
println!("Difference Now - Start: {}", Utc::now().time() - this.start_time.time());
|
2023-07-31 17:50:22 +00:00
|
|
|
this.idle();
|
|
|
|
// 3 retries in case of connection issues
|
|
|
|
let mut loop_breaker: u8 = 0;
|
2023-08-02 22:04:19 +00:00
|
|
|
while !this.run_once(&mut old).is_ok() && loop_breaker <= 3 {
|
2023-07-31 17:50:22 +00:00
|
|
|
println!("Unable to complete Bot cycle, retrying with fresh login credentials");
|
|
|
|
if this.login().is_ok() {
|
|
|
|
this.community_ids.load(&this.auth, &this.config.instance);
|
|
|
|
}
|
|
|
|
sleep(time::Duration::from_secs(10));
|
|
|
|
loop_breaker += 1;
|
|
|
|
};
|
|
|
|
this.print_info();
|
2023-08-02 21:39:35 +00:00
|
|
|
println!("Start Time: {}", this.start_time.time());
|
|
|
|
println!("Previous Time: {}", old);
|
2023-08-02 22:04:19 +00:00
|
|
|
println!("Difference Start - Old: {}", this.start_time.time() - old);
|
2023-08-02 21:42:25 +00:00
|
|
|
println!("Difference Now - Start: {}", Utc::now().time() - this.start_time.time());
|
2023-07-31 17:50:22 +00:00
|
|
|
this.idle();
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Err(e) => {
|
|
|
|
println!("Unable to get initial login:\n {:#?}", e);
|
2023-07-30 18:34:24 +00:00
|
|
|
}
|
|
|
|
}
|
2023-06-21 19:29:14 +00:00
|
|
|
}
|
2023-07-31 17:50:22 +00:00
|
|
|
fn main() {
|
2023-07-29 00:32:58 +00:00
|
|
|
run_bot();
|
2023-06-18 22:26:50 +00:00
|
|
|
}
|