Compare commits

...

23 commits

Author SHA1 Message Date
f3bb504cfd
Release 3.3.1 2025-06-14 20:52:15 +02:00
42aff098bd
Login Delay 2025-06-14 20:52:05 +02:00
204d413779
Release 3.3.0 2025-06-14 20:21:36 +02:00
10111ff612
Change API Version from Lemmy v3 to Piefed Alpha 2025-06-14 20:21:23 +02:00
13954f26aa
Release 3.2.2 2025-04-22 13:33:23 +02:00
3abfaf55c1
Syntax Fix 2025-04-22 13:33:12 +02:00
da4220e027
Iterate over all returned posts from API rather than only the first one since pins stay at the top 2025-04-22 13:27:32 +02:00
3b5e65b350
Release 3.2.1 - fix 2025-03-25 21:11:44 +01:00
041590a559
Release 3.2.0 2024-10-22 16:15:19 +02:00
d6f883f890
Bump API version 2024-10-22 16:14:46 +02:00
b07420e0bd Merge pull request 'Bump forgejo-release to v2' () from actions-update into main
Reviewed-on: https://forgejo.neshweb.net///Neshura/aob-lemmy-bot/pulls/26
2024-08-06 12:23:26 +00:00
0fc71f0a7d Bump forgejo-release to v2 2024-08-06 12:19:37 +00:00
2ae6468ad8
Release 3.1.0 2024-07-15 22:15:49 +02:00
2ecfe88cb9
Update to 0.19.5 and include optional thumbnail 2024-07-15 22:15:31 +02:00
7dcc7bfee2
Release 3.0.3 2024-05-08 16:34:48 +02:00
94d8a4e673
Add Timeout to Status Ping HTTP Request 2024-05-08 16:34:32 +02:00
1b585eab7e
Release 3.0.2 2024-05-07 23:50:14 +02:00
b6f5c38e4a
Overhaul Error handling (Option instead of Result<T, ()> + Logging changes 2024-05-07 23:49:55 +02:00
5d708bdb82
Release 3.0.1 2024-05-07 22:50:22 +02:00
6a8c1662f0
Fix enum problems in config 2024-05-07 22:50:12 +02:00
e02cd900ed
Release 3.0.0 2024-05-07 22:35:15 +02:00
32ea83a7bb
Release Candidate 3.0.0-rc.2 2024-05-07 22:30:02 +02:00
4297860b9e
Legacy fixes for async traits 2024-05-07 22:29:48 +02:00
9 changed files with 948 additions and 251 deletions

View file

@ -137,7 +137,7 @@ jobs:
run: rm release_blobs/build.env
-
name: Release New Version
uses: actions/forgejo-release@v1
uses: actions/forgejo-release@v2
with:
direction: upload
url: https://forgejo.neshweb.net

810
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
[package]
authors = ["Neshura"]
name = "aob-lemmy-bot"
version = "3.0.0-rc.1"
version = "3.3.1"
edition = "2021"
description = "Bot for automatically posting new chapters of 'Ascendance of a Bookworm' released by J-Novel Club"
license = "GPL-3.0-or-later"
@ -17,8 +17,8 @@ systemd-units = { enable = false }
[dependencies]
chrono = "^0.4"
lemmy_api_common = "0.19.3"
lemmy_db_schema = "0.19.3"
lemmy_api_common = "0.19.9"
lemmy_db_schema = "0.19.9"
once_cell = "^1.19"
reqwest = { version = "^0.12", features = ["blocking", "json"] }
serde = "^1.0"
@ -31,4 +31,5 @@ confy = "^0.6"
toml = "^0.8"
systemd-journal-logger = "^2.1.1"
log = "^0.4"
async-trait = "^0.1"
notify = "6.1.1"

View file

@ -1,4 +1,4 @@
use crate::{config::{Config}};
use crate::{config::{Config}, HTTP_CLIENT};
use crate::lemmy::{Lemmy};
use crate::post_history::{SeriesHistory};
use chrono::{DateTime, Duration, Utc};
@ -7,6 +7,15 @@ use notify::{Event, EventKind, event::{AccessKind, AccessMode}, RecursiveMode, W
use tokio::time::sleep;
use systemd_journal_logger::connected_to_journal;
macro_rules! debug {
($msg:tt) => {
match connected_to_journal() {
true => log::debug!("[DEBUG] {}", $msg),
false => println!("[DEBUG] {}", $msg),
}
};
}
macro_rules! info {
($msg:tt) => {
match connected_to_journal() {
@ -72,10 +81,15 @@ impl Bot {
loop {
let mut lemmy = match Lemmy::new(&self.shared_config).await {
Ok(data) => data,
Err(_) => continue,
Err(_) => {
sleep(Duration::seconds(10).to_std().unwrap()).await;
continue;
},
};
lemmy.get_communities().await;
self.history = SeriesHistory::load_history();
let start: DateTime<Utc> = Utc::now();
while Utc::now() - start <= Duration::minutes(60) {
@ -84,10 +98,14 @@ impl Bot {
let read_copy = self.shared_config.read().expect("Read Lock Failed").clone();
for series in read_copy.series {
series.update(&mut self.history, &lemmy, &self.shared_config).await;
debug!("Done Updating Series");
self.wait(1, Wait::Absolute).await;
}
debug!("Awaiting Timeout");
self.wait(30, Wait::Buffer).await;
debug!("Pinging Server");
self.ping_status().await;
debug!("Awaiting Timeout 2");
self.wait(30, Wait::Absolute).await;
}
@ -98,7 +116,7 @@ impl Bot {
async fn ping_status(&self) {
let read_config = &self.shared_config.read().expect("Read Lock Failed").clone();
if let Some(status_url) = &read_config.status_post_url {
match reqwest::get(status_url).await {
match HTTP_CLIENT.get(status_url).send().await {
Ok(_) => {},
Err(e) => {
let err_msg = format!("While pinging status URL: {e}");

View file

@ -2,8 +2,8 @@ use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use chrono::{Timelike, Utc};
use crate::config::PostBody::Description;
use lemmy_api_common::sensitive::Sensitive;
use lemmy_db_schema::PostFeatureType;
use lemmy_db_schema::sensitive::SensitiveString;
use serde_derive::{Deserialize, Serialize};
use crate::lemmy::{Lemmy, PartInfo, PostType};
use crate::post_history::{SeriesHistory};
@ -11,6 +11,15 @@ use systemd_journal_logger::connected_to_journal;
use crate::fetchers::{FetcherTrait, Fetcher};
use crate::fetchers::jnovel::{JNovelFetcher};
macro_rules! debug {
($msg:tt) => {
match connected_to_journal() {
true => log::debug!("[DEBUG] {}", $msg),
false => println!("[DEBUG] {}", $msg),
}
};
}
macro_rules! info {
($msg:tt) => {
match connected_to_journal() {
@ -41,8 +50,8 @@ macro_rules! error {
#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct Config {
pub(crate) instance: String,
username: String,
password: String,
username: SensitiveString,
password: SensitiveString,
pub(crate) status_post_url: Option<String>,
pub(crate) config_reload_seconds: u32,
pub(crate) protected_communities: Vec<String>,
@ -80,12 +89,12 @@ impl Config {
confy::get_configuration_file_path(env!("CARGO_PKG_NAME"), "config").expect("Application will not without confy")
}
pub(crate) fn get_username(&self) -> Sensitive<String> {
Sensitive::new(self.username.clone())
pub(crate) fn get_username(&self) -> SensitiveString {
self.username.clone()
}
pub(crate) fn get_password(&self) -> Sensitive<String> {
Sensitive::new(self.password.clone())
pub(crate) fn get_password(&self) -> SensitiveString {
self.password.clone()
}
}
@ -93,8 +102,8 @@ impl Default for Config {
fn default() -> Self {
Config {
instance: "".to_owned(),
username: "".to_owned(),
password: "".to_owned(),
username: SensitiveString::from("".to_owned()),
password: SensitiveString::from("".to_owned()),
status_post_url: None,
config_reload_seconds: 21600,
protected_communities: vec![],
@ -167,11 +176,17 @@ impl SeriesConfig {
);
info!(info);
let post_id = match lemmy.post(post_data).await {
Ok(data) => data,
Err(_) => {
error!("Error posting chapter");
return;
let post_id = match lemmy.post(post_data.clone()).await {
Some(data) => data,
None => {
error!("Error posting chapter, applying fix for Issue #27");
match lemmy.check_community_for_post(post_data).await {
Some(data) => data,
None => {
error!("Unable to find Post via API");
return;
}
}
}
};
@ -188,31 +203,18 @@ impl SeriesConfig {
post_info.get_post_config(self).name.as_str()
);
info!(info);
let pinned_posts = match lemmy.get_community_pinned(lemmy.get_community_id(&post_info.get_post_config(self).name)).await {
Ok(data) => data,
Err(_) => {
error!("Pinning of Post to community failed");
continue;
}
};
let pinned_posts = lemmy.get_community_pinned(lemmy.get_community_id(&post_info.get_post_config(self).name)).await.unwrap_or_else(|| {
error!("Pinning of Post to community failed");
vec![]
});
if !pinned_posts.is_empty() {
let community_pinned_post = &pinned_posts[0];
match lemmy
.unpin(community_pinned_post.post.id, PostFeatureType::Community)
.await {
Ok(_) => {}
Err(_) => {
error!("Error un-pinning post");
return;
}
if lemmy.unpin(community_pinned_post.post.id, PostFeatureType::Community).await.is_none() {
error!("Error un-pinning post");
}
}
match lemmy.pin(post_id, PostFeatureType::Community).await {
Ok(_) => {}
Err(_) => {
error!("Error pinning post");
return;
}
if lemmy.pin(post_id, PostFeatureType::Community).await.is_none() {
error!("Error pinning post");
}
} else if read_config
.protected_communities
@ -229,10 +231,10 @@ impl SeriesConfig {
let info = format!("Pinning '{}' to Instance", post_info.get_info().title);
info!(info);
let pinned_posts = match lemmy.get_local_pinned().await {
Ok(data) => {data}
Err(_) => {
Some(data) => {data}
None => {
error!("Error fetching pinned posts");
return;
vec![]
}
};
@ -245,25 +247,16 @@ impl SeriesConfig {
continue;
} else {
let community_pinned_post = &pinned_post;
match lemmy
.unpin(community_pinned_post.post.id, PostFeatureType::Local)
.await {
Ok(_) => {}
Err(_) => {
error!("Error pinning post");
return;
}
if lemmy.unpin(community_pinned_post.post.id, PostFeatureType::Local).await.is_none() {
error!("Error pinning post");
continue;
}
break;
}
}
}
match lemmy.pin(post_id, PostFeatureType::Local).await {
Ok(_) => {}
Err(_) => {
error!("Error pinning post");
return;
}
if lemmy.pin(post_id, PostFeatureType::Local).await.is_none() {
error!("Error pinning post");
};
}
@ -283,6 +276,7 @@ impl SeriesConfig {
series_history.set_part(post_info.get_part_info().unwrap_or(PartInfo::NoParts).as_string().as_str(), part_history);
history
.set_series(self.slug.as_str(), series_history);
debug!("Saving History");
history.save_history();
}
}

View file

@ -3,7 +3,7 @@ use chrono::{DateTime, Duration, Utc};
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::ops::Sub;
use url::Url;
use async_trait::async_trait;
use crate::fetchers::{FetcherTrait};
use crate::lemmy::{PartInfo, PostInfo, PostInfoInner, PostType};
use systemd_journal_logger::connected_to_journal;
@ -31,7 +31,7 @@ static PAST_DAYS_ELIGIBLE: u8 = 4;
macro_rules! api_url {
() => {
"https://labs.j-novel.club/app/v1".to_owned()
"https://labs.j-novel.club/app/v2".to_owned()
};
}
@ -94,6 +94,15 @@ pub(crate) struct JNovelFetcher {
series_has_parts: bool
}
impl Default for JNovelFetcher {
fn default() -> Self {
Self {
series_slug: "".to_owned(),
series_has_parts: false,
}
}
}
impl JNovelFetcher {
pub(crate) fn set_series(&mut self, series: String) {
self.series_slug = series;
@ -104,6 +113,7 @@ impl JNovelFetcher {
}
}
#[async_trait]
impl FetcherTrait for JNovelFetcher {
fn new() -> Self {
JNovelFetcher {
@ -190,7 +200,8 @@ impl FetcherTrait for JNovelFetcher {
);
let post_details = PostInfoInner {
title: volume.title.clone(),
url: Url::parse(&post_url).unwrap(),
url: post_url.clone(),
thumbnail: Some(volume.cover.thumbnail.clone())
};
let new_post_info = PostInfo {
@ -213,7 +224,7 @@ impl FetcherTrait for JNovelFetcher {
.or_insert(new_post_info);
}
if let Some(prepub_info) = get_latest_prepub(&volume.slug).await? {
if let Some(prepub_info) = get_latest_prepub(&volume.slug).await {
let prepub_post_info = PostInfo {
post_type: Some(PostType::Chapter),
part: Some(new_part_info),
@ -241,7 +252,7 @@ impl FetcherTrait for JNovelFetcher {
}
async fn get_latest_prepub(volume_slug: &str) -> Result<Option<PostInfoInner>, ()> {
async fn get_latest_prepub(volume_slug: &str) -> Option<PostInfoInner> {
let response = match HTTP_CLIENT
.get(api_url!() + "/volumes/" + volume_slug + "/parts?format=json")
.send()
@ -252,13 +263,13 @@ async fn get_latest_prepub(volume_slug: &str) -> Result<Option<PostInfoInner>, (
Err(e) => {
let err_msg = format!("While getting latest PrePub: {e}");
error!(err_msg);
return Err(());
return None;
}
},
Err(e) => {
let err_msg = format!("{e}");
error!(err_msg);
return Err(());
return None;
}
};
@ -267,7 +278,7 @@ async fn get_latest_prepub(volume_slug: &str) -> Result<Option<PostInfoInner>, (
Err(e) => {
let err_msg = format!("{e}");
error!(err_msg);
return Err(());
return None;
}
};
volume_prepub_parts_data.parts.reverse(); // Makes breaking out of the parts loop easier
@ -282,12 +293,15 @@ async fn get_latest_prepub(volume_slug: &str) -> Result<Option<PostInfoInner>, (
continue;
}
let thumbnail = prepub_part.cover.as_ref().map(|cover| cover.thumbnail.clone());
let post_url = format!("{}/read/{}", jnc_base_url!(), prepub_part.slug);
post_details = Some(PostInfoInner {
title: prepub_part.title.clone(),
url: Url::parse(&post_url).unwrap(),
url: post_url.clone(),
thumbnail
});
}
Ok(post_details)
post_details
}

View file

@ -1,3 +1,4 @@
use async_trait::async_trait;
use serde_derive::{Deserialize, Serialize};
use strum_macros::Display;
use crate::fetchers::Fetcher::Jnc;
@ -6,6 +7,7 @@ use crate::lemmy::{PostInfo};
pub mod jnovel;
#[async_trait]
pub(crate) trait FetcherTrait {
fn new() -> Self where Self: Sized;
async fn check_feed(&self) -> Result<Vec<PostInfo>, ()>;
@ -27,5 +29,5 @@ impl Fetcher {
#[derive(Deserialize, Serialize, Debug, Clone, Display)]
pub(crate) enum Fetcher {
#[serde(rename = "jnc")]
Jnc(JNovelFetcher)
Jnc(#[serde(skip)] JNovelFetcher)
}

View file

@ -5,16 +5,33 @@ use lemmy_api_common::community::{ListCommunities, ListCommunitiesResponse};
use lemmy_api_common::lemmy_db_views::structs::PostView;
use lemmy_api_common::person::{Login, LoginResponse};
use lemmy_api_common::post::{CreatePost, FeaturePost, GetPosts, GetPostsResponse};
use lemmy_api_common::sensitive::Sensitive;
use lemmy_db_schema::newtypes::{CommunityId, LanguageId, PostId};
use lemmy_db_schema::{ListingType, PostFeatureType};
use lemmy_db_schema::{ListingType, PostFeatureType, SortType};
use reqwest::StatusCode;
use std::collections::HashMap;
use std::sync::{RwLock};
use lemmy_db_schema::sensitive::SensitiveString;
use serde::{Deserialize, Serialize};
use url::Url;
use systemd_journal_logger::connected_to_journal;
macro_rules! debug {
($msg:tt) => {
match connected_to_journal() {
true => log::debug!("[DEBUG] {}", $msg),
false => println!("[DEBUG] {}", $msg),
}
};
}
macro_rules! info {
($msg:tt) => {
match connected_to_journal() {
true => log::info!("[INFO] {}", $msg),
false => println!("[INFO] {}", $msg),
}
};
}
macro_rules! error {
($msg:tt) => {
match connected_to_journal() {
@ -25,7 +42,7 @@ macro_rules! error {
}
pub(crate) struct Lemmy {
jwt_token: Sensitive<String>,
jwt_token: SensitiveString,
instance: String,
communities: HashMap<String, CommunityId>,
}
@ -34,7 +51,8 @@ pub(crate) struct Lemmy {
#[derive(Debug, Clone)]
pub(crate) struct PostInfoInner {
pub(crate) title: String,
pub(crate) url: Url,
pub(crate) url: String,
pub(crate) thumbnail: Option<String>
}
#[derive(Debug, Copy, Clone)]
@ -124,7 +142,7 @@ impl PostInfo {
pub(crate) fn get_part_info(&self) -> Option<PartInfo> {
self.part
}
pub(crate) fn get_post_config(&self, series: &SeriesConfig) -> PostConfig {
match self.post_type {
Some(post_type) => {
@ -136,10 +154,10 @@ impl PostInfo {
None => series.prepub_community.clone(),
}
}
pub(crate) fn get_post_data(&self, series: &SeriesConfig, lemmy: &Lemmy) -> CreatePost {
let post_config = self.get_post_config(series);
let post_body = match &post_config.post_body {
PostBody::None => None,
PostBody::Description => self.get_description(),
@ -152,11 +170,13 @@ impl PostInfo {
name: self.get_info().title.clone(),
community_id,
url: Some(self.get_info().url),
custom_thumbnail: self.get_info().thumbnail,
body: post_body,
alt_text: None,
honeypot: None,
nsfw: None,
language_id: Some(LanguageId(37)), // TODO get this id once every few hours per API request, the ordering of IDs suggests that the EN Id might change in the future
}
}
}
}
@ -207,7 +227,7 @@ impl Lemmy {
};
let response = match HTTP_CLIENT
.post(read_config.instance.to_owned() + "/api/v3/user/login")
.post(read_config.instance.to_owned() + "/api/alpha/user/login")
.json(&login_params)
.send()
.await
@ -248,25 +268,37 @@ impl Lemmy {
}
pub(crate) async fn logout(&self) {
let _ = self.post_data_json("/api/v3/user/logout", &"").await;
let _ = self.post_data_json("/api/alpha/user/logout", &"").await;
}
pub(crate) async fn post(&self, post: CreatePost) -> Result<PostId, ()> {
let response: String = self.post_data_json("/api/v3/post", &post).await?;
let json_data: PostView = self.parse_json_map(&response).await?;
pub(crate) async fn post(&self, post: CreatePost) -> Option<PostId> {
let response: String = match self.post_data_json("/api/alpha/post", &post).await {
Some(data) => data,
None => return None,
};
let json_data: PostView = match self.parse_json_map(&response).await {
Some(data) => data,
None => return None,
};
Ok(json_data.post.id)
Some(json_data.post.id)
}
async fn feature(&self, params: FeaturePost) -> Result<PostView, ()> {
let response: String = self.post_data_json("/api/v3/post/feature", &params).await?;
let json_data: PostView = self.parse_json_map(&response).await?;
async fn feature(&self, params: FeaturePost) -> Option<PostView> {
let response: String = match self.post_data_json("/api/alpha/post/feature", &params).await {
Some(data) => data,
None => return None,
};
let json_data: PostView = match self.parse_json_map(&response).await {
Some(data) => data,
None => return None,
};
Ok(json_data)
Some(json_data)
}
pub(crate) async fn unpin(&self, post_id: PostId, location: PostFeatureType) -> Result<PostView, ()> {
pub(crate) async fn unpin(&self, post_id: PostId, location: PostFeatureType) -> Option<PostView> {
let pin_params = FeaturePost {
post_id,
featured: false,
@ -275,7 +307,7 @@ impl Lemmy {
self.feature(pin_params).await
}
pub(crate) async fn pin(&self, post_id: PostId, location: PostFeatureType) -> Result<PostView, ()> {
pub(crate) async fn pin(&self, post_id: PostId, location: PostFeatureType) -> Option<PostView> {
let pin_params = FeaturePost {
post_id,
featured: true,
@ -284,17 +316,23 @@ impl Lemmy {
self.feature(pin_params).await
}
pub(crate) async fn get_community_pinned(&self, community: CommunityId) -> Result<Vec<PostView>, ()> {
pub(crate) async fn get_community_pinned(&self, community: CommunityId) -> Option<Vec<PostView>> {
let list_params = GetPosts {
community_id: Some(community),
type_: Some(ListingType::Local),
..Default::default()
};
let response: String = self.get_data_query("/api/v3/post/list", &list_params).await?;
let json_data: GetPostsResponse = self.parse_json(&response).await?;
let response: String = match self.get_data_query("/api/alpha/post/list", &list_params).await {
Some(data) => data,
None => return None,
};
let json_data: GetPostsResponse = match self.parse_json(&response).await {
Some(data) => data,
None => return None,
};
Ok(json_data
Some(json_data
.posts
.iter()
.filter(|post| post.post.featured_community)
@ -302,16 +340,22 @@ impl Lemmy {
.collect())
}
pub(crate) async fn get_local_pinned(&self) -> Result<Vec<PostView>, ()> {
pub(crate) async fn get_local_pinned(&self) -> Option<Vec<PostView>> {
let list_params = GetPosts {
type_: Some(ListingType::Local),
..Default::default()
};
let response: String = self.get_data_query("/api/v3/post/list", &list_params).await?;
let json_data: GetPostsResponse = self.parse_json(&response).await?;
let response: String = match self.get_data_query("/api/alpha/post/list", &list_params).await {
Some(data) => data,
None => return None,
};
let json_data: GetPostsResponse = match self.parse_json(&response).await {
Some(data) => data,
None => return None,
};
Ok(json_data
Some(json_data
.posts
.iter()
.filter(|post| post.post.featured_local)
@ -325,19 +369,13 @@ impl Lemmy {
..Default::default()
};
let response: String = match self.get_data_query("/api/v3/community/list", &list_params).await {
Ok(data) => data,
Err(_) => {
error!("Unable to extract data from request");
return;
}
let response: String = match self.get_data_query("/api/alpha/community/list", &list_params).await {
Some(data) => data,
None => return,
};
let json_data: ListCommunitiesResponse = match self.parse_json::<ListCommunitiesResponse>(&response).await {
Ok(data) => data,
Err(_) => {
error!("Unable to parse data from json");
return;
},
Some(data) => data,
None => return,
};
let mut communities: HashMap<String, CommunityId> = HashMap::new();
@ -349,62 +387,114 @@ impl Lemmy {
self.communities = communities;
}
async fn post_data_json<T: Serialize>(&self, route: &str, json: &T ) -> Result<String,()> {
pub(crate) async fn check_community_for_post(&self, post: CreatePost) -> Option<PostId> {
let get_params: GetPosts = GetPosts {
type_: None,
sort: Some(SortType::New),
page: None,
limit: None,
community_id: Some(post.community_id),
community_name: None,
saved_only: None,
liked_only: None,
disliked_only: None,
show_hidden: None,
show_read: None,
show_nsfw: None,
page_cursor: None,
};
let response: String = match self.get_data_query("/api/alpha/post/list", &get_params).await {
Some(data) => data,
None => {
error!("Unable to query post list");
return None
},
};
let json_data: GetPostsResponse = match self.parse_json(&response).await {
Some(data) => data,
None => {
error!("Unable to parse post data");
return None
},
};
for api_post in json_data.posts {
if api_post.post.name == post.name {
return Some(api_post.post.id);
}
}
let msg = format!("Unable to find post {}", post.name);
info!(msg);
None
}
async fn post_data_json<T: Serialize>(&self, route: &str, json: &T ) -> Option<String> {
let res = HTTP_CLIENT
.post(format!("{}{route}", &self.instance))
.bearer_auth(&self.jwt_token.to_string())
.bearer_auth(self.jwt_token.to_string())
.json(&json)
.send()
.await;
self.extract_data(res).await
}
async fn get_data_query<T: Serialize>(&self, route: &str, param: &T ) -> Result<String,()> {
async fn get_data_query<T: Serialize>(&self, route: &str, param: &T ) -> Option<String> {
let res = HTTP_CLIENT
.get(format!("{}{route}", &self.instance))
.bearer_auth(&self.jwt_token.to_string())
.bearer_auth(self.jwt_token.to_string())
.query(&param)
.send()
.await;
self.extract_data(res).await
}
async fn extract_data(&self, response: Result<reqwest::Response, reqwest::Error>) -> Result<String,()> {
async fn extract_data(&self, response: Result<reqwest::Response, reqwest::Error>) -> Option<String> {
match response {
Ok(data) => match data.text().await {
Ok(data) => Ok(data),
Err(e) => {
let err_msg = format!("{e}");
Ok(data) => {
if data.status().is_success() {
match data.text().await {
Ok(data) => Some(data),
Err(e) => {
let err_msg = format!("{e}");
error!(err_msg);
None
}
}
}
else {
let err_msg = format!("HTTP Request failed: {}", data.text().await.unwrap());
error!(err_msg);
Err(())
None
}
},
Err(e) => {
let err_msg = format!("{e}");
error!(err_msg);
Err(())
None
}
}
}
async fn parse_json<'a, T: Deserialize<'a>>(&self, response: &'a str) -> Result<T,()> {
async fn parse_json<'a, T: Deserialize<'a>>(&self, response: &'a str) -> Option<T> {
match serde_json::from_str::<T>(response) {
Ok(data) => Ok(data),
Ok(data) => Some(data),
Err(e) => {
let err_msg = format!("{e} while parsing JSON");
let err_msg = format!("while parsing JSON: {e} ");
error!(err_msg);
Err(())
None
}
}
}
async fn parse_json_map<'a, T: Deserialize<'a>>(&self, response: &'a str) -> Result<T,()> {
async fn parse_json_map<'a, T: Deserialize<'a>>(&self, response: &'a str) -> Option<T> {
debug!(response);
match serde_json::from_str::<HashMap<&str, T>>(response) {
Ok(mut data) => Ok(data.remove("post_view").expect("Element should be present")),
Ok(mut data) => Some(data.remove("post_view").expect("Element should be present")),
Err(e) => {
let err_msg = format!("{e} while parsing JSON HashMap");
let err_msg = format!("while parsing JSON HashMap: {e}");
error!(err_msg);
Err(())
None
}
}
}

View file

@ -25,7 +25,17 @@ async fn main() {
.expect("Systemd-Logger crate error")
.install()
.expect("Systemd-Logger crate error");
log::set_max_level(LevelFilter::Info);
match std::env::var("LOG_LEVEL") {
Ok(level) => {
match level.as_str() {
"debug" => log::set_max_level(LevelFilter::Debug),
"info" => log::set_max_level(LevelFilter::Info),
_ => log::set_max_level(LevelFilter::Info),
}
}
_ => log::set_max_level(LevelFilter::Info),
}
let mut bot = Bot::new();
bot.run().await;
}