Commit fa1dfaf3 by 苗权威

1.8

parent 35f456ef
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -122,6 +122,11 @@ public class SpiritController { ...@@ -122,6 +122,11 @@ public class SpiritController {
return "success"; return "success";
} }
@GetMapping("/del")
public void del(String filepath, Long skillId) {
spiritAudioUpload.deleteAudio(filepath, skillId);
}
@GetMapping("/get/csv") @GetMapping("/get/csv")
public void getCsv(String name, HttpServletResponse response) { public void getCsv(String name, HttpServletResponse response) {
String path = csvDic+name; String path = csvDic+name;
......
...@@ -35,6 +35,7 @@ import java.nio.file.StandardOpenOption; ...@@ -35,6 +35,7 @@ import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.stream.Collectors;
/** /**
* @author 苗权威 * @author 苗权威
...@@ -45,9 +46,14 @@ import java.util.regex.Matcher; ...@@ -45,9 +46,14 @@ import java.util.regex.Matcher;
public class SpiritAudioUpload { public class SpiritAudioUpload {
@Value("${csvDic}") @Value("${csvDic}")
private String 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="; @Value("${csvDicForBotChange}")
private volatile String csrfToken = "ThECcNhEBvJDLHL4AtCCWzqO"; 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) { public void updateCookie(String cookie) {
this.cookie = cookie; this.cookie = cookie;
// token=ol977BaL6nE1H5lss8t3Nx7G7LOB9n1S+S8mAlxsZnA=; // token=ol977BaL6nE1H5lss8t3Nx7G7LOB9n1S+S8mAlxsZnA=;
...@@ -133,8 +139,28 @@ public class SpiritAudioUpload { ...@@ -133,8 +139,28 @@ public class SpiritAudioUpload {
return null; 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<String> 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<String> ids, Long skillId) { private void deleteTheAudio(List<String> ids, Long skillId) {
log.error("要删除的id列表:"+ids); log.error("要删除的id列表:"+ids.size());
String url = "https://open.aligenie.com/api/custom/audios/delete"; String url = "https://open.aligenie.com/api/custom/audios/delete";
Map<String, String> headers = new HashMap<>(); Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json"); headers.put("Accept", "application/json");
...@@ -415,20 +441,22 @@ public class SpiritAudioUpload { ...@@ -415,20 +441,22 @@ public class SpiritAudioUpload {
preCsvPath = csvDic+preBotAccount+"_0.csv"; preCsvPath = csvDic+preBotAccount+"_0.csv";
} }
String csvPath; String csvPath;
String errorCsvPath;
if (preBotAccount.equals(botAccount)) { if (preBotAccount.equals(botAccount)) {
if (record) { if (record) {
csvPath = csvDic+botAccount+"_1_r.csv"; csvPath = csvDic+botAccount+"_1_r.csv";
} else { } else {
csvPath = csvDic+botAccount+"_0_r.csv"; csvPath = csvDic+botAccount+"_0_r.csv";
} }
errorCsvPath = csvDic+botAccount+"_error.csv";
} else { } else {
if (record) { if (record) {
csvPath = csvDic+botAccount+"_1.csv"; csvPath = csvDicForBotChange+botAccount+"_1.csv";
} else { } 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)) { if (Boolean.TRUE.equals(record)) {
// id -> DicUploadInfo // id -> DicUploadInfo
String mp3DataPath = "/root/TTS-service/audio/"+botAccount+"/record/"; String mp3DataPath = "/root/TTS-service/audio/"+botAccount+"/record/";
...@@ -501,6 +529,8 @@ public class SpiritAudioUpload { ...@@ -501,6 +529,8 @@ public class SpiritAudioUpload {
} }
} }
buildDicCsv(csvPath, oldDataList); 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 (dataNew.size() != 0) uploadNewData(dataNew, skillId, true, botAccount, csvPath, errorCsvPath, botName);
if (delIds.size() != 0) deleteTheAudio(delIds, skillId); if (delIds.size() != 0) deleteTheAudio(delIds, skillId);
} else { } else {
......
server: server:
port: 8188 port: 8189
logging: logging:
path: /home/dc2-user/projects/audiobox/spirit/logs path: /home/dc2-user/spirit/logs
level: level:
root: error root: error
csvDic: /home/dc2-user/audioBox/spirit/csv/ csvDic: /home/dc2-user/spirit/uploadCsv/
csvDicForBotChange: /home/dc2-user/spirit/fresh/
spring: spring:
......
...@@ -84,6 +84,13 @@ ...@@ -84,6 +84,13 @@
<systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath> <systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.tmall.spirit</groupId>
<artifactId>aliGenie</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/static/aliGenie-intent-sematic.jar</systemPath>
</dependency>
<dependency>
<groupId>ws.schild</groupId> <groupId>ws.schild</groupId>
<artifactId>jave-core</artifactId> <artifactId>jave-core</artifactId>
<version>2.7.1</version> <version>2.7.1</version>
......
...@@ -536,13 +536,18 @@ public class TTSUtils { ...@@ -536,13 +536,18 @@ public class TTSUtils {
// String command = "sox "+ StringUtils.join(filePathList, " "); // String command = "sox "+ StringUtils.join(filePathList, " ");
List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList()); if (filePathList.size() == 1) {
StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex "); String[] arr = filePathList.toArray(new String[]{});
for (int i = 0; i < filePathList.size(); i++) { Files.copy(Paths.get(arr[0]), Paths.get(targetFilepath));
builder.append("[").append(i).append(":a:0]"); } else {
List<String> 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); // filePathList.add(targetFilepath);
// CallPython.execute("sox "+ StringUtils.join(filePathList, " ")); // CallPython.execute("sox "+ StringUtils.join(filePathList, " "));
...@@ -656,6 +661,7 @@ public class TTSUtils { ...@@ -656,6 +661,7 @@ public class TTSUtils {
} }
public static void main(String[] args) throws IOException, UnsupportedAudioFileException { 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"));
} }
} }
...@@ -128,47 +128,71 @@ public class TTServiceUtil { ...@@ -128,47 +128,71 @@ public class TTServiceUtil {
} }
public static void buildMp3ResponseForAudio(HttpServletResponse response, String fileName, Boolean xiaoai, String range) { public static void buildMp3ResponseForAudio(HttpServletResponse response, String fileName, Boolean xiaoai, String range) {
response.setStatus(200);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName)); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
OutputStream out = new BufferedOutputStream(response.getOutputStream())){ OutputStream out = new BufferedOutputStream(response.getOutputStream())){
response.reset(); response.reset();
if (xiaoai) response.setStatus(206);
else response.setStatus(200);
response.setContentType("audio/mp3"); response.setContentType("audio/mp3");
// response.setHeader("Content-Type", "audio/mp3");
response.setHeader("Content-Type", "application/octet-stream");
int length = inputStream.available(); int length = inputStream.available();
// if (!Boolean.TRUE.equals(xiaoai)) {
// response.setHeader("Content-Length", String.valueOf(length));
// }
response.setHeader("Content-Length", String.valueOf(length)); response.setHeader("Content-Length", String.valueOf(length));
range = range.substring(range.indexOf("=")+1, range.indexOf("-")); if (xiaoai) {
String contentRange = "bytes "+range+"-"+length+"/"+length; response.setHeader("Content-Type", "application/octet-stream");
log.info("Content-Range:"+contentRange); range = range.substring(range.indexOf("=")+1, range.indexOf("-"));
response.setHeader("Content-Range", contentRange); String contentRange = "bytes "+range+"-"+length+"/"+length;
response.setHeader("Accept-Ranges", "bytes"); log.info("Content-Range:"+contentRange);
response.setHeader("icy-metaint", "8192"); 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"); // 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]; byte[] buffer = new byte[1024];
int ln; int ln;
while ((ln = inputStream.read(buffer)) != -1) { while ((ln = inputStream.read(buffer)) != -1) {
if (begin > 0) { out.write(buffer, 0, ln);
begin -= ln;
if (begin < 0) {
out.write(buffer, ln+begin, -begin);
}
} else {
out.write(buffer, 0, ln);
}
} }
out.flush(); 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 (ClientAbortException e) {
} catch (IOException e) { } catch (IOException e) {
......
...@@ -236,7 +236,8 @@ public class TTSController { ...@@ -236,7 +236,8 @@ public class TTSController {
@GetMapping("/api/audio/get") @GetMapping("/api/audio/get")
public void apiAudioGet(@RequestParam(required = false) String type, @RequestParam String path, public void apiAudioGet(@RequestParam(required = false) String type, @RequestParam String path,
HttpServletResponse response, HttpServletRequest request) { HttpServletResponse response) {
ttService.apiAudioGet(type, path, response, request); // ttService.apiAudioGet(type, path, response, request);
ttService.apiAudioGetNoRange(type, path, response);
} }
} }
...@@ -2084,11 +2084,11 @@ public class TTService { ...@@ -2084,11 +2084,11 @@ public class TTService {
if (xiaoAi) { if (xiaoAi) {
OkHttp3Utils.backPostAsync(audioUrl+type); OkHttp3Utils.backPostAsync(audioUrl+type);
} }
Enumeration enumeration = request.getHeaderNames(); // Enumeration enumeration = request.getHeaderNames();
while (enumeration.hasMoreElements()) { // while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement(); // String name = (String) enumeration.nextElement();
log.warn(name+":"+request.getHeader(name)); // log.warn(name+":"+request.getHeader(name));
} // }
String range = request.getHeader("range"); String range = request.getHeader("range");
if (Files.exists((pt = Paths.get(path)))) { if (Files.exists((pt = Paths.get(path)))) {
while (XIAOAI_MP3_MARK.contains(path)) { while (XIAOAI_MP3_MARK.contains(path)) {
...@@ -2114,6 +2114,36 @@ public class TTService { ...@@ -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) { public String apiAudio(ApiAudioData apiAudioData) {
List<Dialog> dialogs = apiAudioData.getDialogs(); List<Dialog> dialogs = apiAudioData.getDialogs();
// botname不能为空 // botname不能为空
......
...@@ -290,7 +290,7 @@ public class Test { ...@@ -290,7 +290,7 @@ public class Test {
Pattern pattern = Pattern.compile(TTSUtils.getAbRegex()); Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
String[] notVariableTextArray = pattern.split("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71"); String[] notVariableTextArray = pattern.split("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71");
System.out.println(notVariableTextArray.length);
System.out.println(Arrays.toString(notVariableTextArray)); System.out.println(TTSUtils.buildMP3Filename("为您推荐以上作品:《妖刀异闻录》、《小太阳》、《遇见伽利略》,你可以说:打开某作品"));
} }
} }
...@@ -132,6 +132,19 @@ ...@@ -132,6 +132,19 @@
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId> <artifactId>httpmime</artifactId>
</dependency> </dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/org.apache.commons/commons-text &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org.apache.commons</groupId>-->
<!--<artifactId>commons-text</artifactId>-->
<!--<version>1.8</version>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -7,8 +7,10 @@ package ai.qiwu.com.xiaoduhome.common; ...@@ -7,8 +7,10 @@ package ai.qiwu.com.xiaoduhome.common;
public interface Constants { public interface Constants {
String QI_WU_INTERFACE = "http://didi-gz3.jiaoyou365.com:8070/api/chat2"; 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 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_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_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 = "http://didi-gz4.jiaoyou365.com:9663/api/audio/get?type=";
String TTS_DIDI4_GET_XIAOAI_STATIC = "http://didi-gz4.jiaoyou365.com:9663/static/"; String TTS_DIDI4_GET_XIAOAI_STATIC = "http://didi-gz4.jiaoyou365.com:9663/static/";
...@@ -101,11 +103,18 @@ public interface Constants { ...@@ -101,11 +103,18 @@ public interface Constants {
} }
interface WelcomeWord { interface WelcomeWord {
String WELCOME = "欢迎来到交游天下,你可以说推荐作品给我"; String WELCOME = "欢迎来到交游天下。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";
String WELCOME_FORMAT = "欢迎来到交游天下。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的%s,您可以说打开%s。或者说,推荐其它作品。";
String SKILL = "交游天下"; 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 SKILL_SMART = "智能故事";
String WELCOME_NOVEL = "欢迎来到智能小说,你可以说推荐作品给我"; // 与剧情人物自由对话,带您体验不同的人生和情怀。
String WELCOME_NOVEL = "欢迎来到晓悟智能小说。向您推荐新上线的妖刀异闻录,您可以说打开妖刀异闻录。或者说,推荐其它作品。";
String WELCOME_NOVEL_FORMAT = "欢迎来到晓悟智能小说。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的%s,您可以说打开%s。或者说,推荐其它作品。";
String SKILL_NOVEL = "智能小说"; String SKILL_NOVEL = "智能小说";
String WELCOME_LITERATURE = "欢迎来到互动文艺,你可以说推荐作品给我"; String WELCOME_LITERATURE = "欢迎来到互动文艺,你可以说推荐作品给我";
String SKILL_LITERATURE = "互动文艺"; String SKILL_LITERATURE = "互动文艺";
...@@ -120,9 +129,15 @@ public interface Constants { ...@@ -120,9 +129,15 @@ public interface Constants {
interface EndMsg { interface EndMsg {
String BYE_BYE = "我们的作品库在不断的扩充,欢迎下次再来玩"; String BYE_BYE = "我们的作品库在不断的扩充,欢迎下次再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦"; 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 END_BYE_Adult = "再见啦,记得下次再来玩哦";
String CAN_NOT_UNDERSTAND = "用户无输入或多次输入无法理解"; String CAN_NOT_UNDERSTAND = "用户无输入或多次输入无法理解访问";
String USER_SAY_CANCEL = "用户直接说退出"; String USER_SAY_CANCEL = "用户直接说退出";
String BEFORE_LOAD_OUT = "如果您想退出我们的技能请对我说退出";
} }
interface ErrorMsg { interface ErrorMsg {
...@@ -160,7 +175,7 @@ public interface Constants { ...@@ -160,7 +175,7 @@ public interface Constants {
String FLOWER_INTERFACE = "http://aws-nx2.chewrobot.com:18082/api/flower/count"; 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_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 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 { interface BAI_DU {
...@@ -168,5 +183,4 @@ public interface Constants { ...@@ -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_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"; 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";
} }
} }
...@@ -160,6 +160,45 @@ public class OkHttp3Utils { ...@@ -160,6 +160,45 @@ public class OkHttp3Utils {
@Override @Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody body = response.body()){ 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()); log.info("退出成功:{}", body.string());
} catch (SocketTimeoutException e) { } catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString()); log.error("捕获到SocketTimeoutException:{}", e.toString());
......
package ai.qiwu.com.xiaoduhome.common; package ai.qiwu.com.xiaoduhome.common;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64; 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.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
...@@ -18,6 +20,7 @@ import java.util.Objects; ...@@ -18,6 +20,7 @@ import java.util.Objects;
* @author 苗权威 * @author 苗权威
* @dateTime 19-6-29 下午5:11 * @dateTime 19-6-29 下午5:11
*/ */
@Slf4j
public class Utils { public class Utils {
/** /**
...@@ -129,6 +132,126 @@ public class Utils { ...@@ -129,6 +132,126 @@ public class Utils {
return new Timestamp(new Date(curTimeMills).getTime()); 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 { public static void main(String[] args) throws ParseException {
String s = "[{\"type\": \"SendEvent\",\"componentId\":\"%s\"}]"; String s = "[{\"type\": \"SendEvent\",\"componentId\":\"%s\"}]";
//System.out.println(String.format(s, "gsagh")); //System.out.println(String.format(s, "gsagh"));
......
...@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.controller; ...@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.controller;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException; import org.apache.catalina.connector.ClientAbortException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
...@@ -41,6 +42,11 @@ public class AudioGetController { ...@@ -41,6 +42,11 @@ public class AudioGetController {
// } // }
// } // }
// @GetMapping("/audio/name/change")
// public void changeName(Integer ) {
//
// }
private void buildMp3Response(HttpServletResponse response, String fileName) { private void buildMp3Response(HttpServletResponse response, String fileName) {
response.setStatus(200); response.setStatus(200);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName)); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
......
...@@ -34,7 +34,7 @@ public class SpiritController { ...@@ -34,7 +34,7 @@ public class SpiritController {
*/ */
@PostMapping(value = "/") //交游天下 @PostMapping(value = "/") //交游天下
public ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) { public ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) {
log.info("天猫请求信息:{}",taskQuery); // log.info("天猫请求信息:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery); TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response // build response
...@@ -42,7 +42,7 @@ public class SpiritController { ...@@ -42,7 +42,7 @@ public class SpiritController {
TaskResult taskResult = spiritService.getResponse(query, 1); TaskResult taskResult = spiritService.getResponse(query, 1);
resultModel.setReturnCode("0"); resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult); resultModel.setReturnValue(taskResult);
log.info("天猫响应信息:"+ JSON.toJSONString(resultModel)); // log.info("天猫响应信息:"+ JSON.toJSONString(resultModel));
return resultModel; return resultModel;
} }
......
package ai.qiwu.com.xiaoduhome.controller; 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.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-11-18 下午6:37 * @dateTime 19-11-18 下午6:37
*/ */
@Controller //@Controller
@Slf4j
public class WebSocketLogController { public class WebSocketLogController {
private final ChatLogs chatLogs;
private static ConcurrentHashMap<String, LoginData> loadState = new ConcurrentHashMap<>();
@Autowired
public WebSocketLogController(ChatLogs chatLogs) {
this.chatLogs = chatLogs;
}
@GetMapping("/audio/index") @GetMapping("/audio/index")
public String logIndexPage(ModelMap modelMap) { public String logIndexPage(ModelMap modelMap) {
return "index.html"; return "index.html";
...@@ -36,6 +54,85 @@ public class WebSocketLogController { ...@@ -36,6 +54,85 @@ public class WebSocketLogController {
return "Log4.html"; 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<String, LoginData> 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 // eae846c7d1ca51474ebc7230ace47bf2.txt
@GetMapping("/aligenie/{name}") @GetMapping("/aligenie/{name}")
public String spirit(@PathVariable String name, ModelMap modelMap) { public String spirit(@PathVariable String name, ModelMap modelMap) {
......
package ai.qiwu.com.xiaoduhome.controller; 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.request.XiaoAiRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse; 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.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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RestController; 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 苗权威 * @author 苗权威
...@@ -18,60 +29,106 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -18,60 +29,106 @@ import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/xiaoai") @RequestMapping("/xiaoai")
@Slf4j @Slf4j
@RequiredArgsConstructor(onConstructor_={@Autowired})
public class XiaoAiController { public class XiaoAiController {
private final XiaoAiService xiaoAiService; private final XiaoAiService xiaoAiService;
private final XiaoAiTestService xiaoAiTestService;
@Autowired
public XiaoAiController(XiaoAiService xiaoAiService) {
this.xiaoAiService = xiaoAiService;
}
/** /**
* Controller控制器 * Controller控制器
* @param request * @param request
* @return * @return
*/ */
@RequestMapping("/") @PostMapping("/")
public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) { public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request,HttpServletRequest servletRequest) { // 交游天下
log.info("请求:"+request); log.info("请求:"+request);
XiaoAiResponse response = xiaoAiService.getResponse(request); // log.info("响应:"+response);
log.info("响应:"+response); try {
return response; 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); // return xiaoAiService.getResponse(request);
} }
@RequestMapping("/child") @PostMapping("/child")
public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request) { public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request,HttpServletRequest servletRequest) { // 智能故事
//log.info("请求:"+request); //log.info("请求:"+request);
request.setType(1); try {
XiaoAiResponse response = xiaoAiService.getResponse(request); if (!Utils.encry(1, servletRequest)) {
// log.info("响应:"+response); log.error("验证没通过:1");
return response; 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); // return xiaoAiService.getResponse(request);
} }
@RequestMapping("/story") //互动故事 @PostMapping("/story") //互动故事
public XiaoAiResponse xiaoaiChildStory(@RequestBody XiaoAiRequest request) { // @RequestBody XiaoAiRequest request,
//log.info("请求:"+request); public XiaoAiResponse xiaoaiChildStory(HttpServletRequest servletRequest) {
request.setType(3); // long start = System.currentTimeMillis();
XiaoAiResponse response = xiaoAiService.getResponse(request); // 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); // log.info("响应:"+response);
return response; // return response;
// return xiaoAiService.getResponse(request); // return xiaoAiService.getResponse(request);
} }
@RequestMapping("/adult") @PostMapping("/adult")
public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request) { public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request, HttpServletRequest servletRequest) { // 智能小说
//log.info("请求:"+request); //log.info("请求:"+request);
request.setType(2); try {
XiaoAiResponse response = xiaoAiService.getResponse(request); if (!Utils.encry(2, servletRequest)) {
// log.info("响应:"+response); log.error("验证没通过:2");
return response; 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); // return xiaoAiService.getResponse(request);
} }
@RequestMapping("/literature") // 互动文艺 // @PostMapping("/literature") // 互动文艺
public XiaoAiResponse xiaoaiAdultLiterature(@RequestBody XiaoAiRequest request) { public XiaoAiResponse xiaoaiAdultLiterature(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request); //log.info("请求:"+request);
request.setType(4); request.setType(4);
...@@ -85,8 +142,33 @@ public class XiaoAiController { ...@@ -85,8 +142,33 @@ public class XiaoAiController {
public void xiaoaiPlayed(String userId) { public void xiaoaiPlayed(String userId) {
if (StringUtils.isNotBlank(userId)) { if (StringUtils.isNotBlank(userId)) {
// log.info("小爱确认音频播放:"+userId); // log.info("小爱确认音频播放:"+userId);
xiaoAiService.changeAudioPlayMark(userId); // xiaoAiService.changeAudioPlayMark(userId);
} }
else log.error("/xiaoai/audio/play userId is null"); 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;
}
} }
...@@ -11,15 +11,22 @@ import com.alibaba.da.coin.ide.spi.standard.ResultModel; ...@@ -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.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult; import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.da.coin.ide.spi.trans.MetaFormat; import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils; import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.tags.HtmlEscapingAwareTag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
...@@ -32,36 +39,81 @@ import java.util.UUID; ...@@ -32,36 +39,81 @@ import java.util.UUID;
@Slf4j @Slf4j
public class XiaoDuHomeController { 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() { public String chat() {
HttpServletRequest request = null;
try { try {
//log.info("--------------分界线-------------------"); //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("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
log.info(service.getStrRequest()); // log.info(service.getStrRequest());
//service.disableVerify(); //service.disableVerify();
service.enableVerify(); service.enableVerify();
String str = service.run(); // log.info("响应信息:{}", str);
log.info("响应信息:{}", str); return service.run();
return str; } 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) { } catch (Exception e) {
e.printStackTrace(); log.error("交游:"+e);
//log.error("出现错误 "+e.toString()); //log.error("出现错误 "+e.toString());
} }
return null; return null;
} }
@RequestMapping("/story") //交互故事 @PostMapping("/story") //交互故事
public String story() { public String story() {
try { try {
//log.info("--------------分界线-------------------"); //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("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
// log.info(service.getStrRequest()); log.info(service.getStrRequest());
//service.disableVerify(); //service.disableVerify();
service.enableVerify(); service.enableVerify();
String str = service.run(); String str = service.run();
// log.info("响应信息:{}", str); log.info("响应信息:{}", str);
return str; return str;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -70,7 +122,7 @@ public class XiaoDuHomeController { ...@@ -70,7 +122,7 @@ public class XiaoDuHomeController {
return null; return null;
} }
@RequestMapping("/literature") // 互动文艺 // @PostMapping("/literature") // 互动文艺
public String literature() { public String literature() {
try { try {
//log.info("--------------分界线-------------------"); //log.info("--------------分界线-------------------");
...@@ -89,7 +141,12 @@ public class XiaoDuHomeController { ...@@ -89,7 +141,12 @@ public class XiaoDuHomeController {
return null; return null;
} }
@RequestMapping("/smart") // 智能故事 @RequestMapping(value = "/smart", method = RequestMethod.HEAD)
public void smartHead(HttpServletResponse response) {
response.setStatus(200);
}
@PostMapping("/smart") // 智能故事
public String smart() { public String smart() {
try { try {
//log.info("--------------分界线-------------------"); //log.info("--------------分界线-------------------");
...@@ -98,17 +155,22 @@ public class XiaoDuHomeController { ...@@ -98,17 +155,22 @@ public class XiaoDuHomeController {
// log.info(service.getStrRequest()); // log.info(service.getStrRequest());
//service.disableVerify(); //service.disableVerify();
service.enableVerify(); service.enableVerify();
String str = service.run(); // log.info("响应信息:{}", str);
// log.info("响应信息:{}", str); return service.run();
return str; } catch (MismatchedInputException ex) {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("smart:"+e);
//log.error("出现错误 "+e.toString()); //log.error("出现错误 "+e.toString());
} }
return null; return null;
} }
@RequestMapping("/novel") // 智能小说 @RequestMapping(value = "/novel", method = RequestMethod.HEAD)
public void novelHead(HttpServletResponse response) {
response.setStatus(200);
}
@PostMapping("/novel") // 智能小说
public String novel() { public String novel() {
try { try {
//log.info("--------------分界线-------------------"); //log.info("--------------分界线-------------------");
...@@ -117,11 +179,11 @@ public class XiaoDuHomeController { ...@@ -117,11 +179,11 @@ public class XiaoDuHomeController {
// log.info(service.getStrRequest()); // log.info(service.getStrRequest());
//service.disableVerify(); //service.disableVerify();
service.enableVerify(); service.enableVerify();
String str = service.run(); // log.info("响应信息:{}", str);
// log.info("响应信息:{}", str); return service.run();
return str; } catch (MismatchedInputException ex) {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("novel:"+e);
//log.error("出现错误 "+e.toString()); //log.error("出现错误 "+e.toString());
} }
return null; return null;
......
...@@ -31,6 +31,9 @@ public class GameProjectTb { ...@@ -31,6 +31,9 @@ public class GameProjectTb {
@Column @Column
private Long watch; private Long watch;
// @Column(name = "work_type")
// private Long workType;
@Column(name = "banner_img_url") @Column(name = "banner_img_url")
private String bannerImgUrl; private String bannerImgUrl;
......
...@@ -35,6 +35,9 @@ public class OnProductDetail { ...@@ -35,6 +35,9 @@ public class OnProductDetail {
@Column @Column
private Float score; private Float score;
@Column(name = "work_type")
private Long workType;
@Column(name = "banner_img_url") @Column(name = "banner_img_url")
private String bannerImgUrl; private String bannerImgUrl;
......
...@@ -20,5 +20,5 @@ import java.util.Map; ...@@ -20,5 +20,5 @@ import java.util.Map;
public class OverTimeDetail { public class OverTimeDetail {
private final List<Directive> directives = new ArrayList<>(); private final List<Directive> directives = new ArrayList<>();
private final Map<String, String> attributes = new HashMap<>(); private final Map<String, String> attributes = new HashMap<>();
private Response response = new Response(); private volatile Response response = new Response();
} }
...@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.repository.primary; ...@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.repository.primary;
import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail; import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
...@@ -14,4 +15,9 @@ import java.util.List; ...@@ -14,4 +15,9 @@ import java.util.List;
public interface AllOnProductInfoRepository extends JpaRepository<OnProductDetail, Long> { public interface AllOnProductInfoRepository extends JpaRepository<OnProductDetail, Long> {
List<OnProductDetail> findAllByApplyStatusAndScoreNot(Integer applyStatus, Float score); List<OnProductDetail> findAllByApplyStatusAndScoreNot(Integer applyStatus, Float score);
List<OnProductDetail> findAllByApplyStatusAndWorkType(Integer applyStatus, Long workType);
@Query(value = "select name from game_project_tb where apply_status=1 and work_type=27",nativeQuery = true)
List<String> findNameByApplyStatusAndWorkType(Integer applyStatus, Long workType);
} }
...@@ -29,6 +29,6 @@ public interface GameProjectTbRepository extends JpaRepository<GameProjectTb, Lo ...@@ -29,6 +29,6 @@ public interface GameProjectTbRepository extends JpaRepository<GameProjectTb, Lo
@Query(value = "select id,intro,name,watch,banner_img_url,apply_status,bot_account,user_nickname,score from game_project_tb where apply_status = 1 order by watch desc limit ?1,8", nativeQuery = true) @Query(value = "select id,intro,name,watch,banner_img_url,apply_status,bot_account,user_nickname,score from game_project_tb where apply_status = 1 order by watch desc limit ?1,8", nativeQuery = true)
List<GameProjectTb> postRankBot(Integer begin); List<GameProjectTb> 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<String> getAllOnTableProductIds(); List<String> getAllOnTableProductIds();
} }
...@@ -10,7 +10,6 @@ import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoDocument; ...@@ -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.productInfo.ProductInfoUtils;
import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommandDocument; import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommandDocument;
import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommendUtil; 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.primary.*;
import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB; import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB;
import ai.qiwu.com.xiaoduhome.pojo.*; import ai.qiwu.com.xiaoduhome.pojo.*;
...@@ -54,20 +53,17 @@ import org.apache.commons.lang3.RandomStringUtils; ...@@ -54,20 +53,17 @@ import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils; 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 javax.servlet.http.HttpServletRequest;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.net.URLEncoder;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static ai.qiwu.com.xiaoduhome.common.Constants.*; 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.DPL_COMPONENT_ID.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.ErrorMsg.*; import static ai.qiwu.com.xiaoduhome.common.Constants.ErrorMsg.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.*; import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.*;
...@@ -100,7 +96,7 @@ public class DplBotService extends BaseBot { ...@@ -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 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; private final int type;
...@@ -109,51 +105,96 @@ public class DplBotService extends BaseBot { ...@@ -109,51 +105,96 @@ public class DplBotService extends BaseBot {
public DplBotService(HttpServletRequest request, Integer type) throws IOException { public DplBotService(HttpServletRequest request, Integer type) throws IOException {
super(request); super(request);
this.type = type; this.type = type;
//privateKey为私钥内容,0代表你的Bot在DBP平台debug环境,1或者其他整数代表online环境,
// botMonitor对象已经在bot-sdk里初始化,可以直接调用
this.botMonitor.setEnvironmentInfo(PRIVATE_KEY, 1);
// this.botMonitor.setMonitorEnabled(true);
} }
@Override @Override
public Response onLaunch(LaunchRequest launchRequest) { public Response onLaunch(LaunchRequest launchRequest) {
if (getRequest().getContext().getScreen() == null) { if (getRequest().getContext().getScreen() == null) {
String deviceId = PREFIX_USERID+getDeviceId(); String userId = customUserId();
LAST_OUTTIME_MARK.remove(deviceId); LAST_OUTTIME_MARK.remove(userId);
LAST_OUTTIME_RESULT.remove(deviceId); LAST_OUTTIME_RESULT.remove(userId);
USERID_AUDIO_PATH.remove(deviceId); USERID_AUDIO_PATH.remove(userId);
String welcomeWord; String welcomeWord;
String skillName; String skillName;
String num = RandomStringUtils.randomNumeric(3);
switch (type) { switch (type) {
case 1 : welcomeWord = WelcomeWord.WELCOME_SMART; skillName = SKILL_SMART; break; case 1 : {
case 2 : welcomeWord = WelcomeWord.WELCOME_NOVEL; skillName = SKILL_NOVEL; break; // welcomeWord = WELCOME_SMART_FORMAT;
// try {
// List<String> 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<String> 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 3 : welcomeWord = WelcomeWord.WELCOME_STORY; skillName = SKILL_STORY; break;
case 4 : welcomeWord = WelcomeWord.WELCOME_LITERATURE; skillName = SKILL_LITERATURE; break; case 4 : welcomeWord = WelcomeWord.WELCOME_LITERATURE; skillName = SKILL_LITERATURE; break;
default: welcomeWord = WelcomeWord.WELCOME; skillName = SKILL; break; default: {
welcomeWord = WELCOME_FORMAT;
try {
List<String> 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 standardCard = new StandardCard(skillName, welcomeWord);
standardCard.setImage(FIRST_IMAGE); standardCard.setImage(FIRST_IMAGE);
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord); OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord);
return new Response(outputSpeech, standardCard); return new Response(outputSpeech, standardCard);
} else {
return new Response();
} }
RenderDocument renderDocument = new RenderDocument(FIRST_PAGE); // RenderDocument renderDocument = new RenderDocument(FIRST_PAGE);
this.addDirective(renderDocument); // this.addDirective(renderDocument);
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, Constants.WelcomeWord.WELCOME); // OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, Constants.WelcomeWord.WELCOME);
// 初次进入时创建用户的行为信息,包括历史记录,送花数,收藏记录 // // 初次进入时创建用户的行为信息,包括历史记录,送花数,收藏记录
// 历史记录,收藏记录,送花数,郊游天下id // // 历史记录,收藏记录,送花数,郊游天下id
if (DplbotServiceUtil.USER_HISTORY.get(getUserId()) == null) { // if (DplbotServiceUtil.USER_HISTORY.get(getUserId()) == null) {
String accessToken = getAccessToken(); // String accessToken = getAccessToken();
if (accessToken != null) setSessionAttribute("userId", DplbotServiceUtil.getUserIdByToken(accessToken)); // if (accessToken != null) setSessionAttribute("userId", DplbotServiceUtil.getUserIdByToken(accessToken));
DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, getUserId()); // DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, getUserId());
} // }
return new Response(outputSpeech); // return new Response(outputSpeech);
} }
@Override @Override
protected Response onInent(IntentRequest intentRequest) { protected Response onInent(IntentRequest intentRequest) {
final String userId = getUserId(); final String userId = customUserId();
if (getRequest().getContext().getScreen() == null) { if (getRequest().getContext().getScreen() == null) {
final String deviceUserId = PREFIX_USERID + getDeviceId(); // final String deviceUserId = PREFIX_USERID + getDeviceId();
Byte overTimeType; Byte overTimeType;
String path; String path;
if ((overTimeType = LAST_OUTTIME_MARK.remove(deviceUserId)) != null) { if ((overTimeType = LAST_OUTTIME_MARK.remove(userId)) != null) {
OverTimeDetail lastData = LAST_OUTTIME_RESULT.get(deviceUserId); OverTimeDetail lastData = LAST_OUTTIME_RESULT.get(userId);
if (lastData != null) { if (lastData != null) {
for (Directive directive : lastData.getDirectives()) { for (Directive directive : lastData.getDirectives()) {
//log.info("上次超时保存的Directive:{}",directive.getClass().getName()); //log.info("上次超时保存的Directive:{}",directive.getClass().getName());
...@@ -163,89 +204,91 @@ public class DplBotService extends BaseBot { ...@@ -163,89 +204,91 @@ public class DplBotService extends BaseBot {
//log.info("上次超时保存的key:{}",key); //log.info("上次超时保存的key:{}",key);
this.setSessionAttribute(entry.getKey(), entry.getValue()); this.setSessionAttribute(entry.getKey(), entry.getValue());
} }
LAST_OUTTIME_MARK.remove(deviceUserId); LAST_OUTTIME_MARK.remove(userId);
LAST_OUTTIME_RESULT.remove(deviceUserId); LAST_OUTTIME_RESULT.remove(userId);
return lastData.getResponse(); return lastData.getResponse();
} }
if (overTimeType != 3) { 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 : return buildErrorResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2); XiaoAiConstants.TTS.WAIT_WORD_2);
} }
LAST_OUTTIME_MARK.remove(deviceUserId); LAST_OUTTIME_MARK.remove(userId);
} else if ((path = USERID_AUDIO_PATH.get(deviceUserId)) != null) { } else if ((path = USERID_AUDIO_PATH.get(userId)) != null) {
Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL); Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
addDirective(play); addDirective(play);
log.error("小度音频播放开始事件未被触发:"+path); // log.error("小度音频播放开始事件未被触发:"+path);
dealWithFinishedNoCallEvent(deviceUserId); // dealWithFinishedNoCallEvent(userId);
return new Response(); return new Response();
} }
try { try {
Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, deviceUserId)); Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId));
future.get(2700, TimeUnit.MILLISECONDS); future.get(2700, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e)); log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
return buildErrorResponse(SORRY_UNCATCH); return buildErrorResponse(SORRY_UNCATCH);
} catch (TimeoutException e) { } catch (TimeoutException e) {
log.info("超时,让用户再说一遍:{}",e.toString()); log.info("超时,让用户再说一遍:{}",e.toString());
LAST_OUTTIME_MARK.put(deviceUserId, OUTTIME_TYPE_0); LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_0);
return buildErrorResponse(SORRY_UNCATCH); return buildErrorResponse(SORRY_UNCATCH);
} catch (Exception all) { } catch (Exception all) {
log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all)); log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
return buildErrorResponse(SORRY_UNCATCH); return buildErrorResponse(SORRY_UNCATCH);
} }
OverTimeDetail detail; 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(); 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 { } else {
DplbotServiceUtil.getPOOL().submit(() -> { return new Response();
WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du2");
});
} }
// 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) { private void dealNoScreenIntentTemp(IntentRequest intentRequest, String userId) {
String intentName = getIntent().getName(); String intentName = getIntent().getName();
OverTimeDetail data = new OverTimeDetail(); OverTimeDetail data = new OverTimeDetail();
...@@ -291,13 +334,22 @@ public class DplBotService extends BaseBot { ...@@ -291,13 +334,22 @@ public class DplBotService extends BaseBot {
final String userWord = query.getOriginal(); final String userWord = query.getOriginal();
// if (query != null) userWord = query.getOriginal(); // if (query != null) userWord = query.getOriginal();
if (userWord == null){ if (userWord == null){
log.warn("小度没有传来任何话语"); log.error("小度没有传来任何话语");
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH)); data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
return; return;
} }
log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId()); // log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId());
String response = RequestTerminal.requestTerminateTemp(userWord, userId, type);
log.info("小度,小悟返回:{},",response); 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)) { if (StringUtils.isBlank(response)) {
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH)); data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
return; return;
...@@ -305,47 +357,106 @@ public class DplBotService extends BaseBot { ...@@ -305,47 +357,106 @@ public class DplBotService extends BaseBot {
// String mark = RandomStringUtils.randomAlphabetic(3); // String mark = RandomStringUtils.randomAlphabetic(3);
// AudioBoxData pathData = new AudioBoxData(); // AudioBoxData pathData = new AudioBoxData();
// OkHttp3Utils.asyncPost(XiaoAiConstants.TTS_DIDI3, response, pathData); // 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); 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("小度没有获取到音频链接"); log.error("小度没有获取到音频链接");
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH)); data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
return; return;
} }
final JSONObject ob = JSONObject.parseObject(response); // final JSONObject ob = JSONObject.parseObject(response);
String botAcc = ob.getString("aipioneerUsername"); // String botAcc = ob.getString("aipioneerUsername");
String beforeBotAccount = getSessionAttribute("botAcc"); // String beforeBotAccount = getSessionAttribute("botAcc");
if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(botAcc)) { // if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(botAcc)) {
setSessionAttribute("botAcc", botAcc); // setSessionAttribute("botAcc", botAcc);
data.getAttributes().put("botAcc",botAcc); // data.getAttributes().put("botAcc",botAcc);
} // }
Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL); Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
addDirective(play); addDirective(play);
data.getDirectives().add(play); data.getDirectives().add(play);
USERID_AUDIO_PATH.put(userId, path); USERID_AUDIO_PATH.put(userId, path);
if (userId.equals(DU_DEVICE_ID)) { // if (userId.equals(DU_DEVICE_ID)) {
DplbotServiceUtil.getPOOL().submit(() -> { // DplbotServiceUtil.getPOOL().submit(() -> {
JSONArray array = ob.getJSONArray("dialogs"); // JSONArray array = ob.getJSONArray("dialogs");
StringBuilder builder = new StringBuilder(userWord).append(File.separator); // StringBuilder builder = new StringBuilder(userWord).append(File.separator);
for (Object item: array) { // for (Object item: array) {
String str = ((JSONObject) item).getString("text"); // String str = ((JSONObject) item).getString("text");
builder.append(str.replaceAll("\\{/.*?/}", "")).append(";"); // builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
} // }
WebSocketLog.sendInfo(builder.toString(), "du1"); // WebSocketLog.sendInfo(builder.toString(), "du1");
}); // });
} else { // } else {
DplbotServiceUtil.getPOOL().submit(() -> { // DplbotServiceUtil.getPOOL().submit(() -> {
JSONArray array = ob.getJSONArray("dialogs"); // JSONArray array = ob.getJSONArray("dialogs");
StringBuilder builder = new StringBuilder(userWord).append(File.separator); // StringBuilder builder = new StringBuilder(userWord).append(File.separator);
for (Object item: array) { // for (Object item: array) {
String str = ((JSONObject) item).getString("text"); // String str = ((JSONObject) item).getString("text");
builder.append(str.replaceAll("\\{/.*?/}", "")).append(";"); // builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
} // }
WebSocketLog.sendInfo(builder.toString(), "du2"); // WebSocketLog.sendInfo(builder.toString(), "du2");
}); // });
} // }
} catch (Exception e) { } catch (Exception e) {
log.warn("中控返回结果为空"); log.warn("中控返回结果为空:"+e);
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH)); data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
} }
finally { finally {
...@@ -360,6 +471,7 @@ public class DplBotService extends BaseBot { ...@@ -360,6 +471,7 @@ public class DplBotService extends BaseBot {
private String dealAudioUrl(String path) { private String dealAudioUrl(String path) {
return Constants.TTS_DIDI3_GET+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) { private void dealNoScreenSendFlowerIntent(String userId, OverTimeDetail data) {
...@@ -672,25 +784,28 @@ public class DplBotService extends BaseBot { ...@@ -672,25 +784,28 @@ public class DplBotService extends BaseBot {
case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break; case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break;
} }
if (getRequest().getContext().getScreen() == null) { if (getRequest().getContext().getScreen() == null) {
String deviceId = PREFIX_USERID+getDeviceId(); String userId = customUserId();
LAST_OUTTIME_MARK.remove(deviceId); // LAST_OUTTIME_MARK.remove(userId);
LAST_OUTTIME_RESULT.remove(deviceId); // LAST_OUTTIME_RESULT.remove(userId);
USERID_AUDIO_PATH.remove(deviceId); // USERID_AUDIO_PATH.remove(userId);
String byeWord = EndMsg.END_BYE_Adult; String byeWord = EndMsg.END_BYE_Adult;
switch (type) { 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 3: byeWord = EndMsg.END_BYE_CHILD;break;
case 5: byeWord = EndMsg.END_BYE_JIAOYOU;break;
} }
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord); OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
try { RequestTerminal.backRequest(userId, type);
if (DU_DEVICE_ID.equals(deviceId)) { // try {
RequestTerminal.backRequest(DU_DEVICE_ID, type); // if (DU_DEVICE_ID.equals(deviceId)) {
} else { // RequestTerminal.backRequest(DU_DEVICE_ID, type);
RequestTerminal.backRequestDU2(deviceId, type); // } else {
} // RequestTerminal.backRequestDU2(deviceId, type);
} catch (Exception e) { // }
log.warn("用户退出向中控发出退出指令出错"); // } catch (Exception e) {
} // log.warn("用户退出向中控发出退出指令出错");
// }
return new Response(outputSpeech); return new Response(outputSpeech);
} }
DplbotServiceUtil.writeTheUserHistoryInData(getUserId()); DplbotServiceUtil.writeTheUserHistoryInData(getUserId());
...@@ -897,6 +1012,12 @@ public class DplBotService extends BaseBot { ...@@ -897,6 +1012,12 @@ public class DplBotService extends BaseBot {
return new Response(outputSpeech); 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) { private Response buildNoScreenListCardResponse(String content, String botAccount) {
Pattern pattern = Pattern.compile(Utils.getRegexSeperate()); Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
List<String> actors = DplbotServiceUtil.seperateActor(content, pattern); List<String> actors = DplbotServiceUtil.seperateActor(content, pattern);
...@@ -2202,7 +2323,7 @@ public class DplBotService extends BaseBot { ...@@ -2202,7 +2323,7 @@ public class DplBotService extends BaseBot {
final String botAccount = token.substring(0, sepIndex); final String botAccount = token.substring(0, sepIndex);
String str = "恭喜您支付成功,开始体验吧"; String str = "恭喜您支付成功,开始体验吧";
if (getRequest().getContext().getScreen() != null) { 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"); getSessionAttribute("userId"), PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_screen");
if (response) { if (response) {
HashMap<String, Long> flowerRecords = DplbotServiceUtil.USER_HISTORY.get(getUserId()).getUserBotId2Flowers(); HashMap<String, Long> flowerRecords = DplbotServiceUtil.USER_HISTORY.get(getUserId()).getUserBotId2Flowers();
...@@ -2224,7 +2345,7 @@ public class DplBotService extends BaseBot { ...@@ -2224,7 +2345,7 @@ public class DplBotService extends BaseBot {
str = "很抱歉,您没有支付成功"; str = "很抱歉,您没有支付成功";
} }
} else { } else {
String userId = getDeviceId(); String userId = customUserId();
String jytUserId = getSessionAttribute("userId"); String jytUserId = getSessionAttribute("userId");
if (StringUtils.isBlank(jytUserId)) jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken()); if (StringUtils.isBlank(jytUserId)) jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken());
if (StringUtils.isBlank(jytUserId)) { if (StringUtils.isBlank(jytUserId)) {
...@@ -2244,7 +2365,7 @@ public class DplBotService extends BaseBot { ...@@ -2244,7 +2365,7 @@ public class DplBotService extends BaseBot {
// log.info("音频播放完毕,开麦"); // log.info("音频播放完毕,开麦");
// setSessionAttribute("botAcc",getSessionAttribute("botAcc")); // setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
this.setExpectSpeech(true); this.setExpectSpeech(true);
log.error("FinishedEvent"); // log.error("FinishedEvent");
return new Response(); return new Response();
} }
...@@ -2258,7 +2379,7 @@ public class DplBotService extends BaseBot { ...@@ -2258,7 +2379,7 @@ public class DplBotService extends BaseBot {
@Override @Override
protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) { protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
// setSessionAttribute("botAcc",getSessionAttribute("botAcc")); // setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
USERID_AUDIO_PATH.remove(PREFIX_USERID + getDeviceId()); USERID_AUDIO_PATH.remove(customUserId());
waitAnswer(); waitAnswer();
return new Response(); return new Response();
} }
...@@ -2269,4 +2390,14 @@ public class DplBotService extends BaseBot { ...@@ -2269,4 +2390,14 @@ public class DplBotService extends BaseBot {
waitAnswer(); waitAnswer();
return new Response(); 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, "");
}
} }
...@@ -7,12 +7,20 @@ import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest; ...@@ -7,12 +7,20 @@ import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest;
import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse; import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse;
import ai.qiwu.com.xiaoduhome.pojo.playAside.AsideImageResponse; import ai.qiwu.com.xiaoduhome.pojo.playAside.AsideImageResponse;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest; 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 com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Random; import java.util.Random;
...@@ -23,7 +31,7 @@ import java.util.Random; ...@@ -23,7 +31,7 @@ import java.util.Random;
@Slf4j @Slf4j
class RequestTerminal { 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(); SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
requestPojo.setMsg(userWord); requestPojo.setMsg(userWord);
...@@ -31,14 +39,33 @@ class RequestTerminal { ...@@ -31,14 +39,33 @@ class RequestTerminal {
// log.info("向小悟发送的请求信息:{}", requestJsonStr); // log.info("向小悟发送的请求信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8"); headers.put("Content-Type", "application/json;charset=utf-8");
switch (type) { headers.put("App-Channel-Id", channel);
case 1 : // String ip = Utils.getRemoteIpByServletRequest(request);
case 3 : headers.put("App-Channel-Id", "jiaoyou-audio-child-test");break; // if (StringUtils.isNotBlank(ip)) {
case 2 : // headers.put("ip", ip);
case 4 : headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");break; // if (test++ < 5) {
default: headers.put("App-Channel-Id", "jiaoyou-audio-test"); // 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(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 { static QiWuResponse requestTerminate(String userWord, String userId, int type) throws IOException {
...@@ -86,11 +113,11 @@ class RequestTerminal { ...@@ -86,11 +113,11 @@ class RequestTerminal {
} }
static void backRequest(String userId, int type) { static void backRequest(String userId, int type) {
QiWuRequest requestPojo = new QiWuRequest(); SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME); requestPojo.setMsg("退出");
requestPojo.setMsg("退出当前作品");
String requestJsonStr = JSON.toJSONString(requestPojo); 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); OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr, type);
} }
......
...@@ -26,6 +26,7 @@ import org.springframework.beans.factory.InitializingBean; ...@@ -26,6 +26,7 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
...@@ -77,6 +78,13 @@ public class ScheduleService implements InitializingBean { ...@@ -77,6 +78,13 @@ public class ScheduleService implements InitializingBean {
public static volatile Map<String, String> channelId2RecommendBotAcc = new HashMap<>(); public static volatile Map<String, String> channelId2RecommendBotAcc = new HashMap<>();
public static volatile Map<String, List<String>> channel2Bots = new HashMap<>();
public static volatile Map<String, List<String>> 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 @Autowired
public ScheduleService(GameProjectTbRepository gameProjectTbRepository, public ScheduleService(GameProjectTbRepository gameProjectTbRepository,
ProjectLabelRepository projectLabelRepository, ProjectLabelRepository projectLabelRepository,
...@@ -90,6 +98,14 @@ public class ScheduleService implements InitializingBean { ...@@ -90,6 +98,14 @@ public class ScheduleService implements InitializingBean {
this.xiaoDuOrderTbRepository = xiaoDuOrderTbRepository; this.xiaoDuOrderTbRepository = xiaoDuOrderTbRepository;
} }
// @Scheduled(cron = "* */10 * * * ?")
// public void updateTheWelcomeName() {
// DplbotServiceUtil.POOL.submit(() -> {
// List<OnProductDetail> onlinedProject = allOnProductInfoRepository.findAllByApplyStatusAndWorkType(1,27L);
//
// });
// }
@Scheduled(cron = "0 */30 * * * ?") @Scheduled(cron = "0 */30 * * * ?")
public void cleatUserBehaviorData() { public void cleatUserBehaviorData() {
DplbotServiceUtil.POOL.submit(() -> { DplbotServiceUtil.POOL.submit(() -> {
...@@ -126,7 +142,7 @@ public class ScheduleService implements InitializingBean { ...@@ -126,7 +142,7 @@ public class ScheduleService implements InitializingBean {
}); });
} }
@Scheduled(cron = "*/10 * * * * ?") // @Scheduled(cron = "*/10 * * * * ?")
public void updateTheCurTime() { public void updateTheCurTime() {
DplbotServiceUtil.POOL.submit(() -> curTime = System.currentTimeMillis()); DplbotServiceUtil.POOL.submit(() -> curTime = System.currentTimeMillis());
} }
...@@ -141,7 +157,7 @@ public class ScheduleService implements InitializingBean { ...@@ -141,7 +157,7 @@ public class ScheduleService implements InitializingBean {
//log.error("更新排行榜出错:{}", e.getMessage()); //log.error("更新排行榜出错:{}", e.getMessage());
} }
@Scheduled(cron = "0 0 */1 * * ?") @Scheduled(cron = "0 0 */2 * * ?")
public void initRecommendList() { public void initRecommendList() {
new Thread(() -> { new Thread(() -> {
RECOMMEND_LIST = gameProjectTbRepository.recommendList(); RECOMMEND_LIST = gameProjectTbRepository.recommendList();
...@@ -216,22 +232,21 @@ public class ScheduleService implements InitializingBean { ...@@ -216,22 +232,21 @@ public class ScheduleService implements InitializingBean {
}).start(); }).start();
} }
@Scheduled(cron = "0 0 */1 * * ?") // @Scheduled(cron = "0 0 */1 * * ?")
public void shuffleAllProList() { public void shuffleAllProList() {
new Thread(() -> { new Thread(() -> {
Collections.shuffle(ALL_ON_PRODUCT); Collections.shuffle(ALL_ON_PRODUCT);
}).start(); }).start();
} }
@Scheduled(cron = "0 */30 * * * ?") // @Scheduled(cron = "0 */20 * * * ?")
public void getAllChannelRecommendBotAccount() { public void getAllChannelRecommendBotAccount() {
String response = null; String response = null;
int count = 1; int count = 1;
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
do { do {
try { try {
Thread.sleep(count*5); response = OkHttp3Utils.doGet("http://didi-gz3.jiaoyou365.com:8070/api/sdk/botConfig/all");
response = OkHttp3Utils.doGet("http://didi-gz4.jiaoyou365.com:8070/api/sdk/botConfig/all");
JSONArray array = JSONObject.parseArray(response); JSONArray array = JSONObject.parseArray(response);
if (array != null) { if (array != null) {
for (Object o: array) { for (Object o: array) {
...@@ -244,13 +259,74 @@ public class ScheduleService implements InitializingBean { ...@@ -244,13 +259,74 @@ public class ScheduleService implements InitializingBean {
} catch (Exception e) { } catch (Exception e) {
log.error("getAllChannelRecommendBotAccount:{}",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++; count++;
} while (StringUtils.isBlank(response) && count < 5); } while (StringUtils.isBlank(response) && count < 5);
if (map.size() != 0) { if (map.size() != 0) {
channelId2RecommendBotAcc = map; 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<String, List<String>> 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<String, List<String>> map = jsonObject.toJavaObject(Map.class);
if (map != null && map.size() != 0) {
List<String> jiaoyouList = map.get("jiaoyou-audio-adult-test");
if (!CollectionUtils.isEmpty(jiaoyouList)) map.get("jiaoyou-audio-adult-test").add("遇见伽利略");
List<String> 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() { private void getAsideImg() {
...@@ -260,7 +336,7 @@ public class ScheduleService implements InitializingBean { ...@@ -260,7 +336,7 @@ public class ScheduleService implements InitializingBean {
for (String botId: botIds) { for (String botId: botIds) {
try { try {
HashMap<String, String> params = new HashMap<>(); HashMap<String, String> params = new HashMap<>();
params.put("include", "npcHeadImgUrl"); params.put("include", "audioNpc");
params.put("aipioneerUsername",botId); params.put("aipioneerUsername",botId);
String str = OkHttp3Utils.doGet(ASIDE_IMG_URL, params); String str = OkHttp3Utils.doGet(ASIDE_IMG_URL, params);
AsideImageResponse response = JSON.parseObject(str, AsideImageResponse.class); AsideImageResponse response = JSON.parseObject(str, AsideImageResponse.class);
...@@ -281,8 +357,11 @@ public class ScheduleService implements InitializingBean { ...@@ -281,8 +357,11 @@ public class ScheduleService implements InitializingBean {
initProductList(); initProductList();
deleteOverTimeHistory(); deleteOverTimeHistory();
deleteUnPayedOrder(); deleteUnPayedOrder();
tian(); // tian();
getAsideImg(); getAsideImg();
getAllChannelRecommendBotAccount();
getChannelAllBots();
getJiaoYouChannelRecordBots();
} }
private void tian(){ private void tian(){
......
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("<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n" +
" <title>Title</title>\n" +
"</head>\n" +
"<body>");
// 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<String> list = Arrays.stream(arrTest).filter(s1 -> s1.contains(type))
.map(s1 -> {
String[] arr = s1.split("\n");
return Arrays.stream(arr).map(s -> "<span>"+s+"</span><br>").collect(Collectors.joining(""));
// return StringUtils.join(arr, "");
}).collect(Collectors.toList());
Collections.reverse(list);
List<String> 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 -> "<span>"+ s1 +"</span><br>").collect(Collectors.joining(""));
}).collect(Collectors.toList());
if (list.size() != 0) {
Collections.reverse(list);
result.addAll(list);
}
recur++;
}
result.forEach(s -> builder.append("<span>").append(s).append("</span><br>"));
} else {
String[] arr = response.getData().split("\n");
List<String> list = Arrays.asList(arr);
Collections.reverse(list);
list.forEach(s -> builder.append("<span>").append(s).append("</span><br>"));
// Arrays.stream(arr).forEach(s1 -> builder.append("<span>").append(s1).append("</span><br>"));
}
builder.append("</body>\n" +
"</html>");
return builder.toString();
// List<String> list = Arrays.stream(arr).map(s1 -> "<span>"+s1+"</span><br>").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;
}
}
}
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;
}
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;
}
...@@ -60,7 +60,7 @@ public class InitialData implements InitializingBean { ...@@ -60,7 +60,7 @@ public class InitialData implements InitializingBean {
} }
Map<String, Map<String, String>> npcName2nameId = recordMap.computeIfAbsent(botAccount, s -> new HashMap<>()); Map<String, Map<String, String>> npcName2nameId = recordMap.computeIfAbsent(botAccount, s -> new HashMap<>());
int j = 0; int j = 0;
// "person", "mood", "md5", "id", "text", "upUrl" // "person", "mood", "md5", "id", "upUrl"
for (CSVRecord line: reader) { for (CSVRecord line: reader) {
if (j == 0) { if (j == 0) {
j++; j++;
......
...@@ -72,7 +72,7 @@ public class SpiritService { ...@@ -72,7 +72,7 @@ public class SpiritService {
} }
} }
String userWord = request.getUtterance(); String userWord = request.getUtterance();
log.info("天猫精灵用户说的话:"+userWord); // log.info("天猫精灵用户说的话:"+userWord);
try { try {
Future<TaskResult> future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId)); Future<TaskResult> future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId));
return future.get(1700, TimeUnit.MILLISECONDS); return future.get(1700, TimeUnit.MILLISECONDS);
...@@ -95,19 +95,20 @@ public class SpiritService { ...@@ -95,19 +95,20 @@ public class SpiritService {
//log.info("向终端发出请求的参数信息:{}", requestJsonStr); //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8"); headers.put("Content-Type", "application/json;charset=utf-8");
String channelId = "jiaoyou-audio-test"; String channelId;
switch (type) { switch (type) {
case 2: case 2:
case 4: channelId = "jiaoyou-audio-child-test";break; case 4: channelId = "tianmao-jiaoyou-audio-child-test";break;
case 3: 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); 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) { if (resStr == null) {
return null; return null;
} }
log.info("天猫精灵晓悟返回:"+resStr); // log.info("天猫精灵晓悟返回:"+resStr);
TaskResult taskResult = null; TaskResult taskResult = null;
try { try {
final SpiritTerminateResponse response = JSON.parseObject(resStr, SpiritTerminateResponse.class); final SpiritTerminateResponse response = JSON.parseObject(resStr, SpiritTerminateResponse.class);
......
...@@ -26,13 +26,13 @@ public class RequestTerminal { ...@@ -26,13 +26,13 @@ public class RequestTerminal {
static { static {
ALL_HEADERS = new HashMap<>(); ALL_HEADERS = new HashMap<>();
ALL_HEADERS.put("Content-Type", "application/json;charset=utf-8"); 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 = new HashMap<>();
CHILD_HEADERS.put("Content-Type", "application/json;charset=utf-8"); 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 = new HashMap<>();
ADULT_HEADERS.put("Content-Type", "application/json;charset=utf-8"); 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 { ...@@ -49,18 +49,17 @@ public class RequestTerminal {
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
//log.info("向终端发出请求的参数信息:{}", requestJsonStr); //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap<String, String> headers; HashMap<String, String> headers;
if (type != null) { switch (type) {
if ((type & 1) == 1) headers = CHILD_HEADERS; case 1: headers = CHILD_HEADERS; break;
else headers = ADULT_HEADERS; case 2: headers = ADULT_HEADERS; break;
} else { default: headers = ALL_HEADERS; break;
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);
} }
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; return resStr;
} }
...@@ -69,10 +68,11 @@ public class RequestTerminal { ...@@ -69,10 +68,11 @@ public class RequestTerminal {
requestPojo.setUid(userId); requestPojo.setUid(userId);
requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD); requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD);
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
if (userId.equals(XiaoAiService.deviceId)) { OkHttp3Utils.xiaoaiBackPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type); // if (userId.equals(XiaoAiService.deviceId)) {
}else { // OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_nx2, requestJsonStr, type); // }else {
} // OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
// }
} }
} }
package ai.qiwu.com.xiaoduhome.xiaoai.common; 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.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects; import java.util.Objects;
/** /**
...@@ -11,12 +20,15 @@ import java.util.Objects; ...@@ -11,12 +20,15 @@ import java.util.Objects;
* @author 苗权威 * @author 苗权威
* @dateTime 19-7-6 上午11:16 * @dateTime 19-7-6 上午11:16
*/ */
@Slf4j
public class Utils { public class Utils {
/** /**
* 代表空格,斜杠,单引号,双引号,tab键 * 代表空格,斜杠,单引号,双引号,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对象 * 获取HttpServletRequest对象
...@@ -60,4 +72,82 @@ public class Utils { ...@@ -60,4 +72,82 @@ public class Utils {
} }
return builder.toString(); 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"));
}
} }
...@@ -10,6 +10,7 @@ public interface XiaoAiConstants { ...@@ -10,6 +10,7 @@ public interface XiaoAiConstants {
String QI_WU_TERMINATE_DIDI2 = "http://didi-gz2.jiaoyou365.com:8070/api/chat2"; 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 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_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 TTS_DIDI4 = "http://didi-gz4.jiaoyou365.com:9663/api/audio";
String DEVICE_NAME = "XIAOAI"; String DEVICE_NAME = "XIAOAI";
String CONTENT_TYPE = "application/json;charset=utf-8"; String CONTENT_TYPE = "application/json;charset=utf-8";
...@@ -30,6 +31,7 @@ public interface XiaoAiConstants { ...@@ -30,6 +31,7 @@ public interface XiaoAiConstants {
String WELCOME_WORD_CHILD_STORY = "小朋友你好,欢迎来到互动故事,你可以说推荐作品给我"; String WELCOME_WORD_CHILD_STORY = "小朋友你好,欢迎来到互动故事,你可以说推荐作品给我";
String WELCOME_WORD_Adult = "你好,欢迎来到智能小说,你可以说推荐作品给我"; String WELCOME_WORD_Adult = "你好,欢迎来到智能小说,你可以说推荐作品给我";
String WELCOME_WORD_Adult_literature = "你好,欢迎来到互动文艺,你可以说推荐作品给我"; String WELCOME_WORD_Adult_literature = "你好,欢迎来到互动文艺,你可以说推荐作品给我";
String WELCOME_WORD_DEFAULT = "欢迎来到我们的技能,与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";
String END_BYE = "我们的作品库在不断扩充,欢迎再来玩"; String END_BYE = "我们的作品库在不断扩充,欢迎再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦"; String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_BYE_Adult = "再见啦,记得下次再来玩哦"; String END_BYE_Adult = "再见啦,记得下次再来玩哦";
...@@ -41,4 +43,13 @@ public interface XiaoAiConstants { ...@@ -41,4 +43,13 @@ public interface XiaoAiConstants {
String WAIT_WORD_2 = "由于网络的原因,您可能需要稍稍等等"; String WAIT_WORD_2 = "由于网络的原因,您可能需要稍稍等等";
String WAIT_WORD_3 = "由于网络原因小悟正在加倍努力获取结果,不过您现在得快些对我说些什么,要不然您就退出我们的技能了"; 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==";
}
} }
package ai.qiwu.com.xiaoduhome.xiaoai.model.request.innerRequest; package ai.qiwu.com.xiaoduhome.xiaoai.model.request.innerRequest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
...@@ -11,8 +12,9 @@ import lombok.ToString; ...@@ -11,8 +12,9 @@ import lombok.ToString;
@Getter @Getter
@Setter @Setter
@ToString @ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Request { public class Request {
private int type; private Integer type;
private String request_id; private String request_id;
private Long timestamp; private Long timestamp;
private Boolean no_response; private Boolean no_response;
...@@ -20,4 +22,6 @@ public class Request { ...@@ -20,4 +22,6 @@ public class Request {
private EventProperty event_property; private EventProperty event_property;
private String Locale; private String Locale;
private SlotInfo slot_info; private SlotInfo slot_info;
private Boolean is_monitor;
} }
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<String, String> params;
}
...@@ -17,4 +17,7 @@ public class ToDisplay { ...@@ -17,4 +17,7 @@ public class ToDisplay {
private String url; private String url;
private String text; private String text;
private UITemplate ui_template; private UITemplate ui_template;
private String ui_type;
private PhoneTemplate phone_template;
} }
package ai.qiwu.com.xiaoduhome.xiaoai.service; package ai.qiwu.com.xiaoduhome.xiaoai.service;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils; 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.service.DplbotServiceUtil;
import ai.qiwu.com.xiaoduhome.xiaoai.common.*; import ai.qiwu.com.xiaoduhome.xiaoai.common.*;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest; import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
...@@ -12,21 +11,28 @@ import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.Audi ...@@ -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.directive.Directive;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toDisplay.ToDisplay; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toDisplay.ToDisplay;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak; 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.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File; import java.io.File;
import java.net.URLEncoder;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.*; 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.ERROR_MSG.SORRY_REPEAT;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.PREFIX_USERID; 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.WAIT_WORD_3;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.TTS.WELCOME_WORD_DEFAULT;
/** /**
* @author 苗权威 * @author 苗权威
...@@ -49,7 +55,7 @@ public class XiaoAiService { ...@@ -49,7 +55,7 @@ public class XiaoAiService {
*/ */
private static final ConcurrentHashMap<String, XiaoAiResponse> LAST_OUTTIME_RESULT = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, XiaoAiResponse> LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<String, Byte> LAST_OUTTIME_MARK = new ConcurrentHashMap<>(); public static final ConcurrentHashMap<String, Byte> LAST_OUTTIME_MARK = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, String> LAST_AUDIO_PLAY = new ConcurrentHashMap<>(); // private static final ConcurrentHashMap<String, String> LAST_AUDIO_PLAY = new ConcurrentHashMap<>();
public static final Byte OUTTIME_TYPE_0 = 0; public static final Byte OUTTIME_TYPE_0 = 0;
private static final Byte OUTTIME_TYPE_1 = 1; private static final Byte OUTTIME_TYPE_1 = 1;
...@@ -64,11 +70,12 @@ public class XiaoAiService { ...@@ -64,11 +70,12 @@ public class XiaoAiService {
*/ */
public XiaoAiResponse getResponse(XiaoAiRequest request) { public XiaoAiResponse getResponse(XiaoAiRequest request) {
String userId = getUserId(request); String userId = getUserId(request);
// String userId = "%2FScfTGmNbhn%2Fs8KXMJfZY4nQ%2F";
int type = request.getRequest().getType(); int type = request.getRequest().getType();
switch (type) { switch (type) {
case 0 : return dealWithLaunchRequest(request); case 0 : return dealWithLaunchRequest(request);
case 1 : return dealWithIntentRequest(request, userId); 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); default: return buildTextResponse(SORRY_REPEAT);
} }
} }
...@@ -131,6 +138,21 @@ public class XiaoAiService { ...@@ -131,6 +138,21 @@ public class XiaoAiService {
return response; 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 音频文件地址 * @param audioUrl 音频文件地址
...@@ -194,6 +216,24 @@ public class XiaoAiService { ...@@ -194,6 +216,24 @@ public class XiaoAiService {
return response; 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 请求信息 * @param request 请求信息
...@@ -206,17 +246,53 @@ public class XiaoAiService { ...@@ -206,17 +246,53 @@ public class XiaoAiService {
// } // }
LAST_OUTTIME_RESULT.remove(getUserId(request)); LAST_OUTTIME_RESULT.remove(getUserId(request));
LAST_OUTTIME_MARK.remove(getUserId(request)); LAST_OUTTIME_MARK.remove(getUserId(request));
LAST_AUDIO_PLAY.remove(getUserId(request)); // LAST_AUDIO_PLAY.remove(getUserId(request));
Integer type;
if ((type = request.getType()) != null) { String welcomeWord = null;
switch (type) { String num = RandomStringUtils.randomNumeric(3);
case 1: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_CHILD); Integer type = request.getType();
case 2: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_Adult); switch (type) {
case 3: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_CHILD_STORY); case 1 : {
case 4: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_Adult_literature); // welcomeWord = WELCOME_SMART_FORMAT_AI;
// try {
// List<String> 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<String> 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<String> 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 { ...@@ -226,7 +302,8 @@ public class XiaoAiService {
* @param userId 用户在小爱上的id * @param userId 用户在小爱上的id
* @return 响应信息 * @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(); Boolean idle = request.getRequest().getNo_response();
Byte waitType; Byte waitType;
if ((waitType=LAST_OUTTIME_MARK.remove(userId)) != null) { if ((waitType=LAST_OUTTIME_MARK.remove(userId)) != null) {
...@@ -248,10 +325,15 @@ public class XiaoAiService { ...@@ -248,10 +325,15 @@ public class XiaoAiService {
} }
return LAST_OUTTIME_RESULT.remove(userId); 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)) { if (Boolean.TRUE.equals(idle)) {
try { try {
//log.info("开始等待"); //log.info("开始等待");
Thread.sleep(2000); Thread.sleep(1700);
//log.info("等待OVER"); //log.info("等待OVER");
} catch (InterruptedException e) { } catch (InterruptedException e) {
log.warn("等待中断"); log.warn("等待中断");
...@@ -263,15 +345,11 @@ public class XiaoAiService { ...@@ -263,15 +345,11 @@ public class XiaoAiService {
return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.USER_IDLE : return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.USER_IDLE :
XiaoAiConstants.TTS.ANOTHER_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); // XiaoAiResponse response = getLastResult(userId);
// if (response != null) return response; // if (response != null) return response;
try { try {
Future future = DplbotServiceUtil.getPool().submit(new Task(userId, request.getQuery(), request.getType())); Future future = DplbotServiceUtil.getPool().submit(() -> task(userId, request.getQuery(), request.getType()));
future.get(2250, TimeUnit.MILLISECONDS); future.get(2200, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", e.toString()); log.error("获取任务执行结果出错:{}", e.toString());
return buildTextResponse(SORRY_REPEAT); return buildTextResponse(SORRY_REPEAT);
...@@ -291,23 +369,22 @@ public class XiaoAiService { ...@@ -291,23 +369,22 @@ public class XiaoAiService {
* @param userId 用户id * @param userId 用户id
* @return 返回信息 * @return 返回信息
*/ */
private XiaoAiResponse dealWithEndRequest(String userId, Integer type) { private XiaoAiResponse dealWithEndRequest(String userId, Integer type, Boolean monitor) {
// DplbotServiceUtil.getPool().submit(() -> { // LAST_OUTTIME_MARK.remove(userId);
// try { // LAST_OUTTIME_RESULT.remove(userId);
// RequestTerminal.backBotRequest(userId, type); // LAST_AUDIO_PLAY.remove(userId);
// } catch (Exception e) { if (!monitor) RequestTerminal.backBotRequest(userId, type);
// log.error("向终端发出的退出请求失败:{}", e.toString()); else {
// } log.info("小爱monitor退出请求:"+userId);
// }); }
RequestTerminal.backBotRequest(userId, type); String byeWord;
LAST_OUTTIME_MARK.remove(userId); switch (type) {
LAST_OUTTIME_RESULT.remove(userId); case 1: byeWord = EndMsg.END_BYE_STORY;break;
LAST_AUDIO_PLAY.remove(userId); case 2: byeWord = EndMsg.END_BYE_NOVEL;break;
if (type != null) { case 5: byeWord = EndMsg.END_BYE_JIAOYOU;break;
if ((type & 1) == 1) return buildTextResponse(XiaoAiConstants.TTS.END_BYE_CHILD); default: byeWord = EndMsg.END_BYE_DEFAULT;break;
else return buildTextResponse(XiaoAiConstants.TTS.END_BYE_Adult);
} }
return buildTextResponse(XiaoAiConstants.TTS.END_BYE); return buildCancelTextResponse(byeWord);
} }
/** /**
...@@ -316,119 +393,219 @@ public class XiaoAiService { ...@@ -316,119 +393,219 @@ public class XiaoAiService {
* @return 用户id * @return 用户id
*/ */
private String getUserId(XiaoAiRequest request) { private String getUserId(XiaoAiRequest request) {
String userId = request.getContext().getDevice_id(); String userId = request.getSession().getUser().getUser_id();
if (userId == null) { if (userId == null) {
userId = request.getSession().getUser().getUser_id(); userId = request.getContext().getDevice_id();
if (userId != null) userId = Utils.modifyDeviceId(userId);
} }
if (userId == null) { if (userId == null) {
userId = Utils.useIPAsItsID(); userId = Utils.useIPAsItsID();
} }
userId = PREFIX_USERID+userId; try {
return Utils.modifyDeviceId(userId); 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) { private XiaoAiResponse getLastResult(String userId) {
return LAST_OUTTIME_RESULT.remove(userId); return LAST_OUTTIME_RESULT.remove(userId);
} }
/** private void task(String userId, String userWord, Integer type) {
* 任务封装类 XiaoAiResponse xiaoAiResponse;
*/ if (userWord == null) {
class Task implements Runnable { log.warn("请求中没有带有用户的话");
private final String userId; throw new RequestWordNullException("user word can not be null");
private final String userWord;
private final Integer type;
Task(String userId, String userWord, Integer type) {
this.userId = userId;
this.userWord = userWord;
this.type = type;
} }
String response;
@Override try {
public void run() { response = RequestTerminal.requestTerminate(userId, userWord, type);
XiaoAiResponse xiaoAiResponse; // log.info("小爱,小悟返回:{}", response);
if (userWord == null) { } catch (Exception e) {
log.info("请求中没有带有用户的话"); log.error("向终端发出的请求信息失败:{}", e.toString());
throw new RequestWordNullException("user word can not be null"); xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
} LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
log.info("小爱,用户说的话:{}", userWord); return;
String response; }
if (StringUtils.isBlank(response)) {
log.error("中控返回结果为空");
xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
} else {
try { try {
response = RequestTerminal.requestTerminate(userId, userWord, type); // log.info(response);
log.info("小爱,小悟返回:{}", response); JSONObject object = JSON.parseObject(response);
} catch (Exception e) { JSONArray commands = object.getJSONArray("commands");
log.error("向终端发出的请求信息失败:{}", e.toString()); if (commands != null && commands.size() != 0) {
xiaoAiResponse = buildTextResponse(SORRY_REPEAT); String txt;
LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse); for (Object ob: commands) {
return; txt = ((JSONObject) ob).getString("text");
} int i;
if (StringUtils.isBlank(response)) { if (StringUtils.isNotBlank(txt) && (i=txt.indexOf("out")) != -1) {
log.error("中控返回结果为空"); log.info("小爱,推荐bot退出:{},userId:{}", userWord, userId);
xiaoAiResponse = buildTextResponse(SORRY_REPEAT); String content = txt.substring(i+3, txt.indexOf("☚")).trim();
} else { String skillName, outWord;
String path; switch (type) {
try { case 1: {
boolean one; skillName = SKILL_SMART;
if ((one=userId.equals(deviceId))) { outWord = EndMsg.END_BYE_STORY;
path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI4, response); break;
} else { }
path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response); case 2: {
} skillName = SKILL_NOVEL;
if (StringUtils.isBlank(path) || path.equals("null")) { outWord = EndMsg.END_BYE_NOVEL;
log.error("没有获取到TTS返回的路径path"); break;
LAST_OUTTIME_RESULT.put(userId, buildTextResponse(SORRY_REPEAT)); }
return; default: {
} skillName = SKILL;
if (one) { outWord = EndMsg.END_BYE_JIAOYOU;
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(";");
} }
WebSocketLog.sendInfo(builder.toString(), "ai1"); RequestTerminal.backBotRequest(userId, type);
}); if (StringUtils.isNotBlank(content)) {
} else { content = content.replaceAll("\\{/.*?/}", "")+skillName;
DplbotServiceUtil.getPool().submit(() -> { LAST_OUTTIME_RESULT.put(userId, buildResponseBeforeLoadout(content));
JSONObject ob = JSONObject.parseObject(response); return;
JSONArray array = ob.getJSONArray("dialogs"); } else {
StringBuilder builder = new StringBuilder(userWord).append(File.separator); JSONArray dialogs = object.getJSONArray("dialogs");
for (Object item: array) { if (dialogs != null && dialogs.size() != 0) {
String str = ((JSONObject) item).getString("text"); String str = ((JSONObject)dialogs.get(0)).getString("text");
builder.append(str.replaceAll("\\{/.*?/}", "")).append(";"); 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"); log.error("没有获取到TTS返回的路径path");
xiaoAiResponse = buildTextResponse(SORRY_REPEAT); LAST_OUTTIME_RESULT.put(userId, buildTextResponse(SORRY_REPEAT));
return;
} }
// final String word = userWord; xiaoAiResponse = buildAudioResponse(changeAudioUrl(path, userId));
// DplbotServiceUtil.getPOOL().submit(() -> { // LAST_AUDIO_PLAY.put(userId, path);
// if (deviceId.equals(userId)) { } catch (Exception e) {
// WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator) log.error("没有获取到TTS返回的路径path");
// .append(response.getText()).toString(), "ai1"); xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
// } else {
// WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator)
// .append(response.getText()).toString(), "ai2");
// }
// });
} }
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) { 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(); return new StringBuilder(TTS_DIDI3_GET_XIAOAI).append(userId).append("&path=").append(path).toString();
} }
...@@ -438,13 +615,13 @@ public class XiaoAiService { ...@@ -438,13 +615,13 @@ public class XiaoAiService {
return new StringBuilder(TTS_DIDI4_GET_XIAOAI).append(userId).append("&path=").append(path).toString(); return new StringBuilder(TTS_DIDI4_GET_XIAOAI).append(userId).append("&path=").append(path).toString();
} }
public void changeAudioPlayMark(String userId) { // public void changeAudioPlayMark(String userId) {
LAST_AUDIO_PLAY.remove(userId); // LAST_AUDIO_PLAY.remove(userId);
} // }
public static void main(String[] args) { public static void main(String[] args) {
System.out.println(Utils.modifyDeviceId("XIAOAI_nbNGwo/tZIS8A/mRGVqHog==")); System.out.println(Utils.modifyDeviceId("XIAOAI_Ls69sFTjXN/6831N1VVdfw"));
// oIOWfYEFbZGFHB5DzoMA==; System.out.println(Utils.modifyDeviceId("XIAOAI_+nzkUO6JnLrmiWSlBQaZ9g"));
// oItOWfYEFbtZGFHB5DzoMA== System.out.println(Utils.modifyDeviceId("XIAOAI_Ls69sFTjXN/6831N1VVdfw"));
} }
} }
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<String, XiaoAiResponse> LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<String, Byte> LAST_OUTTIME_MARK = new ConcurrentHashMap<>();
// private static final ConcurrentHashMap<String, String> 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<String, String> 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<String, String> 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<Directive> 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<String> 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<String> 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<String> 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", ""));
}
}
server: server:
port: 8188 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: spring:
datasource: datasource:
...@@ -10,11 +16,13 @@ spring: ...@@ -10,11 +16,13 @@ spring:
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
secondary: secondary:
jdbc-url: jdbc:mysql://localhost:3306/audiobox?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false 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 username: root
password: 38A0O1jEPOE password: 38A0O1jEPOE
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
analysis: analysis:
jdbc-url: jdbc:mysql://localhost:3306/analysis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false 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 username: root
password: 38A0O1jEPOE password: 38A0O1jEPOE
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
...@@ -27,6 +35,8 @@ spring: ...@@ -27,6 +35,8 @@ spring:
output: output:
ansi: ansi:
enabled: detect enabled: detect
thymeleaf:
cache: false
logging: logging:
path: /home/dc2-user/projects/audiobox/duai/logs path: /home/dc2-user/projects/audiobox/duai/logs
level: level:
......
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>对话日志</title>
<script type="text/javascript">
function getToken() {
var token = document.getElementById("tokens").value;
var type = document.getElementById("type").value;
var typeCount = document.getElementById("typeCount").value;
var row = document.getElementById("row").value;
var ajaxObj = new XMLHttpRequest();
console.log(token+":"+type+":"+typeCount+":"+row);
ajaxObj.open('get', '/chat/log?token='+token+'&row='+row+'&count='+typeCount+'&type='+type);
ajaxObj.send();
ajaxObj.onreadystatechange = function () {
if (ajaxObj.readyState === 4 && ajaxObj.status === 200) {
}
}
}
</script>
</head>
<body>
<div>
<label>
<select id="type">
<option value="jiaoyou-audio">音箱</option>
</select>
</label>
<input type="text" id="tokens" th:hidden="true" th:default="${token}"/>
<input type="text" id="typeCount" class="countC" placeholder="请输入所要显示的类型的个数"/>
<input type="text" id="row" class="rowC" placeholder="请输入所要显示的行数"/>
<input type="button" id="search" class="click" value="点击搜索" onclick="getToken()"/>
</div>
<div>
<span th:text="${data}"></span>
</div>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>CHAT LOG</title>
<link rel="stylesheet" type="text/css" th:href="@{/layui.css}">
</head>
<body>
<div class="mainbox">
<p></p>
<div class="subbox">
<p>显示全部日志:</p>
<input type="text" id="row" class="input" placeholder="请输入所要显示的行数,默认1000行"/>
<button type="button" class="layui-btn button " id="one" onclick="getAllToken()">点击搜索</button>
</div>
<div class="subbox">
<p>显示指定类型的日志:</p>
<label>
<select id="type" style="height: 60px; width: 80px;">
<option value="jiaoyou-audio">音箱</option>
<option value="jiaoyou-audio-adult">音箱-成人</option>
<option value="jiaoyou-audio-child">音箱-儿童</option>
<option value="XIAODU_">小度</option>
<option value="XIAOAI_">小爱</option>
</select>
</label>
<!--<input type="text" id="tokens" th:hidden="true" th:default="${token}"/>-->
<input type="text" id="typeCount" class="input" placeholder="请输入所要显示的类型的个数,默认100个"/>
<!--<input type="button" id="search" class="click" value="点击搜索" onclick="getToken()"/>-->
<button type="button" class="layui-btn button " id="two" onclick="getToken()">点击搜索</button>
</div>
</div>
</body>
<style>
.mainbox{
width: 900px;
height: 200px;
margin: 100px auto;
display: flex;
flex-direction: column;
}
.subbox{
width: 900px;
height: 200px;
margin: 100px auto;
display: flex;
flex-direction: row;
}
.input{
width: 500px;
}
button{
flex: 1;
}
</style>
<script th:inline="javascript">
var token = [[${token}]];
function getToken() {
var type = document.getElementById("type").value;
var typeCount = document.getElementById("typeCount").value;
console.log(token+":"+type+":"+typeCount);
window.location.href = "http://didi-gz3.jiaoyou365.com:8188/chat/log?token=" +token+'&count='+typeCount+'&type='+type;
}
function getAllToken() {
var row = document.getElementById("row").value;
window.location.href = "http://didi-gz3.jiaoyou365.com:8188/chat/log?token=" +token+'&row='+row;
}
</script>
</html>
\ No newline at end of file
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Title</title> <title>登录</title>
</head> </head>
<body> <body>
<span>登录失败,请返回</span> <span>登录失败,请返回</span>
......
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>对话日志</title>
<!--<link rel="stylesheet" href="../static/layui.css">-->
<!--<script src="./static/vue.js"></script>-->
<link rel="stylesheet" type="text/css" th:href="@{/layui.css}">
<script th:src="@{/vue.js}"></script>
</head>
<body>
<div id="app">
<div class="mainbox" id="mainbox" >
<!--<div v-for="item in datalist">-->
<div>
<!--<p class=" one_tack ai">{{item.text}}</p>-->
<p class=" one_tack ai">{{text}}</p>
<!-- <p class="one_tack self">{{item.self}}</p> -->
</div>
<p id="text"></p>
</div>
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
datalist: [],
text:"",
},
methods: {
},
mounted: function () {
let that = this;
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
socket = new WebSocket("ws://didi-gz3.jiaoyou365.com:8188/webSocket/chat"); //小度
//打开事件
socket.onopen = function () {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
// console.log(msg.data);
this.text+=msg.data;
var div = document.getElementById('mainbox');
var text = document.getElementById('text');
text.innerHTML=this.text;
div.scrollTop = div.scrollHeight;
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
}
})
</script>
<style>
.mainbox {
width: 1300px;
height: auto;
border: 1px solid black;
display: flex;
flex-direction: column;
margin: 100px auto;
padding: 20px;
}
.ai {
color: green;
}
.one_tack {
margin-top: 10;
}
</style>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>对话日志</title>
<!--<link rel="stylesheet" href="../static/layui.css">-->
<!--<script src="./static/vue.js"></script>-->
<link rel="stylesheet" type="text/css" th:href="@{/layui.css}">
<script th:src="@{/vue.js}"></script>
</head>
<body>
<div id="app">
<div class="mainbox" id="mainbox" >
<!--<div v-for="item in datalist">-->
<div>
<!--<p class=" one_tack ai">{{item.text}}</p>-->
<p class=" one_tack ai">{{text}}</p>
<!-- <p class="one_tack self">{{item.self}}</p> -->
</div>
<p id="text"></p>
</div>
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
datalist: [],
text:"",
},
methods: {
},
mounted: function () {
let that = this;
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
// socket = new WebSocket("${basePath}webSocket/${username}".replace("https","ws"));
// socket = new WebSocket("ws://didi-gz4.jiaoyou365.com:8188/webSocket/du"); //小度
// socket = new WebSocket("ws://didi-gz4.jiaoyou365.com:8188/webSocket/aigz3"); //小度
socket = new WebSocket("ws://didi-gz3.jiaoyou365.com:8188/webSocket/chat"); //小度
//打开事件
socket.onopen = function () {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
// console.log(msg.data);
this.text=msg.data;
// let text2=
// console.log(this.text,"11111");
// let obj = {
// ai: "",
// self: ""
// };
//
// let arr = msg.data.split("/");
// obj.ai = arr[0];
// obj.self = arr[1];
// that.datalist.push(msg.data);
// that.datalist.push(obj);
var div = document.getElementById('mainbox');
var text = document.getElementById('text');
text.innerHTML=msg.data;
div.scrollTop = div.scrollHeight;
// console.log(msg.data);
// console.log(this.alldata);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
}
})
</script>
<style>
.mainbox {
width: 1300px;
height: auto;
border: 1px solid black;
display: flex;
flex-direction: column;
margin: 100px auto;
padding: 20px;
}
.ai {
color: green;
}
.one_tack {
margin-top: 10;
}
</style>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>查看日志登录</title>
<script type="text/javascript">
function getToken() {
var phoneNum = document.getElementById("phoneNum").value;
var captcha = document.getElementById("getCaptcha").value;
// alert("phone:"+phoneNum+",captcha:"+captcha);
var ajaxObj = new XMLHttpRequest();
//var uri = '/xiaodu/security/token?phoneNumber='+phoneNum+'&captcha='+captcha;
ajaxObj.open('get', '/chat/login/check?userName='+phoneNum+'&passwd='+captcha);
ajaxObj.send();
ajaxObj.onreadystatechange = function () {
if (ajaxObj.readyState === 4 && ajaxObj.status === 200) {
if (ajaxObj.responseText.length === 8) {
window.location.href = "http://didi-gz3.jiaoyou365.com:8188/chat/choose?token=" + ajaxObj.responseText;
}
}
}
}
</script>
<style type="text/css">
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #eee;
margin:0;
}
.container {
width: 80%;
padding-left: 15px;
padding-right: 15px;
margin-right: auto;
margin-left: auto;
}
.whole {
text-align: center;
padding: 10px;
margin: 0 auto;
}
.title {
margin-top: 20px;
margin-bottom: 10px;
font-size: 26px;
}
.input {
margin-bottom: -1px;
border-radius: 4px;
height: auto;
width: 88%;
padding: 10px;
font-size: 16px;
color: #555;
background-color: #fff;
border:1px solid #ccc;
}
.click {
display: block;
font-size: 16px;
border-radius: 4px;
color: #fff;
background-color: #337ab7;
padding: 6px 12px;
font-weight: 400;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
border: 1px solid transparent;
margin:10px auto;
width: 96%;
}
</style>
</head>
<body>
<div class="container">
<div class="whole" id="captchaView">
<h2 class="title">CHAT日志</h2>
<input type="text" id="phoneNum" name="phone" class="input" placeholder="请输入用户名"/>
</div>
<div class="whole" id="tokenView">
<input type="password" id="getCaptcha" name="phone" class="input" placeholder="请输入密码"/>
<input type="button" id="toLoad" name="to_load" class="click" value="点击登录" onclick="getToken()"/>
</div>
</div>
</body>
</html>
\ No newline at end of file
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
<button type="button" class="layui-btn button " id="four">小度2号 (gz3)</button> <button type="button" class="layui-btn button " id="four">小度2号 (gz3)</button>
<button type="button" class="layui-btn button " id="tow">小爱1号(gz3)</button> <button type="button" class="layui-btn button " id="tow">小爱1号(gz3)</button>
<button type="button" class="layui-btn button " id="therr">小爱2号(gz3)</button> <button type="button" class="layui-btn button " id="therr">小爱2号(gz3)</button>
<button type="button" class="layui-btn button " id="five">对话日志</button>
</div> </div>
</body> </body>
<style> <style>
...@@ -34,6 +35,7 @@ ...@@ -34,6 +35,7 @@
var tow = document.getElementById("tow"); var tow = document.getElementById("tow");
var therr = document.getElementById("therr"); var therr = document.getElementById("therr");
var four = document.getElementById("four"); var four = document.getElementById("four");
var five = document.getElementById("five");
one.onclick = function(){ one.onclick = function(){
console.log("点击事件"); console.log("点击事件");
...@@ -53,7 +55,10 @@ ...@@ -53,7 +55,10 @@
four.onclick = function(){ four.onclick = function(){
console.log("点击事件"); console.log("点击事件");
window.open("./Log4.html","_blank"); window.open("./Log4.html","_blank");
};
five.onclick = function () {
console.log("点击事件");
window.open("./Log5.html","_blank");
} }
</script> </script>
</html> </html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment