use std::
{
fs,
sync::{ LazyLock, Mutex },
};
use why2::consts as why2_consts;
use crate::
{
crypto,
consts::{ self, SharedKeys },
network::codes::
{
MessageColors,
StoredMessage,
},
};
static HISTORY: LazyLock<Mutex<Vec<StoredMessage>>> = LazyLock::new(|| Mutex::new(load())); static KEYS: LazyLock<SharedKeys> = LazyLock::new(crypto::history_keys);
fn path() -> String {
super::config_path(consts::SERVER_MESSAGES_FILE)
}
fn load() -> Vec<StoredMessage> {
let Ok(bytes) = fs::read(path()) else { return Vec::new() };
let Some(plaintext) = crypto::decrypt_packet::
<{ why2_consts::DEFAULT_GRID_WIDTH }, { why2_consts::DEFAULT_GRID_HEIGHT }>(bytes, &KEYS)
else { return Vec::new() };
wincode::deserialize::<Vec<StoredMessage>>(&plaintext).unwrap_or_default()
}
pub fn store(username: &str, text: &str, colors: &MessageColors) {
let limit: usize = super::read_config("max_persistent_messages");
if limit == 0 { return; }
let mut history = HISTORY.lock().unwrap();
history.push(StoredMessage
{
username: username.to_string(),
text: text.to_string(),
colors: colors.clone(),
});
let over = history.len().saturating_sub(limit);
history.drain(..over);
let bytes = wincode::serialize(&*history).expect("Encoding message history failed");
let sealed = crypto::encrypt_packet::<{ why2_consts::DEFAULT_GRID_WIDTH }, { why2_consts::DEFAULT_GRID_HEIGHT }>(&bytes, &KEYS);
fs::write(path(), sealed).expect("Saving message history failed");
}
pub fn all() -> Vec<StoredMessage> {
HISTORY.lock().unwrap().clone()
}