public async Task should_import_messages_as_replies()
        {
            var messages = new[]
            {
                new ChatMessage
                {
                    SourceName      = "someone",
                    SourceTime      = "2018/12/02 12:00:08",
                    SourceTimestamp = 1547552937,
                    SourceWxId      = "Wx_879LJJKJGS",
                    Content         = new TextChatMessageContent()
                    {
                        Text = "Hello WeChat Message"
                    }
                },
                new ChatMessage
                {
                    SourceName      = "Another one",
                    SourceTime      = "2018/12/02 12:00:09",
                    SourceTimestamp = 1547558937,
                    SourceWxId      = "Wx_879LKJGSJJ",
                    Content         = new TextChatMessageContent()
                    {
                        Text = "The second Message"
                    }
                }
            };

            var importResult = await _importer.Import(messages);

            Assert.Equal(2, importResult.Count);
            Assert.Equal("Hello WeChat Message", importResult[0].Content);
            Assert.Equal("The second Message", importResult[1].Content);
        }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
0
        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);
        }