Skip to content

Commit

Permalink
show mensimates ratings
Browse files Browse the repository at this point in the history
also: remove useless signals, better perf metrics, remove dbg's
  • Loading branch information
fnschmidt committed Jul 5, 2024
1 parent dd08c0e commit 3db31fe
Show file tree
Hide file tree
Showing 9 changed files with 57 additions and 109 deletions.
21 changes: 3 additions & 18 deletions src/bin/mensi-telegram-bin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ async fn main() {
if args.debug {
env::set_var("RUST_LOG", "debug");
} else if env::var(pretty_env_logger::env_logger::DEFAULT_FILTER_ENV).is_err() {
dbg!();
env::set_var("RUST_LOG", "info");
}

Expand Down Expand Up @@ -174,32 +173,19 @@ async fn run_task_scheduler(
start_mensacache_and_campusdual_job(bot.clone(), &sched, jobhandler_task_tx.clone()).await;

let mut loaded_user_data: BTreeMap<i64, RegistrationEntry> = BTreeMap::new();
load_jobs_from_db(
&bot,
&sched,
&mut loaded_user_data,
jobhandler_task_tx.clone(),
)
.await;
load_jobs_from_db(&bot, &sched, &mut loaded_user_data).await;

// start scheduler (non blocking)
sched.start().await.unwrap();

// log::info!(target: "mensi_telegram_rs::TaskSched", "Ready.");
log::info!("Ready.");

// receive job update msg (register/unregister/check existence)
while let Ok(job_handler_task) = jobhandler_task_rx.recv().await {
match job_handler_task.job_type {
JobType::Register => {
handle_add_registration_task(
&bot,
job_handler_task,
&sched,
&mut loaded_user_data,
jobhandler_task_tx.clone(),
)
.await;
handle_add_registration_task(&bot, job_handler_task, &sched, &mut loaded_user_data)
.await;
}

JobType::UpdateRegistration => {
Expand All @@ -208,7 +194,6 @@ async fn run_task_scheduler(
job_handler_task,
&sched,
&mut loaded_user_data,
jobhandler_task_tx.clone(),
)
.await;
}
Expand Down
25 changes: 3 additions & 22 deletions src/bin/stuwe-telegram-bin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ async fn main() {
if args.debug {
env::set_var("RUST_LOG", "debug");
} else if env::var(pretty_env_logger::env_logger::DEFAULT_FILTER_ENV).is_err() {
dbg!();
env::set_var("RUST_LOG", "info");
}

Expand All @@ -99,12 +98,8 @@ async fn main() {
init_mensa_id_db(&mensen).unwrap();

// always update cache on startup
// log::info!(target: "stuwe_telegram_rs::TaskSched", "Updating cache...");
// log::info!(target: "stuwe_telegram_rs::TaskSched", "Updating cache...");
match update_cache().await {
// Ok(_) => log::info!(target: "stuwe_telegram_rs::TaskSched", "Cache updated!"),
Ok(_) => log::info!("Cache updated!"),
// Err(e) => log::error!(target: "stuwe_telegram_rs::TaskSched", "Cache update failed: {}", e),
Err(e) => log::error!("Cache update failed: {}", e),
}

Expand Down Expand Up @@ -184,32 +179,19 @@ async fn run_task_scheduler(
start_mensacache_and_campusdual_job(bot.clone(), &sched, jobhandler_task_tx.clone()).await;

let mut loaded_user_data: BTreeMap<i64, RegistrationEntry> = BTreeMap::new();
load_jobs_from_db(
&bot,
&sched,
&mut loaded_user_data,
jobhandler_task_tx.clone(),
)
.await;
load_jobs_from_db(&bot, &sched, &mut loaded_user_data).await;

// start scheduler (non blocking)
sched.start().await.unwrap();

// log::info!(target: "stuwe_telegram_rs::TaskSched", "Ready.");
log::info!("Ready.");

// receive job update msg (register/unregister/check existence)
while let Ok(job_handler_task) = jobhandler_task_rx.recv().await {
match job_handler_task.job_type {
JobType::Register => {
handle_add_registration_task(
&bot,
job_handler_task,
&sched,
&mut loaded_user_data,
jobhandler_task_tx.clone(),
)
.await;
handle_add_registration_task(&bot, job_handler_task, &sched, &mut loaded_user_data)
.await;
}

JobType::UpdateRegistration => {
Expand All @@ -218,7 +200,6 @@ async fn run_task_scheduler(
job_handler_task,
&sched,
&mut loaded_user_data,
jobhandler_task_tx.clone(),
)
.await;
}
Expand Down
13 changes: 3 additions & 10 deletions src/bot_command_handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,12 @@ pub async fn day_cmd(
_ => unreachable!(),
};

let now = Instant::now();
jobhandler_task_tx
.send(make_query_data(msg.chat.id.0))
.unwrap();

if let Some(registration) = user_registration_data_rx.recv().await.unwrap() {
let text = build_meal_message_dispatcher(days_forward, registration.mensa_id).await;
log::info!("Build {:?} msg: {:.2?}", cmd, now.elapsed());
let now = Instant::now();

bot.send_message(msg.chat.id, text)
Expand Down Expand Up @@ -99,10 +97,6 @@ pub async fn subscribe(
.send(make_query_data(msg.chat.id.0))
.unwrap();
if let Some(registration) = user_registration_data_rx.recv().await.unwrap() {
jobhandler_task_tx
.send(make_query_data(msg.chat.id.0))
.unwrap();

if registration.job_uuid.is_some() {
if rand::thread_rng().gen_range(0..10) == 0 {
send_bloat_image(&bot, msg.chat.id).await;
Expand All @@ -116,8 +110,8 @@ pub async fn subscribe(
} else {
bot.send_message(
msg.chat.id,
"Plan wird ab jetzt automatisch an Wochentagen 06:00 Uhr gesendet.\n\nÄndern mit /uhrzeit",
)
"Plan wird ab jetzt automatisch an Wochentagen *06:00 Uhr* gesendet.\n\nÄndern mit /uhrzeit",
).parse_mode(ParseMode::MarkdownV2)
.await?;

let registration_job = UpdateRegistrationTask {
Expand Down Expand Up @@ -231,8 +225,7 @@ pub async fn start_time_dialogue(
.unwrap();
}

Err(e) => {
dbg!(e);
Err(_) => {
dialogue
.update(DialogueState::AwaitTimeReply)
.await
Expand Down
2 changes: 1 addition & 1 deletion src/campusdual_fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ async fn extract_exam_registr_options(html_text: String) -> Result<Vec<CampusDua
let content_selector = &Selector::parse("td").unwrap();
let mut content = line.select(content_selector);
let class = content.next().unwrap().text().next().unwrap();
let verfahren = content.next().unwrap().text().next().unwrap(); // .inner_html();
let verfahren = content.next().unwrap().text().next().unwrap();

let subline_selector = &Selector::parse(&format!(".child-of-{l_id}")).unwrap();
let status_icon_url = table
Expand Down
35 changes: 34 additions & 1 deletion src/data_backend/mm_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ pub async fn mm_build_meal_msg(days_forward: i64, mensa_location: u8) -> String

// retrieve meals
let day_meals = mm_get_meals_at_mensa_at_day(&requested_date, mensa_location).await;

let now = Instant::now();
let german_date = german_date_fmt(requested_date.date_naive());

// start message formatting
Expand All @@ -87,6 +89,7 @@ pub async fn mm_build_meal_msg(days_forward: i64, mensa_location: u8) -> String

match day_meals {
Ok(meals) => {
println!("{:#?}", &meals);
if meals.is_empty() {
msg += &markdown::bold("\nkeine Daten vorhanden.\n");
} else {
Expand Down Expand Up @@ -133,6 +136,14 @@ pub async fn mm_build_meal_msg(days_forward: i64, mensa_location: u8) -> String
if !price_is_shared {
msg += &format!(" {}\n", &meal.price);
}

if meal.votes != 0 {
msg += &format!(
" Bewertung: {} ({})\n",
float_rating_to_stars(meal.rating),
meal.rating
);
}
}

if price_is_shared {
Expand All @@ -147,5 +158,27 @@ pub async fn mm_build_meal_msg(days_forward: i64, mensa_location: u8) -> String
}
}

escape_markdown_v2(&msg)
let msg = escape_markdown_v2(&msg);
log::info!("MensiMates build msg: {:.2?}", now.elapsed());

msg
}

pub fn float_rating_to_stars(rating: f32) -> String {
let floor = rating.floor();
let partial_star = match rating - floor {
r if r >= 0.875 => '🌕',
r if r >= 0.625 => '🌖',
r if r >= 0.375 => '🌗',
r if r >= 0.125 => '🌘',
_ => '🌑',
};

let mut stars: String = "🌕".repeat(floor as usize);
if (floor as usize) < 5 {
stars.push(partial_star);
stars.push_str(&"🌑".repeat(5 - stars.chars().count()));
}

stars
}
11 changes: 8 additions & 3 deletions src/data_backend/stuwe_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ pub async fn stuwe_build_meal_msg(days_forward: i64, mensa_location: u8) -> Stri
}

// retrieve meals
let now = Instant::now();
let day_meals = get_meals_from_db(requested_date, mensa_location).await;
log::info!("DB data: {:.2?}", now.elapsed());

let now = Instant::now();

// start message formatting
let rand_emoji = EMOJIS[rand::thread_rng().gen_range(0..EMOJIS.len())];
Expand Down Expand Up @@ -90,7 +94,10 @@ pub async fn stuwe_build_meal_msg(days_forward: i64, mensa_location: u8) -> Stri
}
}

escape_markdown_v2(&msg)
let msg = escape_markdown_v2(&msg);
log::info!("StuWe build msg: {:.2?}", now.elapsed());

msg
}

async fn get_meals_from_db(requested_date: DateTime<Local>, mensa: u8) -> Vec<MealGroup> {
Expand Down Expand Up @@ -154,13 +161,11 @@ async fn extract_data_from_html(
meal_groups: meals,
});
} else {
// log::warn!(target: "stuwe_telegram_rs::stuwe_parser", "Mensa not found in DB: {}", mensa_title);
log::warn!("Mensa not found in DB: {}", mensa_title);
}
}
}

// log::info!(target: "stuwe_telegram_rs::stuwe_parser", "HTML → Data: {:.2?}", now.elapsed());
log::info!("HTML → Data: {:.2?}", now.elapsed());
Ok(all_data_for_day)
}
Expand Down
21 changes: 2 additions & 19 deletions src/data_types/mm_data_types.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,5 @@
use serde::{Deserialize, Serialize};

// #[derive(Serialize, Deserialize, Debug, Clone)]
// pub struct MealGroup {
// pub id: u64,
// pub name: String,
// pub description: String,
// pub price: String,
// pub category: String,
// #[serde(rename = "servingDate")]
// pub serving_date: String,
// #[serde(rename = "additionalInfo")]
// pub additional_info: String,
// pub allergens: String,
// pub additives: String,
// pub rating: f32,
// pub votes: u64,
// }

#[derive(Serialize, Deserialize, Debug)]
pub struct GetMensasMensa {
pub id: u8,
Expand All @@ -31,8 +14,8 @@ pub struct MensiMeal {
// id: i64,
pub name: String,
pub price: String,
// rating: f64,
pub rating: f32,
// servingDate: String,
// starsTotal: i64,
// votes: i64,
pub votes: i64,
}
14 changes: 1 addition & 13 deletions src/shared_main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,7 @@ pub async fn build_meal_message_dispatcher(days_forward: i64, mensa_location: u8
}
}

pub async fn load_job(
bot: Bot,
sched: &JobScheduler,
task: JobHandlerTask,
jobhandler_task_tx: broadcast::Sender<JobHandlerTask>,
) -> Option<Uuid> {
pub async fn load_job(bot: Bot, sched: &JobScheduler, task: JobHandlerTask) -> Option<Uuid> {
// return if no time is set
task.hour?;

Expand All @@ -105,13 +100,8 @@ pub async fn load_job(
.as_str(),
move |_uuid, mut _l| {
let bot = bot.clone();
let jobhandler_task_tx = jobhandler_task_tx.clone();

Box::pin(async move {
jobhandler_task_tx
.send(make_query_data(task.chat_id.unwrap()))
.unwrap();

bot.send_message(
ChatId(task.chat_id.unwrap()),
build_meal_message_dispatcher(0, task.mensa_id.unwrap()).await,
Expand Down Expand Up @@ -219,8 +209,6 @@ pub async fn callback_handler(
)
.await;

jobhandler_task_tx.send(make_query_data(chat.id.0)).unwrap();

bot.send_message(chat.id, text)
.parse_mode(ParseMode::MarkdownV2)
.await?;
Expand Down
Loading

0 comments on commit 3db31fe

Please sign in to comment.