HRM-10/HRM.DA/Service/Calendar/CalendarRecurrence.cs
Mohaimen Hasan 838b8d4480 first commit
2026-11-03 13:06:00 +06:00

411 lines
18 KiB
C#

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
{
/// <summary>
/// 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.
/// </summary>
internal static class CalendarRecurrence
{
private const int MaxInterval = 99;
private const int MaxCount = 730;
private const int MaxExceptionDates = 500;
/// <summary>Safety stop: never examine more occurrences than this in one search.</summary>
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
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>The end of the last occurrence, or NULL for a series without COUNT or UNTIL.</summary>
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<DateTime> ParseExceptionDates(string exceptionDates)
{
SortedSet<DateTime> dates = new SortedSet<DateTime>();
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<DateTime> dates)
{
List<string> parts = dates.Select(d => d.ToString(ExceptionDateFormat, CultureInfo.InvariantCulture)).ToList();
return parts.Count == 0 ? null : string.Join(",", parts);
}
/// <summary>Adds one skipped day to an exception-date list and returns the new list.</summary>
internal static string AddExceptionDate(string exceptionDates, DateTime day)
{
SortedSet<DateTime> dates = ParseExceptionDates(exceptionDates);
dates.Add(day.Date);
return FormatExceptionDates(dates);
}
#endregion
#region Occurrences
/// <summary>
/// Occurrences (start, end) in time order, beginning with the first one that has not ended before
/// <paramref name="from"/>. A non-repeating item has exactly one occurrence. Ends inclusive, as stored.
/// </summary>
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<DateTime> 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")
/// <summary>
/// True when no occurrence is shown before <paramref name="occurrenceStart"/>, so "this and following"
/// covers the whole series.
/// </summary>
internal static bool IsFirstOccurrence(CalendarItem item, DateTime occurrenceStart)
{
foreach (var occurrence in Occurrences(item, item.StartDateTime))
return occurrence.Start >= occurrenceStart;
return true;
}
/// <summary>
/// The series' repeat rule changed so that it ends just before <paramref name="occurrenceStart"/>
/// (any COUNT or UNTIL is replaced by an UNTIL on the previous moment, or the previous day for all-day items).
/// </summary>
internal static string RuleEndingBefore(CalendarItem item, DateTime occurrenceStart)
{
List<string> 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);
}
/// <summary>
/// How many times the rule produced the item before <paramref name="occurrenceStart"/>, skipped days included
/// (that is what COUNT counts).
/// </summary>
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;
}
/// <summary>The skipped days on or after <paramref name="fromDay"/> (true) or before it (false).</summary>
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
/// <summary>The first occurrence start later than <paramref name="after"/>, or NULL when there is none.</summary>
internal static DateTime? NextStart(CalendarItem item, DateTime after)
{
foreach (var occurrence in Occurrences(item, after))
{
if (occurrence.Start > after)
return occurrence.Start;
}
return null;
}
/// <summary>Up to <paramref name="max"/> occurrence starts later than <paramref name="after"/>, in time order.</summary>
internal static List<DateTime> NextStarts(CalendarItem item, DateTime after, int max)
{
List<DateTime> starts = new List<DateTime>();
foreach (var occurrence in Occurrences(item, after))
{
if (starts.Count >= max)
break;
if (occurrence.Start > after)
starts.Add(occurrence.Start);
}
return starts;
}
/// <summary>
/// The latest occurrence start from <paramref name="from"/> up to and including <paramref name="to"/>, or NULL.
/// Used to catch up on runs missed while the server was down: only the most recent one is made up.
/// </summary>
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;
}
/// <summary>
/// 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 <see cref="Normalize"/>.
/// </summary>
internal static string SkippedPeriodsProblem(CalendarItem item)
{
if (string.IsNullOrWhiteSpace(item.RecurrenceRule))
return null;
RecurrencePattern rule = new RecurrencePattern(item.RecurrenceRule);
List<int> days = rule.ByMonthDay.Count > 0 ? rule.ByMonthDay : new List<int> { 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
/// <summary>
/// The earliest reminder moment (occurrence start minus an offset) that is later than <paramref name="after"/>,
/// or NULL when no reminder is left. For a one-off item, <paramref name="ownStarts"/> are the attendees' own
/// start dates (a task assignee with personal dates is reminded from their own start).
/// </summary>
internal static DateTime? NextTrigger(CalendarItem item, IList<int> offsetMinutes, DateTime after,
IEnumerable<DateTime> 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;
}
/// <summary>
/// The occurrence whose reminder falls exactly on <paramref name="trigger"/>, 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.
/// </summary>
internal static (DateTime Start, DateTime End)? OccurrenceForTrigger(CalendarItem item, IList<int> offsetMinutes, DateTime trigger,
IEnumerable<DateTime> 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;
}
/// <summary>True when one of the reminders of something starting at <paramref name="start"/> falls on <paramref name="trigger"/>.</summary>
internal static bool IsReminderFor(DateTime start, IList<int> offsetMinutes, DateTime trigger)
{
return offsetMinutes != null && offsetMinutes.Any(o => Math.Abs((start.AddMinutes(-o) - trigger).TotalSeconds) < 1);
}
private static IEnumerable<DateTime> OneOffStarts(CalendarItem item, IEnumerable<DateTime> ownStarts)
{
return new[] { item.StartDateTime }.Concat(ownStarts ?? Enumerable.Empty<DateTime>()).Distinct();
}
#endregion
}
}