using Ease.Core.Utility; using Hangfire; using Hangfire.Storage; using HRM.BO; using HRM.BO.Configuration; using Ical.Net.CalendarComponents; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Net.Mime; namespace HRM.UI.BackgroundJobs.Calendar { /// /// Hangfire jobs of the calendar. They only orchestrate: every decision about what is due and who gets it lives in /// ICalendarItemService. Job arguments are IDs and dates only; the data is always read fresh from the database. /// public class CalendarJobs { public const string QueueName = "calendar"; public const string DispatcherJobId = "calendar-dispatcher"; /// Retired daily birthday digest; kept only so start-up can remove the recurring job where it still exists. public const string BirthdayDigestJobId = "calendar-birthday-digest"; private const int MaxItemsPerRun = 200; /// How long a SyncOutlook run waits for another run of the same item to finish. private static readonly TimeSpan OutlookLockTimeout = TimeSpan.FromMinutes(5); private readonly ICalendarItemService _calendar; private readonly IBackgroundJobClient _jobs; private readonly JobStorage _storage; private readonly CalendarSettings _settings; private readonly EmailSettings _email; private readonly IEmailDispatchService _emailDispatch; public CalendarJobs(ICalendarItemService calendar, IBackgroundJobClient jobs, JobStorage storage, IOptions settings, IOptions email, IEmailDispatchService emailDispatch) { _calendar = calendar; _jobs = jobs; _storage = storage; _settings = settings.Value; _email = email.Value; _emailDispatch = emailDispatch; } #region Reminders /// /// Runs every minute: finds due reminders, schedule-job runs and schedule-email runs (moving each item's NextTriggerAt /// on) and queues one job per reminder or run. Never runs twice at the same time; a failed run simply happens again /// next minute. /// [Queue(QueueName)] [DisableConcurrentExecution(timeoutInSeconds: 300)] [AutomaticRetry(Attempts = 0)] public void Dispatch() { DateTime now = DateTime.Now; if (_settings.RemindersEnabled) { foreach (CalendarDueReminder due in _calendar.TakeDueReminders(now, _settings.ReminderGraceMinutes, MaxItemsPerRun)) { _jobs.Enqueue(j => j.SendReminder(due.CalendarItemID, due.TriggerAt, due.OccurrenceStart, due.OccurrenceEnd)); } } if (_settings.ScheduleJobsEnabled) { foreach (CalendarDueRun run in _calendar.TakeDueScheduleRuns(now, MaxItemsPerRun)) { _jobs.Enqueue(j => j.RunScheduleJob(run.CalendarItemID, run.OccurrenceStart)); } } if (_settings.ScheduleEmailsEnabled) { foreach (CalendarDueRun run in _calendar.TakeDueScheduleEmails(now, MaxItemsPerRun)) { _jobs.Enqueue(j => j.SendScheduleEmail(run.CalendarItemID, run.OccurrenceStart)); } } } /// /// Sends one reminder to everyone on the item who has not declined (and, for tasks, is not done yet). On a one-off /// task, a person with their own start date is reminded only when the reminder belongs to their own start. /// Each person is claimed first, so a retry never repeats a reminder that already went out; a failed send is /// released and the job fails, and Hangfire retries only the people still waiting. /// [Queue(QueueName)] [AutomaticRetry(Attempts = 3)] public void SendReminder(int calendarItemID, DateTime triggerAt, DateTime occurrenceStart, DateTime occurrenceEnd) { CalendarItem item = _calendar.GetForSystem(calendarItemID); if (item == null || item.Status != EnumCalendarItemStatus.Active) return; bool oneOff = string.IsNullOrWhiteSpace(item.RecurrenceRule); List offsets = ReminderOffsets(item); EnumReminderChannel channel = item.ReminderChannel ?? EnumReminderChannel.Both; List failures = new List(); foreach (CalendarItemAttendee attendee in item.Attendees.Where(WantsReminder)) { DateTime start = occurrenceStart; DateTime end = occurrenceEnd; if (oneOff) { // the person's own dates (task assignee) win over the item's dates start = attendee.FromOverride ?? item.StartDateTime; end = attendee.ToOverride ?? item.EndDateTime; if (end < start) end = start; if (!offsets.Any(o => Math.Abs((start.AddMinutes(-o) - triggerAt).TotalSeconds) < 1)) continue; // this reminder is for someone else's dates } if (!_calendar.ClaimReminder(attendee.ID, triggerAt)) continue; // already sent (an earlier attempt of this job) try { Deliver(item, attendee, channel, CalendarMessages.Reminder(item, attendee, start, end, CalendarLink())); } catch (Exception e) { _calendar.ReleaseReminder(attendee.ID, triggerAt, attendee.LastReminderAt); ExceptionLog.Write(e); failures.Add(attendee.Name + ": " + e.Message); } } if (failures.Count > 0) throw new InvalidOperationException("Calendar reminder could not reach everyone: " + string.Join("; ", failures)); } private static bool WantsReminder(CalendarItemAttendee attendee) { return attendee.Status == EnumAttendeeStatus.Active && attendee.AttendeeType != EnumAttendeeType.Department && attendee.ResponseStatus != EnumResponseStatus.Declined && attendee.TaskStatus != EnumCalendarTaskStatus.Done; } private static List ReminderOffsets(CalendarItem item) { try { return item.GetReminderOffsetMinutes(); } catch (ArgumentException) { return new List(); } } #endregion #region Schedule jobs /// /// One run of a schedule job: creates its task, then tells the assignees and sends the Outlook invitations like for /// any new task. Safe to retry: a run creates its task only once, and only the call that created it notifies. /// [Queue(QueueName)] [AutomaticRetry(Attempts = 3)] public void RunScheduleJob(int calendarItemID, DateTime occurrenceStart) { if (!_settings.ScheduleJobsEnabled) return; AfterScheduleRun(_calendar.RunScheduleJob(calendarItemID, occurrenceStart)); } /// Queues the new task's notifications and Outlook invitations; a run that created nothing is logged. private void AfterScheduleRun(CalendarJobRunResult result) { if (result == null) return; if (!result.Created) { if (result.TaskID == 0 && !string.IsNullOrWhiteSpace(result.Message)) ExceptionLog.Write(new InvalidOperationException("Calendar schedule job created no task: " + result.Message)); return; } int taskID = result.TaskID; _jobs.Enqueue(j => j.NotifyChange(taskID, EnumCalendarChange.Created, true)); _jobs.Enqueue(j => j.SyncOutlook(taskID)); } #endregion #region Schedule emails /// /// One run of a schedule email: creates its e-mail batch in the central e-mail log (once per run), then sends it /// through IEmailDispatchService, so every recipient's outcome is logged and Mail Manager's Mail Log History shows /// the run with its sent / failed counts and can retry it. Safe to retry: a repeat finds the same batch and sends /// only the recipients still pending. /// [Queue(QueueName)] [AutomaticRetry(Attempts = 3)] public void SendScheduleEmail(int calendarItemID, DateTime runAt) { // like Mail Manager's general mail: Calendar:SendMail / RedirectAllMailTo (reminders, invitations) do not apply if (!_settings.ScheduleEmailsEnabled) return; CalendarEmailRunResult result = _calendar.PrepareScheduleEmailRun(calendarItemID, runAt); if (result == null || result.MasterEmailLogID <= 0) { if (!string.IsNullOrWhiteSpace(result?.Message)) ExceptionLog.Write(new InvalidOperationException("Calendar schedule email sent nothing: " + result.Message)); return; } // the batch is logged as the person who set the schedule email up; everyone gets the same file EmailDispatchRequest request = new EmailDispatchRequest { UserID = result.CreatedBy, PreserveAttachment = false }; EmailAttachmentInfo attachment = result.Attachment; if (attachment != null) request.AttachmentResolver = (EmailRecipient recipient) => attachment; _emailDispatch.ProcessBatch(result.MasterEmailLogID, request, _email); } #endregion #region Outlook (ICS invitations) /// /// Brings everyone's Outlook in line with the item (Calendar:OutlookSync "Ics"): a REQUEST to whoever has not got /// the current version yet (new people, or after a change), a CANCEL to removed people and, when the item is /// cancelled, to everyone who had it. Progress is stored per person (InviteSentSequence), so a retry only sends /// what is still missing. Runs for the same item never overlap; different items run side by side. /// [Queue(QueueName)] [AutomaticRetry(Attempts = 3)] public void SyncOutlook(int calendarItemID) { if (!OutlookInvitesOn()) return; using (IStorageConnection connection = _storage.GetConnection()) using (connection.AcquireDistributedLock("calendar:outlook:" + calendarItemID, OutlookLockTimeout)) { SyncOutlookLocked(calendarItemID); } } private void SyncOutlookLocked(int calendarItemID) { CalendarItem item = _calendar.GetForSystem(calendarItemID); // a schedule job (or schedule email) is HR's set-up, not a meeting: only the tasks a job creates go to Outlook if (item == null || item.ItemType == EnumCalendarItemType.ScheduleJob || item.ItemType == EnumCalendarItemType.ScheduleEmail) return; string timeZoneId = ResolveIanaTimeZone(); string uidDomain = ResolveUidDomain(); string link = CalendarLink(); bool itemCancelled = item.Status == EnumCalendarItemStatus.Cancelled; List failures = new List(); foreach (CalendarItemAttendee attendee in item.Attendees .Where(a => a.AttendeeType != EnumAttendeeType.Department && !string.IsNullOrWhiteSpace(a.Email))) { bool isOrganizer = attendee.Role == EnumAttendeeRole.Organizer; bool stillIn = attendee.Status == EnumAttendeeStatus.Active && !itemCancelled; try { if (!stillIn) { if (!attendee.InviteSentSequence.HasValue) continue; // never had it in Outlook CalendarMessage message = itemCancelled ? CalendarMessages.Cancelled(item, attendee, link) : CalendarMessages.Removed(item, attendee, link); SendInvite(item, attendee, true, timeZoneId, uidDomain, message); _calendar.MarkInviteSent(attendee.ID, null); } else if (!attendee.InviteSentSequence.HasValue || attendee.InviteSentSequence.Value < item.OutlookSequence) { bool isUpdate = attendee.InviteSentSequence.HasValue; CalendarMessage message = isOrganizer ? CalendarMessages.OrganizerCopy(item, attendee, isUpdate, link) : (isUpdate ? CalendarMessages.Updated(item, attendee, link) : CalendarMessages.Invited(item, attendee, link)); SendInvite(item, attendee, false, timeZoneId, uidDomain, message); _calendar.MarkInviteSent(attendee.ID, item.OutlookSequence); } } catch (Exception e) { ExceptionLog.Write(e); failures.Add(attendee.Name + ": " + e.Message); } } if (failures.Count > 0) throw new InvalidOperationException("Outlook invitation could not reach everyone: " + string.Join("; ", failures)); } /// An HTML e-mail that carries the .ics invitation as a text/calendar part, as Outlook expects. private void SendInvite(CalendarItem item, CalendarItemAttendee to, bool cancel, string timeZoneId, string uidDomain, CalendarMessage message) { string ics = CalendarIcsBuilder.Build(item, to, cancel, timeZoneId, uidDomain, _email.FromAddress); AlternateView calendarView = AlternateView.CreateAlternateViewFromString(ics, new ContentType("text/calendar; method=" + (cancel ? "CANCEL" : "REQUEST") + "; charset=UTF-8")); calendarView.TransferEncoding = TransferEncoding.Base64; SendMail(to.Email, message.MailSubject, message.MailBody, calendarView); } /// /// IANA id of the time zone the stored times are in: Calendar:TimeZoneId (IANA or Windows id), else the server's own. /// Null when it cannot be worked out; invitations then carry "floating" local times. /// private string ResolveIanaTimeZone() { string id = string.IsNullOrWhiteSpace(_settings.TimeZoneId) ? TimeZoneInfo.Local.Id : _settings.TimeZoneId.Trim(); if (TimeZoneInfo.TryConvertWindowsIdToIanaId(id, out string ianaId)) id = ianaId; try { VTimeZone.FromDateTimeZone(id); // validates the id return id; } catch (Exception) { return null; } } /// True when changes reach people as Outlook invitations (mail on, Calendar:OutlookSync "Ics"). private bool OutlookInvitesOn() { return _settings.SendMail && _settings.OutlookSync == EnumOutlookSyncMode.Ics; } /// Calendar:IcsDomain, else the domain of the sending address, else "hrm.local". private string ResolveUidDomain() { if (!string.IsNullOrWhiteSpace(_settings.IcsDomain)) return _settings.IcsDomain.Trim(); string from = _email?.FromAddress ?? string.Empty; int at = from.LastIndexOf('@'); return at >= 0 && at < from.Length - 1 ? from.Substring(at + 1).Trim() : "hrm.local"; } #endregion #region Change notifications /// /// Tells attendees what changed: invited / assigned, updated, removed or cancelled (bell only in ICS mode). /// When only people changed ( false), only those people hear about it: new people, /// removed people, and people whose own title or dates changed. Best effort and not retried, because a retry could /// repeat notifications that already went out. /// [Queue(QueueName)] [AutomaticRetry(Attempts = 0)] public void NotifyChange(int calendarItemID, EnumCalendarChange change, bool detailsChanged) { CalendarItem item = _calendar.GetForSystem(calendarItemID); // a schedule job's targets hear about the tasks it creates (a schedule email's about its e-mails), never about // the job itself if (item == null || item.ItemType == EnumCalendarItemType.ScheduleJob || item.ItemType == EnumCalendarItemType.ScheduleEmail) return; string link = CalendarLink(); // In ICS mode the Outlook invitation (SyncOutlook) is the e-mail, so only the bell goes from here. bool allowMail = !OutlookInvitesOn(); // Rows created or changed by the save that triggered this job carry the same timestamp as the item. DateTime changedAt = item.ModifiedDate ?? item.CreatedDate; bool isFreshItem = !item.ModifiedDate.HasValue; List others = item.Attendees .Where(a => a.Role != EnumAttendeeRole.Organizer && a.AttendeeType != EnumAttendeeType.Department) .ToList(); foreach (CalendarItemAttendee attendee in others) { CalendarMessage message = null; bool touchedNow = attendee.ModifiedDate == changedAt; if (change == EnumCalendarChange.Cancelled) { if (attendee.Status == EnumAttendeeStatus.Active) message = CalendarMessages.Cancelled(item, attendee, link); } else if (change == EnumCalendarChange.Created) { if (attendee.Status == EnumAttendeeStatus.Active) message = CalendarMessages.Invited(item, attendee, link); } else if (change == EnumCalendarChange.Updated) { if (attendee.Status == EnumAttendeeStatus.Removed) { if (touchedNow) message = CalendarMessages.Removed(item, attendee, link); } else if (!isFreshItem && attendee.CreatedDate == changedAt) { message = CalendarMessages.Invited(item, attendee, link); } else if (detailsChanged || isFreshItem || touchedNow) { message = CalendarMessages.Updated(item, attendee, link); } } if (message != null) TryDeliver(item, attendee, message, allowMail); } } /// Tells the organizer that an attendee answered (Yes / No / Maybe) or updated their task progress. [Queue(QueueName)] [AutomaticRetry(Attempts = 0)] public void NotifyOrganizer(int calendarItemID, int attendeeID, EnumCalendarChange change) { CalendarItem item = _calendar.GetForSystem(calendarItemID); if (item == null) return; CalendarItemAttendee organizer = item.Attendees.FirstOrDefault(a => a.Role == EnumAttendeeRole.Organizer); CalendarItemAttendee attendee = item.Attendees.FirstOrDefault(a => a.ID == attendeeID); if (organizer == null || attendee == null || organizer.ID == attendee.ID) return; CalendarMessage message = change == EnumCalendarChange.TaskUpdated ? CalendarMessages.TaskUpdated(item, attendee, CalendarLink()) : CalendarMessages.Responded(item, attendee, CalendarLink()); TryDeliver(item, organizer, message); } #endregion #region Delivery /// Change notifications go out as bell and e-mail; a failure for one person is logged and does not stop the rest. private void TryDeliver(CalendarItem item, CalendarItemAttendee to, CalendarMessage message, bool allowMail = true) { try { Deliver(item, to, allowMail ? EnumReminderChannel.Both : EnumReminderChannel.Bell, message, allowMail); } catch (Exception e) { ExceptionLog.Write(e); } } /// /// E-mail for everyone with an address, then the bell for employees. A user account without an employee has no /// bell, so it gets the e-mail even when only the bell was chosen. Once the e-mail is out, a failed bell is only /// logged, so a retry never sends the e-mail twice; when nothing went out yet, the failure is thrown. /// private void Deliver(CalendarItem item, CalendarItemAttendee to, EnumReminderChannel channel, CalendarMessage message, bool allowMail = true) { bool canBell = to.EmployeeID.HasValue; bool bell = canBell && channel != EnumReminderChannel.Mail; bool mail = allowMail && (channel != EnumReminderChannel.Bell || !canBell); bool mailSent = false; if (mail && _settings.SendMail && !string.IsNullOrWhiteSpace(to.Email)) { SendMail(to.Email, message.MailSubject, message.MailBody); mailSent = true; } if (bell) { try { _calendar.AddInAppNotification(to.EmployeeID.Value, message.Header, message.BellText, item.ID, item.CreatedBy); } catch (Exception e) when (mailSent) { ExceptionLog.Write(e); } } } private void SendMail(string to, string subject, string body, AlternateView calendarView = null) { string recipient = to; if (!string.IsNullOrWhiteSpace(_settings.RedirectAllMailTo)) { // test mode: everything goes to one address, the real recipient is shown in the subject subject = "[Test - for " + to + "] " + subject; recipient = _settings.RedirectAllMailTo.Trim(); } MailSender mail = new MailSender { To = recipient, Subject = subject, Body = body }; mail.SendMailOrThrow(_email, calendarView); } /// Link to the calendar page, from EmailSettings.WebAddress when it is set. private string CalendarLink() { string web = _email?.WebAddress; return string.IsNullOrWhiteSpace(web) ? null : web.TrimEnd('/') + "/#/calendar/my-calendar"; } #endregion } }