async Task <ControllerModels.Messages.CreateReplyResult> CreateMergedReply(int previousMessageId, ControllerModels.Messages.CreateReplyInput input) { var result = new ControllerModels.Messages.CreateReplyResult { Merged = true }; var previousMessage = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == previousMessageId && !m.Deleted); var newBody = $"{previousMessage.OriginalBody}\n\n{input.Body}"; var processedMessage = await ProcessMessageInput(newBody); foreach (var error in processedMessage.Errors) { result.Errors.Add(error.Key, error.Value); } if (!(result.Errors.Any())) { await UpdateMessageRecord(processedMessage, previousMessage); result.MessageId = previousMessage.Id; result.TopicId = previousMessage.TopicId; } return(result); }
public async Task <ControllerModels.Messages.CreateReplyResult> CreateReply(ControllerModels.Messages.CreateReplyInput input) { var result = new ControllerModels.Messages.CreateReplyResult(); var topic = await DbContext.Topics.FirstOrDefaultAsync(m => m.Id == input.TopicId); if (topic is null || topic.Deleted) { result.Errors.Add(nameof(input.TopicId), $"A record does not exist with ID '{input.TopicId}'"); return(result); } var replyTargetMessage = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == input.Id); var previousMessage = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == topic.LastMessageId && m.PostedById == CurrentUser.Id); var now = DateTime.Now; var recentReply = (now - topic.LastMessageTimePosted) < (now - now.AddSeconds(-300)); if (recentReply && !(previousMessage is null) && input.Id == previousMessage.ReplyId) { return(await CreateMergedReply(topic.LastMessageId, input)); } if (result.Errors.Any()) { return(result); } var processedMessage = await ProcessMessageInput(input.Body); foreach (var error in processedMessage.Errors) { result.Errors.Add(error.Key, error.Value); } if (!result.Errors.Any()) { var record = await CreateMessageRecord(processedMessage); record.TopicId = topic.Id; record.ReplyId = replyTargetMessage?.Id ?? 0; DbContext.Update(record); topic.ReplyCount++; topic.LastMessageId = record.Id; topic.LastMessagePostedById = CurrentUser.Id; topic.LastMessageTimePosted = now; topic.LastMessageShortPreview = record.ShortPreview; DbContext.Update(topic); if (!(replyTargetMessage is null) && replyTargetMessage.PostedById != CurrentUser.Id) { var notification = new DataModels.Notification { MessageId = record.Id, UserId = replyTargetMessage.PostedById, TargetUserId = CurrentUser.Id, Time = DateTime.Now, Type = ENotificationType.Quote, Unread = true, }; DbContext.Notifications.Add(notification); } await DbContext.SaveChangesAsync(); UpdateTopicParticipation(topic.Id, CurrentUser.Id, DateTime.Now); result.TopicId = record.TopicId; result.MessageId = record.Id; } return(result); }