1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use crate::todo;
use crate::todotxt;
pub fn is_timer_on(task: &todotxt::Task) -> bool {
if let Some(state) = task.tags.get(todo::TIMER_TAG) {
return state != todo::TIMER_OFF;
}
false
}
pub fn spent_time(task: &todotxt::Task) -> chrono::Duration {
if is_timer_on(task) {
return match calc_time_spent(task) {
Some(n) => chrono::Duration::seconds(n),
None => chrono::Duration::seconds(0),
};
}
if let Some(sp) = task.tags.get(todo::SPENT_TAG) {
if let Ok(n) = sp.parse::<i64>() {
chrono::Duration::seconds(n)
} else {
chrono::Duration::seconds(0)
}
} else {
chrono::Duration::seconds(0)
}
}
pub fn start_timer(task: &mut todotxt::Task) -> bool {
if task.finished || is_timer_on(task) {
return false;
}
let utc = chrono::Utc::now();
let seconds = format!("{}", utc.timestamp());
task.update_tag_with_value(todo::TIMER_TAG, &seconds);
true
}
fn calc_time_spent(task: &todotxt::Task) -> Option<i64> {
if let Some(started) = task.tags.get(todo::TIMER_TAG) {
if let Ok(n) = started.parse::<i64>() {
let dt_start = chrono::NaiveDateTime::from_timestamp(n, 0);
let diff = chrono::Utc::now().naive_utc() - dt_start;
let mut spent: i64 =
if let Some(sp) = task.tags.get(todo::SPENT_TAG) { sp.parse::<i64>().unwrap_or(0) } else { 0 };
if diff.num_seconds() > 0 {
spent += diff.num_seconds();
}
return Some(spent);
}
}
None
}
pub fn stop_timer(task: &mut todotxt::Task) -> bool {
if !is_timer_on(task) {
return false;
}
if let Some(spent) = calc_time_spent(task) {
let new_spent = format!("{}", spent);
task.update_tag_with_value(todo::SPENT_TAG, &new_spent);
task.update_tag_with_value(todo::TIMER_TAG, todo::TIMER_OFF);
return true;
}
false
}