working using systemtime

This commit is contained in:
Vivian Lim 2020-06-27 20:32:42 -07:00
parent 1c4a597eb0
commit 3e1d36ded2
2 changed files with 50 additions and 3 deletions

2
Rocket.toml Normal file
View File

@ -0,0 +1,2 @@
[development]
address = "0.0.0.0"

View File

@ -9,8 +9,9 @@ extern crate anyhow;
use rocket::{http::RawStr, State};
use std::{
collections::BTreeMap,
fmt::Display,
sync::{Arc, Mutex},
time::SystemTime,
time::{Duration, SystemTime},
};
#[derive(Default)]
@ -32,9 +33,51 @@ impl LoggedAccesses {
}
}
impl DeviceLog {
pub fn get_duration(&self) -> Result<(Duration, &SystemTime, &SystemTime), anyhow::Error> {
let start = self.access_times.first().ok_or(anyhow!("No start time"))?;
let end = self.access_times.last().ok_or(anyhow!("No end time"))?;
let duration = end
.duration_since(start.clone())
.map_err(|_| anyhow!("Times could not be diffed"))?;
Ok((duration, &start, &end))
}
}
impl Display for LoggedAccesses {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (device_name, device_log) in &self.devices {
f.write_fmt(format_args!("{}: {}\n", device_name, device_log))?
}
Ok(())
}
}
impl Display for DeviceLog {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.get_duration() {
Ok((duration, start, end)) => f.write_fmt(format_args!(
"{} seconds between first ({:?}) and last ({:?}) call",
duration.as_secs(),
start,
end
)),
Err(e) => f.write_fmt(format_args!("Error getting duration: {}", e)),
}
}
}
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
fn index(state: State<Arc<Mutex<LoggedAccesses>>>) -> Result<String, anyhow::Error> {
match state.clone().lock() {
Ok(logged_accesses) => Ok(format!(
"Devices:\n{}\n\nwhile true; do curl https://pc.vvn.space/log/name; sleep 5; done",
logged_accesses
)),
Err(_) => Err(anyhow!("Couldn't lock state")),
}
}
#[get("/log/<device_name>")]
@ -56,4 +99,6 @@ fn main() {
.manage(Arc::<Mutex<LoggedAccesses>>::default())
.mount("/", routes![index, log])
.launch();
println!("after");
}