public async Task <ActionResult> ImportFromWeChat(ChatHistoryImportingModel model) { var user = HttpContext.DiscussionUser(); var weChatAccount = _wechatAccountRepo.All().FirstOrDefault(wxa => wxa.UserId == user.Id); if (weChatAccount == null) { _logger.LogWarning("导入对话失败:{@ImportAttempt}", new { UserId = user.Id, user.UserName, Result = "未绑定微信号" }); return(BadRequest()); } var messages = await _chatyApiService.GetMessagesInChat(weChatAccount.WxId, model.ChatId); if (messages == null) { return(new StatusCodeResult((int)HttpStatusCode.InternalServerError)); } var replies = await _chatHistoryImporter.Import(messages); var actionResult = CreateTopic(model); if (!(actionResult is RedirectToActionResult redirectResult)) { return(actionResult); } var topicId = (int)redirectResult.RouteValues["Id"]; var topic = _topicRepo.Get(topicId); replies.ForEach(r => { r.TopicId = topicId; _replyRepo.Save(r); }); topic.ReplyCount = replies.Count; topic.LastRepliedByWeChatAccount = replies.Last().CreatedByWeChatAccount; topic.LastRepliedAt = replies.Last().CreatedAtUtc; _topicRepo.Update(topic); _logger.LogInformation("导入对话成功:{@ImportAttempt}", new { TopicId = topic.Id, model.ChatId, topic.ReplyCount, UserId = user.Id, user.UserName }); return(redirectResult); }
public async Task should_create_topic_and_import_chat_session() { var mockUser = _app.MockUser(); var chatyApiService = new Mock <ChatyApiServiceMock>(); const string wxId = "wx_account_id"; const string chatId = "1234214"; const string authorWxId = "Wx_879LKJGSJJ"; chatyApiService .Setup(chaty => chaty.GetMessageList(wxId)) .Returns(Task.FromResult(new List <ChatyMessageListItemViewModel>() { new ChatyMessageListItemViewModel() { ChatId = chatId, MessageSummaryList = new [] { "导入的消息概要1" } } })); chatyApiService .Setup(chaty => chaty.GetMessagesInChat(wxId, chatId)) .Returns(Task.FromResult(new [] { new ChatMessage { SourceName = "某人", SourceTime = "2018/12/02 12:00:09", SourceTimestamp = 1547558937, SourceWxId = authorWxId, Content = new TextChatMessageContent() { Text = "导入的消息概要1 微信消息正文" } } })); var wxAccountRepo = _app.GetService <IRepository <WeChatAccount> >(); wxAccountRepo.Save(new WeChatAccount() { WxId = wxId, UserId = mockUser.Id }); var topicController = CreateControllerWithChatyApiService(chatyApiService.Object); var model = new ChatHistoryImportingModel { Title = "first topic imported form wechat", Content = "**This is the content of this markdown**\r\n* markdown content is greate*", ChatId = chatId, Type = TopicType.Job }; var actionResult = await topicController.ImportFromWeChat(model); var topicCreated = VerifyTopicCreated(actionResult, model); Assert.NotNull(topicCreated.LastRepliedAt); topicCreated.LastRepliedAt.Value.ToString("dddd/MM/dd hh:mm:ss").ShouldNotEqual("2018/12/02 12:00:09"); var author = wxAccountRepo.All().Single(wx => wx.WxId == authorWxId); topicCreated.LastRepliedBy.ShouldBeNull(); topicCreated.LastRepliedByWeChat.ShouldEqual(author.Id); topicCreated.ReplyCount.ShouldEqual(1); topicCreated.ViewCount.ShouldEqual(0); var importedReply = _app.GetService <IRepository <Reply> >().All().Where(reply => reply.TopicId == topicCreated.Id).ToList(); Assert.NotNull(importedReply[0].CreatedByWeChat); importedReply[0].CreatedByWeChat.Value.ShouldEqual(author.Id); importedReply[0].CreatedBy.ShouldBeNull(); importedReply[0].Content.ShouldEqual("导入的消息概要1 微信消息正文"); importedReply.Count.ShouldEqual(1); var importedLog = _app.GetLogs().FirstOrDefault(log => log.Message.Contains("导入对话成功")); Assert.NotNull(importedLog); Assert.Contains($"ChatId = {chatId}", importedLog.Message); Assert.Contains($"TopicId = {topicCreated.Id}", importedLog.Message); Assert.Contains($"ReplyCount = {importedReply.Count}", importedLog.Message); }
public async Task <ActionResult> ImportFromWeChat(ChatHistoryImportingModel model) { if (string.IsNullOrEmpty(_chatyOptions.ServiceBaseUrl)) { _logger.LogWarning("无法导入对话,因为尚未配置 chaty 服务所在的位置"); return(BadRequest()); } var userId = HttpContext.DiscussionUser().Id; var weChatAccount = _wechatAccountRepo.All().FirstOrDefault(wxa => wxa.UserId == userId); if (weChatAccount == null) { _logger.LogWarning("无法导入对话,因为当前用户未绑定微信号"); return(BadRequest()); } var serviceBaseUrl = _chatyOptions.ServiceBaseUrl.TrimEnd('/'); var apiPath = $"{serviceBaseUrl}/chat/detail/{weChatAccount.WxId}/{model.ChatId}"; var chatDetailRequest = new HttpRequestMessage(); chatDetailRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", _chatyOptions.ApiToken); chatDetailRequest.Method = HttpMethod.Get; chatDetailRequest.RequestUri = new Uri(apiPath); var response = await _httpClient.SendAsync(chatDetailRequest, CancellationToken.None); if (!response.IsSuccessStatusCode) { _logger.LogWarning("无法导入对话 因为无法从 chaty 获取聊天内容"); return(BadRequest()); } ChatMessage[] messages; var jsonStream = await response.Content.ReadAsStreamAsync(); using (var reader = new StreamReader(jsonStream, Encoding.UTF8)) { var jsonString = reader.ReadToEnd(); messages = JsonConvert.DeserializeObject <ChatMessage[]>(jsonString, new ChatMessageContentJsonConverter()); } var replies = await _chatHistoryImporter.Import(messages); var actionResult = CreateTopic(model); if (!(actionResult is RedirectToActionResult redirectResult)) { return(actionResult); } var topicId = (int)redirectResult.RouteValues["Id"]; var topic = _topicRepo.Get(topicId); replies.ForEach(r => { r.TopicId = topicId; _replyRepo.Save(r); }); topic.ReplyCount = replies.Count; topic.LastRepliedByWeChatAccount = replies.Last().CreatedByWeChatAccount; topic.LastRepliedAt = replies.Last().CreatedAtUtc; _topicRepo.Update(topic); return(redirectResult); }