diff --git a/.idea/compiler.xml b/.idea/compiler.xml
index 3cb42ad..8982f58 100755
--- a/.idea/compiler.xml
+++ b/.idea/compiler.xml
@@ -33,7 +33,7 @@
-
+
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index 9135d6c..5259ab0 100755
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -10,44 +10,37 @@
+
-
-
-
-
-
-
-
-
-
+
+
+
-
-
-
-
-
+
+
+
-
-
-
+
+
+
+
-
-
+
@@ -91,35 +84,39 @@
-
+
-
-
+
+
+
+
-
-
+
+
-
-
+
+
-
-
+
+
+
+
-
+
-
-
+
+
@@ -128,46 +125,56 @@
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
+
+
+
-
-
+
+
-
-
+
+
-
+
-
-
+
+
@@ -187,36 +194,36 @@
- LAST_OUTTIME_RESULT
- buildLogOutResponse
- request
- secret
- zOQuywFuKjlhbTMr4dHwFA==
- channelId2RecommendBotAcc
- dealT
- channel2Bots
- 刚才走
- jiaoyouChannel2Bots
- request.getSession().getUser()
- commons-lang3
- org.apache.commons
- NUM_OR_ALPHA
- customUserId
- getUserId
- LAST_AUDIO_PLAY
- buildCancelTextResponse
- dealWithEndRequest
+ dealNextPageIntent
+ dealLastPageIntent
+ channelId
+ backToBotIntro
+ dealBackIntent
+ dealStartIntent
+ OnProductDetail
+ s1
+ dealOpenNum
+ jytId
+ dealCollectHistoryJump
+ dealJumpIntent
userId
- yQiYt_RTsMxH92Tn4QsGNdwx
- OJPfsbbA5Qoac2XN3dKRj4Cx
- C1vISzheJtVumYBwGK0IekCtSzSeVyX6lbRIegoew28
- csvDic
- EtfZNKr3Nzh8+y3u1wQ11fYq2aAY+GWGJHyqmZUDHk8=
- buildResponseBeforeLoadout
- 4
- PhoneTemplate
- ASIDE_IMG
- log.info
+ baidu-screen-jiaoyou-audio-test
+ null
+ DplbotServiceUtil.sendOneFlowerByCharge
+ PlayUtils.getPlayDocument
+ XIAOAI_MP3_MARK
+ RequestTerminal
+ DplbotServiceUtil.doesUserCollectThisBot
+ curTime
+ userU
+ dealCollectOrUnCollectIntent
+ jytUserId
+ onInte
+ onIn
+ requestTerminate
+ ScheduleService
+ Task
+ lunchDocument
OPENID_CACHE
@@ -236,57 +243,57 @@
@@ -304,11 +311,11 @@
-
+
-
+
@@ -329,7 +336,7 @@
-
+
@@ -351,25 +358,25 @@
-
+
-
+
-
+
-
+
@@ -377,10 +384,43 @@
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -388,10 +428,21 @@
+
+
+
+
+
+
-
+
+
+
+
-
+
+
+
@@ -401,7 +452,6 @@
-
@@ -411,8 +461,7 @@
-
-
+
@@ -422,7 +471,8 @@
-
+
+
@@ -432,7 +482,7 @@
-
+
@@ -442,8 +492,7 @@
-
-
+
@@ -451,7 +500,9 @@
-
+
+
+
@@ -460,7 +511,6 @@
-
@@ -470,25 +520,20 @@
-
-
-
-
-
-
+
-
+
@@ -502,7 +547,7 @@
-
+
@@ -528,11 +573,11 @@
+
-
@@ -554,13 +599,13 @@
-
-
-
-
+
+
+
+
-
+
@@ -568,8 +613,8 @@
-
-
+
+
@@ -581,12 +626,12 @@
-
-
-
+
+
+
-
+
@@ -594,12 +639,12 @@
-
-
-
+
+
+
-
+
@@ -607,12 +652,12 @@
-
-
+
+
-
+
@@ -929,11 +974,8 @@
-
-
+
-
-
@@ -954,14 +996,17 @@
+
+
+
-
-
-
-
+
+
+
+
@@ -1136,6 +1181,11 @@
+
+
+
+
+
@@ -1145,7 +1195,7 @@
-
+
@@ -1157,7 +1207,7 @@
-
+
@@ -1167,11 +1217,11 @@
-
-
+
+
-
+
@@ -1179,23 +1229,23 @@
-
+
-
+
-
+
-
-
+
+
@@ -1208,396 +1258,429 @@
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
-
+
-
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
+
+
+
-
-
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
-
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
-
-
-
+
-
-
+
+
-
-
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
+
+
+
diff --git a/spirit/src/main/java/ai/qiwu/tmall/spirit/service/Test.java b/spirit/src/main/java/ai/qiwu/tmall/spirit/service/Test.java
new file mode 100644
index 0000000..b73d598
--- /dev/null
+++ b/spirit/src/main/java/ai/qiwu/tmall/spirit/service/Test.java
@@ -0,0 +1,52 @@
+package ai.qiwu.tmall.spirit.service;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author 苗权威
+ * @dateTime 20-1-10 下午1:29
+ */
+public class Test {
+
+ private static void testTts(String path) throws IOException {
+ List lines = Files.readAllLines(Paths.get(path));
+ List postList = new ArrayList<>();
+ List getDuList = new ArrayList<>();
+ List getAiList = new ArrayList<>();
+
+// lines.forEach(s -> {
+// String time = s.substring(s.indexOf("bytes")+6, s.indexOf(" ms"));
+// if (!s.contains("444920673") && Integer.parseInt(time) > 1000) {
+// System.out.println(s);
+// }
+// });
+
+ String s;
+ for (int i = 0; i < lines.size(); i++) {
+ s = lines.get(i);
+ if (s.contains("POST /api/audio")) {
+ for (int j=i+1; j < lines.size(); j++) {
+ s = lines.get(j);
+ if (lines.get(j).contains("GET /api/audio/get")) {
+ break;
+ } else if (s.contains("POST /api/audio")) {
+ getDuList.add(s);
+ break;
+ }
+ }
+ }
+ }
+ getDuList.forEach(System.out::println);
+// System.out.println(postList.size());
+// System.out.println("du:"+getDuList.size());
+// System.out.println("ai:"+getAiList.size());
+ }
+
+ public static void main(String[] args) throws IOException {
+ testTts("/home/yf01/下载/SpiritAudioCsv/ttsLog/access_log.2020-01-05.log");
+ }
+}
diff --git a/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java b/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java
index d2dd098..f802ca4 100644
--- a/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java
+++ b/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java
@@ -50,9 +50,9 @@ public class SpiritAudioUpload {
@Value("${csvDicForBotChange}")
private String csvDicForBotChange;
- private volatile String cookie = "cna=qsWIFY5RHlMCAXeJN3DsHj3O; isg=BISEdD_3hmKO7DG5UmXTs1qBVgu2NamassKvzp4kp88kySaTxK3xlqOrCaG0SuBf; CNZZDATA1261708326=1797143004-1560414985-%7C1578471815; _cnzz_CV1261708326=52463%7C%F0%9F%8C%8E%20skill-audio%2F%E9%9F%B3%E9%A2%91%E5%88%97%E8%A1%A8%E4%BF%A1%E6%81%AF%7Cp; enc=GlWCH0jde0teESrXYo%2BHF75NARTOPv7uKzyscUHesjr8NqyYTkHf%2BD6PG2iP4gPoGIsaO8aq%2BG41Q6kPPhYpvw%3D%3D; UM_distinctid=16ef9e5d343206-06ea6f889716618-76256753-1fa400-16ef9e5d344241; uc1=pas=0&cookie21=UtASsssme%2BBq&tag=8&cookie14=UoTbmEnmIFxXUw%3D%3D&existShop=false&cookie15=Vq8l%2BKCLz3%2F65A%3D%3D&lng=zh_CN&cookie16=VFC%2FuZ9az08KUQ56dCrZDlbNdA%3D%3D; t=925ffaa4a0ded6c2dc567c2eedd425f0; _tb_token_=3a3eeb3e68337; cookie2=145c78f447bf6a4cafb894c15072214f; dnk=tb13503054; tracknick=tb13503054; _l_g_=Ug%3D%3D; unb=1038446007; cookie1=UNMubI1eQ0gVOzLdxFCJj7hzIKFouglcA%2BlE1IYgcZQ%3D; login=true; cookie17=UoH8Vd06g9TEfA%3D%3D; _nk_=tb13503054; sg=47f; csg=f8c7b18a; ctoken=xWUW4TnhPzTyPnCGVcBbhyoc; EGG_SESS=OG910qv3Q3gsrSK4yqRmX3-1-P_ARlUIzlqweqLqnRF5dKELPTe4hiVT80Slz3WPDCsXS99IeB9EJ08mKe1fnB-ky5BqlihGxghSrDaTuitC4LiUArU9fvgELyGofw_TmBaNcyEfrWqC-x_N6rsy8fAw2Pnp69phx2I3tEHsYh8UPT0miVV8Iz9v1Gp1EBu-x7IkCs02BFaNjygAZj4yG5Q0XFHJIVNHemQrHeuxJonSTlJkY2dqCYo_wOLIM5KLVZFHGxoxDIPcuXi37C_MOfK9Sac-zJndlvITiVSRplldFUDbSnyGTHbkxO76r76v-8Pr05wfiN1zzWuCXeZ-ATYX0IDdKpdESz--8JEeGAA-CKkMaOU0K7eXljgXRjsiDcx7bszIDb68PlwlPJV_Ehu3_D2KxVdU_wzX2bzcl-wNpjjmLFUzhoA8YzGs_JsJ2t6rSnRnegg7T0ge7PayU5pvqzfy3hUlevZmqDjZsg2hhW0kAbxkakAlZo7pCAZ-eRFZP_B2VO1qF5N95H2FSGa6CZnH9Rqe1uvQH63cnoppDsHsTis8SMxgvkYBurwjdwjbCqu_DeDR5N_XCsTFRf5Q1Idgcn38mMvfA1PT1Nk2Ye9iWTshl4PD9e3kWc2o3RTKdJNlFkjGb1AUObOobAv1XUXhX0Lx4Ypm6JQIN-2LKqOO4yoqPThj2nfiL6-FVqgNOK0IAHr0EYZS-QXMIBPP5sTUOjOjPPPHc3hJWu0yytS19l7OrV6r5UPVflEJ6_nK_1la9e6AJuDlxI_-mx_qjLXU4cEGYWTF56qcmzXyIRWh0d-rud90Ags2e17C6bzH4ijeY3vQTR9Jezzz_CjiDaT43KLQ_71bHgRYF3DL0xn-HR6QzD0HFtIUHpW_dkeC4l7Lev5zvnXeGKEUE4H-aemCRcmnTW5Rso4-_m2uW6RfUEQ0RlfpFzixKujRu9qZkWDgDTCtEEmSErJ561-mO6PDKLgTifklbRkWLc0oNBuqO0gFdkb58O8lSNum8dwGslDo-eRzKrdB-D8B1-TISMLZm1tL2Aecn9MlXkZUPc62doJjHugczHRbNONrqKkcb0d-HVmOscGgnvl9unbt-fD0wm7225k0ZJ65jESe1LipeVth8W_6hQr2IFktNRqjrN_J8IEgY7NyTauVMDRfhlK1kJ75IPWfqomMQyi30wr2R0_k8rDunfbqf726gZTdKZ109dIsXcxpWsj4v9LGolfXDQQTEFURIXI-lsn1DFkz_LL51K5R9FAIAX00-c5weol75Jgdp1auJfGYuxMlApg8QpbyxL2jReOorI5ioYN76VpQ7RRvHxO1ZMRjNvYUjdHygMcvIqeNArccASaH4Qt5RQ1jrNUFcJ84KPd709GBLt8kxgtEttev9YFHdL3YwLeEJo70Q03BXA7acYQtSQ6iUMoVrR8chjwUJ10zpzcY8QucfrA6p4DdbotQq_n2dFQlWeGGVQUZc11Qr39fekHEc68vjl9TlqSOTqjgASSzg67U6vi3s6LbS1AYMATWzTd0AC281UkjEIkmsLbdinnBtddW5bHZhGeLF01AkvwtUW9oebboJY-4onsMwNivqv6Al7QaWehDeG7kdzWLrU-g9s-ZKa3bwhuMC3VOpgC1y5Vepe9xQilNube431z6JGGW484fbkPcqHG2lrg9uPW-faND328H16PwsihwptEE14JlvxPGLDAZnldYh3RBfhJ2JBR8uhyw7ll7qjAIEud0oOA9EXQg6ppi-KeA0Jvuu5g8a_DbWrg06oV_ZZEl9BUtA_3oCD6rV4Y8PeQqPgiv9cAAUz5c2d40Mmb4GOlJnFzmXxGMa9wZ7X6exvktUmqOrxU7dHEsiFS8XHPIAtBhV7naaoIHLGVxZXHv5Wgy0wPkZMRBJa1l4ipqptNfdz6wGD_M3Nf8feP0UrBOau7VQtqc01R4eXmScY9xoBubyfajp9xkMqJsptAUbE7wZuYNRGq8CwWw8zaDRSpSf3EKEh-THO5tESoXc12mIUn5wBT8kUtE2O828HMeGcJ3PI89QRNcYQeaTmikpzqQf0MiNIaJjsD1PdPC9pVjPQ-9HXWQLylSmgAEHvcqe-s1pCk-g03koACUqKUBnCxIjBaI_By_kMkg1-kuM7TVHTLXzaWGR0cWC6RifnJPC4TBDc7KX-QUsg9GzvDibKY-ZiKULXYQCZTr_p0nKpDqSDZTuEzD14S9m9zMxJXBYI4De-FwMlWjePQkyOME4omwfDrovY33_Hbch8-aOTleVR5BfsOyVhEUdN3Dqs5ARG6AQznfH-pmHLvERYC3-Q==; accountType=TB; accountId=52463; token=+yKlBN44OA/SyckKeOJUlJVzFRetm5fqY9FVaEzSRPE=; confirmProtocolVersion=1";
- private volatile String token = "+yKlBN44OA/SyckKeOJUlJVzFRetm5fqY9FVaEzSRPE=";
- private volatile String csrfToken = "xWUW4TnhPzTyPnCGVcBbhyoc";
+ private volatile String cookie = "cna=qsWIFY5RHlMCAXeJN3DsHj3O; isg=BNvaVmpjAXQDU34UoTi0hnnkaTaFGO4vMccg480nj1B7rE6P6IAnA6zqRsyHl0eq; CNZZDATA1261708326=1797143004-1560414985-%7C1578545339; _cnzz_CV1261708326=52463%7C%F0%9F%8C%8E%20skill%2F%E6%9F%A5%E8%AF%A2%E6%8A%80%E8%83%BD%7C0; enc=GlWCH0jde0teESrXYo%2BHF75NARTOPv7uKzyscUHesjr8NqyYTkHf%2BD6PG2iP4gPoGIsaO8aq%2BG41Q6kPPhYpvw%3D%3D; UM_distinctid=16ef9e5d343206-06ea6f889716618-76256753-1fa400-16ef9e5d344241; EGG_SESS=IdVWNkN2sAOQi1tLSNGnFK5nME5CTP2gTPH6kr89V-k6w6DhWzXgemwSZ-CtWPAe1Stlw2LZewllSuXxWuMyHGx_BNyTHR0DuqWpWr_t58VOdEaFO1qmpqmMOT0CSjxA5Rabb7w5lcyTHTy3w39hDbFqVW8sPjLq4KBzMvs1LcRawoGhgCaPLZ54bK7jJ41CgCLMRjekHPTq9HtHxzo2CEsmlBjYzt016HULppaaulo4FCE5d5IUGtVTmUeN3ufsxLeWrHSQFGz-s_XVflwSrlgtdjI3pKHw_fgunw-4bt8uFk8cG5dWYGacE6xkfq_KavlI2Ar_T61bhkdmvMFQhFRoqe_Qp8loplzIND3_jeoBHjQ25nmlzlYfsBHHIyOhbvwdPymLCcpmFkX2JpT5ovEHqUKV-lU45C93xsDPOY-9s2UrGPMRTAmGY84Kol57qfCNOXUl2wnfirzBKGeJEJo2o-v2T6qyeIFCc4WQqxOGKVYv30TvKQseKeLHFW0q31G-HzDYBoHAelres1yneHO_RLh61tsaYRvTAL4baQ2W5wKF2oxMf6pPtrP1gfmgCYdaW-Sf5WX3oAOTit-HBEGSS0tmQNX50yJprlGExPAPEMR2mzkyWaQhIIrcfXz4Cl8LgJasQZ12EbqbqxZA1x_G1_Bz7spmbOOAP6G97G_o2jQDNCh2_AtrIwFVA77nFIXPBru9FEjdGxyBk0xLqmsF5UClGg9ihLzZGEf8gF_-5BaRKhRXa0TPsYjLYkgUZVy9IHDmQLiMt7aSjZNtVdNJCbP8l5TNQ9wuKoslyb7sL--Jty-GiRWwQZEeqvMWois_KEqfsd3rLVrOUWDFeIPL_6hmvDxwYZgqOFWHjSeYc0bjntQRDpzG3oxMNBkHIM-rcy0eg1UiA1DvomfHYnyayFjqIXMxcOeH7v6l7_EGv9NKlUuHgvOjxwhl8MDfLWJ5jtEpjua6Idg8JH1FCth2icJTmwT9CfWWKWOYTYcwGKJuUiSA6T-Y2J-OHa4wmZwDU3bTggZDrSX_dmCFXbm_gxk2-FhunFJmZ9eWIl4_2YmPuAn7TKi8JBNxap5QGdpNF_XKN-78hyJR92_daoIv0IagZbvfdU1zGeNxpZeeudnraum8pNUXWtUWZlzuKs8OpjvY8JUuoK0Dx_mbZCQmY3-77ltZa5Z4PigPWMGMkYlGr1lusivSDqEW3fonRH5q79xvVIV2D61khPR2halgopkf87LBnnw53ym5i0Ne0q7oEbDzjgbsOliWWv6BUaCd6rg4lF3xWSM0vzvlAgu_R9cDy26h5t9ppxChHtzqw3sn-lFiOuuzgXwMh-uka3oLpvdgCHb2pXHBu-cU9ezQsSz5VA2jvDqbVHGpOFdK9YBoUNhNro4bwszvK_zWgPJiTTi1jx5VqQFWI61aIZnVrZUSVoq0kOuRK79-jTzOcsCqVY1gHCHPEvAw16BKQ584CW1QSFN52_ZsLlrP-SkkrjUJ7GZOMn_um9kbc-a68PKpBDVROG2rXvx8j5p66qY4vIFS9ayQJOeSQyHriQchweqHGeUEs4ngLcBdpeFk8JuAi-xJLUII3Rmt88vKax4SaZOg-9XKkvtef5jRE16NOPUXCiLD_0r9-Lbo0yKVSX3Wjim2gJXWvahilTtV8hBCw7VlQpbiwvAygEsrSFL9-B6dq-FS5cHbTqOZqTThxGdCRrAdMMVzPsfxR7UmSA8ykHRfmHgj3R6Xc1RyloPWr2JMKd9cf6wA03BV_XlpmfdoPzW8OH-cg0pcznY1dGmvkELbEI3RQk-2vDWhIBtcK6TR16wBTn955ZfI0tetTFMh9nD1i1E8qyDGqWJvC7WpikhlekHS3E_40Cvo-d5Kvs4oqrWLqWat-MNE61F-PCC7SDOiflXuf4agWpEWIeHwxaithtv0_32QWCzMGM_8lyGvRdazKMW_H4q7KiT0jtgTB4Tptjjtzs-DUeDXnuoVVNgIZ6evNQGi3QHGZgL3Okbhjn41elMxuu2COG3TgGfj-RfRc6Qlmj_da_Nzk54AkGkhCl_dS2XpmqCGdIrZg1PHjFaPvd_jktehC2kjN9IPdTt_9_BemwXUAJr2jRgcQKwMect1YMfehwG81w6Y3aLs4qXaPJXoEq8Tm03wuZ-uZBE6iGjNuIxe_gboReXulcdvWnxf-b7CoWpUgJBcO-h9bX3y6BS2RLVsPe-BJ0PLF1speq4GJlOYmkzjqt0caUtw83Bd5nXb-AP0jaEBxsdB0N0Nh23tFkjSGKbsCSS6WUOQ5jFDow9o7dld7NG-4g0UTU8fqiW5gjZ80gi8Vgh7kABVkypdeszxFUFdh06YsMe9pEJH8Su_vl4Rq6HL3ztMYA73Cq7SSh047A==; accountType=TB; confirmProtocolVersion=1; ctoken=hIPnBFZTxO70xYEKMWiVP5pJ; hng=CN%7Czh-CN%7CCNY%7C156; t=925ffaa4a0ded6c2dc567c2eedd425f0; tracknick=%5Cu9F50%5Cu609F%5Cu667A%5Cu80FD%5Cu8BED%5Cu97F3; lid=%E9%BD%90%E6%82%9F%E6%99%BA%E8%83%BD%E8%AF%AD%E9%9F%B3; _tb_token_=eebee77e7787e; cookie2=1bc42d8261746e9bfec4fbfb79e712fd; dnk=%5Cu9F50%5Cu609F%5Cu667A%5Cu80FD%5Cu8BED%5Cu97F3; uc1=lng=zh_CN&cookie16=VFC%2FuZ9az08KUQ56dCrZDlbNdA%3D%3D&pas=0&cookie15=V32FPkk%2Fw0dUvg%3D%3D&cookie21=V32FPkk%2FhSg%2F&existShop=false&cookie14=UoTbldffztSu3A%3D%3D&tag=8; _l_g_=Ug%3D%3D; unb=2201499686434; cookie1=BxSjQCQ6sp%2FKUbmJMrRM%2B%2FTeMnxnfP3Ky2LamSxw1u4%3D; login=true; cookie17=UUphy%2FZzlNvrKtsbCQ%3D%3D; _nk_=%5Cu9F50%5Cu609F%5Cu667A%5Cu80FD%5Cu8BED%5Cu97F3; sg=%E9%9F%B343; csg=04a77d7a; accountId=52463; token=t6PHfzW5l84NHrDFNmRRJVHclpUlndw3wDDsqNMRtbE=";
+ private volatile String token = "t6PHfzW5l84NHrDFNmRRJVHclpUlndw3wDDsqNMRtbE=";
+ private volatile String csrfToken = "hIPnBFZTxO70xYEKMWiVP5pJ";
public void updateCookie(String cookie) {
this.cookie = cookie;
@@ -221,7 +221,7 @@ public class SpiritAudioUpload {
ArrayList datas = new ArrayList<>();
List errorDatas = new ArrayList<>();
- int ln = 8;
+ int ln = 9;
int count = 0;
// int errorCount = 0;
@@ -651,7 +651,7 @@ public class SpiritAudioUpload {
List errorDatas = new ArrayList<>();
List datas = new ArrayList<>();
String description;
- int ln = 8;
+ int ln = 9;
int count = 0;
if (Boolean.TRUE.equals(record)) {
String root = "/root/TTS-service/audio/"+botAccount+"/record/";
@@ -848,7 +848,7 @@ public class SpiritAudioUpload {
String mp3FileName = path.substring(path.lastIndexOf("/")+1);
String randomMp3Name;
int i = 0;
- int ln = 8;
+ int ln = 9;
do {
if (i++ == 60) {
i = 0;
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
index d8cd15d..fc0d96d 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
@@ -1173,7 +1173,7 @@ public class TTService {
String.valueOf(pitch), mp3FilePath);
// log.info("CallPython.changeSoundByPython 耗时:{}",System.currentTimeMillis()-start);
if (!TTSUtils.doesFileExist(mp3FilePath)) {
- log.error("python代码出错,mp3文件没有创建成功");
+ log.error("python代码出错,mp3文件没有创建成功.{},{},{},{}", wavFilename, volume, speed, pitch);
res = new ResponseCodeWithData(555);
}
//long changeSoundEndTime = System.currentTimeMillis();
@@ -2120,10 +2120,12 @@ public class TTService {
if (xiaoAi) {
OkHttp3Utils.backPostAsync(audioUrl+type);
}
+ int count = 0;
if (Files.exists((pt = Paths.get(path)))) {
- while (XIAOAI_MP3_MARK.contains(path)) {
+ while (XIAOAI_MP3_MARK.contains(path) && count < 20) {
try {
Thread.sleep(500);
+ count++;
} catch (Exception e) {}
}
TTServiceUtil.buildMp3ResponseForAudioNoRange(response, path, xiaoAi);
@@ -2132,9 +2134,10 @@ public class TTService {
Thread.sleep(1500);
} catch (Exception e) {}
if (Files.exists(pt)) {
- while (XIAOAI_MP3_MARK.contains(path)) {
+ while (XIAOAI_MP3_MARK.contains(path) && count < 20) {
try {
Thread.sleep(300);
+ count++;
} catch (Exception e) {}
}
TTServiceUtil.buildMp3ResponseForAudioNoRange(response, path, xiaoAi);
@@ -2316,9 +2319,9 @@ public class TTService {
}
}
- public static void main(String[] args) {
- System.out.println(URLEncoder.encode("正常0c60f9484eaa35aa7a9e2879c574e8a3.mp3"));
- System.out.println(URLEncoder.encode("正常24f87c9e922d063260634941f5f75be2.mp3"));
- System.out.println(URLEncoder.encode("正常d1a75129c54ef3037bd44e25ab6eeb9a.mp3"));
+ public static void main(String[] args) throws UnsupportedEncodingException {
+ System.out.println(URLEncoder.encode("Ls69sFTjXN%2F6831N1VVdfw%3D%3D", "UTF-8"));
+ System.out.println(URLEncoder.encode("%2BnzkUO6JnLrmiWSlBQaZ9g%3D%3D", "UTF-8"));
+ System.out.println(URLEncoder.encode("EksNVVSieFTobNBZFEOeyw%3D%3D", "UTF-8"));
}
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java
index 148127d..c28e5e4 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java
@@ -280,6 +280,43 @@ public class Test {
}
}
+ private static int changeHanToNum(String numStr) {
+ List list = Arrays.asList("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
+ StringBuilder num = new StringBuilder();
+ boolean first = true;
+ for (String str: numStr.split("")) {
+ int i;
+ if (first) {
+ first = false;
+ if (str.equals("十")) num.append(1);
+ else if ((i = list.indexOf(str)) != -1) num.append(i);
+ }
+ else if ((i = list.indexOf(str)) != -1) num.append(i);
+ }
+ return Integer.parseInt(num.toString());
+ }
+
+ private static Integer extractNum(String numStr) {
+ int num;
+ try {
+ num = Integer.parseInt(numStr);
+ return num;
+ } catch (Exception e) {
+ int i;
+ if ((i=numStr.indexOf("第")) != -1) {
+ String str = numStr.substring(i+1, numStr.length()-1);
+ try {
+ num = Integer.parseInt(str);
+ } catch (Exception e1) {
+ num = changeHanToNum(str);
+ }
+ } else {
+ num = changeHanToNum(numStr);
+ }
+ }
+ return num;
+ }
+
public static void main(String[] args) {
Date date = new Date(1572522571234L);
@@ -291,6 +328,14 @@ public class Test {
Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
String[] notVariableTextArray = pattern.split("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71");
- System.out.println(TTSUtils.buildMP3Filename("为您推荐以上作品:《妖刀异闻录》、《小太阳》、《遇见伽利略》,你可以说:打开某作品"));
+ System.out.println(extractNum("27"));
+ System.out.println(extractNum("二十六"));
+ System.out.println(extractNum("十六"));
+ System.out.println(extractNum("六"));
+ System.out.println(extractNum("第五个"));
+ System.out.println(extractNum("第十五个"));
+ System.out.println(extractNum("第二十六个"));
+ System.out.println(extractNum("第7个"));
+ System.out.println(extractNum("第17个"));
}
}
diff --git a/xiaoduhome/pom.xml b/xiaoduhome/pom.xml
index c1146b5..bc40497 100755
--- a/xiaoduhome/pom.xml
+++ b/xiaoduhome/pom.xml
@@ -32,6 +32,10 @@
spring-boot-starter-websocket
+ org.springframework.boot
+ spring-boot-starter-data-redis
+
+
mysql
mysql-connector-java
runtime
@@ -144,7 +148,6 @@
commons-lang3
3.9
-
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Utils.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Utils.java
index 6912088..eff4d57 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Utils.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Utils.java
@@ -11,10 +11,7 @@ import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Objects;
+import java.util.*;
/**
* @author 苗权威
@@ -30,6 +27,9 @@ public class Utils {
private static final String REGEX_SEPERATE = "【(.+?)】";
+ private static final String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
+// private static final String[] s2 = { "十", "百", "千"};
+
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder
.getRequestAttributes())).getRequest();
@@ -252,13 +252,29 @@ public class Utils {
}
}
+ public static int changeHanToNum(String numStr) {
+ List list = Arrays.asList(s1);
+ StringBuilder num = new StringBuilder();
+ boolean first = true;
+ for (String str: numStr.split("")) {
+ int i;
+ if (first) {
+ first = false;
+ if (str.equals("十")) num.append(1);
+ else if ((i = list.indexOf(str)) != -1) num.append(i);
+ }
+ else if ((i = list.indexOf(str)) != -1) num.append(i);
+ }
+ return Integer.parseInt(num.toString());
+ }
+
public static void main(String[] args) throws ParseException {
String s = "[{\"type\": \"SendEvent\",\"componentId\":\"%s\"}]";
//System.out.println(String.format(s, "gsagh"));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(System.currentTimeMillis());
Timestamp timestamp = Timestamp.valueOf(time);
- System.out.println(timestamp);
- System.out.println(format.format(new Date(System.currentTimeMillis())));
+
+
}
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/config/RedisConfig.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/config/RedisConfig.java
new file mode 100644
index 0000000..82ae6b1
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/config/RedisConfig.java
@@ -0,0 +1,42 @@
+package ai.qiwu.com.xiaoduhome.common.config;
+
+import ai.qiwu.com.xiaoduhome.pojo.OverTimeDetail;
+import ai.qiwu.com.xiaoduhome.pojo.XiaoDuNoScreenStore;
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+/**
+ * @author 苗权威
+ * @dateTime 20-1-9 下午7:54
+ */
+@Configuration
+public class RedisConfig {
+
+ @Bean
+ public RedisTemplate xiaoduRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
+ RedisTemplate redisTemplate = new RedisTemplate<>();
+ redisTemplate.setConnectionFactory(redisConnectionFactory);
+
+ Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(XiaoDuNoScreenStore.class);
+
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+ objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+
+ serializer.setObjectMapper(objectMapper);
+
+ redisTemplate.setKeySerializer(new StringRedisSerializer());
+ redisTemplate.setValueSerializer(serializer);
+ redisTemplate.setHashKeySerializer(new StringRedisSerializer());
+ redisTemplate.setHashValueSerializer(serializer);
+ redisTemplate.afterPropertiesSet();
+ return redisTemplate;
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/TempleUtils.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/TempleUtils.java
index e681e20..9256f04 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/TempleUtils.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/TempleUtils.java
@@ -17,6 +17,7 @@ import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommandPojo;
import ai.qiwu.com.xiaoduhome.entity.primary.GameProjectTb;
import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail;
import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuHistoryBotIdTime;
+import ai.qiwu.com.xiaoduhome.pojo.data.ProjectData;
import ai.qiwu.com.xiaoduhome.pojo.dpl.Item;
import ai.qiwu.com.xiaoduhome.pojo.dpl.MyDocument;
import ai.qiwu.com.xiaoduhome.pojo.pageData.HistoryData;
@@ -254,9 +255,9 @@ public class TempleUtils {
return collect;
}
- public static List buildDataList(List list, int begin) {
+ public static List buildDataList(List list, int begin) {
ArrayList dataList = new ArrayList<>();
- for (GameProjectTb projectInfo : list) {
+ for (ProjectData projectInfo : list) {
String productName = correctName(projectInfo.getName());
String imageId = new StringBuilder(Constants.PRE_PRODUCT_IMG).append(projectInfo.getName()).toString();
String src = new StringBuilder(IMG_PREFIX).append(projectInfo.getBannerImgUrl()).toString();
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/onLunch/LunchUtils.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/onLunch/LunchUtils.java
index bf49b81..533bf79 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/onLunch/LunchUtils.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/onLunch/LunchUtils.java
@@ -3,6 +3,7 @@ package ai.qiwu.com.xiaoduhome.common.temple.onLunch;
import ai.qiwu.com.xiaoduhome.common.temple.TempleUtils;
import ai.qiwu.com.xiaoduhome.pojo.dpl.Event;
import ai.qiwu.com.xiaoduhome.service.ScheduleService;
+import ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
@@ -21,26 +22,53 @@ public class LunchUtils {
private static final LunchPojo LUNCH_LOGO_IMG = buildLogoImage();
private static final LunchPojo LUNCH_HSITORY_IMG = buildHistoryImg();
private static final LunchPojo LUNCH_COLLECT_IMG = buildCollectImg();
- private volatile static LunchDocument lunchDocument = buildLunchDocument();
+ private volatile static LunchDocument lunchDocument = buildLunchNewDocument();
- public static LunchDocument buildLunchDocument() {
+
+ private static LunchDocument buildLunchNewDocument() {
LunchDocument document = new LunchDocument();
document.setDuration(240000);
LunchMainTemplate mainTemplate = new LunchMainTemplate();
document.setMainTemplate(mainTemplate);
- LunchPojo conRecommend = buildLunchList(TempleUtils.buildDataList(ScheduleService.getRecommendList(),1));
- conRecommend.setFirstItem(Collections.singletonList(TempleUtils.getFrameRecommand()));
- conRecommend.setMarginTop("8dp");
+ int size = ScheduleServiceNew.allProjects.size();
+ int rows = size/4 + (size%4 == 0?0:1);
+ int i = 0;
+ List list = new ArrayList<>();
+ LunchPojo rowCon;
+ int begin, end;
+ while (i < rows) {
+ begin = i*4;
+ end = begin+4 > size ? size : begin+4;
+ rowCon = buildLunchList(TempleUtils.buildDataList(ScheduleServiceNew.allProjects.subList(begin, end),begin+1));
+ list.add(rowCon);
+ i++;
+ }
+ LunchPojo scroll = buildLunchScroll();
+ scroll.setItems(list);
+
+ mainTemplate.getItems().addAll(Arrays.asList(LUNCH_BACK_IMG,LUNCH_HEAD,LUNCH_LOGO_IMG,LUNCH_HSITORY_IMG,LUNCH_COLLECT_IMG,scroll));
+ return document;
+ }
+
+ public static LunchDocument buildLunchDocument() {
+ LunchDocument document = new LunchDocument();
+ document.setDuration(240000);
+ LunchMainTemplate mainTemplate = new LunchMainTemplate();
+ document.setMainTemplate(mainTemplate);
- LunchPojo conRanking = buildLunchList(TempleUtils.buildDataList(ScheduleService.getRankingList(), 9));
- conRanking.setFirstItem(Collections.singletonList(TempleUtils.getFrameRakking()));
+// LunchPojo conRecommend = buildLunchList(TempleUtils.buildDataList(ScheduleService.getRecommendList(),1));
+// conRecommend.setFirstItem(Collections.singletonList(TempleUtils.getFrameRecommand()));
+// conRecommend.setMarginTop("8dp");
+//
+// LunchPojo conRanking = buildLunchList(TempleUtils.buildDataList(ScheduleService.getRankingList(), 9));
+// conRanking.setFirstItem(Collections.singletonList(TempleUtils.getFrameRakking()));
LunchPojo conCategory = buildLunchCategoryList(TempleUtils.buildCategoryDataList());
conCategory.setFirstItem(Collections.singletonList(TempleUtils.getFrameCategory()));
LunchPojo scroll = buildLunchScroll();
- scroll.setItems(Arrays.asList(conRecommend,conRanking,conCategory));
+// scroll.setItems(Arrays.asList(conRecommend,conRanking,conCategory));
mainTemplate.getItems().addAll(Arrays.asList(LUNCH_BACK_IMG,LUNCH_HEAD,LUNCH_LOGO_IMG,LUNCH_HSITORY_IMG,LUNCH_COLLECT_IMG,scroll));
return document;
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/play/PlayUtils.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/play/PlayUtils.java
index bcf05a8..6942d1c 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/play/PlayUtils.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/play/PlayUtils.java
@@ -1,9 +1,9 @@
package ai.qiwu.com.xiaoduhome.common.temple.play;
+import ai.qiwu.com.xiaoduhome.pojo.ActorWithWord;
import ai.qiwu.com.xiaoduhome.pojo.dpl.Event;
import ai.qiwu.com.xiaoduhome.pojo.playAside.PlayPageData;
import ai.qiwu.com.xiaoduhome.service.ScheduleService;
-import com.baidu.dueros.data.response.directive.audioplayer.Play;
import java.util.*;
@@ -22,7 +22,7 @@ public class PlayUtils {
private static final PlayPojo PLAY_LIST_ITEM = buildContent();
- public static PlayDocument getPlayDocument(String headerName, List actors, String[] actorWord,
+ public static PlayDocument getPlayDocument(String headerName, List aws,
String audio, String botAccount) {
PlayDocument document = new PlayDocument();
document.setDuration(110000);
@@ -30,10 +30,9 @@ public class PlayUtils {
document.setMainTemplate(mainTemplate);
List dataList = new ArrayList<>();
- int i = 0;
- for (String actor: actors) {
- PlayPageData data = new PlayPageData(actor, ScheduleService.getAsideImgUrl(botAccount, actor),
- actorWord[i++].replaceAll("
","\n"));
+ for (ActorWithWord aw: aws) {
+ PlayPageData data = new PlayPageData(aw.getActor(), ScheduleService.getAsideImgUrl(botAccount, aw.getActor()),
+ aw.getText().replaceAll("
","\n"));
dataList.add(data);
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/recommand/RecommendUtil.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/recommand/RecommendUtil.java
index e69875b..7fe25d2 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/recommand/RecommendUtil.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/temple/recommand/RecommendUtil.java
@@ -3,13 +3,12 @@ package ai.qiwu.com.xiaoduhome.common.temple.recommand;
import ai.qiwu.com.xiaoduhome.common.Constants;
import ai.qiwu.com.xiaoduhome.common.temple.TempleUtils;
-import ai.qiwu.com.xiaoduhome.entity.primary.GameProjectTb;
import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail;
-import ai.qiwu.com.xiaoduhome.pojo.dpl.Data;
+import ai.qiwu.com.xiaoduhome.pojo.data.ProjectData;
import ai.qiwu.com.xiaoduhome.pojo.dpl.Event;
import ai.qiwu.com.xiaoduhome.service.ScheduleService;
+import ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.stereotype.Component;
import java.io.File;
import java.util.*;
@@ -35,7 +34,7 @@ public class RecommendUtil {
private static volatile RecommandDocument rankDocument;
- public static RecommandDocument getRecommendDocument(int num) {
+ public static RecommandDocument getRecommendDocument(int num, String channelId) {
RecommandDocument document = new RecommandDocument();
document.setDuration(120000);
RecommandMainTemplate mainTemplate = new RecommandMainTemplate();
@@ -49,8 +48,8 @@ public class RecommendUtil {
List scrollList = new ArrayList<>();
scrollView.setItems(scrollList);
- int bound = ScheduleService.getAllProductCount();
- List bots = ScheduleService.getAllOnProduct();
+ List bots = ScheduleServiceNew.getTheChannelAllProjectData(channelId);
+ int bound = bots.size();
StringBuilder botIds = new StringBuilder();
int begin = num*RE_RA_CA_PAGE_SIZE;
@@ -105,7 +104,7 @@ public class RecommendUtil {
int count = 0;
while (begin < bound) {
end = begin+4 <= bound ? begin+4 : bound;
- scrollList.add(buildRecommendList(getListDataNoIds(count, begin, end, bots)));
+ scrollList.add(buildRecommendList(getListDataNoIds(count, begin, end, null)));
count++;
begin = end;
}
@@ -119,7 +118,7 @@ public class RecommendUtil {
return document;
}
- public static RecommandDocument getRankDocumentFirstPage() {
+ public static RecommandDocument getRankDocumentFirstPage(String channelId) {
if (rankDocument != null) return rankDocument;
RecommandDocument document = new RecommandDocument();
document.setDuration(120000);
@@ -141,23 +140,27 @@ public class RecommendUtil {
rowContainer.setMarginBottom("55dp");
StringBuilder botIds = new StringBuilder();
- List list = ScheduleService.getRANK_ORDER_IDs();
+ List list = ScheduleServiceNew.getTheChannelProjectsByWatch(channelId);
//log.info("RANK_ORDER_ID_LIST size = "+list.size());
- OnProductDetail first = list.get(0);
+ ProjectData first = list.get(0);
botIds.append(first.getBotAccount()).append(File.separator);
- OnProductDetail second = list.get(1);
+ ProjectData second = list.get(1);
botIds.append(second.getBotAccount()).append(File.separator);
- OnProductDetail third = list.get(2);
+ ProjectData third = list.get(2);
botIds.append(third.getBotAccount()).append(File.separator);
- OnProductDetail forth = list.get(3);
+ ProjectData forth = list.get(3);
botIds.append(forth.getBotAccount()).append(File.separator);
- RecommandPojo pojoFirst = buildImgFrmTxtContainerFirstRow(new StringBuilder(Constants.IMG_PREFIX).append(first.getBannerImgUrl()).toString(), new StringBuilder(Constants.PRE_PRODUCT_IMG).append(first.getName()).toString(),
+ RecommandPojo pojoFirst = buildImgFrmTxtContainerFirstRow(new StringBuilder(Constants.IMG_PREFIX)
+ .append(first.getBannerImgUrl()).toString(), new StringBuilder(Constants.PRE_PRODUCT_IMG).append(first.getName()).toString(),
TempleUtils.correctName(first.getName()), "first.png");
- RecommandPojo pojoSe = buildImgFrmTxtContainerFirstRow(new StringBuilder(Constants.IMG_PREFIX).append(second.getBannerImgUrl()).toString(), new StringBuilder(Constants.PRE_PRODUCT_IMG).append(second.getName()).toString(),
+ RecommandPojo pojoSe = buildImgFrmTxtContainerFirstRow(new StringBuilder(Constants.IMG_PREFIX)
+ .append(second.getBannerImgUrl()).toString(), new StringBuilder(Constants.PRE_PRODUCT_IMG).append(second.getName()).toString(),
TempleUtils.correctName(second.getName()), "second.png");
- RecommandPojo pojoThird = buildImgFrmTxtContainerFirstRow(new StringBuilder(Constants.IMG_PREFIX).append(third.getBannerImgUrl()).toString(), new StringBuilder(Constants.PRE_PRODUCT_IMG).append(third.getName()).toString(),
+ RecommandPojo pojoThird = buildImgFrmTxtContainerFirstRow(new StringBuilder(Constants.IMG_PREFIX)
+ .append(third.getBannerImgUrl()).toString(), new StringBuilder(Constants.PRE_PRODUCT_IMG).append(third.getName()).toString(),
TempleUtils.correctName(third.getName()), "third.png");
- RecommandPojo pojoFourth = buildImgFrmTxtContainerFourth(new StringBuilder(Constants.IMG_PREFIX).append(forth.getBannerImgUrl()).toString(), new StringBuilder(Constants.PRE_PRODUCT_IMG).append(forth.getName()).toString(),
+ RecommandPojo pojoFourth = buildImgFrmTxtContainerFourth(new StringBuilder(Constants.IMG_PREFIX)
+ .append(forth.getBannerImgUrl()).toString(), new StringBuilder(Constants.PRE_PRODUCT_IMG).append(forth.getName()).toString(),
TempleUtils.correctName(forth.getName()));
rowContainer.setItems(Arrays.asList(pojoFirst, pojoSe, pojoThird, pojoFourth));
@@ -168,7 +171,7 @@ public class RecommendUtil {
//scrollList.add(buildRecommendList(getListData(3, 12, 16, list, botIds)));
mainTemplate.getItems().addAll(Arrays.asList(RECOM_BACK_IMG,RANK_HEAD,scrollView,buildPageButton(1,
- ScheduleService.getRankPageSize()),RANK_CATEGORY_FOOTER));
+ list.size()),RANK_CATEGORY_FOOTER));
botIds.deleteCharAt(botIds.length()-1);
String idToken = Base64.getEncoder().encodeToString(botIds.toString().getBytes());
@@ -177,7 +180,7 @@ public class RecommendUtil {
return document;
}
- public static RecommandDocument getRankOtherPageDocument(int num) {
+ public static RecommandDocument getRankOtherPageDocument(int num, String channelId) {
RecommandDocument document = new RecommandDocument();
document.setDuration(120000);
RecommandMainTemplate mainTemplate = new RecommandMainTemplate();
@@ -191,7 +194,7 @@ public class RecommendUtil {
List scrollList = new ArrayList<>();
scrollView.setItems(scrollList);
- List list = ScheduleService.getRANK_ORDER_IDs();
+ List list = ScheduleServiceNew.getTheChannelProjectsByWatch(channelId);
int bound = list.size();
int begin = num*RE_RA_CA_PAGE_SIZE;
int end;
@@ -207,7 +210,7 @@ public class RecommendUtil {
begin = end;
}
mainTemplate.getItems().addAll(Arrays.asList(RECOM_BACK_IMG,RANK_HEAD,scrollView,
- buildPageButton(num+1, ScheduleService.getRankPageSize()),RANK_CATEGORY_FOOTER));
+ buildPageButton(num+1, list.size()),RANK_CATEGORY_FOOTER));
botIds.deleteCharAt(botIds.length()-1);
String idToken = Base64.getEncoder().encodeToString(botIds.toString().getBytes());
@@ -215,7 +218,7 @@ public class RecommendUtil {
return document;
}
- public static RecommandDocument getFunnyDocument(List bots, String audio) {
+ public static RecommandDocument getFunnyDocument(List bots, String audio) {
RecommandDocument document = new RecommandDocument();
document.setDuration(90000);
RecommandMainTemplate mainTemplate = new RecommandMainTemplate();
@@ -224,7 +227,7 @@ public class RecommendUtil {
List data = new ArrayList<>();
StringBuilder botIds = new StringBuilder();
int num = 0;
- for (OnProductDetail bot: bots) {
+ for (ProjectData bot: bots) {
String imgSrc = new StringBuilder(Constants.IMG_PREFIX).append(bot.getBannerImgUrl()).toString();
String imageId = new StringBuilder(Constants.PRE_PRODUCT_IMG).append(bot.getName()).toString();
RecommandBotInfo detail = new RecommandBotInfo(imgSrc,imageId, TempleUtils.correctName(bot.getName()));
@@ -446,11 +449,11 @@ public class RecommendUtil {
return fCon;
}
- private static List getListData(int row,int begin, int end, List bots, StringBuilder botIds) {
+ private static List getListData(int row,int begin, int end, List bots, StringBuilder botIds) {
List data = new ArrayList<>();
int n = 1+row*4;
for (int i = begin; i < end; i++) {
- OnProductDetail bot = bots.get(i);
+ ProjectData bot = bots.get(i);
botIds.append(bot.getBotAccount()).append(File.separator);
String imgSrc = new StringBuilder(Constants.IMG_PREFIX).append(bot.getBannerImgUrl()).toString();
String imageId = new StringBuilder(Constants.PRE_PRODUCT_IMG).append(bot.getName()).toString();
@@ -461,11 +464,11 @@ public class RecommendUtil {
return data;
}
- private static List getListDataNoIds(int row,int begin, int end, List bots) {
+ private static List getListDataNoIds(int row,int begin, int end, List bots) {
List data = new ArrayList<>();
int n = 1+row*4;
for (int i = begin; i < end; i++) {
- OnProductDetail bot = bots.get(i);
+ ProjectData bot = bots.get(i);
String imgSrc = new StringBuilder(Constants.IMG_PREFIX).append(bot.getBannerImgUrl()).toString();
String imageId = new StringBuilder(Constants.PRE_PRODUCT_IMG).append(bot.getName()).toString();
RecommandBotInfo detail = new RecommandBotInfo(imgSrc,imageId, TempleUtils.correctName(bot.getName()));
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/SpiritController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/SpiritController.java
index 3995243..f95409b 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/SpiritController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/SpiritController.java
@@ -8,6 +8,7 @@ import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
@@ -27,6 +28,9 @@ public class SpiritController {
this.spiritService = spiritService;
}
+ @Value("${num}")
+ private String num;
+
/**
* 利用天猫精灵打开发包解析请求并从构造响应数据返回
* @param taskQuery 请求的参数信息
@@ -39,7 +43,7 @@ public class SpiritController {
// build response
ResultModel resultModel = new ResultModel<>();
- TaskResult taskResult = spiritService.getResponse(query, 1);
+ TaskResult taskResult = spiritService.getResponse(query, 4);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
// log.info("天猫响应信息:"+ JSON.toJSONString(resultModel));
@@ -107,4 +111,13 @@ public class SpiritController {
return resultModel;
}
+ @PostMapping("/update/{one}")
+ public void updateCsvMap(@RequestBody String secId, @PathVariable String one) {
+ if ("qiwuAudioMqw123.".equals(secId)) {
+ if (one.equals(num)) {
+ spiritService.updateSpiritCsv();
+ }
+ }
+ }
+
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/WebSocketLogController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/WebSocketLogController.java
index 6721c12..f2e54ca 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/WebSocketLogController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/WebSocketLogController.java
@@ -17,7 +17,7 @@ import java.util.concurrent.ConcurrentHashMap;
* @author 苗权威
* @dateTime 19-11-18 下午6:37
*/
-//@Controller
+@Controller
@Slf4j
public class WebSocketLogController {
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java
index 08a43e0..28bcf16 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java
@@ -6,6 +6,7 @@ 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.XiaoAiServiceRedis;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiTestService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
@@ -34,6 +35,7 @@ public class XiaoAiController {
private final XiaoAiService xiaoAiService;
private final XiaoAiTestService xiaoAiTestService;
+ private final XiaoAiServiceRedis xiaoAiServiceRedis;
/**
* Controller控制器
@@ -94,7 +96,7 @@ public class XiaoAiController {
log.info("请求:"+str);
XiaoAiRequest request = JSON.parseObject(str, XiaoAiRequest.class);
request.setType(5);
- XiaoAiResponse response = xiaoAiTestService.getResponse(request);
+ XiaoAiResponse response = xiaoAiServiceRedis.getResponse(request);
log.info("响应:"+response);
return response;
} catch (Exception e) {
@@ -110,6 +112,33 @@ public class XiaoAiController {
// return xiaoAiService.getResponse(request);
}
+ @PostMapping("/phone") //互动故事
+ // @RequestBody XiaoAiRequest request,
+ public XiaoAiResponse xiaoaiPhoneStory(HttpServletRequest servletRequest) {
+// long start = System.currentTimeMillis();
+// if (!Utils.encry(3, servletRequest)) return null;
+// log.info("encry:"+(System.currentTimeMillis()-start));
+
+ try (InputStream stream = servletRequest.getInputStream()){
+ StringBuilder sb = new StringBuilder();
+ byte[] b = new byte[4096];
+ for (int n; (n = stream.read(b)) != -1;)
+ {
+ sb.append(new String(b, 0, n));
+ }
+ String str = sb.toString();
+ log.info("请求:"+str);
+ XiaoAiRequest request = JSON.parseObject(str, XiaoAiRequest.class);
+ request.setType(5);
+ XiaoAiResponse response = xiaoAiTestService.getResponse(request);
+ log.info("响应:"+response);
+ return response;
+ } catch (Exception e) {
+
+ }
+ return null;
+ }
+
@PostMapping("/adult")
public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request, HttpServletRequest servletRequest) { // 智能小说
//log.info("请求:"+request);
@@ -141,8 +170,8 @@ public class XiaoAiController {
@GetMapping("/audio/play")
public void xiaoaiPlayed(String userId) {
if (StringUtils.isNotBlank(userId)) {
-// log.info("小爱确认音频播放:"+userId);
-// xiaoAiService.changeAudioPlayMark(userId);
+ log.info("小爱确认音频播放:"+userId);
+ xiaoAiServiceRedis.theAudioAlreadyPlay(userId);
}
else log.error("/xiaoai/audio/play userId is null");
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
index 4a622e4..ecb3199 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
@@ -1,6 +1,8 @@
package ai.qiwu.com.xiaoduhome.controller;
import ai.qiwu.com.xiaoduhome.common.Utils;
+import ai.qiwu.com.xiaoduhome.pojo.OverTimeDetail;
+import ai.qiwu.com.xiaoduhome.service.DplBotRedisService;
import ai.qiwu.com.xiaoduhome.service.DplBotService;
import ai.qiwu.com.xiaoduhome.service.ResponseEncapsulation;
import ai.qiwu.com.xiaoduhome.spirit.SpiritService;
@@ -15,6 +17,8 @@ import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@@ -41,6 +45,13 @@ public class XiaoDuHomeController {
private int test = 0;
+ private final StringRedisTemplate stringRedisTemplate;
+
+ @Autowired
+ public XiaoDuHomeController(StringRedisTemplate stringRedisTemplate) {
+ this.stringRedisTemplate = stringRedisTemplate;
+ }
+
@RequestMapping(value = "/chat", method = RequestMethod.HEAD)
public void chatHead(HttpServletResponse response) {
// if (test++ < 5) {
@@ -104,16 +115,17 @@ public class XiaoDuHomeController {
}
@PostMapping("/story") //交互故事
- public String story() {
+ public String story(HttpServletRequest request) {
try {
//log.info("--------------分界线-------------------");
- DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 5);
+// DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 5);
// log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
- log.info(service.getStrRequest());
+ DplBotRedisService service = new DplBotRedisService(request, 5, stringRedisTemplate);
+// log.info(service.getStrRequest());
//service.disableVerify();
service.enableVerify();
String str = service.run();
- log.info("响应信息:{}", str);
+// log.info("响应信息:{}", str);
return str;
} catch (Exception e) {
e.printStackTrace();
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/ActorWithWord.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/ActorWithWord.java
new file mode 100644
index 0000000..6333edf
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/ActorWithWord.java
@@ -0,0 +1,17 @@
+package ai.qiwu.com.xiaoduhome.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 20-1-17 下午2:40
+ */
+@Getter
+@Setter
+@ToString
+public class ActorWithWord {
+ private String actor;
+ private String text;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/OverTimeDetail.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/OverTimeDetail.java
index 8979790..10e6306 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/OverTimeDetail.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/OverTimeDetail.java
@@ -5,7 +5,9 @@ import com.baidu.dueros.model.Response;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
+import lombok.ToString;
+import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -17,8 +19,11 @@ import java.util.Map;
*/
@Getter
@Setter
-public class OverTimeDetail {
+@ToString
+public class OverTimeDetail implements Serializable {
+ private static final long serialVersionUID = 1L;
+
private final List directives = new ArrayList<>();
private final Map attributes = new HashMap<>();
- private volatile Response response = new Response();
+ private volatile Response response;
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/SendFlowerVO.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/SendFlowerVO.java
new file mode 100644
index 0000000..5864ae6
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/SendFlowerVO.java
@@ -0,0 +1,22 @@
+package ai.qiwu.com.xiaoduhome.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 20-1-17 下午7:45
+ */
+@Getter
+@Setter
+@ToString
+public class SendFlowerVO {
+ private String botAccount;
+ private Long num;
+ private Double unitPrice;
+ private String userId;
+ private String name;
+ private String channelId;
+ private Long orderId;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/UserBehaviorData.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/UserBehaviorData.java
index a1bcf35..e461480 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/UserBehaviorData.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/UserBehaviorData.java
@@ -6,6 +6,7 @@ import lombok.ToString;
import java.util.HashMap;
import java.util.List;
+import java.util.Map;
/**
* @author 苗权威
@@ -16,11 +17,11 @@ import java.util.List;
@ToString
public class UserBehaviorData {
// 用户浏览历史
- private volatile HashMap userBotId2History = new HashMap<>();
+ private volatile Map userBotId2History = new HashMap<>();
// 用户对作品所送花的数目
- private volatile HashMap userBotId2Flowers = new HashMap<>();
+ private volatile Map userBotId2Flowers = new HashMap<>();
// 用户是否收藏该作品
- private volatile HashMap userBotId2Collected = new HashMap<>();
+ private volatile Map userBotId2Collected = new HashMap<>();
// 标记清除,每半小时标记一次
private volatile Byte mark = 1;
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/XiaoDuNoScreenStore.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/XiaoDuNoScreenStore.java
new file mode 100644
index 0000000..36a5c77
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/XiaoDuNoScreenStore.java
@@ -0,0 +1,17 @@
+package ai.qiwu.com.xiaoduhome.pojo;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * @author 苗权威
+ * @dateTime 20-1-13 下午1:35
+ */
+@Getter
+@Setter
+@ToString
+public class XiaoDuNoScreenStore {
+ private volatile String audio;
+ private volatile String noPlay;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/data/ProjectData.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/data/ProjectData.java
new file mode 100644
index 0000000..3af799e
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/data/ProjectData.java
@@ -0,0 +1,26 @@
+package ai.qiwu.com.xiaoduhome.pojo.data;
+
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+import java.sql.Timestamp;
+import java.util.List;
+
+/**
+ * @author 苗权威
+ * @dateTime 20-1-15 下午8:30
+ */
+@Getter
+@Setter
+@ToString
+public class ProjectData {
+ private String name;
+ private String intro;
+ private String authorName;
+ private Boolean free;
+ private String botAccount;
+ private String bannerImgUrl;
+ private Timestamp createTime;
+ private List labels;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/secondary/XiaoDuOrderTbRepository.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/secondary/XiaoDuOrderTbRepository.java
index e3fc423..9329338 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/secondary/XiaoDuOrderTbRepository.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/repository/secondary/XiaoDuOrderTbRepository.java
@@ -24,6 +24,8 @@ public interface XiaoDuOrderTbRepository extends JpaRepository S saveAndFlush(S s);
+ XiaoDuOrderTB getByChOrderId (String chOrderId);
+
@Modifying
@Transactional(rollbackFor = Exception.class)
@Query(value = "UPDATE xiaodu_order_tb SET order_id=?1,status=1,update_time=now() WHERE ch_order_id=?2",nativeQuery = true)
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotRedisService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotRedisService.java
new file mode 100755
index 0000000..06ce27a
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotRedisService.java
@@ -0,0 +1,2377 @@
+package ai.qiwu.com.xiaoduhome.service;
+
+//import ai.qiwu.com.xiaoduhome.common.BaseHolder;
+//import ai.qiwu.com.xiaoduhome.common.Constants;
+//import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
+//import ai.qiwu.com.xiaoduhome.common.Utils;
+//import ai.qiwu.com.xiaoduhome.common.temple.CollectHistoryDocument;
+//import ai.qiwu.com.xiaoduhome.common.temple.TempleUtils;
+//import ai.qiwu.com.xiaoduhome.common.temple.onLunch.LunchUtils;
+//import ai.qiwu.com.xiaoduhome.common.temple.play.PlayDocument;
+//import ai.qiwu.com.xiaoduhome.common.temple.play.PlayUtils;
+//import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoDocument;
+//import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoUtils;
+//import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommandDocument;
+//import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommendUtil;
+//import ai.qiwu.com.xiaoduhome.entity.primary.GameProjectTb;
+//import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail;
+//import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB;
+//import ai.qiwu.com.xiaoduhome.pojo.*;
+//import ai.qiwu.com.xiaoduhome.pojo.dpl.MyDocument;
+//import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository;
+//import ai.qiwu.com.xiaoduhome.spirit.SpiritRedisService;
+//import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
+//import com.alibaba.fastjson.JSON;
+//import com.alibaba.fastjson.JSONArray;
+//import com.alibaba.fastjson.JSONObject;
+import com.baidu.dueros.bot.BaseBot;
+//import com.baidu.dueros.data.request.IntentRequest;
+//import com.baidu.dueros.data.request.LaunchRequest;
+//import com.baidu.dueros.data.request.Query;
+//import com.baidu.dueros.data.request.SessionEndedRequest;
+//import com.baidu.dueros.data.request.audioplayer.event.*;
+//import com.baidu.dueros.data.request.events.LinkAccountSucceededEvent;
+//import com.baidu.dueros.data.request.pay.event.ChargeEvent;
+//import com.baidu.dueros.data.response.OutputSpeech;
+//import com.baidu.dueros.data.response.Reprompt;
+//import com.baidu.dueros.data.response.card.*;
+//import com.baidu.dueros.data.response.directive.Directive;
+//import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective;
+//import com.baidu.dueros.data.response.directive.audioplayer.Play;
+//import com.baidu.dueros.data.response.directive.display.PushStack;
+//import com.baidu.dueros.data.response.directive.dpl.ExecuteCommands;
+//import com.baidu.dueros.data.response.directive.dpl.RenderDocument;
+//import com.baidu.dueros.data.response.directive.dpl.commands.SetStateCommand;
+//import com.baidu.dueros.data.response.directive.dpl.commands.UpdateComponentCommand;
+//import com.baidu.dueros.data.response.directive.dpl.event.UserEvent;
+//import com.baidu.dueros.data.response.directive.pay.Charge;
+//import com.baidu.dueros.model.Response;
+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.apache.commons.lang3.exception.ExceptionUtils;
+import org.springframework.data.redis.core.StringRedisTemplate;
+//
+import javax.servlet.http.HttpServletRequest;
+//import java.io.File;
+import java.io.IOException;
+//import java.net.URLEncoder;
+//import java.text.SimpleDateFormat;
+//import java.util.*;
+//import java.util.concurrent.*;
+//import java.util.regex.Pattern;
+//
+//import static ai.qiwu.com.xiaoduhome.common.Constants.*;
+//import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.*;
+//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.WelcomeWord.*;
+//import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.BEARER;
+//import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.FLOWER_INTERFACE;
+//import static ai.qiwu.com.xiaoduhome.service.ScheduleService.*;
+//
+
+/**
+ * @author 苗权威
+ * @dateTime 19-8-6 下午8:06
+ */
+@Slf4j
+public class DplBotRedisService extends BaseBot {
+// private static final MyDocument FIRST_PAGE;
+//
+// private static final ConcurrentHashMap LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
+//
+// private static volatile RecommandDocument FUNNY_DEFAULT_DOCUMENT;
+//
+// static {
+// FIRST_PAGE = JSON.parseObject(DplbotServiceUtil.getDPLTemple("static/json/firstPage.json"), MyDocument.class);
+// }
+//
+// 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 final int type;
+//
+// private final static Reprompt WAIT_WORD = new Reprompt(new OutputSpeech(OutputSpeech.SpeechType.PlainText, "晓悟正在等你的回复"));
+//
+//// private final RedisTemplate redisTemplate;
+//
+//// private final RedisTemplate redisTemplate;
+//
+// private final StringRedisTemplate stringRedisTemplate;
+//
+ public DplBotRedisService(HttpServletRequest request, Integer type,StringRedisTemplate stringRedisTemplate) throws IOException {
+ super(request);
+// this.type = type;
+// this.stringRedisTemplate = stringRedisTemplate;
+ //privateKey为私钥内容,0代表你的Bot在DBP平台debug环境,1或者其他整数代表online环境,
+ // botMonitor对象已经在bot-sdk里初始化,可以直接调用
+// this.botMonitor.setEnvironmentInfo(PRIVATE_KEY, 1);
+// this.botMonitor.setMonitorEnabled(true);
+ }
+//
+// @Override
+// public Response onLaunch(LaunchRequest launchRequest) {
+// if (getRequest().getContext().getScreen() == null) {
+//// String userId = customUserId();
+// stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+customUserId());
+// String welcomeWord;
+// String skillName;
+// String num = RandomStringUtils.randomNumeric(3);
+// switch (type) {
+// case 1 : {
+//// welcomeWord = WELCOME_SMART_FORMAT;
+//// try {
+//// List botList = channel2Bots.get("jiaoyou-audio-child-test");
+//// String name = botList.get(Integer.parseInt(num)%botList.size());
+//// welcomeWord = String.format(welcomeWord, name,name);
+//// } catch (Exception e) {
+//// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+//// welcomeWord = WELCOME_SMART;
+//// }
+// welcomeWord = WELCOME_SMART;
+// skillName = SKILL_SMART;
+// break;
+// }
+// case 2 : {
+//// welcomeWord = WELCOME_NOVEL_FORMAT;
+//// try {
+//// List botList = channel2Bots.get("jiaoyou-audio-adult-test");
+//// String name = botList.get(Integer.parseInt(num)%botList.size());
+//// welcomeWord = String.format(welcomeWord, name,name);
+//// } catch (Exception e) {
+//// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+//// welcomeWord = WELCOME_NOVEL;
+//// }
+// welcomeWord = WELCOME_NOVEL;
+// skillName = SKILL_NOVEL;
+// break;
+// }
+// case 3 : welcomeWord = WelcomeWord.WELCOME_STORY; skillName = SKILL_STORY; break;
+// case 4 : welcomeWord = WelcomeWord.WELCOME_LITERATURE; skillName = SKILL_LITERATURE; break;
+// default: {
+// welcomeWord = WELCOME_FORMAT;
+// try {
+// List botList = jiaoyouChannel2Bots.get("jiaoyou-audio-adult-test");
+// String name = botList.get(Integer.parseInt(num)%botList.size());
+// welcomeWord = String.format(welcomeWord, name,name);
+// } catch (Exception e) {
+// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+// welcomeWord = WELCOME;
+// }
+// skillName = SKILL;
+// break;
+// }
+// }
+// StandardCard standardCard = new StandardCard(skillName, welcomeWord);
+// standardCard.setImage(FIRST_IMAGE);
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord);
+// return new Response(outputSpeech, standardCard);
+// } else {
+// return new Response();
+// }
+//// RenderDocument renderDocument = new RenderDocument(FIRST_PAGE);
+//// this.addDirective(renderDocument);
+//// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, Constants.WelcomeWord.WELCOME);
+//// // 初次进入时创建用户的行为信息,包括历史记录,送花数,收藏记录
+//// // 历史记录,收藏记录,送花数,郊游天下id
+//// if (DplbotServiceUtil.USER_HISTORY.get(getUserId()) == null) {
+//// String accessToken = getAccessToken();
+//// if (accessToken != null) setSessionAttribute("userId", DplbotServiceUtil.getUserIdByToken(accessToken));
+//// DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, getUserId());
+//// }
+//// return new Response(outputSpeech);
+// }
+//
+// @Override
+// protected Response onInent(IntentRequest intentRequest) {
+// final String userId = customUserId();
+// String redisId = SpiritRedisService.PREFIX_REDIS+userId;
+// if (getRequest().getContext().getScreen() == null) {
+//// final String deviceUserId = PREFIX_USERID + getDeviceId();
+//
+// try {
+// String data = stringRedisTemplate.opsForValue().get(redisId);
+// if (StringUtils.isNotBlank(data)) {
+// log.info("超时redis获取信息:"+data);
+// String redisIdleId = SpiritRedisService.PREFIX_REDIS_IDLE+userId;
+// if (data.equals("out")) {
+// String idleNum = stringRedisTemplate.opsForValue().get(redisIdleId);
+// boolean firstIdle;
+// if ((firstIdle = StringUtils.isBlank(idleNum)) || idleNum.equals("1")) {
+// try {
+// Thread.sleep(2000);
+// } catch (Exception e){}
+// data = stringRedisTemplate.opsForValue().get(redisId);
+// if (StringUtils.isNotBlank(data) && !data.equals("out")) {
+// stringRedisTemplate.delete(redisIdleId);
+// stringRedisTemplate.delete(redisId);
+// Directive play = buildNoScreenPlayDirec(dealAudioUrl(data), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+// addDirective(play);
+// return new Response();
+// }
+// if (firstIdle) idleNum = "1";
+// else idleNum = "2";
+// stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 10, TimeUnit.SECONDS);
+// return buildErrorResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
+// XiaoAiConstants.TTS.WAIT_WORD_2);
+// } else {
+// stringRedisTemplate.delete(redisIdleId);
+// stringRedisTemplate.delete(redisId);
+// }
+// } else {
+// stringRedisTemplate.delete(redisId);
+// stringRedisTemplate.delete(redisIdleId);
+// Directive play = buildNoScreenPlayDirec(dealAudioUrl(data), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+// addDirective(play);
+// return new Response();
+// }
+// }
+// } catch (Exception e) {
+// log.error("xiaodu redis error:"+e);
+// }
+//
+// try {
+// Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId));
+//// Response response = future.get(2700, TimeUnit.MILLISECONDS).getResponse();
+// return future.get(1000, TimeUnit.MILLISECONDS);
+// } catch (InterruptedException | ExecutionException e) {
+// log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
+// return buildErrorResponse(SORRY_UNCATCH);
+// } catch (TimeoutException e) {
+// log.info("超时,让用户再说一遍:{}",e.toString());
+// stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 10, TimeUnit.SECONDS);
+// return buildErrorResponse(SORRY_UNCATCH);
+// } catch (Exception all) {
+// log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
+// return buildErrorResponse(SORRY_UNCATCH);
+// }
+// } else {
+// return new Response();
+// }
+//// OverTimeDetail detail;
+//// if ((detail = LAST_OUTTIME_RESULT.remove(userId)) != null) {
+//// for (Directive directive : detail.getDirectives()) {
+//// //log.info("上次超时保存的Directive:{}",directive.getClass().getName());
+//// this.addDirective(directive);
+//// }
+//// for (String key : detail.getAttributes().keySet()) {
+//// //log.info("上次超时保存的key:{}",key);
+//// this.setSessionAttribute(key, detail.getAttributes().get(key));
+//// }
+//// return detail.getResponse();
+//// }
+//// try {
+//// Future future = DplbotServiceUtil.getPOOL().submit(new Task(intentRequest));
+//// future.get(2200, TimeUnit.MILLISECONDS);
+//// } catch (InterruptedException | ExecutionException e) {
+//// log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
+//// return buildErrorResponse(SORRY_UNCATCH);
+//// } catch (TimeoutException e) {
+//// log.info("超时,让用户再说一遍:{}",e.toString());
+//// if ("funny".equals(getIntent().getName()) && FUNNY_DEFAULT_DOCUMENT != null) {
+//// RenderDocument document = new RenderDocument(FUNNY_DEFAULT_DOCUMENT);
+//// this.addDirective(document);
+//// return new Response();
+//// }else {
+//// return buildErrorResponse(SORRY_UNCATCH);
+//// }
+//// } catch (Exception all) {
+//// log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
+//// return buildErrorResponse(SORRY_UNCATCH);
+//// }
+//// OverTimeDetail data = LAST_OUTTIME_RESULT.remove(getUserId());
+//// if (data == null) return new Response();
+//// return data.getResponse();
+// }
+//
+//// private void dealWithFinishedNoCallEvent(String userId) {
+//// if (userId.equals(DU_DEVICE_ID)) {
+//// DplbotServiceUtil.getPOOL().submit(() -> {
+//// WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du1");
+//// });
+//// } else {
+//// DplbotServiceUtil.getPOOL().submit(() -> {
+//// WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du2");
+//// });
+//// }
+//// }
+//
+// private Response dealNoScreenIntentTemp(IntentRequest intentRequest, String userId) {
+// String intentName = getIntent().getName();
+// if ("sendFlower".equals(intentName)) {
+// return dealNoScreenSendFlowerIntent(userId);
+// } else if ("load".equals(intentName)) {
+// Card card = new LinkAccountCard();
+// Response response = buildErrorResponse("请在小度App上完成登录");
+// response.setCard(card);
+// return response;
+// }
+//
+// try {
+// final Query query = intentRequest.getQuery();
+// final String userWord = query.getOriginal();
+//// if (query != null) userWord = query.getOriginal();
+// if (userWord == null){
+// log.error("小度没有传来任何话语");
+// return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+// }
+//// log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId());
+//
+// String channel;
+// switch (type) {
+// case 1 :
+// case 3 : channel = "jiaoyou-audio-child-test";break;
+// case 2 :
+// case 4 : channel = "jiaoyou-audio-adult-test";break;
+// default: channel = "jiaoyou-audio-test";break;
+// }
+// String response = RequestTerminal.requestTerminateTemp(userWord, userId, channel);
+// log.info("小度,小悟返回:{},",response);
+// if (StringUtils.isBlank(response)) {
+// return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+// }
+//// String mark = RandomStringUtils.randomAlphabetic(3);
+//// AudioBoxData pathData = new AudioBoxData();
+//// OkHttp3Utils.asyncPost(XiaoAiConstants.TTS_DIDI3, response, pathData);
+// try {
+// JSONObject object = JSON.parseObject(response);
+// JSONArray commands = object.getJSONArray("commands");
+// if (commands != null && commands.size() != 0) {
+// String txt;
+// for (Object ob: commands) {
+// txt = ((JSONObject) ob).getString("text");
+// int i;
+// if (StringUtils.isNotBlank(txt) && (i=txt.indexOf("out")) != -1) {
+// log.info("小度,推荐bot退出:{},{}",userWord,userId);
+// String content = txt.substring(i+3, txt.indexOf("☚")).trim();
+// String byeWord = null;
+// String skillName = null;
+// switch (type) {
+// case 1: {
+// byeWord = EndMsg.END_BYE_STORY;
+// skillName = SKILL_SMART;
+// break;
+// }
+// case 2: {
+// byeWord = EndMsg.END_BYE_NOVEL;
+// skillName = SKILL_NOVEL;
+// break;
+// }
+// case 5: {
+// byeWord = EndMsg.END_BYE_JIAOYOU;
+// skillName = SKILL;
+// break;
+// }
+// }
+// if (byeWord == null) byeWord = EndMsg.END_BYE_Adult;
+// if (skillName == null) skillName = SKILL_DEFAULT;
+// if (StringUtils.isBlank(content)) {
+// JSONArray dialogs = object.getJSONArray("dialogs");
+// if (dialogs != null && dialogs.size() != 0) {
+// String str = ((JSONObject)dialogs.get(0)).getString("text");
+// if (StringUtils.isNotBlank(str)) {
+// str = str.replaceAll("\\{/.*?/}", "")+skillName;
+// RequestTerminal.backRequest(userId, type);
+// return buildLogOutResponse(str);
+// }
+// }
+// RequestTerminal.backRequest(userId, type);
+// return buildLogOutResponse(byeWord);
+// } else {
+// content = content.replaceAll("\\{/.*?/}", "")+skillName;
+// RequestTerminal.backRequest(userId, type);
+// return buildLogOutResponse(content);
+// }
+// }
+// }
+// }
+// } catch (Exception e) {
+// log.error("推荐bot退出解析出错:"+e);
+// }
+//// String path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
+// String path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", response);
+// if (StringUtils.isBlank(path) || "null".equals(path)) {
+// log.error("小度没有获取到音频链接");
+// return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+// }
+//// final JSONObject ob = JSONObject.parseObject(response);
+//// String botAcc = ob.getString("aipioneerUsername");
+//// String beforeBotAccount = getSessionAttribute("botAcc");
+//// if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(botAcc)) {
+//// setSessionAttribute("botAcc", botAcc);
+//// data.getAttributes().put("botAcc",botAcc);
+//// }
+//
+// Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+// addDirective(play);
+//// if (userId.equals(DU_DEVICE_ID)) {
+//// DplbotServiceUtil.getPOOL().submit(() -> {
+//// JSONArray array = ob.getJSONArray("dialogs");
+//// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+//// for (Object item: array) {
+//// String str = ((JSONObject) item).getString("text");
+//// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+//// }
+//// WebSocketLog.sendInfo(builder.toString(), "du1");
+//// });
+//// } else {
+//// DplbotServiceUtil.getPOOL().submit(() -> {
+//// JSONArray array = ob.getJSONArray("dialogs");
+//// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+//// for (Object item: array) {
+//// String str = ((JSONObject) item).getString("text");
+//// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+//// }
+//// WebSocketLog.sendInfo(builder.toString(), "du2");
+//// });
+//// }
+// log.info("Redis 写入:"+path);
+// stringRedisTemplate.opsForValue().set(SpiritRedisService.PREFIX_REDIS+userId, path, 10, TimeUnit.SECONDS);
+// return new Response();
+// } catch (Exception e) {
+// log.warn("中控返回结果为空:"+e);
+// return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+// }
+// }
+//
+// private String dealAudioUrl(String path) {
+//// return Constants.TTS_DIDI3_GET+path;
+// return "http://didi-gz5.jiaoyou365.com:9663/api/audio/get?path="+path;
+// }
+//
+// private Response dealNoScreenSendFlowerIntent(String userId) {
+// if (getAccessToken() == null) {
+// return buildErrorResponse("该功能需要登录");
+// }
+// String num = getSlot("sys.number");
+// OutputSpeech outputSpeech;
+// String confirmationStatus = getIntent().getConfirmationStatus().name();
+// log.info("槽位确认状态:{}",confirmationStatus);
+// if ("NONE".equals(confirmationStatus)) {
+// if (num == null) {
+// log.info("确认送花个数");
+// ask("sys.number");
+// outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请问您要送几朵花");
+// setExpectSpeech(true);
+// } else {
+// log.info("确认最终送花意图");
+// setConfirmIntent();
+// outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText,
+// new StringBuilder("您要送").append(num).append("朵花是吗").toString());
+// setExpectSpeech(true);
+// }
+// return new Response(outputSpeech);
+// } else if ("CONFIRMED".equals(confirmationStatus)) {
+// log.info("确认");
+// int unitPrice = Integer.parseInt(ScheduleService.FLOWER_UNIT_PRICE);
+// String amount = String.valueOf(unitPrice*Integer.parseInt(num)/100.0);
+// String orderId = new StringBuilder(userId).append(System.currentTimeMillis()).toString();
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken());
+// if (appUserId == null) {
+// log.error("送花时获取用户app_user_id失败");
+// return buildErrorResponse("不好意思出了点问题,请再说一遍吧");
+// }
+// }
+// String botId = getSessionAttribute("botAcc");
+// if (StringUtils.isNotBlank(botId)) {
+// XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
+// XiaoDuOrderTB response = repository.save(buildNoScreenBeforePayPojo(botId, appUserId, userId, unitPrice,
+// Integer.parseInt(num), orderId));
+//
+// if (response != null && response.getId() != null) {
+// String desc = new StringBuilder("感谢您赏赐给该作品的").append(num).append("朵鲜花").toString();
+// String name = ScheduleService.PRODUCT_ID_DETAIL.get(botId).getName();
+// if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
+// .append("的").append(num).append("朵鲜花").toString();
+// Charge charge = new Charge(amount, orderId, num+"朵鲜花", desc);
+// charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
+// addDirective(charge);
+// return buildErrorResponse("请到小度APP上完成支付");
+// } else {
+// log.error("订单没有插入到xioadu_order_tb");
+// return buildErrorResponse(ERROR_SEND_FLOWER);
+// }
+// }else {
+// log.error("无法获取到botID");
+// return buildErrorResponse("只能在作品里才可以送花");
+// }
+// } else {
+// log.info("否定");
+// return buildErrorResponse("好的,已为您终止");
+// }
+// }
+//
+// private Play buildNoScreenPlayDirec(String audioUrl, AudioPlayerDirective.PlayBehaviorType type) {
+// return new Play(type, audioUrl, 0);
+// }
+//
+// /**
+// *
+// * @param idsToken 当前页面作品的id集合
+// * @param overDetail
+// * @return
+// */
+// private Response dealOpenNum(String idsToken, OverTimeDetail overDetail) {
+// int collectNum = Integer.parseInt(getSlot("sys.number"));
+// String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
+// String botID = tokenList[collectNum-1];
+// OnProductDetail detail = ScheduleService.PRODUCT_ID_DETAIL.get(botID);
+// String productName = correctName(detail.getName());
+// String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
+// log.info("进入作品语句:{}", enterProductWord);
+// QiWuResponse data = null;
+// try {
+// data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
+// } catch (IOException e) {
+// log.error("请求终端接口出错:", e.toString());
+// }
+// if (data == null) {
+// return buildErrorResponse(SORRY_UNCATCH);
+// }
+// String text = data.getText();
+//// String aside = DplbotServiceUtil.getAsideText(text);
+//// text = text.substring(text.indexOf("】")+1);
+//// log.info("旁白名字:{}",aside);
+//// PlayDocument document = PlayUtils.getPlayDocument(productName, aside, ScheduleService.getAsideImgUrl(botID, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern), DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botID);
+//
+// RenderDocument render = new RenderDocument(document);
+// this.setSessionAttribute(PRE_COLLE, null);
+// overDetail.getAttributes().put(PRE_COLLE, null);
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace == null || trace.length() != 2) trace = "00";
+// String backTrace = new StringBuilder(trace).append(detail.getBotAccount()).append(File.separator).toString();
+// this.setSessionAttribute(BACK_TRACE, backTrace);
+// overDetail.getAttributes().put(BACK_TRACE,backTrace);
+// this.addDirective(render);
+// overDetail.getDirectives().add(render);
+// return new Response();
+// }
+//
+// @Override
+// protected Response onUserEvent(UserEvent userEvent) {
+// try {
+// //log.info("onUserEvent事件触发,token:{}, componentId:{}",userEvent.getToken(),userEvent.getPayload().getComponentId());
+// if (getAccessToken() != null && getSessionAttribute("userId") == null) {
+// String userId = DplbotServiceUtil.getUsUserId(getUserId(),getAccessToken());
+// setSessionAttribute("userId", userId);
+// }
+// String componentId = userEvent.getPayload().getComponentId();
+// String componentPrefix;
+// if ("audio".equals(componentId)){
+// setExpectSpeech(true);
+// }
+// else if (Constants.PRE_PRODUCT_IMG.equals((componentPrefix = componentId.substring(0, 5)))) {
+// // 作品图片点击事件
+// log.info("图片点击触发");
+// String accessToken = getAccessToken();
+// String userId = getUserId();
+// String productName = componentId.substring(5);
+//
+// OnProductDetail productDetail = ScheduleService.PRODUCT_NAME_DETAIL.get(productName);
+// if (productDetail == null && !productName.equals("清新传{/zhuan4/}")) {
+// return buildErrorResponse("目前不支持该作品");
+// }
+// String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
+//
+// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+// String dateString = formatter.format(productDetail.getCreateTime());
+// String time = new StringBuilder(PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
+// String author = new StringBuilder(PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
+// StringBuilder labels = new StringBuilder(PRODUCT_INTRO.LABEL);
+// for (String label: productDetail.getLabels()) {
+// labels.append(PRODUCT_INTRO.SPACE).append(label);
+// }
+// String intro = productDetail.getIntro();
+// String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
+//
+// // "start product" container button
+// String flowers, flowerReward,collectText, collectUrl, collectComId;
+// if (accessToken != null) {
+// // flower container button
+// Long flowerCount = DplbotServiceUtil.getUserSendFlowerNum(productDetail.getBotAccount(), userId, accessToken);
+// flowers = USER_SEND_FLOWER+flowerCount;
+// flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
+//
+// // collection container button
+// boolean collec = DplbotServiceUtil.didUserCollecThisProduct(productDetail.getBotAccount(), userId,
+// accessToken, getSessionAttribute("userId"));
+// if (collec) {
+// collectText = COLLECED;
+// collectUrl = COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// } else {
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// }
+// } else {
+// flowers = FLOWE;
+// flowerReward = FLOWER_LOAD;
+//
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = FLOWER_LOAD;
+// }
+//
+// ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), time, author, labels.toString(),
+// intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
+//
+// RenderDocument renderDocument = new RenderDocument(document);
+// this.addDirective(renderDocument);
+// //this.addDirective(new PushStack());
+// String trace = getSessionAttribute(BACK_TRACE);
+// log.info("before trace------------:{}",trace);
+// StringBuilder builder = new StringBuilder();
+// if (trace == null || trace.length() < 2) {
+// builder.append("00");
+// } else if (trace.length()>2) {
+// builder.append(trace, 0, 2);
+// } else {
+// builder.append(trace);
+// }
+//
+// trace = builder.append(productDetail.getBotAccount()).toString();
+// log.info("after trace------------:{}",trace);
+// this.setSessionAttribute(BACK_TRACE, trace);
+// return new Response();
+// } else if (Constants.PRE_ENTER_PRODUCT.equals(componentPrefix)) {
+// String productName = componentId.substring(5);
+// String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
+// log.info("进入作品语句:{}", enterProductWord);
+// QiWuResponse data = null;
+// try {
+// data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
+// } catch (IOException e) {
+// log.error("请求终端接口出错:", e.toString());
+// }
+// if (data == null) {
+// return buildErrorResponse(SORRY_UNCATCH);
+// }
+// String text = data.getText();
+//// String aside = DplbotServiceUtil.getAsideText(text);
+//// text = text.substring(text.indexOf("】")+1);
+//// log.info("旁白名字:{}",aside);
+////
+// String keng = productName;
+// if (keng.equals("清新传")) keng = "清新传{/zhuan4/}";
+// String botID = ScheduleService.getProductNameDetail().get(keng).getBotAccount();
+//// PlayDocument document = PlayUtils.getPlayDocument(productName, aside, ScheduleService.getAsideImgUrl(botID, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern), DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botID);
+//
+// RenderDocument render = new RenderDocument(document);
+// this.setSessionAttribute(PRE_COLLE, null);
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace == null || trace.length()<2) trace = "00";
+// else if (trace.length()>2) trace = trace.substring(0,2);
+// if (productName.equals("清新传")) productName = "清新传{/zhuan4/}";
+// String botAccount = ScheduleService.PRODUCT_NAME_DETAIL.get(productName).getBotAccount();
+// this.setSessionAttribute(BACK_TRACE, new StringBuilder(trace).append(botAccount).append(File.separator).toString());
+// this.addDirective(render);
+// } else if (FLOWE.equals(componentPrefix)) {
+// if (FLOWER_LOAD.equals(componentId)) {
+// return load();
+// } else {
+//// Buy buy = new Buy(FLOWER_PRODUCT_ID);
+//// String token = new String(Base64.getEncoder().encode(componentId.substring(5).getBytes()), StandardCharsets.UTF_8);
+//// buy.setToken(token);
+//// addDirective(buy);
+//// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, REWARD_FLOWER);
+//// return new Response(outputSpeech);
+// Charge charge = DplbotServiceUtil.sendOneFlowerByCharge(getUserId(), getSessionAttribute("userId"),
+// getAccessToken(), getSessionAttribute("trace"));
+// if (charge != null) {
+// addDirective(charge);
+// return buildErrorResponse("扫描屏幕上的二维码完成支付");
+// }
+// return new Response();
+// }
+// } else if ("loadingPage".equals(componentId)) {
+// RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
+// this.addDirective(new PushStack());
+// this.addDirective(renderDocument);
+// return new Response();
+// } else if (PRE_COLLE.equals(componentPrefix)) {
+// boolean isUnCollect = "Un".equals(componentId.substring(5,7));
+// final String botId = componentId.substring(7);
+// if (isUnCollect) {
+// //取消收藏
+// DplbotServiceUtil.userUnCollectTheBotInPool(getUserId(), botId, getAccessToken());
+// changeIconIdTextAfterCollect(false, botId);
+// } else {
+// //收藏
+// DplbotServiceUtil.userCollectTheBotInPool(getUserId(), botId, getAccessToken());
+// changeIconIdTextAfterCollect(true, botId);
+// }
+// } else if (PRE_CATEGORY.equals(componentPrefix)) {
+// String category = componentId.substring(5);
+// // 分类推荐页面相同
+// RecommandDocument document = RecommendUtil.getCategory(0, category);
+// if (document == null) return buildErrorResponse("不好意思该分类还没有作品");
+// RenderDocument render = new RenderDocument(document);
+// this.addDirective(render);
+// this.setSessionAttribute("category",category);
+// this.setSessionAttribute("trace","05");
+// } else if ("playButton".equals(componentId)) {
+// return buildErrorResponse("您可以直接对我说我要送花或者我要收藏或取消收藏");
+// } else if ("lunchCollect".equals(componentId)) {
+// return dealOpenCollectClick();
+// } else if ("lunchHistory".equals(componentId)) {
+// return dealHistoryClick();
+// }
+//// else if ("funnyChange".equals(componentId)) {
+//// ExecuteCommands executeCommands = new ExecuteCommands();
+//// AutoPageCommand page = new AutoPageCommand();
+//// page.setComponentId("funnyPage");
+//// page.setDurationInMillisecond(2000);
+//// executeCommands.addCommand(page);
+//// this.addDirective(executeCommands);
+//// }
+// } catch (Exception e) {
+// log.error("onUserEvent error:{}", ExceptionUtils.getStackTrace(e));
+// }
+// return new Response();
+// }
+//
+// @Override
+// protected Response onSessionEnded(SessionEndedRequest sessionEndedRequest) {
+// switch (sessionEndedRequest.getReason()) {
+// case ERROR: dealWithError(sessionEndedRequest); break;
+// case USER_INITIATED: log.info(EndMsg.USER_SAY_CANCEL); break;
+// case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break;
+// }
+// if (getRequest().getContext().getScreen() == null) {
+// String userId = customUserId();
+// String byeWord = EndMsg.END_BYE_Adult;
+// switch (type) {
+// case 2: byeWord = EndMsg.END_BYE_NOVEL;break;
+// case 1: byeWord = EndMsg.END_BYE_STORY;break;
+// case 3: byeWord = EndMsg.END_BYE_CHILD;break;
+// case 5: byeWord = EndMsg.END_BYE_JIAOYOU;break;
+// }
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
+// RequestTerminal.backRequest(userId, type);
+//// try {
+//// if (DU_DEVICE_ID.equals(deviceId)) {
+//// RequestTerminal.backRequest(DU_DEVICE_ID, type);
+//// } else {
+//// RequestTerminal.backRequestDU2(deviceId, type);
+//// }
+//// } catch (Exception e) {
+//// log.warn("用户退出向中控发出退出指令出错");
+//// }
+// return new Response(outputSpeech);
+// }
+// DplbotServiceUtil.writeTheUserHistoryInData(getUserId());
+//// LAST_OUTTIME_RESULT.remove(getUserId());
+// return new Response();
+// }
+//
+// private void dealWithError(SessionEndedRequest request) {
+// switch (request.getError().getType()) {
+// case INTERNAL_ERROR: log.info(ErrorMsg.INTERNAL_ERROR); break;
+// case INVALID_RESPONSE: log.info(ErrorMsg.INVALID_RESPONSE); break;
+// case DEVICE_COMMUNICATION_ERROR: log.info(ErrorMsg.DEVICE_COMMUNICATION_ERROR); break;
+// }
+// log.info("错误信息 : "+ request.getError().getMessage());
+// }
+//
+// private Response dealHistoryClick() {
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(), 0);
+// if (document == null) return buildErrorResponse("不好意思,您太久没玩记录被清空了");
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute("recommand", null);
+// setSessionAttribute("comCnt", null);
+// setSessionAttribute(BACK_TRACE, "02");
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开历史记录");
+// return new Response(outputSpeech);
+// }
+//
+// private Response dealOpenCollectClick() {
+// if (getAccessToken() == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
+// return new Response(outputSpeech);
+// } else {
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(getUserId(), getAccessToken());
+// if (appUserId == null) {
+// return new Response();
+// }
+// }
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(getUserId(), getAccessToken(), appUserId, 0);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute("comCnt", null);
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute(BACK_TRACE, "01");
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开收藏夹");
+// return new Response(outputSpeech);
+// }
+// }
+// return new Response();
+// }
+//
+//// @Override
+//// protected Response onBuyEvent(BuyEvent buyEvent) {
+//// com.baidu.dueros.data.request.buy.event.JYTUserResponse payload = buyEvent.getPayload();
+//// String result = payload.getPurchaseResult().getPurchaseResult();
+//// log.info("此次支付结果:"+result+";msg: "+payload.getMessage());
+//// if (result.equals("SUCCESS")) {
+//// log.info("支付成功");
+//// POOL.submit(new SendFlowerThread(buyEvent));
+//// POOL.submit(new SendFlowerBuyToXiaoduTB(buyEvent));
+//// return buildErrorResponse("感谢大人赏的花");
+//// }
+//// return buildErrorResponse("哎呀,没有支付成功");
+//// }
+//
+//
+// private ExecuteCommands changeIconIdTextAfterCollect(boolean collect, String botId) {
+// ExecuteCommands executeCommands = new ExecuteCommands();
+// UpdateComponentCommand update = new UpdateComponentCommand();
+// String srcValue;
+// String textValue;
+// String idValue;
+// String previousClickId;
+// String unCollectId = new StringBuilder(UN_COLLEC_ID).append(botId).toString();
+// String collectId = new StringBuilder(COLLEC_ID).append(botId).toString();
+// if (collect) {
+// srcValue = COLLECTED_IMG_URL;
+// textValue = COLLECED;
+// idValue = unCollectId;
+// previousClickId = collectId;
+// } else {
+// srcValue = UN_COLLECTED_IMG_URL;
+// textValue = UN_COLLEC;
+// idValue = collectId;
+// previousClickId = unCollectId;
+// }
+//
+// update.setComponentId(previousClickId);
+// update.setDocument(TempleUtils.getCollectIcon(idValue, srcValue, textValue));
+// executeCommands.addCommand(update);
+// this.addDirective(executeCommands);
+// return executeCommands;
+// }
+//
+// private ExecuteCommands changeCollectIconInPlay(boolean collect) {
+// ExecuteCommands executeCommands = new ExecuteCommands();
+// SetStateCommand setState = new SetStateCommand();
+// setState.setComponentId("playCollect");
+// setState.setState("src");
+// if (collect) {
+// setState.setValue(COLLECTED_IMG_URL);
+// }else {
+// setState.setValue(UN_COLLECTED_IMG_URL);
+// }
+// executeCommands.addCommand(setState);
+// return executeCommands;
+// }
+//
+// private Response load() {
+// Card card = new LinkAccountCard();
+// Response response = buildErrorResponse(LOAD_INTRO);
+// response.setCard(card);
+// return response;
+// }
+//
+// private Integer getUserSendFlowerNum(String productId, String accessToken) {
+// HashMap params = new HashMap<>();
+// params.put("module", "works");
+// params.put("aipioneerUsername", productId);
+// HashMap headers = new HashMap<>();
+// headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
+// headers.put("Authorization", new StringBuilder(BEARER).append(accessToken).toString());
+// CodeMsgData response;
+// try {
+// String flowerRes = OkHttp3Utils.doGet(FLOWER_INTERFACE, params, headers);
+// response = JSON.parseObject(flowerRes, CodeMsgData.class);
+// } catch (IOException e) {
+// log.error("请求用户送花数出错");
+// return null;
+// }
+// log.info("调用获取用户送花数接口结果:{}", response);
+// if (response == null || response.getCode() != 1) return null;
+// return response.getData().getCount();
+// }
+//
+//
+// private List getUserProductList(String accessToken) {
+// HashMap params = new HashMap<>();
+// params.put("module", "works");
+// HashMap headers = new HashMap<>();
+// headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
+// headers.put("Authorization", new StringBuilder(BEARER).append(accessToken).toString());
+// UserCollecResult result;
+// try {
+// String resStr = OkHttp3Utils.doGet(XIAOWU_API.USER_CLOOEC_LIST, params, headers);
+// result = JSON.parseObject(resStr, UserCollecResult.class);
+// } catch (Exception e) {
+// log.error("调用获取用户收藏作品列表接口出错:{}", e.toString());
+// return null;
+// }
+// if (result.getCode() == 1) return result.getData();
+// else {
+// log.error("获取用户收藏作品列表出错,错误码:{}, 错误信息:{}", result.getCode(), result.getMsg());
+// return null;
+// }
+// }
+//
+// private static String correctName(String name) {
+// int brace = name.indexOf("{");
+// if (brace != -1) name = name.substring(0, brace);
+// return name;
+// }
+//
+// @Override
+// protected Response onLinkAccountSucceededEvent(LinkAccountSucceededEvent linkAccountSucceededEvent) {
+// log.info("登录成功返回信息:{}",linkAccountSucceededEvent);
+// String accessToken = getAccessToken();
+// String jytUserId;
+// if (getRequest().getContext().getScreen() != null) {
+// log.info("检测到有屏登录");
+// String userId = getUserId();
+// DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, userId);
+// jytUserId = DplbotServiceUtil.getUsUserId(userId, accessToken);
+// if (jytUserId != null)
+// log.warn("登录后获取用户的app id 失败");
+// } else {
+// jytUserId = DplbotServiceUtil.getUserIdByToken(accessToken);
+// if (jytUserId != null)
+// log.warn("登录后获取用户的app id 失败");
+// }
+// setSessionAttribute("userId", jytUserId);
+// return buildErrorResponse("您已登录成功");
+// }
+//
+//// @Override
+//// protected Response onDefaultEvent() {
+//// log.info("未拦截的事件类型:"+getEventType(this.getStrRequest()));
+//// this.waitAnswer();
+//// return new Response();
+//// }
+//
+// private String getEventType(String requestStr) {
+// int typeIndex = requestStr.lastIndexOf("type");
+// int comma = requestStr.indexOf(',', typeIndex);
+// return requestStr.substring(typeIndex, comma);
+// }
+//
+// private Response buildErrorResponse(String errorMsg) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
+// return new Response(outputSpeech);
+// }
+//
+// private Response buildLogOutResponse(String errorMsg) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
+// endDialog();
+// return new Response(outputSpeech);
+// }
+//
+// private Response buildNoScreenListCardResponse(String content, String botAccount) {
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// List actors = DplbotServiceUtil.seperateActor(content, pattern);
+// String[] actorWord = DplbotServiceUtil.seperateActorWord(content, pattern);
+// int i = 0;
+// ListCard listCard = new ListCard();
+// for (String actor: actors) {
+// StandardCardInfo cardInfo = new StandardCardInfo(actor, actorWord[i++].replaceAll("
","\n"));
+// cardInfo.setImage(ScheduleService.getAsideImgUrl(botAccount, actor));
+// listCard.getList().add(cardInfo);
+// }
+//// content = buildText(content);
+// return new Response(null, listCard, WAIT_WORD);
+// }
+//
+// private Response buildNoScreenTextCardREsponse(String content) {
+// content = buildText(content);
+// TextCard textCard = new TextCard(content);
+// return new Response(null, textCard, WAIT_WORD);
+// }
+//
+// private String buildText(String text) {
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// StringBuilder builder = new StringBuilder();
+// List actors = DplbotServiceUtil.seperateActor(text, pattern);
+// String[] word = DplbotServiceUtil.seperateActorWord(text, pattern);
+// int i = 0;
+// for (String actor: actors) {
+// builder.append(actor).append(":").append(word[i].replaceAll("
", "\n")).append("\n");
+// i++;
+// }
+// if (builder.length() == 0) builder.append(text);
+// return builder.toString();
+// }
+//
+// private void backToBotIntro(String botAccount, OverTimeDetail detail) {
+// OnProductDetail productDetail = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount);
+// // product picture
+// String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
+//
+// // product name
+// String productName = correctName(productDetail.getName());
+//
+// // product create time
+// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+// String dateString = formatter.format(productDetail.getCreateTime());
+// String createTime = new StringBuilder(PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
+//
+// // product author
+// String author = new StringBuilder(PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
+//
+// // product labels
+// StringBuilder labels = new StringBuilder(PRODUCT_INTRO.LABEL);
+// for (String label: productDetail.getLabels()) {
+// labels.append(PRODUCT_INTRO.SPACE).append(label);
+// }
+//
+// // product introduction
+// String intro = productDetail.getIntro();
+//
+// // "start product" container button
+// String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
+//
+// String accessToken = getAccessToken();
+// String flowers, flowerReward,collectText, collectUrl, collectComId;
+// if (accessToken != null) {
+// // flower container button
+// Long count = DplbotServiceUtil.getUserSendFlowerNum(botAccount, getUserId(), accessToken);
+// flowers = USER_SEND_FLOWER+count;
+// flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
+//
+// // collection container button
+// boolean collec = DplbotServiceUtil.doesUserCollectThisBot(productDetail.getBotAccount(), accessToken, getUserId());
+// if (collec) {
+// collectText = COLLECED;
+// collectUrl = COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// } else {
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// }
+// } else {
+// flowers = FLOWER;
+// flowerReward = FLOWER_LOAD;
+//
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = FLOWER_LOAD; // 提示登录
+// }
+//
+// ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), createTime, author, labels.toString(),
+// intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
+// RenderDocument renderDocument = new RenderDocument(document);
+// this.addDirective(renderDocument);
+// detail.getDirectives().add(renderDocument);
+// String trace = getSessionAttribute(BACK_TRACE);
+// trace = trace.substring(0, trace.length()-1);
+// this.setSessionAttribute(BACK_TRACE, trace);
+// detail.getAttributes().put(BACK_TRACE,trace);
+// }
+//
+// // 异步发送“退出”给终端
+// private void sendCancellToTerminate(String userId){
+// RequestTerminal.backRequest(userId, type);
+// }
+//
+// class Task implements Runnable{
+// IntentRequest intentRequest;
+//
+// Task(IntentRequest intentRequest) {
+// this.intentRequest = intentRequest;
+// }
+//
+// @Override
+// public void run() {
+// final String userId = getUserId();
+// String intentName = getIntent().getName();
+// OverTimeDetail detail = new OverTimeDetail();
+// log.info("Intent name:{}",intentName);
+// if ("ai.dueros.common.default_intent".equals(intentName) || "funny".equals(intentName)) {
+// dealDefaultIntent(intentRequest, detail, userId, intentName, null);
+// return;
+// }
+// switch (intentName) {
+// case "load" : dealLoadIntent(detail, userId);break;
+// case "back" : dealBackIntent(detail, userId);break;
+// case "openCollect" : dealOpenCollectIntent(detail, userId);break;
+// case "openNum" : dealOpenNumIntent(detail, userId);break;
+// case "lastPage" : dealLastPageIntent(detail, userId, intentRequest);break;
+// case "nextPage" : dealNextPageIntent(detail, userId, intentRequest);break;
+// case "history" : dealHistoryIntent(detail, userId);break;
+// case "recommand" : dealRecommandIntent(detail, userId);break;
+// case "ranking" : dealRankIntent(detail, userId);break;
+// case "collect" :
+// case "unCollect" : dealCollectOrUnCollectIntent(detail, userId, intentName);break;
+// case "sendFlower" : dealSendFlowerIntent(detail, userId);break;
+// case "jump" : dealJumpIntent(detail, userId);break;
+// case "start" : dealStartIntent(detail, userId, intentRequest, intentName);break;
+// }
+// }
+// }
+//
+// private void dealJumpIntent(OverTimeDetail detail, String userId) {
+// String trace = getSessionAttribute("trace");
+// if (trace == null || trace.length() < 2) {
+// detail.setResponse(buildErrorResponse("小悟跳不动了"));
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// return;
+// }
+// String num = getSlot("sys.number");
+// if (num == null) {
+// detail.setResponse(buildErrorResponse("我没听清您要跳转的页面,请再说一遍"));
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// return;
+// }
+// int index = Integer.parseInt(num);
+// char pageSign = trace.charAt(1);
+// switch (pageSign) {
+// case '1' : {
+// dealCollectHistoryJump(index, true, detail, userId);
+// break;
+// }
+// case '2' : {
+// dealCollectHistoryJump(index, false, detail, userId);
+// break;
+// }
+// case '4' : {
+// dealRankJump(index, detail);
+// break;
+// }
+// case '5' : {
+// dealCategoryJump(index, detail);
+// break;
+// }
+// default : {
+// detail.setResponse(buildErrorResponse("该页面不支持跳转"));
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// }
+//
+// private void dealRankJump(int index, OverTimeDetail detail) {
+// index = index == 0 ? index : index-1;
+// RecommandDocument document;
+// if (index == 0) document = RecommendUtil.getRankDocumentFirstPage();
+// else document = RecommendUtil.getRankOtherPageDocument(index);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("超出了范围,无法跳转"));
+// return;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(index+1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute("recommand", document.getRecommendIdList());
+// detail.getAttributes().put("recommand", document.getRecommendIdList());
+// detail.getAttributes().put("comCnt", cmt);
+// }
+//
+// private void dealCategoryJump(int index, OverTimeDetail detail) {
+// index = index == 0 ? index : index-1;
+// String category = getSessionAttribute("category");
+// if (category == null) {
+// detail.setResponse(buildErrorResponse("无法跳转,请说返回然后重新进入当前分类"));
+// return;
+// }
+// RecommandDocument document = RecommendUtil.getCategory(index, category);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("超出了范围,无法跳转"));
+// return;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(index+1);
+// setSessionAttribute("comCnt",cmt);
+// detail.getAttributes().put("comCnt", cmt);
+// }
+//
+// private void dealCollectHistoryJump(int index, boolean collect, OverTimeDetail detail, String userId) {
+// index = index == 0 ? index : index-1;
+// int start = index*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document;
+// if (collect) document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(), getSessionAttribute("userId"), start);
+// else document = DplbotServiceUtil.getHistory(userId, getAccessToken(), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(index+1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// } else {
+// detail.setResponse(buildErrorResponse("超出了范围无法跳到那一页"));
+// }
+// }
+//
+// private void dealStartIntent(OverTimeDetail detail, String userId, IntentRequest intentRequest, String intentName) {
+// String trace = getSessionAttribute("trace");
+// if (trace != null && trace.length() > 2 && !StringUtils.endsWith(trace,File.separator)) {
+// String botId = trace.substring(2);
+// String enterName = new StringBuilder("我要玩")
+// .append(ScheduleService.getProductIdDetail().get(botId).getName()).toString();
+// dealDefaultIntent(intentRequest, detail, userId, intentName, enterName);
+// }else {
+// dealDefaultIntent(intentRequest, detail, userId, intentName, null);
+// }
+// }
+//
+// private void dealSendFlowerIntent(OverTimeDetail detail, String userId) {
+// if (getAccessToken() == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
+// detail.setResponse(new Response(outputSpeech));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// String num = getSlot("sys.number");
+// OutputSpeech outputSpeech;
+// String confirmationStatus = getIntent().getConfirmationStatus().name();
+// log.info("槽位确认状态:{}",confirmationStatus);
+// if ("NONE".equals(confirmationStatus)) {
+// if (num == null) {
+// log.info("确认送花个数");
+// ask("sys.number");
+// outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请问您要送几朵花");
+// setExpectSpeech(true);
+// } else {
+// log.info("确认最终送花意图");
+// setConfirmIntent();
+// outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText,
+// new StringBuilder("您要送").append(num).append("朵花是吗").toString());
+// setExpectSpeech(true);
+// }
+// detail.getResponse().setOutputSpeech(outputSpeech);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// } else if ("CONFIRMED".equals(confirmationStatus)) {
+// log.info("确认");
+// int unitPrice = Integer.parseInt(ScheduleService.FLOWER_UNIT_PRICE);
+// String amount = String.valueOf(unitPrice*Integer.parseInt(num)/100.0);
+// String orderId = new StringBuilder(userId).append(System.currentTimeMillis()).toString();
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken());
+// if (appUserId == null) {
+// log.error("送花时获取用户app_user_id失败");
+// detail.setResponse(buildErrorResponse("不好意思出了点问题,请再说一遍吧"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// }
+// String botId;
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace != null && trace.length() > 2) {
+// if (StringUtils.endsWith(trace, File.separator)) {
+// botId = trace.substring(2, trace.length()-1);
+// }else {
+// botId = trace.substring(2);
+// }
+// XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
+// XiaoDuOrderTB response = repository.save(buildBeforePayPojo(botId, appUserId, userId, unitPrice,
+// Integer.parseInt(num), orderId));
+//
+// if (response != null && response.getId() != null) {
+// String desc = new StringBuilder("感谢您赏赐给该作品的").append(num).append("朵鲜花").toString();
+// String name = ScheduleService.PRODUCT_ID_DETAIL.get(botId).getName();
+// if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
+// .append("的").append(num).append("朵鲜花").toString();
+// Charge charge = new Charge(amount, orderId, "鲜花", desc);
+// charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
+// addDirective(charge);
+// detail.getDirectives().add(charge);
+// detail.setResponse(buildErrorResponse("请扫描二维码完成支付"));
+// } else {
+// log.error("订单没有插入到xioadu_order_tb");
+// detail.setResponse(buildErrorResponse(ERROR_SEND_FLOWER));
+// }
+// }else {
+// log.error("无法获取到botID");
+// detail.setResponse(buildErrorResponse(ERROR_SEND_FLOWER));
+// }
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// } else {
+// log.info("否定");
+// detail.setResponse(buildErrorResponse("好的,已为您终止"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+// }
+//
+// private void dealCollectOrUnCollectIntent(OverTimeDetail detail, String userId, String intentName) {
+// if (getAccessToken() == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
+// detail.setResponse(new Response(outputSpeech));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// boolean collect = "collect".equals(intentName);
+// boolean inProductInfo = false;
+// boolean inPlayInfo = false;
+// String botAccount;
+// String trace = getSessionAttribute("trace");
+// if (trace == null || trace.length() <= 2) {
+// botAccount = getSessionAttribute("botAcc");
+// if(botAccount == null) {
+// String word = COLLECT_FAIL;
+// if (!collect) word = UN_COLLECT_FAIL;
+// detail.setResponse(buildErrorResponse(word));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// } else {
+// if (StringUtils.endsWith(trace, File.separator)) {
+// botAccount = trace.substring(2, trace.length()-1);
+// inPlayInfo = true;
+// }
+// else {
+// inProductInfo = true;
+// botAccount = trace.substring(2);
+// }
+// }
+// try {
+// boolean alreadyCollected = DplbotServiceUtil.doesUserCollectThisBot(botAccount, getAccessToken(), userId);
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken());
+// if (appUserId != null) {
+// if (alreadyCollected) {
+// if (collect) detail.setResponse(buildErrorResponse("您之前就已经收藏过该作品啦,看来你真的很喜欢它"));
+// else {
+// DplbotServiceUtil.userUnCollectTheBotInPool(userId, botAccount, getAccessToken());
+// String botName = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
+// if (inProductInfo) {
+// ExecuteCommands commands = changeIconIdTextAfterCollect(false, botAccount);
+// addDirective(commands);
+// detail.getDirectives().add(commands);
+// } else if (inPlayInfo) {
+// changeCollectIconInPlay(false);
+// }
+// if (botName == null) detail.setResponse(buildErrorResponse(UN_COLLECT_BOT_WORD));
+// else detail.setResponse(buildErrorResponse(String.format(UN_COLLECT_BOT_WORD_MG,botName)));
+// }
+// } else {
+// if (collect) {
+// DplbotServiceUtil.userCollectTheBotInPool(userId, botAccount, getAccessToken());
+// String word = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
+// if (inProductInfo) {
+// ExecuteCommands commands = changeIconIdTextAfterCollect(true, botAccount);
+// addDirective(commands);
+// detail.getDirectives().add(commands);
+// } else if (inPlayInfo) {
+// changeCollectIconInPlay(true);
+// }
+// if (word == null) detail.setResponse(buildErrorResponse(COLLECT_BOT_WORD));
+// else detail.setResponse(buildErrorResponse(String.format(COLLECT_BOT_WORD_MG, correctName(word))));
+// }else {
+// detail.setResponse(buildErrorResponse("您还未收藏过该作品,它不在您的收藏列表内"));
+// }
+// }
+// }else {
+// detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
+// }
+// } catch (Exception e) {
+// log.error("收藏/取消收藏出错:{}",e.toString());
+// detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
+// }
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealRankIntent(OverTimeDetail detail, String userId) {
+// RecommandDocument document = RecommendUtil.getRankDocumentFirstPage();
+// RenderDocument render = new RenderDocument();
+// render.setDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// if (token != null) {
+// setSessionAttribute("recommand", token);
+// setSessionAttribute(PRE_COLLE, null);
+// setSessionAttribute("comCnt", null);
+//
+// detail.getAttributes().put("recommand", token);
+// detail.getAttributes().put(PRE_COLLE, null);
+// detail.getAttributes().put("comCnt", null);
+// }
+// setSessionAttribute(BACK_TRACE, "04");
+// detail.getAttributes().put(BACK_TRACE, "04");
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealRecommandIntent(OverTimeDetail detail, String userId) {
+// RecommandDocument recommandDocument = RecommendUtil.getRecommendDocument(0);
+// RenderDocument render = new RenderDocument();
+// render.setDocument(recommandDocument);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = recommandDocument.getRecommendIdList();
+// if (token != null) {
+// setSessionAttribute("recommand", token);
+// setSessionAttribute(PRE_COLLE, null);
+// setSessionAttribute("comCnt", null);
+//
+// detail.getAttributes().put("comCnt", null);
+// detail.getAttributes().put("recommand", token);
+// detail.getAttributes().put(PRE_COLLE, null);
+// }
+// setSessionAttribute(BACK_TRACE, "03");
+// detail.getAttributes().put(BACK_TRACE,"03");
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealHistoryIntent(OverTimeDetail detail, String userId) {
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(), 0);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("没有更多了"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// //dplBotService.addDirective(new PushStack());
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute("recommand", null);
+// setSessionAttribute("comCnt", null);
+// setSessionAttribute(BACK_TRACE, "02");
+//
+// detail.getDirectives().add(render);
+// detail.getAttributes().put("comCnt", null);
+// detail.getAttributes().put("recommand", null);
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getAttributes().put(BACK_TRACE, "02");
+//
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealNextPageIntent(OverTimeDetail detail, String userId, IntentRequest intentRequest) {
+// String signPage = getSessionAttribute("trace");
+// if (signPage == null || signPage.length() < 2) {
+// detail.setResponse(buildErrorResponse("哎呀,小悟累啦,滑不动了"));
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// return;
+// }
+// char sign = signPage.charAt(1);
+// switch (sign) {
+// case '1': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null) {
+// recommendNextCount = "1";
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// int start = count*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
+// getSessionAttribute("userId"), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(count+1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// } else {
+// detail.setResponse(buildErrorResponse("已经到最后一页了"));
+// }
+// break;
+// }
+// case '2': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null) {
+// recommendNextCount = "1";
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// int start = count*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(count+1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// } else {
+// detail.setResponse(buildErrorResponse("已经到最后一页了"));
+// }
+// break;
+// }
+// case '3': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document = RecommendUtil.getRecommendDocument(count);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("客观你已经翻到底了,没有更多了"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// setSessionAttribute("comCnt",String.valueOf(count+1));
+// detail.getAttributes().put("comCnt",String.valueOf(count+1));
+// break;
+// }
+// case '4': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document = RecommendUtil.getRankOtherPageDocument(count);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("客观你已经翻到底了,没有更多了"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// setSessionAttribute("comCnt",String.valueOf(count+1));
+// detail.getAttributes().put("comCnt",String.valueOf(count+1));
+// break;
+// }
+// case '5':{
+// String category = getSessionAttribute("category");
+// if (category == null) category = "古风";
+// String categoryNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (categoryNextCount != null) count = Integer.parseInt(categoryNextCount);
+// RecommandDocument document = RecommendUtil.getCategory(count,category);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("客观你已经翻到底了,没有更多了"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String countStr = String.valueOf(count+1);
+// setSessionAttribute("comCnt",countStr);
+// detail.getAttributes().put("comCnt",countStr);
+// break;
+// }
+// default:{
+// detail.setResponse(buildErrorResponse("该功能还没实现"));
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// }
+//
+// private void dealLastPageIntent(OverTimeDetail detail, String userId, IntentRequest intentRequest) {
+// String signPage = getSessionAttribute("trace");
+// if (signPage == null || signPage.length() < 2) {
+// detail.setResponse(buildErrorResponse("不好意思,小悟累啦,滑不动了"));
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// return;
+// }
+// char sign = signPage.charAt(1);
+// switch (sign) {
+// case '1':{
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// int start = (count-2)*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
+// getSessionAttribute("userId"), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(count-1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// }
+// break;
+// }
+// case '2':{
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// int start = (count-2)*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(count-1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// }
+// break;
+// }
+// case '3': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document = RecommendUtil.getRecommendDocument(count-2);
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// setSessionAttribute("comCnt",String.valueOf(count-1));
+// detail.getAttributes().put("comCnt",String.valueOf(count-1));
+// break;
+// }
+// case '4': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document;
+// if (count == 2) document = RecommendUtil.getRankDocumentFirstPage();
+// else document = RecommendUtil.getRankOtherPageDocument(count-2);
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// setSessionAttribute("comCnt",String.valueOf(count-1));
+// detail.getAttributes().put("comCnt",String.valueOf(count-1));
+// break;
+// }
+// case '5':{
+// String category = getSessionAttribute("category");
+// if (category == null) category = "古风";
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document = RecommendUtil.getCategory(count-2,category);
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// setSessionAttribute("comCnt",String.valueOf(count-1));
+// detail.getAttributes().put("comCnt",String.valueOf(count-1));
+// break;
+// }
+// default:{
+// detail.setResponse(buildErrorResponse("该功能还没实现"));
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// }
+//
+// private void dealOpenNumIntent(OverTimeDetail detail, String userId) {
+// String trace = getSessionAttribute("trace");
+// if (trace == null || trace.charAt(1) == '0') {
+// String numStr = getSlot("sys.number");
+// int num = 1;
+// if (numStr != null) num = Integer.parseInt(numStr);
+// detail.setResponse(dealOpenNumInHome(num, detail));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// } else if (trace.length() > 2) {
+// detail.setResponse(buildErrorResponse("客官,您在这个页面想打开啥"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// char page = trace.charAt(1);
+// switch (page){
+// case '1':
+// case '2': detail.setResponse(dealOpenNum(getSessionAttribute(PRE_COLLE), detail)); break;
+// case '3': detail.setResponse(dealOpenNumInRecommend(getSessionAttribute("recommand"),detail)); break;
+// case '4': detail.setResponse(dealOpenNumInRecommend(getSessionAttribute("recommand"),detail)); break;
+// case '5': detail.setResponse(dealOpenNumInCategory(userId, detail));break;
+// case '6': detail.setResponse(dealOpenNumInRecommend(getSessionAttribute("recommand"), detail));break;
+// default:{
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "屏幕上的图标都是可以点击的哦");
+// detail.getResponse().setOutputSpeech(outputSpeech);
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealOpenCollectIntent(OverTimeDetail detail, String userId) {
+// if (getAccessToken() == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
+// detail.setResponse(new Response(outputSpeech));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// } else {
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(userId, getAccessToken());
+// if (appUserId == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, SORRY_UNCATCH);
+// detail.setResponse(new Response(outputSpeech));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// }
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(), appUserId, 0);
+// if (document == null) {
+// backToHome(detail);
+// detail.setResponse(buildErrorResponse("您还没有收藏任何作品"));
+// return;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute("recommand", null);
+// setSessionAttribute(BACK_TRACE, "01");
+// setSessionAttribute("comCnt", null);
+// detail.getAttributes().put("comCnt", null);
+// detail.getAttributes().put("recommand", null);
+// detail.getAttributes().put(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(BACK_TRACE,"01");
+// detail.getDirectives().add(render);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+// }
+//
+// private void dealLoadIntent(OverTimeDetail detail, String userId) {
+// detail.setResponse(load());
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealBackIntent(OverTimeDetail detail, String userId) {
+// String trace = getSessionAttribute(BACK_TRACE);
+// char second;
+// if (trace == null || trace.length() <= 2 || getQuery().contains("首")) {
+// // home page
+// backToHome(detail);
+// if (trace != null && StringUtils.endsWith(trace,File.separator)) sendCancellToTerminate(userId);
+// } else if (StringUtils.endsWith(trace,File.separator)){
+// String botAccount = trace.substring(2, trace.length()-1);
+// log.info("返回作品的id:{}", botAccount);
+// backToBotIntro(botAccount, detail);
+// sendCancellToTerminate(userId);
+// } else {
+// second = trace.charAt(1);
+// switch (second){
+// // home page
+// case '0':{
+// backToHome(detail);
+// break;
+// }
+// case '1': {
+// //collect
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(userId, getAccessToken());
+// if (appUserId == null) {
+// backToHome(detail);
+// break;
+// }
+// }
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
+// appUserId, (count-1)*CO_HI_PAGE_SIZE);
+// if (document == null) {
+// backToHome(detail);
+// detail.setResponse(buildErrorResponse("您还未收藏过任何作品,快去收藏吧"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute(BACK_TRACE, "01");
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// detail.getAttributes().put(BACK_TRACE,"01");
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getDirectives().add(render);
+// break;
+// }
+// case '2': {
+// //history
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(), (count-1)*CO_HI_PAGE_SIZE);
+// if (document == null) {
+// backToHome(detail);
+// detail.setResponse(buildErrorResponse("哎呀,可能是您太久没玩了,历史记录已被清空"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute(BACK_TRACE, "02");
+// detail.getAttributes().put(BACK_TRACE,"02");
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getDirectives().add(render);
+// break;
+// }
+// case '3': {
+// //recommend
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// RecommandDocument recommandDocument = RecommendUtil.getRecommendDocument(count-1);
+// if (recommandDocument == null) {
+// RenderDocument render = new RenderDocument();
+// render.setDocument(LunchUtils.getLunchDocument());
+// addDirective(render);
+// detail.getDirectives().add(render);
+// setSessionAttribute(BACK_TRACE, null);
+// detail.getAttributes().put(BACK_TRACE, null);
+// break;
+// }
+// RenderDocument render = new RenderDocument();
+// render.setDocument(recommandDocument);
+// addDirective(render);
+// String token = recommandDocument.getRecommendIdList();
+// if (token != null) {
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// }
+// setSessionAttribute(BACK_TRACE, "03");
+// detail.getAttributes().put(BACK_TRACE, "03");
+// detail.getDirectives().add(render);
+// detail.setResponse(buildErrorResponse("已为您返回到推荐页"));
+// break;
+// }
+// case '4': {
+// //rank
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// RecommandDocument recommandDocument;
+// if (count == 1) recommandDocument = RecommendUtil.getRankDocumentFirstPage();
+// else recommandDocument = RecommendUtil.getRankOtherPageDocument(count-1);
+// if (recommandDocument == null) {
+// RenderDocument render = new RenderDocument();
+// render.setDocument(LunchUtils.getLunchDocument());
+// addDirective(render);
+// detail.getDirectives().add(render);
+// setSessionAttribute(BACK_TRACE, null);
+// detail.getAttributes().put(BACK_TRACE, null);
+// break;
+// }
+// RenderDocument render = new RenderDocument();
+// render.setDocument(recommandDocument);
+// addDirective(render);
+// String token = recommandDocument.getRecommendIdList();
+// if (token != null) {
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// }
+// setSessionAttribute(BACK_TRACE, "04");
+// detail.getAttributes().put(BACK_TRACE, "04");
+// detail.getDirectives().add(render);
+// detail.setResponse(buildErrorResponse("已为您返回到排行榜"));
+// break;
+// }
+// case '5':{
+// String category = getSessionAttribute("category");
+// if (category == null) {
+// backToHome(detail);
+// } else {
+// String count = getSessionAttribute("comCnt");
+// int pageIndex = 0;
+// if (count != null) pageIndex = Integer.parseInt(count)-1;
+// RecommandDocument document = RecommendUtil.getCategory(pageIndex, category);
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// detail.setResponse(buildErrorResponse(new StringBuilder("已为您返回到")
+// .append(category).append("分类第").append(pageIndex+1).append("页").toString()));
+// }
+// break;
+// }
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void backToHome(OverTimeDetail detail) {
+// RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
+// addDirective(renderDocument);
+// setSessionAttribute(BACK_TRACE,null);
+// detail.getAttributes().put(BACK_TRACE,null);
+// detail.getDirectives().add(renderDocument);
+// }
+//
+// private void dealDefaultIntent(IntentRequest intentRequest, OverTimeDetail detail, String userId,
+// String intentName,String word) {
+// if (word == null) {
+// Query query = intentRequest.getQuery();
+// if (query != null) word = query.getOriginal();
+// if (word == null){
+// log.info("小度没有传来任何话语");
+// detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// }
+// QiWuResponse data = null;
+// try {
+// data = RequestTerminal.requestTerminate(word, userId, type);
+// } catch (Exception e) {
+// log.error("请求终端接口出错:", e.toString());
+// }
+// if (data == null) {
+// detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// String text = data.getText();
+// if ("funny".equals(intentName) || data.getAipioneerUsername().equals("4151097686")) {
+// RecommandDocument document = displayFunnyRecommandPage(text, data.getAudio());
+// if (document != null) {
+// document.getMainTemplate().getItems().get(2).setSrc(data.getAudio());
+// FUNNY_DEFAULT_DOCUMENT = document;
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// setSessionAttribute("recommand", document.getRecommendIdList());
+// setSessionAttribute(BACK_TRACE, "06");
+// detail.getAttributes().put(BACK_TRACE, "06");
+// detail.getAttributes().put("recommand", document.getRecommendIdList());
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// log.info("funny has som situation出现问题");
+// }
+//// String aside = DplbotServiceUtil.getAsideText(text);
+//// //log.info("旁白名字:{}",aside);
+//// //log.info("小悟返回:{}", text);
+//// text = text.substring(text.indexOf("】")+1);
+//
+// if (ScheduleService.getExceptBotAccount().contains(data.getAipioneerUsername())) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, text.substring(text.indexOf("】")+1));
+// detail.getResponse().setOutputSpeech(outputSpeech);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// final String botAccount = data.getAipioneerUsername();
+// if (botAccount == null) {
+// detail.setResponse(buildErrorResponse("不支持该作品换一个吧"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// String beforeBotAccount = getSessionAttribute("botAcc");
+// if (!botAccount.equals(beforeBotAccount)) {
+// DplbotServiceUtil.updateTheUserBehaviorDataMark(userId, botAccount, getAccessToken());
+// String productName = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
+//
+//// PlayDocument document = PlayUtils.getPlayDocument(correctName(productName), aside,
+//// ScheduleService.getAsideImgUrl(botAccount, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern),
+// DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botAccount);
+//
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// DplbotServiceUtil.updateTheUserHistory(userId, botAccount, getAccessToken());
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace == null || trace.length() != 2) trace = "00";
+// trace = new StringBuilder(trace).append(botAccount).append(File.separator).toString();
+// setSessionAttribute(BACK_TRACE, trace);
+// setSessionAttribute("botAcc", botAccount);
+// detail.getAttributes().put("botAcc", botAccount);
+// detail.getAttributes().put(BACK_TRACE,trace);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// } else {
+//// ExecuteCommands executeCommands = new ExecuteCommands();
+//// SetStateCommand audio = new SetStateCommand();
+//// SetStateCommand textState = new SetStateCommand();
+//// audio.setComponentId("audioCom");
+//// audio.setState("src");
+//// audio.setValue(data.getAudio());
+//// textState.setComponentId("text");
+//// textState.setState("text");
+//// textState.setValue(text);
+////
+//// SetStateCommand asideImg = new SetStateCommand();
+//// asideImg.setComponentId("asideImg");
+//// asideImg.setState("src");
+//// asideImg.setValue(ScheduleService.getAsideImgUrl(botAccount, aside));
+////
+//// SetStateCommand asideText = new SetStateCommand();
+//// asideText.setComponentId("asideText");
+//// asideText.setState("text");
+//// asideText.setValue(aside);
+////
+//// executeCommands.addCommand(audio);
+//// executeCommands.addCommand(textState);
+//// executeCommands.addCommand(asideImg);
+//// executeCommands.addCommand(asideText);
+//
+//// UpdateComponentCommand update = new UpdateComponentCommand();
+//// update.setComponentId("whole");
+//// update.setDocument(TempleUtils.getPlayUpdate(data.getAudio(), text));
+//// executeCommands.addCommand(update);
+//
+//// addDirective(executeCommands);
+//// detail.getDirectives().add(executeCommands);
+//
+// String productName = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
+//// PlayDocument document = PlayUtils.getPlayDocument(correctName(productName), aside,
+//// ScheduleService.getAsideImgUrl(botAccount, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern),
+// DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botAccount);
+//
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+// }
+//
+// private Response dealOpenNumInRecommend(String idsToken, OverTimeDetail overDetail) {
+// if (idsToken == null) {
+// return buildErrorResponse("请重新进入当前页面");
+// }
+// int collectNum = Integer.parseInt(getSlot("sys.number"));
+// String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
+// if (collectNum > tokenList.length || collectNum <= 0) return buildErrorResponse("这个数字超出了范围");
+// OnProductDetail detail = ScheduleService.PRODUCT_ID_DETAIL.get(tokenList[collectNum-1]);
+// if (DplbotServiceUtil.doesUserPlayed(detail.getBotAccount(), getUserId(), getAccessToken())) {
+// String productName = correctName(detail.getName());
+// return directInProduct(productName, detail.getBotAccount(), overDetail);
+// } else {
+// return enterProductInfo(detail.getName(), overDetail);
+// }
+// }
+//
+// private Response dealOpenNumInCategory(String userId, OverTimeDetail detail) {
+// String count = getSessionAttribute("comCnt");
+// int pageIndex = 0;
+// if (count != null) pageIndex = Integer.parseInt(count)-1;
+// String numStr = getSlot("sys.number");
+// int num = 1;
+// if (numStr != null) num = Integer.parseInt(numStr);
+// List categoryBots = ScheduleService.getCategoryProductIdList().get(getSessionAttribute("category"));
+// num = pageIndex*RE_RA_CA_PAGE_SIZE+num-1;
+// if (num < 0 || num >= categoryBots.size()) {
+// Response response = buildErrorResponse("这个数字超出了范围,作品的序号已显示在图片左上角");
+// detail.setResponse(response);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return response;
+// }
+// String botId = categoryBots.get(num);
+// String name = ScheduleService.getProductIdDetail().get(botId).getName();
+// Response response;
+// if (DplbotServiceUtil.doesUserPlayed(botId, getUserId(), getAccessToken())) response = directInProduct(correctName(name), botId, detail);
+// else response = enterProductInfo(correctName(name), detail);
+// detail.setResponse(response);
+// return response;
+// }
+//
+// private Response dealOpenNumInHome(int num, OverTimeDetail detail) {
+// if (num > 0 && num <= 10) {
+// GameProjectTb bot = ScheduleService.getRecommendList().get(num-1);
+// log.info("历史:作品id:{}",bot.getBotAccount());
+// if (!DplbotServiceUtil.doesUserPlayed(bot.getBotAccount(), getUserId(), getAccessToken())) return enterProductInfo(bot.getName(), detail);
+// else return directInProduct(bot.getName(), bot.getBotAccount(), detail);
+// } else if (num > 10 && num <= 20) {
+// GameProjectTb bot = ScheduleService.getRankingList().get(num-11);
+// log.info("历史:作品id:{}",bot.getBotAccount());
+// if (!DplbotServiceUtil.doesUserPlayed(bot.getBotAccount(), getUserId(), getAccessToken())) return enterProductInfo(bot.getName(), detail);
+// else return directInProduct(bot.getName(), bot.getBotAccount(), detail);
+// } else if (num > 20 && num <= 30) {
+// String categoryName = ScheduleService.CATEGORY[num-21];
+// RecommandDocument document = RecommendUtil.getCategory(0, categoryName);
+// if (document == null) return buildErrorResponse("不好意思该分类还没有作品");
+// RenderDocument render = new RenderDocument(document);
+// this.addDirective(render);
+// detail.getDirectives().add(render);
+// this.setSessionAttribute("category",categoryName);
+// detail.getAttributes().put("category",categoryName);
+// this.setSessionAttribute("trace","05");
+// detail.getAttributes().put("trace","05");
+// return buildErrorResponse(new StringBuilder("为您打开").append(categoryName).append("类作品").toString());
+// }
+// else {
+// return buildErrorResponse("这数字超出我的范围了");
+// }
+// }
+//
+// private Response directInProduct(String name,String botId,OverTimeDetail detail) {
+// String productName = correctName(name);
+// String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
+// log.info("进入作品语句:{}", enterProductWord);
+// QiWuResponse data = null;
+// try {
+// data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
+// } catch (IOException e) {
+// log.error("请求终端接口出错:", e.toString());
+// }
+// if (data == null) {
+// return buildErrorResponse(SORRY_UNCATCH);
+// }
+// String text = data.getText();
+//// String aside = DplbotServiceUtil.getAsideText(text);
+//// text = text.substring(text.indexOf("】")+1);
+//// PlayDocument document = PlayUtils.getPlayDocument(productName, aside,ScheduleService.getAsideImgUrl(botId, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern),
+// DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botId);
+//
+// RenderDocument render = new RenderDocument(document);
+// this.setSessionAttribute(PRE_COLLE, null);
+// detail.getAttributes().put(PRE_COLLE, null);
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace == null || trace.length() != 2) trace = "00";
+// String backTrace = new StringBuilder(trace).append(botId).append(File.separator).toString();
+// this.setSessionAttribute(BACK_TRACE, backTrace);
+// detail.getAttributes().put(BACK_TRACE,backTrace);
+// this.addDirective(render);
+// detail.getDirectives().add(render);
+// return new Response();
+// }
+//
+// private Response enterProductInfo(String productName, OverTimeDetail detail) {
+// OnProductDetail productDetail = ScheduleService.PRODUCT_NAME_DETAIL.get(productName);
+// // product picture
+// String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
+//
+// // product create time
+// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+// String dateString = formatter.format(productDetail.getCreateTime());
+// String createTime = new StringBuilder(PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
+//
+// // product author
+// String author = new StringBuilder(PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
+//
+// // product labels
+// StringBuilder labels = new StringBuilder(PRODUCT_INTRO.LABEL);
+// for (String label: productDetail.getLabels()) {
+// labels.append(PRODUCT_INTRO.SPACE).append(label);
+// }
+//
+// // product introduction
+// String intro = productDetail.getIntro();
+//
+// // "start product" container button
+// String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
+//
+// String accessToken = getAccessToken();
+// String flowers, flowerReward,collectText, collectUrl, collectComId;
+// if (accessToken != null) {
+// // flower container button
+// Long count = DplbotServiceUtil.getUserSendFlowerNum(productDetail.getBotAccount(), getUserId(), accessToken);
+// flowers = USER_SEND_FLOWER+count;
+// flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
+//
+// // collection container button
+// boolean collec = DplbotServiceUtil.doesUserCollectThisBot(productDetail.getBotAccount(), accessToken, getUserId());
+// if (collec) {
+// collectText = COLLECED;
+// collectUrl = COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// } else {
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// }
+// } else {
+// flowers = FLOWER;
+// flowerReward = FLOWER_LOAD;
+//
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = FLOWER_LOAD; // 提示登录
+// }
+//
+// ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), createTime, author, labels.toString(),
+// intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
+//
+// RenderDocument renderDocument = new RenderDocument(document);
+// this.addDirective(renderDocument);
+// detail.getDirectives().add(renderDocument);
+// String trace = getSessionAttribute(BACK_TRACE);
+// log.info("before trace------------:{}",trace);
+// StringBuilder builder = new StringBuilder();
+// if (trace == null || trace.length() < 2) {
+// builder.append("00");
+// } else if (trace.length()>2) {
+// builder.append(trace, 0, 2);
+// } else {
+// builder.append(trace);
+// }
+//
+// trace = builder.append(productDetail.getBotAccount()).toString();
+// log.info("after trace------------:{}",trace);
+// this.setSessionAttribute(BACK_TRACE, trace);
+// detail.getAttributes().put(BACK_TRACE, trace);
+// return new Response();
+// }
+//
+// private RecommandDocument displayFunnyRecommandPage(String word, String audio) {
+// try {
+// List botNames = Utils.getRecommandBotNames(word);
+// log.info("botNames:{}",botNames);
+// List bots = new ArrayList<>();
+// for (String botName : botNames) {
+// if (botName.equals("清新传")) botName = "清新传{/zhuan4/}";
+// OnProductDetail detail = ScheduleService.PRODUCT_NAME_DETAIL.get(botName);
+// if (detail == null) continue;
+// bots.add(detail);
+// }
+// if (bots.size() != 0) return RecommendUtil.getFunnyDocument(bots, audio);
+// } catch (Exception e) {
+// log.error("获取funny页出错:{}",e.toString());
+// }
+// return null;
+// }
+//
+// private XiaoDuOrderTB buildBeforePayPojo(String botAccount, String appUserId, String userId, int unitPrice,
+// long number, String orderId) {
+// XiaoDuOrderTB xiaoDuOrderTB = new XiaoDuOrderTB();
+// buildPayPojoCommon(xiaoDuOrderTB, botAccount, appUserId, userId, unitPrice, number, orderId);
+// xiaoDuOrderTB.setDevice(1);
+// return xiaoDuOrderTB;
+// }
+//
+// private XiaoDuOrderTB buildNoScreenBeforePayPojo(String botAccount, String appUserId, String userId, int unitPrice,
+// long number, String orderId) {
+// XiaoDuOrderTB xiaoDuOrderTB = new XiaoDuOrderTB();
+// buildPayPojoCommon(xiaoDuOrderTB, botAccount, appUserId, userId, unitPrice, number, orderId);
+// xiaoDuOrderTB.setDevice(2);
+// return xiaoDuOrderTB;
+// }
+//
+// private void buildPayPojoCommon(XiaoDuOrderTB xiaoDuOrderTB, String botAccount, String appUserId, String userId, int unitPrice,
+// long number, String orderId) {
+// xiaoDuOrderTB.setBotId(botAccount);
+// xiaoDuOrderTB.setAppUserId(appUserId);
+// xiaoDuOrderTB.setXiaoduUserId(userId);
+// xiaoDuOrderTB.setUnitPrice(unitPrice);
+// xiaoDuOrderTB.setNumber(number);
+// xiaoDuOrderTB.setIsBuy(false);
+// xiaoDuOrderTB.setStatus(false);
+// xiaoDuOrderTB.setChOrderId(orderId);
+// xiaoDuOrderTB.setTimeStamp(curTime);
+// }
+//
+// @Override
+// protected Response onChargeEvent(ChargeEvent chargeEvent) {
+// String token = chargeEvent.getToken();
+// int sepIndex = token.indexOf(File.separator);
+// final String botAccount = token.substring(0, sepIndex);
+// String str = "恭喜您支付成功,开始体验吧";
+// if (getRequest().getContext().getScreen() != null) {
+// boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, customUserId(), getAccessToken(),
+// getSessionAttribute("userId"), PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_screen");
+// if (response) {
+// HashMap flowerRecords = DplbotServiceUtil.USER_HISTORY.get(getUserId()).getUserBotId2Flowers();
+// Long before = flowerRecords.get(botAccount);
+// if (before == null) before = 0L;
+// flowerRecords.put(botAccount, before+1);
+// ExecuteCommands executeCommands = new ExecuteCommands();
+// SetStateCommand stateCommand = new SetStateCommand();
+// stateCommand.setComponentId("pft");
+// stateCommand.setState("text");
+// stateCommand.setValue(USER_SEND_FLOWER+before);
+// executeCommands.addCommand(stateCommand);
+// try {
+// addDirective(executeCommands);
+// } catch (Exception e) {
+// log.info(ExceptionUtils.getStackTrace(e));
+// }
+// } else {
+// str = "很抱歉,您没有支付成功";
+// }
+// } else {
+// String userId = customUserId();
+// String jytUserId = getSessionAttribute("userId");
+// if (StringUtils.isBlank(jytUserId)) jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken());
+// if (StringUtils.isBlank(jytUserId)) {
+// jytUserId = "null";
+// }
+// boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, userId, getAccessToken(),
+// jytUserId, PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_no_screen");
+// if (!response) {
+// str = "很抱歉,您没有支付成功";
+// }
+// }
+// return buildErrorResponse(str);
+// }
+//
+// @Override
+// protected Response onPlaybackFinishedEvent(PlaybackFinishedEvent playbackFinishedEvent) {
+//// log.info("音频播放完毕,开麦");
+//// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+// this.setExpectSpeech(true);
+//// log.error("FinishedEvent");
+// return new Response();
+// }
+//
+// @Override
+// protected Response onPlaybackStoppedEvent(PlaybackStoppedEvent playbackStoppedEvent) {
+//// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+// waitAnswer();
+// return new Response();
+// }
+//
+// @Override
+// protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
+//// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+// Boolean result = stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+customUserId());
+// log.info("音频播放事件删除:"+result);
+// waitAnswer();
+// return new Response();
+// }
+//
+// @Override
+// protected Response onPlaybackNearlyFinishedEvent(PlaybackNearlyFinishedEvent playbackNearlyFinishedEvent) {
+//// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+// waitAnswer();
+// return new Response();
+// }
+//
+// @Override
+// protected Response onDefaultEvent() {
+// if (getRequest().getRequest() instanceof AudioPlayerEvent) {
+// this.setExpectSpeech(true);
+// return new Response();
+// }
+// return new Response();
+// }
+//
+// private String customUserId() {
+// try {
+// return PREFIX_USERID+ URLEncoder.encode(getUserId(), "UTF-8");
+// } catch (Exception e) {
+// log.error("xiaodu userid encode error:{}, {}",e, getUserId());
+// return PREFIX_USERID+ getUserId().replaceAll("/", "");
+// }
+//// return PREFIX_USERID + ai.qiwu.com.xiaoduhome.xiaoai.common.Utils.modifyDeviceId(getUserId());
+//// return PREFIX_USERID + getUserId().replaceAll(NUM_OR_ALPHA, "");
+// }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java
index be3fb3c..daf4572 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotService.java
@@ -1,2403 +1,2403 @@
package ai.qiwu.com.xiaoduhome.service;
-import ai.qiwu.com.xiaoduhome.common.*;
-import ai.qiwu.com.xiaoduhome.common.temple.CollectHistoryDocument;
-import ai.qiwu.com.xiaoduhome.common.temple.TempleUtils;
-import ai.qiwu.com.xiaoduhome.common.temple.onLunch.LunchUtils;
-import ai.qiwu.com.xiaoduhome.common.temple.play.PlayDocument;
-import ai.qiwu.com.xiaoduhome.common.temple.play.PlayUtils;
-import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoDocument;
-import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoUtils;
-import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommandDocument;
-import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommendUtil;
-import ai.qiwu.com.xiaoduhome.entity.primary.*;
-import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB;
-import ai.qiwu.com.xiaoduhome.pojo.*;
-import ai.qiwu.com.xiaoduhome.pojo.dpl.MyDocument;
-import ai.qiwu.com.xiaoduhome.pojo.playAside.PlayPageData;
-import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository;
-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.JSONArray;
-import com.alibaba.fastjson.JSONObject;
+//import ai.qiwu.com.xiaoduhome.common.*;
+//import ai.qiwu.com.xiaoduhome.common.temple.CollectHistoryDocument;
+//import ai.qiwu.com.xiaoduhome.common.temple.TempleUtils;
+//import ai.qiwu.com.xiaoduhome.common.temple.onLunch.LunchUtils;
+//import ai.qiwu.com.xiaoduhome.common.temple.play.PlayDocument;
+//import ai.qiwu.com.xiaoduhome.common.temple.play.PlayUtils;
+//import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoDocument;
+//import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoUtils;
+//import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommandDocument;
+//import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommendUtil;
+//import ai.qiwu.com.xiaoduhome.entity.primary.*;
+//import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB;
+//import ai.qiwu.com.xiaoduhome.pojo.*;
+//import ai.qiwu.com.xiaoduhome.pojo.dpl.MyDocument;
+//import ai.qiwu.com.xiaoduhome.pojo.playAside.PlayPageData;
+//import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository;
+//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.JSONArray;
+//import com.alibaba.fastjson.JSONObject;
import com.baidu.dueros.bot.BaseBot;
-import com.baidu.dueros.data.request.IntentRequest;
-import com.baidu.dueros.data.request.LaunchRequest;
-import com.baidu.dueros.data.request.Query;
-import com.baidu.dueros.data.request.SessionEndedRequest;
-import com.baidu.dueros.data.request.audioplayer.event.PlaybackFinishedEvent;
-import com.baidu.dueros.data.request.audioplayer.event.PlaybackNearlyFinishedEvent;
-import com.baidu.dueros.data.request.audioplayer.event.PlaybackStartedEvent;
-import com.baidu.dueros.data.request.audioplayer.event.PlaybackStoppedEvent;
-import com.baidu.dueros.data.request.events.LinkAccountSucceededEvent;
-import com.baidu.dueros.data.request.pay.event.ChargeEvent;
-import com.baidu.dueros.data.response.OutputSpeech;
-import com.baidu.dueros.data.response.Reprompt;
-import com.baidu.dueros.data.response.card.*;
-import com.baidu.dueros.data.response.directive.Directive;
-import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective;
-import com.baidu.dueros.data.response.directive.audioplayer.Play;
-import com.baidu.dueros.data.response.directive.display.PushStack;
-import com.baidu.dueros.data.response.directive.dpl.ExecuteCommands;
-import com.baidu.dueros.data.response.directive.dpl.RenderDocument;
-import com.baidu.dueros.data.response.directive.dpl.commands.*;
-import com.baidu.dueros.data.response.directive.dpl.event.UserEvent;
-import com.baidu.dueros.data.response.directive.pay.Buy;
-import com.baidu.dueros.data.response.directive.pay.Charge;
-import com.baidu.dueros.model.Response;
-import com.baidu.dueros.nlu.Intent;
+//import com.baidu.dueros.data.request.IntentRequest;
+//import com.baidu.dueros.data.request.LaunchRequest;
+//import com.baidu.dueros.data.request.Query;
+//import com.baidu.dueros.data.request.SessionEndedRequest;
+//import com.baidu.dueros.data.request.audioplayer.event.PlaybackFinishedEvent;
+//import com.baidu.dueros.data.request.audioplayer.event.PlaybackNearlyFinishedEvent;
+//import com.baidu.dueros.data.request.audioplayer.event.PlaybackStartedEvent;
+//import com.baidu.dueros.data.request.audioplayer.event.PlaybackStoppedEvent;
+//import com.baidu.dueros.data.request.events.LinkAccountSucceededEvent;
+//import com.baidu.dueros.data.request.pay.event.ChargeEvent;
+//import com.baidu.dueros.data.response.OutputSpeech;
+//import com.baidu.dueros.data.response.Reprompt;
+//import com.baidu.dueros.data.response.card.*;
+//import com.baidu.dueros.data.response.directive.Directive;
+//import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective;
+//import com.baidu.dueros.data.response.directive.audioplayer.Play;
+//import com.baidu.dueros.data.response.directive.display.PushStack;
+//import com.baidu.dueros.data.response.directive.dpl.ExecuteCommands;
+//import com.baidu.dueros.data.response.directive.dpl.RenderDocument;
+//import com.baidu.dueros.data.response.directive.dpl.commands.*;
+//import com.baidu.dueros.data.response.directive.dpl.event.UserEvent;
+//import com.baidu.dueros.data.response.directive.pay.Buy;
+//import com.baidu.dueros.data.response.directive.pay.Charge;
+//import com.baidu.dueros.model.Response;
+//import com.baidu.dueros.nlu.Intent;
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.apache.commons.lang3.exception.ExceptionUtils;
-import org.apache.commons.lang3.math.NumberUtils;
-
+//import org.apache.commons.lang3.RandomStringUtils;
+//import org.apache.commons.lang3.RandomUtils;
+//import org.apache.commons.lang3.StringUtils;
+//import org.apache.commons.lang3.exception.ExceptionUtils;
+//import org.apache.commons.lang3.math.NumberUtils;
+//
import javax.servlet.http.HttpServletRequest;
import java.io.*;
-import java.net.URLEncoder;
-import java.text.SimpleDateFormat;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.regex.Pattern;
-
-import static ai.qiwu.com.xiaoduhome.common.Constants.*;
-import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.*;
-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.WelcomeWord.*;
-import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.*;
-import static ai.qiwu.com.xiaoduhome.service.ScheduleService.*;
-import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.LAST_OUTTIME_MARK;
-import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.OUTTIME_TYPE_0;
-
+//import java.net.URLEncoder;
+//import java.text.SimpleDateFormat;
+//import java.util.*;
+//import java.util.concurrent.*;
+//import java.util.regex.Pattern;
+//
+//import static ai.qiwu.com.xiaoduhome.common.Constants.*;
+//import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.*;
+//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.WelcomeWord.*;
+//import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.*;
+//import static ai.qiwu.com.xiaoduhome.service.ScheduleService.*;
+//import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.LAST_OUTTIME_MARK;
+//import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.OUTTIME_TYPE_0;
+//
/**
* @author 苗权威
* @dateTime 19-8-6 下午8:06
*/
@Slf4j
public class DplBotService extends BaseBot {
- private static final MyDocument FIRST_PAGE;
-
- private static final ConcurrentHashMap LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
-
- private static volatile RecommandDocument FUNNY_DEFAULT_DOCUMENT;
-
- // 用来处理短时间内的多次请求
- private static final ConcurrentHashMap> CACHE_XIAODU_REQUEST = new ConcurrentHashMap<>();
-
- private static final ConcurrentHashMap USERID_AUDIO_PATH = new ConcurrentHashMap<>();
-
- static {
- FIRST_PAGE = JSON.parseObject(DplbotServiceUtil.getDPLTemple("static/json/firstPage.json"), MyDocument.class);
- }
-
- 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 final int type;
-
- private final static Reprompt WAIT_WORD = new Reprompt(new OutputSpeech(OutputSpeech.SpeechType.PlainText, "晓悟正在等你的回复"));
-
+// private static final MyDocument FIRST_PAGE;
+//
+// private static final ConcurrentHashMap LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
+//
+// private static volatile RecommandDocument FUNNY_DEFAULT_DOCUMENT;
+//
+// // 用来处理短时间内的多次请求
+// private static final ConcurrentHashMap> CACHE_XIAODU_REQUEST = new ConcurrentHashMap<>();
+//
+// private static final ConcurrentHashMap USERID_AUDIO_PATH = new ConcurrentHashMap<>();
+//
+// static {
+// FIRST_PAGE = JSON.parseObject(DplbotServiceUtil.getDPLTemple("static/json/firstPage.json"), MyDocument.class);
+// }
+//
+// 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 final int type;
+//
+// private final static Reprompt WAIT_WORD = new Reprompt(new OutputSpeech(OutputSpeech.SpeechType.PlainText, "晓悟正在等你的回复"));
+//
public DplBotService(HttpServletRequest request, Integer type) throws IOException {
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.setEnvironmentInfo(PRIVATE_KEY, 1);
// this.botMonitor.setMonitorEnabled(true);
}
-
- @Override
- public Response onLaunch(LaunchRequest launchRequest) {
- if (getRequest().getContext().getScreen() == null) {
- String userId = customUserId();
- LAST_OUTTIME_MARK.remove(userId);
- LAST_OUTTIME_RESULT.remove(userId);
- USERID_AUDIO_PATH.remove(userId);
- String welcomeWord;
- String skillName;
- String num = RandomStringUtils.randomNumeric(3);
- switch (type) {
- case 1 : {
-// welcomeWord = WELCOME_SMART_FORMAT;
-// try {
-// List botList = channel2Bots.get("jiaoyou-audio-child-test");
-// String name = botList.get(Integer.parseInt(num)%botList.size());
-// welcomeWord = String.format(welcomeWord, name,name);
-// } catch (Exception e) {
-// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
-// welcomeWord = WELCOME_SMART;
-// }
- welcomeWord = WELCOME_SMART;
- skillName = SKILL_SMART;
- break;
- }
- case 2 : {
-// welcomeWord = WELCOME_NOVEL_FORMAT;
+//
+// @Override
+// public Response onLaunch(LaunchRequest launchRequest) {
+// if (getRequest().getContext().getScreen() == null) {
+// String userId = customUserId();
+// LAST_OUTTIME_MARK.remove(userId);
+// LAST_OUTTIME_RESULT.remove(userId);
+// USERID_AUDIO_PATH.remove(userId);
+// String welcomeWord;
+// String skillName;
+// String num = RandomStringUtils.randomNumeric(3);
+// switch (type) {
+// case 1 : {
+//// welcomeWord = WELCOME_SMART_FORMAT;
+//// try {
+//// List botList = channel2Bots.get("jiaoyou-audio-child-test");
+//// String name = botList.get(Integer.parseInt(num)%botList.size());
+//// welcomeWord = String.format(welcomeWord, name,name);
+//// } catch (Exception e) {
+//// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+//// welcomeWord = WELCOME_SMART;
+//// }
+// welcomeWord = WELCOME_SMART;
+// skillName = SKILL_SMART;
+// break;
+// }
+// case 2 : {
+//// welcomeWord = WELCOME_NOVEL_FORMAT;
+//// try {
+//// List botList = channel2Bots.get("jiaoyou-audio-adult-test");
+//// String name = botList.get(Integer.parseInt(num)%botList.size());
+//// welcomeWord = String.format(welcomeWord, name,name);
+//// } catch (Exception e) {
+//// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+//// welcomeWord = WELCOME_NOVEL;
+//// }
+// welcomeWord = WELCOME_NOVEL;
+// skillName = SKILL_NOVEL;
+// break;
+// }
+// case 3 : welcomeWord = WelcomeWord.WELCOME_STORY; skillName = SKILL_STORY; break;
+// case 4 : welcomeWord = WelcomeWord.WELCOME_LITERATURE; skillName = SKILL_LITERATURE; break;
+// default: {
+// welcomeWord = WELCOME_FORMAT;
// try {
-// List botList = channel2Bots.get("jiaoyou-audio-adult-test");
+// List botList = jiaoyouChannel2Bots.get("jiaoyou-audio-adult-test");
// String name = botList.get(Integer.parseInt(num)%botList.size());
// welcomeWord = String.format(welcomeWord, name,name);
// } catch (Exception e) {
// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
-// welcomeWord = WELCOME_NOVEL;
+// welcomeWord = WELCOME;
// }
- welcomeWord = WELCOME_NOVEL;
- skillName = SKILL_NOVEL;
- break;
- }
- case 3 : welcomeWord = WelcomeWord.WELCOME_STORY; skillName = SKILL_STORY; break;
- case 4 : welcomeWord = WelcomeWord.WELCOME_LITERATURE; skillName = SKILL_LITERATURE; break;
- default: {
- welcomeWord = WELCOME_FORMAT;
- try {
- List botList = jiaoyouChannel2Bots.get("jiaoyou-audio-adult-test");
- String name = botList.get(Integer.parseInt(num)%botList.size());
- welcomeWord = String.format(welcomeWord, name,name);
- } catch (Exception e) {
- log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
- welcomeWord = WELCOME;
- }
- skillName = SKILL;
- break;
- }
- }
- StandardCard standardCard = new StandardCard(skillName, welcomeWord);
- standardCard.setImage(FIRST_IMAGE);
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord);
- return new Response(outputSpeech, standardCard);
- } else {
- return new Response();
- }
-// RenderDocument renderDocument = new RenderDocument(FIRST_PAGE);
-// this.addDirective(renderDocument);
-// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, Constants.WelcomeWord.WELCOME);
-// // 初次进入时创建用户的行为信息,包括历史记录,送花数,收藏记录
-// // 历史记录,收藏记录,送花数,郊游天下id
-// if (DplbotServiceUtil.USER_HISTORY.get(getUserId()) == null) {
-// String accessToken = getAccessToken();
-// if (accessToken != null) setSessionAttribute("userId", DplbotServiceUtil.getUserIdByToken(accessToken));
-// DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, getUserId());
-// }
-// return new Response(outputSpeech);
- }
-
- @Override
- protected Response onInent(IntentRequest intentRequest) {
- final String userId = customUserId();
- if (getRequest().getContext().getScreen() == null) {
-// final String deviceUserId = PREFIX_USERID + getDeviceId();
- Byte overTimeType;
- String path;
- if ((overTimeType = LAST_OUTTIME_MARK.remove(userId)) != null) {
- OverTimeDetail lastData = LAST_OUTTIME_RESULT.get(userId);
- if (lastData != null) {
- for (Directive directive : lastData.getDirectives()) {
- //log.info("上次超时保存的Directive:{}",directive.getClass().getName());
- this.addDirective(directive);
- }
- for (Map.Entry entry : lastData.getAttributes().entrySet()) {
- //log.info("上次超时保存的key:{}",key);
- this.setSessionAttribute(entry.getKey(), entry.getValue());
- }
- LAST_OUTTIME_MARK.remove(userId);
- LAST_OUTTIME_RESULT.remove(userId);
- return lastData.getResponse();
- }
- if (overTimeType != 3) {
- LAST_OUTTIME_MARK.put(userId, (byte) (overTimeType+1));
- return buildErrorResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
- XiaoAiConstants.TTS.WAIT_WORD_2);
- }
- LAST_OUTTIME_MARK.remove(userId);
- } else if ((path = USERID_AUDIO_PATH.get(userId)) != null) {
- Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
- addDirective(play);
-// log.error("小度音频播放开始事件未被触发:"+path);
-// dealWithFinishedNoCallEvent(userId);
- return new Response();
- }
- try {
- Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId));
- future.get(2700, TimeUnit.MILLISECONDS);
- } catch (InterruptedException | ExecutionException e) {
- log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
- return buildErrorResponse(SORRY_UNCATCH);
- } catch (TimeoutException e) {
- log.info("超时,让用户再说一遍:{}",e.toString());
- LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_0);
- return buildErrorResponse(SORRY_UNCATCH);
- } catch (Exception all) {
- log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
- return buildErrorResponse(SORRY_UNCATCH);
- }
- OverTimeDetail detail;
- if ((detail = LAST_OUTTIME_RESULT.remove(userId)) != null) return detail.getResponse();
- return new Response();
- } else {
- 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));
+// skillName = SKILL;
+// break;
+// }
// }
-// return detail.getResponse();
+// StandardCard standardCard = new StandardCard(skillName, welcomeWord);
+// standardCard.setImage(FIRST_IMAGE);
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord);
+// return new Response(outputSpeech, standardCard);
+// } else {
+// return new Response();
// }
-// 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);
+//// RenderDocument renderDocument = new RenderDocument(FIRST_PAGE);
+//// this.addDirective(renderDocument);
+//// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, Constants.WelcomeWord.WELCOME);
+//// // 初次进入时创建用户的行为信息,包括历史记录,送花数,收藏记录
+//// // 历史记录,收藏记录,送花数,郊游天下id
+//// if (DplbotServiceUtil.USER_HISTORY.get(getUserId()) == null) {
+//// String accessToken = getAccessToken();
+//// if (accessToken != null) setSessionAttribute("userId", DplbotServiceUtil.getUserIdByToken(accessToken));
+//// DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, getUserId());
+//// }
+//// return new Response(outputSpeech);
+// }
+//
+// @Override
+// protected Response onInent(IntentRequest intentRequest) {
+// final String userId = customUserId();
+// if (getRequest().getContext().getScreen() == null) {
+//// final String deviceUserId = PREFIX_USERID + getDeviceId();
+// Byte overTimeType;
+// String path;
+// if ((overTimeType = LAST_OUTTIME_MARK.remove(userId)) != null) {
+// OverTimeDetail lastData = LAST_OUTTIME_RESULT.get(userId);
+// if (lastData != null) {
+// for (Directive directive : lastData.getDirectives()) {
+// //log.info("上次超时保存的Directive:{}",directive.getClass().getName());
+// this.addDirective(directive);
+// }
+// for (Map.Entry entry : lastData.getAttributes().entrySet()) {
+// //log.info("上次超时保存的key:{}",key);
+// this.setSessionAttribute(entry.getKey(), entry.getValue());
+// }
+// LAST_OUTTIME_MARK.remove(userId);
+// LAST_OUTTIME_RESULT.remove(userId);
+// return lastData.getResponse();
+// }
+// if (overTimeType != 3) {
+// LAST_OUTTIME_MARK.put(userId, (byte) (overTimeType+1));
+// return buildErrorResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
+// XiaoAiConstants.TTS.WAIT_WORD_2);
+// }
+// LAST_OUTTIME_MARK.remove(userId);
+// } else if ((path = USERID_AUDIO_PATH.get(userId)) != null) {
+// Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+// addDirective(play);
+//// log.error("小度音频播放开始事件未被触发:"+path);
+//// dealWithFinishedNoCallEvent(userId);
// return new Response();
-// }else {
+// }
+// try {
+// Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId));
+// future.get(2700, TimeUnit.MILLISECONDS);
+// } catch (InterruptedException | ExecutionException e) {
+// log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
+// return buildErrorResponse(SORRY_UNCATCH);
+// } catch (TimeoutException e) {
+// log.info("超时,让用户再说一遍:{}",e.toString());
+// LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_0);
+// return buildErrorResponse(SORRY_UNCATCH);
+// } catch (Exception all) {
+// log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
// 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");
-// });
+// OverTimeDetail detail;
+// if ((detail = LAST_OUTTIME_RESULT.remove(userId)) != null) return detail.getResponse();
+// return new Response();
// } else {
-// DplbotServiceUtil.getPOOL().submit(() -> {
-// WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du2");
-// });
+// return new Response();
// }
+//// OverTimeDetail detail;
+//// if ((detail = LAST_OUTTIME_RESULT.remove(userId)) != null) {
+//// for (Directive directive : detail.getDirectives()) {
+//// //log.info("上次超时保存的Directive:{}",directive.getClass().getName());
+//// this.addDirective(directive);
+//// }
+//// for (String key : detail.getAttributes().keySet()) {
+//// //log.info("上次超时保存的key:{}",key);
+//// this.setSessionAttribute(key, detail.getAttributes().get(key));
+//// }
+//// return detail.getResponse();
+//// }
+//// try {
+//// Future future = DplbotServiceUtil.getPOOL().submit(new Task(intentRequest));
+//// future.get(2200, TimeUnit.MILLISECONDS);
+//// } catch (InterruptedException | ExecutionException e) {
+//// log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
+//// return buildErrorResponse(SORRY_UNCATCH);
+//// } catch (TimeoutException e) {
+//// log.info("超时,让用户再说一遍:{}",e.toString());
+//// if ("funny".equals(getIntent().getName()) && FUNNY_DEFAULT_DOCUMENT != null) {
+//// RenderDocument document = new RenderDocument(FUNNY_DEFAULT_DOCUMENT);
+//// this.addDirective(document);
+//// return new Response();
+//// }else {
+//// return buildErrorResponse(SORRY_UNCATCH);
+//// }
+//// } catch (Exception all) {
+//// log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
+//// return buildErrorResponse(SORRY_UNCATCH);
+//// }
+//// OverTimeDetail data = LAST_OUTTIME_RESULT.remove(getUserId());
+//// if (data == null) return new Response();
+//// return data.getResponse();
// }
-
- private void dealNoScreenIntentTemp(IntentRequest intentRequest, String userId) {
- String intentName = getIntent().getName();
- OverTimeDetail data = new OverTimeDetail();
- LAST_OUTTIME_RESULT.put(userId, data);
- if ("sendFlower".equals(intentName)) {
- dealNoScreenSendFlowerIntent(userId, data);
- return;
- } else if ("load".equals(intentName)) {
- Card card = new LinkAccountCard();
- Response response = buildErrorResponse("请在小度App上完成登录");
- response.setCard(card);
- data.setResponse(response);
- return;
- }
-
- List requestList = CACHE_XIAODU_REQUEST.get(userId);
- try {
- if (requestList == null) {
- requestList = new ArrayList<>();
- requestList.add(intentRequest);
- CACHE_XIAODU_REQUEST.put(userId, requestList);
- Thread.sleep(100);
- int i = 1;
- int j;
- int count = 0;
- while (i != (j = CACHE_XIAODU_REQUEST.get(userId).size()) && count < 5) {
- i = j;
- Thread.sleep(100);
- ++count;
- }
- intentRequest = requestList.get(i-1);
- } else {
- requestList.add(intentRequest);
-// log.warn("小度重复现象出现:{},requestId:{}",intentRequest.getQuery().getOriginal(), intentRequest.getRequestId());
- log.warn("小度重复现象出现:{},",getStrRequest());
- synchronized (requestList) {
- requestList.wait(10000);
- log.info("等待线程苏醒");
- }
- return;
- }
- final Query query = intentRequest.getQuery();
- final String userWord = query.getOriginal();
-// if (query != null) userWord = query.getOriginal();
- if (userWord == null){
- log.error("小度没有传来任何话语");
- data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
- return;
- }
-// log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId());
-
- String channel;
- switch (type) {
- case 1 :
- case 3 : channel = "jiaoyou-audio-child-test";break;
- case 2 :
- case 4 : channel = "jiaoyou-audio-adult-test";break;
- default: channel = "jiaoyou-audio-test";break;
- }
- String response = RequestTerminal.requestTerminateTemp(userWord, userId, channel);
-// log.info("小度,小悟返回:{},",response);
- if (StringUtils.isBlank(response)) {
- data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
- return;
- }
-// String mark = RandomStringUtils.randomAlphabetic(3);
-// AudioBoxData pathData = new AudioBoxData();
-// OkHttp3Utils.asyncPost(XiaoAiConstants.TTS_DIDI3, response, pathData);
- try {
- JSONObject object = JSON.parseObject(response);
- JSONArray commands = object.getJSONArray("commands");
- if (commands != null && commands.size() != 0) {
- String txt;
- for (Object ob: commands) {
- txt = ((JSONObject) ob).getString("text");
- int i;
- if (StringUtils.isNotBlank(txt) && (i=txt.indexOf("out")) != -1) {
- log.info("小度,推荐bot退出:{},{}",userWord,userId);
- String content = txt.substring(i+3, txt.indexOf("☚")).trim();
- String byeWord = null;
- String skillName = null;
- switch (type) {
- case 1: {
- byeWord = EndMsg.END_BYE_STORY;
- skillName = SKILL_SMART;
- break;
- }
- case 2: {
- byeWord = EndMsg.END_BYE_NOVEL;
- skillName = SKILL_NOVEL;
- break;
- }
- case 5: {
- byeWord = EndMsg.END_BYE_JIAOYOU;
- skillName = SKILL;
- break;
- }
- }
- if (byeWord == null) byeWord = EndMsg.END_BYE_Adult;
- if (skillName == null) skillName = SKILL_DEFAULT;
- if (StringUtils.isBlank(content)) {
- JSONArray dialogs = object.getJSONArray("dialogs");
- if (dialogs != null && dialogs.size() != 0) {
- String str = ((JSONObject)dialogs.get(0)).getString("text");
- if (StringUtils.isNotBlank(str)) {
- str = str.replaceAll("\\{/.*?/}", "")+skillName;
- data.setResponse(buildLogOutResponse(str));
- RequestTerminal.backRequest(userId, type);
- return;
- }
- }
- RequestTerminal.backRequest(userId, type);
- data.setResponse(buildLogOutResponse(byeWord));
- return;
- } else {
- content = content.replaceAll("\\{/.*?/}", "")+skillName;
- data.setResponse(buildLogOutResponse(content));
- RequestTerminal.backRequest(userId, type);
- return;
- }
- }
- }
- }
- } catch (Exception e) {
- log.error("推荐bot退出解析出错:"+e);
- }
- String path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
-// String path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", response);
- if (StringUtils.isBlank(path) || "null".equals(path)) {
- log.error("小度没有获取到音频链接");
- data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
- return;
- }
-// final JSONObject ob = JSONObject.parseObject(response);
-// String botAcc = ob.getString("aipioneerUsername");
-// String beforeBotAccount = getSessionAttribute("botAcc");
-// if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(botAcc)) {
-// setSessionAttribute("botAcc", botAcc);
-// data.getAttributes().put("botAcc",botAcc);
+//
+//// private void dealWithFinishedNoCallEvent(String userId) {
+//// if (userId.equals(DU_DEVICE_ID)) {
+//// DplbotServiceUtil.getPOOL().submit(() -> {
+//// WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du1");
+//// });
+//// } else {
+//// DplbotServiceUtil.getPOOL().submit(() -> {
+//// WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du2");
+//// });
+//// }
+//// }
+//
+// private void dealNoScreenIntentTemp(IntentRequest intentRequest, String userId) {
+// String intentName = getIntent().getName();
+// OverTimeDetail data = new OverTimeDetail();
+// LAST_OUTTIME_RESULT.put(userId, data);
+// if ("sendFlower".equals(intentName)) {
+// dealNoScreenSendFlowerIntent(userId, data);
+// return;
+// } else if ("load".equals(intentName)) {
+// Card card = new LinkAccountCard();
+// Response response = buildErrorResponse("请在小度App上完成登录");
+// response.setCard(card);
+// data.setResponse(response);
+// return;
+// }
+//
+// List requestList = CACHE_XIAODU_REQUEST.get(userId);
+// try {
+// if (requestList == null) {
+// requestList = new ArrayList<>();
+// requestList.add(intentRequest);
+// CACHE_XIAODU_REQUEST.put(userId, requestList);
+// Thread.sleep(100);
+// int i = 1;
+// int j;
+// int count = 0;
+// while (i != (j = CACHE_XIAODU_REQUEST.get(userId).size()) && count < 5) {
+// i = j;
+// Thread.sleep(100);
+// ++count;
+// }
+// intentRequest = requestList.get(i-1);
+// } else {
+// requestList.add(intentRequest);
+//// log.warn("小度重复现象出现:{},requestId:{}",intentRequest.getQuery().getOriginal(), intentRequest.getRequestId());
+// log.warn("小度重复现象出现:{},",getStrRequest());
+// synchronized (requestList) {
+// requestList.wait(10000);
+// log.info("等待线程苏醒");
+// }
+// return;
// }
-
- Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
- addDirective(play);
- data.getDirectives().add(play);
- USERID_AUDIO_PATH.put(userId, path);
-// if (userId.equals(DU_DEVICE_ID)) {
-// DplbotServiceUtil.getPOOL().submit(() -> {
-// JSONArray array = ob.getJSONArray("dialogs");
-// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
-// for (Object item: array) {
-// String str = ((JSONObject) item).getString("text");
-// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+// final Query query = intentRequest.getQuery();
+// final String userWord = query.getOriginal();
+//// if (query != null) userWord = query.getOriginal();
+// if (userWord == null){
+// log.error("小度没有传来任何话语");
+// data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
+// return;
+// }
+//// log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId());
+//
+// String channel;
+// switch (type) {
+// case 1 :
+// case 3 : channel = "jiaoyou-audio-child-test";break;
+// case 2 :
+// case 4 : channel = "jiaoyou-audio-adult-test";break;
+// default: channel = "jiaoyou-audio-test";break;
+// }
+// String response = RequestTerminal.requestTerminateTemp(userWord, userId, channel);
+//// log.info("小度,小悟返回:{},",response);
+// if (StringUtils.isBlank(response)) {
+// data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
+// return;
+// }
+//// String mark = RandomStringUtils.randomAlphabetic(3);
+//// AudioBoxData pathData = new AudioBoxData();
+//// OkHttp3Utils.asyncPost(XiaoAiConstants.TTS_DIDI3, response, pathData);
+// try {
+// JSONObject object = JSON.parseObject(response);
+// JSONArray commands = object.getJSONArray("commands");
+// if (commands != null && commands.size() != 0) {
+// String txt;
+// for (Object ob: commands) {
+// txt = ((JSONObject) ob).getString("text");
+// int i;
+// if (StringUtils.isNotBlank(txt) && (i=txt.indexOf("out")) != -1) {
+// log.info("小度,推荐bot退出:{},{}",userWord,userId);
+// String content = txt.substring(i+3, txt.indexOf("☚")).trim();
+// String byeWord = null;
+// String skillName = null;
+// switch (type) {
+// case 1: {
+// byeWord = EndMsg.END_BYE_STORY;
+// skillName = SKILL_SMART;
+// break;
+// }
+// case 2: {
+// byeWord = EndMsg.END_BYE_NOVEL;
+// skillName = SKILL_NOVEL;
+// break;
+// }
+// case 5: {
+// byeWord = EndMsg.END_BYE_JIAOYOU;
+// skillName = SKILL;
+// break;
+// }
+// }
+// if (byeWord == null) byeWord = EndMsg.END_BYE_Adult;
+// if (skillName == null) skillName = SKILL_DEFAULT;
+// if (StringUtils.isBlank(content)) {
+// JSONArray dialogs = object.getJSONArray("dialogs");
+// if (dialogs != null && dialogs.size() != 0) {
+// String str = ((JSONObject)dialogs.get(0)).getString("text");
+// if (StringUtils.isNotBlank(str)) {
+// str = str.replaceAll("\\{/.*?/}", "")+skillName;
+// data.setResponse(buildLogOutResponse(str));
+// RequestTerminal.backRequest(userId, type);
+// return;
+// }
+// }
+// RequestTerminal.backRequest(userId, type);
+// data.setResponse(buildLogOutResponse(byeWord));
+// return;
+// } else {
+// content = content.replaceAll("\\{/.*?/}", "")+skillName;
+// data.setResponse(buildLogOutResponse(content));
+// RequestTerminal.backRequest(userId, type);
+// return;
+// }
+// }
// }
-// WebSocketLog.sendInfo(builder.toString(), "du1");
-// });
+// }
+// } catch (Exception e) {
+// log.error("推荐bot退出解析出错:"+e);
+// }
+// String path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
+//// String path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", response);
+// if (StringUtils.isBlank(path) || "null".equals(path)) {
+// log.error("小度没有获取到音频链接");
+// data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
+// return;
+// }
+//// final JSONObject ob = JSONObject.parseObject(response);
+//// String botAcc = ob.getString("aipioneerUsername");
+//// String beforeBotAccount = getSessionAttribute("botAcc");
+//// if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(botAcc)) {
+//// setSessionAttribute("botAcc", botAcc);
+//// data.getAttributes().put("botAcc",botAcc);
+//// }
+//
+// Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+// addDirective(play);
+// data.getDirectives().add(play);
+// USERID_AUDIO_PATH.put(userId, path);
+//// if (userId.equals(DU_DEVICE_ID)) {
+//// DplbotServiceUtil.getPOOL().submit(() -> {
+//// JSONArray array = ob.getJSONArray("dialogs");
+//// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+//// for (Object item: array) {
+//// String str = ((JSONObject) item).getString("text");
+//// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+//// }
+//// WebSocketLog.sendInfo(builder.toString(), "du1");
+//// });
+//// } else {
+//// DplbotServiceUtil.getPOOL().submit(() -> {
+//// JSONArray array = ob.getJSONArray("dialogs");
+//// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+//// for (Object item: array) {
+//// String str = ((JSONObject) item).getString("text");
+//// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+//// }
+//// WebSocketLog.sendInfo(builder.toString(), "du2");
+//// });
+//// }
+// } catch (Exception e) {
+// log.warn("中控返回结果为空:"+e);
+// data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
+// }
+// finally {
+// if (requestList != null && requestList.size() > 1) {
+// synchronized (requestList){
+// requestList.notifyAll();
+// }
+// }
+// CACHE_XIAODU_REQUEST.remove(userId);
+// }
+// }
+//
+// private String dealAudioUrl(String path) {
+// return Constants.TTS_DIDI3_GET+path;
+//// return "http://didi-gz5.jiaoyou365.com:9663/api/audio/get?path="+path;
+// }
+//
+// private void dealNoScreenSendFlowerIntent(String userId, OverTimeDetail data) {
+// if (getAccessToken() == null) {
+// data.setResponse(buildErrorResponse("该功能需要登录"));
+// return ;
+// }
+// String num = getSlot("sys.number");
+// OutputSpeech outputSpeech;
+// String confirmationStatus = getIntent().getConfirmationStatus().name();
+// log.info("槽位确认状态:{}",confirmationStatus);
+// if ("NONE".equals(confirmationStatus)) {
+// if (num == null) {
+// log.info("确认送花个数");
+// ask("sys.number");
+// outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请问您要送几朵花");
+// setExpectSpeech(true);
// } else {
-// DplbotServiceUtil.getPOOL().submit(() -> {
-// JSONArray array = ob.getJSONArray("dialogs");
-// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
-// for (Object item: array) {
-// String str = ((JSONObject) item).getString("text");
-// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
-// }
-// WebSocketLog.sendInfo(builder.toString(), "du2");
-// });
+// log.info("确认最终送花意图");
+// setConfirmIntent();
+// outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText,
+// new StringBuilder("您要送").append(num).append("朵花是吗").toString());
+// setExpectSpeech(true);
// }
- } catch (Exception e) {
- log.warn("中控返回结果为空:"+e);
- data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
- }
- finally {
- if (requestList != null && requestList.size() > 1) {
- synchronized (requestList){
- requestList.notifyAll();
- }
- }
- CACHE_XIAODU_REQUEST.remove(userId);
- }
- }
-
- private String dealAudioUrl(String path) {
- return Constants.TTS_DIDI3_GET+path;
-// return "http://didi-gz5.jiaoyou365.com:9663/api/audio/get?path="+path;
- }
-
- private void dealNoScreenSendFlowerIntent(String userId, OverTimeDetail data) {
- if (getAccessToken() == null) {
- data.setResponse(buildErrorResponse("该功能需要登录"));
- return ;
- }
- String num = getSlot("sys.number");
- OutputSpeech outputSpeech;
- String confirmationStatus = getIntent().getConfirmationStatus().name();
- log.info("槽位确认状态:{}",confirmationStatus);
- if ("NONE".equals(confirmationStatus)) {
- if (num == null) {
- log.info("确认送花个数");
- ask("sys.number");
- outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请问您要送几朵花");
- setExpectSpeech(true);
- } else {
- log.info("确认最终送花意图");
- setConfirmIntent();
- outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText,
- new StringBuilder("您要送").append(num).append("朵花是吗").toString());
- setExpectSpeech(true);
- }
- data.setResponse(new Response(outputSpeech));
- } else if ("CONFIRMED".equals(confirmationStatus)) {
- log.info("确认");
- int unitPrice = Integer.parseInt(ScheduleService.FLOWER_UNIT_PRICE);
- String amount = String.valueOf(unitPrice*Integer.parseInt(num)/100.0);
- String orderId = new StringBuilder(userId).append(System.currentTimeMillis()).toString();
- String appUserId = getSessionAttribute("userId");
- if (appUserId == null) {
- appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken());
- if (appUserId == null) {
- log.error("送花时获取用户app_user_id失败");
- data.setResponse(buildErrorResponse("不好意思出了点问题,请再说一遍吧"));
- return;
- }
- }
- String botId = getSessionAttribute("botAcc");
- if (StringUtils.isNotBlank(botId)) {
- XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
- XiaoDuOrderTB response = repository.save(buildNoScreenBeforePayPojo(botId, appUserId, userId, unitPrice,
- Integer.parseInt(num), orderId));
-
- if (response != null && response.getId() != null) {
- String desc = new StringBuilder("感谢您赏赐给该作品的").append(num).append("朵鲜花").toString();
- String name = ScheduleService.PRODUCT_ID_DETAIL.get(botId).getName();
- if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
- .append("的").append(num).append("朵鲜花").toString();
- Charge charge = new Charge(amount, orderId, num+"朵鲜花", desc);
- charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
- addDirective(charge);
- data.setResponse(buildErrorResponse("请到小度APP上完成支付"));
- } else {
- log.error("订单没有插入到xioadu_order_tb");
- data.setResponse(buildErrorResponse(ERROR_SEND_FLOWER));
- }
- }else {
- log.error("无法获取到botID");
- data.setResponse(buildErrorResponse("只能在作品里才可以送花"));
- }
- } else {
- log.info("否定");
- data.setResponse(buildErrorResponse("好的,已为您终止"));
- }
- }
-
- private Play buildNoScreenPlayDirec(String audioUrl, AudioPlayerDirective.PlayBehaviorType type) {
- return new Play(type, audioUrl, 0);
- }
-
- /**
- *
- * @param idsToken 当前页面作品的id集合
- * @param overDetail
- * @return
- */
- private Response dealOpenNum(String idsToken, OverTimeDetail overDetail) {
- int collectNum = Integer.parseInt(getSlot("sys.number"));
- String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
- String botID = tokenList[collectNum-1];
- OnProductDetail detail = ScheduleService.PRODUCT_ID_DETAIL.get(botID);
- String productName = correctName(detail.getName());
- String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
- log.info("进入作品语句:{}", enterProductWord);
- QiWuResponse data = null;
- try {
- data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
- } catch (IOException e) {
- log.error("请求终端接口出错:", e.toString());
- }
- if (data == null) {
- return buildErrorResponse(SORRY_UNCATCH);
- }
- String text = data.getText();
-// String aside = DplbotServiceUtil.getAsideText(text);
-// text = text.substring(text.indexOf("】")+1);
-// log.info("旁白名字:{}",aside);
-// PlayDocument document = PlayUtils.getPlayDocument(productName, aside, ScheduleService.getAsideImgUrl(botID, aside),
-// data.getAudio(), text);
- Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
- PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern), DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botID);
-
- RenderDocument render = new RenderDocument(document);
- this.setSessionAttribute(PRE_COLLE, null);
- overDetail.getAttributes().put(PRE_COLLE, null);
- String trace = getSessionAttribute(BACK_TRACE);
- if (trace == null || trace.length() != 2) trace = "00";
- String backTrace = new StringBuilder(trace).append(detail.getBotAccount()).append(File.separator).toString();
- this.setSessionAttribute(BACK_TRACE, backTrace);
- overDetail.getAttributes().put(BACK_TRACE,backTrace);
- this.addDirective(render);
- overDetail.getDirectives().add(render);
- return new Response();
- }
-
- @Override
- protected Response onUserEvent(UserEvent userEvent) {
- try {
- //log.info("onUserEvent事件触发,token:{}, componentId:{}",userEvent.getToken(),userEvent.getPayload().getComponentId());
- if (getAccessToken() != null && getSessionAttribute("userId") == null) {
- String userId = DplbotServiceUtil.getUsUserId(getUserId(),getAccessToken());
- setSessionAttribute("userId", userId);
- }
- String componentId = userEvent.getPayload().getComponentId();
- String componentPrefix;
- if ("audio".equals(componentId)){
- setExpectSpeech(true);
- }
- else if (Constants.PRE_PRODUCT_IMG.equals((componentPrefix = componentId.substring(0, 5)))) {
- // 作品图片点击事件
- log.info("图片点击触发");
- String accessToken = getAccessToken();
- String userId = getUserId();
- String productName = componentId.substring(5);
-
- OnProductDetail productDetail = ScheduleService.PRODUCT_NAME_DETAIL.get(productName);
- if (productDetail == null && !productName.equals("清新传{/zhuan4/}")) {
- return buildErrorResponse("目前不支持该作品");
- }
- String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
-
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
- String dateString = formatter.format(productDetail.getCreateTime());
- String time = new StringBuilder(Constants.PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
- String author = new StringBuilder(Constants.PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
- StringBuilder labels = new StringBuilder(Constants.PRODUCT_INTRO.LABEL);
- for (String label: productDetail.getLabels()) {
- labels.append(Constants.PRODUCT_INTRO.SPACE).append(label);
- }
- String intro = productDetail.getIntro();
- String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
-
- // "start product" container button
- String flowers, flowerReward,collectText, collectUrl, collectComId;
- if (accessToken != null) {
- // flower container button
- Long flowerCount = DplbotServiceUtil.getUserSendFlowerNum(productDetail.getBotAccount(), userId, accessToken);
- flowers = USER_SEND_FLOWER+flowerCount;
- flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
-
- // collection container button
- boolean collec = DplbotServiceUtil.didUserCollecThisProduct(productDetail.getBotAccount(), userId,
- accessToken, getSessionAttribute("userId"));
- if (collec) {
- collectText = COLLECED;
- collectUrl = COLLECTED_IMG_URL;
- collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
- } else {
- collectText = UN_COLLEC;
- collectUrl = UN_COLLECTED_IMG_URL;
- collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
- }
- } else {
- flowers = FLOWE;
- flowerReward = FLOWER_LOAD;
-
- collectText = UN_COLLEC;
- collectUrl = UN_COLLECTED_IMG_URL;
- collectComId = FLOWER_LOAD;
- }
-
- ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), time, author, labels.toString(),
- intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
-
- RenderDocument renderDocument = new RenderDocument(document);
- this.addDirective(renderDocument);
- //this.addDirective(new PushStack());
- String trace = getSessionAttribute(BACK_TRACE);
- log.info("before trace------------:{}",trace);
- StringBuilder builder = new StringBuilder();
- if (trace == null || trace.length() < 2) {
- builder.append("00");
- } else if (trace.length()>2) {
- builder.append(trace, 0, 2);
- } else {
- builder.append(trace);
- }
-
- trace = builder.append(productDetail.getBotAccount()).toString();
- log.info("after trace------------:{}",trace);
- this.setSessionAttribute(BACK_TRACE, trace);
- return new Response();
- } else if (Constants.PRE_ENTER_PRODUCT.equals(componentPrefix)) {
- String productName = componentId.substring(5);
- String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
- log.info("进入作品语句:{}", enterProductWord);
- QiWuResponse data = null;
- try {
- data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
- } catch (IOException e) {
- log.error("请求终端接口出错:", e.toString());
- }
- if (data == null) {
- return buildErrorResponse(SORRY_UNCATCH);
- }
- String text = data.getText();
-// String aside = DplbotServiceUtil.getAsideText(text);
-// text = text.substring(text.indexOf("】")+1);
-// log.info("旁白名字:{}",aside);
-//
- String keng = productName;
- if (keng.equals("清新传")) keng = "清新传{/zhuan4/}";
- String botID = ScheduleService.getProductNameDetail().get(keng).getBotAccount();
-// PlayDocument document = PlayUtils.getPlayDocument(productName, aside, ScheduleService.getAsideImgUrl(botID, aside),
-// data.getAudio(), text);
- Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
- PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern), DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botID);
-
- RenderDocument render = new RenderDocument(document);
- this.setSessionAttribute(PRE_COLLE, null);
- String trace = getSessionAttribute(BACK_TRACE);
- if (trace == null || trace.length()<2) trace = "00";
- else if (trace.length()>2) trace = trace.substring(0,2);
- if (productName.equals("清新传")) productName = "清新传{/zhuan4/}";
- String botAccount = ScheduleService.PRODUCT_NAME_DETAIL.get(productName).getBotAccount();
- this.setSessionAttribute(BACK_TRACE, new StringBuilder(trace).append(botAccount).append(File.separator).toString());
- this.addDirective(render);
- } else if (FLOWE.equals(componentPrefix)) {
- if (FLOWER_LOAD.equals(componentId)) {
- return load();
- } else {
-// Buy buy = new Buy(FLOWER_PRODUCT_ID);
-// String token = new String(Base64.getEncoder().encode(componentId.substring(5).getBytes()), StandardCharsets.UTF_8);
-// buy.setToken(token);
-// addDirective(buy);
-// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, REWARD_FLOWER);
-// return new Response(outputSpeech);
- Charge charge = DplbotServiceUtil.sendOneFlowerByCharge(getUserId(), getSessionAttribute("userId"),
- getAccessToken(), getSessionAttribute("trace"));
- if (charge != null) {
- addDirective(charge);
- return buildErrorResponse("扫描屏幕上的二维码完成支付");
- }
- return new Response();
- }
- } else if ("loadingPage".equals(componentId)) {
- RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
- this.addDirective(new PushStack());
- this.addDirective(renderDocument);
- return new Response();
- } else if (PRE_COLLE.equals(componentPrefix)) {
- boolean isUnCollect = "Un".equals(componentId.substring(5,7));
- final String botId = componentId.substring(7);
- if (isUnCollect) {
- //取消收藏
- DplbotServiceUtil.userUnCollectTheBotInPool(getUserId(), botId, getAccessToken());
- changeIconIdTextAfterCollect(false, botId);
- } else {
- //收藏
- DplbotServiceUtil.userCollectTheBotInPool(getUserId(), botId, getAccessToken());
- changeIconIdTextAfterCollect(true, botId);
- }
- } else if (PRE_CATEGORY.equals(componentPrefix)) {
- String category = componentId.substring(5);
- // 分类推荐页面相同
- RecommandDocument document = RecommendUtil.getCategory(0, category);
- if (document == null) return buildErrorResponse("不好意思该分类还没有作品");
- RenderDocument render = new RenderDocument(document);
- this.addDirective(render);
- this.setSessionAttribute("category",category);
- this.setSessionAttribute("trace","05");
- } else if ("playButton".equals(componentId)) {
- return buildErrorResponse("您可以直接对我说我要送花或者我要收藏或取消收藏");
- } else if ("lunchCollect".equals(componentId)) {
- return dealOpenCollectClick();
- } else if ("lunchHistory".equals(componentId)) {
- return dealHistoryClick();
- }
-// else if ("funnyChange".equals(componentId)) {
-// ExecuteCommands executeCommands = new ExecuteCommands();
-// AutoPageCommand page = new AutoPageCommand();
-// page.setComponentId("funnyPage");
-// page.setDurationInMillisecond(2000);
-// executeCommands.addCommand(page);
-// this.addDirective(executeCommands);
-// }
- } catch (Exception e) {
- log.error("onUserEvent error:{}", ExceptionUtils.getStackTrace(e));
- }
- return new Response();
- }
-
- @Override
- protected Response onSessionEnded(SessionEndedRequest sessionEndedRequest) {
- switch (sessionEndedRequest.getReason()) {
- case ERROR: dealWithError(sessionEndedRequest); break;
- case USER_INITIATED: log.info(EndMsg.USER_SAY_CANCEL); break;
- case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break;
- }
- if (getRequest().getContext().getScreen() == null) {
- String userId = customUserId();
-// LAST_OUTTIME_MARK.remove(userId);
-// LAST_OUTTIME_RESULT.remove(userId);
-// USERID_AUDIO_PATH.remove(userId);
- String byeWord = EndMsg.END_BYE_Adult;
- switch (type) {
- case 2: byeWord = EndMsg.END_BYE_NOVEL;break;
- case 1: byeWord = EndMsg.END_BYE_STORY;break;
- case 3: byeWord = EndMsg.END_BYE_CHILD;break;
- case 5: byeWord = EndMsg.END_BYE_JIAOYOU;break;
- }
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
- RequestTerminal.backRequest(userId, type);
-// try {
-// if (DU_DEVICE_ID.equals(deviceId)) {
-// RequestTerminal.backRequest(DU_DEVICE_ID, type);
+// data.setResponse(new Response(outputSpeech));
+// } else if ("CONFIRMED".equals(confirmationStatus)) {
+// log.info("确认");
+// int unitPrice = Integer.parseInt(ScheduleService.FLOWER_UNIT_PRICE);
+// String amount = String.valueOf(unitPrice*Integer.parseInt(num)/100.0);
+// String orderId = new StringBuilder(userId).append(System.currentTimeMillis()).toString();
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken());
+// if (appUserId == null) {
+// log.error("送花时获取用户app_user_id失败");
+// data.setResponse(buildErrorResponse("不好意思出了点问题,请再说一遍吧"));
+// return;
+// }
+// }
+// String botId = getSessionAttribute("botAcc");
+// if (StringUtils.isNotBlank(botId)) {
+// XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
+// XiaoDuOrderTB response = repository.save(buildNoScreenBeforePayPojo(botId, appUserId, userId, unitPrice,
+// Integer.parseInt(num), orderId));
+//
+// if (response != null && response.getId() != null) {
+// String desc = new StringBuilder("感谢您赏赐给该作品的").append(num).append("朵鲜花").toString();
+// String name = ScheduleService.PRODUCT_ID_DETAIL.get(botId).getName();
+// if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
+// .append("的").append(num).append("朵鲜花").toString();
+// Charge charge = new Charge(amount, orderId, num+"朵鲜花", desc);
+// charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
+// addDirective(charge);
+// data.setResponse(buildErrorResponse("请到小度APP上完成支付"));
// } else {
-// RequestTerminal.backRequestDU2(deviceId, type);
+// log.error("订单没有插入到xioadu_order_tb");
+// data.setResponse(buildErrorResponse(ERROR_SEND_FLOWER));
// }
-// } catch (Exception e) {
-// log.warn("用户退出向中控发出退出指令出错");
+// }else {
+// log.error("无法获取到botID");
+// data.setResponse(buildErrorResponse("只能在作品里才可以送花"));
// }
- return new Response(outputSpeech);
- }
- DplbotServiceUtil.writeTheUserHistoryInData(getUserId());
- LAST_OUTTIME_RESULT.remove(getUserId());
- return new Response();
- }
-
- private void dealWithError(SessionEndedRequest request) {
- switch (request.getError().getType()) {
- case INTERNAL_ERROR: log.info(ErrorMsg.INTERNAL_ERROR); break;
- case INVALID_RESPONSE: log.info(ErrorMsg.INVALID_RESPONSE); break;
- case DEVICE_COMMUNICATION_ERROR: log.info(ErrorMsg.DEVICE_COMMUNICATION_ERROR); break;
- }
- log.info("错误信息 : "+ request.getError().getMessage());
- }
-
- private Response dealHistoryClick() {
- CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(), 0);
- if (document == null) return buildErrorResponse("不好意思,您太久没玩记录被清空了");
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- setSessionAttribute(PRE_COLLE,document.getIdToken());
- setSessionAttribute("recommand", null);
- setSessionAttribute("comCnt", null);
- setSessionAttribute(BACK_TRACE, "02");
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开历史记录");
- return new Response(outputSpeech);
- }
-
- private Response dealOpenCollectClick() {
- if (getAccessToken() == null) {
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
- return new Response(outputSpeech);
- } else {
- String appUserId = getSessionAttribute("userId");
- if (appUserId == null) {
- appUserId = DplbotServiceUtil.getUsUserId(getUserId(), getAccessToken());
- if (appUserId == null) {
- return new Response();
- }
- }
- CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(getUserId(), getAccessToken(), appUserId, 0);
- if (document != null) {
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- setSessionAttribute("comCnt", null);
- setSessionAttribute(PRE_COLLE,document.getIdToken());
- setSessionAttribute(BACK_TRACE, "01");
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开收藏夹");
- return new Response(outputSpeech);
- }
- }
- return new Response();
- }
-
+// } else {
+// log.info("否定");
+// data.setResponse(buildErrorResponse("好的,已为您终止"));
+// }
+// }
+//
+// private Play buildNoScreenPlayDirec(String audioUrl, AudioPlayerDirective.PlayBehaviorType type) {
+// return new Play(type, audioUrl, 0);
+// }
+//
+// /**
+// *
+// * @param idsToken 当前页面作品的id集合
+// * @param overDetail
+// * @return
+// */
+// private Response dealOpenNum(String idsToken, OverTimeDetail overDetail) {
+// int collectNum = Integer.parseInt(getSlot("sys.number"));
+// String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
+// String botID = tokenList[collectNum-1];
+// OnProductDetail detail = ScheduleService.PRODUCT_ID_DETAIL.get(botID);
+// String productName = correctName(detail.getName());
+// String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
+// log.info("进入作品语句:{}", enterProductWord);
+// QiWuResponse data = null;
+// try {
+// data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
+// } catch (IOException e) {
+// log.error("请求终端接口出错:", e.toString());
+// }
+// if (data == null) {
+// return buildErrorResponse(SORRY_UNCATCH);
+// }
+// String text = data.getText();
+//// String aside = DplbotServiceUtil.getAsideText(text);
+//// text = text.substring(text.indexOf("】")+1);
+//// log.info("旁白名字:{}",aside);
+//// PlayDocument document = PlayUtils.getPlayDocument(productName, aside, ScheduleService.getAsideImgUrl(botID, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern), DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botID);
+//
+// RenderDocument render = new RenderDocument(document);
+// this.setSessionAttribute(PRE_COLLE, null);
+// overDetail.getAttributes().put(PRE_COLLE, null);
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace == null || trace.length() != 2) trace = "00";
+// String backTrace = new StringBuilder(trace).append(detail.getBotAccount()).append(File.separator).toString();
+// this.setSessionAttribute(BACK_TRACE, backTrace);
+// overDetail.getAttributes().put(BACK_TRACE,backTrace);
+// this.addDirective(render);
+// overDetail.getDirectives().add(render);
+// return new Response();
+// }
+//
// @Override
-// protected Response onBuyEvent(BuyEvent buyEvent) {
-// com.baidu.dueros.data.request.buy.event.JYTUserResponse payload = buyEvent.getPayload();
-// String result = payload.getPurchaseResult().getPurchaseResult();
-// log.info("此次支付结果:"+result+";msg: "+payload.getMessage());
-// if (result.equals("SUCCESS")) {
-// log.info("支付成功");
-// POOL.submit(new SendFlowerThread(buyEvent));
-// POOL.submit(new SendFlowerBuyToXiaoduTB(buyEvent));
-// return buildErrorResponse("感谢大人赏的花");
-// }
-// return buildErrorResponse("哎呀,没有支付成功");
+// protected Response onUserEvent(UserEvent userEvent) {
+// try {
+// //log.info("onUserEvent事件触发,token:{}, componentId:{}",userEvent.getToken(),userEvent.getPayload().getComponentId());
+// if (getAccessToken() != null && getSessionAttribute("userId") == null) {
+// String userId = DplbotServiceUtil.getUsUserId(getUserId(),getAccessToken());
+// setSessionAttribute("userId", userId);
+// }
+// String componentId = userEvent.getPayload().getComponentId();
+// String componentPrefix;
+// if ("audio".equals(componentId)){
+// setExpectSpeech(true);
+// }
+// else if (Constants.PRE_PRODUCT_IMG.equals((componentPrefix = componentId.substring(0, 5)))) {
+// // 作品图片点击事件
+// log.info("图片点击触发");
+// String accessToken = getAccessToken();
+// String userId = getUserId();
+// String productName = componentId.substring(5);
+//
+// OnProductDetail productDetail = ScheduleService.PRODUCT_NAME_DETAIL.get(productName);
+// if (productDetail == null && !productName.equals("清新传{/zhuan4/}")) {
+// return buildErrorResponse("目前不支持该作品");
+// }
+// String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
+//
+// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+// String dateString = formatter.format(productDetail.getCreateTime());
+// String time = new StringBuilder(Constants.PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
+// String author = new StringBuilder(Constants.PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
+// StringBuilder labels = new StringBuilder(Constants.PRODUCT_INTRO.LABEL);
+// for (String label: productDetail.getLabels()) {
+// labels.append(Constants.PRODUCT_INTRO.SPACE).append(label);
+// }
+// String intro = productDetail.getIntro();
+// String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
+//
+// // "start product" container button
+// String flowers, flowerReward,collectText, collectUrl, collectComId;
+// if (accessToken != null) {
+// // flower container button
+// Long flowerCount = DplbotServiceUtil.getUserSendFlowerNum(productDetail.getBotAccount(), userId, accessToken);
+// flowers = USER_SEND_FLOWER+flowerCount;
+// flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
+//
+// // collection container button
+// boolean collec = DplbotServiceUtil.didUserCollecThisProduct(productDetail.getBotAccount(), userId,
+// accessToken, getSessionAttribute("userId"));
+// if (collec) {
+// collectText = COLLECED;
+// collectUrl = COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// } else {
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// }
+// } else {
+// flowers = FLOWE;
+// flowerReward = FLOWER_LOAD;
+//
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = FLOWER_LOAD;
+// }
+//
+// ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), time, author, labels.toString(),
+// intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
+//
+// RenderDocument renderDocument = new RenderDocument(document);
+// this.addDirective(renderDocument);
+// //this.addDirective(new PushStack());
+// String trace = getSessionAttribute(BACK_TRACE);
+// log.info("before trace------------:{}",trace);
+// StringBuilder builder = new StringBuilder();
+// if (trace == null || trace.length() < 2) {
+// builder.append("00");
+// } else if (trace.length()>2) {
+// builder.append(trace, 0, 2);
+// } else {
+// builder.append(trace);
+// }
+//
+// trace = builder.append(productDetail.getBotAccount()).toString();
+// log.info("after trace------------:{}",trace);
+// this.setSessionAttribute(BACK_TRACE, trace);
+// return new Response();
+// } else if (Constants.PRE_ENTER_PRODUCT.equals(componentPrefix)) {
+// String productName = componentId.substring(5);
+// String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
+// log.info("进入作品语句:{}", enterProductWord);
+// QiWuResponse data = null;
+// try {
+// data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
+// } catch (IOException e) {
+// log.error("请求终端接口出错:", e.toString());
+// }
+// if (data == null) {
+// return buildErrorResponse(SORRY_UNCATCH);
+// }
+// String text = data.getText();
+//// String aside = DplbotServiceUtil.getAsideText(text);
+//// text = text.substring(text.indexOf("】")+1);
+//// log.info("旁白名字:{}",aside);
+////
+// String keng = productName;
+// if (keng.equals("清新传")) keng = "清新传{/zhuan4/}";
+// String botID = ScheduleService.getProductNameDetail().get(keng).getBotAccount();
+//// PlayDocument document = PlayUtils.getPlayDocument(productName, aside, ScheduleService.getAsideImgUrl(botID, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern), DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botID);
+//
+// RenderDocument render = new RenderDocument(document);
+// this.setSessionAttribute(PRE_COLLE, null);
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace == null || trace.length()<2) trace = "00";
+// else if (trace.length()>2) trace = trace.substring(0,2);
+// if (productName.equals("清新传")) productName = "清新传{/zhuan4/}";
+// String botAccount = ScheduleService.PRODUCT_NAME_DETAIL.get(productName).getBotAccount();
+// this.setSessionAttribute(BACK_TRACE, new StringBuilder(trace).append(botAccount).append(File.separator).toString());
+// this.addDirective(render);
+// } else if (FLOWE.equals(componentPrefix)) {
+// if (FLOWER_LOAD.equals(componentId)) {
+// return load();
+// } else {
+//// Buy buy = new Buy(FLOWER_PRODUCT_ID);
+//// String token = new String(Base64.getEncoder().encode(componentId.substring(5).getBytes()), StandardCharsets.UTF_8);
+//// buy.setToken(token);
+//// addDirective(buy);
+//// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, REWARD_FLOWER);
+//// return new Response(outputSpeech);
+// Charge charge = DplbotServiceUtil.sendOneFlowerByCharge(getUserId(), getSessionAttribute("userId"),
+// getAccessToken(), getSessionAttribute("trace"));
+// if (charge != null) {
+// addDirective(charge);
+// return buildErrorResponse("扫描屏幕上的二维码完成支付");
+// }
+// return new Response();
+// }
+// } else if ("loadingPage".equals(componentId)) {
+// RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
+// this.addDirective(new PushStack());
+// this.addDirective(renderDocument);
+// return new Response();
+// } else if (PRE_COLLE.equals(componentPrefix)) {
+// boolean isUnCollect = "Un".equals(componentId.substring(5,7));
+// final String botId = componentId.substring(7);
+// if (isUnCollect) {
+// //取消收藏
+// DplbotServiceUtil.userUnCollectTheBotInPool(getUserId(), botId, getAccessToken());
+// changeIconIdTextAfterCollect(false, botId);
+// } else {
+// //收藏
+// DplbotServiceUtil.userCollectTheBotInPool(getUserId(), botId, getAccessToken());
+// changeIconIdTextAfterCollect(true, botId);
+// }
+// } else if (PRE_CATEGORY.equals(componentPrefix)) {
+// String category = componentId.substring(5);
+// // 分类推荐页面相同
+// RecommandDocument document = RecommendUtil.getCategory(0, category);
+// if (document == null) return buildErrorResponse("不好意思该分类还没有作品");
+// RenderDocument render = new RenderDocument(document);
+// this.addDirective(render);
+// this.setSessionAttribute("category",category);
+// this.setSessionAttribute("trace","05");
+// } else if ("playButton".equals(componentId)) {
+// return buildErrorResponse("您可以直接对我说我要送花或者我要收藏或取消收藏");
+// } else if ("lunchCollect".equals(componentId)) {
+// return dealOpenCollectClick();
+// } else if ("lunchHistory".equals(componentId)) {
+// return dealHistoryClick();
+// }
+//// else if ("funnyChange".equals(componentId)) {
+//// ExecuteCommands executeCommands = new ExecuteCommands();
+//// AutoPageCommand page = new AutoPageCommand();
+//// page.setComponentId("funnyPage");
+//// page.setDurationInMillisecond(2000);
+//// executeCommands.addCommand(page);
+//// this.addDirective(executeCommands);
+//// }
+// } catch (Exception e) {
+// log.error("onUserEvent error:{}", ExceptionUtils.getStackTrace(e));
+// }
+// return new Response();
// }
-
-
- private ExecuteCommands changeIconIdTextAfterCollect(boolean collect, String botId) {
- ExecuteCommands executeCommands = new ExecuteCommands();
- UpdateComponentCommand update = new UpdateComponentCommand();
- String srcValue;
- String textValue;
- String idValue;
- String previousClickId;
- String unCollectId = new StringBuilder(UN_COLLEC_ID).append(botId).toString();
- String collectId = new StringBuilder(COLLEC_ID).append(botId).toString();
- if (collect) {
- srcValue = COLLECTED_IMG_URL;
- textValue = COLLECED;
- idValue = unCollectId;
- previousClickId = collectId;
- } else {
- srcValue = UN_COLLECTED_IMG_URL;
- textValue = UN_COLLEC;
- idValue = collectId;
- previousClickId = unCollectId;
- }
-
- update.setComponentId(previousClickId);
- update.setDocument(TempleUtils.getCollectIcon(idValue, srcValue, textValue));
- executeCommands.addCommand(update);
- this.addDirective(executeCommands);
- return executeCommands;
- }
-
- private ExecuteCommands changeCollectIconInPlay(boolean collect) {
- ExecuteCommands executeCommands = new ExecuteCommands();
- SetStateCommand setState = new SetStateCommand();
- setState.setComponentId("playCollect");
- setState.setState("src");
- if (collect) {
- setState.setValue(COLLECTED_IMG_URL);
- }else {
- setState.setValue(UN_COLLECTED_IMG_URL);
- }
- executeCommands.addCommand(setState);
- return executeCommands;
- }
-
- private Response load() {
- Card card = new LinkAccountCard();
- Response response = buildErrorResponse(LOAD_INTRO);
- response.setCard(card);
- return response;
- }
-
- private Integer getUserSendFlowerNum(String productId, String accessToken) {
- HashMap params = new HashMap<>();
- params.put("module", "works");
- params.put("aipioneerUsername", productId);
- HashMap headers = new HashMap<>();
- headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
- headers.put("Authorization", new StringBuilder(BEARER).append(accessToken).toString());
- CodeMsgData response;
- try {
- String flowerRes = OkHttp3Utils.doGet(FLOWER_INTERFACE, params, headers);
- response = JSON.parseObject(flowerRes, CodeMsgData.class);
- } catch (IOException e) {
- log.error("请求用户送花数出错");
- return null;
- }
- log.info("调用获取用户送花数接口结果:{}", response);
- if (response == null || response.getCode() != 1) return null;
- return response.getData().getCount();
- }
-
-
- private List getUserProductList(String accessToken) {
- HashMap params = new HashMap<>();
- params.put("module", "works");
- HashMap headers = new HashMap<>();
- headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
- headers.put("Authorization", new StringBuilder(BEARER).append(accessToken).toString());
- UserCollecResult result;
- try {
- String resStr = OkHttp3Utils.doGet(Constants.XIAOWU_API.USER_CLOOEC_LIST, params, headers);
- result = JSON.parseObject(resStr, UserCollecResult.class);
- } catch (Exception e) {
- log.error("调用获取用户收藏作品列表接口出错:{}", e.toString());
- return null;
- }
- if (result.getCode() == 1) return result.getData();
- else {
- log.error("获取用户收藏作品列表出错,错误码:{}, 错误信息:{}", result.getCode(), result.getMsg());
- return null;
- }
- }
-
- private static String correctName(String name) {
- int brace = name.indexOf("{");
- if (brace != -1) name = name.substring(0, brace);
- return name;
- }
-
- @Override
- protected Response onLinkAccountSucceededEvent(LinkAccountSucceededEvent linkAccountSucceededEvent) {
- log.info("登录成功返回信息:{}",linkAccountSucceededEvent);
- String accessToken = getAccessToken();
- String jytUserId;
- if (getRequest().getContext().getScreen() != null) {
- log.info("检测到有屏登录");
- String userId = getUserId();
- DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, userId);
- jytUserId = DplbotServiceUtil.getUsUserId(userId, accessToken);
- if (jytUserId != null)
- log.warn("登录后获取用户的app id 失败");
- } else {
- jytUserId = DplbotServiceUtil.getUserIdByToken(accessToken);
- if (jytUserId != null)
- log.warn("登录后获取用户的app id 失败");
- }
- setSessionAttribute("userId", jytUserId);
- return buildErrorResponse("您已登录成功");
- }
-
+//
// @Override
-// protected Response onDefaultEvent() {
-// log.info("未拦截的事件类型:"+getEventType(this.getStrRequest()));
-// this.waitAnswer();
+// protected Response onSessionEnded(SessionEndedRequest sessionEndedRequest) {
+// switch (sessionEndedRequest.getReason()) {
+// case ERROR: dealWithError(sessionEndedRequest); break;
+// case USER_INITIATED: log.info(EndMsg.USER_SAY_CANCEL); break;
+// case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break;
+// }
+// if (getRequest().getContext().getScreen() == null) {
+// String userId = customUserId();
+//// LAST_OUTTIME_MARK.remove(userId);
+//// LAST_OUTTIME_RESULT.remove(userId);
+//// USERID_AUDIO_PATH.remove(userId);
+// String byeWord = EndMsg.END_BYE_Adult;
+// switch (type) {
+// case 2: byeWord = EndMsg.END_BYE_NOVEL;break;
+// case 1: byeWord = EndMsg.END_BYE_STORY;break;
+// case 3: byeWord = EndMsg.END_BYE_CHILD;break;
+// case 5: byeWord = EndMsg.END_BYE_JIAOYOU;break;
+// }
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
+// RequestTerminal.backRequest(userId, type);
+//// try {
+//// if (DU_DEVICE_ID.equals(deviceId)) {
+//// RequestTerminal.backRequest(DU_DEVICE_ID, type);
+//// } else {
+//// RequestTerminal.backRequestDU2(deviceId, type);
+//// }
+//// } catch (Exception e) {
+//// log.warn("用户退出向中控发出退出指令出错");
+//// }
+// return new Response(outputSpeech);
+// }
+// DplbotServiceUtil.writeTheUserHistoryInData(getUserId());
+// LAST_OUTTIME_RESULT.remove(getUserId());
// return new Response();
// }
-
- private String getEventType(String requestStr) {
- int typeIndex = requestStr.lastIndexOf("type");
- int comma = requestStr.indexOf(',', typeIndex);
- return requestStr.substring(typeIndex, comma);
- }
-
- private Response buildErrorResponse(String errorMsg) {
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
- return new Response(outputSpeech);
- }
-
- private Response buildLogOutResponse(String errorMsg) {
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
- endDialog();
- return new Response(outputSpeech);
- }
-
- private Response buildNoScreenListCardResponse(String content, String botAccount) {
- Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
- List actors = DplbotServiceUtil.seperateActor(content, pattern);
- String[] actorWord = DplbotServiceUtil.seperateActorWord(content, pattern);
- int i = 0;
- ListCard listCard = new ListCard();
- for (String actor: actors) {
- StandardCardInfo cardInfo = new StandardCardInfo(actor, actorWord[i++].replaceAll("
","\n"));
- cardInfo.setImage(ScheduleService.getAsideImgUrl(botAccount, actor));
- listCard.getList().add(cardInfo);
- }
-// content = buildText(content);
- return new Response(null, listCard, WAIT_WORD);
- }
-
- private Response buildNoScreenTextCardREsponse(String content) {
- content = buildText(content);
- TextCard textCard = new TextCard(content);
- return new Response(null, textCard, WAIT_WORD);
- }
-
- private String buildText(String text) {
- Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
- StringBuilder builder = new StringBuilder();
- List actors = DplbotServiceUtil.seperateActor(text, pattern);
- String[] word = DplbotServiceUtil.seperateActorWord(text, pattern);
- int i = 0;
- for (String actor: actors) {
- builder.append(actor).append(":").append(word[i].replaceAll("
", "\n")).append("\n");
- i++;
- }
- if (builder.length() == 0) builder.append(text);
- return builder.toString();
- }
-
- private void backToBotIntro(String botAccount, OverTimeDetail detail) {
- OnProductDetail productDetail = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount);
- // product picture
- String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
-
- // product name
- String productName = correctName(productDetail.getName());
-
- // product create time
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
- String dateString = formatter.format(productDetail.getCreateTime());
- String createTime = new StringBuilder(Constants.PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
-
- // product author
- String author = new StringBuilder(Constants.PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
-
- // product labels
- StringBuilder labels = new StringBuilder(Constants.PRODUCT_INTRO.LABEL);
- for (String label: productDetail.getLabels()) {
- labels.append(Constants.PRODUCT_INTRO.SPACE).append(label);
- }
-
- // product introduction
- String intro = productDetail.getIntro();
-
- // "start product" container button
- String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
-
- String accessToken = getAccessToken();
- String flowers, flowerReward,collectText, collectUrl, collectComId;
- if (accessToken != null) {
- // flower container button
- Long count = DplbotServiceUtil.getUserSendFlowerNum(botAccount, getUserId(), accessToken);
- flowers = USER_SEND_FLOWER+count;
- flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
-
- // collection container button
- boolean collec = DplbotServiceUtil.doesUserCollectThisBot(productDetail.getBotAccount(), accessToken, getUserId());
- if (collec) {
- collectText = COLLECED;
- collectUrl = COLLECTED_IMG_URL;
- collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
- } else {
- collectText = UN_COLLEC;
- collectUrl = UN_COLLECTED_IMG_URL;
- collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
- }
- } else {
- flowers = FLOWER;
- flowerReward = FLOWER_LOAD;
-
- collectText = UN_COLLEC;
- collectUrl = UN_COLLECTED_IMG_URL;
- collectComId = FLOWER_LOAD; // 提示登录
- }
-
- ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), createTime, author, labels.toString(),
- intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
- RenderDocument renderDocument = new RenderDocument(document);
- this.addDirective(renderDocument);
- detail.getDirectives().add(renderDocument);
- String trace = getSessionAttribute(BACK_TRACE);
- trace = trace.substring(0, trace.length()-1);
- this.setSessionAttribute(BACK_TRACE, trace);
- detail.getAttributes().put(BACK_TRACE,trace);
- }
-
- // 异步发送“退出”给终端
- private void sendCancellToTerminate(String userId){
- RequestTerminal.backRequest(userId, type);
- }
-
- class Task implements Runnable{
- IntentRequest intentRequest;
-
- Task(IntentRequest intentRequest) {
- this.intentRequest = intentRequest;
- }
-
- @Override
- public void run() {
- final String userId = getUserId();
- String intentName = getIntent().getName();
- OverTimeDetail detail = new OverTimeDetail();
- log.info("Intent name:{}",intentName);
- if ("ai.dueros.common.default_intent".equals(intentName) || "funny".equals(intentName)) {
- dealDefaultIntent(intentRequest, detail, userId, intentName, null);
- return;
- }
- switch (intentName) {
- case "load" : dealLoadIntent(detail, userId);break;
- case "back" : dealBackIntent(detail, userId);break;
- case "openCollect" : dealOpenCollectIntent(detail, userId);break;
- case "openNum" : dealOpenNumIntent(detail, userId);break;
- case "lastPage" : dealLastPageIntent(detail, userId, intentRequest);break;
- case "nextPage" : dealNextPageIntent(detail, userId, intentRequest);break;
- case "history" : dealHistoryIntent(detail, userId);break;
- case "recommand" : dealRecommandIntent(detail, userId);break;
- case "ranking" : dealRankIntent(detail, userId);break;
- case "collect" :
- case "unCollect" : dealCollectOrUnCollectIntent(detail, userId, intentName);break;
- case "sendFlower" : dealSendFlowerIntent(detail, userId);break;
- case "jump" : dealJumpIntent(detail, userId);break;
- case "start" : dealStartIntent(detail, userId, intentRequest, intentName);break;
- }
- }
- }
-
- private void dealJumpIntent(OverTimeDetail detail, String userId) {
- String trace = getSessionAttribute("trace");
- if (trace == null || trace.length() < 2) {
- detail.setResponse(buildErrorResponse("小悟跳不动了"));
- LAST_OUTTIME_RESULT.put(userId,detail);
- return;
- }
- String num = getSlot("sys.number");
- if (num == null) {
- detail.setResponse(buildErrorResponse("我没听清您要跳转的页面,请再说一遍"));
- LAST_OUTTIME_RESULT.put(userId,detail);
- return;
- }
- int index = Integer.parseInt(num);
- char pageSign = trace.charAt(1);
- switch (pageSign) {
- case '1' : {
- dealCollectHistoryJump(index, true, detail, userId);
- break;
- }
- case '2' : {
- dealCollectHistoryJump(index, false, detail, userId);
- break;
- }
- case '4' : {
- dealRankJump(index, detail);
- break;
- }
- case '5' : {
- dealCategoryJump(index, detail);
- break;
- }
- default : {
- detail.setResponse(buildErrorResponse("该页面不支持跳转"));
- }
- }
- LAST_OUTTIME_RESULT.put(userId,detail);
- }
-
- private void dealRankJump(int index, OverTimeDetail detail) {
- index = index == 0 ? index : index-1;
- RecommandDocument document;
- if (index == 0) document = RecommendUtil.getRankDocumentFirstPage();
- else document = RecommendUtil.getRankOtherPageDocument(index);
- if (document == null) {
- detail.setResponse(buildErrorResponse("超出了范围,无法跳转"));
- return;
- }
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String cmt = String.valueOf(index+1);
- setSessionAttribute("comCnt",cmt);
- setSessionAttribute("recommand", document.getRecommendIdList());
- detail.getAttributes().put("recommand", document.getRecommendIdList());
- detail.getAttributes().put("comCnt", cmt);
- }
-
- private void dealCategoryJump(int index, OverTimeDetail detail) {
- index = index == 0 ? index : index-1;
- String category = getSessionAttribute("category");
- if (category == null) {
- detail.setResponse(buildErrorResponse("无法跳转,请说返回然后重新进入当前分类"));
- return;
- }
- RecommandDocument document = RecommendUtil.getCategory(index, category);
- if (document == null) {
- detail.setResponse(buildErrorResponse("超出了范围,无法跳转"));
- return;
- }
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String cmt = String.valueOf(index+1);
- setSessionAttribute("comCnt",cmt);
- detail.getAttributes().put("comCnt", cmt);
- }
-
- private void dealCollectHistoryJump(int index, boolean collect, OverTimeDetail detail, String userId) {
- index = index == 0 ? index : index-1;
- int start = index*CO_HI_PAGE_SIZE;
- CollectHistoryDocument document;
- if (collect) document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(), getSessionAttribute("userId"), start);
- else document = DplbotServiceUtil.getHistory(userId, getAccessToken(), start);
- if (document != null) {
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String cmt = String.valueOf(index+1);
- setSessionAttribute("comCnt",cmt);
- setSessionAttribute(PRE_COLLE, document.getIdToken());
- detail.getAttributes().put(PRE_COLLE, document.getIdToken());
- detail.getAttributes().put("comCnt", cmt);
- } else {
- detail.setResponse(buildErrorResponse("超出了范围无法跳到那一页"));
- }
- }
-
- private void dealStartIntent(OverTimeDetail detail, String userId, IntentRequest intentRequest, String intentName) {
- String trace = getSessionAttribute("trace");
- if (trace != null && trace.length() > 2 && !StringUtils.endsWith(trace,File.separator)) {
- String botId = trace.substring(2);
- String enterName = new StringBuilder("我要玩")
- .append(ScheduleService.getProductIdDetail().get(botId).getName()).toString();
- dealDefaultIntent(intentRequest, detail, userId, intentName, enterName);
- }else {
- dealDefaultIntent(intentRequest, detail, userId, intentName, null);
- }
- }
-
- private void dealSendFlowerIntent(OverTimeDetail detail, String userId) {
- if (getAccessToken() == null) {
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
- detail.setResponse(new Response(outputSpeech));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- String num = getSlot("sys.number");
- OutputSpeech outputSpeech;
- String confirmationStatus = getIntent().getConfirmationStatus().name();
- log.info("槽位确认状态:{}",confirmationStatus);
- if ("NONE".equals(confirmationStatus)) {
- if (num == null) {
- log.info("确认送花个数");
- ask("sys.number");
- outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请问您要送几朵花");
- setExpectSpeech(true);
- } else {
- log.info("确认最终送花意图");
- setConfirmIntent();
- outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText,
- new StringBuilder("您要送").append(num).append("朵花是吗").toString());
- setExpectSpeech(true);
- }
- detail.getResponse().setOutputSpeech(outputSpeech);
- LAST_OUTTIME_RESULT.put(userId, detail);
- } else if ("CONFIRMED".equals(confirmationStatus)) {
- log.info("确认");
- int unitPrice = Integer.parseInt(ScheduleService.FLOWER_UNIT_PRICE);
- String amount = String.valueOf(unitPrice*Integer.parseInt(num)/100.0);
- String orderId = new StringBuilder(userId).append(System.currentTimeMillis()).toString();
- String appUserId = getSessionAttribute("userId");
- if (appUserId == null) {
- appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken());
- if (appUserId == null) {
- log.error("送花时获取用户app_user_id失败");
- detail.setResponse(buildErrorResponse("不好意思出了点问题,请再说一遍吧"));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- }
- String botId;
- String trace = getSessionAttribute(BACK_TRACE);
- if (trace != null && trace.length() > 2) {
- if (StringUtils.endsWith(trace, File.separator)) {
- botId = trace.substring(2, trace.length()-1);
- }else {
- botId = trace.substring(2);
- }
- XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
- XiaoDuOrderTB response = repository.save(buildBeforePayPojo(botId, appUserId, userId, unitPrice,
- Integer.parseInt(num), orderId));
-
- if (response != null && response.getId() != null) {
- String desc = new StringBuilder("感谢您赏赐给该作品的").append(num).append("朵鲜花").toString();
- String name = ScheduleService.PRODUCT_ID_DETAIL.get(botId).getName();
- if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
- .append("的").append(num).append("朵鲜花").toString();
- Charge charge = new Charge(amount, orderId, "鲜花", desc);
- charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
- addDirective(charge);
- detail.getDirectives().add(charge);
- detail.setResponse(buildErrorResponse("请扫描二维码完成支付"));
- } else {
- log.error("订单没有插入到xioadu_order_tb");
- detail.setResponse(buildErrorResponse(ERROR_SEND_FLOWER));
- }
- }else {
- log.error("无法获取到botID");
- detail.setResponse(buildErrorResponse(ERROR_SEND_FLOWER));
- }
- LAST_OUTTIME_RESULT.put(userId, detail);
- } else {
- log.info("否定");
- detail.setResponse(buildErrorResponse("好的,已为您终止"));
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
- }
-
- private void dealCollectOrUnCollectIntent(OverTimeDetail detail, String userId, String intentName) {
- if (getAccessToken() == null) {
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
- detail.setResponse(new Response(outputSpeech));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- boolean collect = "collect".equals(intentName);
- boolean inProductInfo = false;
- boolean inPlayInfo = false;
- String botAccount;
- String trace = getSessionAttribute("trace");
- if (trace == null || trace.length() <= 2) {
- botAccount = getSessionAttribute("botAcc");
- if(botAccount == null) {
- String word = COLLECT_FAIL;
- if (!collect) word = UN_COLLECT_FAIL;
- detail.setResponse(buildErrorResponse(word));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- } else {
- if (StringUtils.endsWith(trace, File.separator)) {
- botAccount = trace.substring(2, trace.length()-1);
- inPlayInfo = true;
- }
- else {
- inProductInfo = true;
- botAccount = trace.substring(2);
- }
- }
- try {
- boolean alreadyCollected = DplbotServiceUtil.doesUserCollectThisBot(botAccount, getAccessToken(), userId);
- String appUserId = getSessionAttribute("userId");
- if (appUserId == null) appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken());
- if (appUserId != null) {
- if (alreadyCollected) {
- if (collect) detail.setResponse(buildErrorResponse("您之前就已经收藏过该作品啦,看来你真的很喜欢它"));
- else {
- DplbotServiceUtil.userUnCollectTheBotInPool(userId, botAccount, getAccessToken());
- String botName = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
- if (inProductInfo) {
- ExecuteCommands commands = changeIconIdTextAfterCollect(false, botAccount);
- addDirective(commands);
- detail.getDirectives().add(commands);
- } else if (inPlayInfo) {
- changeCollectIconInPlay(false);
- }
- if (botName == null) detail.setResponse(buildErrorResponse(UN_COLLECT_BOT_WORD));
- else detail.setResponse(buildErrorResponse(String.format(UN_COLLECT_BOT_WORD_MG,botName)));
- }
- } else {
- if (collect) {
- DplbotServiceUtil.userCollectTheBotInPool(userId, botAccount, getAccessToken());
- String word = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
- if (inProductInfo) {
- ExecuteCommands commands = changeIconIdTextAfterCollect(true, botAccount);
- addDirective(commands);
- detail.getDirectives().add(commands);
- } else if (inPlayInfo) {
- changeCollectIconInPlay(true);
- }
- if (word == null) detail.setResponse(buildErrorResponse(COLLECT_BOT_WORD));
- else detail.setResponse(buildErrorResponse(String.format(COLLECT_BOT_WORD_MG, correctName(word))));
- }else {
- detail.setResponse(buildErrorResponse("您还未收藏过该作品,它不在您的收藏列表内"));
- }
- }
- }else {
- detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
- }
- } catch (Exception e) {
- log.error("收藏/取消收藏出错:{}",e.toString());
- detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
- }
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
-
- private void dealRankIntent(OverTimeDetail detail, String userId) {
- RecommandDocument document = RecommendUtil.getRankDocumentFirstPage();
- RenderDocument render = new RenderDocument();
- render.setDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String token = document.getRecommendIdList();
- if (token != null) {
- setSessionAttribute("recommand", token);
- setSessionAttribute(PRE_COLLE, null);
- setSessionAttribute("comCnt", null);
-
- detail.getAttributes().put("recommand", token);
- detail.getAttributes().put(PRE_COLLE, null);
- detail.getAttributes().put("comCnt", null);
- }
- setSessionAttribute(BACK_TRACE, "04");
- detail.getAttributes().put(BACK_TRACE, "04");
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
-
- private void dealRecommandIntent(OverTimeDetail detail, String userId) {
- RecommandDocument recommandDocument = RecommendUtil.getRecommendDocument(0);
- RenderDocument render = new RenderDocument();
- render.setDocument(recommandDocument);
- addDirective(render);
- detail.getDirectives().add(render);
- String token = recommandDocument.getRecommendIdList();
- if (token != null) {
- setSessionAttribute("recommand", token);
- setSessionAttribute(PRE_COLLE, null);
- setSessionAttribute("comCnt", null);
-
- detail.getAttributes().put("comCnt", null);
- detail.getAttributes().put("recommand", token);
- detail.getAttributes().put(PRE_COLLE, null);
- }
- setSessionAttribute(BACK_TRACE, "03");
- detail.getAttributes().put(BACK_TRACE,"03");
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
-
- private void dealHistoryIntent(OverTimeDetail detail, String userId) {
- CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(), 0);
- if (document == null) {
- detail.setResponse(buildErrorResponse("没有更多了"));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- //dplBotService.addDirective(new PushStack());
- setSessionAttribute(PRE_COLLE,document.getIdToken());
- setSessionAttribute("recommand", null);
- setSessionAttribute("comCnt", null);
- setSessionAttribute(BACK_TRACE, "02");
-
- detail.getDirectives().add(render);
- detail.getAttributes().put("comCnt", null);
- detail.getAttributes().put("recommand", null);
- detail.getAttributes().put(PRE_COLLE,document.getIdToken());
- detail.getAttributes().put(BACK_TRACE, "02");
-
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
-
- private void dealNextPageIntent(OverTimeDetail detail, String userId, IntentRequest intentRequest) {
- String signPage = getSessionAttribute("trace");
- if (signPage == null || signPage.length() < 2) {
- detail.setResponse(buildErrorResponse("哎呀,小悟累啦,滑不动了"));
- LAST_OUTTIME_RESULT.put(userId,detail);
- return;
- }
- char sign = signPage.charAt(1);
- switch (sign) {
- case '1': {
- String recommendNextCount = getSessionAttribute("comCnt");
- if (recommendNextCount == null) {
- recommendNextCount = "1";
- }
- int count = Integer.parseInt(recommendNextCount);
- int start = count*CO_HI_PAGE_SIZE;
- CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
- getSessionAttribute("userId"), start);
- if (document != null) {
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String cmt = String.valueOf(count+1);
- setSessionAttribute("comCnt",cmt);
- setSessionAttribute(PRE_COLLE, document.getIdToken());
- detail.getAttributes().put(PRE_COLLE,document.getIdToken());
- detail.getAttributes().put("comCnt", cmt);
- } else {
- detail.setResponse(buildErrorResponse("已经到最后一页了"));
- }
- break;
- }
- case '2': {
- String recommendNextCount = getSessionAttribute("comCnt");
- if (recommendNextCount == null) {
- recommendNextCount = "1";
- }
- int count = Integer.parseInt(recommendNextCount);
- int start = count*CO_HI_PAGE_SIZE;
- CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(), start);
- if (document != null) {
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String cmt = String.valueOf(count+1);
- setSessionAttribute("comCnt",cmt);
- setSessionAttribute(PRE_COLLE, document.getIdToken());
- detail.getAttributes().put(PRE_COLLE,document.getIdToken());
- detail.getAttributes().put("comCnt", cmt);
- } else {
- detail.setResponse(buildErrorResponse("已经到最后一页了"));
- }
- break;
- }
- case '3': {
- String recommendNextCount = getSessionAttribute("comCnt");
- int count = 1;
- if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
- RecommandDocument document = RecommendUtil.getRecommendDocument(count);
- if (document == null) {
- detail.setResponse(buildErrorResponse("客观你已经翻到底了,没有更多了"));
- break;
- }
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String token = document.getRecommendIdList();
- setSessionAttribute("recommand", token);
- detail.getAttributes().put("recommand",token);
- setSessionAttribute("comCnt",String.valueOf(count+1));
- detail.getAttributes().put("comCnt",String.valueOf(count+1));
- break;
- }
- case '4': {
- String recommendNextCount = getSessionAttribute("comCnt");
- int count = 1;
- if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
- RecommandDocument document = RecommendUtil.getRankOtherPageDocument(count);
- if (document == null) {
- detail.setResponse(buildErrorResponse("客观你已经翻到底了,没有更多了"));
- break;
- }
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String token = document.getRecommendIdList();
- setSessionAttribute("recommand", token);
- detail.getAttributes().put("recommand",token);
- setSessionAttribute("comCnt",String.valueOf(count+1));
- detail.getAttributes().put("comCnt",String.valueOf(count+1));
- break;
- }
- case '5':{
- String category = getSessionAttribute("category");
- if (category == null) category = "古风";
- String categoryNextCount = getSessionAttribute("comCnt");
- int count = 1;
- if (categoryNextCount != null) count = Integer.parseInt(categoryNextCount);
- RecommandDocument document = RecommendUtil.getCategory(count,category);
- if (document == null) {
- detail.setResponse(buildErrorResponse("客观你已经翻到底了,没有更多了"));
- break;
- }
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String countStr = String.valueOf(count+1);
- setSessionAttribute("comCnt",countStr);
- detail.getAttributes().put("comCnt",countStr);
- break;
- }
- default:{
- detail.setResponse(buildErrorResponse("该功能还没实现"));
- }
- }
- LAST_OUTTIME_RESULT.put(userId,detail);
- }
-
- private void dealLastPageIntent(OverTimeDetail detail, String userId, IntentRequest intentRequest) {
- String signPage = getSessionAttribute("trace");
- if (signPage == null || signPage.length() < 2) {
- detail.setResponse(buildErrorResponse("不好意思,小悟累啦,滑不动了"));
- LAST_OUTTIME_RESULT.put(userId,detail);
- return;
- }
- char sign = signPage.charAt(1);
- switch (sign) {
- case '1':{
- String recommendNextCount = getSessionAttribute("comCnt");
- if (recommendNextCount == null || "1".equals(recommendNextCount)) {
- detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
- break;
- }
- int count = Integer.parseInt(recommendNextCount);
- int start = (count-2)*CO_HI_PAGE_SIZE;
- CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
- getSessionAttribute("userId"), start);
- if (document != null) {
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String cmt = String.valueOf(count-1);
- setSessionAttribute("comCnt",cmt);
- setSessionAttribute(PRE_COLLE, document.getIdToken());
- detail.getAttributes().put(PRE_COLLE, document.getIdToken());
- detail.getAttributes().put("comCnt", cmt);
- }
- break;
- }
- case '2':{
- String recommendNextCount = getSessionAttribute("comCnt");
- if (recommendNextCount == null || "1".equals(recommendNextCount)) {
- detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
- break;
- }
- int count = Integer.parseInt(recommendNextCount);
- int start = (count-2)*CO_HI_PAGE_SIZE;
- CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(), start);
- if (document != null) {
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String cmt = String.valueOf(count-1);
- setSessionAttribute("comCnt",cmt);
- setSessionAttribute(PRE_COLLE, document.getIdToken());
- detail.getAttributes().put(PRE_COLLE, document.getIdToken());
- detail.getAttributes().put("comCnt", cmt);
- }
- break;
- }
- case '3': {
- String recommendNextCount = getSessionAttribute("comCnt");
- if (recommendNextCount == null || "1".equals(recommendNextCount)) {
- detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
- break;
- }
- int count = Integer.parseInt(recommendNextCount);
- RecommandDocument document = RecommendUtil.getRecommendDocument(count-2);
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String token = document.getRecommendIdList();
- setSessionAttribute("recommand", token);
- detail.getAttributes().put("recommand",token);
- setSessionAttribute("comCnt",String.valueOf(count-1));
- detail.getAttributes().put("comCnt",String.valueOf(count-1));
- break;
- }
- case '4': {
- String recommendNextCount = getSessionAttribute("comCnt");
- if (recommendNextCount == null || "1".equals(recommendNextCount)) {
- detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
- break;
- }
- int count = Integer.parseInt(recommendNextCount);
- RecommandDocument document;
- if (count == 2) document = RecommendUtil.getRankDocumentFirstPage();
- else document = RecommendUtil.getRankOtherPageDocument(count-2);
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- String token = document.getRecommendIdList();
- setSessionAttribute("recommand", token);
- detail.getAttributes().put("recommand",token);
- setSessionAttribute("comCnt",String.valueOf(count-1));
- detail.getAttributes().put("comCnt",String.valueOf(count-1));
- break;
- }
- case '5':{
- String category = getSessionAttribute("category");
- if (category == null) category = "古风";
- String recommendNextCount = getSessionAttribute("comCnt");
- if (recommendNextCount == null || "1".equals(recommendNextCount)) {
- detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
- break;
- }
- int count = Integer.parseInt(recommendNextCount);
- RecommandDocument document = RecommendUtil.getCategory(count-2,category);
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- setSessionAttribute("comCnt",String.valueOf(count-1));
- detail.getAttributes().put("comCnt",String.valueOf(count-1));
- break;
- }
- default:{
- detail.setResponse(buildErrorResponse("该功能还没实现"));
- }
- }
- LAST_OUTTIME_RESULT.put(userId,detail);
- }
-
- private void dealOpenNumIntent(OverTimeDetail detail, String userId) {
- String trace = getSessionAttribute("trace");
- if (trace == null || trace.charAt(1) == '0') {
- String numStr = getSlot("sys.number");
- int num = 1;
- if (numStr != null) num = Integer.parseInt(numStr);
- detail.setResponse(dealOpenNumInHome(num, detail));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- } else if (trace.length() > 2) {
- detail.setResponse(buildErrorResponse("客官,您在这个页面想打开啥"));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- char page = trace.charAt(1);
- switch (page){
- case '1':
- case '2': detail.setResponse(dealOpenNum(getSessionAttribute(PRE_COLLE), detail)); break;
- case '3': detail.setResponse(dealOpenNumInRecommend(getSessionAttribute("recommand"),detail)); break;
- case '4': detail.setResponse(dealOpenNumInRecommend(getSessionAttribute("recommand"),detail)); break;
- case '5': detail.setResponse(dealOpenNumInCategory(userId, detail));break;
- case '6': detail.setResponse(dealOpenNumInRecommend(getSessionAttribute("recommand"), detail));break;
- default:{
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "屏幕上的图标都是可以点击的哦");
- detail.getResponse().setOutputSpeech(outputSpeech);
- }
- }
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
-
- private void dealOpenCollectIntent(OverTimeDetail detail, String userId) {
- if (getAccessToken() == null) {
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
- detail.setResponse(new Response(outputSpeech));
- LAST_OUTTIME_RESULT.put(userId, detail);
- } else {
- String appUserId = getSessionAttribute("userId");
- if (appUserId == null) {
- appUserId = DplbotServiceUtil.getUsUserId(userId, getAccessToken());
- if (appUserId == null) {
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, SORRY_UNCATCH);
- detail.setResponse(new Response(outputSpeech));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- }
- CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(), appUserId, 0);
- if (document == null) {
- backToHome(detail);
- detail.setResponse(buildErrorResponse("您还没有收藏任何作品"));
- return;
- }
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- setSessionAttribute(PRE_COLLE,document.getIdToken());
- setSessionAttribute("recommand", null);
- setSessionAttribute(BACK_TRACE, "01");
- setSessionAttribute("comCnt", null);
- detail.getAttributes().put("comCnt", null);
- detail.getAttributes().put("recommand", null);
- detail.getAttributes().put(PRE_COLLE, document.getIdToken());
- detail.getAttributes().put(BACK_TRACE,"01");
- detail.getDirectives().add(render);
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
- }
-
- private void dealLoadIntent(OverTimeDetail detail, String userId) {
- detail.setResponse(load());
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
-
- private void dealBackIntent(OverTimeDetail detail, String userId) {
- String trace = getSessionAttribute(BACK_TRACE);
- char second;
- if (trace == null || trace.length() <= 2 || getQuery().contains("首")) {
- // home page
- backToHome(detail);
- if (trace != null && StringUtils.endsWith(trace,File.separator)) sendCancellToTerminate(userId);
- } else if (StringUtils.endsWith(trace,File.separator)){
- String botAccount = trace.substring(2, trace.length()-1);
- log.info("返回作品的id:{}", botAccount);
- backToBotIntro(botAccount, detail);
- sendCancellToTerminate(userId);
- } else {
- second = trace.charAt(1);
- switch (second){
- // home page
- case '0':{
- backToHome(detail);
- break;
- }
- case '1': {
- //collect
- String appUserId = getSessionAttribute("userId");
- if (appUserId == null) {
- appUserId = DplbotServiceUtil.getUsUserId(userId, getAccessToken());
- if (appUserId == null) {
- backToHome(detail);
- break;
- }
- }
- String recommendNextCount = getSessionAttribute("comCnt");
- int count = 1;
- if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
- CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
- appUserId, (count-1)*CO_HI_PAGE_SIZE);
- if (document == null) {
- backToHome(detail);
- detail.setResponse(buildErrorResponse("您还未收藏过任何作品,快去收藏吧"));
- break;
- }
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- setSessionAttribute(BACK_TRACE, "01");
- setSessionAttribute(PRE_COLLE,document.getIdToken());
- detail.getAttributes().put(BACK_TRACE,"01");
- detail.getAttributes().put(PRE_COLLE,document.getIdToken());
- detail.getDirectives().add(render);
- break;
- }
- case '2': {
- //history
- String recommendNextCount = getSessionAttribute("comCnt");
- int count = 1;
- if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
- CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(), (count-1)*CO_HI_PAGE_SIZE);
- if (document == null) {
- backToHome(detail);
- detail.setResponse(buildErrorResponse("哎呀,可能是您太久没玩了,历史记录已被清空"));
- break;
- }
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- setSessionAttribute(PRE_COLLE,document.getIdToken());
- setSessionAttribute(BACK_TRACE, "02");
- detail.getAttributes().put(BACK_TRACE,"02");
- detail.getAttributes().put(PRE_COLLE,document.getIdToken());
- detail.getDirectives().add(render);
- break;
- }
- case '3': {
- //recommend
- String recommendNextCount = getSessionAttribute("comCnt");
- int count = 1;
- if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
- RecommandDocument recommandDocument = RecommendUtil.getRecommendDocument(count-1);
- if (recommandDocument == null) {
- RenderDocument render = new RenderDocument();
- render.setDocument(LunchUtils.getLunchDocument());
- addDirective(render);
- detail.getDirectives().add(render);
- setSessionAttribute(BACK_TRACE, null);
- detail.getAttributes().put(BACK_TRACE, null);
- break;
- }
- RenderDocument render = new RenderDocument();
- render.setDocument(recommandDocument);
- addDirective(render);
- String token = recommandDocument.getRecommendIdList();
- if (token != null) {
- setSessionAttribute("recommand", token);
- detail.getAttributes().put("recommand",token);
- }
- setSessionAttribute(BACK_TRACE, "03");
- detail.getAttributes().put(BACK_TRACE, "03");
- detail.getDirectives().add(render);
- detail.setResponse(buildErrorResponse("已为您返回到推荐页"));
- break;
- }
- case '4': {
- //rank
- String recommendNextCount = getSessionAttribute("comCnt");
- int count = 1;
- if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
- RecommandDocument recommandDocument;
- if (count == 1) recommandDocument = RecommendUtil.getRankDocumentFirstPage();
- else recommandDocument = RecommendUtil.getRankOtherPageDocument(count-1);
- if (recommandDocument == null) {
- RenderDocument render = new RenderDocument();
- render.setDocument(LunchUtils.getLunchDocument());
- addDirective(render);
- detail.getDirectives().add(render);
- setSessionAttribute(BACK_TRACE, null);
- detail.getAttributes().put(BACK_TRACE, null);
- break;
- }
- RenderDocument render = new RenderDocument();
- render.setDocument(recommandDocument);
- addDirective(render);
- String token = recommandDocument.getRecommendIdList();
- if (token != null) {
- setSessionAttribute("recommand", token);
- detail.getAttributes().put("recommand",token);
- }
- setSessionAttribute(BACK_TRACE, "04");
- detail.getAttributes().put(BACK_TRACE, "04");
- detail.getDirectives().add(render);
- detail.setResponse(buildErrorResponse("已为您返回到排行榜"));
- break;
- }
- case '5':{
- String category = getSessionAttribute("category");
- if (category == null) {
- backToHome(detail);
- } else {
- String count = getSessionAttribute("comCnt");
- int pageIndex = 0;
- if (count != null) pageIndex = Integer.parseInt(count)-1;
- RecommandDocument document = RecommendUtil.getCategory(pageIndex, category);
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- detail.setResponse(buildErrorResponse(new StringBuilder("已为您返回到")
- .append(category).append("分类第").append(pageIndex+1).append("页").toString()));
- }
- break;
- }
- }
- }
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
-
- private void backToHome(OverTimeDetail detail) {
- RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
- addDirective(renderDocument);
- setSessionAttribute(BACK_TRACE,null);
- detail.getAttributes().put(BACK_TRACE,null);
- detail.getDirectives().add(renderDocument);
- }
-
- private void dealDefaultIntent(IntentRequest intentRequest, OverTimeDetail detail, String userId,
- String intentName,String word) {
- if (word == null) {
- Query query = intentRequest.getQuery();
- if (query != null) word = query.getOriginal();
- if (word == null){
- log.info("小度没有传来任何话语");
- detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- }
- QiWuResponse data = null;
- try {
- data = RequestTerminal.requestTerminate(word, userId, type);
- } catch (Exception e) {
- log.error("请求终端接口出错:", e.toString());
- }
- if (data == null) {
- detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- String text = data.getText();
- if ("funny".equals(intentName) || data.getAipioneerUsername().equals("4151097686")) {
- RecommandDocument document = displayFunnyRecommandPage(text, data.getAudio());
- if (document != null) {
- document.getMainTemplate().getItems().get(2).setSrc(data.getAudio());
- FUNNY_DEFAULT_DOCUMENT = document;
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- setSessionAttribute("recommand", document.getRecommendIdList());
- setSessionAttribute(BACK_TRACE, "06");
- detail.getAttributes().put(BACK_TRACE, "06");
- detail.getAttributes().put("recommand", document.getRecommendIdList());
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- log.info("funny has som situation出现问题");
- }
-// String aside = DplbotServiceUtil.getAsideText(text);
-// //log.info("旁白名字:{}",aside);
-// //log.info("小悟返回:{}", text);
-// text = text.substring(text.indexOf("】")+1);
-
- if (ScheduleService.getExceptBotAccount().contains(data.getAipioneerUsername())) {
- OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, text.substring(text.indexOf("】")+1));
- detail.getResponse().setOutputSpeech(outputSpeech);
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- final String botAccount = data.getAipioneerUsername();
- if (botAccount == null) {
- detail.setResponse(buildErrorResponse("不支持该作品换一个吧"));
- LAST_OUTTIME_RESULT.put(userId, detail);
- return;
- }
- String beforeBotAccount = getSessionAttribute("botAcc");
- if (!botAccount.equals(beforeBotAccount)) {
- DplbotServiceUtil.updateTheUserBehaviorDataMark(userId, botAccount, getAccessToken());
- String productName = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
-
-// PlayDocument document = PlayUtils.getPlayDocument(correctName(productName), aside,
-// ScheduleService.getAsideImgUrl(botAccount, aside),
-// data.getAudio(), text);
- Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
- PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern),
- DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botAccount);
-
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- DplbotServiceUtil.updateTheUserHistory(userId, botAccount, getAccessToken());
- String trace = getSessionAttribute(BACK_TRACE);
- if (trace == null || trace.length() != 2) trace = "00";
- trace = new StringBuilder(trace).append(botAccount).append(File.separator).toString();
- setSessionAttribute(BACK_TRACE, trace);
- setSessionAttribute("botAcc", botAccount);
- detail.getAttributes().put("botAcc", botAccount);
- detail.getAttributes().put(BACK_TRACE,trace);
- LAST_OUTTIME_RESULT.put(userId, detail);
- } else {
-// ExecuteCommands executeCommands = new ExecuteCommands();
-// SetStateCommand audio = new SetStateCommand();
-// SetStateCommand textState = new SetStateCommand();
-// audio.setComponentId("audioCom");
-// audio.setState("src");
-// audio.setValue(data.getAudio());
-// textState.setComponentId("text");
-// textState.setState("text");
-// textState.setValue(text);
-//
-// SetStateCommand asideImg = new SetStateCommand();
-// asideImg.setComponentId("asideImg");
-// asideImg.setState("src");
-// asideImg.setValue(ScheduleService.getAsideImgUrl(botAccount, aside));
-//
-// SetStateCommand asideText = new SetStateCommand();
-// asideText.setComponentId("asideText");
-// asideText.setState("text");
-// asideText.setValue(aside);
-//
-// executeCommands.addCommand(audio);
-// executeCommands.addCommand(textState);
-// executeCommands.addCommand(asideImg);
-// executeCommands.addCommand(asideText);
-
-// UpdateComponentCommand update = new UpdateComponentCommand();
-// update.setComponentId("whole");
-// update.setDocument(TempleUtils.getPlayUpdate(data.getAudio(), text));
-// executeCommands.addCommand(update);
-
-// addDirective(executeCommands);
-// detail.getDirectives().add(executeCommands);
-
- String productName = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
-// PlayDocument document = PlayUtils.getPlayDocument(correctName(productName), aside,
-// ScheduleService.getAsideImgUrl(botAccount, aside),
-// data.getAudio(), text);
- Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
- PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern),
- DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botAccount);
-
- RenderDocument render = new RenderDocument(document);
- addDirective(render);
- detail.getDirectives().add(render);
- LAST_OUTTIME_RESULT.put(userId, detail);
- }
- }
-
- private Response dealOpenNumInRecommend(String idsToken, OverTimeDetail overDetail) {
- if (idsToken == null) {
- return buildErrorResponse("请重新进入当前页面");
- }
- int collectNum = Integer.parseInt(getSlot("sys.number"));
- String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
- if (collectNum > tokenList.length || collectNum <= 0) return buildErrorResponse("这个数字超出了范围");
- OnProductDetail detail = ScheduleService.PRODUCT_ID_DETAIL.get(tokenList[collectNum-1]);
- if (DplbotServiceUtil.doesUserPlayed(detail.getBotAccount(), getUserId(), getAccessToken())) {
- String productName = correctName(detail.getName());
- return directInProduct(productName, detail.getBotAccount(), overDetail);
- } else {
- return enterProductInfo(detail.getName(), overDetail);
- }
- }
-
- private Response dealOpenNumInCategory(String userId, OverTimeDetail detail) {
- String count = getSessionAttribute("comCnt");
- int pageIndex = 0;
- if (count != null) pageIndex = Integer.parseInt(count)-1;
- String numStr = getSlot("sys.number");
- int num = 1;
- if (numStr != null) num = Integer.parseInt(numStr);
- List categoryBots = ScheduleService.getCategoryProductIdList().get(getSessionAttribute("category"));
- num = pageIndex*RE_RA_CA_PAGE_SIZE+num-1;
- if (num < 0 || num >= categoryBots.size()) {
- Response response = buildErrorResponse("这个数字超出了范围,作品的序号已显示在图片左上角");
- detail.setResponse(response);
- LAST_OUTTIME_RESULT.put(userId, detail);
- return response;
- }
- String botId = categoryBots.get(num);
- String name = ScheduleService.getProductIdDetail().get(botId).getName();
- Response response;
- if (DplbotServiceUtil.doesUserPlayed(botId, getUserId(), getAccessToken())) response = directInProduct(correctName(name), botId, detail);
- else response = enterProductInfo(correctName(name), detail);
- detail.setResponse(response);
- return response;
- }
-
- private Response dealOpenNumInHome(int num, OverTimeDetail detail) {
- if (num > 0 && num <= 10) {
- GameProjectTb bot = ScheduleService.getRecommendList().get(num-1);
- log.info("历史:作品id:{}",bot.getBotAccount());
- if (!DplbotServiceUtil.doesUserPlayed(bot.getBotAccount(), getUserId(), getAccessToken())) return enterProductInfo(bot.getName(), detail);
- else return directInProduct(bot.getName(), bot.getBotAccount(), detail);
- } else if (num > 10 && num <= 20) {
- GameProjectTb bot = ScheduleService.getRankingList().get(num-11);
- log.info("历史:作品id:{}",bot.getBotAccount());
- if (!DplbotServiceUtil.doesUserPlayed(bot.getBotAccount(), getUserId(), getAccessToken())) return enterProductInfo(bot.getName(), detail);
- else return directInProduct(bot.getName(), bot.getBotAccount(), detail);
- } else if (num > 20 && num <= 30) {
- String categoryName = ScheduleService.CATEGORY[num-21];
- RecommandDocument document = RecommendUtil.getCategory(0, categoryName);
- if (document == null) return buildErrorResponse("不好意思该分类还没有作品");
- RenderDocument render = new RenderDocument(document);
- this.addDirective(render);
- detail.getDirectives().add(render);
- this.setSessionAttribute("category",categoryName);
- detail.getAttributes().put("category",categoryName);
- this.setSessionAttribute("trace","05");
- detail.getAttributes().put("trace","05");
- return buildErrorResponse(new StringBuilder("为您打开").append(categoryName).append("类作品").toString());
- }
- else {
- return buildErrorResponse("这数字超出我的范围了");
- }
- }
-
- private Response directInProduct(String name,String botId,OverTimeDetail detail) {
- String productName = correctName(name);
- String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
- log.info("进入作品语句:{}", enterProductWord);
- QiWuResponse data = null;
- try {
- data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
- } catch (IOException e) {
- log.error("请求终端接口出错:", e.toString());
- }
- if (data == null) {
- return buildErrorResponse(SORRY_UNCATCH);
- }
- String text = data.getText();
-// String aside = DplbotServiceUtil.getAsideText(text);
-// text = text.substring(text.indexOf("】")+1);
-// PlayDocument document = PlayUtils.getPlayDocument(productName, aside,ScheduleService.getAsideImgUrl(botId, aside),
-// data.getAudio(), text);
- Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
- PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern),
- DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botId);
-
- RenderDocument render = new RenderDocument(document);
- this.setSessionAttribute(PRE_COLLE, null);
- detail.getAttributes().put(PRE_COLLE, null);
- String trace = getSessionAttribute(BACK_TRACE);
- if (trace == null || trace.length() != 2) trace = "00";
- String backTrace = new StringBuilder(trace).append(botId).append(File.separator).toString();
- this.setSessionAttribute(BACK_TRACE, backTrace);
- detail.getAttributes().put(BACK_TRACE,backTrace);
- this.addDirective(render);
- detail.getDirectives().add(render);
- return new Response();
- }
-
- private Response enterProductInfo(String productName, OverTimeDetail detail) {
- OnProductDetail productDetail = ScheduleService.PRODUCT_NAME_DETAIL.get(productName);
- // product picture
- String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
-
- // product create time
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
- String dateString = formatter.format(productDetail.getCreateTime());
- String createTime = new StringBuilder(Constants.PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
-
- // product author
- String author = new StringBuilder(Constants.PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
-
- // product labels
- StringBuilder labels = new StringBuilder(Constants.PRODUCT_INTRO.LABEL);
- for (String label: productDetail.getLabels()) {
- labels.append(Constants.PRODUCT_INTRO.SPACE).append(label);
- }
-
- // product introduction
- String intro = productDetail.getIntro();
-
- // "start product" container button
- String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
-
- String accessToken = getAccessToken();
- String flowers, flowerReward,collectText, collectUrl, collectComId;
- if (accessToken != null) {
- // flower container button
- Long count = DplbotServiceUtil.getUserSendFlowerNum(productDetail.getBotAccount(), getUserId(), accessToken);
- flowers = USER_SEND_FLOWER+count;
- flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
-
- // collection container button
- boolean collec = DplbotServiceUtil.doesUserCollectThisBot(productDetail.getBotAccount(), accessToken, getUserId());
- if (collec) {
- collectText = COLLECED;
- collectUrl = COLLECTED_IMG_URL;
- collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
- } else {
- collectText = UN_COLLEC;
- collectUrl = UN_COLLECTED_IMG_URL;
- collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
- }
- } else {
- flowers = FLOWER;
- flowerReward = FLOWER_LOAD;
-
- collectText = UN_COLLEC;
- collectUrl = UN_COLLECTED_IMG_URL;
- collectComId = FLOWER_LOAD; // 提示登录
- }
-
- ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), createTime, author, labels.toString(),
- intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
-
- RenderDocument renderDocument = new RenderDocument(document);
- this.addDirective(renderDocument);
- detail.getDirectives().add(renderDocument);
- String trace = getSessionAttribute(BACK_TRACE);
- log.info("before trace------------:{}",trace);
- StringBuilder builder = new StringBuilder();
- if (trace == null || trace.length() < 2) {
- builder.append("00");
- } else if (trace.length()>2) {
- builder.append(trace, 0, 2);
- } else {
- builder.append(trace);
- }
-
- trace = builder.append(productDetail.getBotAccount()).toString();
- log.info("after trace------------:{}",trace);
- this.setSessionAttribute(BACK_TRACE, trace);
- detail.getAttributes().put(BACK_TRACE, trace);
- return new Response();
- }
-
- private RecommandDocument displayFunnyRecommandPage(String word, String audio) {
- try {
- List botNames = Utils.getRecommandBotNames(word);
- log.info("botNames:{}",botNames);
- List bots = new ArrayList<>();
- for (String botName : botNames) {
- if (botName.equals("清新传")) botName = "清新传{/zhuan4/}";
- OnProductDetail detail = ScheduleService.PRODUCT_NAME_DETAIL.get(botName);
- if (detail == null) continue;
- bots.add(detail);
- }
- if (bots.size() != 0) return RecommendUtil.getFunnyDocument(bots, audio);
- } catch (Exception e) {
- log.error("获取funny页出错:{}",e.toString());
- }
- return null;
- }
-
- private XiaoDuOrderTB buildBeforePayPojo(String botAccount, String appUserId, String userId, int unitPrice,
- long number, String orderId) {
- XiaoDuOrderTB xiaoDuOrderTB = new XiaoDuOrderTB();
- buildPayPojoCommon(xiaoDuOrderTB, botAccount, appUserId, userId, unitPrice, number, orderId);
- xiaoDuOrderTB.setDevice(1);
- return xiaoDuOrderTB;
- }
-
- private XiaoDuOrderTB buildNoScreenBeforePayPojo(String botAccount, String appUserId, String userId, int unitPrice,
- long number, String orderId) {
- XiaoDuOrderTB xiaoDuOrderTB = new XiaoDuOrderTB();
- buildPayPojoCommon(xiaoDuOrderTB, botAccount, appUserId, userId, unitPrice, number, orderId);
- xiaoDuOrderTB.setDevice(2);
- return xiaoDuOrderTB;
- }
-
- private void buildPayPojoCommon(XiaoDuOrderTB xiaoDuOrderTB, String botAccount, String appUserId, String userId, int unitPrice,
- long number, String orderId) {
- xiaoDuOrderTB.setBotId(botAccount);
- xiaoDuOrderTB.setAppUserId(appUserId);
- xiaoDuOrderTB.setXiaoduUserId(userId);
- xiaoDuOrderTB.setUnitPrice(unitPrice);
- xiaoDuOrderTB.setNumber(number);
- xiaoDuOrderTB.setIsBuy(false);
- xiaoDuOrderTB.setStatus(false);
- xiaoDuOrderTB.setChOrderId(orderId);
- xiaoDuOrderTB.setTimeStamp(curTime);
- }
-
- @Override
- protected Response onChargeEvent(ChargeEvent chargeEvent) {
- String token = chargeEvent.getToken();
- int sepIndex = token.indexOf(File.separator);
- final String botAccount = token.substring(0, sepIndex);
- String str = "恭喜您支付成功,开始体验吧";
- if (getRequest().getContext().getScreen() != null) {
- boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, customUserId(), getAccessToken(),
- getSessionAttribute("userId"), PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_screen");
- if (response) {
- HashMap flowerRecords = DplbotServiceUtil.USER_HISTORY.get(getUserId()).getUserBotId2Flowers();
- Long before = flowerRecords.get(botAccount);
- if (before == null) before = 0L;
- flowerRecords.put(botAccount, before+1);
- ExecuteCommands executeCommands = new ExecuteCommands();
- SetStateCommand stateCommand = new SetStateCommand();
- stateCommand.setComponentId("pft");
- stateCommand.setState("text");
- stateCommand.setValue(USER_SEND_FLOWER+before);
- executeCommands.addCommand(stateCommand);
- try {
- addDirective(executeCommands);
- } catch (Exception e) {
- log.info(ExceptionUtils.getStackTrace(e));
- }
- } else {
- str = "很抱歉,您没有支付成功";
- }
- } else {
- String userId = customUserId();
- String jytUserId = getSessionAttribute("userId");
- if (StringUtils.isBlank(jytUserId)) jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken());
- if (StringUtils.isBlank(jytUserId)) {
- jytUserId = "null";
- }
- boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, userId, getAccessToken(),
- jytUserId, PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_no_screen");
- if (!response) {
- str = "很抱歉,您没有支付成功";
- }
- }
- return buildErrorResponse(str);
- }
-
- @Override
- protected Response onPlaybackFinishedEvent(PlaybackFinishedEvent playbackFinishedEvent) {
-// log.info("音频播放完毕,开麦");
-// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
- this.setExpectSpeech(true);
-// log.error("FinishedEvent");
- return new Response();
- }
-
- @Override
- protected Response onPlaybackStoppedEvent(PlaybackStoppedEvent playbackStoppedEvent) {
-// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
- waitAnswer();
- return new Response();
- }
-
- @Override
- protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
-// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
- USERID_AUDIO_PATH.remove(customUserId());
- waitAnswer();
- return new Response();
- }
-
- @Override
- protected Response onPlaybackNearlyFinishedEvent(PlaybackNearlyFinishedEvent playbackNearlyFinishedEvent) {
-// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
- waitAnswer();
- return new Response();
- }
-
- private String customUserId() {
- try {
- return PREFIX_USERID+ URLEncoder.encode(getUserId(), "UTF-8");
- } catch (Exception e) {
- return PREFIX_USERID+ getUserId().replaceAll("/", "");
- }
-// return PREFIX_USERID + ai.qiwu.com.xiaoduhome.xiaoai.common.Utils.modifyDeviceId(getUserId());
-// return PREFIX_USERID + getUserId().replaceAll(NUM_OR_ALPHA, "");
- }
+//
+// private void dealWithError(SessionEndedRequest request) {
+// switch (request.getError().getType()) {
+// case INTERNAL_ERROR: log.info(ErrorMsg.INTERNAL_ERROR); break;
+// case INVALID_RESPONSE: log.info(ErrorMsg.INVALID_RESPONSE); break;
+// case DEVICE_COMMUNICATION_ERROR: log.info(ErrorMsg.DEVICE_COMMUNICATION_ERROR); break;
+// }
+// log.info("错误信息 : "+ request.getError().getMessage());
+// }
+//
+// private Response dealHistoryClick() {
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(), 0);
+// if (document == null) return buildErrorResponse("不好意思,您太久没玩记录被清空了");
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute("recommand", null);
+// setSessionAttribute("comCnt", null);
+// setSessionAttribute(BACK_TRACE, "02");
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开历史记录");
+// return new Response(outputSpeech);
+// }
+//
+// private Response dealOpenCollectClick() {
+// if (getAccessToken() == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
+// return new Response(outputSpeech);
+// } else {
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(getUserId(), getAccessToken());
+// if (appUserId == null) {
+// return new Response();
+// }
+// }
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(getUserId(), getAccessToken(), appUserId, 0);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute("comCnt", null);
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute(BACK_TRACE, "01");
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开收藏夹");
+// return new Response(outputSpeech);
+// }
+// }
+// return new Response();
+// }
+//
+//// @Override
+//// protected Response onBuyEvent(BuyEvent buyEvent) {
+//// com.baidu.dueros.data.request.buy.event.JYTUserResponse payload = buyEvent.getPayload();
+//// String result = payload.getPurchaseResult().getPurchaseResult();
+//// log.info("此次支付结果:"+result+";msg: "+payload.getMessage());
+//// if (result.equals("SUCCESS")) {
+//// log.info("支付成功");
+//// POOL.submit(new SendFlowerThread(buyEvent));
+//// POOL.submit(new SendFlowerBuyToXiaoduTB(buyEvent));
+//// return buildErrorResponse("感谢大人赏的花");
+//// }
+//// return buildErrorResponse("哎呀,没有支付成功");
+//// }
+//
+//
+// private ExecuteCommands changeIconIdTextAfterCollect(boolean collect, String botId) {
+// ExecuteCommands executeCommands = new ExecuteCommands();
+// UpdateComponentCommand update = new UpdateComponentCommand();
+// String srcValue;
+// String textValue;
+// String idValue;
+// String previousClickId;
+// String unCollectId = new StringBuilder(UN_COLLEC_ID).append(botId).toString();
+// String collectId = new StringBuilder(COLLEC_ID).append(botId).toString();
+// if (collect) {
+// srcValue = COLLECTED_IMG_URL;
+// textValue = COLLECED;
+// idValue = unCollectId;
+// previousClickId = collectId;
+// } else {
+// srcValue = UN_COLLECTED_IMG_URL;
+// textValue = UN_COLLEC;
+// idValue = collectId;
+// previousClickId = unCollectId;
+// }
+//
+// update.setComponentId(previousClickId);
+// update.setDocument(TempleUtils.getCollectIcon(idValue, srcValue, textValue));
+// executeCommands.addCommand(update);
+// this.addDirective(executeCommands);
+// return executeCommands;
+// }
+//
+// private ExecuteCommands changeCollectIconInPlay(boolean collect) {
+// ExecuteCommands executeCommands = new ExecuteCommands();
+// SetStateCommand setState = new SetStateCommand();
+// setState.setComponentId("playCollect");
+// setState.setState("src");
+// if (collect) {
+// setState.setValue(COLLECTED_IMG_URL);
+// }else {
+// setState.setValue(UN_COLLECTED_IMG_URL);
+// }
+// executeCommands.addCommand(setState);
+// return executeCommands;
+// }
+//
+// private Response load() {
+// Card card = new LinkAccountCard();
+// Response response = buildErrorResponse(LOAD_INTRO);
+// response.setCard(card);
+// return response;
+// }
+//
+// private Integer getUserSendFlowerNum(String productId, String accessToken) {
+// HashMap params = new HashMap<>();
+// params.put("module", "works");
+// params.put("aipioneerUsername", productId);
+// HashMap headers = new HashMap<>();
+// headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
+// headers.put("Authorization", new StringBuilder(BEARER).append(accessToken).toString());
+// CodeMsgData response;
+// try {
+// String flowerRes = OkHttp3Utils.doGet(FLOWER_INTERFACE, params, headers);
+// response = JSON.parseObject(flowerRes, CodeMsgData.class);
+// } catch (IOException e) {
+// log.error("请求用户送花数出错");
+// return null;
+// }
+// log.info("调用获取用户送花数接口结果:{}", response);
+// if (response == null || response.getCode() != 1) return null;
+// return response.getData().getCount();
+// }
+//
+//
+// private List getUserProductList(String accessToken) {
+// HashMap params = new HashMap<>();
+// params.put("module", "works");
+// HashMap headers = new HashMap<>();
+// headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
+// headers.put("Authorization", new StringBuilder(BEARER).append(accessToken).toString());
+// UserCollecResult result;
+// try {
+// String resStr = OkHttp3Utils.doGet(Constants.XIAOWU_API.USER_CLOOEC_LIST, params, headers);
+// result = JSON.parseObject(resStr, UserCollecResult.class);
+// } catch (Exception e) {
+// log.error("调用获取用户收藏作品列表接口出错:{}", e.toString());
+// return null;
+// }
+// if (result.getCode() == 1) return result.getData();
+// else {
+// log.error("获取用户收藏作品列表出错,错误码:{}, 错误信息:{}", result.getCode(), result.getMsg());
+// return null;
+// }
+// }
+//
+// private static String correctName(String name) {
+// int brace = name.indexOf("{");
+// if (brace != -1) name = name.substring(0, brace);
+// return name;
+// }
+//
+// @Override
+// protected Response onLinkAccountSucceededEvent(LinkAccountSucceededEvent linkAccountSucceededEvent) {
+// log.info("登录成功返回信息:{}",linkAccountSucceededEvent);
+// String accessToken = getAccessToken();
+// String jytUserId;
+// if (getRequest().getContext().getScreen() != null) {
+// log.info("检测到有屏登录");
+// String userId = getUserId();
+// DplbotServiceUtil.onLunchFillUserBehaviorData(accessToken, userId);
+// jytUserId = DplbotServiceUtil.getUsUserId(userId, accessToken);
+// if (jytUserId != null)
+// log.warn("登录后获取用户的app id 失败");
+// } else {
+// jytUserId = DplbotServiceUtil.getUserIdByToken(accessToken);
+// if (jytUserId != null)
+// log.warn("登录后获取用户的app id 失败");
+// }
+// setSessionAttribute("userId", jytUserId);
+// return buildErrorResponse("您已登录成功");
+// }
+//
+//// @Override
+//// protected Response onDefaultEvent() {
+//// log.info("未拦截的事件类型:"+getEventType(this.getStrRequest()));
+//// this.waitAnswer();
+//// return new Response();
+//// }
+//
+// private String getEventType(String requestStr) {
+// int typeIndex = requestStr.lastIndexOf("type");
+// int comma = requestStr.indexOf(',', typeIndex);
+// return requestStr.substring(typeIndex, comma);
+// }
+//
+// private Response buildErrorResponse(String errorMsg) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
+// return new Response(outputSpeech);
+// }
+//
+// private Response buildLogOutResponse(String errorMsg) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
+// endDialog();
+// return new Response(outputSpeech);
+// }
+//
+// private Response buildNoScreenListCardResponse(String content, String botAccount) {
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// List actors = DplbotServiceUtil.seperateActor(content, pattern);
+// String[] actorWord = DplbotServiceUtil.seperateActorWord(content, pattern);
+// int i = 0;
+// ListCard listCard = new ListCard();
+// for (String actor: actors) {
+// StandardCardInfo cardInfo = new StandardCardInfo(actor, actorWord[i++].replaceAll("
","\n"));
+// cardInfo.setImage(ScheduleService.getAsideImgUrl(botAccount, actor));
+// listCard.getList().add(cardInfo);
+// }
+//// content = buildText(content);
+// return new Response(null, listCard, WAIT_WORD);
+// }
+//
+// private Response buildNoScreenTextCardREsponse(String content) {
+// content = buildText(content);
+// TextCard textCard = new TextCard(content);
+// return new Response(null, textCard, WAIT_WORD);
+// }
+//
+// private String buildText(String text) {
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// StringBuilder builder = new StringBuilder();
+// List actors = DplbotServiceUtil.seperateActor(text, pattern);
+// String[] word = DplbotServiceUtil.seperateActorWord(text, pattern);
+// int i = 0;
+// for (String actor: actors) {
+// builder.append(actor).append(":").append(word[i].replaceAll("
", "\n")).append("\n");
+// i++;
+// }
+// if (builder.length() == 0) builder.append(text);
+// return builder.toString();
+// }
+//
+// private void backToBotIntro(String botAccount, OverTimeDetail detail) {
+// OnProductDetail productDetail = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount);
+// // product picture
+// String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
+//
+// // product name
+// String productName = correctName(productDetail.getName());
+//
+// // product create time
+// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+// String dateString = formatter.format(productDetail.getCreateTime());
+// String createTime = new StringBuilder(Constants.PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
+//
+// // product author
+// String author = new StringBuilder(Constants.PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
+//
+// // product labels
+// StringBuilder labels = new StringBuilder(Constants.PRODUCT_INTRO.LABEL);
+// for (String label: productDetail.getLabels()) {
+// labels.append(Constants.PRODUCT_INTRO.SPACE).append(label);
+// }
+//
+// // product introduction
+// String intro = productDetail.getIntro();
+//
+// // "start product" container button
+// String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
+//
+// String accessToken = getAccessToken();
+// String flowers, flowerReward,collectText, collectUrl, collectComId;
+// if (accessToken != null) {
+// // flower container button
+// Long count = DplbotServiceUtil.getUserSendFlowerNum(botAccount, getUserId(), accessToken);
+// flowers = USER_SEND_FLOWER+count;
+// flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
+//
+// // collection container button
+// boolean collec = DplbotServiceUtil.doesUserCollectThisBot(productDetail.getBotAccount(), accessToken, getUserId());
+// if (collec) {
+// collectText = COLLECED;
+// collectUrl = COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// } else {
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// }
+// } else {
+// flowers = FLOWER;
+// flowerReward = FLOWER_LOAD;
+//
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = FLOWER_LOAD; // 提示登录
+// }
+//
+// ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), createTime, author, labels.toString(),
+// intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
+// RenderDocument renderDocument = new RenderDocument(document);
+// this.addDirective(renderDocument);
+// detail.getDirectives().add(renderDocument);
+// String trace = getSessionAttribute(BACK_TRACE);
+// trace = trace.substring(0, trace.length()-1);
+// this.setSessionAttribute(BACK_TRACE, trace);
+// detail.getAttributes().put(BACK_TRACE,trace);
+// }
+//
+// // 异步发送“退出”给终端
+// private void sendCancellToTerminate(String userId){
+// RequestTerminal.backRequest(userId, type);
+// }
+//
+// class Task implements Runnable{
+// IntentRequest intentRequest;
+//
+// Task(IntentRequest intentRequest) {
+// this.intentRequest = intentRequest;
+// }
+//
+// @Override
+// public void run() {
+// final String userId = getUserId();
+// String intentName = getIntent().getName();
+// OverTimeDetail detail = new OverTimeDetail();
+// log.info("Intent name:{}",intentName);
+// if ("ai.dueros.common.default_intent".equals(intentName) || "funny".equals(intentName)) {
+// dealDefaultIntent(intentRequest, detail, userId, intentName, null);
+// return;
+// }
+// switch (intentName) {
+// case "load" : dealLoadIntent(detail, userId);break;
+// case "back" : dealBackIntent(detail, userId);break;
+// case "openCollect" : dealOpenCollectIntent(detail, userId);break;
+// case "openNum" : dealOpenNumIntent(detail, userId);break;
+// case "lastPage" : dealLastPageIntent(detail, userId, intentRequest);break;
+// case "nextPage" : dealNextPageIntent(detail, userId, intentRequest);break;
+// case "history" : dealHistoryIntent(detail, userId);break;
+// case "recommand" : dealRecommandIntent(detail, userId);break;
+// case "ranking" : dealRankIntent(detail, userId);break;
+// case "collect" :
+// case "unCollect" : dealCollectOrUnCollectIntent(detail, userId, intentName);break;
+// case "sendFlower" : dealSendFlowerIntent(detail, userId);break;
+// case "jump" : dealJumpIntent(detail, userId);break;
+// case "start" : dealStartIntent(detail, userId, intentRequest, intentName);break;
+// }
+// }
+// }
+//
+// private void dealJumpIntent(OverTimeDetail detail, String userId) {
+// String trace = getSessionAttribute("trace");
+// if (trace == null || trace.length() < 2) {
+// detail.setResponse(buildErrorResponse("小悟跳不动了"));
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// return;
+// }
+// String num = getSlot("sys.number");
+// if (num == null) {
+// detail.setResponse(buildErrorResponse("我没听清您要跳转的页面,请再说一遍"));
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// return;
+// }
+// int index = Integer.parseInt(num);
+// char pageSign = trace.charAt(1);
+// switch (pageSign) {
+// case '1' : {
+// dealCollectHistoryJump(index, true, detail, userId);
+// break;
+// }
+// case '2' : {
+// dealCollectHistoryJump(index, false, detail, userId);
+// break;
+// }
+// case '4' : {
+// dealRankJump(index, detail);
+// break;
+// }
+// case '5' : {
+// dealCategoryJump(index, detail);
+// break;
+// }
+// default : {
+// detail.setResponse(buildErrorResponse("该页面不支持跳转"));
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// }
+//
+// private void dealRankJump(int index, OverTimeDetail detail) {
+// index = index == 0 ? index : index-1;
+// RecommandDocument document;
+// if (index == 0) document = RecommendUtil.getRankDocumentFirstPage();
+// else document = RecommendUtil.getRankOtherPageDocument(index);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("超出了范围,无法跳转"));
+// return;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(index+1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute("recommand", document.getRecommendIdList());
+// detail.getAttributes().put("recommand", document.getRecommendIdList());
+// detail.getAttributes().put("comCnt", cmt);
+// }
+//
+// private void dealCategoryJump(int index, OverTimeDetail detail) {
+// index = index == 0 ? index : index-1;
+// String category = getSessionAttribute("category");
+// if (category == null) {
+// detail.setResponse(buildErrorResponse("无法跳转,请说返回然后重新进入当前分类"));
+// return;
+// }
+// RecommandDocument document = RecommendUtil.getCategory(index, category);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("超出了范围,无法跳转"));
+// return;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(index+1);
+// setSessionAttribute("comCnt",cmt);
+// detail.getAttributes().put("comCnt", cmt);
+// }
+//
+// private void dealCollectHistoryJump(int index, boolean collect, OverTimeDetail detail, String userId) {
+// index = index == 0 ? index : index-1;
+// int start = index*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document;
+// if (collect) document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(), getSessionAttribute("userId"), start);
+// else document = DplbotServiceUtil.getHistory(userId, getAccessToken(), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(index+1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// } else {
+// detail.setResponse(buildErrorResponse("超出了范围无法跳到那一页"));
+// }
+// }
+//
+// private void dealStartIntent(OverTimeDetail detail, String userId, IntentRequest intentRequest, String intentName) {
+// String trace = getSessionAttribute("trace");
+// if (trace != null && trace.length() > 2 && !StringUtils.endsWith(trace,File.separator)) {
+// String botId = trace.substring(2);
+// String enterName = new StringBuilder("我要玩")
+// .append(ScheduleService.getProductIdDetail().get(botId).getName()).toString();
+// dealDefaultIntent(intentRequest, detail, userId, intentName, enterName);
+// }else {
+// dealDefaultIntent(intentRequest, detail, userId, intentName, null);
+// }
+// }
+//
+// private void dealSendFlowerIntent(OverTimeDetail detail, String userId) {
+// if (getAccessToken() == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
+// detail.setResponse(new Response(outputSpeech));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// String num = getSlot("sys.number");
+// OutputSpeech outputSpeech;
+// String confirmationStatus = getIntent().getConfirmationStatus().name();
+// log.info("槽位确认状态:{}",confirmationStatus);
+// if ("NONE".equals(confirmationStatus)) {
+// if (num == null) {
+// log.info("确认送花个数");
+// ask("sys.number");
+// outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请问您要送几朵花");
+// setExpectSpeech(true);
+// } else {
+// log.info("确认最终送花意图");
+// setConfirmIntent();
+// outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText,
+// new StringBuilder("您要送").append(num).append("朵花是吗").toString());
+// setExpectSpeech(true);
+// }
+// detail.getResponse().setOutputSpeech(outputSpeech);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// } else if ("CONFIRMED".equals(confirmationStatus)) {
+// log.info("确认");
+// int unitPrice = Integer.parseInt(ScheduleService.FLOWER_UNIT_PRICE);
+// String amount = String.valueOf(unitPrice*Integer.parseInt(num)/100.0);
+// String orderId = new StringBuilder(userId).append(System.currentTimeMillis()).toString();
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken());
+// if (appUserId == null) {
+// log.error("送花时获取用户app_user_id失败");
+// detail.setResponse(buildErrorResponse("不好意思出了点问题,请再说一遍吧"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// }
+// String botId;
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace != null && trace.length() > 2) {
+// if (StringUtils.endsWith(trace, File.separator)) {
+// botId = trace.substring(2, trace.length()-1);
+// }else {
+// botId = trace.substring(2);
+// }
+// XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
+// XiaoDuOrderTB response = repository.save(buildBeforePayPojo(botId, appUserId, userId, unitPrice,
+// Integer.parseInt(num), orderId));
+//
+// if (response != null && response.getId() != null) {
+// String desc = new StringBuilder("感谢您赏赐给该作品的").append(num).append("朵鲜花").toString();
+// String name = ScheduleService.PRODUCT_ID_DETAIL.get(botId).getName();
+// if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
+// .append("的").append(num).append("朵鲜花").toString();
+// Charge charge = new Charge(amount, orderId, "鲜花", desc);
+// charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
+// addDirective(charge);
+// detail.getDirectives().add(charge);
+// detail.setResponse(buildErrorResponse("请扫描二维码完成支付"));
+// } else {
+// log.error("订单没有插入到xioadu_order_tb");
+// detail.setResponse(buildErrorResponse(ERROR_SEND_FLOWER));
+// }
+// }else {
+// log.error("无法获取到botID");
+// detail.setResponse(buildErrorResponse(ERROR_SEND_FLOWER));
+// }
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// } else {
+// log.info("否定");
+// detail.setResponse(buildErrorResponse("好的,已为您终止"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+// }
+//
+// private void dealCollectOrUnCollectIntent(OverTimeDetail detail, String userId, String intentName) {
+// if (getAccessToken() == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
+// detail.setResponse(new Response(outputSpeech));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// boolean collect = "collect".equals(intentName);
+// boolean inProductInfo = false;
+// boolean inPlayInfo = false;
+// String botAccount;
+// String trace = getSessionAttribute("trace");
+// if (trace == null || trace.length() <= 2) {
+// botAccount = getSessionAttribute("botAcc");
+// if(botAccount == null) {
+// String word = COLLECT_FAIL;
+// if (!collect) word = UN_COLLECT_FAIL;
+// detail.setResponse(buildErrorResponse(word));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// } else {
+// if (StringUtils.endsWith(trace, File.separator)) {
+// botAccount = trace.substring(2, trace.length()-1);
+// inPlayInfo = true;
+// }
+// else {
+// inProductInfo = true;
+// botAccount = trace.substring(2);
+// }
+// }
+// try {
+// boolean alreadyCollected = DplbotServiceUtil.doesUserCollectThisBot(botAccount, getAccessToken(), userId);
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken());
+// if (appUserId != null) {
+// if (alreadyCollected) {
+// if (collect) detail.setResponse(buildErrorResponse("您之前就已经收藏过该作品啦,看来你真的很喜欢它"));
+// else {
+// DplbotServiceUtil.userUnCollectTheBotInPool(userId, botAccount, getAccessToken());
+// String botName = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
+// if (inProductInfo) {
+// ExecuteCommands commands = changeIconIdTextAfterCollect(false, botAccount);
+// addDirective(commands);
+// detail.getDirectives().add(commands);
+// } else if (inPlayInfo) {
+// changeCollectIconInPlay(false);
+// }
+// if (botName == null) detail.setResponse(buildErrorResponse(UN_COLLECT_BOT_WORD));
+// else detail.setResponse(buildErrorResponse(String.format(UN_COLLECT_BOT_WORD_MG,botName)));
+// }
+// } else {
+// if (collect) {
+// DplbotServiceUtil.userCollectTheBotInPool(userId, botAccount, getAccessToken());
+// String word = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
+// if (inProductInfo) {
+// ExecuteCommands commands = changeIconIdTextAfterCollect(true, botAccount);
+// addDirective(commands);
+// detail.getDirectives().add(commands);
+// } else if (inPlayInfo) {
+// changeCollectIconInPlay(true);
+// }
+// if (word == null) detail.setResponse(buildErrorResponse(COLLECT_BOT_WORD));
+// else detail.setResponse(buildErrorResponse(String.format(COLLECT_BOT_WORD_MG, correctName(word))));
+// }else {
+// detail.setResponse(buildErrorResponse("您还未收藏过该作品,它不在您的收藏列表内"));
+// }
+// }
+// }else {
+// detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
+// }
+// } catch (Exception e) {
+// log.error("收藏/取消收藏出错:{}",e.toString());
+// detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
+// }
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealRankIntent(OverTimeDetail detail, String userId) {
+// RecommandDocument document = RecommendUtil.getRankDocumentFirstPage();
+// RenderDocument render = new RenderDocument();
+// render.setDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// if (token != null) {
+// setSessionAttribute("recommand", token);
+// setSessionAttribute(PRE_COLLE, null);
+// setSessionAttribute("comCnt", null);
+//
+// detail.getAttributes().put("recommand", token);
+// detail.getAttributes().put(PRE_COLLE, null);
+// detail.getAttributes().put("comCnt", null);
+// }
+// setSessionAttribute(BACK_TRACE, "04");
+// detail.getAttributes().put(BACK_TRACE, "04");
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealRecommandIntent(OverTimeDetail detail, String userId) {
+// RecommandDocument recommandDocument = RecommendUtil.getRecommendDocument(0);
+// RenderDocument render = new RenderDocument();
+// render.setDocument(recommandDocument);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = recommandDocument.getRecommendIdList();
+// if (token != null) {
+// setSessionAttribute("recommand", token);
+// setSessionAttribute(PRE_COLLE, null);
+// setSessionAttribute("comCnt", null);
+//
+// detail.getAttributes().put("comCnt", null);
+// detail.getAttributes().put("recommand", token);
+// detail.getAttributes().put(PRE_COLLE, null);
+// }
+// setSessionAttribute(BACK_TRACE, "03");
+// detail.getAttributes().put(BACK_TRACE,"03");
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealHistoryIntent(OverTimeDetail detail, String userId) {
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(), 0);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("没有更多了"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// //dplBotService.addDirective(new PushStack());
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute("recommand", null);
+// setSessionAttribute("comCnt", null);
+// setSessionAttribute(BACK_TRACE, "02");
+//
+// detail.getDirectives().add(render);
+// detail.getAttributes().put("comCnt", null);
+// detail.getAttributes().put("recommand", null);
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getAttributes().put(BACK_TRACE, "02");
+//
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealNextPageIntent(OverTimeDetail detail, String userId, IntentRequest intentRequest) {
+// String signPage = getSessionAttribute("trace");
+// if (signPage == null || signPage.length() < 2) {
+// detail.setResponse(buildErrorResponse("哎呀,小悟累啦,滑不动了"));
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// return;
+// }
+// char sign = signPage.charAt(1);
+// switch (sign) {
+// case '1': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null) {
+// recommendNextCount = "1";
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// int start = count*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
+// getSessionAttribute("userId"), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(count+1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// } else {
+// detail.setResponse(buildErrorResponse("已经到最后一页了"));
+// }
+// break;
+// }
+// case '2': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null) {
+// recommendNextCount = "1";
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// int start = count*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(count+1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// } else {
+// detail.setResponse(buildErrorResponse("已经到最后一页了"));
+// }
+// break;
+// }
+// case '3': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document = RecommendUtil.getRecommendDocument(count);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("客观你已经翻到底了,没有更多了"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// setSessionAttribute("comCnt",String.valueOf(count+1));
+// detail.getAttributes().put("comCnt",String.valueOf(count+1));
+// break;
+// }
+// case '4': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document = RecommendUtil.getRankOtherPageDocument(count);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("客观你已经翻到底了,没有更多了"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// setSessionAttribute("comCnt",String.valueOf(count+1));
+// detail.getAttributes().put("comCnt",String.valueOf(count+1));
+// break;
+// }
+// case '5':{
+// String category = getSessionAttribute("category");
+// if (category == null) category = "古风";
+// String categoryNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (categoryNextCount != null) count = Integer.parseInt(categoryNextCount);
+// RecommandDocument document = RecommendUtil.getCategory(count,category);
+// if (document == null) {
+// detail.setResponse(buildErrorResponse("客观你已经翻到底了,没有更多了"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String countStr = String.valueOf(count+1);
+// setSessionAttribute("comCnt",countStr);
+// detail.getAttributes().put("comCnt",countStr);
+// break;
+// }
+// default:{
+// detail.setResponse(buildErrorResponse("该功能还没实现"));
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// }
+//
+// private void dealLastPageIntent(OverTimeDetail detail, String userId, IntentRequest intentRequest) {
+// String signPage = getSessionAttribute("trace");
+// if (signPage == null || signPage.length() < 2) {
+// detail.setResponse(buildErrorResponse("不好意思,小悟累啦,滑不动了"));
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// return;
+// }
+// char sign = signPage.charAt(1);
+// switch (sign) {
+// case '1':{
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// int start = (count-2)*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
+// getSessionAttribute("userId"), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(count-1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// }
+// break;
+// }
+// case '2':{
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// int start = (count-2)*CO_HI_PAGE_SIZE;
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(), start);
+// if (document != null) {
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String cmt = String.valueOf(count-1);
+// setSessionAttribute("comCnt",cmt);
+// setSessionAttribute(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put("comCnt", cmt);
+// }
+// break;
+// }
+// case '3': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document = RecommendUtil.getRecommendDocument(count-2);
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// setSessionAttribute("comCnt",String.valueOf(count-1));
+// detail.getAttributes().put("comCnt",String.valueOf(count-1));
+// break;
+// }
+// case '4': {
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document;
+// if (count == 2) document = RecommendUtil.getRankDocumentFirstPage();
+// else document = RecommendUtil.getRankOtherPageDocument(count-2);
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// String token = document.getRecommendIdList();
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// setSessionAttribute("comCnt",String.valueOf(count-1));
+// detail.getAttributes().put("comCnt",String.valueOf(count-1));
+// break;
+// }
+// case '5':{
+// String category = getSessionAttribute("category");
+// if (category == null) category = "古风";
+// String recommendNextCount = getSessionAttribute("comCnt");
+// if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+// detail.setResponse(buildErrorResponse("客观,前面没啦,没法往前翻了"));
+// break;
+// }
+// int count = Integer.parseInt(recommendNextCount);
+// RecommandDocument document = RecommendUtil.getCategory(count-2,category);
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// setSessionAttribute("comCnt",String.valueOf(count-1));
+// detail.getAttributes().put("comCnt",String.valueOf(count-1));
+// break;
+// }
+// default:{
+// detail.setResponse(buildErrorResponse("该功能还没实现"));
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId,detail);
+// }
+//
+// private void dealOpenNumIntent(OverTimeDetail detail, String userId) {
+// String trace = getSessionAttribute("trace");
+// if (trace == null || trace.charAt(1) == '0') {
+// String numStr = getSlot("sys.number");
+// int num = 1;
+// if (numStr != null) num = Integer.parseInt(numStr);
+// detail.setResponse(dealOpenNumInHome(num, detail));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// } else if (trace.length() > 2) {
+// detail.setResponse(buildErrorResponse("客官,您在这个页面想打开啥"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// char page = trace.charAt(1);
+// switch (page){
+// case '1':
+// case '2': detail.setResponse(dealOpenNum(getSessionAttribute(PRE_COLLE), detail)); break;
+// case '3': detail.setResponse(dealOpenNumInRecommend(getSessionAttribute("recommand"),detail)); break;
+// case '4': detail.setResponse(dealOpenNumInRecommend(getSessionAttribute("recommand"),detail)); break;
+// case '5': detail.setResponse(dealOpenNumInCategory(userId, detail));break;
+// case '6': detail.setResponse(dealOpenNumInRecommend(getSessionAttribute("recommand"), detail));break;
+// default:{
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "屏幕上的图标都是可以点击的哦");
+// detail.getResponse().setOutputSpeech(outputSpeech);
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealOpenCollectIntent(OverTimeDetail detail, String userId) {
+// if (getAccessToken() == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
+// detail.setResponse(new Response(outputSpeech));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// } else {
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(userId, getAccessToken());
+// if (appUserId == null) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, SORRY_UNCATCH);
+// detail.setResponse(new Response(outputSpeech));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// }
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(), appUserId, 0);
+// if (document == null) {
+// backToHome(detail);
+// detail.setResponse(buildErrorResponse("您还没有收藏任何作品"));
+// return;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute("recommand", null);
+// setSessionAttribute(BACK_TRACE, "01");
+// setSessionAttribute("comCnt", null);
+// detail.getAttributes().put("comCnt", null);
+// detail.getAttributes().put("recommand", null);
+// detail.getAttributes().put(PRE_COLLE, document.getIdToken());
+// detail.getAttributes().put(BACK_TRACE,"01");
+// detail.getDirectives().add(render);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+// }
+//
+// private void dealLoadIntent(OverTimeDetail detail, String userId) {
+// detail.setResponse(load());
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void dealBackIntent(OverTimeDetail detail, String userId) {
+// String trace = getSessionAttribute(BACK_TRACE);
+// char second;
+// if (trace == null || trace.length() <= 2 || getQuery().contains("首")) {
+// // home page
+// backToHome(detail);
+// if (trace != null && StringUtils.endsWith(trace,File.separator)) sendCancellToTerminate(userId);
+// } else if (StringUtils.endsWith(trace,File.separator)){
+// String botAccount = trace.substring(2, trace.length()-1);
+// log.info("返回作品的id:{}", botAccount);
+// backToBotIntro(botAccount, detail);
+// sendCancellToTerminate(userId);
+// } else {
+// second = trace.charAt(1);
+// switch (second){
+// // home page
+// case '0':{
+// backToHome(detail);
+// break;
+// }
+// case '1': {
+// //collect
+// String appUserId = getSessionAttribute("userId");
+// if (appUserId == null) {
+// appUserId = DplbotServiceUtil.getUsUserId(userId, getAccessToken());
+// if (appUserId == null) {
+// backToHome(detail);
+// break;
+// }
+// }
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
+// appUserId, (count-1)*CO_HI_PAGE_SIZE);
+// if (document == null) {
+// backToHome(detail);
+// detail.setResponse(buildErrorResponse("您还未收藏过任何作品,快去收藏吧"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute(BACK_TRACE, "01");
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// detail.getAttributes().put(BACK_TRACE,"01");
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getDirectives().add(render);
+// break;
+// }
+// case '2': {
+// //history
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(), (count-1)*CO_HI_PAGE_SIZE);
+// if (document == null) {
+// backToHome(detail);
+// detail.setResponse(buildErrorResponse("哎呀,可能是您太久没玩了,历史记录已被清空"));
+// break;
+// }
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute(BACK_TRACE, "02");
+// detail.getAttributes().put(BACK_TRACE,"02");
+// detail.getAttributes().put(PRE_COLLE,document.getIdToken());
+// detail.getDirectives().add(render);
+// break;
+// }
+// case '3': {
+// //recommend
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// RecommandDocument recommandDocument = RecommendUtil.getRecommendDocument(count-1);
+// if (recommandDocument == null) {
+// RenderDocument render = new RenderDocument();
+// render.setDocument(LunchUtils.getLunchDocument());
+// addDirective(render);
+// detail.getDirectives().add(render);
+// setSessionAttribute(BACK_TRACE, null);
+// detail.getAttributes().put(BACK_TRACE, null);
+// break;
+// }
+// RenderDocument render = new RenderDocument();
+// render.setDocument(recommandDocument);
+// addDirective(render);
+// String token = recommandDocument.getRecommendIdList();
+// if (token != null) {
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// }
+// setSessionAttribute(BACK_TRACE, "03");
+// detail.getAttributes().put(BACK_TRACE, "03");
+// detail.getDirectives().add(render);
+// detail.setResponse(buildErrorResponse("已为您返回到推荐页"));
+// break;
+// }
+// case '4': {
+// //rank
+// String recommendNextCount = getSessionAttribute("comCnt");
+// int count = 1;
+// if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+// RecommandDocument recommandDocument;
+// if (count == 1) recommandDocument = RecommendUtil.getRankDocumentFirstPage();
+// else recommandDocument = RecommendUtil.getRankOtherPageDocument(count-1);
+// if (recommandDocument == null) {
+// RenderDocument render = new RenderDocument();
+// render.setDocument(LunchUtils.getLunchDocument());
+// addDirective(render);
+// detail.getDirectives().add(render);
+// setSessionAttribute(BACK_TRACE, null);
+// detail.getAttributes().put(BACK_TRACE, null);
+// break;
+// }
+// RenderDocument render = new RenderDocument();
+// render.setDocument(recommandDocument);
+// addDirective(render);
+// String token = recommandDocument.getRecommendIdList();
+// if (token != null) {
+// setSessionAttribute("recommand", token);
+// detail.getAttributes().put("recommand",token);
+// }
+// setSessionAttribute(BACK_TRACE, "04");
+// detail.getAttributes().put(BACK_TRACE, "04");
+// detail.getDirectives().add(render);
+// detail.setResponse(buildErrorResponse("已为您返回到排行榜"));
+// break;
+// }
+// case '5':{
+// String category = getSessionAttribute("category");
+// if (category == null) {
+// backToHome(detail);
+// } else {
+// String count = getSessionAttribute("comCnt");
+// int pageIndex = 0;
+// if (count != null) pageIndex = Integer.parseInt(count)-1;
+// RecommandDocument document = RecommendUtil.getCategory(pageIndex, category);
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// detail.setResponse(buildErrorResponse(new StringBuilder("已为您返回到")
+// .append(category).append("分类第").append(pageIndex+1).append("页").toString()));
+// }
+// break;
+// }
+// }
+// }
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+//
+// private void backToHome(OverTimeDetail detail) {
+// RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
+// addDirective(renderDocument);
+// setSessionAttribute(BACK_TRACE,null);
+// detail.getAttributes().put(BACK_TRACE,null);
+// detail.getDirectives().add(renderDocument);
+// }
+//
+// private void dealDefaultIntent(IntentRequest intentRequest, OverTimeDetail detail, String userId,
+// String intentName,String word) {
+// if (word == null) {
+// Query query = intentRequest.getQuery();
+// if (query != null) word = query.getOriginal();
+// if (word == null){
+// log.info("小度没有传来任何话语");
+// detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// }
+// QiWuResponse data = null;
+// try {
+// data = RequestTerminal.requestTerminate(word, userId, type);
+// } catch (Exception e) {
+// log.error("请求终端接口出错:", e.toString());
+// }
+// if (data == null) {
+// detail.setResponse(buildErrorResponse(SORRY_UNCATCH));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// String text = data.getText();
+// if ("funny".equals(intentName) || data.getAipioneerUsername().equals("4151097686")) {
+// RecommandDocument document = displayFunnyRecommandPage(text, data.getAudio());
+// if (document != null) {
+// document.getMainTemplate().getItems().get(2).setSrc(data.getAudio());
+// FUNNY_DEFAULT_DOCUMENT = document;
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// setSessionAttribute("recommand", document.getRecommendIdList());
+// setSessionAttribute(BACK_TRACE, "06");
+// detail.getAttributes().put(BACK_TRACE, "06");
+// detail.getAttributes().put("recommand", document.getRecommendIdList());
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// log.info("funny has som situation出现问题");
+// }
+//// String aside = DplbotServiceUtil.getAsideText(text);
+//// //log.info("旁白名字:{}",aside);
+//// //log.info("小悟返回:{}", text);
+//// text = text.substring(text.indexOf("】")+1);
+//
+// if (ScheduleService.getExceptBotAccount().contains(data.getAipioneerUsername())) {
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, text.substring(text.indexOf("】")+1));
+// detail.getResponse().setOutputSpeech(outputSpeech);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// final String botAccount = data.getAipioneerUsername();
+// if (botAccount == null) {
+// detail.setResponse(buildErrorResponse("不支持该作品换一个吧"));
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return;
+// }
+// String beforeBotAccount = getSessionAttribute("botAcc");
+// if (!botAccount.equals(beforeBotAccount)) {
+// DplbotServiceUtil.updateTheUserBehaviorDataMark(userId, botAccount, getAccessToken());
+// String productName = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
+//
+//// PlayDocument document = PlayUtils.getPlayDocument(correctName(productName), aside,
+//// ScheduleService.getAsideImgUrl(botAccount, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern),
+// DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botAccount);
+//
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// DplbotServiceUtil.updateTheUserHistory(userId, botAccount, getAccessToken());
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace == null || trace.length() != 2) trace = "00";
+// trace = new StringBuilder(trace).append(botAccount).append(File.separator).toString();
+// setSessionAttribute(BACK_TRACE, trace);
+// setSessionAttribute("botAcc", botAccount);
+// detail.getAttributes().put("botAcc", botAccount);
+// detail.getAttributes().put(BACK_TRACE,trace);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// } else {
+//// ExecuteCommands executeCommands = new ExecuteCommands();
+//// SetStateCommand audio = new SetStateCommand();
+//// SetStateCommand textState = new SetStateCommand();
+//// audio.setComponentId("audioCom");
+//// audio.setState("src");
+//// audio.setValue(data.getAudio());
+//// textState.setComponentId("text");
+//// textState.setState("text");
+//// textState.setValue(text);
+////
+//// SetStateCommand asideImg = new SetStateCommand();
+//// asideImg.setComponentId("asideImg");
+//// asideImg.setState("src");
+//// asideImg.setValue(ScheduleService.getAsideImgUrl(botAccount, aside));
+////
+//// SetStateCommand asideText = new SetStateCommand();
+//// asideText.setComponentId("asideText");
+//// asideText.setState("text");
+//// asideText.setValue(aside);
+////
+//// executeCommands.addCommand(audio);
+//// executeCommands.addCommand(textState);
+//// executeCommands.addCommand(asideImg);
+//// executeCommands.addCommand(asideText);
+//
+//// UpdateComponentCommand update = new UpdateComponentCommand();
+//// update.setComponentId("whole");
+//// update.setDocument(TempleUtils.getPlayUpdate(data.getAudio(), text));
+//// executeCommands.addCommand(update);
+//
+//// addDirective(executeCommands);
+//// detail.getDirectives().add(executeCommands);
+//
+// String productName = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount).getName();
+//// PlayDocument document = PlayUtils.getPlayDocument(correctName(productName), aside,
+//// ScheduleService.getAsideImgUrl(botAccount, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern),
+// DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botAccount);
+//
+// RenderDocument render = new RenderDocument(document);
+// addDirective(render);
+// detail.getDirectives().add(render);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// }
+// }
+//
+// private Response dealOpenNumInRecommend(String idsToken, OverTimeDetail overDetail) {
+// if (idsToken == null) {
+// return buildErrorResponse("请重新进入当前页面");
+// }
+// int collectNum = Integer.parseInt(getSlot("sys.number"));
+// String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
+// if (collectNum > tokenList.length || collectNum <= 0) return buildErrorResponse("这个数字超出了范围");
+// OnProductDetail detail = ScheduleService.PRODUCT_ID_DETAIL.get(tokenList[collectNum-1]);
+// if (DplbotServiceUtil.doesUserPlayed(detail.getBotAccount(), getUserId(), getAccessToken())) {
+// String productName = correctName(detail.getName());
+// return directInProduct(productName, detail.getBotAccount(), overDetail);
+// } else {
+// return enterProductInfo(detail.getName(), overDetail);
+// }
+// }
+//
+// private Response dealOpenNumInCategory(String userId, OverTimeDetail detail) {
+// String count = getSessionAttribute("comCnt");
+// int pageIndex = 0;
+// if (count != null) pageIndex = Integer.parseInt(count)-1;
+// String numStr = getSlot("sys.number");
+// int num = 1;
+// if (numStr != null) num = Integer.parseInt(numStr);
+// List categoryBots = ScheduleService.getCategoryProductIdList().get(getSessionAttribute("category"));
+// num = pageIndex*RE_RA_CA_PAGE_SIZE+num-1;
+// if (num < 0 || num >= categoryBots.size()) {
+// Response response = buildErrorResponse("这个数字超出了范围,作品的序号已显示在图片左上角");
+// detail.setResponse(response);
+// LAST_OUTTIME_RESULT.put(userId, detail);
+// return response;
+// }
+// String botId = categoryBots.get(num);
+// String name = ScheduleService.getProductIdDetail().get(botId).getName();
+// Response response;
+// if (DplbotServiceUtil.doesUserPlayed(botId, getUserId(), getAccessToken())) response = directInProduct(correctName(name), botId, detail);
+// else response = enterProductInfo(correctName(name), detail);
+// detail.setResponse(response);
+// return response;
+// }
+//
+// private Response dealOpenNumInHome(int num, OverTimeDetail detail) {
+// if (num > 0 && num <= 10) {
+// GameProjectTb bot = ScheduleService.getRecommendList().get(num-1);
+// log.info("历史:作品id:{}",bot.getBotAccount());
+// if (!DplbotServiceUtil.doesUserPlayed(bot.getBotAccount(), getUserId(), getAccessToken())) return enterProductInfo(bot.getName(), detail);
+// else return directInProduct(bot.getName(), bot.getBotAccount(), detail);
+// } else if (num > 10 && num <= 20) {
+// GameProjectTb bot = ScheduleService.getRankingList().get(num-11);
+// log.info("历史:作品id:{}",bot.getBotAccount());
+// if (!DplbotServiceUtil.doesUserPlayed(bot.getBotAccount(), getUserId(), getAccessToken())) return enterProductInfo(bot.getName(), detail);
+// else return directInProduct(bot.getName(), bot.getBotAccount(), detail);
+// } else if (num > 20 && num <= 30) {
+// String categoryName = ScheduleService.CATEGORY[num-21];
+// RecommandDocument document = RecommendUtil.getCategory(0, categoryName);
+// if (document == null) return buildErrorResponse("不好意思该分类还没有作品");
+// RenderDocument render = new RenderDocument(document);
+// this.addDirective(render);
+// detail.getDirectives().add(render);
+// this.setSessionAttribute("category",categoryName);
+// detail.getAttributes().put("category",categoryName);
+// this.setSessionAttribute("trace","05");
+// detail.getAttributes().put("trace","05");
+// return buildErrorResponse(new StringBuilder("为您打开").append(categoryName).append("类作品").toString());
+// }
+// else {
+// return buildErrorResponse("这数字超出我的范围了");
+// }
+// }
+//
+// private Response directInProduct(String name,String botId,OverTimeDetail detail) {
+// String productName = correctName(name);
+// String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
+// log.info("进入作品语句:{}", enterProductWord);
+// QiWuResponse data = null;
+// try {
+// data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
+// } catch (IOException e) {
+// log.error("请求终端接口出错:", e.toString());
+// }
+// if (data == null) {
+// return buildErrorResponse(SORRY_UNCATCH);
+// }
+// String text = data.getText();
+//// String aside = DplbotServiceUtil.getAsideText(text);
+//// text = text.substring(text.indexOf("】")+1);
+//// PlayDocument document = PlayUtils.getPlayDocument(productName, aside,ScheduleService.getAsideImgUrl(botId, aside),
+//// data.getAudio(), text);
+// Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+// PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.seperateActor(text, pattern),
+// DplbotServiceUtil.seperateActorWord(text, pattern), data.getAudio(), botId);
+//
+// RenderDocument render = new RenderDocument(document);
+// this.setSessionAttribute(PRE_COLLE, null);
+// detail.getAttributes().put(PRE_COLLE, null);
+// String trace = getSessionAttribute(BACK_TRACE);
+// if (trace == null || trace.length() != 2) trace = "00";
+// String backTrace = new StringBuilder(trace).append(botId).append(File.separator).toString();
+// this.setSessionAttribute(BACK_TRACE, backTrace);
+// detail.getAttributes().put(BACK_TRACE,backTrace);
+// this.addDirective(render);
+// detail.getDirectives().add(render);
+// return new Response();
+// }
+//
+// private Response enterProductInfo(String productName, OverTimeDetail detail) {
+// OnProductDetail productDetail = ScheduleService.PRODUCT_NAME_DETAIL.get(productName);
+// // product picture
+// String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
+//
+// // product create time
+// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+// String dateString = formatter.format(productDetail.getCreateTime());
+// String createTime = new StringBuilder(Constants.PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
+//
+// // product author
+// String author = new StringBuilder(Constants.PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
+//
+// // product labels
+// StringBuilder labels = new StringBuilder(Constants.PRODUCT_INTRO.LABEL);
+// for (String label: productDetail.getLabels()) {
+// labels.append(Constants.PRODUCT_INTRO.SPACE).append(label);
+// }
+//
+// // product introduction
+// String intro = productDetail.getIntro();
+//
+// // "start product" container button
+// String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
+//
+// String accessToken = getAccessToken();
+// String flowers, flowerReward,collectText, collectUrl, collectComId;
+// if (accessToken != null) {
+// // flower container button
+// Long count = DplbotServiceUtil.getUserSendFlowerNum(productDetail.getBotAccount(), getUserId(), accessToken);
+// flowers = USER_SEND_FLOWER+count;
+// flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
+//
+// // collection container button
+// boolean collec = DplbotServiceUtil.doesUserCollectThisBot(productDetail.getBotAccount(), accessToken, getUserId());
+// if (collec) {
+// collectText = COLLECED;
+// collectUrl = COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// } else {
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
+// }
+// } else {
+// flowers = FLOWER;
+// flowerReward = FLOWER_LOAD;
+//
+// collectText = UN_COLLEC;
+// collectUrl = UN_COLLECTED_IMG_URL;
+// collectComId = FLOWER_LOAD; // 提示登录
+// }
+//
+// ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), createTime, author, labels.toString(),
+// intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
+//
+// RenderDocument renderDocument = new RenderDocument(document);
+// this.addDirective(renderDocument);
+// detail.getDirectives().add(renderDocument);
+// String trace = getSessionAttribute(BACK_TRACE);
+// log.info("before trace------------:{}",trace);
+// StringBuilder builder = new StringBuilder();
+// if (trace == null || trace.length() < 2) {
+// builder.append("00");
+// } else if (trace.length()>2) {
+// builder.append(trace, 0, 2);
+// } else {
+// builder.append(trace);
+// }
+//
+// trace = builder.append(productDetail.getBotAccount()).toString();
+// log.info("after trace------------:{}",trace);
+// this.setSessionAttribute(BACK_TRACE, trace);
+// detail.getAttributes().put(BACK_TRACE, trace);
+// return new Response();
+// }
+//
+// private RecommandDocument displayFunnyRecommandPage(String word, String audio) {
+// try {
+// List botNames = Utils.getRecommandBotNames(word);
+// log.info("botNames:{}",botNames);
+// List bots = new ArrayList<>();
+// for (String botName : botNames) {
+// if (botName.equals("清新传")) botName = "清新传{/zhuan4/}";
+// OnProductDetail detail = ScheduleService.PRODUCT_NAME_DETAIL.get(botName);
+// if (detail == null) continue;
+// bots.add(detail);
+// }
+// if (bots.size() != 0) return RecommendUtil.getFunnyDocument(bots, audio);
+// } catch (Exception e) {
+// log.error("获取funny页出错:{}",e.toString());
+// }
+// return null;
+// }
+//
+// private XiaoDuOrderTB buildBeforePayPojo(String botAccount, String appUserId, String userId, int unitPrice,
+// long number, String orderId) {
+// XiaoDuOrderTB xiaoDuOrderTB = new XiaoDuOrderTB();
+// buildPayPojoCommon(xiaoDuOrderTB, botAccount, appUserId, userId, unitPrice, number, orderId);
+// xiaoDuOrderTB.setDevice(1);
+// return xiaoDuOrderTB;
+// }
+//
+// private XiaoDuOrderTB buildNoScreenBeforePayPojo(String botAccount, String appUserId, String userId, int unitPrice,
+// long number, String orderId) {
+// XiaoDuOrderTB xiaoDuOrderTB = new XiaoDuOrderTB();
+// buildPayPojoCommon(xiaoDuOrderTB, botAccount, appUserId, userId, unitPrice, number, orderId);
+// xiaoDuOrderTB.setDevice(2);
+// return xiaoDuOrderTB;
+// }
+//
+// private void buildPayPojoCommon(XiaoDuOrderTB xiaoDuOrderTB, String botAccount, String appUserId, String userId, int unitPrice,
+// long number, String orderId) {
+// xiaoDuOrderTB.setBotId(botAccount);
+// xiaoDuOrderTB.setAppUserId(appUserId);
+// xiaoDuOrderTB.setXiaoduUserId(userId);
+// xiaoDuOrderTB.setUnitPrice(unitPrice);
+// xiaoDuOrderTB.setNumber(number);
+// xiaoDuOrderTB.setIsBuy(false);
+// xiaoDuOrderTB.setStatus(false);
+// xiaoDuOrderTB.setChOrderId(orderId);
+// xiaoDuOrderTB.setTimeStamp(curTime);
+// }
+//
+// @Override
+// protected Response onChargeEvent(ChargeEvent chargeEvent) {
+// String token = chargeEvent.getToken();
+// int sepIndex = token.indexOf(File.separator);
+// final String botAccount = token.substring(0, sepIndex);
+// String str = "恭喜您支付成功,开始体验吧";
+// if (getRequest().getContext().getScreen() != null) {
+// boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, customUserId(), getAccessToken(),
+// getSessionAttribute("userId"), PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_screen");
+// if (response) {
+// HashMap flowerRecords = DplbotServiceUtil.USER_HISTORY.get(getUserId()).getUserBotId2Flowers();
+// Long before = flowerRecords.get(botAccount);
+// if (before == null) before = 0L;
+// flowerRecords.put(botAccount, before+1);
+// ExecuteCommands executeCommands = new ExecuteCommands();
+// SetStateCommand stateCommand = new SetStateCommand();
+// stateCommand.setComponentId("pft");
+// stateCommand.setState("text");
+// stateCommand.setValue(USER_SEND_FLOWER+before);
+// executeCommands.addCommand(stateCommand);
+// try {
+// addDirective(executeCommands);
+// } catch (Exception e) {
+// log.info(ExceptionUtils.getStackTrace(e));
+// }
+// } else {
+// str = "很抱歉,您没有支付成功";
+// }
+// } else {
+// String userId = customUserId();
+// String jytUserId = getSessionAttribute("userId");
+// if (StringUtils.isBlank(jytUserId)) jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken());
+// if (StringUtils.isBlank(jytUserId)) {
+// jytUserId = "null";
+// }
+// boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, userId, getAccessToken(),
+// jytUserId, PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_no_screen");
+// if (!response) {
+// str = "很抱歉,您没有支付成功";
+// }
+// }
+// return buildErrorResponse(str);
+// }
+//
+// @Override
+// protected Response onPlaybackFinishedEvent(PlaybackFinishedEvent playbackFinishedEvent) {
+//// log.info("音频播放完毕,开麦");
+//// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+// this.setExpectSpeech(true);
+//// log.error("FinishedEvent");
+// return new Response();
+// }
+//
+// @Override
+// protected Response onPlaybackStoppedEvent(PlaybackStoppedEvent playbackStoppedEvent) {
+//// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+// waitAnswer();
+// return new Response();
+// }
+//
+// @Override
+// protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
+//// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+// USERID_AUDIO_PATH.remove(customUserId());
+// waitAnswer();
+// return new Response();
+// }
+//
+// @Override
+// protected Response onPlaybackNearlyFinishedEvent(PlaybackNearlyFinishedEvent playbackNearlyFinishedEvent) {
+//// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+// waitAnswer();
+// return new Response();
+// }
+//
+// private String customUserId() {
+// try {
+// return PREFIX_USERID+ URLEncoder.encode(getUserId(), "UTF-8");
+// } catch (Exception e) {
+// return PREFIX_USERID+ getUserId().replaceAll("/", "");
+// }
+//// return PREFIX_USERID + ai.qiwu.com.xiaoduhome.xiaoai.common.Utils.modifyDeviceId(getUserId());
+//// return PREFIX_USERID + getUserId().replaceAll(NUM_OR_ALPHA, "");
+// }
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotServiceBoth.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotServiceBoth.java
new file mode 100644
index 0000000..beb0904
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotServiceBoth.java
@@ -0,0 +1,2249 @@
+package ai.qiwu.com.xiaoduhome.service;
+
+import ai.qiwu.com.xiaoduhome.common.BaseHolder;
+import ai.qiwu.com.xiaoduhome.common.Constants;
+import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
+import ai.qiwu.com.xiaoduhome.common.Utils;
+import ai.qiwu.com.xiaoduhome.common.temple.CollectHistoryDocument;
+import ai.qiwu.com.xiaoduhome.common.temple.TempleUtils;
+import ai.qiwu.com.xiaoduhome.common.temple.onLunch.LunchUtils;
+import ai.qiwu.com.xiaoduhome.common.temple.play.PlayDocument;
+import ai.qiwu.com.xiaoduhome.common.temple.play.PlayUtils;
+import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoDocument;
+import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoUtils;
+import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommandDocument;
+import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommendUtil;
+import ai.qiwu.com.xiaoduhome.entity.primary.GameProjectTb;
+import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail;
+import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB;
+import ai.qiwu.com.xiaoduhome.pojo.*;
+import ai.qiwu.com.xiaoduhome.pojo.data.ProjectData;
+import ai.qiwu.com.xiaoduhome.pojo.dpl.MyDocument;
+import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository;
+import ai.qiwu.com.xiaoduhome.spirit.SpiritRedisService;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.baidu.dueros.bot.BaseBot;
+import com.baidu.dueros.data.request.IntentRequest;
+import com.baidu.dueros.data.request.LaunchRequest;
+import com.baidu.dueros.data.request.Query;
+import com.baidu.dueros.data.request.SessionEndedRequest;
+import com.baidu.dueros.data.request.audioplayer.event.*;
+import com.baidu.dueros.data.request.events.LinkAccountSucceededEvent;
+import com.baidu.dueros.data.request.pay.event.ChargeEvent;
+import com.baidu.dueros.data.response.OutputSpeech;
+import com.baidu.dueros.data.response.Reprompt;
+import com.baidu.dueros.data.response.card.*;
+import com.baidu.dueros.data.response.directive.Directive;
+import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective;
+import com.baidu.dueros.data.response.directive.audioplayer.Play;
+import com.baidu.dueros.data.response.directive.display.PushStack;
+import com.baidu.dueros.data.response.directive.dpl.ExecuteCommands;
+import com.baidu.dueros.data.response.directive.dpl.RenderDocument;
+import com.baidu.dueros.data.response.directive.dpl.commands.SetStateCommand;
+import com.baidu.dueros.data.response.directive.dpl.commands.UpdateComponentCommand;
+import com.baidu.dueros.data.response.directive.dpl.event.UserEvent;
+import com.baidu.dueros.data.response.directive.pay.Charge;
+import com.baidu.dueros.model.Response;
+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.apache.commons.lang3.exception.ExceptionUtils;
+import org.springframework.data.redis.core.StringRedisTemplate;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.File;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.regex.Pattern;
+
+import static ai.qiwu.com.xiaoduhome.common.Constants.*;
+import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.*;
+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.WelcomeWord.*;
+import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.BEARER;
+import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.FLOWER_INTERFACE;
+import static ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil.USER_HISTORY;
+import static ai.qiwu.com.xiaoduhome.service.ScheduleService.*;
+
+/**
+ * @author mqw
+ */
+@Slf4j
+public class DplBotServiceBoth extends BaseBot {
+ private static final MyDocument FIRST_PAGE;
+
+ private static final ConcurrentHashMap LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
+
+ static {
+ FIRST_PAGE = JSON.parseObject(DplbotServiceUtil.getDPLTemple("static/json/firstPage.json"), MyDocument.class);
+ }
+
+ 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 final int type;
+
+ private final static Reprompt WAIT_WORD = new Reprompt(new OutputSpeech(OutputSpeech.SpeechType.PlainText, "晓悟正在等你的回复"));
+
+// private final RedisTemplate redisTemplate;
+
+// private final RedisTemplate redisTemplate;
+
+ private final StringRedisTemplate stringRedisTemplate;
+
+ private final String channel;
+
+ public DplBotServiceBoth(HttpServletRequest request, Integer type,StringRedisTemplate stringRedisTemplate) throws IOException {
+ super(request);
+ this.type = type;
+ switch (type) {
+ case 1: channel = "jiaoyou-audio-child-test";break;
+ case 2: channel = "jiaoyou-audio-adult-test";break;
+ case 5: channel = "jiaoyou-audio-test";break;
+ default: channel = "baidu-screen-jiaoyou-audio-test";
+ }
+ this.stringRedisTemplate = stringRedisTemplate;
+ //privateKey为私钥内容,0代表你的Bot在DBP平台debug环境,1或者其他整数代表online环境,
+ // botMonitor对象已经在bot-sdk里初始化,可以直接调用
+// this.botMonitor.setEnvironmentInfo(PRIVATE_KEY, 1);
+// this.botMonitor.setMonitorEnabled(true);
+ }
+
+ @Override
+ public Response onLaunch(LaunchRequest launchRequest) {
+ if (getRequest().getContext().getScreen() == null) {
+// String userId = customUserId();
+ stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+customUserId());
+ String welcomeWord;
+ String skillName;
+ String num = RandomStringUtils.randomNumeric(3);
+ switch (type) {
+ case 1 : {
+// welcomeWord = WELCOME_SMART_FORMAT;
+// try {
+// List botList = channel2Bots.get("jiaoyou-audio-child-test");
+// String name = botList.get(Integer.parseInt(num)%botList.size());
+// welcomeWord = String.format(welcomeWord, name,name);
+// } catch (Exception e) {
+// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+// welcomeWord = WELCOME_SMART;
+// }
+ welcomeWord = WELCOME_SMART;
+ skillName = SKILL_SMART;
+ break;
+ }
+ case 2 : {
+// welcomeWord = WELCOME_NOVEL_FORMAT;
+// try {
+// List botList = channel2Bots.get("jiaoyou-audio-adult-test");
+// String name = botList.get(Integer.parseInt(num)%botList.size());
+// welcomeWord = String.format(welcomeWord, name,name);
+// } catch (Exception e) {
+// log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+// welcomeWord = WELCOME_NOVEL;
+// }
+ welcomeWord = WELCOME_NOVEL;
+ skillName = SKILL_NOVEL;
+ break;
+ }
+ case 3 : welcomeWord = WelcomeWord.WELCOME_STORY; skillName = SKILL_STORY; break;
+ case 4 : welcomeWord = WelcomeWord.WELCOME_LITERATURE; skillName = SKILL_LITERATURE; break;
+ default: {
+ welcomeWord = WELCOME_FORMAT;
+ try {
+ List botList = jiaoyouChannel2Bots.get("jiaoyou-audio-adult-test");
+ String name = botList.get(Integer.parseInt(num)%botList.size());
+ welcomeWord = String.format(welcomeWord, name,name);
+ } catch (Exception e) {
+ log.error("onLaunch welcomeWord type:{}, error:{}", type, e);
+ welcomeWord = WELCOME;
+ }
+ skillName = SKILL;
+ break;
+ }
+ }
+ StandardCard standardCard = new StandardCard(skillName, welcomeWord);
+ standardCard.setImage(FIRST_IMAGE);
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord);
+ return new Response(outputSpeech, standardCard);
+ } else {
+ RenderDocument renderDocument = new RenderDocument(FIRST_PAGE);
+ this.addDirective(renderDocument);
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, Constants.WelcomeWord.WELCOME);
+ // 初次进入时创建用户的行为信息,包括历史记录,送花数,收藏记录
+ // 历史记录,收藏记录,送花数,郊游天下id
+ String accessToken = getAccessToken();
+ String userId = getUserId();
+ UserBehaviorData data;
+ if ((data= USER_HISTORY.get(userId)) == null) {
+ if (accessToken == null) {
+ DplbotServiceUtil.onLunchFillUserBehaviorData(userId, channel, null);
+ } else {
+ userId=DplbotServiceUtil.getUserIdByToken(accessToken, channel);
+ if (StringUtils.isNotBlank(userId)) {
+ DplbotServiceUtil.onLunchFillUserBehaviorData(userId, channel, userId);
+ }
+ }
+ } else if (accessToken != null && data.getJytUserId() == null){
+ userId=DplbotServiceUtil.getUserIdByToken(accessToken, channel);
+ if (StringUtils.isNotBlank(userId)) data.setJytUserId(userId);
+ }
+ return new Response(outputSpeech);
+ }
+ }
+
+ @Override
+ protected Response onInent(IntentRequest intentRequest) {
+ final String userId = customUserId();
+ String redisId = SpiritRedisService.PREFIX_REDIS+userId;
+ if (getRequest().getContext().getScreen() == null) {
+// final String deviceUserId = PREFIX_USERID + getDeviceId();
+
+ try {
+ String data = stringRedisTemplate.opsForValue().get(redisId);
+ if (StringUtils.isNotBlank(data)) {
+ log.info("超时redis获取信息:"+data);
+ String redisIdleId = SpiritRedisService.PREFIX_REDIS_IDLE+userId;
+ if (data.equals("out")) {
+ String idleNum = stringRedisTemplate.opsForValue().get(redisIdleId);
+ boolean firstIdle;
+ if ((firstIdle = StringUtils.isBlank(idleNum)) || idleNum.equals("1")) {
+ try {
+ Thread.sleep(2000);
+ } catch (Exception e){}
+ data = stringRedisTemplate.opsForValue().get(redisId);
+ if (StringUtils.isNotBlank(data) && !data.equals("out")) {
+ stringRedisTemplate.delete(redisIdleId);
+ stringRedisTemplate.delete(redisId);
+ Directive play = buildNoScreenPlayDirec(dealAudioUrl(data), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+ addDirective(play);
+ return new Response();
+ }
+ if (firstIdle) idleNum = "1";
+ else idleNum = "2";
+ stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 10, TimeUnit.SECONDS);
+ return buildErrorResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
+ XiaoAiConstants.TTS.WAIT_WORD_2);
+ } else {
+ stringRedisTemplate.delete(redisIdleId);
+ stringRedisTemplate.delete(redisId);
+ }
+ } else {
+ stringRedisTemplate.delete(redisId);
+ stringRedisTemplate.delete(redisIdleId);
+ Directive play = buildNoScreenPlayDirec(dealAudioUrl(data), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+ addDirective(play);
+ return new Response();
+ }
+ }
+ } catch (Exception e) {
+ log.error("xiaodu redis error:"+e);
+ }
+
+ try {
+ Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId));
+ return future.get(2700, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | ExecutionException e) {
+ log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
+ return buildErrorResponse(SORRY_UNCATCH);
+ } catch (TimeoutException e) {
+ log.info("超时,让用户再说一遍:{}",e.toString());
+ stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 10, TimeUnit.SECONDS);
+ return buildErrorResponse(SORRY_UNCATCH);
+ } catch (Exception all) {
+ log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
+ return buildErrorResponse(SORRY_UNCATCH);
+ }
+ } else {
+
+ try {
+ Future future = DplbotServiceUtil.getPOOL().submit(() -> dealDefaultIntent(intentRequest, getUserId(),
+ null, channel));
+ return 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());
+ return buildErrorResponse(SORRY_UNCATCH);
+ } catch (Exception all) {
+ log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
+ return buildErrorResponse(SORRY_UNCATCH);
+ }
+ }
+ }
+
+ private Response dealNoScreenIntentTemp(IntentRequest intentRequest, String userId) {
+ String intentName = getIntent().getName();
+ if ("sendFlower".equals(intentName)) {
+ return dealNoScreenSendFlowerIntent(userId, null);
+ } else if ("load".equals(intentName)) {
+ Card card = new LinkAccountCard();
+ Response response = buildErrorResponse("请在小度App上完成登录");
+ response.setCard(card);
+ return response;
+ }
+
+ try {
+ final Query query = intentRequest.getQuery();
+ final String userWord = query.getOriginal();
+// if (query != null) userWord = query.getOriginal();
+ if (userWord == null){
+ log.error("小度没有传来任何话语");
+ return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+ }
+// log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId());
+
+ String channel;
+ switch (type) {
+ case 1 :
+ case 3 : channel = "jiaoyou-audio-child-test";break;
+ case 2 :
+ case 4 : channel = "jiaoyou-audio-adult-test";break;
+ default: channel = "jiaoyou-audio-test";break;
+ }
+ String response = RequestTerminal.requestTerminateTemp(userWord, userId, channel);
+ log.info("小度,小悟返回:{},",response);
+ if (StringUtils.isBlank(response)) {
+ return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+ }
+// String mark = RandomStringUtils.randomAlphabetic(3);
+// AudioBoxData pathData = new AudioBoxData();
+// OkHttp3Utils.asyncPost(XiaoAiConstants.TTS_DIDI3, response, pathData);
+ try {
+ JSONObject object = JSON.parseObject(response);
+ JSONArray commands = object.getJSONArray("commands");
+ if (commands != null && commands.size() != 0) {
+ String txt;
+ for (Object ob: commands) {
+ txt = ((JSONObject) ob).getString("text");
+ int i;
+ if (StringUtils.isNotBlank(txt) && (i=txt.indexOf("out")) != -1) {
+ log.info("小度,推荐bot退出:{},{}",userWord,userId);
+ String content = txt.substring(i+3, txt.indexOf("☚")).trim();
+ String byeWord = null;
+ String skillName = null;
+ switch (type) {
+ case 1: {
+ byeWord = EndMsg.END_BYE_STORY;
+ skillName = SKILL_SMART;
+ break;
+ }
+ case 2: {
+ byeWord = EndMsg.END_BYE_NOVEL;
+ skillName = SKILL_NOVEL;
+ break;
+ }
+ case 5: {
+ byeWord = EndMsg.END_BYE_JIAOYOU;
+ skillName = SKILL;
+ break;
+ }
+ }
+ if (byeWord == null) byeWord = EndMsg.END_BYE_Adult;
+ if (skillName == null) skillName = SKILL_DEFAULT;
+ if (StringUtils.isBlank(content)) {
+ JSONArray dialogs = object.getJSONArray("dialogs");
+ if (dialogs != null && dialogs.size() != 0) {
+ String str = ((JSONObject)dialogs.get(0)).getString("text");
+ if (StringUtils.isNotBlank(str)) {
+ str = str.replaceAll("\\{/.*?/}", "")+skillName;
+ RequestTerminal.backRequest(userId, type);
+ return buildLogOutResponse(str);
+ }
+ }
+ RequestTerminal.backRequest(userId, type);
+ return buildLogOutResponse(byeWord);
+ } else {
+ content = content.replaceAll("\\{/.*?/}", "")+skillName;
+ RequestTerminal.backRequest(userId, type);
+ return buildLogOutResponse(content);
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("推荐bot退出解析出错:"+e);
+ }
+// String path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
+ String path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", response);
+ if (StringUtils.isBlank(path) || "null".equals(path)) {
+ log.error("小度没有获取到音频链接");
+ return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+ }
+// final JSONObject ob = JSONObject.parseObject(response);
+// String botAcc = ob.getString("aipioneerUsername");
+// String beforeBotAccount = getSessionAttribute("botAcc");
+// if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(botAcc)) {
+// setSessionAttribute("botAcc", botAcc);
+// data.getAttributes().put("botAcc",botAcc);
+// }
+
+ Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+ addDirective(play);
+// if (userId.equals(DU_DEVICE_ID)) {
+// DplbotServiceUtil.getPOOL().submit(() -> {
+// JSONArray array = ob.getJSONArray("dialogs");
+// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+// for (Object item: array) {
+// String str = ((JSONObject) item).getString("text");
+// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+// }
+// WebSocketLog.sendInfo(builder.toString(), "du1");
+// });
+// } else {
+// DplbotServiceUtil.getPOOL().submit(() -> {
+// JSONArray array = ob.getJSONArray("dialogs");
+// StringBuilder builder = new StringBuilder(userWord).append(File.separator);
+// for (Object item: array) {
+// String str = ((JSONObject) item).getString("text");
+// builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
+// }
+// WebSocketLog.sendInfo(builder.toString(), "du2");
+// });
+// }
+ log.info("Redis 写入:"+path);
+ stringRedisTemplate.opsForValue().set(SpiritRedisService.PREFIX_REDIS+userId, path, 10, TimeUnit.SECONDS);
+ return new Response();
+ } catch (Exception e) {
+ log.warn("中控返回结果为空:"+e);
+ return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+ }
+ }
+
+ private String dealAudioUrl(String path) {
+// return Constants.TTS_DIDI3_GET+path;
+ return "http://didi-gz5.jiaoyou365.com:9663/api/audio/get?path="+path;
+ }
+
+ private Response dealNoScreenSendFlowerIntent(String userId, String channelId) {
+ if (getAccessToken() == null) {
+ return buildErrorResponse("该功能需要登录");
+ }
+ String num = getSlot("sys.number");
+ OutputSpeech outputSpeech;
+ String confirmationStatus = getIntent().getConfirmationStatus().name();
+ log.info("槽位确认状态:{}",confirmationStatus);
+ if ("NONE".equals(confirmationStatus)) {
+ if (num == null) {
+ log.info("确认送花个数");
+ ask("sys.number");
+ outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请问您要送几朵花");
+ setExpectSpeech(true);
+ } else {
+ log.info("确认最终送花意图");
+ setConfirmIntent();
+ outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText,
+ new StringBuilder("您要送").append(num).append("朵花是吗").toString());
+ setExpectSpeech(true);
+ }
+ return new Response(outputSpeech);
+ } else if ("CONFIRMED".equals(confirmationStatus)) {
+ log.info("确认");
+ int unitPrice = Integer.parseInt(ScheduleService.FLOWER_UNIT_PRICE);
+ String amount = String.valueOf(unitPrice*Integer.parseInt(num)/100.0);
+ String orderId = userId + System.currentTimeMillis();
+ String appUserId = getSessionAttribute("userId");
+ if (appUserId == null) {
+ if (channelId == null) appUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken(), null);
+ else appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken(), channelId);
+ if (appUserId == null) {
+ log.error("送花时获取用户app_user_id失败");
+ return buildErrorResponse("不好意思出了点问题,请再说一遍吧");
+ }
+ }
+ String botId = getSessionAttribute("botAcc");
+ if (StringUtils.isNotBlank(botId)) {
+ XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
+ XiaoDuOrderTB response = repository.save(buildNoScreenBeforePayPojo(botId, appUserId, userId, unitPrice,
+ Integer.parseInt(num), orderId));
+
+ if (response != null && response.getId() != null) {
+ String desc = new StringBuilder("感谢您赏赐给该作品的").append(num).append("朵鲜花").toString();
+ String name = ScheduleService.PRODUCT_ID_DETAIL.get(botId).getName();
+ if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
+ .append("的").append(num).append("朵鲜花").toString();
+ Charge charge = new Charge(amount, orderId, num+"朵鲜花", desc);
+ charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
+ addDirective(charge);
+ return buildErrorResponse("请到小度APP上完成支付");
+ } else {
+ log.error("订单没有插入到xioadu_order_tb");
+ return buildErrorResponse(ERROR_SEND_FLOWER);
+ }
+ }else {
+ log.error("无法获取到botID");
+ return buildErrorResponse("只能在作品里才可以送花");
+ }
+ } else {
+ log.info("否定");
+ return buildErrorResponse("好的,已为您终止");
+ }
+ }
+
+ private Play buildNoScreenPlayDirec(String audioUrl, AudioPlayerDirective.PlayBehaviorType type) {
+ return new Play(type, audioUrl, 0);
+ }
+
+ /**
+ *
+ * @param idsToken 当前页面作品的id集合
+ * @return
+ */
+ private Response dealOpenNum(String idsToken, int collectNum) {
+ String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
+ String botID = tokenList[collectNum-1];
+ ProjectData detail = ScheduleServiceNew.getProjectByBotAccount(botID);
+ String productName = correctName(detail.getName());
+ String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
+ log.info("进入作品语句:{}", enterProductWord);
+ String data = null;
+ try {
+ data = RequestTerminal.requestTerminateTemp(enterProductWord, getUserId(), channel);
+ } catch (IOException e) {
+ log.error("请求终端接口出错:", e.toString());
+ }
+ if (data == null) {
+ return buildErrorResponse(SORRY_UNCATCH);
+ }
+
+
+ String path = null;
+ try {
+ path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
+ } catch (Exception e) {
+ log.warn("没有获取到TTS返回地址");
+ }
+ if (StringUtils.isBlank(path) || "null".equals(path)) {
+ log.error("小度没有获取到音频链接");
+ return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+ }
+ PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.getTheActorsWithWords(JSON.parseObject(data).getJSONArray("dialogs")),
+ dealAudioUrl(path), botID);
+ RenderDocument render = new RenderDocument(document);
+ this.setSessionAttribute(PRE_COLLE, null);
+ String trace = getSessionAttribute(BACK_TRACE);
+ if (trace == null || trace.length() != 2) trace = "00";
+ String backTrace = new StringBuilder(trace).append(detail.getBotAccount()).append(File.separator).toString();
+ this.setSessionAttribute(BACK_TRACE, backTrace);
+ this.addDirective(render);
+ return new Response();
+ }
+
+ @Override
+ protected Response onUserEvent(UserEvent userEvent) {
+ try {
+ //log.info("onUserEvent事件触发,token:{}, componentId:{}",userEvent.getToken(),userEvent.getPayload().getComponentId());
+ if (getAccessToken() != null && getSessionAttribute("userId") == null) {
+ String userId = DplbotServiceUtil.getUsUserId(getUserId(),getAccessToken(), channel);
+ setSessionAttribute("userId", userId);
+ }
+ String componentId = userEvent.getPayload().getComponentId();
+ String componentPrefix;
+ if ("audio".equals(componentId)){
+ setExpectSpeech(true);
+ }
+ else if (Constants.PRE_PRODUCT_IMG.equals((componentPrefix = componentId.substring(0, 5)))) {
+ // 作品图片点击事件
+ log.info("图片点击触发");
+ String accessToken = getAccessToken();
+ String userId = getUserId();
+ String productName = componentId.substring(5);
+
+ ProjectData productDetail = ScheduleServiceNew.getProjectByName(productName);
+ if (productDetail == null) {
+ return buildErrorResponse("目前不支持该作品");
+ }
+ String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
+
+ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+ String dateString = formatter.format(productDetail.getCreateTime());
+ String time = new StringBuilder(PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
+ String author = new StringBuilder(PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
+ StringBuilder labels = new StringBuilder(PRODUCT_INTRO.LABEL);
+ for (String label: productDetail.getLabels()) {
+ labels.append(PRODUCT_INTRO.SPACE).append(label);
+ }
+ String intro = productDetail.getIntro();
+ String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
+
+ // "start product" container button
+ String flowers, flowerReward,collectText, collectUrl, collectComId;
+ if (accessToken != null) {
+ // flower container button
+ Long flowerCount = DplbotServiceUtil.getUserSendFlowerNum(productDetail.getBotAccount(), userId,
+ channel,accessToken, getSessionAttribute("userId"));
+ flowers = USER_SEND_FLOWER+flowerCount;
+ flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
+
+ // collection container button
+ boolean collec = DplbotServiceUtil.didUserCollecThisProduct(productDetail.getBotAccount(), userId,
+ accessToken, getSessionAttribute("userId"));
+ if (collec) {
+ collectText = COLLECED;
+ collectUrl = COLLECTED_IMG_URL;
+ collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
+ } else {
+ collectText = UN_COLLEC;
+ collectUrl = UN_COLLECTED_IMG_URL;
+ collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
+ }
+ } else {
+ flowers = FLOWE;
+ flowerReward = FLOWER_LOAD;
+
+ collectText = UN_COLLEC;
+ collectUrl = UN_COLLECTED_IMG_URL;
+ collectComId = FLOWER_LOAD;
+ }
+
+ ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), time, author, labels.toString(),
+ intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
+
+ RenderDocument renderDocument = new RenderDocument(document);
+ this.addDirective(renderDocument);
+ //this.addDirective(new PushStack());
+ String trace = getSessionAttribute(BACK_TRACE);
+ log.info("before trace------------:{}",trace);
+ StringBuilder builder = new StringBuilder();
+ if (trace == null || trace.length() < 2) {
+ builder.append("00");
+ } else if (trace.length()>2) {
+ builder.append(trace, 0, 2);
+ } else {
+ builder.append(trace);
+ }
+
+ trace = builder.append(productDetail.getBotAccount()).toString();
+ log.info("after trace------------:{}",trace);
+ this.setSessionAttribute(BACK_TRACE, trace);
+ return new Response();
+ } else if (Constants.PRE_ENTER_PRODUCT.equals(componentPrefix)) {
+ String productName = componentId.substring(5);
+ String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
+ log.info("进入作品语句:{}", enterProductWord);
+ String data = null;
+ try {
+ data = RequestTerminal.requestTerminateTemp(enterProductWord, getUserId(), channel);
+ } catch (IOException e) {
+ log.error("请求终端接口出错:", e.toString());
+ }
+ if (data == null) {
+ return buildErrorResponse(SORRY_UNCATCH);
+ }
+
+ String path = null;
+ try {
+ path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
+ } catch (Exception e) {
+ log.warn("没有获取到TTS返回地址");
+ }
+ if (StringUtils.isBlank(path) || "null".equals(path)) {
+ log.error("小度没有获取到音频链接");
+ return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+ }
+ String botID = ScheduleServiceNew.getProjectByName(productName).getBotAccount();
+ PlayDocument document = PlayUtils.getPlayDocument(productName,
+ DplbotServiceUtil.getTheActorsWithWords(JSON.parseObject(data).getJSONArray("dialogs")),
+ dealAudioUrl(path), botID);
+
+ RenderDocument render = new RenderDocument(document);
+ this.setSessionAttribute(PRE_COLLE, null);
+ String trace = getSessionAttribute(BACK_TRACE);
+ if (trace == null || trace.length()<2) trace = "00";
+ else if (trace.length()>2) trace = trace.substring(0,2);
+ String botAccount = ScheduleServiceNew.getProjectByName(productName).getBotAccount();
+ this.setSessionAttribute(BACK_TRACE, new StringBuilder(trace).append(botAccount).append(File.separator).toString());
+ this.addDirective(render);
+ } else if (FLOWE.equals(componentPrefix)) {
+ if (FLOWER_LOAD.equals(componentId)) {
+ return load();
+ } else {
+// Buy buy = new Buy(FLOWER_PRODUCT_ID);
+// String token = new String(Base64.getEncoder().encode(componentId.substring(5).getBytes()), StandardCharsets.UTF_8);
+// buy.setToken(token);
+// addDirective(buy);
+// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, REWARD_FLOWER);
+// return new Response(outputSpeech);
+ Charge charge = DplbotServiceUtil.sendOneFlowerByCharge(getUserId(), getSessionAttribute("userId"),
+ getAccessToken(), getSessionAttribute("trace"),channel);
+ if (charge != null) {
+ addDirective(charge);
+ return buildErrorResponse("扫描屏幕上的二维码完成支付");
+ }
+ return new Response();
+ }
+ } else if ("loadingPage".equals(componentId)) {
+ RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
+ this.addDirective(new PushStack());
+ this.addDirective(renderDocument);
+ return new Response();
+ } else if (PRE_COLLE.equals(componentPrefix)) {
+ boolean isUnCollect = "Un".equals(componentId.substring(5,7));
+ final String botId = componentId.substring(7);
+ if (isUnCollect) {
+ //取消收藏
+ DplbotServiceUtil.userUnCollectTheBot(getUserId(), botId, channel, getSessionAttribute("userId"), getAccessToken());
+ changeIconIdTextAfterCollect(false, botId);
+ } else {
+ //收藏
+ DplbotServiceUtil.userCollectTheBot(getUserId(), botId, channel, getSessionAttribute("userId"),getAccessToken());
+ changeIconIdTextAfterCollect(true, botId);
+ }
+ } else if (PRE_CATEGORY.equals(componentPrefix)) {
+ String category = componentId.substring(5);
+ // 分类推荐页面相同
+ RecommandDocument document = RecommendUtil.getCategory(0, category);
+ if (document == null) return buildErrorResponse("不好意思该分类还没有作品");
+ RenderDocument render = new RenderDocument(document);
+ this.addDirective(render);
+ this.setSessionAttribute("category",category);
+ this.setSessionAttribute("trace","05");
+ } else if ("playButton".equals(componentId)) {
+ return buildErrorResponse("您可以直接对我说我要送花或者我要收藏或取消收藏");
+ } else if ("lunchCollect".equals(componentId)) {
+ return dealOpenCollectClick();
+ } else if ("lunchHistory".equals(componentId)) {
+ return dealHistoryClick();
+ }
+// else if ("funnyChange".equals(componentId)) {
+// ExecuteCommands executeCommands = new ExecuteCommands();
+// AutoPageCommand page = new AutoPageCommand();
+// page.setComponentId("funnyPage");
+// page.setDurationInMillisecond(2000);
+// executeCommands.addCommand(page);
+// this.addDirective(executeCommands);
+// }
+ } catch (Exception e) {
+ log.error("onUserEvent error:{}", ExceptionUtils.getStackTrace(e));
+ }
+ return new Response();
+ }
+
+ @Override
+ protected Response onSessionEnded(SessionEndedRequest sessionEndedRequest) {
+ switch (sessionEndedRequest.getReason()) {
+ case ERROR: dealWithError(sessionEndedRequest); break;
+ case USER_INITIATED: log.info(EndMsg.USER_SAY_CANCEL); break;
+ case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break;
+ }
+ if (getRequest().getContext().getScreen() == null) {
+ String userId = customUserId();
+ String byeWord = EndMsg.END_BYE_Adult;
+ switch (type) {
+ case 2: byeWord = EndMsg.END_BYE_NOVEL;break;
+ case 1: byeWord = EndMsg.END_BYE_STORY;break;
+ case 3: byeWord = EndMsg.END_BYE_CHILD;break;
+ case 5: byeWord = EndMsg.END_BYE_JIAOYOU;break;
+ }
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
+ RequestTerminal.backRequest(userId, type);
+// try {
+// if (DU_DEVICE_ID.equals(deviceId)) {
+// RequestTerminal.backRequest(DU_DEVICE_ID, type);
+// } else {
+// RequestTerminal.backRequestDU2(deviceId, type);
+// }
+// } catch (Exception e) {
+// log.warn("用户退出向中控发出退出指令出错");
+// }
+ return new Response(outputSpeech);
+ }
+ DplbotServiceUtil.writeTheUserHistoryInData(getUserId());
+// LAST_OUTTIME_RESULT.remove(getUserId());
+ return new Response();
+ }
+
+ private void dealWithError(SessionEndedRequest request) {
+ switch (request.getError().getType()) {
+ case INTERNAL_ERROR: log.info(ErrorMsg.INTERNAL_ERROR); break;
+ case INVALID_RESPONSE: log.info(ErrorMsg.INVALID_RESPONSE); break;
+ case DEVICE_COMMUNICATION_ERROR: log.info(ErrorMsg.DEVICE_COMMUNICATION_ERROR); break;
+ }
+ log.info("错误信息 : "+ request.getError().getMessage());
+ }
+
+ private Response dealHistoryClick() {
+ CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(),
+ getSessionAttribute("userId"), 0, channel);
+ if (document == null) return buildErrorResponse("不好意思,您太久没玩记录被清空了");
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ setSessionAttribute(PRE_COLLE,document.getIdToken());
+ setSessionAttribute("recommand", null);
+ setSessionAttribute("comCnt", null);
+ setSessionAttribute(BACK_TRACE, "02");
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开历史记录");
+ return new Response(outputSpeech);
+ }
+
+ private Response dealOpenCollectClick() {
+ if (getAccessToken() == null) {
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
+ return new Response(outputSpeech);
+ } else {
+ String appUserId = getSessionAttribute("userId");
+ if (appUserId == null) {
+ appUserId = DplbotServiceUtil.getUsUserId(getUserId(), getAccessToken(), channel);
+ if (appUserId == null) {
+ return new Response();
+ }
+ }
+ CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(getUserId(), getAccessToken(),
+ appUserId, 0, channel);
+ if (document != null) {
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ setSessionAttribute("comCnt", null);
+ setSessionAttribute(PRE_COLLE,document.getIdToken());
+ setSessionAttribute(BACK_TRACE, "01");
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开收藏夹");
+ return new Response(outputSpeech);
+ }
+ }
+ return new Response();
+ }
+
+// @Override
+// protected Response onBuyEvent(BuyEvent buyEvent) {
+// com.baidu.dueros.data.request.buy.event.JYTUserResponse payload = buyEvent.getPayload();
+// String result = payload.getPurchaseResult().getPurchaseResult();
+// log.info("此次支付结果:"+result+";msg: "+payload.getMessage());
+// if (result.equals("SUCCESS")) {
+// log.info("支付成功");
+// POOL.submit(new SendFlowerThread(buyEvent));
+// POOL.submit(new SendFlowerBuyToXiaoduTB(buyEvent));
+// return buildErrorResponse("感谢大人赏的花");
+// }
+// return buildErrorResponse("哎呀,没有支付成功");
+// }
+
+
+ private ExecuteCommands changeIconIdTextAfterCollect(boolean collect, String botId) {
+ ExecuteCommands executeCommands = new ExecuteCommands();
+ UpdateComponentCommand update = new UpdateComponentCommand();
+ String srcValue;
+ String textValue;
+ String idValue;
+ String previousClickId;
+ String unCollectId = new StringBuilder(UN_COLLEC_ID).append(botId).toString();
+ String collectId = new StringBuilder(COLLEC_ID).append(botId).toString();
+ if (collect) {
+ srcValue = COLLECTED_IMG_URL;
+ textValue = COLLECED;
+ idValue = unCollectId;
+ previousClickId = collectId;
+ } else {
+ srcValue = UN_COLLECTED_IMG_URL;
+ textValue = UN_COLLEC;
+ idValue = collectId;
+ previousClickId = unCollectId;
+ }
+
+ update.setComponentId(previousClickId);
+ update.setDocument(TempleUtils.getCollectIcon(idValue, srcValue, textValue));
+ executeCommands.addCommand(update);
+ this.addDirective(executeCommands);
+ return executeCommands;
+ }
+
+ private ExecuteCommands changeCollectIconInPlay(boolean collect) {
+ ExecuteCommands executeCommands = new ExecuteCommands();
+ SetStateCommand setState = new SetStateCommand();
+ setState.setComponentId("playCollect");
+ setState.setState("src");
+ if (collect) {
+ setState.setValue(COLLECTED_IMG_URL);
+ }else {
+ setState.setValue(UN_COLLECTED_IMG_URL);
+ }
+ executeCommands.addCommand(setState);
+ return executeCommands;
+ }
+
+ private Response load() {
+ Card card = new LinkAccountCard();
+ Response response = buildErrorResponse(LOAD_INTRO);
+ response.setCard(card);
+ return response;
+ }
+
+ private Integer getUserSendFlowerNum(String productId, String accessToken) {
+ HashMap params = new HashMap<>();
+ params.put("module", "works");
+ params.put("aipioneerUsername", productId);
+ HashMap headers = new HashMap<>();
+ headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
+ headers.put("Authorization", new StringBuilder(BEARER).append(accessToken).toString());
+ CodeMsgData response;
+ try {
+ String flowerRes = OkHttp3Utils.doGet(FLOWER_INTERFACE, params, headers);
+ response = JSON.parseObject(flowerRes, CodeMsgData.class);
+ } catch (IOException e) {
+ log.error("请求用户送花数出错");
+ return null;
+ }
+ log.info("调用获取用户送花数接口结果:{}", response);
+ if (response == null || response.getCode() != 1) return null;
+ return response.getData().getCount();
+ }
+
+
+ private List getUserProductList(String accessToken) {
+ HashMap params = new HashMap<>();
+ params.put("module", "works");
+ HashMap headers = new HashMap<>();
+ headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
+ headers.put("Authorization", new StringBuilder(BEARER).append(accessToken).toString());
+ UserCollecResult result;
+ try {
+ String resStr = OkHttp3Utils.doGet(XIAOWU_API.USER_CLOOEC_LIST, params, headers);
+ result = JSON.parseObject(resStr, UserCollecResult.class);
+ } catch (Exception e) {
+ log.error("调用获取用户收藏作品列表接口出错:{}", e.toString());
+ return null;
+ }
+ if (result.getCode() == 1) return result.getData();
+ else {
+ log.error("获取用户收藏作品列表出错,错误码:{}, 错误信息:{}", result.getCode(), result.getMsg());
+ return null;
+ }
+ }
+
+ private static String correctName(String name) {
+ int brace = name.indexOf("{");
+ if (brace != -1) name = name.substring(0, brace);
+ return name;
+ }
+
+ @Override
+ protected Response onLinkAccountSucceededEvent(LinkAccountSucceededEvent linkAccountSucceededEvent) {
+ log.info("登录成功返回信息:{}",linkAccountSucceededEvent);
+ String accessToken = getAccessToken();
+ String jytUserId;
+ if (getRequest().getContext().getScreen() != null) {
+ log.info("检测到有屏登录");
+ String userId = getUserId();
+ jytUserId = DplbotServiceUtil.getUserIdByToken(accessToken, channel);
+ DplbotServiceUtil.onLunchFillUserBehaviorData(userId, accessToken, jytUserId);
+ if (jytUserId == null)
+ log.warn("登录后获取用户的app id 失败");
+ } else {
+ jytUserId = DplbotServiceUtil.getUserIdByToken(accessToken, null);
+ if (jytUserId == null)
+ log.warn("登录后获取用户的app id 失败");
+ }
+ setSessionAttribute("userId", jytUserId);
+ return buildErrorResponse("您已登录成功");
+ }
+
+// @Override
+// protected Response onDefaultEvent() {
+// log.info("未拦截的事件类型:"+getEventType(this.getStrRequest()));
+// this.waitAnswer();
+// return new Response();
+// }
+
+ private String getEventType(String requestStr) {
+ int typeIndex = requestStr.lastIndexOf("type");
+ int comma = requestStr.indexOf(',', typeIndex);
+ return requestStr.substring(typeIndex, comma);
+ }
+
+ private Response buildErrorResponse(String errorMsg) {
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
+ return new Response(outputSpeech);
+ }
+
+ private Response buildLogOutResponse(String errorMsg) {
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
+ endDialog();
+ return new Response(outputSpeech);
+ }
+
+ private Response buildNoScreenListCardResponse(String content, String botAccount) {
+ Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+ List actors = DplbotServiceUtil.seperateActor(content, pattern);
+ String[] actorWord = DplbotServiceUtil.seperateActorWord(content, pattern);
+ int i = 0;
+ ListCard listCard = new ListCard();
+ for (String actor: actors) {
+ StandardCardInfo cardInfo = new StandardCardInfo(actor, actorWord[i++].replaceAll("
","\n"));
+ cardInfo.setImage(ScheduleService.getAsideImgUrl(botAccount, actor));
+ listCard.getList().add(cardInfo);
+ }
+// content = buildText(content);
+ return new Response(null, listCard, WAIT_WORD);
+ }
+
+ private Response buildNoScreenTextCardREsponse(String content) {
+ content = buildText(content);
+ TextCard textCard = new TextCard(content);
+ return new Response(null, textCard, WAIT_WORD);
+ }
+
+ private String buildText(String text) {
+ Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
+ StringBuilder builder = new StringBuilder();
+ List actors = DplbotServiceUtil.seperateActor(text, pattern);
+ String[] word = DplbotServiceUtil.seperateActorWord(text, pattern);
+ int i = 0;
+ for (String actor: actors) {
+ builder.append(actor).append(":").append(word[i].replaceAll("
", "\n")).append("\n");
+ i++;
+ }
+ if (builder.length() == 0) builder.append(text);
+ return builder.toString();
+ }
+
+ private void backToBotIntro(String botAccount, String channelId) {
+ ProjectData data = ScheduleServiceNew.getProjectByBotAccount(botAccount);
+ // product picture
+ String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(data.getBannerImgUrl()).toString();
+
+ // product name
+ String productName = correctName(data.getName());
+
+ // product create time
+ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+ String dateString = formatter.format(data.getCreateTime());
+ String createTime = PRODUCT_INTRO.CREATE_TIME + dateString;
+
+ // product author
+ String author = PRODUCT_INTRO.AUTHOR + data.getAuthorName();
+
+ // product labels
+ StringBuilder labels = new StringBuilder(PRODUCT_INTRO.LABEL);
+ for (String label: data.getLabels()) {
+ labels.append(PRODUCT_INTRO.SPACE).append(label);
+ }
+
+ // product introduction
+ String intro = data.getIntro();
+
+ // "start product" container button
+ String enterProName = Constants.PRE_ENTER_PRODUCT + productName;
+
+ String accessToken = getAccessToken();
+ String flowers, flowerReward,collectText, collectUrl, collectComId;
+ if (accessToken != null) {
+ // flower container button
+ Long count = DplbotServiceUtil.getUserSendFlowerNum(botAccount, getUserId(), channelId, accessToken,
+ getSessionAttribute("userId"));
+ flowers = USER_SEND_FLOWER+count;
+ flowerReward = FLOWE + data.getBotAccount();
+
+ // collection container button
+ boolean collec = DplbotServiceUtil.doesUserCollectThisBot(data.getBotAccount(), accessToken, getUserId(),
+ channelId, getSessionAttribute("userId"));
+ if (collec) {
+ collectText = COLLECED;
+ collectUrl = COLLECTED_IMG_URL;
+ collectComId = UN_COLLEC_ID + data.getBotAccount();
+ } else {
+ collectText = UN_COLLEC;
+ collectUrl = UN_COLLECTED_IMG_URL;
+ collectComId = COLLEC_ID + data.getBotAccount();
+ }
+ } else {
+ flowers = FLOWER;
+ flowerReward = FLOWER_LOAD;
+
+ collectText = UN_COLLEC;
+ collectUrl = UN_COLLECTED_IMG_URL;
+ collectComId = FLOWER_LOAD; // 提示登录
+ }
+
+ ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), createTime, author, labels.toString(),
+ intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
+ RenderDocument renderDocument = new RenderDocument(document);
+ this.addDirective(renderDocument);
+ String trace = getSessionAttribute(BACK_TRACE);
+ trace = trace.substring(0, trace.length()-1);
+ this.setSessionAttribute(BACK_TRACE, trace);
+ }
+
+ // 异步发送“退出”给终端
+ private void sendCancellToTerminate(String userId){
+ RequestTerminal.backRequest(userId, type);
+ }
+
+ private Response dealJumpIntent(String userId, String numStr, String channelId) {
+ String trace = getSessionAttribute("trace");
+ if (trace == null || trace.length() < 2) {
+ return buildErrorResponse("小悟跳不动了");
+ }
+ int index = extractNum(numStr);
+ char pageSign = trace.charAt(1);
+ Response response;
+ switch (pageSign) {
+ case '1' :
+ case '2' : response = dealCollectHistoryJump(index, true, userId, channelId);break;
+ case '4' : response = dealRankJump(index, channelId);break;
+ case '5' : response = dealCategoryJump(index);break;
+ default : response = buildErrorResponse("该页面不支持跳转");
+ }
+ return response;
+ }
+
+ private Response dealRankJump(int index, String channelId) {
+ index = index == 0 ? index : index-1;
+ RecommandDocument document;
+ if (index == 0) document = RecommendUtil.getRankDocumentFirstPage(channelId);
+ else document = RecommendUtil.getRankOtherPageDocument(index, channelId);
+ if (document == null) {
+ return buildErrorResponse("超出了范围,无法跳转");
+ }
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String cmt = String.valueOf(index+1);
+ setSessionAttribute("comCnt",cmt);
+ setSessionAttribute(PRE_COLLE, document.getRecommendIdList());
+ return new Response();
+ }
+
+ private Response dealCategoryJump(int index) {
+ index = index == 0 ? index : index-1;
+ String category = getSessionAttribute("category");
+ if (category == null) {
+ return buildErrorResponse("无法跳转,请说返回然后重新进入当前分类");
+ }
+ RecommandDocument document = RecommendUtil.getCategory(index, category);
+ if (document == null) {
+ return buildErrorResponse("超出了范围,无法跳转");
+ }
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String cmt = String.valueOf(index+1);
+ setSessionAttribute("comCnt",cmt);
+ return new Response();
+ }
+
+ private Response dealCollectHistoryJump(int index, boolean collect, String userId, String channelId) {
+ index = index == 0 ? index : index-1;
+ int start = index*CO_HI_PAGE_SIZE;
+ CollectHistoryDocument document;
+ if (collect) document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),
+ getSessionAttribute("userId"), start, channelId);
+ else document = DplbotServiceUtil.getHistory(userId, getAccessToken(), getSessionAttribute("userId"),start,channelId);
+ if (document != null) {
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String cmt = String.valueOf(index+1);
+ setSessionAttribute("comCnt",cmt);
+ setSessionAttribute(PRE_COLLE, document.getIdToken());
+ return new Response();
+ } else {
+ return buildErrorResponse("超出了范围无法跳到那一页");
+ }
+ }
+
+ private Response dealStartIntent(String userId, IntentRequest intentRequest, String channelId) {
+ String trace = getSessionAttribute("trace");
+ if (trace != null && trace.length() > 2 && !StringUtils.endsWith(trace,File.separator)) {
+ String botId = trace.substring(2);
+ String enterName = "打开" +
+ ScheduleServiceNew.getProjectByBotAccount(botId).getName();
+ return dealDefaultIntent(intentRequest, userId, enterName, channelId);
+ }else {
+ backToHome();
+ }
+ return new Response();
+ }
+
+ private Response dealSendFlowerIntent(String userId, String numStr) {
+ if (getAccessToken() == null) {
+ return buildErrorResponse("该功能需要登录,请说小度小度,登录");
+ }
+ int num = extractNum(numStr);
+ int unitPrice = Integer.parseInt(ScheduleService.FLOWER_UNIT_PRICE);
+ String amount = String.valueOf(unitPrice*num/100.0);
+ String orderId = userId + System.currentTimeMillis();
+ String appUserId = getSessionAttribute("userId");
+ if (appUserId == null) {
+ appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken(), channel);
+ if (appUserId == null) {
+ log.error("送花时获取用户app_user_id失败");
+ return buildErrorResponse("不好意思出了点问题,请再说一遍吧");
+ }
+ }
+ String botId;
+ String trace = getSessionAttribute(BACK_TRACE);
+ if (trace != null && trace.length() > 2) {
+ if (StringUtils.endsWith(trace, File.separator)) {
+ botId = trace.substring(2, trace.length()-1);
+ }else {
+ botId = trace.substring(2);
+ }
+
+ XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
+ XiaoDuOrderTB response = repository.save(buildBeforePayPojo(botId, appUserId, userId, unitPrice,
+ num, orderId));
+ if (response != null && response.getId() != null) {
+ String desc = new StringBuilder("感谢您赏赐给该作品的").append(num).append("朵鲜花").toString();
+ String name = ScheduleServiceNew.getProjectByBotAccount(botId).getName();
+ if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
+ .append("的").append(num).append("朵鲜花").toString();
+ Charge charge = new Charge(amount, orderId, "鲜花", desc);
+ charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
+ addDirective(charge);
+ return buildErrorResponse("请扫描二维码完成支付");
+ } else {
+ log.warn("订单没有插入到xioadu_order_tb");
+ return buildErrorResponse(ERROR_SEND_FLOWER);
+ }
+ }else {
+ log.warn("无法获取到botID");
+ return buildErrorResponse(ERROR_SEND_FLOWER);
+ }
+ }
+
+ private Response dealCollectOrUnCollectIntent(String userId, String intentName) {
+ if (getAccessToken() == null) {
+ return buildErrorResponse("该功能需要登录,请说小度小度,登录");
+ }
+ boolean collect = "collect".equals(intentName);
+ boolean inProductInfo = false;
+ boolean inPlayInfo = false;
+ String botAccount;
+ String trace = getSessionAttribute("trace");
+ if (trace == null || trace.length() <= 2) {
+ botAccount = getSessionAttribute("botAcc");
+ if(botAccount == null) {
+ String word = COLLECT_FAIL;
+ if (!collect) word = UN_COLLECT_FAIL;
+ return buildErrorResponse(word);
+ }
+ } else {
+ if (StringUtils.endsWith(trace, File.separator)) {
+ botAccount = trace.substring(2, trace.length()-1);
+ inPlayInfo = true;
+ }
+ else {
+ inProductInfo = true;
+ botAccount = trace.substring(2);
+ }
+ }
+ try {
+ String appUserId = getSessionAttribute("userId");
+ if (appUserId == null) appUserId = DplbotServiceUtil.getUsUserId(userId,getAccessToken(), channel);
+ boolean alreadyCollected = DplbotServiceUtil.doesUserCollectThisBot(botAccount, getAccessToken(), userId,
+ channel, appUserId);
+ if (appUserId != null) {
+ if (alreadyCollected) {
+ if (collect) return buildErrorResponse("您之前就已经收藏过该作品啦,看来你真的很喜欢它");
+ else {
+ DplbotServiceUtil.userUnCollectTheBot(userId, botAccount, channel, appUserId, getAccessToken());
+ String botName = ScheduleServiceNew.getProjectByBotAccount(botAccount).getName();
+ if (inProductInfo) {
+ ExecuteCommands commands = changeIconIdTextAfterCollect(false, botAccount);
+ addDirective(commands);
+ } else if (inPlayInfo) {
+ changeCollectIconInPlay(false);
+ }
+ if (botName == null) return buildErrorResponse(UN_COLLECT_BOT_WORD);
+ else return buildErrorResponse(String.format(UN_COLLECT_BOT_WORD_MG,botName));
+ }
+ } else {
+ if (collect) {
+ DplbotServiceUtil.userCollectTheBot(userId, botAccount, channel, appUserId, getAccessToken());
+ String word = ScheduleServiceNew.getProjectByBotAccount(botAccount).getName();
+ if (inProductInfo) {
+ ExecuteCommands commands = changeIconIdTextAfterCollect(true, botAccount);
+ addDirective(commands);
+ } else if (inPlayInfo) {
+ changeCollectIconInPlay(true);
+ }
+ if (word == null) return buildErrorResponse(COLLECT_BOT_WORD);
+ else return buildErrorResponse(String.format(COLLECT_BOT_WORD_MG, correctName(word)));
+ }else {
+ return buildErrorResponse("您还未收藏过该作品,它不在您的收藏列表内");
+ }
+ }
+ }else {
+ return buildErrorResponse(SORRY_UNCATCH);
+ }
+ } catch (Exception e) {
+ log.error("收藏/取消收藏出错:{}",e.toString());
+ return buildErrorResponse(SORRY_UNCATCH);
+ }
+ }
+
+ private Response dealRankIntent(String channelId) {
+ RecommandDocument document = RecommendUtil.getRankDocumentFirstPage(channelId);
+ RenderDocument render = new RenderDocument();
+ render.setDocument(document);
+ addDirective(render);
+ String token = document.getRecommendIdList();
+ setSessionAttribute(PRE_COLLE, token);
+ setSessionAttribute("comCnt", null);
+ setSessionAttribute(BACK_TRACE, "04");
+ return buildErrorResponse("正在为您打开排行榜");
+ }
+
+ private void dealRecommandIntent(OverTimeDetail detail, String userId) {
+ RecommandDocument recommandDocument = RecommendUtil.getRecommendDocument(0, channel);
+ RenderDocument render = new RenderDocument();
+ render.setDocument(recommandDocument);
+ addDirective(render);
+ detail.getDirectives().add(render);
+ String token = recommandDocument.getRecommendIdList();
+ if (token != null) {
+ setSessionAttribute("recommand", token);
+ setSessionAttribute(PRE_COLLE, null);
+ setSessionAttribute("comCnt", null);
+
+ detail.getAttributes().put("comCnt", null);
+ detail.getAttributes().put("recommand", token);
+ detail.getAttributes().put(PRE_COLLE, null);
+ }
+ setSessionAttribute(BACK_TRACE, "03");
+ detail.getAttributes().put(BACK_TRACE,"03");
+ LAST_OUTTIME_RESULT.put(userId, detail);
+ }
+
+ private Response dealHistoryIntent(String channelId) {
+ CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(),
+ getSessionAttribute("userId"),0, channelId);
+ if (document == null) {
+ return buildErrorResponse("没有更多了");
+ }
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ //dplBotService.addDirective(new PushStack());
+ setSessionAttribute(PRE_COLLE,document.getIdToken());
+// setSessionAttribute("recommand", null);
+// setSessionAttribute("comCnt", null);
+ setSessionAttribute(BACK_TRACE, "02");
+ return buildErrorResponse("正在为您打开历史记录");
+ }
+
+ private Response dealNextPageIntent(String userId, String channelId) {
+ String signPage = getSessionAttribute("trace");
+ if (signPage == null || signPage.length() < 2) {
+ return buildErrorResponse("哎呀,小悟累啦,滑不动了");
+ }
+ char sign = signPage.charAt(1);
+ switch (sign) {
+ case '1': {
+ String recommendNextCount = getSessionAttribute("comCnt");
+ if (recommendNextCount == null) {
+ recommendNextCount = "1";
+ }
+ int count = Integer.parseInt(recommendNextCount);
+ int start = count*CO_HI_PAGE_SIZE;
+ String jytUserId = getSessionAttribute("userId");
+ if (StringUtils.isBlank(jytUserId)) {
+ UserBehaviorData data = USER_HISTORY.get(userId);
+ if (data != null) {
+ jytUserId = data.getJytUserId();
+ if (StringUtils.isBlank(jytUserId)) {
+ jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken(), null);
+ data.setJytUserId(jytUserId);
+ }
+ }
+ }
+ CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId,getAccessToken(),
+ jytUserId, start, channelId);
+ if (document != null) {
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String cmt = String.valueOf(count+1);
+ setSessionAttribute("comCnt",cmt);
+ setSessionAttribute(PRE_COLLE, document.getIdToken());
+ }
+ return new Response();
+ }
+ case '2': {
+ String recommendNextCount = getSessionAttribute("comCnt");
+ if (recommendNextCount == null) {
+ recommendNextCount = "1";
+ }
+ int count = Integer.parseInt(recommendNextCount);
+ int start = count*CO_HI_PAGE_SIZE;
+ CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(),
+ getSessionAttribute("userId"),start,channelId);
+ if (document != null) {
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String cmt = String.valueOf(count+1);
+ setSessionAttribute("comCnt",cmt);
+ setSessionAttribute(PRE_COLLE, document.getIdToken());
+ }
+ return new Response();
+ }
+ case '3': {
+ String recommendNextCount = getSessionAttribute("comCnt");
+ int count = 1;
+ if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+ RecommandDocument document = RecommendUtil.getRecommendDocument(count,channelId);
+ if (document == null) {
+ return buildErrorResponse("客观你已经翻到底了,没有更多了");
+ }
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String token = document.getRecommendIdList();
+ setSessionAttribute(PRE_COLLE, token);
+ setSessionAttribute("comCnt",String.valueOf(count+1));
+ return new Response();
+ }
+ case '4': {
+ String recommendNextCount = getSessionAttribute("comCnt");
+ int count = 1;
+ if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+ RecommandDocument document = RecommendUtil.getRankOtherPageDocument(count, channelId);
+ if (document == null) {
+ return buildErrorResponse("客观你已经翻到底了,没有更多了");
+ }
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String token = document.getRecommendIdList();
+ setSessionAttribute(PRE_COLLE, token);
+ setSessionAttribute("comCnt",String.valueOf(count+1));
+ return new Response();
+ }
+ case '5':{
+ String category = getSessionAttribute("category");
+ if (category == null) category = "古风";
+ String categoryNextCount = getSessionAttribute("comCnt");
+ int count = 1;
+ if (categoryNextCount != null) count = Integer.parseInt(categoryNextCount);
+ RecommandDocument document = RecommendUtil.getCategory(count,category);
+ if (document == null) {
+ return buildErrorResponse("客观你已经翻到底了,没有更多了");
+ }
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String countStr = String.valueOf(count+1);
+ setSessionAttribute("comCnt",countStr);
+ return new Response();
+ }
+ default:{
+ return buildErrorResponse("可以跟我说返回或者回到首页");
+ }
+ }
+ }
+
+ private Response dealLastPageIntent(String userId, String channelId) {
+ String signPage = getSessionAttribute("trace");
+ if (signPage == null || signPage.length() < 2) {
+ return buildErrorResponse("不好意思,小悟累啦,滑不动了");
+ }
+ char sign = signPage.charAt(1);
+ switch (sign) {
+ case '1':{
+ String recommendNextCount = getSessionAttribute("comCnt");
+ if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+ return buildErrorResponse("客观,前面没啦,没法往前翻了");
+ }
+ int count = Integer.parseInt(recommendNextCount);
+ int start = (count-2)*CO_HI_PAGE_SIZE;
+ String jytUserId = getSessionAttribute("userId");
+ if (StringUtils.isBlank(jytUserId)) {
+ UserBehaviorData data = USER_HISTORY.get(userId);
+ if (data != null) {
+ jytUserId = data.getJytUserId();
+ if (StringUtils.isBlank(jytUserId)) {
+ jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken(), null);
+ data.setJytUserId(jytUserId);
+ }
+ }
+ }
+ CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId,getAccessToken(),
+ getSessionAttribute("userId"), start, channelId);
+ if (document != null) {
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String cmt = String.valueOf(count-1);
+ setSessionAttribute("comCnt",cmt);
+ setSessionAttribute(PRE_COLLE, document.getIdToken());
+ }
+ break;
+ }
+ case '2':{
+ String recommendNextCount = getSessionAttribute("comCnt");
+ if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+ return buildErrorResponse("客观,前面没啦,没法往前翻了");
+ }
+ int count = Integer.parseInt(recommendNextCount);
+ int start = (count-2)*CO_HI_PAGE_SIZE;
+ CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(),
+ getSessionAttribute("userId"), start, channelId);
+ if (document != null) {
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String cmt = String.valueOf(count-1);
+ setSessionAttribute("comCnt",cmt);
+ setSessionAttribute(PRE_COLLE, document.getIdToken());
+ }
+ break;
+ }
+ case '3': {
+ String recommendNextCount = getSessionAttribute("comCnt");
+ if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+ return buildErrorResponse("客观,前面没啦,没法往前翻了");
+ }
+ int count = Integer.parseInt(recommendNextCount);
+ RecommandDocument document = RecommendUtil.getRecommendDocument(count-2, channelId);
+ if (document != null) {
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String token = document.getRecommendIdList();
+ setSessionAttribute(PRE_COLLE, token);
+ setSessionAttribute("comCnt",String.valueOf(count-1));
+ }
+ break;
+ }
+ case '4': {
+ String recommendNextCount = getSessionAttribute("comCnt");
+ if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+ return buildErrorResponse("客观,前面没啦,没法往前翻了");
+ }
+ int count = Integer.parseInt(recommendNextCount);
+ RecommandDocument document;
+ if (count == 2) document = RecommendUtil.getRankDocumentFirstPage(channelId);
+ else document = RecommendUtil.getRankOtherPageDocument(count-2, channelId);
+ if (document != null) {
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ String token = document.getRecommendIdList();
+ setSessionAttribute(PRE_COLLE, token);
+ setSessionAttribute("comCnt",String.valueOf(count-1));
+ }
+ break;
+ }
+ case '5':{
+ String category = getSessionAttribute("category");
+ if (category == null) category = "古风";
+ String recommendNextCount = getSessionAttribute("comCnt");
+ if (recommendNextCount == null || "1".equals(recommendNextCount)) {
+ return buildErrorResponse("客观,前面没啦,没法往前翻了");
+ }
+ int count = Integer.parseInt(recommendNextCount);
+ RecommandDocument document = RecommendUtil.getCategory(count-2,category);
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ setSessionAttribute("comCnt",String.valueOf(count-1));
+ break;
+ }
+ default:{
+ return buildErrorResponse("可以跟我说返回或者回到首页");
+ }
+ }
+ return new Response();
+ }
+
+ private Response dealOpenNumIntent(String numStr, String channelId) {
+ String trace = getSessionAttribute("trace");
+ int num = extractNum(numStr.replaceAll(" ", ""));
+ if (trace == null || trace.charAt(1) == '0') {
+ return dealOpenNumInHome(num);
+ } else if (trace.length() > 2) {
+ return buildErrorResponse("客官,您在这个页面想打开啥");
+ }
+ char page = trace.charAt(1);
+ Response response;
+ switch (page){
+ case '1':
+ case '2': response = dealOpenNum(getSessionAttribute(PRE_COLLE), num); break;
+ case '3':
+ case '4':
+ case '6': response = dealOpenNumInRecommend(getSessionAttribute(PRE_COLLE), num, channelId); break;
+ case '5': response = dealOpenNumInCategory(channelId);break;
+ default:{
+ response = buildErrorResponse("屏幕上的图标都是可以点击的哦");
+ }
+ }
+ return response;
+ }
+
+ private Integer extractNum(String numStr) {
+ int num;
+ try {
+ num = Integer.parseInt(numStr);
+ return num;
+ } catch (Exception e) {
+ int i;
+ if ((i=numStr.indexOf("第")) != -1) {
+ String str = numStr.substring(i+1, numStr.length()-1);
+ try {
+ num = Integer.parseInt(str);
+ } catch (Exception e1) {
+ num = Utils.changeHanToNum(str);
+ }
+ } else {
+ num = Utils.changeHanToNum(numStr);
+ }
+ }
+ return num;
+ }
+
+ private Response dealOpenCollectIntent(String channelId) {
+ if (getAccessToken() == null) {
+ return buildErrorResponse("该功能需要登录,请说小度小度,登录");
+ } else {
+ String jytId = getSessionAttribute("userId");
+ if (StringUtils.isBlank(jytId)) {
+ jytId = DplbotServiceUtil.getUserIdByToken(getAccessToken(), null);
+ if (StringUtils.isBlank(jytId)) return buildErrorResponse("不好意思没有获取到您的收藏记录");
+ }
+ CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(getUserId(),getAccessToken(), jytId, 0, channelId);
+ if (document == null) {
+ backToHome();
+ return buildErrorResponse("不好意思没有获取到您的收藏记录");
+ }
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ setSessionAttribute(PRE_COLLE,document.getIdToken());
+ setSessionAttribute(BACK_TRACE, "01");
+ return buildErrorResponse("正在为您打开收藏列表");
+ }
+ }
+
+ private Response dealBackIntent(String userId, String channelId) {
+ String trace = getSessionAttribute(BACK_TRACE);
+ char second;
+ if (trace == null || trace.length() <= 2 || getQuery().contains("首")) {
+ // home page
+ backToHome();
+ if (trace != null && StringUtils.endsWith(trace,File.separator)) sendCancellToTerminate(userId);
+ } else if (StringUtils.endsWith(trace,File.separator)){
+ String botAccount = trace.substring(2, trace.length()-1);
+ log.info("返回作品的id:{}", botAccount);
+ backToBotIntro(botAccount, channelId);
+ sendCancellToTerminate(userId);
+ } else {
+ second = trace.charAt(1);
+ switch (second){
+ // home page
+ case '0':{
+ backToHome();
+ break;
+ }
+ case '1': {
+ //collect
+ String appUserId = getSessionAttribute("userId");
+ if (StringUtils.isBlank(appUserId)) {
+ UserBehaviorData data = USER_HISTORY.get(userId);
+ if (data != null) appUserId = data.getJytUserId();
+ if (StringUtils.isBlank(appUserId)) {
+ appUserId = DplbotServiceUtil.getUsUserId(userId, getAccessToken(), channelId);
+ }
+ }
+ String recommendNextCount = getSessionAttribute("comCnt");
+ int count = 1;
+ if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+ CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(userId, getAccessToken(),appUserId,
+ (count-1)*CO_HI_PAGE_SIZE, channelId);
+ if (document == null) {
+ backToHome();
+ return buildErrorResponse("您还未收藏过任何作品,快去收藏吧");
+ }
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ setSessionAttribute(BACK_TRACE, "01");
+ setSessionAttribute(PRE_COLLE,document.getIdToken());
+ return buildErrorResponse("已为您返回到收藏页");
+ }
+ case '2': {
+ //history
+ String recommendNextCount = getSessionAttribute("comCnt");
+ int count = 1;
+ if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+ CollectHistoryDocument document = DplbotServiceUtil.getHistory(userId, getAccessToken(),getSessionAttribute("userId"),
+ (count-1)*CO_HI_PAGE_SIZE, channelId);
+ if (document == null) {
+ backToHome();
+ return buildErrorResponse("哎呀,可能是您太久没玩了,历史记录已被清空");
+ }
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ setSessionAttribute(PRE_COLLE,document.getIdToken());
+ setSessionAttribute(BACK_TRACE, "02");
+ return buildErrorResponse("已为您返回到历史记录页");
+ }
+ case '3': {
+ //recommend
+ String recommendNextCount = getSessionAttribute("comCnt");
+ int count = 1;
+ if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+ RecommandDocument recommandDocument = RecommendUtil.getRecommendDocument(count-1, channelId);
+ if (recommandDocument == null) {
+ RenderDocument render = new RenderDocument();
+ render.setDocument(LunchUtils.getLunchDocument());
+ addDirective(render);
+ setSessionAttribute(BACK_TRACE, null);
+ break;
+ }
+ RenderDocument render = new RenderDocument();
+ render.setDocument(recommandDocument);
+ addDirective(render);
+ setSessionAttribute(PRE_COLLE, recommandDocument.getRecommendIdList());
+ setSessionAttribute(BACK_TRACE, "03");
+ return buildErrorResponse("已为您返回到推荐页");
+ }
+ case '4': {
+ //rank
+ String recommendNextCount = getSessionAttribute("comCnt");
+ int count = 1;
+ if (recommendNextCount != null) count = Integer.parseInt(recommendNextCount);
+ RecommandDocument recommandDocument;
+ if (count == 1) recommandDocument = RecommendUtil.getRankDocumentFirstPage(channelId);
+ else recommandDocument = RecommendUtil.getRankOtherPageDocument(count-1, channelId);
+ if (recommandDocument == null) {
+ RenderDocument render = new RenderDocument();
+ render.setDocument(LunchUtils.getLunchDocument());
+ addDirective(render);
+ setSessionAttribute(BACK_TRACE, null);
+ break;
+ }
+ RenderDocument render = new RenderDocument();
+ render.setDocument(recommandDocument);
+ addDirective(render);
+ setSessionAttribute(PRE_COLLE, recommandDocument.getRecommendIdList());
+ setSessionAttribute(BACK_TRACE, "04");
+ return buildErrorResponse("已为您返回到排行榜");
+ }
+ case '5':{
+ String category = getSessionAttribute("category");
+ if (category == null) {
+ backToHome();
+ } else {
+ String count = getSessionAttribute("comCnt");
+ int pageIndex = 0;
+ if (count != null) pageIndex = Integer.parseInt(count)-1;
+ RecommandDocument document = RecommendUtil.getCategory(pageIndex, category);
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ return buildErrorResponse(new StringBuilder("已为您返回到")
+ .append(category).append("分类第").append(pageIndex+1).append("页").toString());
+ }
+ }
+ }
+ }
+ return new Response();
+ }
+
+ private void backToHome() {
+ RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
+ addDirective(renderDocument);
+ setSessionAttribute(BACK_TRACE,null);
+ }
+
+ private Response dealDefaultIntent(IntentRequest intentRequest, String userId, String word, String channelId) {
+ if (word == null) {
+ Query query = intentRequest.getQuery();
+ if (query != null) word = query.getOriginal();
+ if (word == null){
+ log.info("小度没有传来任何话语");
+ return buildErrorResponse(SORRY_UNCATCH);
+ }
+ }
+ String data = null;
+ try {
+ data = RequestTerminal.requestTerminateTemp(word, userId, channelId);
+ } catch (Exception e) {
+ log.error("请求终端接口出错:", e.toString());
+ }
+ if (StringUtils.isBlank(data)) {
+ return buildErrorResponse(SORRY_UNCATCH);
+ }
+ JSONObject object = JSON.parseObject(data);
+ try {
+ JSONArray commands = object.getJSONArray("commands");
+ if (commands != null && commands.size() == 1) {
+ String txt = ((JSONObject)commands.get(0)).getString("text");
+ int i;
+ if (StringUtils.isNotBlank(txt) && (i = txt.indexOf("☛")) != -1) {
+ int end = txt.indexOf("☚");
+ String command = txt.substring(i+1, end).trim();
+ if (StringUtils.isNotBlank(command)) {
+ if ((i=command.indexOf("out")) != -1) {
+ log.info("小度,推荐bot退出:{},{}",word,userId);
+ String content = command.substring(i+3).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;
+ RequestTerminal.backRequest(userId, type);
+ return buildLogOutResponse(str);
+ }
+ }
+ RequestTerminal.backRequest(userId, type);
+ return buildLogOutResponse(byeWord);
+ } else {
+ content = content.replaceAll("\\{/.*?/}", "")+skillName;
+ RequestTerminal.backRequest(userId, type);
+ return buildLogOutResponse(content);
+ }
+ }
+ switch (command) {
+ case "recommend": {
+ String path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
+ if (StringUtils.isBlank(path) || "null".equals(path)) {
+ log.error("小度没有获取到音频链接");
+ return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+ }
+ String text = ((JSONObject) object.getJSONArray("dialogs").get(0)).getString("text");
+ RecommandDocument document = displayFunnyRecommandPage(text, dealAudioUrl(path));
+ if (document != null) {
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ setSessionAttribute(PRE_COLLE, document.getRecommendIdList());
+ setSessionAttribute(BACK_TRACE, "06");
+ }
+ return new Response();
+ }
+ case "history" : return dealHistoryIntent(channelId);
+ case "collect" : return dealOpenCollectIntent(channelId);
+ case "next" : return dealNextPageIntent(userId,channelId);
+ case "before" : return dealLastPageIntent(userId, channelId);
+ case "back" : return dealBackIntent(userId, channelId);
+ case "load" : return load();
+ case "start" : return dealStartIntent(userId, intentRequest, channelId);
+ case "openRank" : return dealRankIntent(channelId);
+ case "openNum" : return dealOpenNumIntent(txt.substring(end+1), channelId);
+ case "jump" : return dealJumpIntent(userId, txt.substring(end+1), channelId);
+ case "store" : return dealCollectOrUnCollectIntent(userId, "collect");
+ case "unStore" : return dealCollectOrUnCollectIntent(userId, "unCollect");
+ case "flower" : return dealSendFlowerIntent(userId, txt.substring(end+1));
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("推荐bot退出解析出错:"+e);
+ return new Response();
+ }
+
+// String aside = DplbotServiceUtil.getAsideText(text);
+// //log.info("旁白名字:{}",aside);
+// //log.info("小悟返回:{}", text);
+// text = text.substring(text.indexOf("】")+1);
+ String path = null;
+ try {
+ path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
+ } catch (Exception e) {
+ log.warn("没有获取到TTS返回地址");
+ }
+ if (StringUtils.isBlank(path) || "null".equals(path)) {
+ log.error("小度没有获取到音频链接");
+ return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+ }
+
+ String botAccount = object.getString("aipioneerUsername");
+ String beforeBotAccount = getSessionAttribute("botAcc");
+ if (!botAccount.equals(beforeBotAccount)) {
+ DplbotServiceUtil.updateTheUserBehaviorDataMark(userId, botAccount, getAccessToken(), getSessionAttribute("userId"));
+ String productName = ScheduleServiceNew.getProjectByBotAccount(botAccount).getName();
+ PlayDocument document = PlayUtils.getPlayDocument(productName, DplbotServiceUtil.getTheActorsWithWords(object.getJSONArray("dialogs")),
+ dealAudioUrl(path), botAccount);
+
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ DplbotServiceUtil.updateTheUserHistory(userId, botAccount, getAccessToken(), channelId);
+ String trace = getSessionAttribute(BACK_TRACE);
+ if (trace == null || trace.length() != 2) trace = "00";
+ trace = new StringBuilder(trace).append(botAccount).append(File.separator).toString();
+ setSessionAttribute(BACK_TRACE, trace);
+ setSessionAttribute("botAcc", botAccount);
+ } else {
+// ExecuteCommands executeCommands = new ExecuteCommands();
+// SetStateCommand audio = new SetStateCommand();
+// SetStateCommand textState = new SetStateCommand();
+// audio.setComponentId("audioCom");
+// audio.setState("src");
+// audio.setValue(data.getAudio());
+// textState.setComponentId("text");
+// textState.setState("text");
+// textState.setValue(text);
+//
+// SetStateCommand asideImg = new SetStateCommand();
+// asideImg.setComponentId("asideImg");
+// asideImg.setState("src");
+// asideImg.setValue(ScheduleService.getAsideImgUrl(botAccount, aside));
+//
+// SetStateCommand asideText = new SetStateCommand();
+// asideText.setComponentId("asideText");
+// asideText.setState("text");
+// asideText.setValue(aside);
+//
+// executeCommands.addCommand(audio);
+// executeCommands.addCommand(textState);
+// executeCommands.addCommand(asideImg);
+// executeCommands.addCommand(asideText);
+
+// UpdateComponentCommand update = new UpdateComponentCommand();
+// update.setComponentId("whole");
+// update.setDocument(TempleUtils.getPlayUpdate(data.getAudio(), text));
+// executeCommands.addCommand(update);
+
+// addDirective(executeCommands);
+// detail.getDirectives().add(executeCommands);
+
+ String productName = ScheduleServiceNew.getProjectByBotAccount(botAccount).getName();
+// PlayDocument document = PlayUtils.getPlayDocument(correctName(productName), aside,
+// ScheduleService.getAsideImgUrl(botAccount, aside),
+// data.getAudio(), text);
+ PlayDocument document = PlayUtils.getPlayDocument(productName,
+ DplbotServiceUtil.getTheActorsWithWords(object.getJSONArray("dialogs")), dealAudioUrl(path), botAccount);
+
+ RenderDocument render = new RenderDocument(document);
+ addDirective(render);
+ }
+ return new Response();
+ }
+
+ private Response dealOpenNumInRecommend(String idsToken, int collectNum, String channelId) {
+ if (idsToken == null) {
+ return buildErrorResponse("请重新进入当前页面");
+ }
+ String[] tokenList = new String(Base64.getDecoder().decode(idsToken)).split(File.separator);
+ if (collectNum > tokenList.length || collectNum <= 0) return buildErrorResponse("这个数字超出了范围");
+ ProjectData detail = ScheduleServiceNew.getProjectByBotAccount(tokenList[collectNum-1]);
+ if (DplbotServiceUtil.doesUserPlayed(detail.getBotAccount(), getUserId(), getAccessToken())) {
+ String productName = correctName(detail.getName());
+ return directInProduct(productName, detail.getBotAccount());
+ } else {
+ return enterProductInfo(detail.getName(), channelId);
+ }
+ }
+
+ private Response dealOpenNumInCategory(String channelId) {
+ String count = getSessionAttribute("comCnt");
+ int pageIndex = 0;
+ if (count != null) pageIndex = Integer.parseInt(count)-1;
+ String numStr = getSlot("sys.number");
+ int num = 1;
+ if (numStr != null) num = Integer.parseInt(numStr);
+ List categoryBots = ScheduleService.getCategoryProductIdList().get(getSessionAttribute("category"));
+ num = pageIndex*RE_RA_CA_PAGE_SIZE+num-1;
+ if (num < 0 || num >= categoryBots.size()) {
+ return buildErrorResponse("这个数字超出了范围,作品的序号已显示在图片左上角");
+ }
+ String botId = categoryBots.get(num);
+ String name = ScheduleServiceNew.getProjectByBotAccount(botId).getName();
+ Response response;
+ if (DplbotServiceUtil.doesUserPlayed(botId, getUserId(), getAccessToken())) response = directInProduct(correctName(name), botId);
+ else response = enterProductInfo(correctName(name), channelId);
+ return response;
+ }
+
+ private Response dealOpenNumInHome(int num) {
+ if (num <= ScheduleServiceNew.allProjects.size()) {
+ ProjectData bot = ScheduleServiceNew.allProjects.get(num-1);
+ if (!DplbotServiceUtil.doesUserPlayed(bot.getBotAccount(), getUserId(), getAccessToken())) return enterProductInfo(bot.getName(), channel);
+ else return directInProduct(bot.getName(), bot.getBotAccount());
+ }
+// if (num > 0 && num <= 10) {
+// GameProjectTb bot = ScheduleService.getRecommendList().get(num-1);
+// log.info("历史:作品id:{}",bot.getBotAccount());
+// if (!DplbotServiceUtil.doesUserPlayed(bot.getBotAccount(), getUserId(), getAccessToken())) return enterProductInfo(bot.getName(), channel);
+// else return directInProduct(bot.getName(), bot.getBotAccount());
+// } else if (num > 10 && num <= 20) {
+// GameProjectTb bot = ScheduleService.getRankingList().get(num-11);
+// log.info("历史:作品id:{}",bot.getBotAccount());
+// if (!DplbotServiceUtil.doesUserPlayed(bot.getBotAccount(), getUserId(), getAccessToken())) return enterProductInfo(bot.getName(), channel);
+// else return directInProduct(bot.getName(), bot.getBotAccount());
+// } else if (num > 20 && num <= 30) {
+// String categoryName = ScheduleService.CATEGORY[num-21];
+// RecommandDocument document = RecommendUtil.getCategory(0, categoryName);
+// if (document == null) return buildErrorResponse("不好意思该分类还没有作品");
+// RenderDocument render = new RenderDocument(document);
+// this.addDirective(render);
+// this.setSessionAttribute("category",categoryName);
+// this.setSessionAttribute("trace","05");
+// return buildErrorResponse(new StringBuilder("为您打开").append(categoryName).append("类作品").toString());
+// }
+ else {
+ return buildErrorResponse("这数字超出我的范围了");
+ }
+ }
+
+ private Response directInProduct(String name,String botId) {
+ String productName = correctName(name);
+ String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
+ log.info("进入作品语句:{}", enterProductWord);
+ String data = null;
+ try {
+ data = RequestTerminal.requestTerminateTemp(enterProductWord, getUserId(), channel);
+ } catch (IOException e) {
+ log.error("请求终端接口出错:", e.toString());
+ }
+ if (data == null) {
+ return buildErrorResponse(SORRY_UNCATCH);
+ }
+ String path = null;
+ try {
+ path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:9663/api/audio", data);
+ } catch (Exception e) {
+ log.warn("没有获取到TTS返回地址");
+ }
+ if (StringUtils.isBlank(path) || "null".equals(path)) {
+ log.error("小度没有获取到音频链接");
+ return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
+ }
+ PlayDocument document = PlayUtils.getPlayDocument(productName,
+ DplbotServiceUtil.getTheActorsWithWords(JSON.parseObject(data).getJSONArray("dialogs")), dealAudioUrl(path), botId);
+
+ RenderDocument render = new RenderDocument(document);
+ this.setSessionAttribute(PRE_COLLE, null);
+ String trace = getSessionAttribute(BACK_TRACE);
+ if (trace == null || trace.length() != 2) trace = "00";
+ String backTrace = new StringBuilder(trace).append(botId).append(File.separator).toString();
+ this.setSessionAttribute(BACK_TRACE, backTrace);
+ this.addDirective(render);
+ return new Response();
+ }
+
+ private Response enterProductInfo(String productName, String channelId) {
+ ProjectData productDetail = ScheduleServiceNew.getProjectByName(productName);
+ // product picture
+ String imgUrl = new StringBuilder(Constants.IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
+
+ // product create time
+ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+ String dateString = formatter.format(productDetail.getCreateTime());
+ String createTime = new StringBuilder(PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
+
+ // product author
+ String author = new StringBuilder(PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName()).toString();
+
+ // product labels
+ StringBuilder labels = new StringBuilder(PRODUCT_INTRO.LABEL);
+ for (String label: productDetail.getLabels()) {
+ labels.append(PRODUCT_INTRO.SPACE).append(label);
+ }
+
+ // product introduction
+ String intro = productDetail.getIntro();
+
+ // "start product" container button
+ String enterProName = Constants.PRE_ENTER_PRODUCT + productName;
+
+ String accessToken = getAccessToken();
+ String flowers, flowerReward,collectText, collectUrl, collectComId;
+ if (accessToken != null) {
+ // flower container button
+ Long count = DplbotServiceUtil.getUserSendFlowerNum(productDetail.getBotAccount(), getUserId(), channelId,
+ accessToken, getSessionAttribute("userId"));
+ flowers = USER_SEND_FLOWER+count;
+ flowerReward = FLOWE + productDetail.getBotAccount();
+
+ // collection container button
+ boolean collec = DplbotServiceUtil.doesUserCollectThisBot(productDetail.getBotAccount(), accessToken,
+ getUserId(), channelId, getSessionAttribute("userId"));
+ if (collec) {
+ collectText = COLLECED;
+ collectUrl = COLLECTED_IMG_URL;
+ collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
+ } else {
+ collectText = UN_COLLEC;
+ collectUrl = UN_COLLECTED_IMG_URL;
+ collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
+ }
+ } else {
+ flowers = FLOWER;
+ flowerReward = FLOWER_LOAD;
+
+ collectText = UN_COLLEC;
+ collectUrl = UN_COLLECTED_IMG_URL;
+ collectComId = FLOWER_LOAD; // 提示登录
+ }
+
+ ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(imgUrl, correctName(productName), createTime, author, labels.toString(),
+ intro, enterProName, flowerReward, flowers, collectComId, collectUrl, collectText);
+
+ RenderDocument renderDocument = new RenderDocument(document);
+ this.addDirective(renderDocument);
+ String trace = getSessionAttribute(BACK_TRACE);
+ log.info("before trace------------:{}",trace);
+ StringBuilder builder = new StringBuilder();
+ if (trace == null || trace.length() < 2) {
+ builder.append("00");
+ } else if (trace.length()>2) {
+ builder.append(trace, 0, 2);
+ } else {
+ builder.append(trace);
+ }
+
+ trace = builder.append(productDetail.getBotAccount()).toString();
+ log.info("after trace------------:{}",trace);
+ this.setSessionAttribute(BACK_TRACE, trace);
+ return new Response();
+ }
+
+ private RecommandDocument displayFunnyRecommandPage(String word, String audio) {
+ try {
+ List botNames = Utils.getRecommandBotNames(word);
+ log.info("botNames:{}",botNames);
+ List bots = new ArrayList<>();
+ for (String botName : botNames) {
+ ProjectData detail = ScheduleServiceNew.getProjectByName(botName);
+ if (detail == null) continue;
+ bots.add(detail);
+ }
+ if (bots.size() != 0) return RecommendUtil.getFunnyDocument(bots, audio);
+ } catch (Exception e) {
+ log.error("获取funny页出错:{}",e.toString());
+ }
+ return null;
+ }
+
+ private XiaoDuOrderTB buildBeforePayPojo(String botAccount, String appUserId, String userId, int unitPrice,
+ long number, String orderId) {
+ XiaoDuOrderTB xiaoDuOrderTB = new XiaoDuOrderTB();
+ buildPayPojoCommon(xiaoDuOrderTB, botAccount, appUserId, userId, unitPrice, number, orderId);
+ xiaoDuOrderTB.setDevice(1);
+ return xiaoDuOrderTB;
+ }
+
+ private XiaoDuOrderTB buildNoScreenBeforePayPojo(String botAccount, String appUserId, String userId, int unitPrice,
+ long number, String orderId) {
+ XiaoDuOrderTB xiaoDuOrderTB = new XiaoDuOrderTB();
+ buildPayPojoCommon(xiaoDuOrderTB, botAccount, appUserId, userId, unitPrice, number, orderId);
+ xiaoDuOrderTB.setDevice(2);
+ return xiaoDuOrderTB;
+ }
+
+ private void buildPayPojoCommon(XiaoDuOrderTB xiaoDuOrderTB, String botAccount, String appUserId, String userId, int unitPrice,
+ long number, String orderId) {
+ xiaoDuOrderTB.setBotId(botAccount);
+ xiaoDuOrderTB.setAppUserId(appUserId);
+ xiaoDuOrderTB.setXiaoduUserId(userId);
+ xiaoDuOrderTB.setUnitPrice(unitPrice);
+ xiaoDuOrderTB.setNumber(number);
+ xiaoDuOrderTB.setIsBuy(false);
+ xiaoDuOrderTB.setStatus(false);
+ xiaoDuOrderTB.setChOrderId(orderId);
+ xiaoDuOrderTB.setTimeStamp(curTime);
+ }
+
+ @Override
+ protected Response onChargeEvent(ChargeEvent chargeEvent) {
+ String token = chargeEvent.getToken();
+ int sepIndex = token.indexOf(File.separator);
+ final String botAccount = token.substring(0, sepIndex);
+ String str = "恭喜您支付成功,开始体验吧";
+ if (getRequest().getContext().getScreen() != null) {
+ boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, customUserId(), getAccessToken(),
+ getSessionAttribute("userId"), PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_screen");
+ if (response) {
+ Map flowerRecords = USER_HISTORY.get(getUserId()).getUserBotId2Flowers();
+ Long before = flowerRecords.get(botAccount);
+ if (before == null) before = 0L;
+ flowerRecords.put(botAccount, before+1);
+ ExecuteCommands executeCommands = new ExecuteCommands();
+ SetStateCommand stateCommand = new SetStateCommand();
+ stateCommand.setComponentId("pft");
+ stateCommand.setState("text");
+ stateCommand.setValue(USER_SEND_FLOWER+before);
+ executeCommands.addCommand(stateCommand);
+ try {
+ addDirective(executeCommands);
+ } catch (Exception e) {
+ log.info(ExceptionUtils.getStackTrace(e));
+ }
+ } else {
+ str = "很抱歉,您没有支付成功";
+ }
+ } else {
+ String userId = customUserId();
+ String jytUserId = getSessionAttribute("userId");
+ if (StringUtils.isBlank(jytUserId)) jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken(), channel);
+ if (StringUtils.isBlank(jytUserId)) {
+ jytUserId = "null";
+ }
+ boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, userId, getAccessToken(),
+ jytUserId, PRODUCT_ID_DETAIL.get(botAccount).getName(), "xiaodu_no_screen");
+ if (!response) {
+ str = "很抱歉,您没有支付成功";
+ }
+ }
+ return buildErrorResponse(str);
+ }
+
+ @Override
+ protected Response onPlaybackFinishedEvent(PlaybackFinishedEvent playbackFinishedEvent) {
+// log.info("音频播放完毕,开麦");
+// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+ this.setExpectSpeech(true);
+// log.error("FinishedEvent");
+ return new Response();
+ }
+
+ @Override
+ protected Response onPlaybackStoppedEvent(PlaybackStoppedEvent playbackStoppedEvent) {
+// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+ waitAnswer();
+ return new Response();
+ }
+
+ @Override
+ protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
+// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+ Boolean result = stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+customUserId());
+ log.info("音频播放事件删除:"+result);
+ waitAnswer();
+ return new Response();
+ }
+
+ @Override
+ protected Response onPlaybackNearlyFinishedEvent(PlaybackNearlyFinishedEvent playbackNearlyFinishedEvent) {
+// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
+ waitAnswer();
+ return new Response();
+ }
+
+ @Override
+ protected Response onDefaultEvent() {
+ if (getRequest().getRequest() instanceof AudioPlayerEvent) {
+ this.setExpectSpeech(true);
+ return new Response();
+ }
+ return new Response();
+ }
+
+ private String customUserId() {
+ try {
+ return PREFIX_USERID+ URLEncoder.encode(getUserId(), "UTF-8");
+ } catch (Exception e) {
+ log.error("xiaodu userid encode error:{}, {}",e, getUserId());
+ return PREFIX_USERID+ getUserId().replaceAll("/", "");
+ }
+// return PREFIX_USERID + ai.qiwu.com.xiaoduhome.xiaoai.common.Utils.modifyDeviceId(getUserId());
+// return PREFIX_USERID + getUserId().replaceAll(NUM_OR_ALPHA, "");
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplbotServiceUtil.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplbotServiceUtil.java
index c83feb1..e138e50 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplbotServiceUtil.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplbotServiceUtil.java
@@ -10,9 +10,8 @@ import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail;
import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuHistoryBotIdTime;
import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuHistoryTB;
import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB;
-import ai.qiwu.com.xiaoduhome.pojo.JYTUserResponse;
-import ai.qiwu.com.xiaoduhome.pojo.UserBehaviorData;
-import ai.qiwu.com.xiaoduhome.pojo.UserInfoByTokenResult;
+import ai.qiwu.com.xiaoduhome.pojo.*;
+import ai.qiwu.com.xiaoduhome.pojo.data.ProjectData;
import ai.qiwu.com.xiaoduhome.pojo.pageData.HistoryData;
import ai.qiwu.com.xiaoduhome.repository.primary.AppFavoriteTBRepository;
import ai.qiwu.com.xiaoduhome.repository.primary.AppFlowerTBRepository;
@@ -21,6 +20,8 @@ import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuHistoryBotTimeRepositor
import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuHistoryTBRepository;
import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository;
import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
import com.baidu.dueros.data.request.pay.event.ChargeEvent;
import com.baidu.dueros.data.request.pay.event.Payload;
import com.baidu.dueros.data.response.directive.pay.Charge;
@@ -28,7 +29,9 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.data.domain.Example;
+import org.springframework.util.CollectionUtils;
import java.io.File;
import java.io.IOException;
@@ -56,6 +59,11 @@ import static ai.qiwu.com.xiaoduhome.service.ScheduleService.curTime;
*/
@Slf4j
public class DplbotServiceUtil {
+ final static String HOST_UTL;
+ static {
+ HOST_UTL = Config.getProperty("requestHost", "http://didi-gz4.jiaoyou365.com:18082/");
+ log.info("hostUrl:"+HOST_UTL);
+ }
private static final int CORE = Runtime.getRuntime().availableProcessors();
static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(CORE+1, 1500,
@@ -88,21 +96,24 @@ public class DplbotServiceUtil {
}
}
- static String getUsUserId(String userId, String accessToken) {
- UserBehaviorData data = USER_HISTORY.computeIfAbsent(userId, s -> new UserBehaviorData());
- String usId = data.getJytUserId();
- if (usId == null) {
- log.info("getUsUserId:请求getUserIdByToken");
- usId = getUserIdByToken(accessToken);
- data.setJytUserId(usId);
+ static String getUsUserId(String userId, String accessToken, String channelId) {
+ UserBehaviorData data = USER_HISTORY.get(userId);
+ String jytId;
+ if (data == null) {
+ jytId = getUserIdByToken(accessToken, channelId);
+ onLunchFillUserBehaviorData(userId, channelId, jytId);
+ return jytId;
+ } else if (StringUtils.isBlank(data.getJytUserId())) {
+ jytId = getUserIdByToken(accessToken, channelId);
+ data.setJytUserId(jytId);
}
- return usId;
+ return data.getJytUserId();
}
- static String getUserIdByToken(String accessToken) {
+ static String getUserIdByToken(String accessToken, String channelId) {
try {
HashMap headers = new HashMap<>();
- headers.put("App-Channel-Id", "JIAOYOUTIANXIA");
+// headers.put("App-Channel-Id", channelId);
headers.put("Authorization", new StringBuilder(BEARER).append(accessToken).toString());
String str = OkHttp3Utils.doGet(USER_ID_BY_TOKEN, new HashMap<>(), headers);
log.info("getUserIdByToken:{}",str);
@@ -121,39 +132,75 @@ public class DplbotServiceUtil {
return null;
}
- static void onLunchGetUserHistory(final String userId) {
+// static void onLunchGetUserHistory(final String userId) {
+// POOL.submit(() -> {
+// XiaoDuHistoryTBRepository repository = BaseHolder.getBean("xiaoDuHistoryTBRepository");
+// UserBehaviorData data = USER_HISTORY.computeIfAbsent(userId, s -> new UserBehaviorData());
+// HashMap userBotId2History = data.getUserBotId2History();
+// for (XiaoDuHistoryTB historyTB: repository.getByXiaoduUserId(userId)) {
+// userBotId2History.put(historyTB.getBotId(), historyTB.getLastTime());
+// }
+// //log.info("用户历史记录:{}",USER_HISTORY);
+// });
+// }
+
+ static void onLunchFillUserBehaviorData(final String userId, final String channelId, final String jytUserId) {
POOL.submit(() -> {
- XiaoDuHistoryTBRepository repository = BaseHolder.getBean("xiaoDuHistoryTBRepository");
- UserBehaviorData data = USER_HISTORY.computeIfAbsent(userId, s -> new UserBehaviorData());
- HashMap userBotId2History = data.getUserBotId2History();
- for (XiaoDuHistoryTB historyTB: repository.getByXiaoduUserId(userId)) {
- userBotId2History.put(historyTB.getBotId(), historyTB.getLastTime());
+ Map params = new HashMap<>();
+ params.put("userId", userId);
+ params.put("channelId", channelId);
+ try {
+ String response = OkHttp3Utils.doGet(HOST_UTL+"/audio_box/behavior", params);
+ if (StringUtils.isNotBlank(response)) {
+ JSONObject result = JSON.parseObject(response);
+ if (NumberUtils.INTEGER_ONE.equals(result.getInteger("code"))) {
+ result = result.getJSONObject("data");
+ Map botAccount2HistoryTime = result.getObject("history", Map.class);
+ Map botAccount2Flowers = result.getObject("flowers", Map.class);
+ Map botAccount2FavoriteTime = result.getObject("favorite", Map.class);
+ UserBehaviorData data = new UserBehaviorData();
+ if (!CollectionUtils.isEmpty(botAccount2HistoryTime)) data.setUserBotId2History(botAccount2HistoryTime);
+ if (!CollectionUtils.isEmpty(botAccount2FavoriteTime)) data.setUserBotId2Collected(botAccount2FavoriteTime);
+ if (!CollectionUtils.isEmpty(botAccount2Flowers)) data.setUserBotId2Flowers(botAccount2Flowers);
+ data.setJytUserId(jytUserId);
+ USER_HISTORY.put(userId, data);
+ }
+ }
+ } catch (Exception e) {
+ log.warn("onLunch,获取用户信息失败:"+userId);
}
- //log.info("用户历史记录:{}",USER_HISTORY);
});
}
- static void onLunchFillUserBehaviorData(final String accessToken, final String userId) {
- POOL.submit(() -> {
- XiaoDuHistoryTBRepository repository = BaseHolder.getBean("xiaoDuHistoryTBRepository");
- UserBehaviorData data = USER_HISTORY.computeIfAbsent(userId, s -> new UserBehaviorData());
- HashMap userBotId2History = data.getUserBotId2History();
- for (XiaoDuHistoryTB historyTB: repository.getByXiaoduUserId(userId)) {
- userBotId2History.put(historyTB.getBotId(), historyTB.getLastTime());
- }
- if (accessToken != null) {
- log.info("onLunchFillUserBehaviorData:请求getUserIdByToken");
- String jytUserId = DplbotServiceUtil.getUserIdByToken(accessToken);
- if (jytUserId != null) {
+ private static UserBehaviorData onLunchFillUserBehaviorDataInMaster(final String userId,
+ final String channelId, final String jytUserId) {
+ Map params = new HashMap<>();
+ params.put("userId", userId);
+ params.put("channelId", channelId);
+ try {
+ String response = OkHttp3Utils.doGet(HOST_UTL+"/audio_box/behavior", params);
+ if (StringUtils.isNotBlank(response)) {
+ JSONObject result = JSON.parseObject(response);
+ if (NumberUtils.INTEGER_ONE.equals(result.getInteger("code"))) {
+ result = result.getJSONObject("data");
+ Map botAccount2HistoryTime = result.getObject("history", Map.class);
+ Map botAccount2Flowers = result.getObject("flowers", Map.class);
+ Map botAccount2FavoriteTime = result.getObject("favorite", Map.class);
+ UserBehaviorData data = new UserBehaviorData();
+ if (!CollectionUtils.isEmpty(botAccount2HistoryTime)) data.setUserBotId2History(botAccount2HistoryTime);
+ if (!CollectionUtils.isEmpty(botAccount2FavoriteTime)) data.setUserBotId2Collected(botAccount2FavoriteTime);
+ if (!CollectionUtils.isEmpty(botAccount2Flowers)) data.setUserBotId2Flowers(botAccount2Flowers);
data.setJytUserId(jytUserId);
- getUserFavorite(userId, jytUserId);
- getUserSendFlowerInfo(userId,jytUserId);
+ USER_HISTORY.put(userId, data);
+ return data;
}
}
- });
+ } catch (Exception e) {
+ log.warn("onLunch,获取用户信息失败:"+userId);
+ }
+ return null;
}
-
public static ThreadPoolExecutor getPOOL() {
return POOL;
}
@@ -180,28 +227,16 @@ public class DplbotServiceUtil {
return builder.toString();
}
- static boolean doesUserCollectThisBot(String botID, String accessToken, String userId) {
+ static boolean doesUserCollectThisBot(String botID, String accessToken, String userId, String channelId, String jytUserId) {
boolean collected = false;
if (accessToken != null) {
UserBehaviorData userData = USER_HISTORY.get(userId);
- if (userData != null) {
- collected = userData.getUserBotId2Collected().containsKey(botID);
- } else {
- POOL.submit(() -> getUserFavorite(userId, getUsUserId(userId, accessToken)));
- try {
- String jytUserId = getUsUserId(userId, accessToken);
- if (jytUserId != null) {
- AppFavoriteTBRepository repository = BaseHolder.getBean("appFavoriteTBRepository");
-// AppFavoriteTB tb = new AppFavoriteTB();
-// tb.setBotId(botID);
-// tb.setUserId(Long.parseLong(jytUserId));
-// Example example = Example.of(tb);
-// collected = repository.exists(example);
- collected = repository.existsByBotIdAndUserId(botID, jytUserId);
- }
- } catch (Exception e) {
- }
+ if (userData == null) {
+ if (StringUtils.isBlank(jytUserId)) jytUserId = getUserIdByToken(accessToken, channelId);
+ userData = onLunchFillUserBehaviorDataInMaster(userId, channelId, jytUserId);
+ if (userData == null) return false;
}
+ collected = userData.getUserBotId2Collected().containsKey(botID);
}
return collected;
}
@@ -212,107 +247,60 @@ public class DplbotServiceUtil {
return text.substring(i1+1, i2);
}
- static Long getUserSendFlowerNum(String botAccount, String userID, String accessToken) {
- UserBehaviorData data = USER_HISTORY.get(userID);
- if (data != null) {
+ static Long getUserSendFlowerNum(String botAccount, String userID, String channelId, String accessToken, String jytUserId) {
+ if (accessToken != null) {
+ UserBehaviorData data = USER_HISTORY.get(userID);
+ if (data == null) {
+ if (StringUtils.isBlank(jytUserId)) jytUserId = getUserIdByToken(accessToken, channelId);
+ data = onLunchFillUserBehaviorDataInMaster(userID, channelId, jytUserId);
+ if (data == null) return 0L;
+ }
Long count = data.getUserBotId2Flowers().get(botAccount);
if (count == null) count = 0L;
return count;
- } else {
- onLunchFillUserBehaviorData(accessToken, userID);
- AppFlowerTBTintRepository repository = BaseHolder.getBean("appFlowerTBTintRepository");
- List tinies = repository.getByUserIdAndBotId(userID, botAccount);
- if (tinies != null) {
- long sum = 0;
- for (AppFlowerTBTiny tiny:tinies) {
- sum += tiny.getNumber();
- }
- return sum;
- }
}
return 0L;
}
- static boolean didUserCollecThisProduct(String botAccount, String userID, String accessToken, String jytUserId) {
+ static boolean didUserCollecThisProduct(String botAccount, String userID,
+ String jytUserId, String channelId) {
UserBehaviorData data = USER_HISTORY.get(userID);
- if (data != null) {
- Long time = data.getUserBotId2Collected().get(botAccount);
- return time != null;
- } else {
- onLunchFillUserBehaviorData(accessToken, userID);
- if (jytUserId == null) {
- log.info("didUserCollecThisProduct:请求getUserIdByToken");
- jytUserId = getUserIdByToken(accessToken);
- }
- if (jytUserId == null) return false;
- AppFavoriteTBRepository repository = BaseHolder.getBean("appFavoriteTBRepository");
-// AppFavoriteTB favorite = new AppFavoriteTB();
-// favorite.setUserId(Long.parseLong(jytUserId));
-// favorite.setBotId(botAccount);
-// Example example = Example.of(favorite);
-// return repository.exists(example);
- return repository.existsByBotIdAndUserId(botAccount, jytUserId);
- }
+ if (data == null) data = onLunchFillUserBehaviorDataInMaster(userID, channelId, jytUserId);
+ if (data == null) return false;
+ Long time = data.getUserBotId2Collected().get(botAccount);
+ return time != null;
}
- static void userUnCollectTheBotInPool(final String userId, final String botAccount, final String accessToken) {
- POOL.submit(() -> userUnCollectTheBot(userId, botAccount, accessToken));
- }
-
- private static void userUnCollectTheBot(String userId, String botAccount, String accessToken) {
- String jytUserId = getUsUserId(userId, accessToken);
- if (jytUserId != null) {
- AppFavoriteTBRepository repository = BaseHolder.getBean("appFavoriteTBRepository");
- repository.deleteByBotIdAndUserId(botAccount, jytUserId);
- }
-
+ static void userUnCollectTheBot(final String userId, final String botAccount, String channelId,
+ String jytUserId, String accessToken) {
UserBehaviorData behaviorData = USER_HISTORY.get(userId);
+ if (behaviorData == null) {
+ if (StringUtils.isBlank(jytUserId)) jytUserId = getUserIdByToken(accessToken, channelId);
+ behaviorData = onLunchFillUserBehaviorDataInMaster(userId, channelId, jytUserId);
+ }
if (behaviorData != null) {
behaviorData.getUserBotId2Collected().remove(botAccount);
- } else {
- if (jytUserId != null) {
- UserBehaviorData data = USER_HISTORY.computeIfAbsent(userId, s -> new UserBehaviorData());
- data.setJytUserId(jytUserId);
- getUserFavorite(userId, jytUserId);
- getUserSendFlowerInfo(userId, jytUserId);
- }
}
}
- static void userCollectTheBotInPool(final String userId, final String botAccount, final String accessToken) {
- POOL.submit(() -> userCollectTheBot(userId, botAccount, accessToken));
- }
-
- private static void userCollectTheBot(String userId, String botAccount, String accessToken) {
- String jytUserId = getUsUserId(userId, accessToken);
- if (jytUserId != null) {
- AppFavoriteTBRepository repository = BaseHolder.getBean("appFavoriteTBRepository");
- AppFavoriteTB entity = new AppFavoriteTB();
- entity.setBotId(botAccount);
- entity.setUserId(jytUserId);
- entity.setModule(0);
- repository.save(entity);
- }
+ static void userCollectTheBot(String userId, String botAccount, String channelId, String jytUserId, String accessToken) {
UserBehaviorData behaviorData = USER_HISTORY.get(userId);
+ if (behaviorData == null) {
+ if (StringUtils.isBlank(jytUserId)) jytUserId = getUserIdByToken(accessToken, channelId);
+ behaviorData = onLunchFillUserBehaviorDataInMaster(userId, channelId, jytUserId);
+ }
if (behaviorData != null) {
behaviorData.getUserBotId2Collected().put(botAccount, curTime);
- } else {
- if (jytUserId != null) {
- UserBehaviorData data = USER_HISTORY.computeIfAbsent(userId, s -> new UserBehaviorData());
- data.setJytUserId(jytUserId);
- getUserFavorite(userId, jytUserId);
- getUserSendFlowerInfo(userId, jytUserId);
- }
}
}
- static Charge sendOneFlowerByCharge(String userId, String jytUserId, String accessToken, String trace) {
+ static Charge sendOneFlowerByCharge(String userId, String jytUserId, String accessToken, String trace, String channelId) {
String price = ScheduleService.FLOWER_UNIT_PRICE;
int unitPrice = Integer.parseInt(price);
String amount = String.valueOf(unitPrice/100.0);
- String orderId = new StringBuilder(userId).append(System.currentTimeMillis()).toString();
+ String orderId = new StringBuilder(userId).append("_").append(System.currentTimeMillis()).toString();
if (jytUserId == null) {
- jytUserId = getUsUserId(userId, accessToken);
+ jytUserId = getUsUserId(userId, accessToken, channelId);
if (jytUserId == null) return null;
}
String botId;
@@ -357,29 +345,23 @@ public class DplbotServiceUtil {
return xiaoDuOrderTB;
}
- static boolean doesUserPlayed(String botAccount, String userId, String accessToken) {
+ static boolean doesUserPlayed(String botAccount, String userId, String channelId) {
UserBehaviorData data = USER_HISTORY.get(userId);
- if (data != null) return data.getUserBotId2History().containsKey(botAccount);
- onLunchFillUserBehaviorData(accessToken, userId);
- return false;
+ if (data == null) data = onLunchFillUserBehaviorDataInMaster(userId, channelId, null);
+ if (data == null) return false;
+ return data.getUserBotId2History().containsKey(botAccount);
}
- static void updateTheUserHistory(final String userId,final String botAccount, final String accessToken) {
+ static void updateTheUserHistory(final String userId,final String botAccount, final String accessToken,
+ final String channelId) {
POOL.submit(() -> {
UserBehaviorData data = USER_HISTORY.get(userId);
if (data == null) {
- XiaoDuHistoryTBRepository repository = BaseHolder.getBean("xiaoDuHistoryTBRepository");
- XiaoDuHistoryTB historyTB = repository.getByXiaoduUserIdAndBotId(userId, botAccount);
- if (historyTB == null) {
- historyTB = new XiaoDuHistoryTB();
- historyTB.setLastTime(curTime);
- historyTB.setBotId(botAccount);
- historyTB.setXiaoduUserId(userId);
- } else {
- historyTB.setLastTime(curTime);
+ String jytUserId = null;
+ if (accessToken != null) {
+ jytUserId = getUserIdByToken(accessToken, channelId);
}
- repository.save(historyTB);
- onLunchFillUserBehaviorData(accessToken, userId);
+ onLunchFillUserBehaviorDataInMaster(userId, channelId, jytUserId);
} else {
data.getUserBotId2History().put(botAccount, curTime);
}
@@ -425,7 +407,10 @@ public class DplbotServiceUtil {
final String num = token.substring(sepIndex+1);
POOL.submit(() -> {
XiaoDuOrderTbRepository repository = BaseHolder.getBean("xiaoDuOrderTbRepository");
+ Long id = 0L;
try {
+ XiaoDuOrderTB tb = repository.getByChOrderId(chOrderId);
+ id = tb.getId();
repository.updateAterSeccessPayed(baiduOrderReferenceId,chOrderId);
} catch (Exception e) {
// StringWriter writer = new StringWriter();
@@ -433,30 +418,28 @@ public class DplbotServiceUtil {
log.error("更新用户{}的支付状态出错:{},订单信息:订单号:{}.baiduOrderId:{},createTime:{}",
e.toString(),userId, chOrderId, baiduOrderReferenceId, createTimestamp);
}
+
try {
String appUserId = jytUserId;
- if (StringUtils.isBlank(jytUserId)) appUserId = getUsUserId(userId,accessToken);
- if (StringUtils.isBlank(jytUserId)) {
+ if (StringUtils.isBlank(appUserId)) appUserId = getUsUserId(userId,accessToken, channelId);
+ if (StringUtils.isBlank(appUserId)) {
log.error("像app_flower_tb中添加数据失败因为无法获取到用户的id,数据信息:botAccount:{},num:{},xiaoduUserId:{}",
botAccount,num,userId);
return;
}
- if ("null".equals(jytUserId)) {
+ if ("null".equals(appUserId)) {
log.error("小度无屏在向app-flower_tb插入数据时没有获取到此用户登录的userID,数据信息:botAccount:{},num:{},xiaoduUserId:{}",
botAccount,num,userId);
}
- AppFlowerTBRepository flower = BaseHolder.getBean("appFlowerTBRepository");
- AppFlowerTB flowerTB = new AppFlowerTB();
- flowerTB.setBotName(botAccount);
- flowerTB.setModule(0);
- flowerTB.setNumber(Long.parseLong(num));
- flowerTB.setOrderId(0L);
- flowerTB.setStatus(1);
- flowerTB.setUnitPrice(Double.parseDouble(Config.getProperty("unitPrice", Constants.UNIT_PRICE))/100);
- flowerTB.setUserId(appUserId);
- flowerTB.setWorkName(workName);
- flowerTB.setChannelId(channelId);
- flower.save(flowerTB);
+ SendFlowerVO vo = new SendFlowerVO();
+ vo.setBotAccount(botAccount);
+ vo.setChannelId(channelId);
+ vo.setName(workName);
+ vo.setNum(Long.parseLong(num));
+ vo.setUnitPrice(Double.parseDouble(Config.getProperty("unitPrice", Constants.UNIT_PRICE))/100);
+ vo.setOrderId(id);
+ vo.setUserId(appUserId);
+ OkHttp3Utils.doPostJsonStr(HOST_UTL+"/audio_box/flower", JSON.toJSONString(vo));
} catch (Exception e) {
log.error("像app_flower_tb中添加数据失败,{},数据信息:botAccount:{},num:{},xiaoduUserId:{}",
e.toString(),botAccount,num,userId);
@@ -473,80 +456,63 @@ public class DplbotServiceUtil {
}
}
- static void updateTheUserBehaviorDataMark(final String userId, final String botAccount, final String accessToken) {
+ static void updateTheUserBehaviorDataMark(final String userId, final String botAccount,
+ final String accessToken, final String jytUserId) {
POOL.submit(() -> {
UserBehaviorData data = USER_HISTORY.get(userId);
if (data != null) {
data.setMark((byte) 1);
data.getUserBotId2History().put(botAccount, curTime);
} else {
- XiaoDuHistoryTBRepository repository = BaseHolder.getBean("xiaoDuHistoryTBRepository");
- UserBehaviorData behaviorData = USER_HISTORY.computeIfAbsent(userId, s -> new UserBehaviorData());
- HashMap userBotId2History = behaviorData.getUserBotId2History();
- for (XiaoDuHistoryTB historyTB: repository.getByXiaoduUserId(userId)) {
- userBotId2History.put(historyTB.getBotId(), historyTB.getLastTime());
- }
- userBotId2History.put(botAccount, curTime);
- behaviorData.setMark((byte) 1);
- if (accessToken != null) {
- log.info("onLunchFillUserBehaviorData:请求getUserIdByToken");
- String jytUserId = DplbotServiceUtil.getUserIdByToken(accessToken);
- if (jytUserId != null) {
- behaviorData.setJytUserId(jytUserId);
- getUserFavorite(userId, jytUserId);
- getUserSendFlowerInfo(userId,jytUserId);
- }
- }
+ onLunchFillUserBehaviorDataInMaster(userId, accessToken, jytUserId);
}
});
}
- static CollectHistoryDocument getCollectPage(String userId, String accessToken, String jytId, int start) {
- List favoriteProducts = new ArrayList<>();
+ static CollectHistoryDocument getCollectPage(String userId, String accessToken, String jytId, int start, String channelId) {
UserBehaviorData behaviorData = USER_HISTORY.get(userId);
- int pageNum = 0;
+ int pageNum;
if (behaviorData == null) {
- onLunchFillUserBehaviorData(accessToken, userId);
- if (jytId == null) jytId = getUserIdByToken(accessToken);
- if (jytId != null) {
- AppFavoriteTBRepository favorite = BaseHolder.getBean("appFavoriteTBRepository");
- favoriteProducts = favorite.getFavoriteLimit(jytId, start);
- }
- }else {
- int bound = behaviorData.getUserBotId2Collected().size();
- if (start >= bound) {
- return null;
- }
- pageNum = bound/CO_HI_PAGE_SIZE + (bound%CO_HI_PAGE_SIZE == 0 ? 0 : 1);
- log.info("collect/history: pagesize:{},bound{}",pageNum,bound);
- TreeMap order = new TreeMap<>((o1, o2) -> (o1 < o2) ? 1 : ((o1.equals(o2)) ? 0 : -1));
- for (Map.Entry entry: behaviorData.getUserBotId2Collected().entrySet()) {
- order.put(entry.getValue(), entry.getKey());
- }
- int i = 0, e = start+CO_HI_PAGE_SIZE;
- for (Map.Entry entry: order.entrySet()) {
- if (i == e) break;
- if (i++ >= start) {
- favoriteProducts.add(entry.getValue());
- }
+ if (StringUtils.isBlank(jytId)) jytId = getUserIdByToken(accessToken,channelId);
+ behaviorData = onLunchFillUserBehaviorDataInMaster(userId, channelId, jytId);
+ if (behaviorData == null) return null;
+ }
+ Map userBotId2Collected = behaviorData.getUserBotId2Collected();
+ int bound = userBotId2Collected.size();
+ if (start >= bound) {
+ return null;
+ }
+ pageNum = bound/CO_HI_PAGE_SIZE + (bound%CO_HI_PAGE_SIZE == 0 ? 0 : 1);
+ log.info("collect/history: pagesize:{},bound{}",pageNum,bound);
+ TreeMap order = new TreeMap<>((o1, o2) -> (o1 < o2) ? 1 : ((o1.equals(o2)) ? 0 : -1));
+ for (Map.Entry entry: userBotId2Collected.entrySet()) {
+ order.put(entry.getValue(), entry.getKey());
+ }
+ List favoriteProducts = new ArrayList<>();
+ int i = 0, e = start+CO_HI_PAGE_SIZE;
+ for (Map.Entry entry: order.entrySet()) {
+ if (i == e) break;
+ if (i++ >= start) {
+ favoriteProducts.add(entry.getValue());
}
}
+
log.info("favoriteProducts length:{}, start:{}", favoriteProducts.size(), start);
if (favoriteProducts.size() == 0) return null;
ArrayList projectInfoList = new ArrayList<>();
- int i = 1;
+ int j = 1;
//log.info("id list:{}", favoriteProducts);
final StringBuilder build = new StringBuilder();
for (String botAccount :favoriteProducts) {
build.append(botAccount).append(File.separator);
- OnProductDetail productDetail = ScheduleService.getProductIdDetail().get(botAccount);
+ ProjectData productDetail = ScheduleServiceNew.getProjectByBotAccount(botAccount);
String intro = productDetail.getIntro();
if (StringUtils.isBlank(intro)) intro = "作者太懒没写介绍";
String imgUrl = new StringBuilder(IMG_PREFIX).append(productDetail.getBannerImgUrl()).toString();
String botAccountId = new StringBuilder(Constants.PRE_PRODUCT_IMG).append(correctName(productDetail.getName())).toString();
String name = productDetail.getName();
- HistoryData data = new HistoryData(botAccountId, i++, imgUrl, correctName(name), intro);
+ HistoryData data = new HistoryData(botAccountId, j++, imgUrl, correctName(name), intro);
data.setAuthorName(productDetail.getAuthorName());
projectInfoList.add(data);
}
@@ -561,15 +527,15 @@ public class DplbotServiceUtil {
return collectHistoryDocument;
}
- static CollectHistoryDocument getHistory(String userId, String accessToken, int start) {
+ static CollectHistoryDocument getHistory(String userId, String accessToken,String jytUserId, int start, String channelId) {
List historyProducts = new ArrayList<>();
UserBehaviorData behaviorData = USER_HISTORY.get(userId);
int pageNum = 0;
if (behaviorData == null) {
- onLunchFillUserBehaviorData(accessToken, userId);
- XiaoDuHistoryBotTimeRepository historyRepository = BaseHolder.getBean("xiaoDuHistoryBotTimeRepository");
- historyProducts = historyRepository.getByXiaoduUserIdLimit(userId, start);
- } else {
+ if (StringUtils.isBlank(jytUserId) && StringUtils.isNotBlank(accessToken)) jytUserId = getUserIdByToken(accessToken, channelId);
+ behaviorData = onLunchFillUserBehaviorDataInMaster(userId, channelId, jytUserId);
+ }
+ if (behaviorData != null) {
try {
int bound = behaviorData.getUserBotId2History().size();
if (start >= bound) return null;
@@ -589,38 +555,39 @@ public class DplbotServiceUtil {
}
}
} catch (Exception e){}
+ if (historyProducts.size() == 0) return null;
+
+ ArrayList projectInfoList = new ArrayList<>();
+ int i = 1;
+ final StringBuilder build = new StringBuilder();
+ SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
+ historyProducts.sort((o1, o2) -> (o1.getLastTime() projectInfoList = new ArrayList<>();
- int i = 1;
- final StringBuilder build = new StringBuilder();
- SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
- historyProducts.sort((o1, o2) -> (o1.getLastTime() getTheActorsWithWords(JSONArray array) {
+ if (array != null && array.size() > 0) {
+ JSONObject job;
+ ActorWithWord aw;
+ List list= new ArrayList<>();
+ for (Object ob: array) {
+ job = (JSONObject)ob;
+ aw = new ActorWithWord();
+ aw.setActor(job.getString("npcName"));
+ aw.setText(job.getString("text"));
+ list.add(aw);
+ }
+ return list;
+ }
+ return null;
+ }
+
public static String[] seperateActorWord(String text, Pattern pattern) {
String[] actorWords = pattern.split(text);
if (StringUtils.startsWith(text.trim(), "【")) {
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java
index c991d7a..7afc928 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java
@@ -2,27 +2,15 @@ package ai.qiwu.com.xiaoduhome.service;
import ai.qiwu.com.xiaoduhome.common.Constants;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
-import ai.qiwu.com.xiaoduhome.common.Utils;
import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest;
import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse;
import ai.qiwu.com.xiaoduhome.pojo.playAside.AsideImageResponse;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest;
-import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
-import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import javax.servlet.http.HttpServletRequest;
-import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStreamReader;
-import java.nio.charset.StandardCharsets;
-import java.util.Enumeration;
import java.util.HashMap;
-import java.util.Random;
/**
* @author 苗权威
@@ -64,8 +52,8 @@ class RequestTerminal {
// case 4 : headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");break;
// default: headers.put("App-Channel-Id", "jiaoyou-audio-test");
// }
- return OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, requestJsonStr, headers);
-// return OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, headers);
+// 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 {
@@ -117,8 +105,8 @@ class RequestTerminal {
requestPojo.setUid(userId);
requestPojo.setMsg("退出");
String requestJsonStr = JSON.toJSONString(requestPojo);
-// OkHttp3Utils.backPostAsync("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, type);
- OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr, type);
+ OkHttp3Utils.backPostAsync("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, type);
+// OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr, type);
}
static void backRequestDU2(String userId, int type) {
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleService.java
index c8e2dc8..caa268e 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleService.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleService.java
@@ -106,8 +106,36 @@ public class ScheduleService implements InitializingBean {
// });
// }
- @Scheduled(cron = "0 */30 * * * ?")
- public void cleatUserBehaviorData() {
+ @Scheduled(cron = "0 0 17 * * ?")
+ public void initAllOnTableProductInfo() {
+ new Thread(() -> {
+ ALL_ON_PRODUCT = allOnProductInfoRepository.findAllByApplyStatusAndScoreNot(1, 0f);
+ allProductCount = ALL_ON_PRODUCT.size();
+ rankPageSize = allProductCount / RE_RA_CA_PAGE_SIZE + (allProductCount%RE_RA_CA_PAGE_SIZE == 0 ? 0:1);
+ TreeMap rankOrder = new TreeMap<>((o1, o2) -> o1-o2 < 0 ? 1 :(o1.equals(o2) ? 0 : -1));
+ HashMap nd = new HashMap<>();
+ HashMap id = new HashMap<>();
+ for (OnProductDetail item : ALL_ON_PRODUCT) {
+ String productName = item.getName();
+ String botAccount = item.getBotAccount();
+ List labels = projectLabelRepository.productLabels(item.getId());
+ //PRODUCT_LABELS.put(productName, labels);
+ item.setLabels(labels);
+ nd.put(productName, item);
+ id.put(botAccount, item);
+ rankOrder.put(item.getWatch(), item);
+ }
+ PRODUCT_NAME_DETAIL = nd;
+ PRODUCT_ID_DETAIL = id;
+ RANK_ORDER_IDs = new ArrayList<>(rankOrder.values());
+ RecommendUtil.setRankDocument(null);
+ //log.info("作品详细信息:{}", PRODUCT_NAME_DETAIL);
+ }).start();
+ //log.error("更新推荐页出错:{}", e.getMessage());
+ }
+
+ @Scheduled(cron = "0 * */1 * * ?")
+ public void clearUserBehaviorData() {
DplbotServiceUtil.POOL.submit(() -> {
List needClear = new ArrayList<>();
for (String userId: DplbotServiceUtil.USER_HISTORY.keySet()) {
@@ -116,25 +144,6 @@ public class ScheduleService implements InitializingBean {
if (data.getMark() == 1) data.setMark((byte) 0);
else {
needClear.add(userId);
- XiaoDuHistoryTBRepository repository = BaseHolder.getBean("xiaoDuHistoryTBRepository");
- for (Map.Entry entry: data.getUserBotId2History().entrySet()) {
- String botId = entry.getKey();
- Long time = entry.getValue();
- XiaoDuHistoryTB historyTB = repository.getByXiaoduUserIdAndBotId(userId, botId);
- if (historyTB == null) {
- historyTB = new XiaoDuHistoryTB();
- historyTB.setLastTime(time);
- historyTB.setBotId(botId);
- historyTB.setXiaoduUserId(userId);
- } else {
- if (historyTB.getLastTime().equals(time)) continue;
- historyTB.setLastTime(time);
- }
- repository.save(historyTB);
- }
- data.setUserBotId2Collected(null);
- data.setUserBotId2Flowers(null);
- data.setUserBotId2History(null);
}
}
}
@@ -142,12 +151,12 @@ public class ScheduleService implements InitializingBean {
});
}
-// @Scheduled(cron = "*/10 * * * * ?")
+ @Scheduled(cron = "*/30 * * * * ?")
public void updateTheCurTime() {
DplbotServiceUtil.POOL.submit(() -> curTime = System.currentTimeMillis());
}
- @Scheduled(cron = "0 0 19 * * ?")
+// @Scheduled(cron = "0 0 19 * * ?")
public void initRankingList() {
new Thread(() -> {
RANKING_LIST = gameProjectTbRepository.findFirst8();
@@ -157,7 +166,7 @@ public class ScheduleService implements InitializingBean {
//log.error("更新排行榜出错:{}", e.getMessage());
}
- @Scheduled(cron = "0 0 */2 * * ?")
+// @Scheduled(cron = "0 0 */2 * * ?")
public void initRecommendList() {
new Thread(() -> {
RECOMMEND_LIST = gameProjectTbRepository.recommendList();
@@ -167,34 +176,6 @@ public class ScheduleService implements InitializingBean {
//log.error("更新推荐页出错:{}", e.getMessage());
}
- @Scheduled(cron = "0 0 17 * * ?")
- public void initAllOnTableProductInfo() {
- new Thread(() -> {
- ALL_ON_PRODUCT = allOnProductInfoRepository.findAllByApplyStatusAndScoreNot(1, 0f);
- allProductCount = ALL_ON_PRODUCT.size();
- rankPageSize = allProductCount / RE_RA_CA_PAGE_SIZE + (allProductCount%RE_RA_CA_PAGE_SIZE == 0 ? 0:1);
- TreeMap rankOrder = new TreeMap<>((o1, o2) -> o1-o2 < 0 ? 1 :(o1.equals(o2) ? 0 : -1));
- HashMap nd = new HashMap<>();
- HashMap id = new HashMap<>();
- for (OnProductDetail item : ALL_ON_PRODUCT) {
- String productName = item.getName();
- String botAccount = item.getBotAccount();
- List labels = projectLabelRepository.productLabels(item.getId());
- //PRODUCT_LABELS.put(productName, labels);
- item.setLabels(labels);
- nd.put(productName, item);
- id.put(botAccount, item);
- rankOrder.put(item.getWatch(), item);
- }
- PRODUCT_NAME_DETAIL = nd;
- PRODUCT_ID_DETAIL = id;
- RANK_ORDER_IDs = new ArrayList<>(rankOrder.values());
- RecommendUtil.setRankDocument(null);
- //log.info("作品详细信息:{}", PRODUCT_NAME_DETAIL);
- }).start();
- //log.error("更新推荐页出错:{}", e.getMessage());
- }
-
@Scheduled(cron = "0 0 1 * * ?")
public void initProductList() {
new Thread(() -> {
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java
new file mode 100644
index 0000000..ac74fed
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java
@@ -0,0 +1,83 @@
+package ai.qiwu.com.xiaoduhome.service;
+
+import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
+import ai.qiwu.com.xiaoduhome.pojo.data.ProjectData;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.stereotype.Component;
+import org.springframework.util.CollectionUtils;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * @author 苗权威
+ * @dateTime 20-1-15 下午8:24
+ */
+@Slf4j
+@Component
+public class ScheduleServiceNew implements InitializingBean {
+ public static volatile List allProjects = new ArrayList<>();
+ private static volatile Map botAccount2Project = new HashMap<>();
+ private static volatile Map name2Project = new HashMap<>();
+ private static volatile Map> channel2BotAccountList = new HashMap<>();
+
+ @Override
+ public void afterPropertiesSet() throws Exception {
+ getAllProjects();
+ }
+
+ private void getAllProjects() {
+ new Thread(() -> {
+ try {
+ String response = OkHttp3Utils.doGet(DplbotServiceUtil.HOST_UTL+"/audio_box/project");
+ if (StringUtils.isNotBlank(response)) {
+ JSONObject object = JSON.parseObject(response);
+ List list = object.getObject("bots", List.class);
+ Map> map = object.getObject("channelAcc", Map.class);
+ if (!CollectionUtils.isEmpty(list)) {
+ final Map botAcc = new HashMap<>();
+ final Map name = new HashMap<>();
+ list.forEach(projectData -> {
+ botAcc.put(projectData.getBotAccount(), projectData);
+ name.put(projectData.getName(), projectData);
+ });
+ botAccount2Project = botAcc;
+ name2Project = name;
+ allProjects = list;
+ }
+ if (!CollectionUtils.isEmpty(map)) {
+ channel2BotAccountList = map;
+ }
+ }
+ } catch (Exception e) {
+ log.warn("ScheduleServiceNew#getAllProjects获取所有作品信息失败:"+e);
+ }
+ }).start();
+ }
+
+ static ProjectData getProjectByName(String name) {
+ return name2Project.get(name);
+ }
+
+ static ProjectData getProjectByBotAccount(String botAccount) {
+ return botAccount2Project.get(botAccount);
+ }
+
+ public static List getTheChannelAllProjectData(String channel) {
+ return channel2BotAccountList.get(channel).keySet().stream().map(s -> botAccount2Project.get(s)).collect(Collectors.toList());
+ }
+
+ public static List getTheChannelProjectsByWatch(String channel) {
+ TreeMap order = new TreeMap<>(Comparator.reverseOrder());
+ channel2BotAccountList.get(channel).forEach((key, value) -> order.put(value, key));
+ List datas = new ArrayList<>();
+ for (String botAcc: order.values()) {
+ datas.add(botAccount2Project.get(botAcc));
+ }
+ return datas;
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/InitialData.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/InitialData.java
index 03274b5..94edd90 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/InitialData.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/InitialData.java
@@ -30,8 +30,13 @@ public class InitialData implements InitializingBean {
@Value("${csvDic}")
private String csvDic;
- private static volatile Map>> recordMap;
- private static volatile Map>>> audioMap;
+ @Value("${csvChildDic}")
+ private String csvChildDic;
+
+ static volatile Map>> recordMap;
+ static volatile Map>> childRecordMap;
+ static volatile Map>>> audioMap;
+ static volatile Map>>> childAudioMap;
static volatile Map botAccount2ItsCache;
static {
@@ -106,6 +111,71 @@ public class InitialData implements InitializingBean {
} catch (Exception e) {
log.error(e.toString());
}
+
+ try {
+ File[] csvFiles = new File(csvChildDic).listFiles((dir, name) -> StringUtils.endsWith(name, ".csv"));
+ if (csvFiles != null && csvFiles.length != 0) {
+ CSVParser reader;
+ for (File file: csvFiles) {
+ String fileName = file.getName();
+ int i = fileName.indexOf("_");
+ String botAccount = fileName.substring(0, i);
+ boolean record = Integer.valueOf(fileName.substring(i+1, i+2)) == 1;
+ reader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader(
+ new FileInputStream(file), Charset.forName("UTF-8"))));
+ if (record) {
+ if (childRecordMap.containsKey(botAccount)) {
+ log.error("重复:{}",fileName);
+ continue;
+ }
+ Map> npcName2nameId = childRecordMap.computeIfAbsent(botAccount, s -> new HashMap<>());
+ int j = 0;
+ // "person", "mood", "md5", "id", "upUrl"
+ for (CSVRecord line: reader) {
+ if (j == 0) {
+ j++;
+ continue;
+ }
+ String npcName = line.get(0);
+ String md5 = line.get(2);
+ md5 = md5.substring(0, md5.indexOf("."));
+ String id = line.get(3);
+ Map mp3Name2Id = npcName2nameId.computeIfAbsent(npcName, s -> new HashMap<>());
+ mp3Name2Id.put(md5, id);
+ }
+ botAccount2ItsCache.put(botAccount, true);
+ } else {
+ if (childAudioMap.containsKey(botAccount)) {
+ log.error("重复:{}",fileName);
+ continue;
+ }
+ Map>> person2toneMd5Id = childAudioMap.computeIfAbsent(botAccount, s -> new HashMap<>());
+ int j = 0;
+ for (CSVRecord line: reader) {
+ if (j == 0) {
+ j++;
+ continue;
+ }
+ String person = line.get(0);
+ String mood = line.get(1);
+ String md5 = line.get(2);
+ if (StringUtils.endsWith(md5, ".wav")) continue;
+ md5 = md5.substring(0, md5.indexOf("."));
+ String id = line.get(3);
+ Map> tone2Md5Id = person2toneMd5Id.computeIfAbsent(person, s -> new HashMap<>());
+ Map md52Id = tone2Md5Id.computeIfAbsent(mood, s -> new HashMap<>());
+ md52Id.put(md5, id);
+ }
+ botAccount2ItsCache.put(botAccount, false);
+ }
+ reader.close();
+ }
+ } else {
+ log.warn("没有数据文件");
+ }
+ } catch (Exception e) {
+ log.error(e.toString());
+ }
}
static String getRecordId(String botAccount, String npcName, String text) {
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritRedisService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritRedisService.java
new file mode 100644
index 0000000..38a2452
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritRedisService.java
@@ -0,0 +1,495 @@
+package ai.qiwu.com.xiaoduhome.spirit;
+
+import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
+import ai.qiwu.com.xiaoduhome.common.Utils;
+import ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
+import com.alibaba.da.coin.ide.spi.meta.Action;
+import com.alibaba.da.coin.ide.spi.meta.AskedInfoMsg;
+import com.alibaba.da.coin.ide.spi.meta.ExecuteCode;
+import com.alibaba.da.coin.ide.spi.meta.ResultType;
+import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
+import com.alibaba.da.coin.ide.spi.standard.TaskResult;
+import com.alibaba.fastjson.JSON;
+import com.baidu.dueros.data.response.directive.Directive;
+import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective;
+import com.baidu.dueros.model.Response;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.csv.CSVFormat;
+import org.apache.commons.csv.CSVParser;
+import org.apache.commons.csv.CSVRecord;
+import org.apache.commons.lang3.RandomUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+
+import java.io.*;
+import java.nio.charset.Charset;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import static ai.qiwu.com.xiaoduhome.spirit.InitialData.*;
+import static ai.qiwu.com.xiaoduhome.spirit.InitialData.botAccount2ItsCache;
+
+/**
+ * @author 苗权威
+ * 20-1-9 下午5:04
+ */
+@Service
+@Slf4j
+public class SpiritRedisService {
+ @Value("${csvDic}")
+ private String csvDic;
+
+ @Value("${csvChildDic}")
+ private String csvChildDic;
+
+ private static final String AB_REGEX = "\uD83C\uDD70(.*?)\uD83C\uDD71";
+
+ private final StringRedisTemplate stringRedisTemplate;
+
+ public static final String PREFIX_REDIS = "audio_box_";
+
+ public static final String PREFIX_REDIS_IDLE = "audio_idle_";
+
+ public SpiritRedisService(StringRedisTemplate stringRedisTemplate) {
+ this.stringRedisTemplate = stringRedisTemplate;
+ }
+
+ /**
+ * 获取返回给天猫的数据
+ * @param request 请求参数
+ * @return 返回数据封装在开发包中的TaskResult
+ */
+ public TaskResult getResponse(TaskQuery request, int type) {
+ return getNeededParam(request, type);
+ }
+
+ /**
+ * 解析获取需要的参数信息:用户的话,用户的id,意图id
+ * @param request 请求参数
+ * @return 返回数据封装在开发包中的TaskResult
+ */
+ private TaskResult getNeededParam(TaskQuery request, int type) {
+ String userId = getUserId(request);
+ String redisId = PREFIX_REDIS+userId;
+ if (StringUtils.isBlank(userId)) return buildTextTaskResult("不好意思好像出了什么问题,正在抓紧修复中", request.getIntentId());
+ Long intentId = request.getIntentId();
+ try {
+// long start = System.currentTimeMillis();
+ String data = stringRedisTemplate.opsForValue().get(redisId);
+// log.info("redis get cost:"+(System.currentTimeMillis()-start));
+ if (StringUtils.isNotBlank(data)) {
+ String redisIdleId = PREFIX_REDIS_IDLE+userId;
+ if (data.equals("out")) {
+ String idleNum = stringRedisTemplate.opsForValue().get(redisIdleId);
+ boolean firstIdle;
+ if ((firstIdle = StringUtils.isBlank(idleNum)) || idleNum.equals("1")) {
+ try {
+ Thread.sleep(1000);
+ } catch (Exception e){}
+ data = stringRedisTemplate.opsForValue().get(redisId);
+ if (StringUtils.isNotBlank(data) && !data.equals("out")) {
+ stringRedisTemplate.delete(redisIdleId);
+ stringRedisTemplate.delete(redisId);
+ return buildAudioTaskResult(Arrays.asList(data.split(",")), intentId);
+ }
+ if (firstIdle) idleNum = "1";
+ else idleNum = "2";
+ stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 10, TimeUnit.SECONDS);
+ return buildTextTaskResult((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
+ XiaoAiConstants.TTS.WAIT_WORD_2, intentId);
+ } else {
+ stringRedisTemplate.delete(redisIdleId);
+ stringRedisTemplate.delete(redisId);
+ }
+ } else {
+ stringRedisTemplate.delete(redisId);
+ stringRedisTemplate.delete(redisIdleId);
+ return buildAudioTaskResult(Arrays.asList(data.split(",")), intentId);
+ }
+ }
+ } catch (Exception e) {
+ log.error("tmall redis error:"+e);
+ }
+
+ String userWord = request.getUtterance();
+// log.info("天猫精灵用户说的话:"+userWord);
+ try {
+ Future future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId));
+ return future.get(1700, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | ExecutionException e) {
+ log.error("天猫精灵出现问题:{}", ExceptionUtils.getStackTrace(e));
+ } catch (TimeoutException e) {
+ log.warn("超时");
+ stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 20, TimeUnit.SECONDS);
+ return buildTextTaskResult("不好意思晓悟没有听清您刚才说的话,请再重复一遍吧", intentId);
+ }
+ return buildTextTaskResult("不好意思请再说一遍吧", intentId);
+ }
+
+ private TaskResult requestTerminate(String userId, String userWord, Integer type, Long intentId) throws IOException {
+ SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
+ requestPojo.setUid(userId);
+// requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME);
+ requestPojo.setMsg(userWord);
+ String requestJsonStr = JSON.toJSONString(requestPojo);
+ //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
+ HashMap headers = new HashMap<>();
+ headers.put("Content-Type", "application/json;charset=utf-8");
+ String channelId;
+ switch (type) {
+ case 2:
+ case 4: channelId = "tianmao-jiaoyou-audio-child-test";break;
+ case 3:
+ case 5: channelId= "tianmao-jiaoyou-audio-adult-test";break;
+ default: channelId = "tianmao-jiaoyou-audio-test";
+ }
+ headers.put("App-Channel-Id", channelId);
+ String resStr= OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
+ if (resStr == null) {
+ return null;
+ }
+// log.info("天猫精灵晓悟返回:"+resStr);
+ TaskResult taskResult = null;
+ try {
+ final SpiritTerminateResponse response = JSON.parseObject(resStr, SpiritTerminateResponse.class);
+ if (CollectionUtils.isEmpty(response.getDialogs())) {
+ taskResult = buildTextTaskResult("不好意思晓悟没有听清您刚才说的话,请再重复一遍吧", intentId);
+ return taskResult;
+ }
+ List list = dealResponse(response, userId);
+ if (CollectionUtils.isEmpty(list)) {
+ StringBuilder builder = new StringBuilder();
+ response.getDialogs().forEach(dialog -> builder.append(buildText(dialog.getText())));
+ if (builder.length() != 0) taskResult = buildTextTaskResult(builder.toString(), intentId);
+ } else {
+ taskResult = buildAudioTaskResult(list, intentId);
+ }
+ } catch (Exception e) {
+ log.error(e.toString());
+ }
+ if (taskResult == null) {
+ taskResult = buildTextTaskResult("不好意思晓悟没有听清您刚才说的话,请再重复一遍吧", intentId);
+ }
+ return taskResult;
+ }
+
+ private List dealResponse(SpiritTerminateResponse response, String userId) {
+ List idList = new ArrayList<>();
+ List