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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use ansi_term::{Colour, Style};
use indicatif::{ProgressBar, ProgressStyle};
use notify_rust::Notification;
use pager::Pager;
use serde::{Deserialize, Serialize};
use simpler_timer::Timer;
use std::fs::File;
use std::io::ErrorKind;
use std::io::{BufReader, Read};
use std::io::{BufWriter, Write};
use std::time::Duration;
use time::OffsetDateTime;
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Session {
title: String,
labels: Vec<String>,
date: String,
time: String,
}
pub fn timer(title: &str, labels: &str) -> std::io::Result<()> {
let bar = ProgressBar::new(1500);
bar.set_style(
ProgressStyle::default_bar()
.template(" {bar:40.cyan/blue} {elapsed_precise}")
.progress_chars("##-"),
);
let periodic = Timer::with_duration(Duration::from_secs(1));
let timeout = Timer::with_duration(Duration::from_secs(1500));
println!(" Focusing on: {}", Colour::Cyan.paint(title));
loop {
if periodic.expired() {
bar.inc(1);
periodic.reset();
}
if timeout.expired() {
bar.finish();
println!("Session ended, take a break.");
break;
}
}
let session = generate_session(title, labels)?;
init_history()?;
let mut history = read_history()?;
history.insert(0, session);
write_history(&history)?;
notify(title)?;
Ok(())
}
fn notify(title: &str) -> std::io::Result<()> {
let body = format!("Session Ended: `{}`, take a break.", title);
Notification::new()
.summary("Session")
.body(&body)
.appname("session")
.timeout(0)
.show()
.unwrap();
Ok(())
}
fn generate_session(title: &str, labels: &str) -> std::io::Result<Session> {
let date = format!("{}", OffsetDateTime::now_local().date());
let time = OffsetDateTime::now_local().time().format("%R");
let lbls: Vec<String> = labels.split(',').map(|s| s.trim().to_owned()).collect();
Ok(Session {
title: String::from(title),
labels: lbls,
date,
time,
})
}
fn init_history() -> std::io::Result<()> {
File::open("./.session.json").unwrap_or_else(|error| {
if error.kind() == ErrorKind::NotFound {
let file = File::create("./.session.json").unwrap_or_else(|error| {
panic!("Problem creating the file: {:?}", error);
});
let initial_json = "[]";
let f = File::create("./.session.json").expect("Unable to create file");
let mut f = BufWriter::new(f);
f.write_all(initial_json.as_bytes())
.expect("Unable to write data");
file
} else {
panic!("Problem opening the file: {:?}", error);
}
});
Ok(())
}
fn read_history() -> std::io::Result<Vec<Session>> {
let mut data = String::new();
let f = File::open("./.session.json").expect("Unable to open file");
let mut br = BufReader::new(f);
br.read_to_string(&mut data).expect("Unable to read string");
let v: Vec<Session> = serde_json::from_str(&data)?;
Ok(v)
}
fn write_history(history: &[Session]) -> std::io::Result<()> {
let output = serde_json::to_string(&history).unwrap();
let f = File::create("./.session.json").expect("Unable to create file");
let mut f = BufWriter::new(f);
f.write_all(output.as_bytes())
.expect("Unable to write data");
Ok(())
}
fn filter_sessions(labels: &str) -> Vec<Session> {
let history = read_history().unwrap();
let mut filtered: Vec<Session> = vec![];
for label in labels.split(',') {
for session in history.iter() {
if session.labels.iter().any(|p| p == label.trim()) {
filtered.push(session.clone());
}
}
}
if labels == "" {
history
} else {
filtered
}
}
pub fn status(labels: &str) -> std::io::Result<()> {
let to_show = filter_sessions(labels);
let total_minutes = to_show.len() * 25;
let hours = total_minutes / 60;
let minutes = total_minutes % 60;
let date = format!("{}", OffsetDateTime::now_local().date());
let today = to_show.iter().filter(|p| p.date == date).count();
let today_total_minutes = today * 25;
let today_hours = today_total_minutes / 60;
let today_minutes = today_total_minutes % 60;
let today_str = format!(
"TODAY: {} sessions {}h:{}m ",
today, today_hours, today_minutes
);
let today = to_show.iter().filter(|p| p.date == date).count();
match today {
0..=2 => {
print!("{}", Colour::Red.paint(today_str));
}
3..=7 => {
print!("{}", Colour::Yellow.paint(today_str));
}
_ => {
print!("{}", Colour::Green.paint(today_str));
}
}
println!(
"{}",
format!(
"<{} sessions {}h:{}m (all time)>",
to_show.len(),
hours,
minutes
)
);
Ok(())
}
pub fn log(labels: &str) -> std::io::Result<()> {
let to_show = filter_sessions(labels);
let label_style = Style::new().bold().on(Colour::Cyan).fg(Colour::Black);
Pager::with_pager("less -r").setup();
status(labels)?;
for session in to_show {
println!(
"\n{}",
Colour::Cyan.paint(format!("Title: {}", session.title))
);
println!("Labels: {}", label_style.paint(session.labels.join(",")));
println!("Date: {} {}", session.date, session.time);
}
Ok(())
}