diff --git a/Cargo.toml b/Cargo.toml index ec668c9..93137f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,4 +6,3 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -rand = "0.8.5" diff --git a/src/main.rs b/src/main.rs index d9397e6..428b23d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,45 @@ -use rand::seq::IteratorRandom; +use std::{hash::Hasher, collections::hash_map::DefaultHasher, time::{SystemTime, UNIX_EPOCH}}; + +// this is trash but i only need a unique string each minute +fn formatted_timestamp() -> String { + let t = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("UNIX time overflowed again") + .as_secs(); + format!( + "D{} H{} M{}", + (t / (60 * 60 * 24)), + (t / (60 * 60)) % 60, + (t / 60) % 60, + ) +} fn main() { - let file = std::env::var("MOOD_FILE").unwrap_or("/srv/http/api/mood.txt".to_string()); - let content = std::fs::read_to_string(file).unwrap(); - let choice = content.lines().choose(&mut rand::thread_rng()).unwrap(); + let now_str = formatted_timestamp(); + + let mut hasher = DefaultHasher::new(); + hasher.write(now_str.as_bytes()); + let index = hasher.finish() as usize; + + let file = std::env::var("MOOD_FILE").expect("missing MOOD_FILE env variable"); + let content = std::fs::read_to_string(file).expect("could not read MOOD_FILE contents"); + + let lines : Vec<(u64, &str)> = content.lines() + .map(|l| l.split_once(' ').unwrap()) + .map(|(n, l)| (n.parse::().unwrap(), l)) + .collect(); + + let mut pool = Vec::new(); + pool.reserve(lines.iter().map(|(x,_)| x).sum::() as usize); + for (count, line) in lines { + for _ in 0..count { + pool.push(line); + } + } + + let choice = pool[index % pool.len()]; println!("Content-type: application/json"); println!(); - println!("{{\"mood\":\"{}\"}}", choice); + println!("{{\"id\":{},\"mood\":\"{}\"}}", index, choice); }