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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#![allow(non_snake_case)]
#![doc = include_str!("../docs.md")]
use chrono::{NaiveDate};
use colored::*;
use pest::Parser;
use pest_derive::Parser;
use std::collections::HashMap;
use std::str::FromStr;
use thiserror::Error;
/// The `ICalParser` struct is the main parser for the iCalendar format.
#[derive(Parser)]
#[grammar = "./grammar.pest"]
pub struct ICalParser;
/// Enum representing errors during PARSING of the iCal fiel.
#[derive(Error, Debug)]
pub enum ICalendarParsingError {
#[error("Eror parsing iCal file: {0}")]
ParsingTimeError(String),
}
/// Struct representing an iCalendar file.
#[derive(Debug, PartialEq)]
pub struct ICalendar {
/// The version of the iCalendar format used.
pub version: Option<f64>,
/// The product ID identifying the software that created the iCalendar file.
pub prodid: Option<String>,
/// A list of events contained in the iCalendar file.
pub events: Vec<Event>,
/// A list of comments found in the iCalendar file.
pub comments: Vec<String>,
}
/// Struct representing a single event in the iCalendar file.
#[derive(Debug, PartialEq)]
pub struct Event {
/// Unique identifier for the event.
pub uid: Option<String>,
/// Organizer of the event.
pub organizer: Option<String>,
/// The start date and time of the event.
pub dtstart: Option<String>,
/// The end date and time of the event.
pub dtend: Option<String>,
/// The summary or title of the event.
pub summary: Option<String>,
/// The geographical location of the event.
pub geo: Option<(f64, f64)>,
/// A detailed description of the event.
pub description: Option<String>,
/// A list of comments associated with the event.
pub comments: Vec<String>,
}
/// Trait to allow pretty printing to the *stdout* (pls note that stdout is only supported output).
pub trait PrettyPrint {
/// Prints the iCalendar or event in a human-readable format with optional colorization.
///
/// # Arguments
///
/// * `colored` - A boolean flag to enable or disable colorized output. If `None`, colorization is enabled by default.
fn pretty_print(&self, colored: Option<bool>);
}
impl ICalendar {
/// Parses an iCalendar string and returns an `ICalendar` struct.
///
/// # Arguments
///
/// * `ical_text` - A string containing the texual representation of the iCalendar.
///
/// # Returns
///
/// * A result containing either the parsed `ICalendar` object or an `ICalendarParsingError`.
pub fn parse(ical_text: &str) -> Result<Self, ICalendarParsingError> {
let mut calendar = ICalendar {
version: None,
prodid: None,
events: Vec::new(),
comments: Vec::new(),
};
let pairs_unfolded = ICalParser::parse(Rule::vc_calendar, ical_text);
let parsed_tokens = match pairs_unfolded {
Ok(parsed_ical) => parsed_ical,
Err(error) => return Err(ICalendarParsingError::ParsingTimeError(error.to_string())),
};
log::debug!("Parsed pairs: {:?}", parsed_tokens);
for top_lvl_token in parsed_tokens {
let inner = top_lvl_token.into_inner();
for inner_token in inner {
log::debug!("Got pair type: {:?}", inner_token.as_rule());
match inner_token.as_rule() {
Rule::comment => {
let comment_str = inner_token
.as_str()
.trim_start_matches(';')
.trim()
.to_string();
calendar.comments.push(comment_str);
}
Rule::version => {
let version_str = inner_token.as_str().trim_start_matches("VERSION:");
calendar.version = Some(version_str.parse().unwrap());
}
Rule::prodid => {
let prodid_str = inner_token.as_str().trim_start_matches("PRODID:");
calendar.prodid = Some(prodid_str.to_string());
}
Rule::event => {
let event = Event::parse(inner_token);
log::debug!("Parsed event: {:?}", event);
calendar.events.push(event);
}
_ => {}
}
}
}
Ok(calendar)
}
pub fn print_most_busy_day(&self, colored: Option<bool>) {
let mut date_count: HashMap<String, usize> = HashMap::new();
for event in &self.events {
if let Some(dtstart) = &event.dtstart {
if let Ok(date) = parse_event_date(dtstart) {
*date_count.entry(date).or_insert(0) += 1;
}
}
}
let colored = colored.unwrap_or(true);
if let Some((busy_date, event_count)) = date_count.iter().max_by_key(|&(_, count)| count) {
if colored {
println!(
"{}: {} - {} event(s)",
"Most Busy Day".bold().underline().cyan(),
busy_date,
event_count
);
} else {
println!(
"{}: {} - {} event(s)",
"Most Busy Day", busy_date, event_count
);
}
} else {
println!("No events found to determine the busiest day.");
}
}
}
impl PrettyPrint for ICalendar {
fn pretty_print(&self, colored: Option<bool>) {
let colored = colored.unwrap_or(true);
if colored {
println!("{}", "iCalendar File".bold().underline().cyan());
} else {
println!("iCalendar File");
}
if let Some(version) = self.version {
if colored {
println!("{}: {}", "Version".yellow(), version);
} else {
println!("Version: {}", version);
}
}
if let Some(prodid) = &self.prodid {
if colored {
println!("{}: {}", "Product ID".yellow(), prodid);
} else {
println!("Product ID: {}", prodid);
}
}
for comment in &self.comments {
if colored {
println!("{}", format!("Comment: {}", comment).yellow());
} else {
println!("Comment: {}", comment);
}
}
for event in self.events.iter() {
event.pretty_print(Some(colored));
}
}
}
impl Event {
/// Parses a single event from the iCalendar data.
///
/// # Arguments
///
/// * `pair` - The pairs from the parsing of the iCalendar text file.
///
/// # Returns
///
/// * The parsed `Event` struct containing the event data.
fn parse(pair: pest::iterators::Pair<Rule>) -> Self {
let mut event = Event {
uid: None,
organizer: None,
dtstart: None,
dtend: None,
summary: None,
geo: None,
description: None,
comments: Vec::new(),
};
for inner_pair in pair.into_inner() {
match inner_pair.as_rule() {
Rule::comment => {
let comment_str = inner_pair
.as_str()
.trim_start_matches(';')
.trim()
.to_string();
event.comments.push(comment_str); // Store the comment in the event
}
Rule::uid => {
event.uid = Some(inner_pair.as_str().trim_start_matches("UID:").to_string());
}
Rule::organizer => {
let organizer_str = inner_pair.as_str().trim_start_matches("ORGANIZER;CN=");
let organizer_details: Vec<&str> = organizer_str.split(":MAILTO:").collect();
if organizer_details.len() == 2 {
event.organizer = Some(format!(
"{} <{}>",
organizer_details[0], organizer_details[1]
));
}
}
Rule::dtstart => {
event.dtstart = Some(
inner_pair
.as_str()
.trim_start_matches("DTSTART:")
.to_string(),
);
}
Rule::dtend => {
event.dtend =
Some(inner_pair.as_str().trim_start_matches("DTEND:").to_string());
}
Rule::summary => {
event.summary = Some(
inner_pair
.as_str()
.trim_start_matches("SUMMARY:")
.to_string(),
);
}
Rule::geo => {
let geo_str = inner_pair.as_str().trim_start_matches("GEO:");
let coords: Vec<&str> = geo_str.split(',').collect();
if coords.len() == 2 {
if let (Ok(lat), Ok(lon)) =
(f64::from_str(coords[0]), f64::from_str(coords[1]))
{
event.geo = Some((lat, lon));
}
}
}
Rule::dsc => {
event.description = Some(
inner_pair
.as_str()
.trim_start_matches("DESCRIPTION:")
.to_string(),
);
}
_ => {}
}
}
event
}
}
impl PrettyPrint for Event {
fn pretty_print(&self, colored: Option<bool>) {
let colored = colored.unwrap_or(true);
if colored {
println!(
"\n{} {}",
"Event".bold().underline().blue(),
self.uid.as_deref().unwrap_or("Unknown")
);
} else {
println!("\nEvent {}", self.uid.as_deref().unwrap_or("Unknown"));
}
if let Some(uid) = &self.uid {
if colored {
println!(" {}: {}", "UID".green(), uid);
} else {
println!(" UID: {}", uid);
}
}
if let Some(organizer) = &self.organizer {
if colored {
println!(" {}: {}", "Organizer".green(), organizer);
} else {
println!(" Organizer: {}", organizer);
}
}
if let Some(dtstart) = &self.dtstart {
if colored {
println!(" {}: {}", "Start Date".green(), dtstart);
} else {
println!(" Start Date: {}", dtstart);
}
}
if let Some(dtend) = &self.dtend {
if colored {
println!(" {}: {}", "End Date".green(), dtend);
} else {
println!(" End Date: {}", dtend);
}
}
if let Some(summary) = &self.summary {
if colored {
println!(" {}: {}", "Summary".green(), summary);
} else {
println!(" Summary: {}", summary);
}
}
if let Some((lat, lon)) = self.geo {
if colored {
println!(" {}: {}, {}", "Location (Geo)".green(), lat, lon);
} else {
println!(" Location (Geo): {}, {}", lat, lon);
}
}
if let Some(description) = &self.description {
if colored {
println!(" {}: {}", "Description".green(), description);
} else {
println!(" Description: {}", description);
}
}
for comment in &self.comments {
if colored {
println!("{}", format!(" Comment: {}", comment).yellow());
} else {
println!(" Comment: {}", comment);
}
}
}
}
fn parse_event_date(dtstart: &str) -> Result<String, String> {
// The iCalendar date format is YYYYMMDDTHHMMSSZ, so we want to extract just the date portion (YYYYMMDD)
let date_part = dtstart
.split('T')
.next()
.ok_or_else(|| "Invalid date format".to_string())?;
// Try to parse the date portion into a NaiveDate
let naive_date = NaiveDate::parse_from_str(date_part, "%Y%m%d")
.map_err(|e| format!("Error parsing date: {}", e))?;
// Return the date in YYYY-MM-DD format
Ok(naive_date.format("%Y-%m-%d").to_string())
}