using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using HRM.BO; using Ical.Net; using Ical.Net.CalendarComponents; using Ical.Net.DataTypes; namespace HRM.DA { /// /// Repeat rules (RFC 5545 RRULE, the same format Outlook uses) for calendar items, worked out with Ical.Net. /// Times are "floating" local times, exactly as stored, so nothing shifts between time zones. /// Exception dates are whole days ("yyyy-MM-dd"): an occurrence that starts on such a day is skipped. /// internal static class CalendarRecurrence { private const int MaxInterval = 99; private const int MaxCount = 730; private const int MaxExceptionDates = 500; /// Safety stop: never examine more occurrences than this in one search. private const int MaxScan = 3000; private const string ExceptionDateFormat = "yyyy-MM-dd"; private static readonly FrequencyType[] AllowedFrequencies = { FrequencyType.Daily, FrequencyType.Weekly, FrequencyType.Monthly, FrequencyType.Yearly }; #region Validation /// /// Checks the item's repeat rule and exception dates, rewrites them in canonical form and works out /// RecurrenceEndDate (NULL when the series never ends). Throws ArgumentException on bad input. /// internal static void Normalize(CalendarItem item) { if (string.IsNullOrWhiteSpace(item.RecurrenceRule)) { item.RecurrenceRule = null; item.RecurrenceEndDate = null; item.ExceptionDates = null; return; } string text = item.RecurrenceRule.Trim(); if (text.StartsWith("RRULE:", StringComparison.OrdinalIgnoreCase)) text = text.Substring("RRULE:".Length); RecurrencePattern rule; try { rule = new RecurrencePattern(text); } catch (Exception) { throw new ArgumentException("The repeat setting is not valid."); } if (!AllowedFrequencies.Contains(rule.Frequency)) throw new ArgumentException("Repeat can be daily, weekly, monthly or yearly."); if (rule.Interval < 1 || rule.Interval > MaxInterval) throw new ArgumentException("Repeat every can be from 1 to " + MaxInterval + "."); if (rule.Count.HasValue && rule.Until != null) throw new ArgumentException("A repeat can end on a date or after a number of times, not both."); if (rule.Count.HasValue && (rule.Count.Value < 1 || rule.Count.Value > MaxCount)) throw new ArgumentException("A repeat can happen from 1 to " + MaxCount + " times."); if (rule.Until != null && rule.Until.Value.Date < item.StartDateTime.Date) throw new ArgumentException("The repeat end date must not be before the start."); item.RecurrenceRule = rule.ToString(); item.ExceptionDates = FormatExceptionDates(ParseExceptionDates(item.ExceptionDates)); item.RecurrenceEndDate = ComputeSeriesEnd(item, rule); } /// The end of the last occurrence, or NULL for a series without COUNT or UNTIL. private static DateTime? ComputeSeriesEnd(CalendarItem item, RecurrencePattern rule) { if (!rule.Count.HasValue && rule.Until == null) return null; DateTime? lastEnd = null; foreach (var occurrence in Occurrences(item, item.StartDateTime)) lastEnd = occurrence.End; return lastEnd ?? item.EndDateTime; } #endregion #region Exception dates internal static SortedSet ParseExceptionDates(string exceptionDates) { SortedSet dates = new SortedSet(); if (string.IsNullOrWhiteSpace(exceptionDates)) return dates; foreach (string part in exceptionDates.Split(',', StringSplitOptions.RemoveEmptyEntries)) { if (!DateTime.TryParseExact(part.Trim(), ExceptionDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date)) throw new ArgumentException("A skipped date is not valid."); dates.Add(date.Date); } if (dates.Count > MaxExceptionDates) throw new ArgumentException("Too many skipped dates."); return dates; } internal static string FormatExceptionDates(IEnumerable dates) { List parts = dates.Select(d => d.ToString(ExceptionDateFormat, CultureInfo.InvariantCulture)).ToList(); return parts.Count == 0 ? null : string.Join(",", parts); } /// Adds one skipped day to an exception-date list and returns the new list. internal static string AddExceptionDate(string exceptionDates, DateTime day) { SortedSet dates = ParseExceptionDates(exceptionDates); dates.Add(day.Date); return FormatExceptionDates(dates); } #endregion #region Occurrences /// /// Occurrences (start, end) in time order, beginning with the first one that has not ended before /// . A non-repeating item has exactly one occurrence. Ends inclusive, as stored. /// internal static IEnumerable<(DateTime Start, DateTime End)> Occurrences(CalendarItem item, DateTime from) { TimeSpan duration = item.EndDateTime - item.StartDateTime; if (string.IsNullOrWhiteSpace(item.RecurrenceRule)) { if (item.EndDateTime >= from) yield return (item.StartDateTime, item.EndDateTime); yield break; } SortedSet skipped = ParseExceptionDates(item.ExceptionDates); CalendarEvent calendarEvent = BuildEvent(item, duration); // Start early enough to catch an occurrence that began before "from" but is still running. DateTime searchFrom = from - duration; if (searchFrom < item.StartDateTime) searchFrom = item.StartDateTime; int scanned = 0; foreach (Occurrence occurrence in calendarEvent.GetOccurrences(ToCalDateTime(searchFrom, item.IsAllDay), null)) { if (++scanned > MaxScan) yield break; DateTime start = occurrence.Period.StartTime.Value; if (skipped.Contains(start.Date)) continue; DateTime end = start + duration; if (end < from) continue; yield return (start, end); } } private static CalendarEvent BuildEvent(CalendarItem item, TimeSpan duration) { CalendarEvent calendarEvent = new CalendarEvent { DtStart = ToCalDateTime(item.StartDateTime, item.IsAllDay), // all-day ends are stored inclusive; iCalendar wants the exclusive next day DtEnd = item.IsAllDay ? ToCalDateTime(item.EndDateTime.Date.AddDays(1), true) : ToCalDateTime(item.StartDateTime + duration, false) }; calendarEvent.RecurrenceRule = new RecurrencePattern(item.RecurrenceRule); return calendarEvent; } private static CalDateTime ToCalDateTime(DateTime value, bool allDay) { return allDay ? new CalDateTime(DateOnly.FromDateTime(value)) : new CalDateTime(value, true); } #endregion #region Splitting a series ("this and following") /// /// True when no occurrence is shown before , so "this and following" /// covers the whole series. /// internal static bool IsFirstOccurrence(CalendarItem item, DateTime occurrenceStart) { foreach (var occurrence in Occurrences(item, item.StartDateTime)) return occurrence.Start >= occurrenceStart; return true; } /// /// The series' repeat rule changed so that it ends just before /// (any COUNT or UNTIL is replaced by an UNTIL on the previous moment, or the previous day for all-day items). /// internal static string RuleEndingBefore(CalendarItem item, DateTime occurrenceStart) { List parts = item.RecurrenceRule.Split(';', StringSplitOptions.RemoveEmptyEntries) .Where(p => !p.StartsWith("COUNT=", StringComparison.OrdinalIgnoreCase) && !p.StartsWith("UNTIL=", StringComparison.OrdinalIgnoreCase)) .ToList(); parts.Add(item.IsAllDay ? "UNTIL=" + occurrenceStart.Date.AddDays(-1).ToString("yyyyMMdd", CultureInfo.InvariantCulture) : "UNTIL=" + occurrenceStart.AddSeconds(-1).ToString("yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture)); return string.Join(";", parts); } /// /// How many times the rule produced the item before , skipped days included /// (that is what COUNT counts). /// internal static int CountBefore(CalendarItem item, DateTime occurrenceStart) { CalendarItem withoutSkips = new CalendarItem { StartDateTime = item.StartDateTime, EndDateTime = item.EndDateTime, IsAllDay = item.IsAllDay, RecurrenceRule = item.RecurrenceRule }; int count = 0; foreach (var occurrence in Occurrences(withoutSkips, item.StartDateTime)) { if (occurrence.Start >= occurrenceStart) break; count++; } return count; } /// The skipped days on or after (true) or before it (false). internal static string SplitExceptionDates(string exceptionDates, DateTime fromDay, bool onOrAfter) { return FormatExceptionDates(ParseExceptionDates(exceptionDates) .Where(d => onOrAfter ? d >= fromDay.Date : d < fromDay.Date)); } #endregion #region Schedule job runs /// The first occurrence start later than , or NULL when there is none. internal static DateTime? NextStart(CalendarItem item, DateTime after) { foreach (var occurrence in Occurrences(item, after)) { if (occurrence.Start > after) return occurrence.Start; } return null; } /// Up to occurrence starts later than , in time order. internal static List NextStarts(CalendarItem item, DateTime after, int max) { List starts = new List(); foreach (var occurrence in Occurrences(item, after)) { if (starts.Count >= max) break; if (occurrence.Start > after) starts.Add(occurrence.Start); } return starts; } /// /// The latest occurrence start from up to and including , or NULL. /// Used to catch up on runs missed while the server was down: only the most recent one is made up. /// internal static DateTime? LatestStartBetween(CalendarItem item, DateTime from, DateTime to) { DateTime? latest = null; foreach (var occurrence in Occurrences(item, from)) { if (occurrence.Start > to) break; if (occurrence.Start >= from) latest = occurrence.Start; } return latest; } /// /// Why the repeat rule would quietly leave some periods out, or NULL. RFC 5545 skips a month that has no such day /// instead of moving to its last day, so a monthly rule on day 29-31 misses months and a yearly rule on /// 29 February runs only in leap years. Expects a rule already checked by . /// internal static string SkippedPeriodsProblem(CalendarItem item) { if (string.IsNullOrWhiteSpace(item.RecurrenceRule)) return null; RecurrencePattern rule = new RecurrencePattern(item.RecurrenceRule); List days = rule.ByMonthDay.Count > 0 ? rule.ByMonthDay : new List { item.StartDateTime.Day }; if (rule.Frequency == FrequencyType.Monthly && rule.ByMonth.Count == 0) { int lateDay = days.Where(d => d > 28).DefaultIfEmpty(0).Max(); if (lateDay > 0) return "Some months have no day " + lateDay + ", so it would not run in those months. " + "Tick \"Use the last day of every month\", or start on day 28 or earlier."; } if (rule.Frequency == FrequencyType.Yearly && rule.ByMonth.Count == 0 && rule.ByMonthDay.Count == 0 && item.StartDateTime.Month == 2 && item.StartDateTime.Day == 29) return "29 February comes only in leap years, so it would run only every fourth year. Start on another day."; return null; } #endregion #region Reminders /// /// The earliest reminder moment (occurrence start minus an offset) that is later than , /// or NULL when no reminder is left. For a one-off item, are the attendees' own /// start dates (a task assignee with personal dates is reminded from their own start). /// internal static DateTime? NextTrigger(CalendarItem item, IList offsetMinutes, DateTime after, IEnumerable ownStarts = null) { if (offsetMinutes == null || offsetMinutes.Count == 0) return null; DateTime? best = null; if (string.IsNullOrWhiteSpace(item.RecurrenceRule)) { foreach (DateTime start in OneOffStarts(item, ownStarts)) { foreach (int offset in offsetMinutes) { DateTime trigger = start.AddMinutes(-offset); if (trigger > after && (!best.HasValue || trigger < best.Value)) best = trigger; } } return best; } int maxOffset = offsetMinutes.Max(); foreach (var occurrence in Occurrences(item, after)) { // occurrences come in start order: once even the largest offset cannot beat "best", stop if (best.HasValue && occurrence.Start.AddMinutes(-maxOffset) > best.Value) break; foreach (int offset in offsetMinutes) { DateTime trigger = occurrence.Start.AddMinutes(-offset); if (trigger > after && (!best.HasValue || trigger < best.Value)) best = trigger; } } return best; } /// /// The occurrence whose reminder falls exactly on , if any. For a one-off item this is /// the item itself when the trigger matches its start or one of the attendees' own starts. /// internal static (DateTime Start, DateTime End)? OccurrenceForTrigger(CalendarItem item, IList offsetMinutes, DateTime trigger, IEnumerable ownStarts = null) { if (offsetMinutes == null || offsetMinutes.Count == 0) return null; if (string.IsNullOrWhiteSpace(item.RecurrenceRule)) { bool due = OneOffStarts(item, ownStarts).Any(start => IsReminderFor(start, offsetMinutes, trigger)); return due ? (item.StartDateTime, item.EndDateTime) : ((DateTime, DateTime)?)null; } int maxOffset = offsetMinutes.Max(); foreach (var occurrence in Occurrences(item, trigger)) { if (occurrence.Start > trigger.AddMinutes(maxOffset)) break; if (IsReminderFor(occurrence.Start, offsetMinutes, trigger)) return occurrence; } return null; } /// True when one of the reminders of something starting at falls on . internal static bool IsReminderFor(DateTime start, IList offsetMinutes, DateTime trigger) { return offsetMinutes != null && offsetMinutes.Any(o => Math.Abs((start.AddMinutes(-o) - trigger).TotalSeconds) < 1); } private static IEnumerable OneOffStarts(CalendarItem item, IEnumerable ownStarts) { return new[] { item.StartDateTime }.Concat(ownStarts ?? Enumerable.Empty()).Distinct(); } #endregion } }