use std::path::{Path, PathBuf};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use super::settings::Signed;
use super::store::Store;
use crate::proxy_session::Key;
const DOMAIN: &[u8] = b"openmoat-remote-listening-v1\n";
const VERSION: u32 = 1;
const FILE: &str = "listening.json";
pub const LIVE_MS: i64 = 15_000;
const AHEAD_MS: i64 = 2_000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Beat {
pub version: u32,
pub channel: String,
pub at_ms: i64,
#[serde(default)]
pub mac: String,
}
impl Signed for Beat {
const DOMAIN: &'static [u8] = DOMAIN;
fn version(&self) -> u32 {
self.version
}
fn mac(&mut self) -> &mut String {
&mut self.mac
}
}
fn path(store: &Store) -> PathBuf {
store.dir().join(FILE)
}
pub fn beat(store: &Store, key: &Key, channel: &str, now_ms: i64) -> Result<()> {
let mut beat = Beat {
version: VERSION,
channel: channel.to_owned(),
at_ms: now_ms,
mac: String::new(),
};
<Beat as Signed>::save(&mut beat, &path(store), key)
}
pub fn stop(store: &Store) {
let _ = std::fs::remove_file(path(store));
}
pub fn live(store: &Store, key: &Key, channel: &str, now_ms: i64) -> bool {
read(&path(store), key).is_some_and(|b| {
b.channel == channel
&& b.at_ms <= now_ms.saturating_add(AHEAD_MS)
&& now_ms.saturating_sub(b.at_ms) <= LIVE_MS
})
}
fn read(path: &Path, key: &Key) -> Option<Beat> {
<Beat as Signed>::load(path, key).ok()
}