Skip to content

Commit

Permalink
refactoring code
Browse files Browse the repository at this point in the history
  • Loading branch information
cristiancolosimo committed Oct 10, 2023
1 parent 4d9ed86 commit de785d9
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 86 deletions.
6 changes: 0 additions & 6 deletions .env
Original file line number Diff line number Diff line change
@@ -1,6 +0,0 @@
POLLING_INTERVAL=60
HISTORY_INTERVAL=125
GET_LAB_STATE_ENDPOINT=http://presence.hlcs.it/gates/internal/
GET_LAB_HISTORY_ENDPOINT=http://presence.hlcs.it/requests/internal/
RUST_LOG=info
TELOXIDE_TOKEN="6039572435:AAHg8t2WF94y4-j-Rik-YDA4yBKERHEwt4w"
154 changes: 74 additions & 80 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

use chrono::DateTime;
use serde::Deserialize;
use sqlx::{sqlite::SqlitePool, Pool, Sqlite};
Expand All @@ -25,7 +24,7 @@ async fn get_db() -> Pool<Sqlite> {
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
status bool,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
timestamp TIMESTAMP
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
Expand All @@ -44,29 +43,27 @@ fn generate_response(status: bool, name: Option<String>) -> String {
let current_hh_mm_ss = chrono::Local::now().format("%H:%M:%S").to_string();
let current_dd_mm_yyyy = chrono::Local::now().format("%d/%m/%Y").to_string();

let mut string_response = String::new();
if (status == false) {
if !status {
//Closed
string_response = format!(
return format!(
"Il laboratorio è stato chiuso alle {} del {}",
current_hh_mm_ss, current_dd_mm_yyyy
);
} else if (status == true && name.is_some()) {
//Open
string_response = format!(
} else if status == true && name.is_some() {
//Open with name
return format!(
"Il laboratorio è stato aperto alle {} del {} da {}",
current_hh_mm_ss,
current_dd_mm_yyyy,
name.unwrap()
);
} else {
//Open
string_response = format!(
//Open without name
return format!(
"Il laboratorio è stato aperto alle {} del {}",
current_hh_mm_ss, current_dd_mm_yyyy
);
}
return string_response;
}

#[derive(Debug, Deserialize)]
Expand All @@ -85,38 +82,42 @@ async fn fetch_history() -> Option<String> {
let max_time_diff_history: i64 = max_time_diff_history.parse().unwrap();
let current_state_lab_raw = reqwest::get(get_lab_history_endpoint).await;

match current_state_lab_raw {
Ok(val) => {
let parsed_resp: Vec<UserHistoryFetch> =
val.json::<Vec<UserHistoryFetch>>().await.unwrap();
let first_user = parsed_resp.first();
if first_user.is_some() {
let first_user = first_user.unwrap();
let time = format!("{}+02:00", first_user.time);
let time_parsed = DateTime::parse_from_rfc3339(&time);
if time_parsed.is_err(){
log::error!("Error parsing time: {:?} , {}" , time_parsed, time);
return None;
}
let time_parsed = time_parsed.unwrap();
let current_time = chrono::Local::now();
let time_diff = current_time.signed_duration_since(time_parsed);
let time_diff = time_diff.num_seconds();
if time_diff < max_time_diff_history{
return Some(first_user.user.clone())
}
return None;
}
return None;
}
Err(err) => {
log::error!("Error fetching lab history: {:?}", err);
}
// handle the error
if current_state_lab_raw.is_err() {
log::error!("Error fetching lab history: {:?}", current_state_lab_raw);
return None;
}
None
}

let val = current_state_lab_raw.unwrap();
let parsed_resp: Vec<UserHistoryFetch> = val.json::<Vec<UserHistoryFetch>>().await.unwrap();

let first_user = parsed_resp.first();
if first_user.is_none() {
return None;
}
let first_user = first_user.unwrap();
let env_time_offset = std::env::var("CHRONO_TIME_OFFSET");
let time_offset = if env_time_offset.is_ok() {
env_time_offset.unwrap()
} else {
//Italy offset //Offset Z for UTC
String::from("+02:00")
};
let time = format!("{}{}", first_user.time, time_offset);
let time_parsed = DateTime::parse_from_rfc3339(&time);
if time_parsed.is_err() {
log::error!("Error parsing time: {:?} , {}", time_parsed, time);
return None;
}
let time_parsed = time_parsed.unwrap();
let current_time = chrono::Local::now();
let time_diff = current_time
.signed_duration_since(time_parsed)
.num_seconds();
if time_diff < max_time_diff_history {
return Some(first_user.user.clone());
}
return None;
}

async fn fetching_state_loop(pool: &Pool<Sqlite>) {
let get_lab_state_endpoint = std::env::var("GET_LAB_STATE_ENDPOINT").unwrap();
Expand All @@ -130,7 +131,7 @@ async fn fetching_state_loop(pool: &Pool<Sqlite>) {
current_state_lab_id = current_state_lab.id;
}
Err(_) => {
log::error!("Error fetching lab state: ");
log::error!("Error fetching lab state ");
}
}
log::info!("Current state 2: {:?}", current_state_lab_id);
Expand All @@ -140,33 +141,28 @@ async fn fetching_state_loop(pool: &Pool<Sqlite>) {
sqlx::query_as::<Sqlite, Log>("SELECT * FROM logs ORDER BY id DESC LIMIT 1")
.fetch_one(pool)
.await;
let db_last_state: bool = match db_last_state {
match db_last_state {
Ok(data) => {
let db_last_status = data.status;
if db_last_status == current_state_lab_id {
log::info!("Current state:: no change");
log::info!("Current state: equal to last state");
return;
}

sqlx::query::<Sqlite>("INSERT INTO logs (status) VALUES (?)")
sqlx::query::<Sqlite>("INSERT INTO logs (status,timestamp) VALUES (?,?)")
.bind(current_state_lab_id)
.bind(chrono::Local::now().to_rfc3339())
.execute(pool)
.await
.unwrap();
let message: String;
let message: String;
if current_state_lab_id {
let history_user_name = fetch_history().await;
if(history_user_name.is_some()){
message = generate_response(current_state_lab_id, Some(history_user_name.unwrap()));
}
else{
message = generate_response(current_state_lab_id, None);
}

}else{
message = generate_response(current_state_lab_id, history_user_name);
} else {
message = generate_response(current_state_lab_id, None);
}

sqlx::query_as::<Sqlite, User>("SELECT * FROM users")
.fetch_all(pool)
.await
Expand All @@ -188,31 +184,30 @@ async fn fetching_state_loop(pool: &Pool<Sqlite>) {
data.status
}
Err(error) => {
//Insert first record
log::error!("Current state:: error {:?}", error);
log::info!("Current state:: no last state");
//Insert genesis status record
log::error!("Error genesis status record: {:?}", error);
log::info!("Current state: no last state, inserting genesis status in DB");
match sqlx::query::<Sqlite>("INSERT INTO logs (status) VALUES (?)")
.bind(false)
.bind(current_state_lab_id)
.execute(pool)
.await
{
Ok(_) => {
log::info!("Current state:: state 0 inserted");
log::info!("Current state: genesis status inserted in DB");
}
Err(err) => {
log::error!("Current state:: error insert state 0 error {:?}", err);
log::error!("Error insert genesis status in DB {:?}", err);
}
}
false
}
};
log::info!("Current state 4: {:?}", db_last_state);
}

#[tokio::main]
async fn main() {
pretty_env_logger::init();
log::info!("Starting throw dice bot...");
log::info!("Starting bot...");

let bot = Bot::from_env();

Expand All @@ -227,7 +222,7 @@ async fn main() {

loop {
interval.tick().await;
log::info!("Fetching state...");
log::info!("Fetching state LAB...");
fetching_state_loop(&pool_loop).await;
}
});
Expand All @@ -243,40 +238,39 @@ async fn loop_telegram(bot: Bot, msg: Message, db: Pool<Sqlite>) -> ResponseResu
.execute(&db)
.await;
let db_last_state: Result<Log, sqlx::Error> =
sqlx::query_as::<Sqlite, Log>("SELECT * FROM logs ORDER BY id DESC LIMIT 1")
.fetch_one(&db)
.await;
let mut message_status:Option<String> = None;
if( db_last_state.is_ok()){
sqlx::query_as::<Sqlite, Log>("SELECT * FROM logs ORDER BY id DESC LIMIT 1")
.fetch_one(&db)
.await;
let mut message_status: Option<String> = None;
if db_last_state.is_ok() {
let db_last_state = db_last_state.unwrap();
if(db_last_state.status){
if db_last_state.status {
message_status = Some(String::from("Il laboratorio è attualmente aperto"));
}
else{
} else {
message_status = Some(String::from("Il laboratorio è attualmente chiuso"));
}

}

match query {
Ok(_) => {
log::info!("User added to db");
let message: &str = "Ciao, sono il bot HLCS 🦀. Ti avviserò quando il laboratorio sarà aperto o chiuso";
let message: &str =
"Ciao, sono il bot HLCS 🦀. Ti avviserò quando il laboratorio sarà aperto o chiuso";
bot.send_message(msg.chat.id, message).await?;
if(message_status.is_some()){
bot.send_message(msg.chat.id, message_status.unwrap()).await?;
if message_status.is_some() {
bot.send_message(msg.chat.id, message_status.unwrap())
.await?;
}

}
Err(err) => {
log::info!("User already exists in db {:?}", err);
let message: &str = "Ciao, sono il bot HLCS 🦀. Ti avviserò quando il laboratorio sarà aperto o chiuso, ti avverto che eri già iscritto";
bot.send_message(msg.chat.id, message).await?;

if(message_status.is_some()){
bot.send_message(msg.chat.id, message_status.unwrap()).await?;
if message_status.is_some() {
bot.send_message(msg.chat.id, message_status.unwrap())
.await?;
}

}
}
Ok(())
Expand Down

0 comments on commit de785d9

Please sign in to comment.