Move yearly recurrence out of Event and into scheduler

This commit is contained in:
Matteo Settenvini 2022-08-03 19:31:06 +02:00
parent f98c82ae7f
commit e6288cfde1
Signed by: matteo
GPG key ID: 8576CC1AD97D42DF
3 changed files with 40 additions and 26 deletions

View file

@ -25,7 +25,12 @@ struct CsvRecord {
dinner: String,
}
pub async fn with(api_client: &ApiClient, calendar: &str, csv_file: &Path) -> Result<()> {
pub async fn with(
api_client: &ApiClient,
calendar: &str,
csv_file: &Path,
yearly_recurring_events: bool,
) -> Result<()> {
let mut csv = csv::Reader::from_path(csv_file)?;
let records = csv.deserialize::<CsvRecord>().flatten().collect::<Vec<_>>();
@ -51,7 +56,7 @@ pub async fn with(api_client: &ApiClient, calendar: &str, csv_file: &Path) -> Re
})
.flatten();
publish_events(&api_client, calendar, events).await?;
publish_events(&api_client, calendar, events, yearly_recurring_events).await?;
Ok(())
}
@ -111,6 +116,7 @@ async fn publish_events<'a, EventsIter>(
api_client: &ApiClient,
calendar: &str,
events: EventsIter,
yearly_recurring_events: bool,
) -> Result<()>
where
EventsIter: Iterator<Item = Event>,
@ -134,9 +140,28 @@ where
&ev.ends_at.date(),
&ev.recipe.name
);
let cal = icalendar::Calendar::new()
.push::<icalendar::Event>(ev.into())
.done();
let end_time = ev.ends_at;
let mut event: icalendar::Event = ev.into();
if yearly_recurring_events {
use chrono::Datelike;
use icalendar::Component;
const DAY_NAMES: [&str; 7] = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
event.add_property(
"RRULE",
&format!(
"FREQ=YEARLY;BYDAY={weekday};BYWEEKNO={weekno}",
weekday = DAY_NAMES
.get(end_time.weekday().num_days_from_monday() as usize)
.unwrap(),
weekno = end_time.iso_week().week(),
),
);
}
let cal = icalendar::Calendar::new().push(event).done();
let cal_as_string = (&cal.to_string())
.replacen(