using HRM.BO; using Ical.Net.CalendarComponents; using Ical.Net.DataTypes; using Ical.Net.Serialization; using System; using System.Globalization; using IcalCalendar = Ical.Net.Calendar; namespace HRM.UI.BackgroundJobs.Calendar { /// /// Builds the iCalendar (.ics) meeting invitation that makes a calendar item appear in Outlook (and Gmail, etc.). /// One invitation per person: the same UID for everybody, so Outlook matches later updates (higher SEQUENCE) and /// cancellations (METHOD:CANCEL) to the entry it already has. /// public static class CalendarIcsBuilder { private const string ProductId = "-//CEL//HRM Calendar//EN"; /// The stable unique id of an item in every invitation it ever gets. public static string Uid(int calendarItemID, string domain) { return "hrm-calendar-" + calendarItemID + "@" + domain; } /// The item, as stored (attendees not needed). /// The one person this invitation is for. /// True for a cancellation (item cancelled, or this person removed). /// IANA time zone of the stored times, or null to write "floating" local times. /// Domain for the UID. /// The mailbox the invitation is sent from (shown as organizer, with the real organizer's name). public static string Build(CalendarItem item, CalendarItemAttendee recipient, bool cancel, string timeZoneId, string uidDomain, string organizerEmail) { IcalCalendar calendar = new IcalCalendar { Method = cancel ? "CANCEL" : "REQUEST", ProductId = ProductId }; bool useTimeZone = !item.IsAllDay && !string.IsNullOrWhiteSpace(timeZoneId); if (useTimeZone) calendar.AddTimeZone(VTimeZone.FromDateTimeZone(timeZoneId)); // A one-off task can have the person's own title and dates; a repeating item always uses the series. bool recurring = !string.IsNullOrWhiteSpace(item.RecurrenceRule); DateTime start = !recurring && recipient.FromOverride.HasValue ? recipient.FromOverride.Value : item.StartDateTime; DateTime end = !recurring && recipient.ToOverride.HasValue ? recipient.ToOverride.Value : item.EndDateTime; if (end < start) end = start; string title = string.IsNullOrWhiteSpace(recipient.TitleOverride) ? item.Title : recipient.TitleOverride; CalendarEvent calendarEvent = new CalendarEvent { Uid = Uid(item.ID, uidDomain), Sequence = item.OutlookSequence, Summary = title, Description = BuildDescription(item), Location = item.Location, // all-day ends are stored inclusive; iCalendar wants the exclusive next day DtStart = ToCalDateTime(start, item.IsAllDay, useTimeZone ? timeZoneId : null), DtEnd = item.IsAllDay ? new CalDateTime(DateOnly.FromDateTime(end).AddDays(1)) : ToCalDateTime(end, false, useTimeZone ? timeZoneId : null), Status = cancel ? "CANCELLED" : "CONFIRMED", Transparency = "OPAQUE", Priority = ToIcalPriority(item.Priority) }; if (!string.IsNullOrWhiteSpace(organizerEmail)) { Organizer organizer = new Organizer("mailto:" + organizerEmail.Trim()); if (!string.IsNullOrWhiteSpace(item.OrganizerName)) organizer.CommonName = item.OrganizerName; calendarEvent.Organizer = organizer; } if (recurring) { calendarEvent.RecurrenceRule = new RecurrencePattern(item.RecurrenceRule); foreach (DateTime skippedDay in ParseExceptionDates(item.ExceptionDates)) { calendarEvent.ExceptionDates.Add(item.IsAllDay ? new CalDateTime(DateOnly.FromDateTime(skippedDay)) : ToCalDateTime(skippedDay.Date + item.StartDateTime.TimeOfDay, false, useTimeZone ? timeZoneId : null)); } } Attendee attendee = new Attendee("mailto:" + recipient.Email.Trim()) { Role = recipient.Role == EnumAttendeeRole.Optional ? "OPT-PARTICIPANT" : "REQ-PARTICIPANT", ParticipationStatus = "NEEDS-ACTION", // answers are given in HRM; an Outlook reply would only reach the sending mailbox Rsvp = false }; if (!string.IsNullOrWhiteSpace(recipient.Name)) attendee.CommonName = recipient.Name; calendarEvent.Attendees.Add(attendee); calendar.Events.Add(calendarEvent); return new CalendarSerializer().SerializeToString(calendar); } #region Helpers private static CalDateTime ToCalDateTime(DateTime value, bool allDay, string timeZoneId) { if (allDay) return new CalDateTime(DateOnly.FromDateTime(value)); return timeZoneId == null ? new CalDateTime(value, true) : new CalDateTime(value, timeZoneId, true); } /// iCalendar priority: 1 = high, 5 = normal, 9 = low, 0 = not set. private static int ToIcalPriority(EnumCalendarPriority? priority) { switch (priority) { case EnumCalendarPriority.High: return 1; case EnumCalendarPriority.Normal: return 5; case EnumCalendarPriority.Low: return 9; default: return 0; } } private static string BuildDescription(CalendarItem item) { string note = "Created in HRM. Please give your answer or update in HRM (My Calendar)."; return string.IsNullOrWhiteSpace(item.Description) ? note : item.Description.Trim() + "\n\n" + note; } private static System.Collections.Generic.IEnumerable ParseExceptionDates(string exceptionDates) { if (string.IsNullOrWhiteSpace(exceptionDates)) yield break; foreach (string part in exceptionDates.Split(',', StringSplitOptions.RemoveEmptyEntries)) { if (DateTime.TryParseExact(part.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime day)) yield return day; } } #endregion } }