Alex Mikhalev
4 years ago
5 changed files with 179 additions and 18 deletions
@ -0,0 +1,75 @@
@@ -0,0 +1,75 @@
|
||||
use crate::{ |
||||
model::SectionId, |
||||
section_runner::{SecRun, SecRunState, SecRunnerState}, |
||||
}; |
||||
use chrono::{DateTime, Utc}; |
||||
use serde::Serialize; |
||||
use std::time::SystemTime; |
||||
use tokio::time::Instant; |
||||
|
||||
#[derive(Clone, Debug, Serialize)] |
||||
#[serde(rename_all = "camelCase")] |
||||
pub struct SecRunJson { |
||||
id: i32, |
||||
section: SectionId, |
||||
total_duration: f64, |
||||
duration: f64, |
||||
start_time: Option<String>, |
||||
pause_time: Option<String>, |
||||
unpause_time: Option<String>, |
||||
} |
||||
|
||||
impl SecRunJson { |
||||
fn from_run(run: &SecRun) -> Option<Self> { |
||||
let (now, system_now) = (Instant::now(), SystemTime::now()); |
||||
let instant_to_string = |instant: Instant| -> String { |
||||
DateTime::<Utc>::from(system_now - now.duration_since(instant)).to_rfc3339() |
||||
}; |
||||
let (start_time, pause_time) = match run.state { |
||||
SecRunState::Finished | SecRunState::Cancelled => { |
||||
return None; |
||||
} |
||||
SecRunState::Waiting => (None, None), |
||||
SecRunState::Running { start_time } => (Some(instant_to_string(start_time)), None), |
||||
SecRunState::Paused { |
||||
start_time, |
||||
pause_time, |
||||
} => ( |
||||
Some(instant_to_string(start_time)), |
||||
Some(instant_to_string(pause_time)), |
||||
), |
||||
}; |
||||
Some(Self { |
||||
id: run.handle.clone().into_inner(), |
||||
section: run.section.id, |
||||
total_duration: run.total_duration.as_secs_f64(), |
||||
duration: run.duration.as_secs_f64(), |
||||
start_time, |
||||
pause_time, |
||||
unpause_time: None, // TODO: this is kinda useless, should probably be removed
|
||||
}) |
||||
} |
||||
} |
||||
|
||||
#[derive(Clone, Debug, Serialize)] |
||||
#[serde(rename_all = "camelCase")] |
||||
pub struct SecRunnerStateJson { |
||||
queue: Vec<SecRunJson>, |
||||
current: Option<SecRunJson>, |
||||
paused: bool, |
||||
} |
||||
|
||||
impl From<&SecRunnerState> for SecRunnerStateJson { |
||||
fn from(state: &SecRunnerState) -> Self { |
||||
let mut run_queue = state.run_queue.iter(); |
||||
let current = run_queue.next().and_then(|run| SecRunJson::from_run(run)); |
||||
let queue = run_queue |
||||
.filter_map(|run| SecRunJson::from_run(run)) |
||||
.collect(); |
||||
Self { |
||||
queue, |
||||
current, |
||||
paused: state.paused, |
||||
} |
||||
} |
||||
} |
Loading…
Reference in new issue