/// <summary> /// Process and send event notification in teams /// </summary> /// /// <param name="currentDateTime">Current dateTime</param> /// <returns>A <see cref="Task"/>Representing the asynchronous operation</returns> public async Task <HttpResponseMessage> Post(string currentDateTime = "") { this.logProvider.LogInfo($"Processing events to send the event card in team. CurrentDateTime:{currentDateTime}"); DateTimeOffset currentDateTimeOffset; if (!DateTimeOffset.TryParse(currentDateTime, null, DateTimeStyles.AdjustToUniversal, out currentDateTimeOffset)) { currentDateTimeOffset = DateTimeOffset.UtcNow; } this.recurringEvents = await(await this.eventHelper.GetRecurringEventsToSendNotificationAsync(currentDateTimeOffset.DateTime)).ToListAsync(); this.logProvider.LogInfo($"found {this.recurringEvents.Count} to share with team."); if (this.recurringEvents.Count > 0) { List <string> eventIds = this.recurringEvents.Select(x => x.EventId).ToList(); this.logProvider.LogInfo($"found {this.recurringEvents.Count} to share with team.eventIds:" + string.Join(",", eventIds)); this.celebrationEvents = await this.eventHelper.GetEventsByEventIdsAsync(eventIds); if (this.celebrationEvents.Count > 0) { this.users = await this.userManagementHelper.GetUsersByAadObjectIdsAsync(this.celebrationEvents.Select(x => x.OwnerAadObjectId).ToList()); this.connectorServiceHelper = new ConnectorServiceHelper(this.CreateConnectorClient(this.users.FirstOrDefault().ServiceUrl), this.logProvider); this.teamsEventsDictionary = new Dictionary <string, List <string> >(); foreach (var recurringEvent in this.recurringEvents) { var celebrationEvent = this.celebrationEvents.Where(x => x.Id == recurringEvent.EventId).FirstOrDefault(); if (celebrationEvent != null) { foreach (var team in celebrationEvent.Teams) { this.UpdateTeamsEventsDictionary(team.Id, celebrationEvent.Id); } } } await this.ProcessEvents(); } } return(new HttpResponseMessage(HttpStatusCode.OK)); }
/// <summary> /// Receives message from user and reply to it. /// </summary> /// <param name="activity">activity object.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { UserTelemetryInitializer.SetTelemetryUserId(HttpContext.Current, activity.From.Id); this.LogUserActivity(activity); this.teamMembers = null; if (activity.Type == ActivityTypes.Invoke || (activity.Type == ActivityTypes.Message && activity.Value != null)) { using (var dialogScope = DialogModule.BeginLifetimeScope(Conversation.Container, activity)) { var dialog = dialogScope.Resolve <RootDialog>(); await Conversation.SendAsync(activity, () => dialog); } } else { using (var dialogScope = DialogModule.BeginLifetimeScope(this.scope, activity)) { IConnectorClient connectorClient = dialogScope.Resolve <IConnectorClient>(); this.connectorServiceHelper = new ConnectorServiceHelper(connectorClient, this.logProvider); if (activity.Type == ActivityTypes.Message) { Activity welcomeActivity = activity.CreateReply(); welcomeActivity.Attachments.Add(CelebrationCard.GetWelcomeCardInResponseToUserMessage().ToAttachment()); await connectorClient.Conversations.ReplyToActivityAsync(welcomeActivity); } else { await this.HandleSystemMessageAsync(connectorClient, activity); } } } var response = this.Request.CreateResponse(HttpStatusCode.OK); return(response); }
/// <summary> /// Reliable message delivery. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task <HttpResponseMessage> Post() { // Delete all expired messages. await this.eventHelper.DeleteExpiredMessagesAsync(); List <int> statusCodes = new List <int> { 429, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511 }; var eventMessages = await this.eventHelper.GetEventMessagesByEventStatus(statusCodes); this.connectorServiceHelper = new ConnectorServiceHelper(this.CreateConnectorClient(eventMessages.FirstOrDefault().Activity.ServiceUrl), this.logProvider); var previewMessages = eventMessages.Where(x => x.MessageType == MessageType.Preview).ToList(); var eventNotificationMessages = eventMessages.Where(x => x.MessageType == MessageType.Event).ToList(); // Retry sending event notification await this.SendEventCard(eventNotificationMessages); // Retry for preview card. await this.SendEventCard(previewMessages); return(new HttpResponseMessage(HttpStatusCode.OK)); }
/// <summary> /// Process request to send preview card /// </summary> /// <param name="currentDateTime">Current dateTime</param> /// <returns>A <see cref="Task"/>Representing the asynchronous operation</returns> public async Task <HttpResponseMessage> Post(string currentDateTime = "") { this.logProvider.LogInfo($"Processing events to send the reminder to owner. CurrentDateTime:{currentDateTime}"); DateTimeOffset currentDateTimeOffset; if (!DateTimeOffset.TryParse(currentDateTime, null, DateTimeStyles.AdjustToUniversal, out currentDateTimeOffset)) { currentDateTimeOffset = DateTimeOffset.UtcNow; } var events = await(await this.eventHelper.GetCelebrationEventsAsync(GetEventQuery(currentDateTimeOffset.Date))).ToListAsync(); this.logProvider.LogInfo($"found {events.Count} which are coming in next 72 hours."); if (events.Count > 0) { var existingRecurringEvents = await(await this.eventHelper.GetRecurringEventsAsync(events.Select(x => x.Id).ToList())).ToListAsync(); this.logProvider.LogInfo($"Found {existingRecurringEvents.Count} for which reminder has already sent"); int lastAttemptStatusCode = (int)HttpStatusCode.OK; string responseBody = string.Empty; // remove events which exist in Occurrences collection events.RemoveAll(x => existingRecurringEvents.Any(y => y.EventId == x.Id)); if (events.Count > 0) { this.users = await this.userManagementHelper.GetUsersByAadObjectIdsAsync(events.Select(x => x.OwnerAadObjectId).ToList()); this.connectorServiceHelper = new ConnectorServiceHelper(this.CreateConnectorClient(this.users.FirstOrDefault().ServiceUrl), this.logProvider); } // Loop each event and make entry in Occurrences collection to send preview and event card. foreach (var celebrationEvent in events) { this.logProvider.LogInfo("Processing event to send reminder", new Dictionary <string, string>() { { "EventId", celebrationEvent.Id }, { "UserObjectId", celebrationEvent.OwnerAadObjectId } }); // Get event owner information. var user = this.users.Where(x => x.AadObjectId == celebrationEvent.OwnerAadObjectId).FirstOrDefault(); // update conversation id if it is null. await this.ModifyUserDetailsAsync(user); DateTime upcomingEventDate = Common.GetUpcomingEventDate(celebrationEvent.Date, currentDateTimeOffset.Date); var timespan = Array.ConvertAll <string, int>(ApplicationSettings.TimeToPostCelebration.Split(':'), Convert.ToInt32); DateTime upcomingEventDateTime = upcomingEventDate.AddHours(timespan[0]).AddMinutes(timespan[1]); DateTimeOffset upcomingEventDateTimeInUTC = TimeZoneInfo.ConvertTimeToUtc(upcomingEventDateTime, TimeZoneInfo.FindSystemTimeZoneById(celebrationEvent.TimeZoneId)); // add an entry to Occurrence collection for all the upcoming event. EventOccurrence eventOccurrence = new EventOccurrence { EventId = celebrationEvent.Id, Date = upcomingEventDateTimeInUTC, }; await this.eventHelper.AddRecurringEventAsync(eventOccurrence); // Do not send reminder if event is today. if (upcomingEventDate != currentDateTimeOffset.Date) { // Add new entry to EventMessages collection for reminder. EventMessage eventMessage = new EventMessage { OccurrenceId = eventOccurrence.Id, EventId = celebrationEvent.Id, Activity = this.GetEventMessageActivity(celebrationEvent, user), MessageType = MessageType.Preview, ExpireAt = upcomingEventDate.AddHours(24), }; await this.eventHelper.AddEventMessageAsync(eventMessage); bool isMessageSentSuccessfully = false; Exception exception = null; try { HeroCard previewCard = CelebrationCard.GetPreviewCard(eventMessage.Activity); string message = string.Format(Strings.PreviewText, user.UserName); this.logProvider.LogInfo("Sending reminder message to the owner of the event", new Dictionary <string, string>() { { "EventId", celebrationEvent.Id }, { "Attachment", Newtonsoft.Json.JsonConvert.SerializeObject(previewCard) }, { "Message", message }, }); // Send reminder of event to owner. await this.connectorServiceHelper.SendPersonalMessageAsync( message, new List <Attachment> { previewCard.ToAttachment() }, user.ConversationId); this.logProvider.LogInfo($"Reminder message sent to the owner of the event. EventId: {celebrationEvent.Id}"); } catch (HttpException httpException) { lastAttemptStatusCode = httpException.GetHttpCode(); responseBody = httpException.GetHtmlErrorMessage(); exception = httpException; } catch (ErrorResponseException errorResponseException) { lastAttemptStatusCode = (int)errorResponseException.Response.StatusCode; responseBody = errorResponseException.Response.Content.ToString(); exception = errorResponseException; } catch (Exception ex) { lastAttemptStatusCode = (int)HttpStatusCode.BadRequest; responseBody = ex.ToString(); } finally { if (!isMessageSentSuccessfully) { this.logProvider.LogError("Failed to send reminder for upcoming event.", exception, new Dictionary <string, string> { { "EventId", eventMessage.EventId }, { "OccurrenceId", eventMessage.OccurrenceId }, { "eventActivity", eventMessage.Activity.ToString() }, { "LastAttemptStatusCode", lastAttemptStatusCode.ToString() }, { "LastAttemptTime", DateTime.UtcNow.ToString() }, { "ConversationId", user.ConversationId }, }); } MessageSendResult messageSendResult = new MessageSendResult() { LastAttemptTime = DateTime.UtcNow, StatusCode = lastAttemptStatusCode, ResponseBody = responseBody, }; await this.eventHelper.UpdateEventMessageAsync(eventMessage.Id, messageSendResult); } } else { this.logProvider.LogInfo("Not sending reminder for this event as its upcoming event date is today."); } } } return(new HttpResponseMessage(HttpStatusCode.OK)); }