mirror of
https://git.alemi.dev/mood.git
synced 2024-11-21 16:14:48 +01:00
feat: weighted random, 1 per minute
This commit is contained in:
parent
2a37428f56
commit
05fde380f9
2 changed files with 39 additions and 6 deletions
|
@ -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"
|
||||
|
|
44
src/main.rs
44
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::<u64>().unwrap(), l))
|
||||
.collect();
|
||||
|
||||
let mut pool = Vec::new();
|
||||
pool.reserve(lines.iter().map(|(x,_)| x).sum::<u64>() 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);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue