From fa1dfaf35eda4c38602c723d9859b622f598fd56 Mon Sep 17 00:00:00 2001
From: 苗权威 <1160292058@qq.com>
Date: Wed, 8 Jan 2020 21:32:46 +0800
Subject: [PATCH] 1.8
---
.idea/workspace.xml | 927 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
spirit/src/main/java/ai/qiwu/tmall/spirit/controller/SpiritController.java | 5 +++++
spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java | 44 +++++++++++++++++++++++++++++++++++++-------
spirit/src/main/resources/application.yml | 7 ++++---
third_party_load/pom.xml | 7 +++++++
third_party_load/src/main/resources/static/aliGenie-intent-sematic.jar | Bin 0 -> 85708 bytes
tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java | 20 +++++++++++++-------
tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------
tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java | 5 +++--
tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java | 40 +++++++++++++++++++++++++++++++++++-----
tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java | 4 ++--
xiaoduhome/pom.xml | 13 +++++++++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Constants.java | 26 ++++++++++++++++++++------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/OkHttp3Utils.java | 39 +++++++++++++++++++++++++++++++++++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Utils.java | 123 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/AudioGetController.java | 6 ++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/SpiritController.java | 4 ++--
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/WebSocketLogController.java | 99 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java | 150 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/GameProjectTb.java | 3 +++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/OnProductDetail.java | 3 +++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/OverTimeDetail.java | 2 +-
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/AllOnProductInfoRepository.java | 6 ++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/GameProjectTbRepository.java | 2 +-
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java | 403 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------------------------------------------------------------------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java | 49 ++++++++++++++++++++++++++++++++++++++-----------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleService.java | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/ChatLogs.java | 142 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LogResponse.java | 15 +++++++++++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LoginData.java | 17 +++++++++++++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/InitialData.java | 2 +-
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritService.java | 13 +++++++------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java | 38 +++++++++++++++++++-------------------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/Utils.java | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java | 11 +++++++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/innerRequest/Request.java | 6 +++++-
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/PhoneTemplate.java | 19 +++++++++++++++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/ToDisplay.java | 3 +++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java | 441 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiTestService.java | 517 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
xiaoduhome/src/main/resources/application.yml | 10 ++++++++++
xiaoduhome/src/main/resources/templates/ChatLog.html | 39 +++++++++++++++++++++++++++++++++++++++
xiaoduhome/src/main/resources/templates/ChatLogChoose.html | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
xiaoduhome/src/main/resources/templates/LoadFailed.html | 4 ++--
xiaoduhome/src/main/resources/templates/Log5(1).html | 107 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
xiaoduhome/src/main/resources/templates/Log5.html | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
xiaoduhome/src/main/resources/templates/LookLogLogin.html | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
xiaoduhome/src/main/resources/templates/index.html | 7 ++++++-
49 files changed, 3048 insertions(+), 995 deletions(-)
create mode 100644 third_party_load/src/main/resources/static/aliGenie-intent-sematic.jar
create mode 100644 xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/ChatLogs.java
create mode 100644 xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LogResponse.java
create mode 100644 xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LoginData.java
create mode 100644 xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/PhoneTemplate.java
create mode 100644 xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiTestService.java
create mode 100644 xiaoduhome/src/main/resources/templates/ChatLog.html
create mode 100644 xiaoduhome/src/main/resources/templates/ChatLogChoose.html
create mode 100644 xiaoduhome/src/main/resources/templates/Log5(1).html
create mode 100644 xiaoduhome/src/main/resources/templates/Log5.html
create mode 100644 xiaoduhome/src/main/resources/templates/LookLogLogin.html
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index c154bde..9135d6c 100755
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -7,49 +7,46 @@
-
-
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
-
+
+
+
+
+
-
-
+
+
+
-
-
+
+
+
@@ -94,88 +91,83 @@
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
+
-
-
+
+
-
-
+
+
-
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
-
+
+
-
-
-
-
-
+
+
-
+
-
-
+
+
@@ -186,44 +178,45 @@
-
+
+
- oldDatas
- skillId
- headers
- preBotAccount
- deleteTheAudio
- /home/dc2-user/projects/audiobox
- path
- description
- log.info
- log.warn
- x-csrf-token
- file
- substring
- catch
- 4
- count
- listFiles
- null
- Token
- token
- ctoken
- dataNew
- buildTaskResult
- QI_WU_TERMINATE_DIDI
- filePath
- usDir
+ LAST_OUTTIME_RESULT
+ buildLogOutResponse
+ request
+ secret
+ zOQuywFuKjlhbTMr4dHwFA==
channelId2RecommendBotAcc
- LAST_OUTTIME_MARK
- changeAudioUrl
- range
+ dealT
+ channel2Bots
+ 刚才走
+ jiaoyouChannel2Bots
+ request.getSession().getUser()
+ commons-lang3
+ org.apache.commons
+ NUM_OR_ALPHA
+ customUserId
+ getUserId
+ LAST_AUDIO_PLAY
+ buildCancelTextResponse
+ dealWithEndRequest
+ userId
+ yQiYt_RTsMxH92Tn4QsGNdwx
+ OJPfsbbA5Qoac2XN3dKRj4Cx
+ C1vISzheJtVumYBwGK0IekCtSzSeVyX6lbRIegoew28
+ csvDic
+ EtfZNKr3Nzh8+y3u1wQ11fYq2aAY+GWGJHyqmZUDHk8=
+ buildResponseBeforeLoadout
+ 4
+ PhoneTemplate
+ ASIDE_IMG
+ log.info
OPENID_CACHE
@@ -243,57 +236,57 @@
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
+
+
+
-
-
+
+
+
+
+
+
@@ -320,15 +313,6 @@
-
-
-
-
-
-
-
-
-
@@ -344,9 +328,9 @@
-
-
-
+
+
+
@@ -357,8 +341,6 @@
-
-
@@ -369,229 +351,78 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
-
-
-
+
-
-
-
+
-
-
-
+
-
-
-
+
-
+
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
-
+
-
+
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
@@ -600,6 +431,8 @@
+
+
@@ -609,6 +442,8 @@
+
+
@@ -616,9 +451,7 @@
-
-
-
+
@@ -626,9 +459,8 @@
-
-
-
+
+
@@ -636,9 +468,9 @@
-
-
-
+
+
+
@@ -647,11 +479,16 @@
+
+
+
+
+
@@ -665,7 +502,7 @@
-
+
@@ -684,11 +521,11 @@
+
-
@@ -717,7 +554,7 @@
-
+
@@ -731,8 +568,8 @@
-
-
+
+
@@ -744,12 +581,12 @@
-
-
-
+
+
+
-
+
@@ -770,12 +607,12 @@
-
-
-
+
+
+
-
+
@@ -1092,8 +929,11 @@
+
+
-
+
+
@@ -1114,17 +954,14 @@
-
-
-
+
+
-
-
@@ -1295,7 +1132,10 @@
-
+
+
+
+
@@ -1305,7 +1145,7 @@
-
+
@@ -1317,7 +1157,7 @@
-
+
@@ -1325,36 +1165,36 @@
-
+
-
-
+
+
-
+
-
+
-
+
-
+
-
+
@@ -1368,419 +1208,396 @@
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
+
+
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
+
+
-
+
-
+
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
+
+
-
+
-
+
-
-
+
+
+
+
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
+
+
diff --git a/spirit/src/main/java/ai/qiwu/tmall/spirit/controller/SpiritController.java b/spirit/src/main/java/ai/qiwu/tmall/spirit/controller/SpiritController.java
index 0b02e75..a223d10 100644
--- a/spirit/src/main/java/ai/qiwu/tmall/spirit/controller/SpiritController.java
+++ b/spirit/src/main/java/ai/qiwu/tmall/spirit/controller/SpiritController.java
@@ -122,6 +122,11 @@ public class SpiritController {
return "success";
}
+ @GetMapping("/del")
+ public void del(String filepath, Long skillId) {
+ spiritAudioUpload.deleteAudio(filepath, skillId);
+ }
+
@GetMapping("/get/csv")
public void getCsv(String name, HttpServletResponse response) {
String path = csvDic+name;
diff --git a/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java b/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java
index 6e1b774..d2dd098 100644
--- a/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java
+++ b/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java
@@ -35,6 +35,7 @@ import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
+import java.util.stream.Collectors;
/**
* @author 苗权威
@@ -45,9 +46,14 @@ import java.util.regex.Matcher;
public class SpiritAudioUpload {
@Value("${csvDic}")
private String csvDic;
- private volatile String cookie = "cna=qsWIFY5RHlMCAXeJN3DsHj3O; isg=BFhY_wUGsjusjZ29XklHD24lKo8q6b1WxqYDypJJcBNeLfsXOFA0W-fLZaW4JnSj; CNZZDATA1261708326=1797143004-1560414985-%7C1577077139; _cnzz_CV1261708326=52463%7C%F0%9F%8C%8E%20common%2F%E8%8E%B7%E5%8F%96%20oss%20token%7Cp; hng=CN%7Czh-CN%7CCNY%7C156; enc=GlWCH0jde0teESrXYo%2BHF75NARTOPv7uKzyscUHesjr8NqyYTkHf%2BD6PG2iP4gPoGIsaO8aq%2BG41Q6kPPhYpvw%3D%3D; UM_distinctid=16ef9e5d343206-06ea6f889716618-76256753-1fa400-16ef9e5d344241; uc1=pas=0&cookie21=UtASsssme%2BBq&tag=8&cookie14=UoTbmEnmIFxXUw%3D%3D&existShop=false&cookie15=Vq8l%2BKCLz3%2F65A%3D%3D&lng=zh_CN&cookie16=VFC%2FuZ9az08KUQ56dCrZDlbNdA%3D%3D; t=925ffaa4a0ded6c2dc567c2eedd425f0; _tb_token_=3a3eeb3e68337; cookie2=145c78f447bf6a4cafb894c15072214f; dnk=tb13503054; tracknick=tb13503054; _l_g_=Ug%3D%3D; unb=1038446007; cookie1=UNMubI1eQ0gVOzLdxFCJj7hzIKFouglcA%2BlE1IYgcZQ%3D; login=true; cookie17=UoH8Vd06g9TEfA%3D%3D; _nk_=tb13503054; sg=47f; csg=f8c7b18a; ctoken=ThECcNhEBvJDLHL4AtCCWzqO; accountType=TB; EGG_SESS=OG910qv3Q3gsrSK4yqRmX3-1-P_ARlUIzlqweqLqnRF5dKELPTe4hiVT80Slz3WPDCsXS99IeB9EJ08mKe1fnCJBm_qC4NhmU1P2hSXcOOxhqcjA9knJrTbFO_08KukZd6segTIuGD5H9RDPRbAiBTjq3sXZE-ONRz07itH3ie_0MGVIB8n-XxMFQYetkS-BR11S3A-MA1iaMpYPPHfR5b5tg5_xnx0qw6APDlgMbNATwwRwWP1cybf5tiXsOgBw1DDDyMsFi0RN_djZp8RCYf7gwrqOhh3hNqNOz0IxeCznza7eUv9tbTMaR9r62A4NvYwEMI6gKCAQklI7LyPiHnc_xayqlbJxJdVGSv42QrTGGpDNj6tiQKCCRsKISe_3MCOJIIp5hDb2ybw_UcogYaiEd6IcIg97LWKY6ee-fuVIK9zSfzz60mlEYpKJ0KpK1XIeQXvt77C1Gv6yv-Vcw3fk_5Pnfq0frq5N0N3xgDDXaWxX1Vu6BUgBgtOYK8GpHmGi2tDTs-Fx3ATG9lELByjlDBVA1uHlmw4FAXR6gq_3DdvAbMlR2XYshBrIe9PpMNjHHHhjGPY9MdkFSX2HgXKcnCy_ID6oizYaaykxQGRv8mHiW8YjzE6X-KgXwm3JvFkHAqEXkty_xPBoz6u97mgJfY0Cps2ezNUQVgdIKupkX5NUvlFBDJD7lr1N6qZPChrPBluSDyexWuljvO2GB1ZsFKf2GVkCBvTIL5KMB3jrp37o7_9iztF50t4sVEY6jtjpXgSYXBs08gYX4cls2y3Jz3qgZ3GRNjqUOkm-KTg6V6D_cOxVx9lfoYH8oFX_ZixCURKlSOvDu8WIcj1_CCvPgEZbXfbYQLLmDQzk1X95SsJRd-sx2pZNu6e9ygDK-CG70ZMsJG1VfA2eBtss7nTpg2Poqlt7TirUPK9uQyneKBmB4EyyiJMZhJAzVKuQNPIUbiJwx8c23C-FH9iH6nR2vf10xcCv1ubRZqpxp33ucko9JAH2F7Mh9_dUeLsV8qiHHMdVFyAgrDslZ3K-RwUO_Fw_llfJ2Z4NQbwXG78lM5SlIi9W-26QdVEypDizWvuU56-Si9g5UhJ4ge2icWt-H3J9Gi6jf0OtQ7bdANyRIsou9X-pv0h_JjNtRyYlxpJk9ACiSdAwQvMv9_mgF1R5pS4cWb8nhG3BCDoKWJpZxIdwaHcLVvjP3ODJj0NOMvXHzHWvTXm646c5XTJSEMDFZYVz6suWLC-zlWzvPQbprj_rXaEHzPGL664gWnfUXOqTabK2OlQSSmnrzrSoVQIxy67VHcWDLGiggRzUxrh1J1wNiw6IRqFR6So-To74fagJX1jou2XSrdABsxGLOP2nMWEL719p7fpYSVsHwfPcCQUvs0J6UhMpOCqMlZjL8Xs5_p2DMX9fHc0HsRkgmbtYUfJ_R76pqm8ZKO2GMPSH6oJSHIndtkKzIGUwFqGMI-3ghXpmbbHCrcmYQ4h2HfO-2e7_NbhaDo5mj23KY6dG7Gcb5PMVfVxMgAY6raFfkAme6J8SR6_dQTAU9EizXWpslXXM2HeF3oKmrLpK4gWnoNaLmpN7MRPT7XUWP-UDaqxvy17rpHBAqM-AVwkVIJb4p29ycd0yGP34CgfA9z--n-LllmcMQ_MEo-Hu8en8wdKKgwyWJsIjxZAnWvG1YXe669xJ2LTFPPI7VP87T7P7y6KlNe9BarvWhWB76iJbB285jfiNQktDEX4PKsDR2Zvg384rKgEwlzeTgm7GiIkJfDnIZpphzwun-Ef2ejxCPwFGVhtMOOe4Qc-zDnItuielOx554weMBkfaI8N7e4sYJzBpjuIrhJWEJXjDtmwoo2IiRyiIitYWF7_t0pkJ6l2yxmBYb8zya_KxZe0RB2t6--3HTBTEGbCJvlfFDCzEVl88RDQdqzlHb5m8K9ncz0rUsonkRX_ym_yrif4lGVGM7NSGslp3PE4oY2RHFENxaLIifRmOI_GJPNGOIlaaaL4g-NCjWX2iDXKu4HQ3uLtDPS5nIIP-x7Dx6IInGpvFto1a0XyO44jsxhM01ZGR1ruCamyKov5grz0uoa0qcEAmX7L_V02nn3rakHWigyGQPgYmVG9DjbeE6w4mRTKe9uJ9LRpWnd0LP8P_vqPnIfK98zv5S2TswLlSbuy7hVCYKdtbJwvV7uVj2oYqwOQn4WhyP_gdRz4gFJQIr3XM7BdSBmke080u9fwYC1rIBb1_S5R8Pld04X3paL5Wc3A9PSOijtWoMpGFnT1AiXmc4WlCqDDdHB3xMR1f-GY_16ZWwk1xgyhy6ywqzgSpVvbWyw==; accountId=52463; token=hYDNXw+5PWJXA+QLwV3ToIKiqhXcIpGf5GxU1zvIt3E=; confirmProtocolVersion=1";
- private volatile String token = "hYDNXw+5PWJXA+QLwV3ToIKiqhXcIpGf5GxU1zvIt3E=";
- private volatile String csrfToken = "ThECcNhEBvJDLHL4AtCCWzqO";
+
+ @Value("${csvDicForBotChange}")
+ private String csvDicForBotChange;
+
+ private volatile String cookie = "cna=qsWIFY5RHlMCAXeJN3DsHj3O; isg=BISEdD_3hmKO7DG5UmXTs1qBVgu2NamassKvzp4kp88kySaTxK3xlqOrCaG0SuBf; CNZZDATA1261708326=1797143004-1560414985-%7C1578471815; _cnzz_CV1261708326=52463%7C%F0%9F%8C%8E%20skill-audio%2F%E9%9F%B3%E9%A2%91%E5%88%97%E8%A1%A8%E4%BF%A1%E6%81%AF%7Cp; enc=GlWCH0jde0teESrXYo%2BHF75NARTOPv7uKzyscUHesjr8NqyYTkHf%2BD6PG2iP4gPoGIsaO8aq%2BG41Q6kPPhYpvw%3D%3D; UM_distinctid=16ef9e5d343206-06ea6f889716618-76256753-1fa400-16ef9e5d344241; uc1=pas=0&cookie21=UtASsssme%2BBq&tag=8&cookie14=UoTbmEnmIFxXUw%3D%3D&existShop=false&cookie15=Vq8l%2BKCLz3%2F65A%3D%3D&lng=zh_CN&cookie16=VFC%2FuZ9az08KUQ56dCrZDlbNdA%3D%3D; t=925ffaa4a0ded6c2dc567c2eedd425f0; _tb_token_=3a3eeb3e68337; cookie2=145c78f447bf6a4cafb894c15072214f; dnk=tb13503054; tracknick=tb13503054; _l_g_=Ug%3D%3D; unb=1038446007; cookie1=UNMubI1eQ0gVOzLdxFCJj7hzIKFouglcA%2BlE1IYgcZQ%3D; login=true; cookie17=UoH8Vd06g9TEfA%3D%3D; _nk_=tb13503054; sg=47f; csg=f8c7b18a; ctoken=xWUW4TnhPzTyPnCGVcBbhyoc; EGG_SESS=OG910qv3Q3gsrSK4yqRmX3-1-P_ARlUIzlqweqLqnRF5dKELPTe4hiVT80Slz3WPDCsXS99IeB9EJ08mKe1fnB-ky5BqlihGxghSrDaTuitC4LiUArU9fvgELyGofw_TmBaNcyEfrWqC-x_N6rsy8fAw2Pnp69phx2I3tEHsYh8UPT0miVV8Iz9v1Gp1EBu-x7IkCs02BFaNjygAZj4yG5Q0XFHJIVNHemQrHeuxJonSTlJkY2dqCYo_wOLIM5KLVZFHGxoxDIPcuXi37C_MOfK9Sac-zJndlvITiVSRplldFUDbSnyGTHbkxO76r76v-8Pr05wfiN1zzWuCXeZ-ATYX0IDdKpdESz--8JEeGAA-CKkMaOU0K7eXljgXRjsiDcx7bszIDb68PlwlPJV_Ehu3_D2KxVdU_wzX2bzcl-wNpjjmLFUzhoA8YzGs_JsJ2t6rSnRnegg7T0ge7PayU5pvqzfy3hUlevZmqDjZsg2hhW0kAbxkakAlZo7pCAZ-eRFZP_B2VO1qF5N95H2FSGa6CZnH9Rqe1uvQH63cnoppDsHsTis8SMxgvkYBurwjdwjbCqu_DeDR5N_XCsTFRf5Q1Idgcn38mMvfA1PT1Nk2Ye9iWTshl4PD9e3kWc2o3RTKdJNlFkjGb1AUObOobAv1XUXhX0Lx4Ypm6JQIN-2LKqOO4yoqPThj2nfiL6-FVqgNOK0IAHr0EYZS-QXMIBPP5sTUOjOjPPPHc3hJWu0yytS19l7OrV6r5UPVflEJ6_nK_1la9e6AJuDlxI_-mx_qjLXU4cEGYWTF56qcmzXyIRWh0d-rud90Ags2e17C6bzH4ijeY3vQTR9Jezzz_CjiDaT43KLQ_71bHgRYF3DL0xn-HR6QzD0HFtIUHpW_dkeC4l7Lev5zvnXeGKEUE4H-aemCRcmnTW5Rso4-_m2uW6RfUEQ0RlfpFzixKujRu9qZkWDgDTCtEEmSErJ561-mO6PDKLgTifklbRkWLc0oNBuqO0gFdkb58O8lSNum8dwGslDo-eRzKrdB-D8B1-TISMLZm1tL2Aecn9MlXkZUPc62doJjHugczHRbNONrqKkcb0d-HVmOscGgnvl9unbt-fD0wm7225k0ZJ65jESe1LipeVth8W_6hQr2IFktNRqjrN_J8IEgY7NyTauVMDRfhlK1kJ75IPWfqomMQyi30wr2R0_k8rDunfbqf726gZTdKZ109dIsXcxpWsj4v9LGolfXDQQTEFURIXI-lsn1DFkz_LL51K5R9FAIAX00-c5weol75Jgdp1auJfGYuxMlApg8QpbyxL2jReOorI5ioYN76VpQ7RRvHxO1ZMRjNvYUjdHygMcvIqeNArccASaH4Qt5RQ1jrNUFcJ84KPd709GBLt8kxgtEttev9YFHdL3YwLeEJo70Q03BXA7acYQtSQ6iUMoVrR8chjwUJ10zpzcY8QucfrA6p4DdbotQq_n2dFQlWeGGVQUZc11Qr39fekHEc68vjl9TlqSOTqjgASSzg67U6vi3s6LbS1AYMATWzTd0AC281UkjEIkmsLbdinnBtddW5bHZhGeLF01AkvwtUW9oebboJY-4onsMwNivqv6Al7QaWehDeG7kdzWLrU-g9s-ZKa3bwhuMC3VOpgC1y5Vepe9xQilNube431z6JGGW484fbkPcqHG2lrg9uPW-faND328H16PwsihwptEE14JlvxPGLDAZnldYh3RBfhJ2JBR8uhyw7ll7qjAIEud0oOA9EXQg6ppi-KeA0Jvuu5g8a_DbWrg06oV_ZZEl9BUtA_3oCD6rV4Y8PeQqPgiv9cAAUz5c2d40Mmb4GOlJnFzmXxGMa9wZ7X6exvktUmqOrxU7dHEsiFS8XHPIAtBhV7naaoIHLGVxZXHv5Wgy0wPkZMRBJa1l4ipqptNfdz6wGD_M3Nf8feP0UrBOau7VQtqc01R4eXmScY9xoBubyfajp9xkMqJsptAUbE7wZuYNRGq8CwWw8zaDRSpSf3EKEh-THO5tESoXc12mIUn5wBT8kUtE2O828HMeGcJ3PI89QRNcYQeaTmikpzqQf0MiNIaJjsD1PdPC9pVjPQ-9HXWQLylSmgAEHvcqe-s1pCk-g03koACUqKUBnCxIjBaI_By_kMkg1-kuM7TVHTLXzaWGR0cWC6RifnJPC4TBDc7KX-QUsg9GzvDibKY-ZiKULXYQCZTr_p0nKpDqSDZTuEzD14S9m9zMxJXBYI4De-FwMlWjePQkyOME4omwfDrovY33_Hbch8-aOTleVR5BfsOyVhEUdN3Dqs5ARG6AQznfH-pmHLvERYC3-Q==; accountType=TB; accountId=52463; token=+yKlBN44OA/SyckKeOJUlJVzFRetm5fqY9FVaEzSRPE=; confirmProtocolVersion=1";
+ private volatile String token = "+yKlBN44OA/SyckKeOJUlJVzFRetm5fqY9FVaEzSRPE=";
+ private volatile String csrfToken = "xWUW4TnhPzTyPnCGVcBbhyoc";
+
public void updateCookie(String cookie) {
this.cookie = cookie;
// token=ol977BaL6nE1H5lss8t3Nx7G7LOB9n1S+S8mAlxsZnA=;
@@ -133,8 +139,28 @@ public class SpiritAudioUpload {
return null;
}
+ public void deleteAudio(String filePath, Long skillId) {
+ try (CSVParser csvRecords = CSVFormat.EXCEL.parse(new BufferedReader(
+ new InputStreamReader(new FileInputStream(new File(filePath)), StandardCharsets.UTF_8)))){
+ boolean first = true;
+ String id;
+ List idList = new ArrayList<>();
+ for (CSVRecord line: csvRecords) {
+ if (first) {
+ first = false;
+ continue;
+ }
+ id = line.get(3);
+ idList.add(id);
+ }
+ deleteTheAudio(idList, skillId);
+ } catch (Exception e) {
+ log.error("deleteAudio:"+e);
+ }
+ }
+
private void deleteTheAudio(List ids, Long skillId) {
- log.error("要删除的id列表:"+ids);
+ log.error("要删除的id列表:"+ids.size());
String url = "https://open.aligenie.com/api/custom/audios/delete";
Map headers = new HashMap<>();
headers.put("Accept", "application/json");
@@ -415,20 +441,22 @@ public class SpiritAudioUpload {
preCsvPath = csvDic+preBotAccount+"_0.csv";
}
String csvPath;
+ String errorCsvPath;
if (preBotAccount.equals(botAccount)) {
if (record) {
csvPath = csvDic+botAccount+"_1_r.csv";
} else {
csvPath = csvDic+botAccount+"_0_r.csv";
}
+ errorCsvPath = csvDic+botAccount+"_error.csv";
} else {
if (record) {
- csvPath = csvDic+botAccount+"_1.csv";
+ csvPath = csvDicForBotChange+botAccount+"_1.csv";
} else {
- csvPath = csvDic+botAccount+"_0.csv";
+ csvPath = csvDicForBotChange+botAccount+"_0.csv";
}
+ errorCsvPath = csvDicForBotChange+botAccount+"_error.csv";
}
- String errorCsvPath = csvDic+botAccount+"_error.csv";
if (Boolean.TRUE.equals(record)) {
// id -> DicUploadInfo
String mp3DataPath = "/root/TTS-service/audio/"+botAccount+"/record/";
@@ -501,6 +529,8 @@ public class SpiritAudioUpload {
}
}
buildDicCsv(csvPath, oldDataList);
+ log.error("dataNew:"+dataNew.size());
+ log.error("delIds:"+delIds.size());
if (dataNew.size() != 0) uploadNewData(dataNew, skillId, true, botAccount, csvPath, errorCsvPath, botName);
if (delIds.size() != 0) deleteTheAudio(delIds, skillId);
} else {
diff --git a/spirit/src/main/resources/application.yml b/spirit/src/main/resources/application.yml
index 24cb3a6..ba51ebb 100755
--- a/spirit/src/main/resources/application.yml
+++ b/spirit/src/main/resources/application.yml
@@ -1,11 +1,12 @@
server:
- port: 8188
+ port: 8189
logging:
- path: /home/dc2-user/projects/audiobox/spirit/logs
+ path: /home/dc2-user/spirit/logs
level:
root: error
-csvDic: /home/dc2-user/audioBox/spirit/csv/
+csvDic: /home/dc2-user/spirit/uploadCsv/
+csvDicForBotChange: /home/dc2-user/spirit/fresh/
spring:
diff --git a/third_party_load/pom.xml b/third_party_load/pom.xml
index 2f2625b..f9606fb 100755
--- a/third_party_load/pom.xml
+++ b/third_party_load/pom.xml
@@ -84,6 +84,13 @@
${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar
+ com.tmall.spirit
+ aliGenie
+ 1.0.0
+ system
+ ${project.basedir}/src/main/resources/static/aliGenie-intent-sematic.jar
+
+
ws.schild
jave-core
2.7.1
diff --git a/third_party_load/src/main/resources/static/aliGenie-intent-sematic.jar b/third_party_load/src/main/resources/static/aliGenie-intent-sematic.jar
new file mode 100644
index 0000000..27df896
Binary files /dev/null and b/third_party_load/src/main/resources/static/aliGenie-intent-sematic.jar differ
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
index 5e03114..366a114 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
@@ -536,13 +536,18 @@ public class TTSUtils {
// String command = "sox "+ StringUtils.join(filePathList, " ");
- List str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
- StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex ");
- for (int i = 0; i < filePathList.size(); i++) {
- builder.append("[").append(i).append(":a:0]");
+ if (filePathList.size() == 1) {
+ String[] arr = filePathList.toArray(new String[]{});
+ Files.copy(Paths.get(arr[0]), Paths.get(targetFilepath));
+ } else {
+ List str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
+ StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex ");
+ for (int i = 0; i < filePathList.size(); i++) {
+ builder.append("[").append(i).append(":a:0]");
+ }
+ builder.append("concat=n=").append(filePathList.size()).append(":v=0:a=1[a] -map [a] ").append(targetFilepath);
+ CallPython.ffmpegExecute(builder.toString());
}
- builder.append("concat=n=").append(filePathList.size()).append(":v=0:a=1[a] -map [a] ").append(targetFilepath);
- CallPython.ffmpegExecute(builder.toString());
// filePathList.add(targetFilepath);
// CallPython.execute("sox "+ StringUtils.join(filePathList, " "));
@@ -656,6 +661,7 @@ public class TTSUtils {
}
public static void main(String[] args) throws IOException, UnsupportedAudioFileException {
- UploadCallbackUnzip("/home/yf01/下载/tts/testzip","/home/yf01/下载/testUnzip.zip");
+// UploadCallbackUnzip("/home/yf01/下载/tts/testzip","/home/yf01/下载/testUnzip.zip");
+ Files.copy(Paths.get("/home/yf01/下载/d46f2708a6a79f5bcc4623b1030b8aca.mp3"), Paths.get("/home/yf01/下载/d46Test.mp3"));
}
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java
index 40c020d..6366279 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java
@@ -128,47 +128,71 @@ public class TTServiceUtil {
}
public static void buildMp3ResponseForAudio(HttpServletResponse response, String fileName, Boolean xiaoai, String range) {
- response.setStatus(200);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
OutputStream out = new BufferedOutputStream(response.getOutputStream())){
response.reset();
+ if (xiaoai) response.setStatus(206);
+ else response.setStatus(200);
response.setContentType("audio/mp3");
-// response.setHeader("Content-Type", "audio/mp3");
- response.setHeader("Content-Type", "application/octet-stream");
int length = inputStream.available();
-// if (!Boolean.TRUE.equals(xiaoai)) {
-// response.setHeader("Content-Length", String.valueOf(length));
-// }
response.setHeader("Content-Length", String.valueOf(length));
- range = range.substring(range.indexOf("=")+1, range.indexOf("-"));
- String contentRange = "bytes "+range+"-"+length+"/"+length;
- log.info("Content-Range:"+contentRange);
- response.setHeader("Content-Range", contentRange);
- response.setHeader("Accept-Ranges", "bytes");
- response.setHeader("icy-metaint", "8192");
+ if (xiaoai) {
+ response.setHeader("Content-Type", "application/octet-stream");
+ range = range.substring(range.indexOf("=")+1, range.indexOf("-"));
+ String contentRange = "bytes "+range+"-"+length+"/"+length;
+ log.info("Content-Range:"+contentRange);
+ response.setHeader("Content-Range", contentRange);
+ response.setHeader("Accept-Ranges", "bytes");
+// response.setHeader("icy-metaint", "8192");
+ int begin = Integer.valueOf(range);
+ byte[] buffer = new byte[1024];
+ int ln;
+ while ((ln = inputStream.read(buffer)) != -1) {
+ if (begin > 0) {
+ begin -= ln;
+ if (begin < 0) {
+ out.write(buffer, ln+begin, -begin);
+ }
+ } else {
+ out.write(buffer, 0, ln);
+ }
+ }
+ out.flush();
+ } else {
+ response.setHeader("Content-Type", "audio/mp3");
+ byte[] buffer = new byte[1024];
+ int ln;
+ while ((ln = inputStream.read(buffer)) != -1) {
+ out.write(buffer, 0, ln);
+ }
+ out.flush();
+ }
// response.setHeader("Cache-Control", "max-age=43200, public");
- int begin = Integer.valueOf(range);
+ } catch (ClientAbortException e) {
+
+ } catch (IOException e) {
+ log.error("buildMp3Response:写入音频流到HttpServletResponse失败:{}", e.toString());
+ }
+ }
+
+ public static void buildMp3ResponseForAudioNoRange(HttpServletResponse response, String fileName, Boolean xiaoai) {
+ try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
+ OutputStream out = new BufferedOutputStream(response.getOutputStream())){
+ response.reset();
+// if (xiaoai) response.setStatus(206);
+// else response.setStatus(200);
+ response.setStatus(200);
+ response.setContentType("audio/mp3");
+ response.setHeader("Content-Type", "audio/mp3");
+ if (!xiaoai) response.setHeader("Content-Length", String.valueOf(inputStream.available()));
byte[] buffer = new byte[1024];
int ln;
while ((ln = inputStream.read(buffer)) != -1) {
- if (begin > 0) {
- begin -= ln;
- if (begin < 0) {
- out.write(buffer, ln+begin, -begin);
- }
- } else {
- out.write(buffer, 0, ln);
- }
+ out.write(buffer, 0, ln);
}
out.flush();
-// byte[] buffer = new byte[1024];
-// int ln;
-// while ((ln = inputStream.read(buffer)) != -1) {
-// out.write(buffer, 0, ln);
-// }
-// out.flush();
} catch (ClientAbortException e) {
} catch (IOException e) {
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java
index d07392b..e156ff8 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java
@@ -236,7 +236,8 @@ public class TTSController {
@GetMapping("/api/audio/get")
public void apiAudioGet(@RequestParam(required = false) String type, @RequestParam String path,
- HttpServletResponse response, HttpServletRequest request) {
- ttService.apiAudioGet(type, path, response, request);
+ HttpServletResponse response) {
+// ttService.apiAudioGet(type, path, response, request);
+ ttService.apiAudioGetNoRange(type, path, response);
}
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
index 6a289d8..d8cd15d 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
@@ -2084,11 +2084,11 @@ public class TTService {
if (xiaoAi) {
OkHttp3Utils.backPostAsync(audioUrl+type);
}
- Enumeration enumeration = request.getHeaderNames();
- while (enumeration.hasMoreElements()) {
- String name = (String) enumeration.nextElement();
- log.warn(name+":"+request.getHeader(name));
- }
+// Enumeration enumeration = request.getHeaderNames();
+// while (enumeration.hasMoreElements()) {
+// String name = (String) enumeration.nextElement();
+// log.warn(name+":"+request.getHeader(name));
+// }
String range = request.getHeader("range");
if (Files.exists((pt = Paths.get(path)))) {
while (XIAOAI_MP3_MARK.contains(path)) {
@@ -2114,6 +2114,36 @@ public class TTService {
}
}
+ public void apiAudioGetNoRange(String type, String path, HttpServletResponse response) {
+ Path pt;
+ boolean xiaoAi = StringUtils.isNotBlank(type);
+ if (xiaoAi) {
+ OkHttp3Utils.backPostAsync(audioUrl+type);
+ }
+ if (Files.exists((pt = Paths.get(path)))) {
+ while (XIAOAI_MP3_MARK.contains(path)) {
+ try {
+ Thread.sleep(500);
+ } catch (Exception e) {}
+ }
+ TTServiceUtil.buildMp3ResponseForAudioNoRange(response, path, xiaoAi);
+ } else {
+ try {
+ Thread.sleep(1500);
+ } catch (Exception e) {}
+ if (Files.exists(pt)) {
+ while (XIAOAI_MP3_MARK.contains(path)) {
+ try {
+ Thread.sleep(300);
+ } catch (Exception e) {}
+ }
+ TTServiceUtil.buildMp3ResponseForAudioNoRange(response, path, xiaoAi);
+ } else {
+ log.error("等待2s后仍未获取到音箱的音频结果");
+ }
+ }
+ }
+
public String apiAudio(ApiAudioData apiAudioData) {
List dialogs = apiAudioData.getDialogs();
// botname不能为空
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java
index ebd6c56..148127d 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java
@@ -290,7 +290,7 @@ public class Test {
Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
String[] notVariableTextArray = pattern.split("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71");
- System.out.println(notVariableTextArray.length);
- System.out.println(Arrays.toString(notVariableTextArray));
+
+ System.out.println(TTSUtils.buildMP3Filename("为您推荐以上作品:《妖刀异闻录》、《小太阳》、《遇见伽利略》,你可以说:打开某作品"));
}
}
diff --git a/xiaoduhome/pom.xml b/xiaoduhome/pom.xml
index 3494109..c1146b5 100755
--- a/xiaoduhome/pom.xml
+++ b/xiaoduhome/pom.xml
@@ -132,6 +132,19 @@
org.apache.httpcomponents
httpmime
+
+
+
+
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ 3.9
+
+
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Constants.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Constants.java
index 03637fe..451e7fa 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Constants.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Constants.java
@@ -7,8 +7,10 @@ package ai.qiwu.com.xiaoduhome.common;
public interface Constants {
String QI_WU_INTERFACE = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
+ String QI_WU_INTERFACE_di2 = "http://didi-gz2.jiaoyou365.com:8070/api/chat2";
String INTERFACE_DI = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
String TTS_DIDI3_GET = "http://didi-gz3.jiaoyou365.com:9663/api/audio/get?path=";
+ String TTS_DIDI2_GET = "http://didi-gz2.jiaoyou365.com:9663/api/audio/get?path=";
String TTS_DIDI3_GET_XIAOAI = "http://didi-gz3.jiaoyou365.com:9663/api/audio/get?type=";
String TTS_DIDI4_GET_XIAOAI = "http://didi-gz4.jiaoyou365.com:9663/api/audio/get?type=";
String TTS_DIDI4_GET_XIAOAI_STATIC = "http://didi-gz4.jiaoyou365.com:9663/static/";
@@ -101,11 +103,18 @@ public interface Constants {
}
interface WelcomeWord {
- String WELCOME = "欢迎来到交游天下,你可以说推荐作品给我";
+ String WELCOME = "欢迎来到交游天下。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";
+ String WELCOME_FORMAT = "欢迎来到交游天下。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的%s,您可以说打开%s。或者说,推荐其它作品。";
String SKILL = "交游天下";
- String WELCOME_SMART = "小朋友你好,欢迎来到智能故事,你可以对我说有什么好玩的吗";
+ String SKILL_DEFAULT = "我们的技能";
+ // 欢迎来到晓悟智能故事。与可爱的角色们自由对话,畅游不同的故事世界。我们新上线了遇见伽利略,你可以说打开遇见伽利略。或者说,推荐其它作品。
+ String WELCOME_SMART = "欢迎来到晓悟智能故事。我们新上线了遇见伽利略,你可以说打开遇见伽利略。或者说,推荐其它作品。";
+ String WELCOME_SMART_FORMAT = "欢迎来到晓悟智能故事。与可爱的角色们自由对话,畅游不同的故事世界。我们新上线了%s,你可以说打开%s。或者说,推荐其它作品。";
+ String WELCOME_SMART_FORMAT_AI = "欢迎来到晓悟智能故事。推荐我们新上线的%s,你可以说打开%s。或者说,推荐其它作品。";
String SKILL_SMART = "智能故事";
- String WELCOME_NOVEL = "欢迎来到智能小说,你可以说推荐作品给我";
+ // 与剧情人物自由对话,带您体验不同的人生和情怀。
+ String WELCOME_NOVEL = "欢迎来到晓悟智能小说。向您推荐新上线的妖刀异闻录,您可以说打开妖刀异闻录。或者说,推荐其它作品。";
+ String WELCOME_NOVEL_FORMAT = "欢迎来到晓悟智能小说。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的%s,您可以说打开%s。或者说,推荐其它作品。";
String SKILL_NOVEL = "智能小说";
String WELCOME_LITERATURE = "欢迎来到互动文艺,你可以说推荐作品给我";
String SKILL_LITERATURE = "互动文艺";
@@ -120,9 +129,15 @@ public interface Constants {
interface EndMsg {
String BYE_BYE = "我们的作品库在不断的扩充,欢迎下次再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
+ String END_BYE_NOVEL = "后续有更多作品上线,欢迎常来访问智能小说。"; // smart novel
+ String END_BYE_STORY = "智能故事后续会有更多作品上线,欢迎常来"; // smart story
+ String END_BYE_JIAOYOU = "交游天下后续会有更多作品上线,欢迎常来";
+ String END_BYE_DEFAULT = "后续会有更多作品上线,欢迎常来我们的技能";
String END_BYE_Adult = "再见啦,记得下次再来玩哦";
- String CAN_NOT_UNDERSTAND = "用户无输入或多次输入无法理解";
+ String CAN_NOT_UNDERSTAND = "用户无输入或多次输入无法理解访问";
String USER_SAY_CANCEL = "用户直接说退出";
+
+ String BEFORE_LOAD_OUT = "如果您想退出我们的技能请对我说退出";
}
interface ErrorMsg {
@@ -160,7 +175,7 @@ public interface Constants {
String FLOWER_INTERFACE = "http://aws-nx2.chewrobot.com:18082/api/flower/count";
String USER_CLOOEC_LIST = "http://aliyun-hz1.chewrobot.com:18082/api/favorite";
String USER_ID_BY_TOKEN = "https://account-center-test.chewrobot.com/api/sdk/user/info";
- String ASIDE_IMG_URL = "http://didi-gz5.jiaoyou365.com:18082/api/works";
+ String ASIDE_IMG_URL = "http://didi-gz3.jiaoyou365.com:18082/api/works";
}
interface BAI_DU {
@@ -168,5 +183,4 @@ public interface Constants {
String BAIDU_TOKEN = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&client_id=dSG525LMr887uLlfAyK1C1ag&client_secret=1azuXoKHMSWT5MVNNkZ4C5mED23qySZh&redirect_uri=https%3A%2F%2Fwww.miaoshop.top%2Fxiaodu%2Fbaidu%2Fcode&code=";
String BAIDU_AUTHORIZE = "https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=dSG525LMr887uLlfAyK1C1ag&redirect_uri=https%3A%2F%2Fwww.miaoshop.top%2Fxiaodu%2Fbaidu%2Fcode&confirm_login=1&state=mqw";
}
-
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/OkHttp3Utils.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/OkHttp3Utils.java
index 01d3c57..fd34d50 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/OkHttp3Utils.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/OkHttp3Utils.java
@@ -160,6 +160,45 @@ public class OkHttp3Utils {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody body = response.body()){
+// body.string();
+ log.info("退出成功:{}", body.string());
+ } catch (SocketTimeoutException e) {
+ log.error("捕获到SocketTimeoutException:{}", e.toString());
+ client.dispatcher().cancelAll();
+ client.connectionPool().evictAll();
+ } catch (Exception e) {
+ log.error(ExceptionUtils.getStackTrace(e));
+ }
+ }
+ });
+ }
+
+ public static void xiaoaiBackPostAsync(String url, String requestJsonStr, Integer type) {
+ String header = "xiaoai-jiaoyou-audio-test";
+ if (type != null) {
+ switch (type) {
+ case 1 :
+ case 3 : header = "xiaoai-jiaoyou-audio-child-test";break;
+ case 2 :
+ case 4 : header = "xiaoai-jiaoyou-audio-adult-test";break;
+ default: header = "xiaoai-jiaoyou-audio-test";
+ }
+ }
+ Request request = new Request.Builder()
+ .url(url)
+ .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr))
+ .header("App-Channel-Id", header)
+ .build();
+ client.newCall(request).enqueue(new Callback() {
+ @Override
+ public void onFailure(@NotNull Call call, @NotNull IOException e) {
+ log.info("退出失败");
+ }
+
+ @Override
+ public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
+ try (ResponseBody body = response.body()){
+// body.string();
log.info("退出成功:{}", body.string());
} catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Utils.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Utils.java
index 3d42403..6912088 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Utils.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Utils.java
@@ -1,6 +1,8 @@
package ai.qiwu.com.xiaoduhome.common;
+import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@@ -18,6 +20,7 @@ import java.util.Objects;
* @author 苗权威
* @dateTime 19-6-29 下午5:11
*/
+@Slf4j
public class Utils {
/**
@@ -129,6 +132,126 @@ public class Utils {
return new Timestamp(new Date(curTimeMills).getTime());
}
+ /**
+ * 获取真实ip
+ *
+ * @param acceptInnerIp 是否可以返回内网ip
+ * @return 真实ip
+ */
+ public static String getRemoteIpByServletRequest(HttpServletRequest request) {
+ String ip = request.getHeader("x-forwarded-for");
+ if (StringUtils.isNotBlank(ip)) {
+ // 多次反向代理后会有多个ip值,第一个ip才是真实ip
+// log.info("x:"+ip);
+ if (ip.contains(",")) {
+ ip = ip.split(",")[0];
+ }
+ }
+ if (isIpValid(ip)) {
+ return ip;
+ }
+ ip = request.getHeader("Proxy-Client-IP");
+ if (isIpValid(ip)) {
+// log.info("pro:"+ip);
+ return ip;
+ }
+ ip = request.getHeader("WL-Proxy-Client-IP");
+ if (isIpValid(ip)) {
+// log.info("wl:"+ip);
+ return ip;
+ }
+ ip = request.getHeader("HTTP_CLIENT_IP");
+ if (isIpValid(ip)) {
+ return ip;
+ }
+ ip = request.getHeader("HTTP_X_FORWARDED_FOR");
+ if (isIpValid(ip)) {
+// log.info("HTTP:"+ip);
+ return ip;
+ }
+ ip = request.getHeader("X-Real-IP");
+ if (isIpValid(ip)) {
+// log.info("x-R:"+ip);
+ return ip;
+ }
+ ip = request.getRemoteAddr();
+// log.info("remote:"+ip);
+ return ip;
+ }
+
+ /**
+ * 判断是否有效
+ * @param ip ip
+ * @param acceptInnerIp 是否接受内网ip
+ * @return
+ */
+ private static boolean isIpValid(String ip, boolean acceptInnerIp) {
+ return acceptInnerIp ? isIpValid(ip) : isIpValidAndNotPrivate(ip);
+ }
+
+ /**
+ * 仅仅判断ip是否有效
+ * @param ip
+ * @return
+ */
+ private static boolean isIpValid(String ip) {
+ if (StringUtils.isBlank(ip)) {
+ return false;
+ }
+ String[] split = ip.split("\\.");
+ if (split.length != 4) {
+ return false;
+ }
+ try {
+ long first = Long.valueOf(split[0]);
+ long second = Long.valueOf(split[1]);
+ long third = Long.valueOf(split[2]);
+ long fourth = Long.valueOf(split[3]);
+ return first < 256 && first > 0
+ && second < 256 && second >= 0
+ && third < 256 && third >= 0
+ && fourth < 256 && fourth >= 0;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+
+ /**
+ * 判断ip是否有效,并且不是内网ip
+ * @param ip
+ * @return
+ */
+ private static boolean isIpValidAndNotPrivate(String ip) {
+ if (StringUtils.isBlank(ip)) {
+ return false;
+ }
+ String[] split = ip.split("\\.");
+ try {
+ long first = Long.valueOf(split[0]);
+ long second = Long.valueOf(split[1]);
+ long third = Long.valueOf(split[2]);
+ long fourth = Long.valueOf(split[3]);
+ if (first < 256 && first > 0
+ && second < 256 && second >= 0
+ && third < 256 && third >= 0
+ && fourth < 256 && fourth >= 0) {
+ if (first == 10) {
+ return false;
+ }
+ if (first == 172 && (second >= 16 && second <= 31)) {
+ return false;
+ }
+ if (first == 192 && second == 168) {
+ return false;
+ }
+ return true;
+ }
+ return false;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+
public static void main(String[] args) throws ParseException {
String s = "[{\"type\": \"SendEvent\",\"componentId\":\"%s\"}]";
//System.out.println(String.format(s, "gsagh"));
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/AudioGetController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/AudioGetController.java
index 32cce15..9c10fe4 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/AudioGetController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/AudioGetController.java
@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.controller;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
+import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
@@ -41,6 +42,11 @@ public class AudioGetController {
// }
// }
+// @GetMapping("/audio/name/change")
+// public void changeName(Integer ) {
+//
+// }
+
private void buildMp3Response(HttpServletResponse response, String fileName) {
response.setStatus(200);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/SpiritController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/SpiritController.java
index 61f7dc5..3995243 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/SpiritController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/SpiritController.java
@@ -34,7 +34,7 @@ public class SpiritController {
*/
@PostMapping(value = "/") //交游天下
public ResultModel getResponse(@RequestBody String taskQuery) {
- log.info("天猫请求信息:{}",taskQuery);
+// log.info("天猫请求信息:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
@@ -42,7 +42,7 @@ public class SpiritController {
TaskResult taskResult = spiritService.getResponse(query, 1);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
- log.info("天猫响应信息:"+ JSON.toJSONString(resultModel));
+// log.info("天猫响应信息:"+ JSON.toJSONString(resultModel));
return resultModel;
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/WebSocketLogController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/WebSocketLogController.java
index 63164b7..6721c12 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/WebSocketLogController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/WebSocketLogController.java
@@ -1,16 +1,34 @@
package ai.qiwu.com.xiaoduhome.controller;
+import ai.qiwu.com.xiaoduhome.service.chatsLog.ChatLogs;
+import ai.qiwu.com.xiaoduhome.service.chatsLog.LoginData;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+
/**
* @author 苗权威
* @dateTime 19-11-18 下午6:37
*/
-@Controller
+//@Controller
+@Slf4j
public class WebSocketLogController {
+ private final ChatLogs chatLogs;
+ private static ConcurrentHashMap loadState = new ConcurrentHashMap<>();
+
+ @Autowired
+ public WebSocketLogController(ChatLogs chatLogs) {
+ this.chatLogs = chatLogs;
+ }
+
@GetMapping("/audio/index")
public String logIndexPage(ModelMap modelMap) {
return "index.html";
@@ -36,6 +54,85 @@ public class WebSocketLogController {
return "Log4.html";
}
+// @GetMapping("/chat/log")
+// public @ResponseBody String logTemp(String token, @RequestParam(required = false) Integer row,
+// @RequestParam(required = false) String count,
+// @RequestParam(required = false) String type) {
+// if (StringUtils.isBlank(token)) return "超时重新登录";
+// LoginData data;
+// if ((data = loadState.get(token)) == null) return "超时重新登录";
+// long current = System.currentTimeMillis();
+// if (current-data.getTime() > 7200000) {
+// loadState.remove(token);
+// return "超时重新登录";
+// }
+// if (row == null || row == 0) row = 1000;
+// String s = chatLogs.look(row, count, type);
+// if (s == null) s = "出错,请刷新重试";
+// return s;
+// }
+
+ @GetMapping("/chat/log")
+ public @ResponseBody String logTemp(String token, @RequestParam(required = false) Integer row,
+ @RequestParam(required = false) String count,
+ @RequestParam(required = false) String type) {
+ if (StringUtils.isBlank(token)) return "超时重新登录";
+ LoginData data;
+ if ((data = loadState.get(token)) == null) return "超时重新登录";
+ long current = System.currentTimeMillis();
+ if (current-data.getTime() > 7200000) {
+ loadState.remove(token);
+ return "超时重新登录";
+ }
+ if (row == null || row == 0) row = 1000;
+ String s = chatLogs.look(row, count, type);
+ if (s == null) s = "出错,请刷新重试";
+ return s;
+ }
+
+ @GetMapping("/chat/choose")
+ public String logTemp(String token, ModelMap modelMap) {
+ if (StringUtils.isBlank(token)) return "LoadFailed.html";
+ LoginData data;
+ if ((data = loadState.get(token)) == null) return "LoadFailed.html";
+ long current = System.currentTimeMillis();
+ if (current-data.getTime() > 7200000) {
+ loadState.remove(token);
+ return "LoadFailed.html";
+ }
+ modelMap.put("token", token);
+ return "ChatLogChoose.html";
+ }
+
+ @GetMapping("/chat/login/check")
+ public @ResponseBody String lookLogSignIn(String userName, String passwd) {
+ log.info(userName+":"+passwd);
+ long current = System.currentTimeMillis();
+ loadState.entrySet().removeIf(entry -> current-entry.getValue().getTime() > 7200000);
+ if ("qiwu".equals(userName) && "qiwuai2020".equals(passwd)) {
+ LoginData data;
+ for (Map.Entry entry: loadState.entrySet()) {
+ if (userName.equals(entry.getValue().getUsername())) {
+ entry.getValue().setTime(current);
+ return entry.getKey();
+ }
+ }
+ String token = RandomStringUtils.randomAlphabetic(8);
+ data = new LoginData();
+ data.setUsername(userName);
+ data.setToken(token);
+ data.setTime(current);
+ loadState.put(token, data);
+ return token;
+ }
+ return "0";
+ }
+
+ @GetMapping("/chat/login")
+ public String login(ModelMap modelMap) {
+ return "LookLogLogin.html";
+ }
+
// eae846c7d1ca51474ebc7230ace47bf2.txt
@GetMapping("/aligenie/{name}")
public String spirit(@PathVariable String name, ModelMap modelMap) {
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java
index b6fb4e9..08a43e0 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java
@@ -1,15 +1,26 @@
package ai.qiwu.com.xiaoduhome.controller;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.Utils;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.Response;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
+import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiTestService;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.InputStream;
+import java.lang.reflect.Type;
+import java.util.Enumeration;
+
+import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
/**
* @author 苗权威
@@ -18,60 +29,106 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/xiaoai")
@Slf4j
+@RequiredArgsConstructor(onConstructor_={@Autowired})
public class XiaoAiController {
private final XiaoAiService xiaoAiService;
-
- @Autowired
- public XiaoAiController(XiaoAiService xiaoAiService) {
- this.xiaoAiService = xiaoAiService;
- }
+ private final XiaoAiTestService xiaoAiTestService;
/**
* Controller控制器
* @param request
* @return
*/
- @RequestMapping("/")
- public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) {
+ @PostMapping("/")
+ public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request,HttpServletRequest servletRequest) { // 交游天下
log.info("请求:"+request);
- XiaoAiResponse response = xiaoAiService.getResponse(request);
- log.info("响应:"+response);
- return response;
+ // log.info("响应:"+response);
+ try {
+ if (!Utils.encry(5, servletRequest)) {
+ log.error("验证没通过:5");
+ return null;
+ }
+ request.setType(5);
+ return xiaoAiService.getResponse(request);
+ } catch (Exception e) {
+ log.error("controller xiaoai:"+e);
+ }
+ return buildTextResponse(SORRY_REPEAT);
// return xiaoAiService.getResponse(request);
}
- @RequestMapping("/child")
- public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request) {
+ @PostMapping("/child")
+ public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request,HttpServletRequest servletRequest) { // 智能故事
//log.info("请求:"+request);
- request.setType(1);
- XiaoAiResponse response = xiaoAiService.getResponse(request);
-// log.info("响应:"+response);
- return response;
+ try {
+ if (!Utils.encry(1, servletRequest)) {
+ log.error("验证没通过:1");
+ return null;
+ }
+ request.setType(1);
+ // log.info("响应:"+response);
+ return xiaoAiService.getResponse(request);
+ } catch (Exception e) {
+ log.error("controller xiaoaiChild:"+e);
+ }
+ return buildTextResponse(SORRY_REPEAT);
// return xiaoAiService.getResponse(request);
}
- @RequestMapping("/story") //互动故事
- public XiaoAiResponse xiaoaiChildStory(@RequestBody XiaoAiRequest request) {
- //log.info("请求:"+request);
- request.setType(3);
- XiaoAiResponse response = xiaoAiService.getResponse(request);
+ @PostMapping("/story") //互动故事
+ // @RequestBody XiaoAiRequest request,
+ public XiaoAiResponse xiaoaiChildStory(HttpServletRequest servletRequest) {
+// long start = System.currentTimeMillis();
+// if (!Utils.encry(3, servletRequest)) return null;
+// log.info("encry:"+(System.currentTimeMillis()-start));
+
+ try (InputStream stream = servletRequest.getInputStream()){
+ StringBuilder sb = new StringBuilder();
+ byte[] b = new byte[4096];
+ for (int n; (n = stream.read(b)) != -1;)
+ {
+ sb.append(new String(b, 0, n));
+ }
+ String str = sb.toString();
+ log.info("请求:"+str);
+ XiaoAiRequest request = JSON.parseObject(str, XiaoAiRequest.class);
+ request.setType(5);
+ XiaoAiResponse response = xiaoAiTestService.getResponse(request);
+ log.info("响应:"+response);
+ return response;
+ } catch (Exception e) {
+
+ }
+ return null;
+
+// log.info("请求:"+request);
+// request.setType(5);
+// XiaoAiResponse response = xiaoAiService.getResponse(request);
// log.info("响应:"+response);
- return response;
+// return response;
// return xiaoAiService.getResponse(request);
}
- @RequestMapping("/adult")
- public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request) {
+ @PostMapping("/adult")
+ public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request, HttpServletRequest servletRequest) { // 智能小说
//log.info("请求:"+request);
- request.setType(2);
- XiaoAiResponse response = xiaoAiService.getResponse(request);
-// log.info("响应:"+response);
- return response;
+ try {
+ if (!Utils.encry(2, servletRequest)) {
+ log.error("验证没通过:2");
+ return null;
+ }
+ request.setType(2);
+ // log.info("响应:"+response);
+ return xiaoAiService.getResponse(request);
+ } catch (Exception e) {
+ log.error("controller xiaoaiAdult:"+e);
+ }
+ return buildTextResponse(SORRY_REPEAT);
// return xiaoAiService.getResponse(request);
}
- @RequestMapping("/literature") // 互动文艺
+// @PostMapping("/literature") // 互动文艺
public XiaoAiResponse xiaoaiAdultLiterature(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request);
request.setType(4);
@@ -85,8 +142,33 @@ public class XiaoAiController {
public void xiaoaiPlayed(String userId) {
if (StringUtils.isNotBlank(userId)) {
// log.info("小爱确认音频播放:"+userId);
- xiaoAiService.changeAudioPlayMark(userId);
+// xiaoAiService.changeAudioPlayMark(userId);
}
else log.error("/xiaoai/audio/play userId is null");
}
+
+ private XiaoAiResponse buildResponse() {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(false);
+
+ Response responseInfo = new Response();
+ // 这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,
+ // 若不主动打开则小爱在一次会话后退出技能。
+ responseInfo.setOpen_mic(true);
+ response.setResponse(responseInfo);
+ return response;
+ }
+
+ private XiaoAiResponse buildTextResponse(String text) {
+ XiaoAiResponse response = buildResponse();
+ Response responseInfo = response.getResponse();
+
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+
+ return response;
+ }
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
index d9310a1..4a622e4 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
@@ -11,15 +11,22 @@ import com.alibaba.da.coin.ide.spi.standard.ResultModel;
import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
+import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.servlet.tags.HtmlEscapingAwareTag;
+import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedReader;
import java.io.File;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.Enumeration;
import java.util.Map;
import java.util.UUID;
@@ -32,36 +39,81 @@ import java.util.UUID;
@Slf4j
public class XiaoDuHomeController {
- @RequestMapping("/chat") //互动天地
+ private int test = 0;
+
+ @RequestMapping(value = "/chat", method = RequestMethod.HEAD)
+ public void chatHead(HttpServletResponse response) {
+// if (test++ < 5) {
+// try {
+// Enumeration enumeration = request.getHeaderNames();
+// while (enumeration.hasMoreElements()) {
+// String name = (String) enumeration.nextElement();
+// log.info(name+":"+request.getHeader(name));
+// }
+// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
+// StringBuilder builder = new StringBuilder();
+// String temp;
+// while((temp = bufferedReader.readLine()) != null) {
+// builder.append(temp);
+// }
+// log.info("message:"+builder.toString());
+// } catch (Exception e) {
+// log.warn("探活 failed:"+e);
+// }
+// }
+ response.setStatus(200);
+ }
+
+ @PostMapping("/chat") //互动天地
public String chat() {
+ HttpServletRequest request = null;
try {
//log.info("--------------分界线-------------------");
- DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 5);
+ DplBotService service = new DplBotService((request=Utils.getHttpServletRequest()), 5);
// log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
- log.info(service.getStrRequest());
+// log.info(service.getStrRequest());
//service.disableVerify();
service.enableVerify();
- String str = service.run();
- log.info("响应信息:{}", str);
- return str;
+ // log.info("响应信息:{}", str);
+ return service.run();
+ } catch (MismatchedInputException ex) {
+ log.info("交游探活:"+ex);
+ if (test++ < 5) {
+ try {
+ Enumeration enumeration = request.getHeaderNames();
+ while (enumeration.hasMoreElements()) {
+ String name = (String) enumeration.nextElement();
+ log.info(name+":"+request.getHeader(name));
+ }
+ BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
+ StringBuilder builder = new StringBuilder();
+ String temp;
+ while((temp = bufferedReader.readLine()) != null) {
+ builder.append(temp);
+ }
+ log.info("message:"+builder.toString());
+ } catch (Exception e) {
+ log.warn("探活 failed:"+e);
+ }
+ }
} catch (Exception e) {
- e.printStackTrace();
+ log.error("交游:"+e);
//log.error("出现错误 "+e.toString());
}
return null;
}
- @RequestMapping("/story") //交互故事
+ @PostMapping("/story") //交互故事
public String story() {
try {
//log.info("--------------分界线-------------------");
- DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 3);
+ DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 5);
// log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
-// log.info(service.getStrRequest());
+ log.info(service.getStrRequest());
//service.disableVerify();
service.enableVerify();
String str = service.run();
-// log.info("响应信息:{}", str);
+ log.info("响应信息:{}", str);
return str;
} catch (Exception e) {
e.printStackTrace();
@@ -70,7 +122,7 @@ public class XiaoDuHomeController {
return null;
}
- @RequestMapping("/literature") // 互动文艺
+// @PostMapping("/literature") // 互动文艺
public String literature() {
try {
//log.info("--------------分界线-------------------");
@@ -89,7 +141,12 @@ public class XiaoDuHomeController {
return null;
}
- @RequestMapping("/smart") // 智能故事
+ @RequestMapping(value = "/smart", method = RequestMethod.HEAD)
+ public void smartHead(HttpServletResponse response) {
+ response.setStatus(200);
+ }
+
+ @PostMapping("/smart") // 智能故事
public String smart() {
try {
//log.info("--------------分界线-------------------");
@@ -98,17 +155,22 @@ public class XiaoDuHomeController {
// log.info(service.getStrRequest());
//service.disableVerify();
service.enableVerify();
- String str = service.run();
-// log.info("响应信息:{}", str);
- return str;
+ // log.info("响应信息:{}", str);
+ return service.run();
+ } catch (MismatchedInputException ex) {
} catch (Exception e) {
- e.printStackTrace();
+ log.error("smart:"+e);
//log.error("出现错误 "+e.toString());
}
return null;
}
- @RequestMapping("/novel") // 智能小说
+ @RequestMapping(value = "/novel", method = RequestMethod.HEAD)
+ public void novelHead(HttpServletResponse response) {
+ response.setStatus(200);
+ }
+
+ @PostMapping("/novel") // 智能小说
public String novel() {
try {
//log.info("--------------分界线-------------------");
@@ -117,11 +179,11 @@ public class XiaoDuHomeController {
// log.info(service.getStrRequest());
//service.disableVerify();
service.enableVerify();
- String str = service.run();
-// log.info("响应信息:{}", str);
- return str;
+ // log.info("响应信息:{}", str);
+ return service.run();
+ } catch (MismatchedInputException ex) {
} catch (Exception e) {
- e.printStackTrace();
+ log.error("novel:"+e);
//log.error("出现错误 "+e.toString());
}
return null;
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/GameProjectTb.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/GameProjectTb.java
index 05bc3ca..5116496 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/GameProjectTb.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/GameProjectTb.java
@@ -31,6 +31,9 @@ public class GameProjectTb {
@Column
private Long watch;
+// @Column(name = "work_type")
+// private Long workType;
+
@Column(name = "banner_img_url")
private String bannerImgUrl;
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/OnProductDetail.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/OnProductDetail.java
index 913a25b..3894308 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/OnProductDetail.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/entity/primary/OnProductDetail.java
@@ -35,6 +35,9 @@ public class OnProductDetail {
@Column
private Float score;
+ @Column(name = "work_type")
+ private Long workType;
+
@Column(name = "banner_img_url")
private String bannerImgUrl;
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/OverTimeDetail.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/OverTimeDetail.java
index 89024e6..8979790 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/OverTimeDetail.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/OverTimeDetail.java
@@ -20,5 +20,5 @@ import java.util.Map;
public class OverTimeDetail {
private final List directives = new ArrayList<>();
private final Map attributes = new HashMap<>();
- private Response response = new Response();
+ private volatile Response response = new Response();
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/AllOnProductInfoRepository.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/AllOnProductInfoRepository.java
index cdab0a9..2ff2f29 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/AllOnProductInfoRepository.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/AllOnProductInfoRepository.java
@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.repository.primary;
import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@@ -14,4 +15,9 @@ import java.util.List;
public interface AllOnProductInfoRepository extends JpaRepository {
List findAllByApplyStatusAndScoreNot(Integer applyStatus, Float score);
+
+ List findAllByApplyStatusAndWorkType(Integer applyStatus, Long workType);
+
+ @Query(value = "select name from game_project_tb where apply_status=1 and work_type=27",nativeQuery = true)
+ List findNameByApplyStatusAndWorkType(Integer applyStatus, Long workType);
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/GameProjectTbRepository.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/GameProjectTbRepository.java
index 1efc51e..d1a6273 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/GameProjectTbRepository.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/primary/GameProjectTbRepository.java
@@ -29,6 +29,6 @@ public interface GameProjectTbRepository extends JpaRepository postRankBot(Integer begin);
- @Query(value = "select bot_account from game_project_tb where apply_status=1",nativeQuery = true)
+ @Query(value = "select bot_account from game_project_tb where apply_status=1 and work_type=27",nativeQuery = true)
List getAllOnTableProductIds();
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java
index fb787e6..be3fb3c 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java
@@ -10,7 +10,6 @@ import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoDocument;
import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoUtils;
import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommandDocument;
import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommendUtil;
-import ai.qiwu.com.xiaoduhome.controller.WebSocketLog;
import ai.qiwu.com.xiaoduhome.entity.primary.*;
import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB;
import ai.qiwu.com.xiaoduhome.pojo.*;
@@ -54,20 +53,17 @@ import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
-import org.springframework.data.domain.Example;
+import org.apache.commons.lang3.math.NumberUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
-import java.nio.charset.StandardCharsets;
-import java.sql.Date;
-import java.sql.Timestamp;
+import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Pattern;
import static ai.qiwu.com.xiaoduhome.common.Constants.*;
-import static ai.qiwu.com.xiaoduhome.common.Constants.CATEGORY_IMG_URL.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.ErrorMsg.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.*;
@@ -100,7 +96,7 @@ public class DplBotService extends BaseBot {
private static final String FIRST_IMAGE = "https://didi-gz4.jiaoyou365.com/duai/image/Loading.png";
- private static final String DU_DEVICE_ID = "XIAODU_2bf4f1ade0565b09bef2c529b03e163b";
+// private static final String DU_DEVICE_ID = "XIAODU_2bf4f1ade0565b09bef2c529b03e163b";
private final int type;
@@ -109,51 +105,96 @@ public class DplBotService extends BaseBot {
public DplBotService(HttpServletRequest request, Integer type) throws IOException {
super(request);
this.type = type;
+ //privateKey为私钥内容,0代表你的Bot在DBP平台debug环境,1或者其他整数代表online环境,
+ // botMonitor对象已经在bot-sdk里初始化,可以直接调用
+ this.botMonitor.setEnvironmentInfo(PRIVATE_KEY, 1);
+// this.botMonitor.setMonitorEnabled(true);
}
@Override
public Response onLaunch(LaunchRequest launchRequest) {
if (getRequest().getContext().getScreen() == null) {
- String deviceId = PREFIX_USERID+getDeviceId();
- LAST_OUTTIME_MARK.remove(deviceId);
- LAST_OUTTIME_RESULT.remove(deviceId);
- USERID_AUDIO_PATH.remove(deviceId);
+ String userId = customUserId();
+ LAST_OUTTIME_MARK.remove(userId);
+ LAST_OUTTIME_RESULT.remove(userId);
+ USERID_AUDIO_PATH.remove(userId);
String welcomeWord;
String skillName;
+ String num = RandomStringUtils.randomNumeric(3);
switch (type) {
- case 1 : welcomeWord = WelcomeWord.WELCOME_SMART; skillName = SKILL_SMART; break;
- case 2 : welcomeWord = WelcomeWord.WELCOME_NOVEL; skillName = SKILL_NOVEL; break;
+ case 1 : {
+// welcomeWord = WELCOME_SMART_FORMAT;
+// try {
+// List botList = channel2Bots.get("jiaoyou-audio-child-test");
+// String name = botList.get(Integer.parseInt(num)%botList.size());
+// welcomeWord = String.format(welcomeWord, name,name);
+// } catch (Exception e) {
+// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+// welcomeWord = WELCOME_SMART;
+// }
+ welcomeWord = WELCOME_SMART;
+ skillName = SKILL_SMART;
+ break;
+ }
+ case 2 : {
+// welcomeWord = WELCOME_NOVEL_FORMAT;
+// try {
+// List botList = channel2Bots.get("jiaoyou-audio-adult-test");
+// String name = botList.get(Integer.parseInt(num)%botList.size());
+// welcomeWord = String.format(welcomeWord, name,name);
+// } catch (Exception e) {
+// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+// welcomeWord = WELCOME_NOVEL;
+// }
+ welcomeWord = WELCOME_NOVEL;
+ skillName = SKILL_NOVEL;
+ break;
+ }
case 3 : welcomeWord = WelcomeWord.WELCOME_STORY; skillName = SKILL_STORY; break;
case 4 : welcomeWord = WelcomeWord.WELCOME_LITERATURE; skillName = SKILL_LITERATURE; break;
- default: welcomeWord = WelcomeWord.WELCOME; skillName = SKILL; break;
+ default: {
+ welcomeWord = WELCOME_FORMAT;
+ try {
+ List botList = jiaoyouChannel2Bots.get("jiaoyou-audio-adult-test");
+ String name = botList.get(Integer.parseInt(num)%botList.size());
+ welcomeWord = String.format(welcomeWord, name,name);
+ } catch (Exception e) {
+ log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+ welcomeWord = WELCOME;
+ }
+ skillName = SKILL;
+ break;
+ }
}
StandardCard standardCard = new StandardCard(skillName, welcomeWord);
standardCard.setImage(FIRST_IMAGE);
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord);
return new Response(outputSpeech, standardCard);
+ } else {
+ return new Response();
}
- RenderDocument renderDocument = new RenderDocument(FIRST_PAGE);
- this.addDirective(renderDocument);
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, Constants.WelcomeWord.WELCOME);
- // 初次进入时创建用户的行为信息,包括历史记录,送花数,收藏记录
- // 历史记录,收藏记录,送花数,郊游天下id
- if (DplbotServiceUtil.USER_HISTORY.get(getUserId()) == null) {
- String accessToken = getAccessToken();
- if (accessToken != null) setSessionAttribute("userId", DplbotServiceUtil.getUserIdByToken(accessToken));
- DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, getUserId());
- }
- return new Response(outputSpeech);
+// RenderDocument renderDocument = new RenderDocument(FIRST_PAGE);
+// this.addDirective(renderDocument);
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, Constants.WelcomeWord.WELCOME);
+// // 初次进入时创建用户的行为信息,包括历史记录,送花数,收藏记录
+// // 历史记录,收藏记录,送花数,郊游天下id
+// if (DplbotServiceUtil.USER_HISTORY.get(getUserId()) == null) {
+// String accessToken = getAccessToken();
+// if (accessToken != null) setSessionAttribute("userId", DplbotServiceUtil.getUserIdByToken(accessToken));
+// DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, getUserId());
+// }
+// return new Response(outputSpeech);
}
@Override
protected Response onInent(IntentRequest intentRequest) {
- final String userId = getUserId();
+ final String userId = customUserId();
if (getRequest().getContext().getScreen() == null) {
- final String deviceUserId = PREFIX_USERID + getDeviceId();
+// final String deviceUserId = PREFIX_USERID + getDeviceId();
Byte overTimeType;
String path;
- if ((overTimeType = LAST_OUTTIME_MARK.remove(deviceUserId)) != null) {
- OverTimeDetail lastData = LAST_OUTTIME_RESULT.get(deviceUserId);
+ if ((overTimeType = LAST_OUTTIME_MARK.remove(userId)) != null) {
+ OverTimeDetail lastData = LAST_OUTTIME_RESULT.get(userId);
if (lastData != null) {
for (Directive directive : lastData.getDirectives()) {
//log.info("上次超时保存的Directive:{}",directive.getClass().getName());
@@ -163,89 +204,91 @@ public class DplBotService extends BaseBot {
//log.info("上次超时保存的key:{}",key);
this.setSessionAttribute(entry.getKey(), entry.getValue());
}
- LAST_OUTTIME_MARK.remove(deviceUserId);
- LAST_OUTTIME_RESULT.remove(deviceUserId);
+ LAST_OUTTIME_MARK.remove(userId);
+ LAST_OUTTIME_RESULT.remove(userId);
return lastData.getResponse();
}
if (overTimeType != 3) {
- LAST_OUTTIME_MARK.put(deviceUserId, (byte) (overTimeType+1));
+ LAST_OUTTIME_MARK.put(userId, (byte) (overTimeType+1));
return buildErrorResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2);
}
- LAST_OUTTIME_MARK.remove(deviceUserId);
- } else if ((path = USERID_AUDIO_PATH.get(deviceUserId)) != null) {
+ LAST_OUTTIME_MARK.remove(userId);
+ } else if ((path = USERID_AUDIO_PATH.get(userId)) != null) {
Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
addDirective(play);
- log.error("小度音频播放开始事件未被触发:"+path);
- dealWithFinishedNoCallEvent(deviceUserId);
+// log.error("小度音频播放开始事件未被触发:"+path);
+// dealWithFinishedNoCallEvent(userId);
return new Response();
}
try {
- Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, deviceUserId));
+ Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId));
future.get(2700, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
return buildErrorResponse(SORRY_UNCATCH);
} catch (TimeoutException e) {
log.info("超时,让用户再说一遍:{}",e.toString());
- LAST_OUTTIME_MARK.put(deviceUserId, OUTTIME_TYPE_0);
+ LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_0);
return buildErrorResponse(SORRY_UNCATCH);
} catch (Exception all) {
log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
return buildErrorResponse(SORRY_UNCATCH);
}
OverTimeDetail detail;
- if ((detail = LAST_OUTTIME_RESULT.remove(deviceUserId)) != null) return detail.getResponse();
+ if ((detail = LAST_OUTTIME_RESULT.remove(userId)) != null) return detail.getResponse();
return new Response();
- }
- OverTimeDetail detail;
- if ((detail = LAST_OUTTIME_RESULT.remove(userId)) != null) {
- for (Directive directive : detail.getDirectives()) {
- //log.info("上次超时保存的Directive:{}",directive.getClass().getName());
- this.addDirective(directive);
- }
- for (String key : detail.getAttributes().keySet()) {
- //log.info("上次超时保存的key:{}",key);
- this.setSessionAttribute(key, detail.getAttributes().get(key));
- }
- return detail.getResponse();
- }
- try {
- Future future = DplbotServiceUtil.getPOOL().submit(new Task(intentRequest));
- future.get(2200, TimeUnit.MILLISECONDS);
- } catch (InterruptedException | ExecutionException e) {
- log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
- return buildErrorResponse(SORRY_UNCATCH);
- } catch (TimeoutException e) {
- log.info("超时,让用户再说一遍:{}",e.toString());
- if ("funny".equals(getIntent().getName()) && FUNNY_DEFAULT_DOCUMENT != null) {
- RenderDocument document = new RenderDocument(FUNNY_DEFAULT_DOCUMENT);
- this.addDirective(document);
- return new Response();
- }else {
- return buildErrorResponse(SORRY_UNCATCH);
- }
- } catch (Exception all) {
- log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
- return buildErrorResponse(SORRY_UNCATCH);
- }
- OverTimeDetail data = LAST_OUTTIME_RESULT.remove(getUserId());
- if (data == null) return new Response();
- return data.getResponse();
- }
-
- private void dealWithFinishedNoCallEvent(String userId) {
- if (userId.equals(DU_DEVICE_ID)) {
- DplbotServiceUtil.getPOOL().submit(() -> {
- WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du1");
- });
} else {
- DplbotServiceUtil.getPOOL().submit(() -> {
- WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du2");
- });
+ return new Response();
}
+// OverTimeDetail detail;
+// if ((detail = LAST_OUTTIME_RESULT.remove(userId)) != null) {
+// for (Directive directive : detail.getDirectives()) {
+// //log.info("上次超时保存的Directive:{}",directive.getClass().getName());
+// this.addDirective(directive);
+// }
+// for (String key : detail.getAttributes().keySet()) {
+// //log.info("上次超时保存的key:{}",key);
+// this.setSessionAttribute(key, detail.getAttributes().get(key));
+// }
+// return detail.getResponse();
+// }
+// try {
+// Future future = DplbotServiceUtil.getPOOL().submit(new Task(intentRequest));
+// future.get(2200, TimeUnit.MILLISECONDS);
+// } catch (InterruptedException | ExecutionException e) {
+// log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
+// return buildErrorResponse(SORRY_UNCATCH);
+// } catch (TimeoutException e) {
+// log.info("超时,让用户再说一遍:{}",e.toString());
+// if ("funny".equals(getIntent().getName()) && FUNNY_DEFAULT_DOCUMENT != null) {
+// RenderDocument document = new RenderDocument(FUNNY_DEFAULT_DOCUMENT);
+// this.addDirective(document);
+// return new Response();
+// }else {
+// return buildErrorResponse(SORRY_UNCATCH);
+// }
+// } catch (Exception all) {
+// log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
+// return buildErrorResponse(SORRY_UNCATCH);
+// }
+// OverTimeDetail data = LAST_OUTTIME_RESULT.remove(getUserId());
+// if (data == null) return new Response();
+// return data.getResponse();
}
+// private void dealWithFinishedNoCallEvent(String userId) {
+// if (userId.equals(DU_DEVICE_ID)) {
+// DplbotServiceUtil.getPOOL().submit(() -> {
+// WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du1");
+// });
+// } else {
+// DplbotServiceUtil.getPOOL().submit(() -> {
+// WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du2");
+// });
+// }
+// }
+
private void dealNoScreenIntentTemp(IntentRequest intentRequest, String userId) {
String intentName = getIntent().getName();
OverTimeDetail data = new OverTimeDetail();
@@ -291,13 +334,22 @@ public class DplBotService extends BaseBot {
final String userWord = query.getOriginal();
// if (query != null) userWord = query.getOriginal();
if (userWord == null){
- log.warn("小度没有传来任何话语");
+ log.error("小度没有传来任何话语");
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
return;
}
- log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId());
- String response = RequestTerminal.requestTerminateTemp(userWord, userId, type);
- log.info("小度,小悟返回:{},",response);
+// log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId());
+
+ String channel;
+ switch (type) {
+ case 1 :
+ case 3 : channel = "jiaoyou-audio-child-test";break;
+ case 2 :
+ case 4 : channel = "jiaoyou-audio-adult-test";break;
+ default: channel = "jiaoyou-audio-test";break;
+ }
+ String response = RequestTerminal.requestTerminateTemp(userWord, userId, channel);
+// log.info("小度,小悟返回:{},",response);
if (StringUtils.isBlank(response)) {
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
return;
@@ -305,47 +357,106 @@ public class DplBotService extends BaseBot {
// String mark = RandomStringUtils.randomAlphabetic(3);
// AudioBoxData pathData = new AudioBoxData();
// OkHttp3Utils.asyncPost(XiaoAiConstants.TTS_DIDI3, response, pathData);
+ try {
+ JSONObject object = JSON.parseObject(response);
+ JSONArray commands = object.getJSONArray("commands");
+ if (commands != null && commands.size() != 0) {
+ String txt;
+ for (Object ob: commands) {
+ txt = ((JSONObject) ob).getString("text");
+ int i;
+ if (StringUtils.isNotBlank(txt) && (i=txt.indexOf("out")) != -1) {
+ log.info("小度,推荐bot退出:{},{}",userWord,userId);
+ String content = txt.substring(i+3, txt.indexOf("☚")).trim();
+ String byeWord = null;
+ String skillName = null;
+ switch (type) {
+ case 1: {
+ byeWord = EndMsg.END_BYE_STORY;
+ skillName = SKILL_SMART;
+ break;
+ }
+ case 2: {
+ byeWord = EndMsg.END_BYE_NOVEL;
+ skillName = SKILL_NOVEL;
+ break;
+ }
+ case 5: {
+ byeWord = EndMsg.END_BYE_JIAOYOU;
+ skillName = SKILL;
+ break;
+ }
+ }
+ if (byeWord == null) byeWord = EndMsg.END_BYE_Adult;
+ if (skillName == null) skillName = SKILL_DEFAULT;
+ if (StringUtils.isBlank(content)) {
+ JSONArray dialogs = object.getJSONArray("dialogs");
+ if (dialogs != null && dialogs.size() != 0) {
+ String str = ((JSONObject)dialogs.get(0)).getString("text");
+ if (StringUtils.isNotBlank(str)) {
+ str = str.replaceAll("\\{/.*?/}", "")+skillName;
+ data.setResponse(buildLogOutResponse(str));
+ RequestTerminal.backRequest(userId, type);
+ return;
+ }
+ }
+ RequestTerminal.backRequest(userId, type);
+ data.setResponse(buildLogOutResponse(byeWord));
+ return;
+ } else {
+ content = content.replaceAll("\\{/.*?/}", "")+skillName;
+ data.setResponse(buildLogOutResponse(content));
+ RequestTerminal.backRequest(userId, type);
+ return;
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("推荐bot退出解析出错:"+e);
+ }
String path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
- if (StringUtils.isBlank(path)) {
+// String path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", response);
+ if (StringUtils.isBlank(path) || "null".equals(path)) {
log.error("小度没有获取到音频链接");
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
return;
}
- final JSONObject ob = JSONObject.parseObject(response);
- String botAcc = ob.getString("aipioneerUsername");
- String beforeBotAccount = getSessionAttribute("botAcc");
- if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(botAcc)) {
- setSessionAttribute("botAcc", botAcc);
- data.getAttributes().put("botAcc",botAcc);
- }
+// final JSONObject ob = JSONObject.parseObject(response);
+// String botAcc = ob.getString("aipioneerUsername");
+// String beforeBotAccount = getSessionAttribute("botAcc");
+// if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(botAcc)) {
+// setSessionAttribute("botAcc", botAcc);
+// data.getAttributes().put("botAcc",botAcc);
+// }
Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
addDirective(play);
data.getDirectives().add(play);
USERID_AUDIO_PATH.put(userId, path);
- if (userId.equals(DU_DEVICE_ID)) {
- DplbotServiceUtil.getPOOL().submit(() -> {
- JSONArray array = ob.getJSONArray("dialogs");
- StringBuilder builder = new StringBuilder(userWord).append(File.separator);
- for (Object item: array) {
- String str = ((JSONObject) item).getString("text");
- builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
- }
- WebSocketLog.sendInfo(builder.toString(), "du1");
- });
- } else {
- DplbotServiceUtil.getPOOL().submit(() -> {
- JSONArray array = ob.getJSONArray("dialogs");
- StringBuilder builder = new StringBuilder(userWord).append(File.separator);
- for (Object item: array) {
- String str = ((JSONObject) item).getString("text");
- builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
- }
- WebSocketLog.sendInfo(builder.toString(), "du2");
- });
- }
+// if (userId.equals(DU_DEVICE_ID)) {
+// DplbotServiceUtil.getPOOL().submit(() -> {
+// JSONArray array = ob.getJSONArray("dialogs");
+// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+// for (Object item: array) {
+// String str = ((JSONObject) item).getString("text");
+// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+// }
+// WebSocketLog.sendInfo(builder.toString(), "du1");
+// });
+// } else {
+// DplbotServiceUtil.getPOOL().submit(() -> {
+// JSONArray array = ob.getJSONArray("dialogs");
+// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+// for (Object item: array) {
+// String str = ((JSONObject) item).getString("text");
+// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+// }
+// WebSocketLog.sendInfo(builder.toString(), "du2");
+// });
+// }
} catch (Exception e) {
- log.warn("中控返回结果为空");
+ log.warn("中控返回结果为空:"+e);
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
}
finally {
@@ -360,6 +471,7 @@ public class DplBotService extends BaseBot {
private String dealAudioUrl(String path) {
return Constants.TTS_DIDI3_GET+path;
+// return "http://didi-gz5.jiaoyou365.com:9663/api/audio/get?path="+path;
}
private void dealNoScreenSendFlowerIntent(String userId, OverTimeDetail data) {
@@ -672,25 +784,28 @@ public class DplBotService extends BaseBot {
case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break;
}
if (getRequest().getContext().getScreen() == null) {
- String deviceId = PREFIX_USERID+getDeviceId();
- LAST_OUTTIME_MARK.remove(deviceId);
- LAST_OUTTIME_RESULT.remove(deviceId);
- USERID_AUDIO_PATH.remove(deviceId);
+ String userId = customUserId();
+// LAST_OUTTIME_MARK.remove(userId);
+// LAST_OUTTIME_RESULT.remove(userId);
+// USERID_AUDIO_PATH.remove(userId);
String byeWord = EndMsg.END_BYE_Adult;
switch (type) {
- case 1:
+ case 2: byeWord = EndMsg.END_BYE_NOVEL;break;
+ case 1: byeWord = EndMsg.END_BYE_STORY;break;
case 3: byeWord = EndMsg.END_BYE_CHILD;break;
+ case 5: byeWord = EndMsg.END_BYE_JIAOYOU;break;
}
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
- try {
- if (DU_DEVICE_ID.equals(deviceId)) {
- RequestTerminal.backRequest(DU_DEVICE_ID, type);
- } else {
- RequestTerminal.backRequestDU2(deviceId, type);
- }
- } catch (Exception e) {
- log.warn("用户退出向中控发出退出指令出错");
- }
+ RequestTerminal.backRequest(userId, type);
+// try {
+// if (DU_DEVICE_ID.equals(deviceId)) {
+// RequestTerminal.backRequest(DU_DEVICE_ID, type);
+// } else {
+// RequestTerminal.backRequestDU2(deviceId, type);
+// }
+// } catch (Exception e) {
+// log.warn("用户退出向中控发出退出指令出错");
+// }
return new Response(outputSpeech);
}
DplbotServiceUtil.writeTheUserHistoryInData(getUserId());
@@ -897,6 +1012,12 @@ public class DplBotService extends BaseBot {
return new Response(outputSpeech);
}
+ private Response buildLogOutResponse(String errorMsg) {
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
+ endDialog();
+ return new Response(outputSpeech);
+ }
+
private Response buildNoScreenListCardResponse(String content, String botAccount) {
Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
List actors = DplbotServiceUtil.seperateActor(content, pattern);
@@ -2202,7 +2323,7 @@ public class DplBotService extends BaseBot {
final String botAccount = token.substring(0, sepIndex);
String str = "恭喜您支付成功,开始体验吧";
if (getRequest().getContext().getScreen() != null) {
- boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, getUserId(), getAccessToken(),
+ boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, customUserId(), getAccessToken(),
getSessionAttribute("userId"), PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_screen");
if (response) {
HashMap flowerRecords = DplbotServiceUtil.USER_HISTORY.get(getUserId()).getUserBotId2Flowers();
@@ -2224,7 +2345,7 @@ public class DplBotService extends BaseBot {
str = "很抱歉,您没有支付成功";
}
} else {
- String userId = getDeviceId();
+ String userId = customUserId();
String jytUserId = getSessionAttribute("userId");
if (StringUtils.isBlank(jytUserId)) jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken());
if (StringUtils.isBlank(jytUserId)) {
@@ -2244,7 +2365,7 @@ public class DplBotService extends BaseBot {
// log.info("音频播放完毕,开麦");
// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
this.setExpectSpeech(true);
- log.error("FinishedEvent");
+// log.error("FinishedEvent");
return new Response();
}
@@ -2258,7 +2379,7 @@ public class DplBotService extends BaseBot {
@Override
protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
- USERID_AUDIO_PATH.remove(PREFIX_USERID + getDeviceId());
+ USERID_AUDIO_PATH.remove(customUserId());
waitAnswer();
return new Response();
}
@@ -2269,4 +2390,14 @@ public class DplBotService extends BaseBot {
waitAnswer();
return new Response();
}
+
+ private String customUserId() {
+ try {
+ return PREFIX_USERID+ URLEncoder.encode(getUserId(), "UTF-8");
+ } catch (Exception e) {
+ return PREFIX_USERID+ getUserId().replaceAll("/", "");
+ }
+// return PREFIX_USERID + ai.qiwu.com.xiaoduhome.xiaoai.common.Utils.modifyDeviceId(getUserId());
+// return PREFIX_USERID + getUserId().replaceAll(NUM_OR_ALPHA, "");
+ }
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java
index 5add8be..c991d7a 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java
@@ -7,12 +7,20 @@ import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest;
import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse;
import ai.qiwu.com.xiaoduhome.pojo.playAside.AsideImageResponse;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
+import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.servlet.http.HttpServletRequest;
+import java.io.BufferedReader;
import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.Enumeration;
import java.util.HashMap;
import java.util.Random;
@@ -23,7 +31,7 @@ import java.util.Random;
@Slf4j
class RequestTerminal {
- static String requestTerminateTemp(String userWord, String userId, int type) throws IOException {
+ static String requestTerminateTemp(String userWord, String userId, String channel) throws IOException {
SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId);
requestPojo.setMsg(userWord);
@@ -31,14 +39,33 @@ class RequestTerminal {
// log.info("向小悟发送的请求信息:{}", requestJsonStr);
HashMap headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
- switch (type) {
- case 1 :
- case 3 : headers.put("App-Channel-Id", "jiaoyou-audio-child-test");break;
- case 2 :
- case 4 : headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");break;
- default: headers.put("App-Channel-Id", "jiaoyou-audio-test");
- }
+ headers.put("App-Channel-Id", channel);
+// String ip = Utils.getRemoteIpByServletRequest(request);
+// if (StringUtils.isNotBlank(ip)) {
+// headers.put("ip", ip);
+// if (test++ < 5) {
+// try {
+// Enumeration enumeration = request.getHeaderNames();
+// while (enumeration.hasMoreElements()) {
+// String name = (String) enumeration.nextElement();
+// log.info(name+":"+request.getHeader(name));
+// }
+// } catch (Exception e) {
+// log.warn("failed:"+e);
+// }
+// }
+// } else {
+// log.warn("ip is null");
+// }
+// switch (type) {
+// case 1 :
+// case 3 : headers.put("App-Channel-Id", "jiaoyou-audio-child-test");break;
+// case 2 :
+// case 4 : headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");break;
+// default: headers.put("App-Channel-Id", "jiaoyou-audio-test");
+// }
return OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, requestJsonStr, headers);
+// return OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, headers);
}
static QiWuResponse requestTerminate(String userWord, String userId, int type) throws IOException {
@@ -86,11 +113,11 @@ class RequestTerminal {
}
static void backRequest(String userId, int type) {
- QiWuRequest requestPojo = new QiWuRequest();
+ SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId);
-// requestPojo.setAccess(Constants.SERVICE_NAME);
- requestPojo.setMsg("退出当前作品");
+ requestPojo.setMsg("退出");
String requestJsonStr = JSON.toJSONString(requestPojo);
+// OkHttp3Utils.backPostAsync("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, type);
OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr, type);
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleService.java
index 40e8f45..c8e2dc8 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleService.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleService.java
@@ -26,6 +26,7 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
+import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -77,6 +78,13 @@ public class ScheduleService implements InitializingBean {
public static volatile Map channelId2RecommendBotAcc = new HashMap<>();
+ public static volatile Map> channel2Bots = new HashMap<>();
+ public static volatile Map> jiaoyouChannel2Bots = new HashMap<>();
+
+// public static volatile String STORY_WELCOME_WORD = "欢迎来到晓悟智能故事频道。与可爱的角色们自由对话,畅游不同的故事世界。我们新上线的遇见伽利略,你可以说打开遇见伽利略。或者说,推荐其它作品。";// 智能故事
+// public static volatile String NOVEL_WELCOME_WORD = "欢迎来到晓悟智能小说频道。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";// 智能小说
+// public static volatile String JIAOYOU_WELCOME_WORD = "欢迎来到晓悟智能小说频道。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";// 智能小说
+
@Autowired
public ScheduleService(GameProjectTbRepository gameProjectTbRepository,
ProjectLabelRepository projectLabelRepository,
@@ -90,6 +98,14 @@ public class ScheduleService implements InitializingBean {
this.xiaoDuOrderTbRepository = xiaoDuOrderTbRepository;
}
+// @Scheduled(cron = "* */10 * * * ?")
+// public void updateTheWelcomeName() {
+// DplbotServiceUtil.POOL.submit(() -> {
+// List onlinedProject = allOnProductInfoRepository.findAllByApplyStatusAndWorkType(1,27L);
+//
+// });
+// }
+
@Scheduled(cron = "0 */30 * * * ?")
public void cleatUserBehaviorData() {
DplbotServiceUtil.POOL.submit(() -> {
@@ -126,7 +142,7 @@ public class ScheduleService implements InitializingBean {
});
}
- @Scheduled(cron = "*/10 * * * * ?")
+// @Scheduled(cron = "*/10 * * * * ?")
public void updateTheCurTime() {
DplbotServiceUtil.POOL.submit(() -> curTime = System.currentTimeMillis());
}
@@ -141,7 +157,7 @@ public class ScheduleService implements InitializingBean {
//log.error("更新排行榜出错:{}", e.getMessage());
}
- @Scheduled(cron = "0 0 */1 * * ?")
+ @Scheduled(cron = "0 0 */2 * * ?")
public void initRecommendList() {
new Thread(() -> {
RECOMMEND_LIST = gameProjectTbRepository.recommendList();
@@ -216,22 +232,21 @@ public class ScheduleService implements InitializingBean {
}).start();
}
- @Scheduled(cron = "0 0 */1 * * ?")
+// @Scheduled(cron = "0 0 */1 * * ?")
public void shuffleAllProList() {
new Thread(() -> {
Collections.shuffle(ALL_ON_PRODUCT);
}).start();
}
- @Scheduled(cron = "0 */30 * * * ?")
+// @Scheduled(cron = "0 */20 * * * ?")
public void getAllChannelRecommendBotAccount() {
String response = null;
int count = 1;
Map map = new HashMap<>();
do {
try {
- Thread.sleep(count*5);
- response = OkHttp3Utils.doGet("http://didi-gz4.jiaoyou365.com:8070/api/sdk/botConfig/all");
+ response = OkHttp3Utils.doGet("http://didi-gz3.jiaoyou365.com:8070/api/sdk/botConfig/all");
JSONArray array = JSONObject.parseArray(response);
if (array != null) {
for (Object o: array) {
@@ -244,13 +259,74 @@ public class ScheduleService implements InitializingBean {
} catch (Exception e) {
log.error("getAllChannelRecommendBotAccount:{}",e);
}
- if (StringUtils.isBlank(response)) log.warn("第"+count+"次获取channelId失败");
+ if (StringUtils.isBlank(response)) {
+ try {
+ Thread.sleep(count*5);
+ } catch (Exception e) {}
+ log.warn("第"+count+"次获取channelId失败");
+ }
count++;
} while (StringUtils.isBlank(response) && count < 5);
if (map.size() != 0) {
channelId2RecommendBotAcc = map;
- log.error("audio channelId list:"+map);
}
+ log.info("channelId2RecommendBotAcc:"+channelId2RecommendBotAcc);
+ }
+
+ @Scheduled(cron = "0 */30 * * * ?")
+ public void getChannelAllBots() {
+ String response;
+ JSONObject jsonObject;
+ int count = 1;
+ boolean success = false;
+ do {
+ try {
+ response = OkHttp3Utils.doGet("http://didi-gz3.jiaoyou365.com:18082/api/data/audio/list");
+ jsonObject = JSON.parseObject(response).getJSONObject("data");
+ Map> map = jsonObject.toJavaObject(Map.class);
+ if (map != null && map.size() != 0) {
+ channel2Bots = map;
+ success = true;
+ } else {
+ log.info("getChannelAllBots failed count="+count);
+ Thread.sleep(count*5);
+ }
+ } catch (Exception e) {
+ log.warn("getChannelAllBots: "+e);
+ }
+ count++;
+ } while (!success && count < 5);
+ log.info("getChannelAllBots:"+channel2Bots);
+ }
+
+ @Scheduled(cron = "0 */30 * * * ?")
+ public void getJiaoYouChannelRecordBots() {
+ String response;
+ JSONObject jsonObject;
+ int count = 1;
+ boolean success = false;
+ do {
+ try {
+ response = OkHttp3Utils.doGet("http://didi-gz3.jiaoyou365.com:18082/api/data/audio/list/jiaoyou");
+ jsonObject = JSON.parseObject(response).getJSONObject("data");
+ Map> map = jsonObject.toJavaObject(Map.class);
+ if (map != null && map.size() != 0) {
+ List jiaoyouList = map.get("jiaoyou-audio-adult-test");
+ if (!CollectionUtils.isEmpty(jiaoyouList)) map.get("jiaoyou-audio-adult-test").add("遇见伽利略");
+ List xiaoaiJiaoyouList = map.get("xiaoai-jiaoyou-audio-adult-test");
+ if (!CollectionUtils.isEmpty(xiaoaiJiaoyouList)) map.get("xiaoai-jiaoyou-audio-adult-test").add("遇见伽利略");
+ jiaoyouChannel2Bots = map;
+ success = true;
+ } else {
+ log.info("getChannelAllBots failed count="+count);
+ Thread.sleep(count*5);
+ }
+ } catch (Exception e) {
+ log.warn("getChannelAllBots: "+e);
+ }
+ count++;
+ } while (!success && count < 5);
+ log.info("getChannelAllBots:"+jiaoyouChannel2Bots);
}
private void getAsideImg() {
@@ -260,7 +336,7 @@ public class ScheduleService implements InitializingBean {
for (String botId: botIds) {
try {
HashMap params = new HashMap<>();
- params.put("include", "npcHeadImgUrl");
+ params.put("include", "audioNpc");
params.put("aipioneerUsername",botId);
String str = OkHttp3Utils.doGet(ASIDE_IMG_URL, params);
AsideImageResponse response = JSON.parseObject(str, AsideImageResponse.class);
@@ -281,8 +357,11 @@ public class ScheduleService implements InitializingBean {
initProductList();
deleteOverTimeHistory();
deleteUnPayedOrder();
- tian();
+// tian();
getAsideImg();
+ getAllChannelRecommendBotAccount();
+ getChannelAllBots();
+ getJiaoYouChannelRecordBots();
}
private void tian(){
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/ChatLogs.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/ChatLogs.java
new file mode 100644
index 0000000..ab9951c
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/ChatLogs.java
@@ -0,0 +1,142 @@
+package ai.qiwu.com.xiaoduhome.service.chatsLog;
+
+import ai.qiwu.com.xiaoduhome.controller.WebSocketLog;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-12-30 上午10:59
+ */
+@Service
+@Slf4j
+public class ChatLogs {
+ private static final String PATH = "/root/programsCN/chats.log";
+
+ public String look(Integer row, String typeCount, String type) {
+ if (row == null || row == 0) row = 1000;
+ try {
+ LogResponse response = readLastRows(PATH, StandardCharsets.UTF_8, row);
+ if (StringUtils.isNotBlank(response.getData())) {
+ StringBuilder builder = new StringBuilder("\n" +
+ "\n" +
+ "\n" +
+ " \n" +
+ " Title \n" +
+ "\n" +
+ "");
+// StringBuilder builder = new StringBuilder();
+ if (StringUtils.isNotBlank(type)) {
+ if (StringUtils.isBlank(typeCount)) typeCount = "100";
+ int count = Integer.parseInt(typeCount);
+ String[] arrTest = response.getData().split("\n\n");
+ List list = Arrays.stream(arrTest).filter(s1 -> s1.contains(type))
+ .map(s1 -> {
+ String[] arr = s1.split("\n");
+ return Arrays.stream(arr).map(s -> ""+s+" ").collect(Collectors.joining(""));
+// return StringUtils.join(arr, "");
+ }).collect(Collectors.toList());
+ Collections.reverse(list);
+ List result = new ArrayList<>(list);
+ int recur = 0;
+ while (result.size() < count && response.getIndex() > 0 && recur < 200) {
+ response = readLastRowsWithIndex(PATH, StandardCharsets.UTF_8, response.getIndex(), 800);
+ arrTest = response.getData().split("\n\n");
+ list = Arrays.stream(arrTest).filter(s1 -> s1.contains(type)).map(s -> {
+ String[] arr = s.split("\n");
+ return Arrays.stream(arr).map(s1 -> ""+ s1 +" ").collect(Collectors.joining(""));
+ }).collect(Collectors.toList());
+ if (list.size() != 0) {
+ Collections.reverse(list);
+ result.addAll(list);
+ }
+ recur++;
+ }
+ result.forEach(s -> builder.append("").append(s).append(" "));
+ } else {
+ String[] arr = response.getData().split("\n");
+ List list = Arrays.asList(arr);
+ Collections.reverse(list);
+ list.forEach(s -> builder.append("").append(s).append(" "));
+// Arrays.stream(arr).forEach(s1 -> builder.append("").append(s1).append(" "));
+ }
+ builder.append("\n" +
+ "");
+ return builder.toString();
+// List list = Arrays.stream(arr).map(s1 -> ""+s1+" ").collect(Collectors.toList());
+// s = StringUtils.join(list, "");
+ }
+// s = s.replaceAll("\\{/.*/}", "");
+// WebSocketLog.sendInfo(s, "chat");
+ } catch (Exception e) {
+ log.error("ChatLogs:"+e.toString());
+ }
+ return null;
+ }
+
+ private static LogResponse readLastRows(String filename, Charset charset, int rows) throws IOException {
+ charset = charset == null ? Charset.defaultCharset() : charset;
+ String lineSeparator = System.getProperty("line.separator");
+ try (RandomAccessFile rf = new RandomAccessFile(filename, "r")) {
+ // 每次读取的字节数要和系统换行符大小一致
+ byte[] c = new byte[lineSeparator.getBytes().length];
+ // 在获取到指定行数和读完文档之前,从文档末尾向前移动指针,遍历文档每一个字节
+ for (long pointer = rf.length(), lineSeparatorNum = 0; pointer >= 0; rf.seek(pointer--)) {
+ // 移动指针
+ rf.seek(pointer);
+ // 读取数据
+ int readLength = rf.read(c);
+ if (readLength != -1 && new String(c, 0, readLength).equals(lineSeparator) && ++lineSeparatorNum == rows) {
+ // 找到足够数量换行符则退出循环
+ break;
+ }
+ }
+ LogResponse response = new LogResponse();
+ long index = rf.getFilePointer();
+ response.setIndex(index);
+ byte[] tempbytes = new byte[(int) (rf.length() - index)];
+ rf.readFully(tempbytes);
+ response.setData(new String(tempbytes, charset));
+ return response;
+ }
+ }
+
+ private static LogResponse readLastRowsWithIndex(String filename, Charset charset, long start, int rows) throws IOException {
+ charset = charset == null ? Charset.defaultCharset() : charset;
+ String lineSeparator = System.getProperty("line.separator");
+ try (RandomAccessFile rf = new RandomAccessFile(filename, "r")) {
+ // 每次读取的字节数要和系统换行符大小一致
+ byte[] c = new byte[lineSeparator.getBytes().length];
+ // 在获取到指定行数和读完文档之前,从文档末尾向前移动指针,遍历文档每一个字节
+ for (long pointer = start, lineSeparatorNum = 0; pointer >= 0; rf.seek(pointer--)) {
+ // 移动指针
+ rf.seek(pointer);
+ // 读取数据
+ int readLength = rf.read(c);
+ if (readLength != -1 && new String(c, 0, readLength).equals(lineSeparator) && ++lineSeparatorNum == rows) {
+ // 找到足够数量换行符则退出循环
+ break;
+ }
+ }
+ LogResponse response = new LogResponse();
+ long index = rf.getFilePointer();
+ response.setIndex(index);
+ byte[] tempbytes = new byte[(int) (start-index)];
+ rf.readFully(tempbytes);
+ response.setData(new String(tempbytes, charset));
+ return response;
+ }
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LogResponse.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LogResponse.java
new file mode 100644
index 0000000..aeaa445
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LogResponse.java
@@ -0,0 +1,15 @@
+package ai.qiwu.com.xiaoduhome.service.chatsLog;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-12-30 下午4:53
+ */
+@Getter
+@Setter
+public class LogResponse {
+ private String data;
+ private Long index;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LoginData.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LoginData.java
new file mode 100644
index 0000000..5cb2fde
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/chatsLog/LoginData.java
@@ -0,0 +1,17 @@
+package ai.qiwu.com.xiaoduhome.service.chatsLog;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-12-30 下午3:15
+ */
+@Getter
+@Setter
+public class LoginData {
+ private String username;
+ private String passwd;
+ private Long time;
+ private String token;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/InitialData.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/InitialData.java
index 60e9475..03274b5 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/InitialData.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/InitialData.java
@@ -60,7 +60,7 @@ public class InitialData implements InitializingBean {
}
Map> npcName2nameId = recordMap.computeIfAbsent(botAccount, s -> new HashMap<>());
int j = 0;
- // "person", "mood", "md5", "id", "text", "upUrl"
+ // "person", "mood", "md5", "id", "upUrl"
for (CSVRecord line: reader) {
if (j == 0) {
j++;
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritService.java
index 7939943..a86bcc4 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritService.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritService.java
@@ -72,7 +72,7 @@ public class SpiritService {
}
}
String userWord = request.getUtterance();
- log.info("天猫精灵用户说的话:"+userWord);
+// log.info("天猫精灵用户说的话:"+userWord);
try {
Future future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId));
return future.get(1700, TimeUnit.MILLISECONDS);
@@ -95,19 +95,20 @@ public class SpiritService {
//log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
- String channelId = "jiaoyou-audio-test";
+ String channelId;
switch (type) {
case 2:
- case 4: channelId = "jiaoyou-audio-child-test";break;
+ case 4: channelId = "tianmao-jiaoyou-audio-child-test";break;
case 3:
- case 5: channelId= "jiaoyou-audio-adult-test";break;
+ case 5: channelId= "tianmao-jiaoyou-audio-adult-test";break;
+ default: channelId = "tianmao-jiaoyou-audio-test";
}
headers.put("App-Channel-Id", channelId);
- String resStr= OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI2, requestJsonStr, headers);;
+ String resStr= OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);;
if (resStr == null) {
return null;
}
- log.info("天猫精灵晓悟返回:"+resStr);
+// log.info("天猫精灵晓悟返回:"+resStr);
TaskResult taskResult = null;
try {
final SpiritTerminateResponse response = JSON.parseObject(resStr, SpiritTerminateResponse.class);
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java
index 76e0b2d..a50eb8d 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java
@@ -26,13 +26,13 @@ public class RequestTerminal {
static {
ALL_HEADERS = new HashMap<>();
ALL_HEADERS.put("Content-Type", "application/json;charset=utf-8");
- ALL_HEADERS.put("App-Channel-Id", "jiaoyou-audio-test");
+ ALL_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-test");
CHILD_HEADERS = new HashMap<>();
CHILD_HEADERS.put("Content-Type", "application/json;charset=utf-8");
- CHILD_HEADERS.put("App-Channel-Id", "jiaoyou-audio-child-test");
+ CHILD_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-child-test");
ADULT_HEADERS = new HashMap<>();
ADULT_HEADERS.put("Content-Type", "application/json;charset=utf-8");
- ADULT_HEADERS.put("App-Channel-Id", "jiaoyou-audio-adult-test");
+ ADULT_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-adult-test");
}
/**
@@ -49,18 +49,17 @@ public class RequestTerminal {
String requestJsonStr = JSON.toJSONString(requestPojo);
//log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap headers;
- if (type != null) {
- if ((type & 1) == 1) headers = CHILD_HEADERS;
- else headers = ADULT_HEADERS;
- } else {
- headers = ALL_HEADERS;
- }
- String resStr;
- if (userId.equals(XiaoAiService.deviceId)) {
- resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_nx2, requestJsonStr, headers);
- }else {
- resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
+ switch (type) {
+ case 1: headers = CHILD_HEADERS; break;
+ case 2: headers = ADULT_HEADERS; break;
+ default: headers = ALL_HEADERS; break;
}
+ String resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);;
+// if (userId.equals(XiaoAiService.deviceId)) {
+// resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
+// }else {
+// resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
+// }
return resStr;
}
@@ -69,10 +68,11 @@ public class RequestTerminal {
requestPojo.setUid(userId);
requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD);
String requestJsonStr = JSON.toJSONString(requestPojo);
- if (userId.equals(XiaoAiService.deviceId)) {
- OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
- }else {
- OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_nx2, requestJsonStr, type);
- }
+ OkHttp3Utils.xiaoaiBackPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
+// if (userId.equals(XiaoAiService.deviceId)) {
+// OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
+// }else {
+// OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
+// }
}
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/Utils.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/Utils.java
index 8751234..3e17006 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/Utils.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/Utils.java
@@ -1,9 +1,18 @@
package ai.qiwu.com.xiaoduhome.xiaoai.common;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.codec.binary.Hex;
+import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
import java.util.Objects;
/**
@@ -11,12 +20,15 @@ import java.util.Objects;
* @author 苗权威
* @dateTime 19-7-6 上午11:16
*/
+@Slf4j
public class Utils {
/**
* 代表空格,斜杠,单引号,双引号,tab键
*/
- private static final String STRIP = " /'\"\\t";
+ private static final String STRIP = " /'\"\\t+";
+
+// public static final String NUM_OR_ALPHA = "[^0-9a-zA-Z]";
/**
* 获取HttpServletRequest对象
@@ -60,4 +72,82 @@ public class Utils {
}
return builder.toString();
}
+
+ public static boolean encry(Integer type, HttpServletRequest request) {
+ String host = "didi-gz4.jiaoyou365.com";
+ String xiaomiDate = request.getHeader("x-xiaomi-date");
+ String md5 = request.getHeader("content-md5");
+ if (StringUtils.isBlank(md5)) md5 = "";
+ String contentType = request.getHeader("content-type");
+ String authorization = request.getHeader("authorization");
+ if (StringUtils.isAnyBlank(xiaomiDate, contentType, authorization)) return false;
+ String secret, urlPath, keyId;
+ switch (type) {
+ case 1: {
+ secret = XiaoAiConstants.SECURITY.SMART_STORY_SECRET;
+ keyId = XiaoAiConstants.SECURITY.SMART_STORY_KEYID;
+ urlPath = "/xiaoai/child";
+ break;
+ }
+ case 2:{
+ secret = XiaoAiConstants.SECURITY.SMART_NOVEL_SECRET;
+ keyId = XiaoAiConstants.SECURITY.SMART_NOVEL_KEYID;
+ urlPath = "/xiaoai/adult";
+ break;
+ }
+ case 3:{
+ secret = "Q+TOpok4Dy/CMCXgHE6HFNrmdImYoJmRQlAGx7LkI54=";
+ keyId = "zOQuywFuKjlhbTMr4dHwFA==";
+ urlPath = "/xiaoaiTest/story";
+ break;
+ }
+ case 4:{
+ secret = "AaBr41l9jrPFir3c0tVdjl+nnwtMC6xcM4b/ua/MspA=";
+ keyId = "8eQZnL/YfA783qd/LOY0pw==";
+ urlPath = "/xiaoaiTest/story";
+ break;
+ }
+ default:{
+ secret = XiaoAiConstants.SECURITY.SMART_JIAOYOU_SECRET;
+ keyId = XiaoAiConstants.SECURITY.SMART_JIAOYOU_KEYID;
+ urlPath = "/xiaoai/";
+ break;
+ }
+ }
+ String algorithmForMac = "HmacSHA256";
+
+ String method = "POST";
+ String param = "";
+ String source = new StringBuilder().append(method).append('\n').append(urlPath).append('\n').append(param).append('\n')
+ .append(xiaomiDate).append('\n').append(host).append('\n')
+ .append(contentType).append('\n').append(md5).append('\n').toString();
+ try {
+ Mac mac = Mac.getInstance(algorithmForMac);
+ SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.decodeBase64(secret), algorithmForMac);
+ mac.init(secretKeySpec);
+// String signature = Hex.encodeHexString(mac.doFinal(source.getBytes(StandardCharsets.UTF_8)));
+ String signature = new StringBuilder("MIAI-HmacSHA256-V1 ").append(keyId).append("::")
+ .append(Hex.encodeHexString(mac.doFinal(source.getBytes(StandardCharsets.UTF_8)))).toString();
+ return signature.equals(authorization);
+// boolean result = signature.equals(authorization);
+// log.info("signature:{}, compare:{}",signature, result);
+// return result;
+ } catch (Exception e) {
+ log.error("encry:"+e);
+ }
+ return false;
+ }
+
+ public static void main(String[] args) throws UnsupportedEncodingException {
+// SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
+// sdf3.setTimeZone(TimeZone.getTimeZone("GMT"));
+// String rfc1123_3 = sdf3.format(new Date(System.currentTimeMillis()-100000));
+// System.out.println("rfc1123_3 = "+rfc1123_3);
+// System.out.println(new Date(System.currentTimeMillis()));
+ String s = URLEncoder.encode("+Ls69sFTjXN/6//831N1V==Vdfw", "UTF-8");
+// System.out.println(s);
+ System.out.println("+Ls69sFTjXN/683//1N1V==Vdfw".replaceAll("/", ""));
+ System.out.println(URLEncoder.encode("sgagsgdg", "UTF-8"));
+ System.out.println(URLEncoder.encode("123467845131", "UTF-8"));
+ }
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java
index 663e99d..7eba075 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java
@@ -10,6 +10,7 @@ public interface XiaoAiConstants {
String QI_WU_TERMINATE_DIDI2 = "http://didi-gz2.jiaoyou365.com:8070/api/chat2";
String QI_WU_TERMINATE_nx2 = "http://didi-gz4.jiaoyou365.com:8070/api/chat2";
String TTS_DIDI3 = "http://didi-gz3.jiaoyou365.com:9663/api/audio";
+ String TTS_DIDI2 = "http://didi-gz2.jiaoyou365.com:9663/api/audio";
String TTS_DIDI4 = "http://didi-gz4.jiaoyou365.com:9663/api/audio";
String DEVICE_NAME = "XIAOAI";
String CONTENT_TYPE = "application/json;charset=utf-8";
@@ -30,6 +31,7 @@ public interface XiaoAiConstants {
String WELCOME_WORD_CHILD_STORY = "小朋友你好,欢迎来到互动故事,你可以说推荐作品给我";
String WELCOME_WORD_Adult = "你好,欢迎来到智能小说,你可以说推荐作品给我";
String WELCOME_WORD_Adult_literature = "你好,欢迎来到互动文艺,你可以说推荐作品给我";
+ String WELCOME_WORD_DEFAULT = "欢迎来到我们的技能,与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";
String END_BYE = "我们的作品库在不断扩充,欢迎再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_BYE_Adult = "再见啦,记得下次再来玩哦";
@@ -41,4 +43,13 @@ public interface XiaoAiConstants {
String WAIT_WORD_2 = "由于网络的原因,您可能需要稍稍等等";
String WAIT_WORD_3 = "由于网络原因小悟正在加倍努力获取结果,不过您现在得快些对我说些什么,要不然您就退出我们的技能了";
}
+
+ interface SECURITY {
+ String SMART_STORY_SECRET = "J03wDvFuUtr0lgBAm628aSNZiC0haluC/yXe90//Z7M=";
+ String SMART_STORY_KEYID = "5hlvswxeP9J1Ths0+fL9vQ==";
+ String SMART_NOVEL_SECRET = "IeVTzSD1wHDSoboQhqQFTHJgB28Wr/HtxkgkL5HLmmY=";
+ String SMART_NOVEL_KEYID = "RrNYDL7DeNgKZGAW/KC6Iw==";
+ String SMART_JIAOYOU_SECRET = "kkluiypsxYwGzLej+ZAHoo/ec0gnoOsBdr8uzmBn1+M=";
+ String SMART_JIAOYOU_KEYID = "BDLeaCyRlF7wI8Wvb/RjwA==";
+ }
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/innerRequest/Request.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/innerRequest/Request.java
index d910d07..74007b5 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/innerRequest/Request.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/innerRequest/Request.java
@@ -1,5 +1,6 @@
package ai.qiwu.com.xiaoduhome.xiaoai.model.request.innerRequest;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@@ -11,8 +12,9 @@ import lombok.ToString;
@Getter
@Setter
@ToString
+@JsonIgnoreProperties(ignoreUnknown = true)
public class Request {
- private int type;
+ private Integer type;
private String request_id;
private Long timestamp;
private Boolean no_response;
@@ -20,4 +22,6 @@ public class Request {
private EventProperty event_property;
private String Locale;
private SlotInfo slot_info;
+
+ private Boolean is_monitor;
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/PhoneTemplate.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/PhoneTemplate.java
new file mode 100644
index 0000000..c5667a8
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/PhoneTemplate.java
@@ -0,0 +1,19 @@
+package ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toDisplay;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+import java.util.Map;
+
+/**
+ * @author 苗权威
+ * @dateTime 20-1-7 下午8:34
+ */
+@Getter
+@Setter
+@ToString
+public class PhoneTemplate {
+ private String template_name;
+ private Map params;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/ToDisplay.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/ToDisplay.java
index 53dc378..8f5cef3 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/ToDisplay.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/response/innerResponse/toDisplay/ToDisplay.java
@@ -17,4 +17,7 @@ public class ToDisplay {
private String url;
private String text;
private UITemplate ui_template;
+
+ private String ui_type;
+ private PhoneTemplate phone_template;
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java
index ac8cd39..9b32e0b 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java
@@ -1,7 +1,6 @@
package ai.qiwu.com.xiaoduhome.xiaoai.service;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
-import ai.qiwu.com.xiaoduhome.controller.WebSocketLog;
import ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil;
import ai.qiwu.com.xiaoduhome.xiaoai.common.*;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
@@ -12,21 +11,28 @@ import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.Audi
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.Directive;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toDisplay.ToDisplay;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
+import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.io.File;
+import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.*;
+import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.*;
+import static ai.qiwu.com.xiaoduhome.service.ScheduleService.channel2Bots;
+import static ai.qiwu.com.xiaoduhome.service.ScheduleService.jiaoyouChannel2Bots;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.PREFIX_USERID;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.TTS.WAIT_WORD_3;
+import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.TTS.WELCOME_WORD_DEFAULT;
/**
* @author 苗权威
@@ -49,7 +55,7 @@ public class XiaoAiService {
*/
private static final ConcurrentHashMap LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
public static final ConcurrentHashMap LAST_OUTTIME_MARK = new ConcurrentHashMap<>();
- private static final ConcurrentHashMap LAST_AUDIO_PLAY = new ConcurrentHashMap<>();
+// private static final ConcurrentHashMap LAST_AUDIO_PLAY = new ConcurrentHashMap<>();
public static final Byte OUTTIME_TYPE_0 = 0;
private static final Byte OUTTIME_TYPE_1 = 1;
@@ -64,11 +70,12 @@ public class XiaoAiService {
*/
public XiaoAiResponse getResponse(XiaoAiRequest request) {
String userId = getUserId(request);
+// String userId = "%2FScfTGmNbhn%2Fs8KXMJfZY4nQ%2F";
int type = request.getRequest().getType();
switch (type) {
case 0 : return dealWithLaunchRequest(request);
case 1 : return dealWithIntentRequest(request, userId);
- case 2 : return dealWithEndRequest(userId, request.getType());
+ case 2 : return dealWithEndRequest(userId, request.getType(), Boolean.TRUE.equals(request.getRequest().getIs_monitor()));
default: return buildTextResponse(SORRY_REPEAT);
}
}
@@ -131,6 +138,21 @@ public class XiaoAiService {
return response;
}
+ private XiaoAiResponse buildResponseBeforeLoadout(String text) {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(true);
+
+ Response responseInfo = new Response();
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+
+ response.setResponse(responseInfo);
+ return response;
+ }
+
/**
* 构建语音返回信息
* @param audioUrl 音频文件地址
@@ -194,6 +216,24 @@ public class XiaoAiService {
return response;
}
+ private XiaoAiResponse buildCancelTextResponse(String text) {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(true);
+
+ Response responseInfo = new Response();
+ // 这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,
+ // 若不主动打开则小爱在一次会话后退出技能。
+ responseInfo.setOpen_mic(false);
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+ response.setResponse(responseInfo);
+
+ return response;
+ }
+
/**
* 处理启动意图,返回欢迎语
* @param request 请求信息
@@ -206,17 +246,53 @@ public class XiaoAiService {
// }
LAST_OUTTIME_RESULT.remove(getUserId(request));
LAST_OUTTIME_MARK.remove(getUserId(request));
- LAST_AUDIO_PLAY.remove(getUserId(request));
- Integer type;
- if ((type = request.getType()) != null) {
- switch (type) {
- case 1: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_CHILD);
- case 2: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_Adult);
- case 3: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_CHILD_STORY);
- case 4: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_Adult_literature);
+// LAST_AUDIO_PLAY.remove(getUserId(request));
+
+ String welcomeWord = null;
+ String num = RandomStringUtils.randomNumeric(3);
+ Integer type = request.getType();
+ switch (type) {
+ case 1 : {
+// welcomeWord = WELCOME_SMART_FORMAT_AI;
+// try {
+// List botList = channel2Bots.get("xiaoai-jiaoyou-audio-child-test");
+// String name = botList.get(Integer.parseInt(num)%botList.size());
+// welcomeWord = String.format(welcomeWord, name,name);
+// } catch (Exception e) {
+// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+// welcomeWord = WELCOME_SMART;
+// }
+ welcomeWord = WELCOME_SMART;
+ break;
+ }
+ case 2 : {
+// welcomeWord = WELCOME_NOVEL_FORMAT;
+// try {
+// List botList = channel2Bots.get("xiaoai-jiaoyou-audio-adult-test");
+// String name = botList.get(Integer.parseInt(num)%botList.size());
+// welcomeWord = String.format(welcomeWord, name,name);
+// } catch (Exception e) {
+// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+// welcomeWord = WELCOME_NOVEL;
+// }
+ welcomeWord = WELCOME_NOVEL;
+ break;
+ }
+ case 5 : {
+ welcomeWord = WELCOME_FORMAT;
+ try {
+ List botList = jiaoyouChannel2Bots.get("xiaoai-jiaoyou-audio-adult-test");
+ String name = botList.get(Integer.parseInt(num)%botList.size());
+ welcomeWord = String.format(welcomeWord, name,name);
+ } catch (Exception e) {
+ log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+ welcomeWord = WELCOME;
+ }
+ break;
}
}
- return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD);
+ if (welcomeWord == null) welcomeWord = WELCOME_WORD_DEFAULT;
+ return buildTextResponse(welcomeWord);
}
/**
@@ -226,7 +302,8 @@ public class XiaoAiService {
* @param userId 用户在小爱上的id
* @return 响应信息
*/
- private XiaoAiResponse dealWithIntentRequest(XiaoAiRequest request, String userId) {
+ private XiaoAiResponse dealWithIntentRequest(final XiaoAiRequest request, final String userId) {
+// if (Boolean.TRUE.equals(request.getRequest().getIs_monitor())) return buildTextResponse("测试返回");
Boolean idle = request.getRequest().getNo_response();
Byte waitType;
if ((waitType=LAST_OUTTIME_MARK.remove(userId)) != null) {
@@ -248,10 +325,15 @@ public class XiaoAiService {
}
return LAST_OUTTIME_RESULT.remove(userId);
}
+// String path;
+// if ((path = LAST_AUDIO_PLAY.get(userId)) != null) {
+// log.info(userId+": audio no play");
+// return buildAudioResponse(changeAudioUrl(path, userId));
+// }
if (Boolean.TRUE.equals(idle)) {
try {
//log.info("开始等待");
- Thread.sleep(2000);
+ Thread.sleep(1700);
//log.info("等待OVER");
} catch (InterruptedException e) {
log.warn("等待中断");
@@ -263,15 +345,11 @@ public class XiaoAiService {
return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.USER_IDLE :
XiaoAiConstants.TTS.ANOTHER_USER_IDLE);
}
- String path;
- if ((path = LAST_AUDIO_PLAY.get(userId)) != null) {
- return buildAudioResponse(changeAudioUrl(path, userId));
- }
// XiaoAiResponse response = getLastResult(userId);
// if (response != null) return response;
try {
- Future future = DplbotServiceUtil.getPool().submit(new Task(userId, request.getQuery(), request.getType()));
- future.get(2250, TimeUnit.MILLISECONDS);
+ Future future = DplbotServiceUtil.getPool().submit(() -> task(userId, request.getQuery(), request.getType()));
+ future.get(2200, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", e.toString());
return buildTextResponse(SORRY_REPEAT);
@@ -291,23 +369,22 @@ public class XiaoAiService {
* @param userId 用户id
* @return 返回信息
*/
- private XiaoAiResponse dealWithEndRequest(String userId, Integer type) {
-// DplbotServiceUtil.getPool().submit(() -> {
-// try {
-// RequestTerminal.backBotRequest(userId, type);
-// } catch (Exception e) {
-// log.error("向终端发出的退出请求失败:{}", e.toString());
-// }
-// });
- RequestTerminal.backBotRequest(userId, type);
- LAST_OUTTIME_MARK.remove(userId);
- LAST_OUTTIME_RESULT.remove(userId);
- LAST_AUDIO_PLAY.remove(userId);
- if (type != null) {
- if ((type & 1) == 1) return buildTextResponse(XiaoAiConstants.TTS.END_BYE_CHILD);
- else return buildTextResponse(XiaoAiConstants.TTS.END_BYE_Adult);
+ private XiaoAiResponse dealWithEndRequest(String userId, Integer type, Boolean monitor) {
+// LAST_OUTTIME_MARK.remove(userId);
+// LAST_OUTTIME_RESULT.remove(userId);
+// LAST_AUDIO_PLAY.remove(userId);
+ if (!monitor) RequestTerminal.backBotRequest(userId, type);
+ else {
+ log.info("小爱monitor退出请求:"+userId);
+ }
+ String byeWord;
+ switch (type) {
+ case 1: byeWord = EndMsg.END_BYE_STORY;break;
+ case 2: byeWord = EndMsg.END_BYE_NOVEL;break;
+ case 5: byeWord = EndMsg.END_BYE_JIAOYOU;break;
+ default: byeWord = EndMsg.END_BYE_DEFAULT;break;
}
- return buildTextResponse(XiaoAiConstants.TTS.END_BYE);
+ return buildCancelTextResponse(byeWord);
}
/**
@@ -316,119 +393,219 @@ public class XiaoAiService {
* @return 用户id
*/
private String getUserId(XiaoAiRequest request) {
- String userId = request.getContext().getDevice_id();
+ String userId = request.getSession().getUser().getUser_id();
if (userId == null) {
- userId = request.getSession().getUser().getUser_id();
+ userId = request.getContext().getDevice_id();
+ if (userId != null) userId = Utils.modifyDeviceId(userId);
}
if (userId == null) {
userId = Utils.useIPAsItsID();
}
- userId = PREFIX_USERID+userId;
- return Utils.modifyDeviceId(userId);
+ try {
+ return PREFIX_USERID+ URLEncoder.encode(userId, "UTF-8");
+ } catch (Exception e) {
+ return PREFIX_USERID+ userId.replaceAll("/", "");
+ }
+// return PREFIX_USERID+userId.replaceAll(NUM_OR_ALPHA, "");
+// return Utils.modifyDeviceId(userId);
}
private XiaoAiResponse getLastResult(String userId) {
return LAST_OUTTIME_RESULT.remove(userId);
}
- /**
- * 任务封装类
- */
- class Task implements Runnable {
- private final String userId;
- private final String userWord;
- private final Integer type;
-
- Task(String userId, String userWord, Integer type) {
- this.userId = userId;
- this.userWord = userWord;
- this.type = type;
+ private void task(String userId, String userWord, Integer type) {
+ XiaoAiResponse xiaoAiResponse;
+ if (userWord == null) {
+ log.warn("请求中没有带有用户的话");
+ throw new RequestWordNullException("user word can not be null");
}
-
- @Override
- public void run() {
- XiaoAiResponse xiaoAiResponse;
- if (userWord == null) {
- log.info("请求中没有带有用户的话");
- throw new RequestWordNullException("user word can not be null");
- }
- log.info("小爱,用户说的话:{}", userWord);
- String response;
+ String response;
+ try {
+ response = RequestTerminal.requestTerminate(userId, userWord, type);
+// log.info("小爱,小悟返回:{}", response);
+ } catch (Exception e) {
+ log.error("向终端发出的请求信息失败:{}", e.toString());
+ xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+ LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
+ return;
+ }
+ if (StringUtils.isBlank(response)) {
+ log.error("中控返回结果为空");
+ xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+ } else {
try {
- response = RequestTerminal.requestTerminate(userId, userWord, type);
- log.info("小爱,小悟返回:{}", response);
- } catch (Exception e) {
- log.error("向终端发出的请求信息失败:{}", e.toString());
- xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
- LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
- return;
- }
- if (StringUtils.isBlank(response)) {
- log.error("中控返回结果为空");
- xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
- } else {
- String path;
- try {
- boolean one;
- if ((one=userId.equals(deviceId))) {
- path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI4, response);
- } else {
- path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
- }
- if (StringUtils.isBlank(path) || path.equals("null")) {
- log.error("没有获取到TTS返回的路径path");
- LAST_OUTTIME_RESULT.put(userId, buildTextResponse(SORRY_REPEAT));
- return;
- }
- if (one) {
- xiaoAiResponse = buildAudioResponse(changeAudioUrlTemp(path, userId));
- } else {
- xiaoAiResponse = buildAudioResponse(changeAudioUrl(path, userId));
- }
- LAST_AUDIO_PLAY.put(userId, path);
- if (userId.equals(deviceId)) {
- DplbotServiceUtil.getPool().submit(() -> {
- JSONObject ob = JSONObject.parseObject(response);
- JSONArray array = ob.getJSONArray("dialogs");
- StringBuilder builder = new StringBuilder(userWord).append(File.separator);
- for (Object item: array) {
- String str = ((JSONObject) item).getString("text");
- builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+// log.info(response);
+ JSONObject object = JSON.parseObject(response);
+ JSONArray commands = object.getJSONArray("commands");
+ if (commands != null && commands.size() != 0) {
+ String txt;
+ for (Object ob: commands) {
+ txt = ((JSONObject) ob).getString("text");
+ int i;
+ if (StringUtils.isNotBlank(txt) && (i=txt.indexOf("out")) != -1) {
+ log.info("小爱,推荐bot退出:{},userId:{}", userWord, userId);
+ String content = txt.substring(i+3, txt.indexOf("☚")).trim();
+ String skillName, outWord;
+ switch (type) {
+ case 1: {
+ skillName = SKILL_SMART;
+ outWord = EndMsg.END_BYE_STORY;
+ break;
+ }
+ case 2: {
+ skillName = SKILL_NOVEL;
+ outWord = EndMsg.END_BYE_NOVEL;
+ break;
+ }
+ default: {
+ skillName = SKILL;
+ outWord = EndMsg.END_BYE_JIAOYOU;
+ }
}
- WebSocketLog.sendInfo(builder.toString(), "ai1");
- });
- } else {
- DplbotServiceUtil.getPool().submit(() -> {
- JSONObject ob = JSONObject.parseObject(response);
- JSONArray array = ob.getJSONArray("dialogs");
- StringBuilder builder = new StringBuilder(userWord).append(File.separator);
- for (Object item: array) {
- String str = ((JSONObject) item).getString("text");
- builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+ RequestTerminal.backBotRequest(userId, type);
+ if (StringUtils.isNotBlank(content)) {
+ content = content.replaceAll("\\{/.*?/}", "")+skillName;
+ LAST_OUTTIME_RESULT.put(userId, buildResponseBeforeLoadout(content));
+ return;
+ } else {
+ JSONArray dialogs = object.getJSONArray("dialogs");
+ if (dialogs != null && dialogs.size() != 0) {
+ String str = ((JSONObject)dialogs.get(0)).getString("text");
+ if (StringUtils.isNotBlank(str)) {
+ str = str.replaceAll("\\{/.*?/}", "")+skillName;
+ LAST_OUTTIME_RESULT.put(userId, buildResponseBeforeLoadout(str));
+ return;
+ }
+ }
+ LAST_OUTTIME_RESULT.put(userId, buildResponseBeforeLoadout(outWord));
+ return;
}
- WebSocketLog.sendInfo(builder.toString(), "ai2");
- });
+ }
}
- } catch (Exception e) {
+ }
+ } catch (Exception e) {
+ log.error("推荐bot退出解析出错:"+e);
+ }
+
+ String path;
+ try {
+ path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
+ if (StringUtils.isBlank(path) || path.equals("null")) {
log.error("没有获取到TTS返回的路径path");
- xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+ LAST_OUTTIME_RESULT.put(userId, buildTextResponse(SORRY_REPEAT));
+ return;
}
-// final String word = userWord;
-// DplbotServiceUtil.getPOOL().submit(() -> {
-// if (deviceId.equals(userId)) {
-// WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator)
-// .append(response.getText()).toString(), "ai1");
-// } else {
-// WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator)
-// .append(response.getText()).toString(), "ai2");
-// }
-// });
+ xiaoAiResponse = buildAudioResponse(changeAudioUrl(path, userId));
+// LAST_AUDIO_PLAY.put(userId, path);
+ } catch (Exception e) {
+ log.error("没有获取到TTS返回的路径path");
+ xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
}
- LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
}
+ LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
}
+// /**
+// * 任务封装类
+// */
+// class Task implements Runnable {
+// private final String userId;
+// private final String userWord;
+// private final Integer type;
+//
+// Task(String userId, String userWord, Integer type) {
+// this.userId = userId;
+// this.userWord = userWord;
+// this.type = type;
+// }
+//
+// @Override
+// public void run() {
+// XiaoAiResponse xiaoAiResponse;
+// if (userWord == null) {
+// log.info("请求中没有带有用户的话");
+// throw new RequestWordNullException("user word can not be null");
+// }
+// log.info("小爱,用户说的话:{}", userWord);
+// String response;
+// try {
+// response = RequestTerminal.requestTerminate(userId, userWord, type);
+// log.info("小爱,小悟返回:{}", response);
+// } catch (Exception e) {
+// log.error("向终端发出的请求信息失败:{}", e.toString());
+// xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+// LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
+// return;
+// }
+// if (StringUtils.isBlank(response)) {
+// log.error("中控返回结果为空");
+// xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+// } else {
+// String path;
+// try {
+// boolean one;
+// if ((one=userId.equals(deviceId))) {
+//// path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI4, response);
+// path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
+// } else {
+// path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
+// }
+// if (StringUtils.isBlank(path) || path.equals("null")) {
+// log.error("没有获取到TTS返回的路径path");
+// LAST_OUTTIME_RESULT.put(userId, buildTextResponse(SORRY_REPEAT));
+// return;
+// }
+// if (one) {
+// xiaoAiResponse = buildAudioResponse(changeAudioUrl(path, userId));
+// } else {
+// xiaoAiResponse = buildAudioResponse(changeAudioUrl(path, userId));
+// }
+// LAST_AUDIO_PLAY.put(userId, path);
+// if (userId.equals(deviceId)) {
+// DplbotServiceUtil.getPool().submit(() -> {
+// JSONObject ob = JSONObject.parseObject(response);
+// JSONArray array = ob.getJSONArray("dialogs");
+// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+// for (Object item: array) {
+// String str = ((JSONObject) item).getString("text");
+// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+// }
+// WebSocketLog.sendInfo(builder.toString(), "ai1");
+// });
+// } else {
+// DplbotServiceUtil.getPool().submit(() -> {
+// JSONObject ob = JSONObject.parseObject(response);
+// JSONArray array = ob.getJSONArray("dialogs");
+// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+// for (Object item: array) {
+// String str = ((JSONObject) item).getString("text");
+// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+// }
+// WebSocketLog.sendInfo(builder.toString(), "ai2");
+// });
+// }
+// } catch (Exception e) {
+// log.error("没有获取到TTS返回的路径path");
+// xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+// }
+//// final String word = userWord;
+//// DplbotServiceUtil.getPOOL().submit(() -> {
+//// if (deviceId.equals(userId)) {
+//// WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator)
+//// .append(response.getText()).toString(), "ai1");
+//// } else {
+//// WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator)
+//// .append(response.getText()).toString(), "ai2");
+//// }
+//// });
+// }
+// LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
+// }
+// }
+
private String changeAudioUrl(String path, String userId) {
+ path = path.replaceAll("%2F", "/");
return new StringBuilder(TTS_DIDI3_GET_XIAOAI).append(userId).append("&path=").append(path).toString();
}
@@ -438,13 +615,13 @@ public class XiaoAiService {
return new StringBuilder(TTS_DIDI4_GET_XIAOAI).append(userId).append("&path=").append(path).toString();
}
- public void changeAudioPlayMark(String userId) {
- LAST_AUDIO_PLAY.remove(userId);
- }
+// public void changeAudioPlayMark(String userId) {
+// LAST_AUDIO_PLAY.remove(userId);
+// }
public static void main(String[] args) {
- System.out.println(Utils.modifyDeviceId("XIAOAI_nbNGwo/tZIS8A/mRGVqHog=="));
-// oIOWfYEFbZGFHB5DzoMA==;
-// oItOWfYEFbtZGFHB5DzoMA==
+ System.out.println(Utils.modifyDeviceId("XIAOAI_Ls69sFTjXN/6831N1VVdfw"));
+ System.out.println(Utils.modifyDeviceId("XIAOAI_+nzkUO6JnLrmiWSlBQaZ9g"));
+ System.out.println(Utils.modifyDeviceId("XIAOAI_Ls69sFTjXN/6831N1VVdfw"));
}
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiTestService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiTestService.java
new file mode 100644
index 0000000..eb49222
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiTestService.java
@@ -0,0 +1,517 @@
+package ai.qiwu.com.xiaoduhome.xiaoai.service;
+
+import ai.qiwu.com.xiaoduhome.common.Constants;
+import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
+import ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil;
+import ai.qiwu.com.xiaoduhome.service.ScheduleService;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.RequestTerminal;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.RequestWordNullException;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.Utils;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.Response;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.AudioItem.AudioItem;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.AudioItem.AudioStream;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.Directive;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toDisplay.PhoneTemplate;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toDisplay.ToDisplay;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.lang3.RandomUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.*;
+
+import static ai.qiwu.com.xiaoduhome.common.Constants.TTS_DIDI3_GET_XIAOAI;
+import static ai.qiwu.com.xiaoduhome.common.Constants.TTS_DIDI4_GET_XIAOAI;
+import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.*;
+import static ai.qiwu.com.xiaoduhome.service.ScheduleService.channel2Bots;
+import static ai.qiwu.com.xiaoduhome.service.ScheduleService.jiaoyouChannel2Bots;
+import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
+import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.PREFIX_USERID;
+import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.TTS.WAIT_WORD_3;
+import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.TTS.WELCOME_WORD_DEFAULT;
+
+/**
+ * @author 苗权威
+ * @dateTime 20-1-7 下午8:15
+ */
+@Service
+@Slf4j
+public class XiaoAiTestService {
+ private static final ConcurrentHashMap LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
+ public static final ConcurrentHashMap LAST_OUTTIME_MARK = new ConcurrentHashMap<>();
+// private static final ConcurrentHashMap LAST_AUDIO_PLAY = new ConcurrentHashMap<>();
+
+ public static final Byte OUTTIME_TYPE_0 = 0;
+ private static final Byte OUTTIME_TYPE_1 = 1;
+ private static final Byte OUTTIME_TYPE_2 = 2;
+
+ public static final String deviceId = "XIAOAI_nbNGwoZIS8AmRGVqHog==";//XIAOAI_nbNGwoZIS8AmRGVqHog==,XIAOAI_oIOWfYEFbZGFHB5DzoMA==
+
+ /**
+ * 处理不同意图,type为0则说明是启动,为1则说明是会话进行中,为2则说明用户退出
+ * @param request 封装请求信息
+ * @return 响应结果
+ */
+ public XiaoAiResponse getResponse(XiaoAiRequest request) {
+ String userId = getUserId(request);
+// String userId = "%2FScfTGmNbhn%2Fs8KXMJfZY4nQ%2F";
+ int type = request.getRequest().getType();
+ switch (type) {
+ case 0 : return dealWithLaunchRequest(request);
+ case 1 : return dealWithIntentRequest(request, userId);
+ case 2 : return dealWithEndRequest(userId, request.getType());
+ default: return buildTextResponse(SORRY_REPEAT);
+ }
+ }
+
+ /**
+ * 构建基础返回信息,注意is_session_end字段置为false,
+ * open_mic这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,若不主动打开则小爱在一次会话后退出技能。
+ * @return 小爱返回信息
+ */
+ private XiaoAiResponse buildResponse() {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(false);
+
+ Response responseInfo = new Response();
+ // 这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,
+ // 若不主动打开则小爱在一次会话后退出技能。
+ responseInfo.setOpen_mic(true);
+ response.setResponse(responseInfo);
+ return response;
+ }
+
+ private XiaoAiResponse buildLunchResponse(String text) {
+ XiaoAiResponse response = buildResponse();
+ Response responseInfo = response.getResponse();
+
+ ToDisplay toDisplay = new ToDisplay();
+// toDisplay.setType(3);
+ toDisplay.setUi_type("phone");
+
+ PhoneTemplate phoneTemplate = new PhoneTemplate();
+ phoneTemplate.setTemplate_name("smartNovelLunch");
+ Map params = new HashMap<>();
+ params.put("box0_title", "智能小说");
+ params.put("box0_subtitle","几十部精彩作品在等着你");
+ params.put("box0_text", text);
+ params.put("box0_image", "https://didi-gz4.jiaoyou365.com/duai/image/Loading.png");
+ phoneTemplate.setParams(params);
+ toDisplay.setPhone_template(phoneTemplate);
+ responseInfo.setTo_display(toDisplay);
+
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+
+ return response;
+ }
+
+ private XiaoAiResponse buildResponseBeforeLoadout(String text) {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(true);
+
+ Response responseInfo = new Response();
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+
+ response.setResponse(responseInfo);
+ return response;
+ }
+
+ /**
+ * 构建语音返回信息
+ * @param audioUrl 音频文件地址
+ * @return 小爱返回信息
+ */
+ private XiaoAiResponse buildAudioResponse(String audioUrl, JSONObject object) {
+ XiaoAiResponse response = buildResponse();
+ Response responseInfo = response.getResponse();
+
+ ToDisplay toDisplay = new ToDisplay();
+// toDisplay.setType(3);
+ toDisplay.setUi_type("phone");
+
+ PhoneTemplate phoneTemplate = new PhoneTemplate();
+ JSONArray array = object.getJSONArray("dialogs");
+ JSONObject job;
+ String actorUrl, text, actor, prefix, suffix;
+ int i = 0;
+ Map params = new HashMap<>();
+ for (Object ob: array) {
+ if (i == 4) break;
+ prefix = "box"+i;
+ job = (JSONObject)ob;
+ actor = job.getString("npcName");
+ actorUrl = ScheduleService.getAsideImgUrl(job.getString("botAccount"), actor);
+ text = job.getString("text");
+ if (StringUtils.isNotBlank(text)) {
+ text = text.replaceAll("\\{/.*?/}|\uD83C\uDD70|\uD83C\uDD71", "");
+ }
+ params.put(prefix+"_actor", actor);
+ params.put(prefix+"_text", text);
+ params.put(prefix+"_image", actorUrl);
+ i++;
+ }
+ switch (i) {
+ case 1: suffix = "One";break;
+ case 2: suffix = "Two";break;
+ case 3: suffix = "Thr";break;
+ case 4: suffix = "Four";break;
+ default: suffix = "One";
+ }
+ phoneTemplate.setParams(params);
+ phoneTemplate.setTemplate_name("smartNovelInt"+suffix);
+ toDisplay.setPhone_template(phoneTemplate);
+ responseInfo.setTo_display(toDisplay);
+
+ Directive directive = new Directive();
+ directive.setType("audio");
+ AudioItem audioItem = new AudioItem();
+ AudioStream audioStream = new AudioStream();
+ audioStream.setUrl(audioUrl);
+ audioItem.setStream(audioStream);
+ directive.setAudio_item(audioItem);
+ List directives = new ArrayList<>();
+ directives.add(directive);
+ responseInfo.setDirectives(directives);
+
+ return response;
+ }
+
+ /**
+ * 构建文字返回信息
+ * @param text 文字
+ * @return 小爱返回信息
+ */
+ private XiaoAiResponse buildTextResponse(String text) {
+ XiaoAiResponse response = buildResponse();
+ Response responseInfo = response.getResponse();
+
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+
+
+ return response;
+ }
+
+ private XiaoAiResponse buildCancelTextResponse(String text) {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(true);
+
+ Response responseInfo = new Response();
+ // 这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,
+ // 若不主动打开则小爱在一次会话后退出技能。
+ responseInfo.setOpen_mic(false);
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+ response.setResponse(responseInfo);
+
+ return response;
+ }
+
+ /**
+ * 处理启动意图,返回欢迎语
+ * @param request 请求信息
+ * @return 响应信息
+ */
+ private XiaoAiResponse dealWithLaunchRequest(XiaoAiRequest request) {
+// if (deviceId == null) {
+// deviceId = getUserId(request);
+// log.info("didi-gz3 deviceId:"+deviceId);
+// }
+ LAST_OUTTIME_RESULT.remove(getUserId(request));
+ LAST_OUTTIME_MARK.remove(getUserId(request));
+// LAST_AUDIO_PLAY.remove(getUserId(request));
+
+ String welcomeWord = null;
+ String num = RandomStringUtils.randomNumeric(3);
+ Integer type = request.getType();
+ switch (type) {
+ case 1 : {
+ welcomeWord = WELCOME_SMART_FORMAT_AI;
+ try {
+ List botList = channel2Bots.get("xiaoai-jiaoyou-audio-child-test");
+ String name = botList.get(Integer.parseInt(num)%botList.size());
+ welcomeWord = String.format(welcomeWord, name,name);
+ } catch (Exception e) {
+ log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+ welcomeWord = WELCOME_SMART;
+ }
+ break;
+ }
+ case 2 : {
+ welcomeWord = WELCOME_NOVEL_FORMAT;
+ try {
+ List botList = channel2Bots.get("xiaoai-jiaoyou-audio-adult-test");
+ String name = botList.get(Integer.parseInt(num)%botList.size());
+ welcomeWord = String.format(welcomeWord, name,name);
+ } catch (Exception e) {
+ log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+ welcomeWord = WELCOME_NOVEL;
+ }
+ break;
+ }
+ case 5 : {
+ welcomeWord = WELCOME_FORMAT;
+ try {
+ List botList = jiaoyouChannel2Bots.get("xiaoai-jiaoyou-audio-adult-test");
+ String name = botList.get(Integer.parseInt(num)%botList.size());
+ welcomeWord = String.format(welcomeWord, name,name);
+ } catch (Exception e) {
+ log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+ welcomeWord = WELCOME;
+ }
+ break;
+ }
+ }
+ if (welcomeWord == null) welcomeWord = WELCOME_WORD_DEFAULT;
+ return buildLunchResponse(welcomeWord);
+ }
+
+ /**
+ * 处理正常会话意图;
+ * 将任务提交线程池,监控其执行时间,若1.8s内没有返回则判为超时,提示用户稍等,下一次再将结果返回给用户
+ * @param request 请求信息
+ * @param userId 用户在小爱上的id
+ * @return 响应信息
+ */
+ private XiaoAiResponse dealWithIntentRequest(final XiaoAiRequest request, final String userId) {
+ Boolean idle = request.getRequest().getNo_response();
+ Byte waitType;
+ if ((waitType=LAST_OUTTIME_MARK.remove(userId)) != null) {
+ boolean firstTime = waitType == 0;
+ if (LAST_OUTTIME_RESULT.get(userId) == null) {
+ if (Boolean.TRUE.equals(idle)) {
+ if (firstTime) {
+ LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_1);
+ return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
+ XiaoAiConstants.TTS.WAIT_WORD_2);
+ } else {
+ LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_2);
+ return buildTextResponse(WAIT_WORD_3);
+ }
+ }
+ LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_0);
+ return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
+ XiaoAiConstants.TTS.WAIT_WORD_2);
+ }
+ return LAST_OUTTIME_RESULT.remove(userId);
+ }
+// String path;
+// if ((path = LAST_AUDIO_PLAY.get(userId)) != null) {
+// log.info(userId+": audio no play");
+// return buildAudioResponse(changeAudioUrl(path, userId));
+// }
+ if (Boolean.TRUE.equals(idle)) {
+ try {
+ //log.info("开始等待");
+ Thread.sleep(1700);
+ //log.info("等待OVER");
+ } catch (InterruptedException e) {
+ log.warn("等待中断");
+ }
+// XiaoAiResponse response = getLastResult(userId);
+// if (response != null) return response;
+ //log.info("用户没说话");
+ //return buildTextResponse(".");
+ return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.USER_IDLE :
+ XiaoAiConstants.TTS.ANOTHER_USER_IDLE);
+ }
+// XiaoAiResponse response = getLastResult(userId);
+// if (response != null) return response;
+ try {
+ Future future = DplbotServiceUtil.getPool().submit(() -> task(userId, request.getQuery(), request.getType()));
+ future.get(2200, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | ExecutionException e) {
+ log.error("获取任务执行结果出错:{}", e.toString());
+ return buildTextResponse(SORRY_REPEAT);
+ } catch (TimeoutException e) {
+ log.info("超时,让用户再说一遍:{}",e.toString());
+ LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_0);
+ return buildTextResponse(XiaoAiConstants.ERROR_MSG.TIME_OUT);
+ } catch (Exception all) {
+ log.error("任务执行发生了错误:{}", all.toString());
+ return buildTextResponse(SORRY_REPEAT);
+ }
+ return LAST_OUTTIME_RESULT.remove(userId);
+ }
+
+ /**
+ * 处理用户退出意图,先向中控发送“退出”,之后返回结束语
+ * @param userId 用户id
+ * @return 返回信息
+ */
+ private XiaoAiResponse dealWithEndRequest(String userId, Integer type) {
+// LAST_OUTTIME_MARK.remove(userId);
+// LAST_OUTTIME_RESULT.remove(userId);
+// LAST_AUDIO_PLAY.remove(userId);
+ RequestTerminal.backBotRequest(userId, type);
+ String byeWord;
+ switch (type) {
+ case 1: byeWord = Constants.EndMsg.END_BYE_STORY;break;
+ case 2: byeWord = Constants.EndMsg.END_BYE_NOVEL;break;
+ case 5: byeWord = Constants.EndMsg.END_BYE_JIAOYOU;break;
+ default: byeWord = Constants.EndMsg.END_BYE_DEFAULT;break;
+ }
+ return buildCancelTextResponse(byeWord);
+ }
+
+ /**
+ * 获取用户id
+ * @param request 请求信息
+ * @return 用户id
+ */
+ private String getUserId(XiaoAiRequest request) {
+ String userId = request.getSession().getUser().getUser_id();
+ if (userId == null) {
+ userId = request.getContext().getDevice_id();
+ if (userId != null) userId = Utils.modifyDeviceId(userId);
+ }
+ if (userId == null) {
+ userId = Utils.useIPAsItsID();
+ }
+ try {
+ return PREFIX_USERID+ URLEncoder.encode(userId, "UTF-8");
+ } catch (Exception e) {
+ return PREFIX_USERID+ userId.replaceAll("/", "");
+ }
+// return PREFIX_USERID+userId.replaceAll(NUM_OR_ALPHA, "");
+// return Utils.modifyDeviceId(userId);
+ }
+
+ private XiaoAiResponse getLastResult(String userId) {
+ return LAST_OUTTIME_RESULT.remove(userId);
+ }
+
+ private void task(String userId, String userWord, Integer type) {
+ XiaoAiResponse xiaoAiResponse;
+ if (userWord == null) {
+ log.warn("请求中没有带有用户的话");
+ throw new RequestWordNullException("user word can not be null");
+ }
+ String response;
+ try {
+ response = RequestTerminal.requestTerminate(userId, userWord, type);
+// log.info("小爱,小悟返回:{}", response);
+ } catch (Exception e) {
+ log.error("向终端发出的请求信息失败:{}", e.toString());
+ xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+ LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
+ return;
+ }
+ if (StringUtils.isBlank(response)) {
+ log.error("中控返回结果为空");
+ xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+ } else {
+ JSONObject object = JSON.parseObject(response);
+ try {
+// log.info(response);
+ JSONArray commands = object.getJSONArray("commands");
+ if (commands != null && commands.size() != 0) {
+ String txt;
+ for (Object ob: commands) {
+ txt = ((JSONObject) ob).getString("text");
+ int i;
+ if (StringUtils.isNotBlank(txt) && (i=txt.indexOf("out")) != -1) {
+ log.info("小爱,推荐bot退出:{},userId:{}", userWord, userId);
+ String content = txt.substring(i+3, txt.indexOf("☚")).trim();
+ String skillName, outWord;
+ switch (type) {
+ case 1: {
+ skillName = SKILL_SMART;
+ outWord = Constants.EndMsg.END_BYE_STORY;
+ break;
+ }
+ case 2: {
+ skillName = SKILL_NOVEL;
+ outWord = Constants.EndMsg.END_BYE_NOVEL;
+ break;
+ }
+ default: {
+ skillName = SKILL;
+ outWord = Constants.EndMsg.END_BYE_JIAOYOU;
+ }
+ }
+ RequestTerminal.backBotRequest(userId, type);
+ if (StringUtils.isNotBlank(content)) {
+ content = content.replaceAll("\\{/.*?/}", "")+skillName;
+ LAST_OUTTIME_RESULT.put(userId, buildResponseBeforeLoadout(content));
+ return;
+ } else {
+ JSONArray dialogs = object.getJSONArray("dialogs");
+ if (dialogs != null && dialogs.size() != 0) {
+ String str = ((JSONObject)dialogs.get(0)).getString("text");
+ if (StringUtils.isNotBlank(str)) {
+ str = str.replaceAll("\\{/.*?/}", "")+skillName;
+ LAST_OUTTIME_RESULT.put(userId, buildResponseBeforeLoadout(str));
+ return;
+ }
+ }
+ LAST_OUTTIME_RESULT.put(userId, buildResponseBeforeLoadout(outWord));
+ return;
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("推荐bot退出解析出错:"+e);
+ }
+
+ String path;
+ try {
+ path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
+ if (StringUtils.isBlank(path) || path.equals("null")) {
+ log.error("没有获取到TTS返回的路径path");
+ LAST_OUTTIME_RESULT.put(userId, buildTextResponse(SORRY_REPEAT));
+ return;
+ }
+ xiaoAiResponse = buildAudioResponse(changeAudioUrl(path, userId), object);
+// LAST_AUDIO_PLAY.put(userId, path);
+ } catch (Exception e) {
+ log.error("没有获取到TTS返回的路径path");
+ xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+ }
+ }
+ LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
+ }
+
+ private String changeAudioUrl(String path, String userId) {
+ path = path.replaceAll("%2F", "/");
+ return new StringBuilder(TTS_DIDI3_GET_XIAOAI).append(userId).append("&path=").append(path).toString();
+ }
+
+ private String changeAudioUrlTemp(String path, String userId) {
+ path = path.replaceAll("%2F", "/");
+// return new StringBuilder(TTS_DIDI4_GET_XIAOAI_STATIC).append(path.substring(path.indexOf("audio")+6)).toString();
+ return new StringBuilder(TTS_DIDI4_GET_XIAOAI).append(userId).append("&path=").append(path).toString();
+ }
+
+ public static void main(String[] args) throws UnsupportedEncodingException {
+ System.out.println("你\uD83C\uDD70挑战成功\uD83C\uDD71,皮皮再将{/dsfd/},皮皮".replaceAll("\\{/.*?/}|\uD83C\uDD70|\uD83C\uDD71", ""));
+ }
+}
diff --git a/xiaoduhome/src/main/resources/application.yml b/xiaoduhome/src/main/resources/application.yml
index 198d0aa..40159ea 100755
--- a/xiaoduhome/src/main/resources/application.yml
+++ b/xiaoduhome/src/main/resources/application.yml
@@ -1,5 +1,11 @@
server:
port: 8188
+ tomcat:
+# accesslog:
+# enabled: true
+# pattern: '%h %l %u %t "%r" %s %b bytes %D ms'
+# directory: /home/dc2-user/projects/audiobox/duai/tomcat
+ max-threads: 1024
spring:
datasource:
@@ -10,11 +16,13 @@ spring:
driver-class-name: com.mysql.cj.jdbc.Driver
secondary:
jdbc-url: jdbc:mysql://localhost:3306/audiobox?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
+# jdbc-url: jdbc:mysql://localhost:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root
password: 38A0O1jEPOE
driver-class-name: com.mysql.cj.jdbc.Driver
analysis:
jdbc-url: jdbc:mysql://localhost:3306/analysis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
+# jdbc-url: jdbc:mysql://localhost:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root
password: 38A0O1jEPOE
driver-class-name: com.mysql.cj.jdbc.Driver
@@ -27,6 +35,8 @@ spring:
output:
ansi:
enabled: detect
+ thymeleaf:
+ cache: false
logging:
path: /home/dc2-user/projects/audiobox/duai/logs
level:
diff --git a/xiaoduhome/src/main/resources/templates/ChatLog.html b/xiaoduhome/src/main/resources/templates/ChatLog.html
new file mode 100644
index 0000000..071f4a4
--- /dev/null
+++ b/xiaoduhome/src/main/resources/templates/ChatLog.html
@@ -0,0 +1,39 @@
+
+
+
+
+ 对话日志
+
+
+
+
+
+
+ 音箱
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/xiaoduhome/src/main/resources/templates/ChatLogChoose.html b/xiaoduhome/src/main/resources/templates/ChatLogChoose.html
new file mode 100644
index 0000000..a0d8c7c
--- /dev/null
+++ b/xiaoduhome/src/main/resources/templates/ChatLogChoose.html
@@ -0,0 +1,73 @@
+
+
+
+
+
+
+ CHAT LOG
+
+
+
+
+
+
+
+
显示指定类型的日志:
+
+
+ 音箱
+ 音箱-成人
+ 音箱-儿童
+ 小度
+ 小爱
+
+
+
+
+
+
点击搜索
+
+
+
+
+
+
\ No newline at end of file
diff --git a/xiaoduhome/src/main/resources/templates/LoadFailed.html b/xiaoduhome/src/main/resources/templates/LoadFailed.html
index f0f1ecb..31b2f1e 100755
--- a/xiaoduhome/src/main/resources/templates/LoadFailed.html
+++ b/xiaoduhome/src/main/resources/templates/LoadFailed.html
@@ -1,8 +1,8 @@
-
+
- Title
+ 登录
登录失败,请返回
diff --git a/xiaoduhome/src/main/resources/templates/Log5(1).html b/xiaoduhome/src/main/resources/templates/Log5(1).html
new file mode 100644
index 0000000..9c43f74
--- /dev/null
+++ b/xiaoduhome/src/main/resources/templates/Log5(1).html
@@ -0,0 +1,107 @@
+
+
+
+
+
+ 对话日志
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/xiaoduhome/src/main/resources/templates/Log5.html b/xiaoduhome/src/main/resources/templates/Log5.html
new file mode 100644
index 0000000..caa43a7
--- /dev/null
+++ b/xiaoduhome/src/main/resources/templates/Log5.html
@@ -0,0 +1,128 @@
+
+
+
+
+
+ 对话日志
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/xiaoduhome/src/main/resources/templates/LookLogLogin.html b/xiaoduhome/src/main/resources/templates/LookLogLogin.html
new file mode 100644
index 0000000..fbb6f2d
--- /dev/null
+++ b/xiaoduhome/src/main/resources/templates/LookLogLogin.html
@@ -0,0 +1,89 @@
+
+
+
+
+ 查看日志登录
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/xiaoduhome/src/main/resources/templates/index.html b/xiaoduhome/src/main/resources/templates/index.html
index 7a55629..4c26ec0 100644
--- a/xiaoduhome/src/main/resources/templates/index.html
+++ b/xiaoduhome/src/main/resources/templates/index.html
@@ -13,6 +13,7 @@
小度2号 (gz3)
小爱1号(gz3)
小爱2号(gz3)
+ 对话日志