Move username and password to config file

This commit is contained in:
Neshura 2023-12-29 14:35:07 +01:00
parent 654bc5c7f8
commit 8d75aaa4f7
Signed by: Neshura
GPG key ID: B6983AAA6B9A7A6C
6 changed files with 46 additions and 27 deletions

View file

@ -1,15 +1,10 @@
# ascendance-of-a-bookworm-bot
**.env**
```bash
LEMMY_USERNAME="BotUserName"
LEMMY_PASSWORD="BotPassword"
```
*Note: Passwords containing special characters might need to be escaped using '\'*
**config.toml**
```toml
instance = "https://lemmy.example.org"
username = "BotUserName"
password = "BotPassword" # Note: Passwords containing special characters might need to be escaped using '\\'
status_post_url = "PostUrlForStatusMonitoring"
config_reload_seconds = 10800

View file

@ -13,15 +13,11 @@ use crate::post_history::SeriesHistory;
use tokio::time::sleep;
pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
let credentials = match lemmy::Credentials::set_credentials() {
Ok(creds) => creds,
Err(e) => panic!("{}", e.to_string()),
};
let mut last_reload: DateTime<Utc>;
let mut lemmy: Lemmy;
let mut login_error: bool;
let mut communities;
let mut credentials;
{
let mut write = data.write().await;
@ -34,6 +30,11 @@ pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
last_reload = Utc::now();
}
{
let read = data.read().await;
credentials = lemmy::Credentials::set_credentials(&read.config);
}
{
let read = data.read().await;
lemmy = match lemmy::login(&credentials, read.config.instance.as_str()).await {
@ -77,6 +78,14 @@ pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
}
}
{
let read = data.read().await;
if read.start - last_reload >= Duration::seconds(read.config.config_reload_seconds as i64) {
credentials = lemmy::Credentials::set_credentials(&read.config);
}
}
{
let read = data.read().await;
if login_error {

View file

@ -4,6 +4,8 @@ use crate::config::PostBody::Description;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct Config {
pub(crate) instance: String,
pub(crate) username: String,
pub(crate) password: String,
pub(crate) status_post_url: Option<String>,
pub(crate) config_reload_seconds: u32,
pub(crate) protected_communities: Vec<String>,
@ -12,12 +14,21 @@ pub(crate) struct Config {
impl Config {
pub(crate) fn load() -> Result<Self, String> {
let cfg: Self = match confy::load_path("./config.toml") {
let cfg: Self = match confy::load(env!("CARGO_PKG_NAME"), "config") {
Ok(data) => data,
Err(_) => panic!("config.toml not found!"),
Err(e) => panic!("config.toml not found: {e}"),
};
if cfg.instance.is_empty() {
panic!("config.toml not found!")
panic!("bot instance not set!")
}
if cfg.username.is_empty() {
panic!("bot username not set!")
}
if cfg.password.is_empty() {
panic!("bot password not provided!")
}
cfg.series.iter().for_each(|series| {
@ -33,6 +44,8 @@ impl Default for Config {
fn default() -> Self {
Config {
instance: "".to_owned(),
username: "".to_owned(),
password: "".to_owned(),
status_post_url: None,
config_reload_seconds: 21600,
protected_communities: vec![],

View file

@ -1,6 +1,4 @@
use std::collections::HashMap;
use std::env;
use std::env::VarError;
use lemmy_api_common::community::{ListCommunities, ListCommunitiesResponse};
use lemmy_api_common::lemmy_db_views::structs::PostView;
use lemmy_api_common::person::{Login, LoginResponse};
@ -9,6 +7,7 @@ use lemmy_api_common::sensitive::Sensitive;
use lemmy_db_schema::newtypes::{CommunityId, PostId};
use lemmy_db_schema::{ListingType, PostFeatureType};
use reqwest::StatusCode;
use crate::config::Config;
use crate::HTTP_CLIENT;
pub(crate) struct Credentials {
@ -25,13 +24,11 @@ impl Credentials {
Sensitive::new(self.password.clone())
}
pub(crate) fn set_credentials() -> Result<Self, VarError> {
let username = env::var("LEMMY_USERNAME")?;
let password = env::var("LEMMY_PASSWORD")?;
Ok(Credentials {
username,
password,
})
pub(crate) fn set_credentials(config: &Config) -> Self {
Self {
username: config.username.clone(),
password: config.password.clone(),
}
}
}

View file

@ -5,7 +5,6 @@ use std::{collections::HashMap, vec};
use std::fmt::Debug;
use std::sync::{Arc};
use tokio::sync::{RwLock};
use dotenv::dotenv;
use strum_macros::Display;
use tokio::time::sleep;
use crate::config::Config;
@ -40,6 +39,8 @@ impl SharedData {
messages: vec![],
config: Config {
instance: "".to_owned(),
username: "".to_owned(),
password: "".to_owned(),
status_post_url: None,
config_reload_seconds: 0,
protected_communities: vec![],
@ -82,7 +83,6 @@ impl Message {
#[tokio::main]
async fn main() {
dotenv().ok();
let mut data = SharedData::new();

View file

@ -12,7 +12,12 @@ pub(crate) struct SeriesHistory {
impl SeriesHistory {
pub(crate) fn load_history() -> Result<Self, String> {
match Path::new("history.toml").exists() {
let path = confy::get_configuration_file_path(env!("CARGO_PKG_NAME"), "config").expect("Something went wrong with confy");
let config_dir = path.parent().expect("Something went wrong with confy");
match Path::new(format!("{}/history.toml", config_dir.to_str().expect("Conversion to str should not fail for a dir")).as_str()).exists() {
true => {
let file_contents: String = match fs::read_to_string("history.toml") {
Ok(data) => data,