diff --git a/.idea/libraries/Maven__com_alibaba_fastjson_1_2_72.xml b/.idea/libraries/Maven__com_alibaba_fastjson_1_2_72.xml
new file mode 100644
index 0000000..1d88443
--- /dev/null
+++ b/.idea/libraries/Maven__com_alibaba_fastjson_1_2_72.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index 0d44865..5ece711 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -6,22 +6,28 @@
-
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
@@ -61,58 +67,41 @@
-
-
+
+
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
-
-
-
+
+
@@ -129,36 +118,36 @@
- tmpRequest
- fileName
- particularPersonMoodUrl
+ BASE_AUDIO_URL
httpClient
- RandomAccessFile
- transfer
- getFromFutureAndGenerateB64File
- redisKey
- filePath
- xiaoai
path
- URLEncoder.encode
- text
- requestTemplate
- 缓存
- 2
- stringRedisTemplate.opsForValue()
- 5
- 1
- ffmpeg
- generalMP3
- npcName
- data
- String rootFolderRoot = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString();
- String uploadFolderRoot = new StringBuilder(rootFolderRoot).append(Initialize.getUploadedDir()).append(File.separator).toString();
- 中控
- buildTTS_lsResponse
+ evictExpiredConnections
+ maxIdleTime
+ doPostJsonStrForCentralWithUidParam
+ OkHttp3Utils
+ evictIdleConnections
stringRedisTemplate
- generalMP3 wav
- targetFilepath
+ params
+ parseObject
+ customUserId
+ buildNoScreenPlayDirec
+ RequestTerminal
+ onSessionEnded
+ dealWithError
+ onPlaybackStartedEvent
+ onPlaybackStoppedEvent
+ intentRequest
+ onIntent
+ onInent
+ dealNoScreenIntentTemp
+ THIRD_PARTY_WITH_ITS_PER
+ AUDIO_DIR
+ generalMP3
+ OFFLINE_SERVER
+ ONLINE_CACHE_URL
+ url
+ genRecordWithChange
+ 23
log
@@ -171,51 +160,57 @@
@@ -247,10 +242,10 @@
-
-
+
+
-
+
@@ -307,45 +302,25 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
-
+
-
+
@@ -353,21 +328,21 @@
-
+
-
+
-
+
-
-
+
+
@@ -379,12 +354,13 @@
-
+
+
@@ -400,7 +376,7 @@
-
+
@@ -414,12 +390,12 @@
-
-
-
+
+
+
-
+
@@ -427,12 +403,12 @@
-
-
+
+
-
+
@@ -509,25 +485,25 @@
-
+
+
+
+
-
-
-
-
+
+
-
@@ -676,29 +652,78 @@
-
+
+
+
+
+
+
+
+
+
+
-
+
-
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
@@ -706,7 +731,7 @@
-
+
@@ -721,447 +746,414 @@
-
+
-
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
+
+
+
+
+
-
+
+
-
-
-
-
-
-
+
+
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
+
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
-
-
+
-
+
-
-
-
-
-
+
+
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
-
+
-
+
-
-
+
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
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 e9e8ef0..21600ee 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
@@ -1207,27 +1207,45 @@ public class SpiritAudioUpload {
return ApachHttpUtils.getProbe(path, headers);
}
- private static void jmeter(List recommendWordList, CSVPrinter csvPrinter, String uid, List keyList,
- int index, int botCount, Map openMap) throws IOException {
- Collections.shuffle(recommendWordList);
- for (int j = 0; j < 10; j++) {
- csvPrinter.printRecord(uid, recommendWordList.get(j));
- }
- String openBot = keyList.get(index%botCount);
- csvPrinter.printRecord(uid, openBot);
- String openBotPath = "/home/yf01/下载/yace/"+openMap.get(openBot);
- try (CSVParser botReader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader(
- new FileInputStream(openBotPath), Charset.forName("UTF-8"))))){
- String word;
- for (CSVRecord line: botReader) {
- word = line.get(0);
- csvPrinter.printRecord(uid, StringUtils.isBlank(word) ? "是的":word);
+ private static void oneCsv3million() {
+ List recommendWordList = new ArrayList<>();
+ Map openMap = new HashMap<>();
+ try (CSVParser recommendReader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader(
+ new FileInputStream("/home/yf01/下载/yace/recommand.csv"), Charset.forName("UTF-8"))));
+ CSVParser openReader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader(
+ new FileInputStream("/home/yf01/下载/yace/open.csv"), Charset.forName("UTF-8"))))){
+ for (CSVRecord line: recommendReader) {
+ recommendWordList.add(line.get(0));
+ }
+ for (CSVRecord line: openReader) {
+ openMap.put(line.get(0), line.get(1));
+ }
+ String uid;
+ CSVFormat format;
+ int index = 0;
+ int botCount = openMap.size();
+ List keyList = new ArrayList<>(openMap.keySet());
+ for (int i = 1; i <= 30; i++) {
+ format = CSVFormat.DEFAULT.withHeader(String.valueOf(i), "word");
+ try (CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(
+ new FileOutputStream("/home/yf01/oneCsv3Million/datum_"+i+".csv", true), Charset.forName("UTF-8")),format)) {
+ uid = RandomStringUtils.random(11, true, true)+"_";
+ for (int j = 0; j < 100000; j++) {
+ for (int k = 0; k < 21; k++) {
+ jmeter(recommendWordList, csvPrinter, uid+j, keyList, index+k, botCount, openMap);
+ }
+ csvPrinter.printRecord(uid+j, "退出");
+ index++;
+ Collections.shuffle(keyList);
+ }
+ }
}
+ } catch (IOException e) {
+ e.printStackTrace();
}
- csvPrinter.printRecord(uid, "退出当前作品");
}
- public static void main(String[] args) throws IOException {
+ private static void oneCsvOneUserId() {
List recommendWordList = new ArrayList<>();
Map openMap = new HashMap<>();
try (CSVParser recommendReader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader(
@@ -1246,12 +1264,12 @@ public class SpiritAudioUpload {
int index = 0;
int botCount = openMap.size();
List keyList = new ArrayList<>(openMap.keySet());
- for (int i = 1; i <= 3000; i++) {
+ for (int i = 1; i <= 2000; i++) {
uid = RandomStringUtils.random(10, true, true)+"_"+i;
format = CSVFormat.DEFAULT.withHeader(uid, "word");
try (CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(
- new FileOutputStream("/home/yf01/下载/yace/data/datum_"+i+".csv", true), Charset.forName("UTF-8")),format)) {
- for (int j = 0; j < 20; j++) {
+ new FileOutputStream("/home/yf01/5Bot/datum_"+i+".csv", true), Charset.forName("UTF-8")),format)) {
+ for (int j = 0; j < 5; j++) {
jmeter(recommendWordList, csvPrinter, uid, keyList, index+j, botCount, openMap);
}
csvPrinter.printRecord(uid, "退出");
@@ -1262,4 +1280,31 @@ public class SpiritAudioUpload {
e.printStackTrace();
}
}
+
+ private static void jmeter(List recommendWordList, CSVPrinter csvPrinter, String uid, List keyList,
+ int index, int botCount, Map openMap) throws IOException {
+ Collections.shuffle(recommendWordList);
+ for (int j = 0; j < 5; j++) {
+ csvPrinter.printRecord(uid, recommendWordList.get(j));
+ }
+ String openBot = keyList.get(index%botCount);
+ csvPrinter.printRecord(uid, openBot);
+ String openBotPath = "/home/yf01/下载/yace/"+openMap.get(openBot);
+ try (CSVParser botReader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader(
+ new FileInputStream(openBotPath), Charset.forName("UTF-8"))))){
+ String word;
+ int count = 0;
+ for (CSVRecord line: botReader) {
+ if (count == 15) break;
+ word = line.get(0);
+ csvPrinter.printRecord(uid, StringUtils.isBlank(word) ? "是的":word);
+ count++;
+ }
+ }
+ csvPrinter.printRecord(uid, "退出当前作品");
+ }
+
+ public static void main(String[] args) throws IOException {
+ oneCsvOneUserId();
+ }
}
diff --git a/tts_service/pom.xml b/tts_service/pom.xml
index cbde4d4..4aaa298 100755
--- a/tts_service/pom.xml
+++ b/tts_service/pom.xml
@@ -57,11 +57,13 @@
org.apache.httpcomponents
httpclient
+ 4.5.12
org.apache.httpcomponents
httpmime
+ 4.5.12
@@ -72,7 +74,7 @@
com.alibaba
fastjson
- 1.2.60
+ 1.2.72
org.projectlombok
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ApachHttpUtils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ApachHttpUtils.java
index bfbc70a..7dc81fb 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ApachHttpUtils.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ApachHttpUtils.java
@@ -5,9 +5,7 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.math.NumberUtils;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.NameValuePair;
+import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
@@ -15,11 +13,14 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;
+import org.apache.http.conn.ConnectionKeepAliveStrategy;
+import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
@@ -28,16 +29,21 @@ import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
+import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.protocol.HTTP;
+import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
+import javax.net.ssl.SSLException;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
+import java.net.ConnectException;
import java.net.URISyntaxException;
+import java.net.UnknownHostException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
@@ -46,12 +52,11 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
/**
* @author 苗权威
@@ -75,11 +80,42 @@ public class ApachHttpUtils {
connManager.setMaxTotal(1000);//最大连接数设置
connManager.setDefaultMaxPerRoute(800);//per route最大连接数设置
+// ConnectionKeepAliveStrategy myStrategy = (response, context) -> {
+// HeaderElementIterator it = new BasicHeaderElementIterator(
+// response.headerIterator(HTTP.CONN_KEEP_ALIVE));
+// while (it.hasNext()) {
+// HeaderElement he = it.nextElement();
+// String param = he.getName();
+// String value = he.getValue();
+// log.info("CONN_KEEP_ALIVE:{}:{}",param,value);
+// if (value != null && param.equalsIgnoreCase("timeout")) {
+// try {
+// return Long.parseLong(value) * 1000;
+// } catch(NumberFormatException ignore) {
+// }
+// }
+// }
+//
+//// HeaderElementIterator connectionClose = new BasicHeaderElementIterator(
+//// response.headerIterator(HTTP.CONN_DIRECTIVE));
+//// while (connectionClose.hasNext()) {
+//// HeaderElement he = connectionClose.nextElement();
+//// String param = he.getName();
+//// String value = he.getValue();
+//// log.info("CONN_DIRECTIVE:{}:{}",param,value);
+//// }
+// return 1;
+// };
+
httpClient = HttpClients.custom()
.setConnectionManager(connManager)
- .setRetryHandler(new DefaultHttpRequestRetryHandler(4, false))
+ .setRetryHandler(new CustomRetry())
.setDefaultRequestConfig(requestConfig)
+ .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
+ .evictIdleConnections(5, TimeUnit.SECONDS)
.build();
+
+// new IdleConnectionMonitorThread(connManager).start();
}
}
return httpClient;
@@ -536,7 +572,7 @@ public class ApachHttpUtils {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
- .setSocketTimeout(60000).build();
+ .setSocketTimeout(35000).build();
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-type", "application/json");
httpPost.setEntity(new StringEntity(jsonString, ContentType.APPLICATION_JSON));
@@ -551,20 +587,77 @@ public class ApachHttpUtils {
}
return status;
-// try (InputStream stream = response.getEntity().getContent();
-// FileChannel fileChannel = new RandomAccessFile(path, "rw").getChannel()){
-// long count = stream.available();
-// ReadableByteChannel fromChannel = Channels.newChannel(stream);
-// System.out.println("audioPost=======:"+count+",path="+path+",url:"+url+",jsonurl:"+jsonString);
-// fileChannel.transferFrom(fromChannel, 0, count);
-// return HttpServletResponse.SC_OK;
-// } catch (IOException e) {
-// log.error("audioPost error:"+e);
-// return 500;
+// Integer status;
+// if ((status=response.getStatusLine().getStatusCode()) == HttpServletResponse.SC_OK) {
+// HttpEntity httpEntity = response.getEntity();
+// try (FileChannel fileChannel = new RandomAccessFile(path, "rw").getChannel()){
+// long count = httpEntity.getContentLength();
+//
+// ReadableByteChannel fromChannel = Channels.newChannel(httpEntity.getContent());
+// System.out.println("audioPost=======:"+count+",path="+path);
+// fileChannel.transferFrom(fromChannel, 0, count);
+// EntityUtils.consume(httpEntity);
+// return HttpServletResponse.SC_OK;
+// } catch (IOException e) {
+// log.error("audioPost error:"+e);
+// return 500;
+// }
// }
+// return status;
} catch (IOException e) {
log.error("audioPost error2:"+e);
}
return 0;
}
+
+// static class IdleConnectionMonitorThread extends Thread {
+//
+// private final HttpClientConnectionManager connMgr;
+// private volatile boolean shutdown;
+//
+// IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
+// super();
+// this.connMgr = connMgr;
+// }
+//
+// @Override
+// public void run() {
+// try {
+// while (!shutdown) {
+// synchronized (this) {
+// wait(5000);
+// // Close expired connections
+// connMgr.closeExpiredConnections();
+// // Optionally, close connections
+// // that have been idle longer than 30 sec
+// connMgr.closeIdleConnections(20, TimeUnit.SECONDS);
+// }
+// }
+// } catch (InterruptedException ex) {
+// // terminate
+// }
+// }
+//
+// public void shutdown() {
+// shutdown = true;
+// synchronized (this) {
+// notifyAll();
+// }
+// }
+//
+// }
+
+ static class CustomRetry extends DefaultHttpRequestRetryHandler {
+
+ CustomRetry() {
+ super(3, false, Arrays.asList(InterruptedIOException.class, UnknownHostException.class,
+ ConnectException.class, SSLException.class, NoHttpResponseException.class));
+ }
+
+ @Override
+ public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
+ log.warn("tries number:"+executionCount);
+ return super.retryRequest(exception, executionCount, context);
+ }
+ }
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
index c67f8ce..e555569 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
@@ -5,6 +5,8 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
@@ -66,7 +68,12 @@ public class CallPython {
String[] args = {INTERPRETER, Initialize.getChangeSound(), wav_filename, volume, speed, pitch, filename};
// log.info("wav file:{}, vlo:{},speed:{}, pitch:{}", wav_filename, volume, speed, pitch);
// return processUtil(args);
- return execute(args);
+ String s = execute(args);
+ if ("0".equals(s)) {
+ Files.deleteIfExists(Paths.get(wav_filename));
+ log.warn("检测到wav文件格式有问题,删除"+filename);
+ }
+ return s;
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java
index 66d46d9..9e6b4b7 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java
@@ -1,7 +1,5 @@
package ai.qiwu.com.tts_service.common;
-import org.springframework.beans.factory.annotation.Autowired;
-
/**
* 常量设置
* @author 苗权威
@@ -25,9 +23,12 @@ public interface TTSConstants {
String TTS_REMOTE_LOCALHOST = "localhost";
interface BAI_DU {
- String APP_ID = "16998411";
- String API_KEY = "bHlKRYe9d5o7Ad2z2D5aGiVw";
- String SECRET_KEY = "f5bGP0PapVqSdl8gAOKGawHGlsSnHulB";
+// String APP_ID = "16998411";
+ String APP_ID = "16424686";
+// String API_KEY = "bHlKRYe9d5o7Ad2z2D5aGiVw";
+ String API_KEY = "YzZhZlb9lDnj8W4Z9GpsFQFo";
+// String SECRET_KEY = "f5bGP0PapVqSdl8gAOKGawHGlsSnHulB";
+ String SECRET_KEY = "Era6sREv5lgnOTpbcChmpruLZGY6C6Q9";
}
interface LIE_HU {
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
index 25d18f6..21878ee 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
@@ -381,19 +381,17 @@ public class TTSUtils {
* @return 结果
*/
public static boolean doesFileExist(String filePath) {
- File file = new File(filePath);
- if (file.exists()) {
- //log.info("文件:{},大小为:{}", filePath, file.length());
- if (file.length() == 0) {
- log.info("大小为0的文件:{}",filePath);
-// if (file.delete()) {
-// log.info("大小为0的文件:{}, 删除成功",filePath);
-// } else {
-// log.info("大小为0的文件:{}, 删除失败",filePath);
-// }
-// return false;
+ try {
+ Path pt;
+ if (Files.exists((pt=Paths.get(filePath)))) {
+ //log.info("文件:{},大小为:{}", filePath, file.length());
+ if (Files.size(pt) == 0) {
+ log.info("大小为0的文件:{}",filePath);
+ }
+ return true;
}
- return true;
+ } catch (IOException e) {
+ log.error("doesFileExist error:{},filepath:{}",e, filePath);
}
return false;
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java
index 3f848de..bb1b0d9 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java
@@ -81,11 +81,14 @@ public class Initialize implements InitializingBean {
*/
private static volatile Map ONLINE_ID_2_URL;
+ private static volatile Map> ONLINE_ID_2_PERSON_TON;
+
/**
* 线上url -> (person,mood)
*/
private static volatile Map> URL_2_PERSON_TON;
+
/**
* 服务器标识
*/
@@ -112,6 +115,8 @@ public class Initialize implements InitializingBean {
* 线下服务地址,用于删除线下服务器上的缓存还有响应线下mp3文件的请求
*/
public static final String OFFLINE_SERVER;
+
+ public static final String ONLINE_CACHE_URL;
/**
* 第三方请求的标识,出现在tts_ls请求返回的.b64文件名列表和.b64文件数据中
*/
@@ -148,6 +153,7 @@ public class Initialize implements InitializingBean {
URL_LS = new ArrayList<>();
THIRD_PARTY_TTS = new ArrayList<>();
ONLINE_ID_2_URL = new HashMap<>();
+ ONLINE_ID_2_PERSON_TON = new HashMap<>();
URL_2_PERSON_TON = new HashMap<>();
PERSON_INFO_ONLINE = new HashMap<>();
PERSON_INFO_OFFLINE = new HashMap<>();
@@ -174,6 +180,7 @@ public class Initialize implements InitializingBean {
}
OFFLINE_SERVER = Config.getProperty("offline_server");
+ ONLINE_CACHE_URL = Config.getProperty("online_cache_url", "http://hw-gz21.heyqiwu.cn:9100/api/tts/del_offline");
THIRD_PARTY = Config.getProperty("third_party_tts_text");
CHANGE_SOUND = Config.getProperty("change_sound_path");
@@ -221,6 +228,7 @@ public class Initialize implements InitializingBean {
String url = String.format("%s:9%03d/synthesize", Initialize.getOnlineServer(withOnLine), speakerInfo.getId());
URL_LS.add(url);
+ ONLINE_ID_2_PERSON_TON.put(speakerInfo.getId(), Arrays.asList(person,mood));
ONLINE_ID_2_URL.put(speakerInfo.getId(), url);
URL_2_PERSON_TON.put(url, Arrays.asList(person,mood));
@@ -234,7 +242,7 @@ public class Initialize implements InitializingBean {
PersonInfo personInfo_offline = PERSON_INFO_OFFLINE.computeIfAbsent(person_offline, k -> new PersonInfo(name, sex));
personInfo_offline.getMood().add(mood);
- if (jump != null && !jump.equals(speakerInfo.getId())) {
+ if (jump != null && jump != 0 && !jump.equals(speakerInfo.getId())) {
Map mood2jumpUrl = OFFLINE_2_ONLINE.computeIfAbsent(person_offline, k -> new HashMap<>());
mood2jumpUrl.put(mood, jump);
}
@@ -283,6 +291,7 @@ public class Initialize implements InitializingBean {
List URL_LS_TEMP = new ArrayList<>();
Map ONLINE_ID_2_URL_TEMP = new HashMap<>();
Map> URL_2_PERSON_TON_TEMP = new HashMap<>();
+ Map> ONLINE_ID_2_PERSON_MOOD_TEMP = new HashMap<>();
Map> PERSON_MOODURL_TEMP = new HashMap<>();
Map PERSON_INFO_OFFLINE_TEMP = new HashMap<>();
Map> OFFLINE_2_ONLINE_TEMP = new HashMap<>();
@@ -290,7 +299,7 @@ public class Initialize implements InitializingBean {
List speakerInfos = speakerInfoRepository.findByIsDelete("0");
for (SpeakersInfo speakerInfo: speakerInfos) {
refreshData(speakerInfo, PERSON_INFO_ONLINE_TEMP, THIRD_PARTY_TTS_TEMP, URL_LS_TEMP, ONLINE_ID_2_URL_TEMP,
- URL_2_PERSON_TON_TEMP,PERSON_MOODURL_TEMP, PERSON_INFO_OFFLINE_TEMP, OFFLINE_2_ONLINE_TEMP);
+ URL_2_PERSON_TON_TEMP,PERSON_MOODURL_TEMP, PERSON_INFO_OFFLINE_TEMP, OFFLINE_2_ONLINE_TEMP, ONLINE_ID_2_PERSON_MOOD_TEMP);
}
PERSON_INFO_ONLINE = PERSON_INFO_ONLINE_TEMP;
THIRD_PARTY_TTS = THIRD_PARTY_TTS_TEMP;
@@ -300,6 +309,7 @@ public class Initialize implements InitializingBean {
PERSON_MOODURL = PERSON_MOODURL_TEMP;
PERSON_INFO_OFFLINE = PERSON_INFO_OFFLINE_TEMP;
OFFLINE_2_ONLINE = OFFLINE_2_ONLINE_TEMP;
+ ONLINE_ID_2_PERSON_TON = ONLINE_ID_2_PERSON_MOOD_TEMP;
// 若B05不在线上,则从线上中选择一person值替代
if (!PERSON_INFO_ONLINE.containsKey(init_person)) {
@@ -322,7 +332,7 @@ public class Initialize implements InitializingBean {
private void refreshData(SpeakersInfo speakerInfo,Map PERSON_INFO_ONLINE, List THIRD_PARTY_TTS,
List URL_LS, Map ONLINE_ID_2_URL, Map> URL_2_PERSON_TON,
Map> PERSON_MOODURL, Map PERSON_INFO_OFFLINE, Map> OFFLINE_2_ONLINE) {
+ Map> OFFLINE_2_ONLINE, Map> ONLINE_ID_2_PERSON_MOOD) {
final String name = speakerInfo.getName();
final String sex = speakerInfo.getSex();
String mood = speakerInfo.getMood();
@@ -343,6 +353,7 @@ public class Initialize implements InitializingBean {
String url = String.format("%s:9%03d/synthesize", Initialize.getOnlineServer(withOnLine), speakerInfo.getId());
URL_LS.add(url);
+ ONLINE_ID_2_PERSON_MOOD.put(speakerInfo.getId(), Arrays.asList(person,mood));
ONLINE_ID_2_URL.put(speakerInfo.getId(), url);
URL_2_PERSON_TON.put(url, Arrays.asList(person,mood));
@@ -473,14 +484,19 @@ public class Initialize implements InitializingBean {
}
static List getTheOfflineJumpPersonInfo(String person, String mood) {
+ List list;
Map moodJumpId = OFFLINE_2_ONLINE.get(person);
if (moodJumpId != null) {
Integer id;
if ((id=moodJumpId.get(mood)) != null) {
- return URL_2_PERSON_TON.get(ONLINE_ID_2_URL.get(id));
+ list = ONLINE_ID_2_PERSON_TON.get(id);
+ if (list != null && list.size() == 2 && !StringUtils.isAnyBlank(list.get(0), list.get(1))) return list;
+ else {
+ log.warn("数据库jump数据不正确:id:{},person,mood:{}",id,list);
+ }
}
}
- List list = new ArrayList<>();
+ list = new ArrayList<>();
list.add(init_person);
list.add(init_tone);
log.warn("没有获取到该人物情绪对应的线上person选用默认");
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 824c498..7a7beb2 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
@@ -146,10 +146,10 @@ public class TTService {
String result = TTSConstants.DELETE_SUCCESS;
try {
//String url = String.format("%s/online_cache", Initialize.getOfflineServer());
- String url = new StringBuilder(Initialize.getOfflineServer()).append(File.separator).append("online_cache").toString();
- deleteOfflineResCode = OkHttp3Utils.doDeleteReturnCode(url, new HashMap<>(), offlineStr);
+// String url = new StringBuilder(Initialize.getOfflineServer()).append(File.separator).append("online_cache").toString();
+ deleteOfflineResCode = OkHttp3Utils.doDeleteReturnCode(Initialize.ONLINE_CACHE_URL, new HashMap<>(), offlineStr);
if (deleteOfflineResCode != 200) {
- log.error("对:{} 地址的delete请求失败,响应码:{}",url, deleteOfflineResCode);
+ log.error("对:{} 地址的delete请求失败,响应码:{}",Initialize.ONLINE_CACHE_URL, deleteOfflineResCode);
result = TTSConstants.DELETE_OFFLINE_FAIL;
deleteOfflineResCode = 555;
}else {
@@ -2301,7 +2301,7 @@ public class TTService {
}
if (!fileExist) {
response.setStatus(404);
- log.warn("等待8s后音频文件仍不存在:"+path);
+ log.warn("等待16s后音频文件仍不存在:"+path);
return;
}
while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(path))&& count < 30) {
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java
index 4c3eb0a..bffc26d 100644
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java
@@ -13,7 +13,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
-import org.springframework.util.DigestUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
@@ -150,7 +149,7 @@ public class TTServiceEdition2 {
// redisKey = filePath;
// }
try {
- if ((setSuccess=Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(filePath, "1", 15, TimeUnit.SECONDS)))) {
+ if ((setSuccess=Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(filePath, "1", 40, TimeUnit.SECONDS)))) {
ResponseCodeWithData codeWithData = generalMP3(moodUrl, data, filePath, requestMethod, getOnline);
if (codeWithData == null) {
TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
@@ -237,7 +236,7 @@ public class TTServiceEdition2 {
}
while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(filename))&& count < 30) {
try {
- Thread.sleep(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ Thread.sleep(500);
count++;
} catch (Exception e) {}
}
@@ -353,28 +352,28 @@ public class TTServiceEdition2 {
.append(File.separator).append(fileName).toString();
}
+// if (!TTSUtils.doesFileExist(filepath) && !botName.equals("550829152")) {
if (!TTSUtils.doesFileExist(filepath)) {
- if (botName.equals("550829152")) return;
final GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), text,
person, tone, botName, true, volume, speed, pitch);
- if (!isPersonThirdParty) data.setNpcName(npcName);
+ data.setNpcName(npcName);
final String path = filepath;
final String moodUrl = url;
Future future = POOL.submit(() -> {
-// String encodePth;
-// try {
-// encodePth = URLEncoder.encode(path, "UTF-8");
-// encodePth = encodePth.replaceAll("%2F", "/");
-// } catch (Exception e) {
-// encodePth = path;
-// }
- if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(path, "1", 20, TimeUnit.SECONDS))) {
- log.info("future generate:{},text:{}",path,text);
- if (!TTSUtils.doesFileExist(path)) {
- ResponseCodeWithData response1 = generalMP3(moodUrl, data, path, "GET",true);
- if (response1 == null) response1 = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "tts_ls:generalMP3 return null");
+ int waitTime = 40;
+ if (isPersonThirdParty) waitTime = 45;
+ if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(path, "1", waitTime, TimeUnit.SECONDS))) {
+// log.info("future generate:{},text:{}",path,text);
+ try {
+ if (!TTSUtils.doesFileExist(path)) {
+ ResponseCodeWithData response1 = generalMP3(moodUrl, data, path, "GET",true);
+ if (response1 == null) response1 = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "tts_ls:generalMP3 return null");
+ return response1;
+ }
+ } catch (Exception e) {
+ log.error("tts_ls in future :{},path:{}",e,path);
+ } finally {
stringRedisTemplate.delete(path);
- return response1;
}
}
return new ResponseCodeWithData(8, path);
@@ -396,10 +395,11 @@ public class TTServiceEdition2 {
if ((xiaoai="xiaoai".equals(platform)) || !StringUtils.endsWith(_type, "64")) {
// 异步合成b64文件
final String finalBotName = botName;
- POOL.submit(() -> getFromFutureAndGenerateB64File(futures, response, file_ls, xiaoai, finalBotName));
+// if (!botName.equals("550829152")) POOL.submit(() -> getFromFutureAndGenerateB64File(futures, response, file_ls, xiaoai, finalBotName, true));
+ POOL.submit(() -> getFromFutureAndGenerateB64File(futures, response, file_ls, xiaoai, finalBotName, true));
dealMp3UrlRequest(response, file_ls, botName, _type, xiaoai);
} else {
- if (!getFromFutureAndGenerateB64File(futures, response, file_ls, false, botName)) return;
+ if (!getFromFutureAndGenerateB64File(futures, response, file_ls, false, botName, false)) return;
dealHasB64FileRequest(response, file_ls, botName, _type);
}
} else {
@@ -434,7 +434,7 @@ public class TTServiceEdition2 {
return res;
}
}
- if (TTSUtils.doesFileExist(wavFilename)) {
+ if (!TTSUtils.doesFileExist(wavFilename)) {
log.error("generalMP3 wav size is 0:{}",wavFilename);
return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
@@ -453,6 +453,7 @@ public class TTServiceEdition2 {
if (Initialize.OFFLINE_SERVER.equals(url)) {
data.setFormat("mp3");
int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath);
+
if (status != HttpServletResponse.SC_OK) {
log.info("直接下载人物{}的mp3文件失败,TEXT:{}",filePath,data.getText());
}
@@ -471,13 +472,10 @@ public class TTServiceEdition2 {
private ResponseCodeWithData requestTemplate(String url, GeneralMP3Data data, String filePath, boolean getOnline) {
ResponseCodeWithData res;
int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath);
-// OkHttp3Utils.doPostTimeout()
if (status == 0) res = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "请求出错");
else if (status == HttpServletResponse.SC_NOT_FOUND && Initialize.OFFLINE_SERVER.equals(url)) {
if (!getOnline) return new ResponseCodeWithData(HttpServletResponse.SC_NOT_FOUND, "没有找到该文件");
List list = Initialize.getTheOfflineJumpPersonInfo(data.getPerson(), data.getTone());
-
-// log.warn("build new jump GeneralMP3Data");
GeneralMP3Data jumpedData = new GeneralMP3Data(data.getServer(), data.getText(), list.get(0), list.get(1),
data.getBotname(), data.getCache(), data.getVolume(), data.getSpeed(), data.getPitch());
log.warn("线下人物请求404,跳转到其对应的线上人物:人物:{}->{},情绪:{}->{}",data.getPerson(),jumpedData.getPerson(),data.getTone(), jumpedData.getTone());
@@ -580,7 +578,9 @@ public class TTServiceEdition2 {
}
// 合并所有分段mp3文件
try {
+ long start = System.currentTimeMillis();
TTSUtils.combineMp3File(combineMp3Text2FilePath.values(), personToneFilePath);
+ log.warn("拼接耗时:{}->{}",personToneFilePath,(System.currentTimeMillis()-start));
if (!new File(personToneFilePath).exists()) {
log.error("分段合并音频,未找到合并后的文件");
return false;
@@ -602,7 +602,9 @@ public class TTServiceEdition2 {
log.error("第三方请求内容为空");
return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "第三方请求内容为空");
}
+// long start = System.currentTimeMillis();
result = ThirdPartyService.thirdPartyCall(text, Initialize.theThirdPartysPer(person), filepath, person);
+// log.info(person+"第三方请求耗时:"+(System.currentTimeMillis()-start));
if (result) {
return new ResponseCodeWithData(HttpServletResponse.SC_OK, "创建第三方wav文件成功");
}
@@ -611,7 +613,7 @@ public class TTServiceEdition2 {
}
private boolean getFromFutureAndGenerateB64File(List> futures, HttpServletResponse response,
- List file_ls, boolean xiaoai, String botName) {
+ List file_ls, boolean xiaoai, String botName, boolean asyn) {
// 阻塞等待mp3文件生成成功
// if (futures.size() == 0) log.info("futures is empty");
for (Future future : futures) {
@@ -619,7 +621,7 @@ public class TTServiceEdition2 {
ResponseCodeWithData data = future.get(6, TimeUnit.MINUTES);
if (data.getCode() != HttpServletResponse.SC_OK) {
if (data.getCode() == 8) {
- log.info("tts_ls:出现竞争情况->"+data.getRes()+",时间:"+new Date(System.currentTimeMillis()));
+ log.info("tts_ls:出现竞争情况->"+data.getRes());
if (data.getRes() != null) {
int count = 0;
while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(data.getRes())) && count < 20) {
@@ -632,19 +634,44 @@ public class TTServiceEdition2 {
}
if (count == 20 && Boolean.TRUE.equals(stringRedisTemplate.hasKey(data.getRes()))) {
log.warn("tts_ls:10s后竞争者仍未完成音频操作->"+data.getRes());
- TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ if (!asyn) TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
+ null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return false;
}
+ if (!TTSUtils.doesFileExist(data.getRes())) {
+ if (count < 20) {
+ log.warn("竞争但是 redis 没有该键,文件却不存在:"+data.getCode());
+ do {
+ try {
+ Thread.sleep(500);
+ } catch (Exception e){
+ // do nothing
+ }
+ ++count;
+ } while (!TTSUtils.doesFileExist(data.getRes()) && count < 20);
+ if (count == 20 && !TTSUtils.doesFileExist(data.getRes())) {
+ log.error("竞争但是 redis 没有该键,文件却不存在,继续等待至超时,文件仍不存在:");
+ if (!asyn) TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
+ null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return false;
+ }
+ } else {
+ log.error("竞争但是 redis 没有该键,文件却不存在,已到超时时间直接返回错误:"+data.getCode());
+ if (!asyn) TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
+ null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return false;
+ }
+ }
}
} else {
log.error("tts_ls: future execute fail, status:"+data.getCode());
- TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(data.getCode()), null, data.getCode());
+ if (!asyn) TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(data.getCode()), null, data.getCode());
return false;
}
}
} catch (Exception e) {
log.error("tts_ls获取结果出错:{}", ExceptionUtils.getStackTrace(e));
- TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_BAD_REQUEST), null, HttpServletResponse.SC_BAD_REQUEST);
+ if (!asyn) TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_BAD_REQUEST), null, HttpServletResponse.SC_BAD_REQUEST);
return false;
}
}
@@ -729,6 +756,7 @@ public class TTServiceEdition2 {
if (xiaoai) {
String tmp_audio_name = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai", TTSUtils.buildMP3Filename(file_ls.toString())}, File.separator);
String audio = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="+tmp_audio_name.substring(23);
+// String audio = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="+tmp_audio_name;
if (!Files.exists(Paths.get(tmp_audio_name))) {
audio += "&exist=1";
}
@@ -798,6 +826,7 @@ public class TTServiceEdition2 {
audio.setB64("");
}
audio.setUrl(pre+path.substring(23));
+// audio.setUrl(pre+path);
ttsLsResponse.getAudio().add(audio);
}
}
@@ -813,6 +842,7 @@ public class TTServiceEdition2 {
}
path = path+".b64";
audio.setFilename(path.substring(23));
+// audio.setFilename(path);
try {
audio.setB64(TTSUtils.readAllFile(path));
} catch (Exception e) {
@@ -832,10 +862,13 @@ public class TTServiceEdition2 {
ttsLsResponse.getAudio().add(audio);
continue;
}
+ String relative = path.substring(23);
+// String relative = path;
if (Files.exists(Paths.get(path))) {
- audio.setUrl(pre+path.substring(23));
+ audio.setUrl(pre+relative);
+// audio.setUrl(pre+path);
} else {
- audio.setUrl(pre+path.substring(23)+"&exist=1");
+ audio.setUrl(pre+relative+"&exist=1");
}
ttsLsResponse.getAudio().add(audio);
}
@@ -853,6 +886,7 @@ public class TTServiceEdition2 {
}
String relativePath;
audio.setFilename((relativePath=path.substring(23))+".b64");
+// audio.setFilename((relativePath=path)+".b64");
if (Files.exists(Paths.get(path))) {
audio.setUrl(pre+relativePath);
} else {
@@ -866,6 +900,7 @@ public class TTServiceEdition2 {
for (String name: file_ls) {
TtsLsAudio audio = new TtsLsAudio();
audio.setFilename(name.substring(23));
+// audio.setFilename(name);
ttsLsResponse.getAudio().add(audio);
}
}
@@ -948,14 +983,16 @@ public class TTServiceEdition2 {
allExist = false;
final GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), text,
person, tone, botName, true, volume, speed, pitch);
- if (!isPersonThirdParty) data.setNpcName(npcName);
+ data.setNpcName(npcName);
final String path = filepath;
final String moodUrl = url;
Future future = POOL.submit(() -> {
boolean setSuccess = false;
try {
+ int waitTime = 40;
+ if (isPersonThirdParty) waitTime = 45;
if ((setSuccess = Boolean.TRUE.equals(stringRedisTemplate.opsForValue()
- .setIfAbsent(path, "1", 20, TimeUnit.SECONDS)))) {
+ .setIfAbsent(path, "1", waitTime, TimeUnit.SECONDS)))) {
if (!TTSUtils.doesFileExist(path)) return generalMP3(moodUrl, data, path, "GET",true);
}
return new ResponseCodeWithData(8, path);
@@ -980,6 +1017,7 @@ public class TTServiceEdition2 {
}
// cut "/root/TTS-service/audio"
String result = tmp_audio_name.substring(23);
+// String result = tmp_audio_name;
try {
result = URLEncoder.encode(result, "UTF-8");
} catch (Exception e) {
@@ -993,8 +1031,10 @@ public class TTServiceEdition2 {
if (!TTSUtils.doesFileExist(tmp_audio_name)) {
POOL.submit(() -> task(futures, tmp_audio_name, file_ls));
return "a"+tmp_audio_name.substring(23);
+// return "a"+tmp_audio_name;
} else {
return tmp_audio_name.substring(23);
+// return tmp_audio_name;
}
}
}
@@ -1068,15 +1108,14 @@ public class TTServiceEdition2 {
}
public static void main(String[] args) {
-// List file_ls = new ArrayList<>();
-// file_ls.add("/root/TTS-service/audio/46128715/B32/通用/22d08303d7c18ef3f7d56f30ed1cd0b0.mp3");
-// file_ls.add("/root/TTS-service/audio/46128715/A25_offline/开心/b8a01e3bfe90be43ff2cf9f973d29674.mp3");
-// String tmp_name = TTSUtils.pythonlistToStr(file_ls);
-// String tmp_audio_name = StringUtils.join(new String[]{"46128715", "xiaoai", tmp_name}, File.separator);
-// String audio = "/api/audio/cache/"+"46128715"+"/?filename="+tmp_audio_name;
-// System.out.println(audio);
+ System.out.println(TTSUtils.buildMP3Filename("冷灵儿"));
+ System.out.println(TTSUtils.buildMP3Filename("的"));
+ System.out.println(TTSUtils.buildMP3Filename("技能"));
+ System.out.println(TTSUtils.buildMP3Filename("是"));
+ System.out.println(TTSUtils.buildMP3Filename("普通攻击,格挡"));
+ System.out.println(TTSUtils.buildMP3Filename("杀手"));
+ System.out.println(TTSUtils.buildMP3Filename("生命"));
+ System.out.println(TTSUtils.buildMP3Filename("10"));
- String s = "\uD83C\uDD70推荐如下作品:《江湖逆袭记》、《{/test/}穿越小剧本》、《小太阳》\uD83C\uDD71 你可以说:“打开江湖逆袭记”".replaceAll("\\{/.*?/}|\uD83C\uDD70|\uD83C\uDD71", "").trim();
- System.out.println(s);
}
}
diff --git a/xiaoduhome/pom.xml b/xiaoduhome/pom.xml
index fd082b0..1aa26ee 100755
--- a/xiaoduhome/pom.xml
+++ b/xiaoduhome/pom.xml
@@ -94,7 +94,7 @@
com.alibaba
fastjson
- 1.2.62
+ 1.2.72
@@ -126,16 +126,16 @@
gson
2.8.5
-
-
- org.apache.httpcomponents
- httpclient
-
-
-
- org.apache.httpcomponents
- httpmime
-
+
+
+
+
+
+
+
+
+
+
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/ApachHttpUtils.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/ApachHttpUtils.java
deleted file mode 100644
index 1bd5cfc..0000000
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/ApachHttpUtils.java
+++ /dev/null
@@ -1,104 +0,0 @@
-package ai.qiwu.com.xiaoduhome.common;
-
-import lombok.extern.slf4j.Slf4j;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.ContentType;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.entity.mime.HttpMultipartMode;
-import org.apache.http.entity.mime.MultipartEntityBuilder;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
-import org.apache.http.protocol.HTTP;
-import org.springframework.util.CollectionUtils;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import java.util.Map;
-
-/**
- * @author 苗权威
- * @dateTime 19-12-4 下午7:59
- */
-@Slf4j
-public class ApachHttpUtils {
- private static CloseableHttpClient httpClient;
- static {
- PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
- cm.setMaxTotal(100);
- cm.setDefaultMaxPerRoute(50);
- httpClient = HttpClients.custom().setConnectionManager(cm).build();
- }
-
- public static String post(String url, String jsonString, Map headers) {
- String result = null;
- HttpPost httpPost = new HttpPost(url);
- RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
- httpPost.setConfig(requestConfig);
- if (!CollectionUtils.isEmpty(headers)) headers.forEach(httpPost::setHeader);
- else {
- httpPost.addHeader("Content-type", "application/json; charset=utf-8");
- httpPost.setHeader("Accept", "application/json");
- }
- httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
- try(CloseableHttpResponse response = httpClient.execute(httpPost);
- BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = in.readLine()) != null) {
- sb.append(line);
- }
- result = sb.toString();
- } catch (IOException e) {
- log.error("post表单请求出错:"+e);
- }
- return result;
- }
-
- public static String requestByPostParts(Map map, Map headers, String url, Charset charset, File file) {
- try {
- HttpPost post = new HttpPost(url);
- if (!CollectionUtils.isEmpty(headers)) headers.forEach(post::setHeader);
- MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
- multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
- if(map!=null) {
- ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, StandardCharsets.UTF_8);
- for (Map.Entry stringObjectEntry : map.entrySet()) {
- String key = stringObjectEntry.getKey();
- String value = stringObjectEntry.getValue();
- multipartEntityBuilder.addTextBody(key, value, contentType);
- }
- }
- if (file != null) {
- multipartEntityBuilder.addBinaryBody("file", file);
- }
- post.setEntity(multipartEntityBuilder.build());
- HttpResponse resp = httpClient.execute(post);
- int ret = resp.getStatusLine().getStatusCode();
- if (ret != 200) return null;
- HttpEntity entity = resp.getEntity();
- try (BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), charset))){
- StringBuilder responseString = new StringBuilder();
- String result = br.readLine();
- while (result != null)
- {
- responseString.append(result);
- result = br.readLine();
- }
- return responseString.toString();
- }
- } catch (Exception e)
- {
- log.error(e.toString());
- }
- return null;
- }
-}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/OkHttp3Utils.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/OkHttp3Utils.java
index 8bc82ca..98b18ca 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/OkHttp3Utils.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/OkHttp3Utils.java
@@ -5,6 +5,7 @@ import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.NotNull;
+import org.springframework.util.CollectionUtils;
import java.io.File;
import java.io.IOException;
@@ -36,14 +37,17 @@ public class OkHttp3Utils {
public static String doGet(String url, Map params, Map header) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
+
HttpUrl.Builder urlBuild = request.url().newBuilder();
+ if (!CollectionUtils.isEmpty(params)) {
+ Iterator> paramsIterator = params.entrySet().iterator();
+ paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
+ }
Headers.Builder headerBuilder = request.headers().newBuilder();
-
- Iterator> headIterator = header.entrySet().iterator();
- headIterator.forEachRemaining(e -> headerBuilder.add(e.getKey(), e.getValue()));
-
- Iterator> paramsIterator = params.entrySet().iterator();
- paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
+ if (!CollectionUtils.isEmpty(header)) {
+ Iterator> headIterator = header.entrySet().iterator();
+ headIterator.forEachRemaining(e -> headerBuilder.add(e.getKey(), e.getValue()));
+ }
builder.url(urlBuild.build()).headers(headerBuilder.build());
Response response = client.newCall(builder.build()).execute();
@@ -87,7 +91,7 @@ public class OkHttp3Utils {
return null;
}
- public static String doPostJsonStr(String url, String requestJsonStr, HashMap headers) throws IOException {
+ public static String doPostJsonStr(String url, String requestJsonStr, Map headers) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
@@ -108,6 +112,32 @@ public class OkHttp3Utils {
return null;
}
+ public static String doPostJsonStrForCentralWithUidParam(String url, String requestJsonStr, Map headers,
+ String uid) throws IOException {
+ Request.Builder builder = new Request.Builder();
+ Request request = builder.url(url).build();
+ HttpUrl.Builder urlBuild = request.url().newBuilder();
+ Headers.Builder headBuilder = request.headers().newBuilder();
+
+ Iterator> headIterator = headers.entrySet().iterator();
+ headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
+
+ urlBuild.addQueryParameter("uid", uid);
+
+ builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
+ Response response = client.newCall(builder.build()).execute();
+ try (ResponseBody body = response.body()){
+ return body.string();
+ }catch (SocketTimeoutException e) {
+ log.error("捕获到SocketTimeoutException:{}", e.toString());
+ client.dispatcher().cancelAll();
+ client.connectionPool().evictAll();
+ } catch (Exception e) {
+ log.error("doPostJsonStrForCentralWithUidParam error:"+e);
+ }
+ return null;
+ }
+
public static void asyncPost(String url, String strJson, final AudioBoxData data) {
Request request = new Request.Builder()
.url(url)
@@ -303,7 +333,7 @@ public class OkHttp3Utils {
});
}
- public static void postAsync(String url, String requestJsonStr) {
+ public static void postAsync(String url, String requestJsonStr, String prefixLog) {
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(requestJsonStr,MediaType.parse("application/json; charset=utf-8")))
@@ -311,11 +341,12 @@ public class OkHttp3Utils {
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
- log.info("天猫精灵发送无音频数据失败");
+ log.warn(prefixLog+" 失败");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
+ log.info(prefixLog+" 成功");
try (ResponseBody body = response.body()){
body.string();
} catch (SocketTimeoutException e) {
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 aa81490..73685ce 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
@@ -51,6 +51,7 @@ public class SpiritController {
*/
@PostMapping(value = "/") //智能小说
public ResultModel getResponse(@RequestBody String taskQuery) {
+ log.info("==========================");
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
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 26376f3..490c9c6 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
@@ -8,6 +8,8 @@ import ai.qiwu.com.xiaoduhome.xiaoai.common.Utils;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.Response;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.actionProperty.ActionProperty;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.actionProperty.AppIntentInfo;
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;
@@ -41,9 +43,39 @@ import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SOR
public class XiaoAiController {
// private final XiaoAiService xiaoAiService;
- private final XiaoAiTestService xiaoAiTestService;
+// private final XiaoAiTestService xiaoAiTestService;
private final XiaoAiServiceRedis xiaoAiServiceRedis;
+ private final static XiaoAiResponse PHONE_RESPONSE;
+
+ static {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(true);
+
+ Response responseInfo = new Response();
+ // 这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,
+ // 若不主动打开则小爱在一次会话后退出技能。
+ responseInfo.setOpen_mic(false);
+ responseInfo.setAction("App.LaunchIntent");
+
+ ActionProperty actionProperty = new ActionProperty();
+ AppIntentInfo appIntentInfo = new AppIntentInfo();
+ appIntentInfo.setIntent_type("activity");
+ appIntentInfo.setUri("intent://com.qiwu.life.ui.activity.LaunchActivity");
+ actionProperty.setApp_intent_info(appIntentInfo);
+ responseInfo.setAction_property(actionProperty);
+
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText("请下载app后体验");
+ responseInfo.setTo_speak(toSpeak);
+
+ response.setResponse(responseInfo);
+
+ PHONE_RESPONSE = response;
+ }
+
/**
* Controller控制器
* @param request
@@ -70,6 +102,7 @@ public class XiaoAiController {
@PostMapping("/adult")
public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request, HttpServletRequest servletRequest) { // 智能小说
//log.info("请求:"+request);
+ log.info("================================");
try {
if (!Utils.encry(2, servletRequest)) {
log.error("验证没通过:2");
@@ -105,7 +138,7 @@ public class XiaoAiController {
@PostMapping("/phone") // 手机技能
// @RequestBody XiaoAiRequest request,
- public XiaoAiResponse xiaoaiPhoneStory(@RequestBody XiaoAiRequest request, HttpServletRequest servletRequest) {
+ public XiaoAiResponse xiaoaiPhoneStory(@RequestBody XiaoAiRequest request) {
// long start = System.currentTimeMillis();
// if (!Utils.encry(3, servletRequest)) return null;
// log.info("encry:"+(System.currentTimeMillis()-start));
@@ -119,7 +152,7 @@ public class XiaoAiController {
// }
// String str = sb.toString();
// log.info("请求:"+str);
-// XiaoAiRequest request = JSON.parseObject(str, XiaoAiRequest.class);
+// XiaoAiRequest xiaoAiRequest = JSON.parseObject(str, XiaoAiRequest.class);
// request.setType(5);
// XiaoAiResponse response = xiaoAiTestService.getResponse(request);
// log.info("响应:"+JSON.toJSONString(response));
@@ -127,12 +160,11 @@ public class XiaoAiController {
// } catch (Exception e) {
//
// }
-// return null;
try {
- request.setType(5);
- // log.info("响应:"+response);
- return xiaoAiTestService.getResponse(request);
+// log.info("请求信息:"+request);
+ // log.info("响应信息:"+response);
+ return PHONE_RESPONSE;
} catch (Exception e) {
log.error("controller xiaoai phone:"+e);
}
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 8fe57f7..429104c 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
@@ -4,32 +4,18 @@ 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.NoticeReceiveData;
-import ai.qiwu.com.xiaoduhome.pojo.OverTimeDetail;
-import ai.qiwu.com.xiaoduhome.pojo.UserBehaviorData;
import ai.qiwu.com.xiaoduhome.pojo.data.BaseHostData;
import ai.qiwu.com.xiaoduhome.service.*;
-import ai.qiwu.com.xiaoduhome.spirit.SpiritService;
-import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
-import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
-import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
-import com.alibaba.da.coin.ide.spi.standard.ResultModel;
-import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
-import com.alibaba.da.coin.ide.spi.standard.TaskResult;
-import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import com.alibaba.fastjson.JSON;
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.Cursor;
-import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
-import org.springframework.util.CollectionUtils;
-import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
-import org.springframework.web.servlet.tags.HtmlEscapingAwareTag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -38,10 +24,6 @@ import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-import java.util.concurrent.TimeUnit;
/**
* @author 苗权威
@@ -174,68 +156,68 @@ public class XiaoDuHomeController {
return null;
}
- @PostMapping("/change/host")
- public void changeBaseHost(@RequestBody BaseHostData data) {
- if (StringUtils.startsWith(data.getSecretKey(), "mqw")
- && StringUtils.endsWith(data.getSecretKey(),"#") && data.getSecretKey().length() == 8) {
- if (ScheduleServiceNew.THE_PROCESS_IS_MASTER) {
- for (String slaveProcessUrl : ScheduleServiceNew.serverAddresses) {
- OkHttp3Utils.serverChangeCallOtherSalve(slaveProcessUrl+"xiaoduhome/change/host", JSON.toJSONString(data));
- }
- }
- ScheduleServiceNew.OLD_BASE_HOST_URL = ScheduleServiceNew.BASE_HOST_URL;
- ScheduleServiceNew.BASE_HOST_URL = data.getHost();
- stringRedisTemplate.opsForValue().setIfAbsent(Constants.SERVER_CHANGE_KEY, "1", 4, TimeUnit.MINUTES);
- ScheduleServiceNew.SERVER_CHANGE = true;
- }
- log.info("BASE_HOST_URL:"+ScheduleServiceNew.BASE_HOST_URL);
- log.info("OLD_BASE_HOST_URL:"+ScheduleServiceNew.OLD_BASE_HOST_URL);
- }
-
- @PostMapping("/change/host/getInOldServerNum")
- public String getOldServerUserNum(@RequestBody BaseHostData data) {
- if (StringUtils.startsWith(data.getSecretKey(), "mqw")
- && StringUtils.endsWith(data.getSecretKey(),"#") && data.getSecretKey().length() == 8) {
- if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.SERVER_CHANGE_KEY))) {
- Cursor scan = stringRedisTemplate.getConnectionFactory().getConnection()
- .scan(ScanOptions.scanOptions().match(Constants.CAN_NOT_MOVE_USER_KEY+"*").build());
- int staynUM = 0;
- while (scan.hasNext()) {
- scan.next();
- staynUM++;
- }
- String s = new StringBuilder("正在切换服务器,剩余时间(s):")
- .append(stringRedisTemplate.getExpire(Constants.SERVER_CHANGE_KEY)).append(",停留在旧服务器人数:")
- .append(staynUM).append(",新BASE_HOST地址:")
- .append(ScheduleServiceNew.BASE_HOST_URL).append(",旧BASE_HOST地址:").append(ScheduleServiceNew.OLD_BASE_HOST_URL)
- .append(",标志为值:").append(ScheduleServiceNew.SERVER_CHANGE).toString();
+// @PostMapping("/change/host")
+// public void changeBaseHost(@RequestBody BaseHostData data) {
+// if (StringUtils.startsWith(data.getSecretKey(), "mqw")
+// && StringUtils.endsWith(data.getSecretKey(),"#") && data.getSecretKey().length() == 8) {
+// if (ScheduleServiceNew.THE_PROCESS_IS_MASTER) {
+// for (String slaveProcessUrl : ScheduleServiceNew.serverAddresses) {
+// OkHttp3Utils.serverChangeCallOtherSalve(slaveProcessUrl+"xiaoduhome/change/host", JSON.toJSONString(data));
+// }
+// }
+// ScheduleServiceNew.OLD_BASE_HOST_URL = ScheduleServiceNew.BASE_HOST_URL;
+// ScheduleServiceNew.BASE_HOST_URL = data.getHost();
+// stringRedisTemplate.opsForValue().setIfAbsent(Constants.SERVER_CHANGE_KEY, "1", 4, TimeUnit.MINUTES);
+// ScheduleServiceNew.SERVER_CHANGE = true;
+// }
+// log.info("BASE_HOST_URL:"+ScheduleServiceNew.BASE_HOST_URL);
+// log.info("OLD_BASE_HOST_URL:"+ScheduleServiceNew.OLD_BASE_HOST_URL);
+// }
- log.info(s);
- return s;
- }
- Cursor scan = stringRedisTemplate.getConnectionFactory().getConnection()
- .scan(ScanOptions.scanOptions().match(Constants.CAN_NOT_MOVE_USER_KEY+"*").build());
- if (!scan.hasNext()) {
- ScheduleServiceNew.SERVER_CHANGE = false;
- if (ScheduleServiceNew.THE_PROCESS_IS_MASTER) {
- for (String slaveProcessUrl : ScheduleServiceNew.serverAddresses) {
- OkHttp3Utils.serverChangeCallOtherSalve(slaveProcessUrl+"xiaoduhome/change/host/getInOldServerNum", JSON.toJSONString(data));
- }
- }
- log.info("There is no one in old server,标志为值:"+ScheduleServiceNew.SERVER_CHANGE+",新BASE_HOST地址:"+ScheduleServiceNew.BASE_HOST_URL);
- return "There is no one in old server";
- } else {
- int staynUM = 0;
- while (scan.hasNext()) {
- scan.next();
- staynUM++;
- }
- log.info(staynUM+" users in oldServer,标志为值:"+ScheduleServiceNew.SERVER_CHANGE+",新BASE_HOST地址:"+ScheduleServiceNew.BASE_HOST_URL);
- return staynUM+" users in oldServer";
- }
- }
- return "secret wrong";
- }
+// @PostMapping("/change/host/getInOldServerNum")
+// public String getOldServerUserNum(@RequestBody BaseHostData data) {
+// if (StringUtils.startsWith(data.getSecretKey(), "mqw")
+// && StringUtils.endsWith(data.getSecretKey(),"#") && data.getSecretKey().length() == 8) {
+// if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.SERVER_CHANGE_KEY))) {
+// Cursor scan = stringRedisTemplate.getConnectionFactory().getConnection()
+// .scan(ScanOptions.scanOptions().match(Constants.CAN_NOT_MOVE_USER_KEY+"*").build());
+// int staynUM = 0;
+// while (scan.hasNext()) {
+// scan.next();
+// staynUM++;
+// }
+// String s = new StringBuilder("正在切换服务器,剩余时间(s):")
+// .append(stringRedisTemplate.getExpire(Constants.SERVER_CHANGE_KEY)).append(",停留在旧服务器人数:")
+// .append(staynUM).append(",新BASE_HOST地址:")
+// .append(ScheduleServiceNew.BASE_HOST_URL).append(",旧BASE_HOST地址:").append(ScheduleServiceNew.OLD_BASE_HOST_URL)
+// .append(",标志为值:").append(ScheduleServiceNew.SERVER_CHANGE).toString();
+//
+// log.info(s);
+// return s;
+// }
+// Cursor scan = stringRedisTemplate.getConnectionFactory().getConnection()
+// .scan(ScanOptions.scanOptions().match(Constants.CAN_NOT_MOVE_USER_KEY+"*").build());
+// if (!scan.hasNext()) {
+// ScheduleServiceNew.SERVER_CHANGE = false;
+// if (ScheduleServiceNew.THE_PROCESS_IS_MASTER) {
+// for (String slaveProcessUrl : ScheduleServiceNew.serverAddresses) {
+// OkHttp3Utils.serverChangeCallOtherSalve(slaveProcessUrl+"xiaoduhome/change/host/getInOldServerNum", JSON.toJSONString(data));
+// }
+// }
+// log.info("There is no one in old server,标志为值:"+ScheduleServiceNew.SERVER_CHANGE+",新BASE_HOST地址:"+ScheduleServiceNew.BASE_HOST_URL);
+// return "There is no one in old server";
+// } else {
+// int staynUM = 0;
+// while (scan.hasNext()) {
+// scan.next();
+// staynUM++;
+// }
+// log.info(staynUM+" users in oldServer,标志为值:"+ScheduleServiceNew.SERVER_CHANGE+",新BASE_HOST地址:"+ScheduleServiceNew.BASE_HOST_URL);
+// return staynUM+" users in oldServer";
+// }
+// }
+// return "secret wrong";
+// }
@PostMapping("/notice")
public void receiveOtherServerNotice(@RequestBody NoticeReceiveData data) {
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutSideCache.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutSideCache.java
new file mode 100644
index 0000000..ed8db7c
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutSideCache.java
@@ -0,0 +1,85 @@
+package ai.qiwu.com.xiaoduhome.outside;
+
+import ai.qiwu.com.xiaoduhome.common.Config;
+import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
+import ai.qiwu.com.xiaoduhome.outside.model.AudioInfo;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.TypeReference;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.stereotype.Component;
+import org.springframework.util.CollectionUtils;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * painter
+ * 20-7-2 上午10:46
+ */
+@Component
+@Slf4j
+public class OutSideCache implements InitializingBean {
+ static volatile Map cacheAudioInfo = new HashMap<>();
+
+ private static final String AUDIO_INFO_INTERFACE;
+
+ public static final String SINGLE_BOT_INTERFACE;
+
+ static final boolean DOES_DEV_ENV;
+
+ static {
+ DOES_DEV_ENV = "dev".equals(Config.getProperty("programEnv"));
+ SINGLE_BOT_INTERFACE = Config.getProperty("singleBotInterface");
+ AUDIO_INFO_INTERFACE = Config.getProperty("audioInfoInterface");
+ log.info("AUDIO_INFO_INTERFACE:"+AUDIO_INFO_INTERFACE);
+ }
+
+ @Override
+ public void afterPropertiesSet() throws Exception {
+ initFillCacheData();
+ }
+
+ private void initFillCacheData() {
+ Map map = null;
+ int count = 1;
+ do {
+ try {
+ String response = OkHttp3Utils.doGet(AUDIO_INFO_INTERFACE, null, null);
+ List infos = JSON.parseObject(response, new TypeReference>(){});
+ if (!CollectionUtils.isEmpty(infos)) {
+ map = new HashMap<>();
+ for (AudioInfo info: infos) {
+ map.put(info.getInfoId(), info);
+ }
+ cacheAudioInfo = map;
+ } else {
+ log.warn("第{}次初始化获取音箱第三方信息,返回为空",count);
+ }
+ } catch (Exception e) {
+ log.error("第{}次初始化获取音箱第三方信息失败:{}",count,e);
+ }
+ count++;
+ } while (map != null && count <= 3);
+ }
+
+ static AudioInfo fillTheParticularBotInfo(Long infoId) {
+ Map params = new HashMap<>(1);
+ params.put("infoId", String.valueOf(infoId));
+ try {
+ String response = OkHttp3Utils.doGet(AUDIO_INFO_INTERFACE, params, null);
+ List infos = JSON.parseObject(response, new TypeReference>(){});
+ if (!CollectionUtils.isEmpty(infos)) {
+ AudioInfo info = infos.get(0);
+ cacheAudioInfo.put(info.getInfoId(), info);
+ return info;
+ } else {
+ log.warn("获取音箱第三方信息返回为空:infoId:{}",infoId);
+ }
+ } catch (Exception e) {
+ log.error("获取音箱第三方信息失败:infoId:{},{}",infoId,e);
+ }
+ return null;
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutSideXiaoDuService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutSideXiaoDuService.java
new file mode 100644
index 0000000..615a762
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutSideXiaoDuService.java
@@ -0,0 +1,237 @@
+package ai.qiwu.com.xiaoduhome.outside;
+
+import ai.qiwu.com.xiaoduhome.common.Constants;
+import ai.qiwu.com.xiaoduhome.outside.model.AudioInfo;
+import ai.qiwu.com.xiaoduhome.outside.model.SingleBotResponse;
+import ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil;
+import ai.qiwu.com.xiaoduhome.spirit.SpiritRedisService;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.RequestTerminal;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
+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.SessionEndedRequest;
+import com.baidu.dueros.data.request.videoplayer.event.PlaybackFinishedEvent;
+import com.baidu.dueros.data.request.videoplayer.event.PlaybackNearlyFinishedEvent;
+import com.baidu.dueros.data.request.videoplayer.event.PlaybackStartedEvent;
+import com.baidu.dueros.data.request.videoplayer.event.PlaybackStoppedEvent;
+import com.baidu.dueros.data.response.OutputSpeech;
+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.model.Response;
+import lombok.extern.slf4j.Slf4j;
+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.IOException;
+import java.net.URLEncoder;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import static ai.qiwu.com.xiaoduhome.common.Constants.ErrorMsg.SORRY_UNCATCH;
+import static ai.qiwu.com.xiaoduhome.common.Constants.PREFIX_USERID;
+
+/**
+ * painter
+ * 20-7-2 下午4:28
+ */
+@Slf4j
+public class OutSideXiaoDuService extends BaseBot {
+
+ private final StringRedisTemplate stringRedisTemplate;
+ private final AudioInfo audioInfo;
+
+ OutSideXiaoDuService(HttpServletRequest request, StringRedisTemplate stringRedisTemplate, AudioInfo audioInfo) throws IOException {
+ super(request);
+ this.stringRedisTemplate = stringRedisTemplate;
+ this.audioInfo = audioInfo;
+ //privateKey为私钥内容,0代表你的Bot在DBP平台debug环境,1或者其他整数代表online环境,
+ // botMonitor对象已经在bot-sdk里初始化,可以直接调用
+ this.botMonitor.setEnvironmentInfo(audioInfo.getPrivateKey(), 1);
+ }
+
+ @Override
+ protected Response onLaunch(LaunchRequest launchRequest) {
+ String redisId;
+ String userId = customUserId();
+ if (Boolean.TRUE.equals(stringRedisTemplate.hasKey((redisId= SpiritRedisService.PREFIX_REDIS+userId)))) {
+ stringRedisTemplate.delete(redisId);
+ }
+ String welcomeWord = audioInfo.getFirstWord();
+ if (StringUtils.isBlank(welcomeWord)) {
+ try {
+ Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp("开始", userId));
+ return future.get(2500, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | ExecutionException e) {
+ log.error("outside xiaodu 获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
+ return buildTextResponse(SORRY_UNCATCH);
+ } catch (TimeoutException e) {
+ log.warn("outside xiaodu 超时,让用户再说一遍:{}");
+ stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 15, TimeUnit.SECONDS);
+ return buildTextResponse(SORRY_UNCATCH);
+ } catch (Exception all) {
+ log.error("outside xiaodu 任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
+ return buildTextResponse(SORRY_UNCATCH);
+ }
+ }
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord);
+ return new Response(outputSpeech);
+ }
+
+ @Override
+ protected Response onInent(IntentRequest intentRequest) {
+ final String userId = customUserId();
+ String redisId = SpiritRedisService.PREFIX_REDIS+userId;
+ try {
+ if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(redisId))) {
+ String data = stringRedisTemplate.opsForValue().get(redisId);
+ log.warn("超时redis获取信息:"+data);
+ if (StringUtils.isNotBlank(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){}
+ if (firstIdle) idleNum = "1";
+ else idleNum = "2";
+ stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 15, TimeUnit.SECONDS);
+ return buildTextResponse((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 = buildNoScreenPlay(data, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+ addDirective(play);
+ return new Response();
+ }
+ } else {
+ stringRedisTemplate.delete(redisId);
+ }
+ }
+ } catch (Exception e) {
+ log.error("xiaodu redis error:"+e);
+ }
+
+ try {
+
+ Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest.getQuery().getOriginal(), userId));
+ return future.get(2500, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | ExecutionException e) {
+ log.error("outside xiaodu 获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
+ return buildTextResponse(SORRY_UNCATCH);
+ } catch (TimeoutException e) {
+ log.warn("outside xiaodu 超时,让用户再说一遍:{}");
+ stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 15, TimeUnit.SECONDS);
+ return buildTextResponse(SORRY_UNCATCH);
+ } catch (Exception all) {
+ log.error("outside xiaodu 任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
+ return buildTextResponse(SORRY_UNCATCH);
+ }
+ }
+
+ @Override
+ protected Response onSessionEnded(SessionEndedRequest sessionEndedRequest) {
+ switch (sessionEndedRequest.getReason()) {
+ case ERROR: dealWithError(sessionEndedRequest); break;
+ case USER_INITIATED: log.info(Constants.EndMsg.USER_SAY_CANCEL); break;
+ case EXCEEDED_MAX_REPROMPTS: log.info(Constants.EndMsg.CAN_NOT_UNDERSTAND);break;
+ }
+ String byeWord = audioInfo.getLastWord();
+ if (StringUtils.isBlank(byeWord)) byeWord = OutsideConstant.OUTSIDE_BYE_WORD;
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
+ return new Response(outputSpeech);
+ }
+
+ @Override
+ protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
+ waitAnswer();
+ return new Response();
+ }
+
+ @Override
+ protected Response onPlaybackStoppedEvent(PlaybackStoppedEvent playbackStoppedEvent) {
+ waitAnswer();
+ return new Response();
+ }
+
+ @Override
+ protected Response onPlaybackNearlyFinishedEvent(PlaybackNearlyFinishedEvent playbackNearlyFinishedEvent) {
+ waitAnswer();
+ return new Response();
+ }
+
+ @Override
+ protected Response onPlaybackFinishedEvent(PlaybackFinishedEvent playbackFinishedEvent) {
+ this.setExpectSpeech(true);
+ return new Response();
+ }
+
+ private String customUserId() {
+ try {
+ return PREFIX_USERID+ URLEncoder.encode(getUserId(), "UTF-8");
+ } catch (Exception e) {
+ log.error("outside xiaodu userid encode error:{}, {}",e, getUserId());
+ return PREFIX_USERID+ getUserId().replaceAll("/", "");
+ }
+ }
+
+ private Response buildTextResponse(String errorMsg) {
+ OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
+ return new Response(outputSpeech);
+ }
+
+ private Play buildNoScreenPlay(String audioUrl, AudioPlayerDirective.PlayBehaviorType type) {
+ return new Play(type, audioUrl, 0);
+ }
+
+ private Response dealNoScreenIntentTemp(String userWord, String userId) {
+ try {
+ if (userWord == null){
+ log.error("小度没有传来任何话语");
+ return buildTextResponse(Constants.ErrorMsg.SORRY_UNCATCH);
+ }
+ log.info("outside 小度.用户说的话:{}",userWord);
+ SingleBotResponse response = RequestTerminal.xiaoduOutSideRequestTerminate(userId, userWord, audioInfo.getBotAccount());
+ log.info("outside 小度,小悟返回:{},",response);
+
+ if (OutsideConstant.CMDCODE_OUT.equals(response.getData().getCmdCode())) {
+ String bye = audioInfo.getLastWord();
+ if (StringUtils.isBlank(bye)) bye = "再见";
+ return buildTextResponse(bye);
+ }
+ String path;
+ Directive play = buildNoScreenPlay((path=response.getData().getAudioUrl()), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
+ addDirective(play);
+ if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue()
+ .setIfPresent(SpiritRedisService.PREFIX_REDIS+userId, path, 15, TimeUnit.SECONDS))) {
+ log.warn("outside xiaodu 超时redis存储成功");
+ }
+ return new Response();
+ } catch (Exception e) {
+ log.warn("outside xiaodu 获取中控结果出错:"+e);
+ return buildTextResponse(Constants.ErrorMsg.SORRY_UNCATCH);
+ }
+ }
+
+ private void dealWithError(SessionEndedRequest request) {
+ switch (request.getError().getType()) {
+ case INTERNAL_ERROR: log.info(Constants.ErrorMsg.INTERNAL_ERROR); break;
+ case INVALID_RESPONSE: log.info(Constants.ErrorMsg.INVALID_RESPONSE); break;
+ case DEVICE_COMMUNICATION_ERROR: log.info(Constants.ErrorMsg.DEVICE_COMMUNICATION_ERROR); break;
+ }
+ log.info("错误信息 : "+ request.getError().getMessage());
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutsideConstant.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutsideConstant.java
new file mode 100644
index 0000000..b4409b0
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutsideConstant.java
@@ -0,0 +1,11 @@
+package ai.qiwu.com.xiaoduhome.outside;
+
+/**
+ * painter
+ * 20-7-2 下午3:48
+ */
+public interface OutsideConstant {
+ Integer CMDCODE_OUT = 10011;
+
+ String OUTSIDE_BYE_WORD = "再见";
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutsideController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutsideController.java
new file mode 100644
index 0000000..ab316bb
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutsideController.java
@@ -0,0 +1,171 @@
+package ai.qiwu.com.xiaoduhome.outside;
+
+import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
+import ai.qiwu.com.xiaoduhome.common.Utils;
+import ai.qiwu.com.xiaoduhome.outside.model.AudioInfo;
+import ai.qiwu.com.xiaoduhome.service.DplBotServiceBoth;
+import ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.Response;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
+import com.alibaba.fastjson.JSON;
+import com.fasterxml.jackson.databind.exc.MismatchedInputException;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.codec.binary.Hex;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.util.CollectionUtils;
+import org.springframework.web.bind.annotation.*;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import static ai.qiwu.com.xiaoduhome.outside.OutSideCache.DOES_DEV_ENV;
+import static ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew.XIAO_AI_ENCRY_HOST;
+import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
+
+/**
+ * painter
+ * 20-6-28 下午3:56
+ */
+@RestController
+@RequestMapping("/outside")
+@Slf4j
+public class OutsideController {
+
+ private final OutsideXiaoAiService outsideXiaoAiService;
+ private final StringRedisTemplate stringRedisTemplate;
+
+ @Value("#{'${colony.servers}'.split(',')}")
+ private List servers;
+
+ @Autowired
+ public OutsideController(OutsideXiaoAiService outsideXiaoAiService, StringRedisTemplate stringRedisTemplate) {
+ this.outsideXiaoAiService = outsideXiaoAiService;
+ this.stringRedisTemplate = stringRedisTemplate;
+ }
+
+ @PostMapping("/data/cache")
+ public void cacheAudioInfoChange(@RequestBody AudioInfo audioInfo) {
+ if (audioInfo.getInfoId() != null) {
+ OutSideCache.cacheAudioInfo.put(audioInfo.getInfoId(), audioInfo);
+ if (!CollectionUtils.isEmpty(servers)) {
+ for (String server: servers) {
+ OkHttp3Utils.postAsync(server+"outside/notify/data/cache", JSON.toJSONString(audioInfo),
+ "异步通知对外开放作品数据变更信息,"+server);
+ }
+ }
+ }
+ }
+
+ @PostMapping("/notify/data/cache")
+ public void notifyOtherServer(@RequestBody AudioInfo audioInfo) {
+ if (audioInfo.getInfoId() != null) {
+ OutSideCache.cacheAudioInfo.put(audioInfo.getInfoId(), audioInfo);
+ }
+ }
+
+ @PostMapping("/xiaoai/{id}")
+ public XiaoAiResponse xiaoaiOutSide(@PathVariable Long id, @RequestBody XiaoAiRequest request, HttpServletRequest servletRequest) {
+ log.info("--------------分界线-------------------");
+ AudioInfo info = OutSideCache.cacheAudioInfo.get(id);
+ if (info == null) info = OutSideCache.fillTheParticularBotInfo(id);
+ if (info == null) return buildTextResponse("没有找到该技能的信息,请在创作平台更新技能信息");
+ try {
+ if (!encry(info.getXiaoaiSecret(), info.getXiaoaiKeyId(), servletRequest.getRequestURI(), servletRequest)) {
+ log.error("验证没通过:"+id);
+ return null;
+ }
+ return outsideXiaoAiService.getResponse(request, info, DOES_DEV_ENV);
+ } catch (Exception e) {
+ log.error("xiaoaiOutSide: "+e);
+ }
+ return buildTextResponse(SORRY_REPEAT);
+ }
+
+ @RequestMapping(value = "/novel", method = RequestMethod.HEAD)
+ public void novelHead(HttpServletResponse response) {
+ response.setStatus(200);
+ }
+
+ @PostMapping("/xiaodu/{id}")
+ public String xiaoduOutSide(@PathVariable Long id, HttpServletRequest request) {
+ try {
+ log.info("--------------分界线-------------------");
+ AudioInfo info = OutSideCache.cacheAudioInfo.get(id);
+ if (info == null) info = OutSideCache.fillTheParticularBotInfo(id);
+ if (info == null) {
+ log.warn("没有找到该技能的信息:"+id);
+ return null;
+ }
+ OutSideXiaoDuService service = new OutSideXiaoDuService(request, stringRedisTemplate, info);
+ service.enableVerify();
+ return service.run();
+ } catch (Exception e) {
+ log.error("xiaoduOutSide:"+e);
+ }
+ return null;
+ }
+
+ private XiaoAiResponse buildResponse() {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(false);
+
+ Response responseInfo = new Response();
+ // 这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,
+ // 若不主动打开则小爱在一次会话后退出技能。
+ responseInfo.setOpen_mic(true);
+ response.setResponse(responseInfo);
+ return response;
+ }
+
+ private XiaoAiResponse buildTextResponse(String text) {
+ XiaoAiResponse response = buildResponse();
+ Response responseInfo = response.getResponse();
+
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+
+ return response;
+ }
+
+ private static boolean encry(String secret, String keyId, String urlPath, HttpServletRequest request) {
+ String host = XIAO_AI_ENCRY_HOST;
+ String xiaomiDate = request.getHeader("x-xiaomi-date");
+ String md5 = request.getHeader("content-md5");
+ if (StringUtils.isBlank(md5)) md5 = "";
+ String contentType = request.getHeader("content-type");
+ String authorization = request.getHeader("authorization");
+ if (StringUtils.isAnyBlank(xiaomiDate, contentType, authorization)) return false;
+
+ String algorithmForMac = "HmacSHA256";
+
+ String method = "POST";
+ String param = "";
+ String source = new StringBuilder().append(method).append('\n').append(urlPath).append('\n').append(param).append('\n')
+ .append(xiaomiDate).append('\n').append(host).append('\n')
+ .append(contentType).append('\n').append(md5).append('\n').toString();
+ try {
+ Mac mac = Mac.getInstance(algorithmForMac);
+ SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.decodeBase64(secret), algorithmForMac);
+ mac.init(secretKeySpec);
+ String signature = new StringBuilder("MIAI-HmacSHA256-V1 ").append(keyId).append("::")
+ .append(Hex.encodeHexString(mac.doFinal(source.getBytes(StandardCharsets.UTF_8)))).toString();
+ return signature.equals(authorization);
+ } catch (Exception e) {
+ log.error("outside encry:"+e);
+ }
+ return false;
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutsideXiaoAiService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutsideXiaoAiService.java
new file mode 100644
index 0000000..cded371
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/OutsideXiaoAiService.java
@@ -0,0 +1,324 @@
+package ai.qiwu.com.xiaoduhome.outside;
+
+import ai.qiwu.com.xiaoduhome.common.Constants;
+import ai.qiwu.com.xiaoduhome.outside.model.AudioInfo;
+import ai.qiwu.com.xiaoduhome.outside.model.SingleBotResponse;
+import ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil;
+import ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew;
+import ai.qiwu.com.xiaoduhome.spirit.SpiritRedisService;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.RequestTerminal;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.RequestWordNullException;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.Utils;
+import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.Response;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.AudioItem.AudioItem;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.AudioItem.AudioStream;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.Directive;
+import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.RandomUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
+import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.PREFIX_USERID;
+
+/**
+ * painter
+ * 20-6-28 下午3:57
+ */
+@Service
+@Slf4j
+public class OutsideXiaoAiService {
+ private final StringRedisTemplate stringRedisTemplate;
+
+ @Autowired
+ public OutsideXiaoAiService(StringRedisTemplate stringRedisTemplate) {
+ this.stringRedisTemplate = stringRedisTemplate;
+ }
+
+ /**
+ * 处理不同意图,type为0则说明是启动,为1则说明是会话进行中,为2则说明用户退出
+ * @param request 封装请求信息
+ * @return 响应结果
+ */
+ public XiaoAiResponse getResponse(XiaoAiRequest request, AudioInfo info, Boolean dev) {
+ String userId = getUserId(request);
+ int type = request.getRequest().getType();
+ if (dev && Boolean.TRUE.equals(request.getRequest().getIs_monitor())) {
+ return buildTextResponse("outside 判定为监控请求,过滤");
+ }
+ switch (type) {
+ case 0 : return dealWithLaunchRequest(userId, info);
+ case 1 : return dealWithIntentRequest(request, userId, info);
+ case 2 : return dealWithEndRequest(userId, info.getLastWord());
+ default: return buildTextResponse(SORRY_REPEAT);
+ }
+ }
+
+ /**
+ * 处理启动意图,返回欢迎语
+ * @return 响应信息
+ */
+ private XiaoAiResponse dealWithLaunchRequest(String userId, AudioInfo info) {
+ stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+userId);
+ String welcomeWord;
+ if (StringUtils.isBlank((welcomeWord=info.getFirstWord()))) {
+ String redisId = SpiritRedisService.PREFIX_REDIS+userId;
+ try {
+ Future future = DplbotServiceUtil.getPool().submit(() -> task(userId, "开始", info));
+ return future.get(2000, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | ExecutionException e) {
+ log.error("outside 获取任务执行结果出错:{}", e.toString());
+ return buildTextResponse(SORRY_REPEAT);
+ } catch (TimeoutException e) {
+ log.info("outside 超时,让用户再说一遍");
+ stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 15, TimeUnit.SECONDS);
+ return buildTextResponse(XiaoAiConstants.ERROR_MSG.TIME_OUT);
+ } catch (Exception all) {
+ log.error("outside 任务执行发生了错误:{}", all.toString());
+ return buildTextResponse(SORRY_REPEAT);
+ }
+ }
+ return buildTextResponse(welcomeWord);
+ }
+
+ /**
+ * 处理正常会话意图;
+ * 将任务提交线程池,监控其执行时间,若1.8s内没有返回则判为超时,提示用户稍等,下一次再将结果返回给用户
+ * @param request 请求信息
+ * @param userId 用户在小爱上的id
+ * @return 响应信息
+ */
+ private XiaoAiResponse dealWithIntentRequest(final XiaoAiRequest request, final String userId, AudioInfo info) {
+ Boolean idle = request.getRequest().getNo_response();
+ String redisId = SpiritRedisService.PREFIX_REDIS+userId;
+ try {
+ if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(redisId))) {
+ String data = stringRedisTemplate.opsForValue().get(redisId);
+ log.info("outside 超时redis获取信息:"+data);
+ if (StringUtils.isNotBlank(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(1500);
+ } catch (Exception e){}
+ if (firstIdle) idleNum = "1";
+ else idleNum = "2";
+ stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 15, TimeUnit.SECONDS);
+ return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
+ XiaoAiConstants.TTS.WAIT_WORD_2);
+ } else {
+ stringRedisTemplate.delete(redisIdleId);
+ stringRedisTemplate.delete(redisId);
+ }
+ } else {
+ if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(redisIdleId))) stringRedisTemplate.delete(redisIdleId);
+ stringRedisTemplate.delete(redisId);
+ return buildAudioResponse(data);
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("outside xiaoai redis error:"+e);
+ }
+ if (Boolean.TRUE.equals(idle)) {
+ try {
+ //log.info("开始等待");
+ Thread.sleep(2000);
+ //log.info("等待OVER");
+ } catch (InterruptedException e) {
+ log.warn("outside 等待中断");
+ }
+ return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.USER_IDLE :
+ XiaoAiConstants.TTS.ANOTHER_USER_IDLE);
+ }
+ try {
+ Future future = DplbotServiceUtil.getPool().submit(() -> task(userId, request.getQuery(), info));
+ return future.get(2000, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | ExecutionException e) {
+ log.error("outside 获取任务执行结果出错:{}", e.toString());
+ return buildTextResponse(SORRY_REPEAT);
+ } catch (TimeoutException e) {
+ log.info("outside 超时,让用户再说一遍");
+ stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 15, TimeUnit.SECONDS);
+ return buildTextResponse(XiaoAiConstants.ERROR_MSG.TIME_OUT);
+ } catch (Exception all) {
+ log.error("outside 任务执行发生了错误:{}", all.toString());
+ return buildTextResponse(SORRY_REPEAT);
+ }
+ }
+
+ /**
+ * 处理用户退出意图,先向中控发送“退出”,之后返回结束语
+ * @param userId 用户id
+ * @return 返回信息
+ */
+ private XiaoAiResponse dealWithEndRequest(String userId, String byeWord) {
+ if (ScheduleServiceNew.SERVER_CHANGE) stringRedisTemplate.delete(Constants.CAN_NOT_MOVE_USER_KEY+userId);
+ if (StringUtils.isBlank(byeWord)) byeWord = OutsideConstant.OUTSIDE_BYE_WORD;
+ return buildCancelTextResponse(byeWord);
+ }
+
+ /**
+ * 获取用户id
+ * @param request 请求信息
+ * @return 用户id
+ */
+ private String getUserId(XiaoAiRequest request) {
+ String userId = request.getSession().getUser().getUser_id();
+ if (userId == null) {
+ userId = request.getContext().getDevice_id();
+ if (userId != null) userId = Utils.modifyDeviceId(userId);
+ }
+ if (userId == null) {
+ userId = Utils.useIPAsItsID();
+ }
+ try {
+ return PREFIX_USERID+ URLEncoder.encode(userId, "UTF-8");
+ } catch (Exception e) {
+ log.error("outside xiaoai userid encode error:{}, {}",e, userId);
+ return PREFIX_USERID+ userId.replaceAll("/", "");
+ }
+ }
+
+ private XiaoAiResponse task(String userId, String userWord, AudioInfo info) {
+ if (userWord == null) {
+ log.warn("outside 请求中没有带有用户的话");
+ throw new RequestWordNullException("outside user word can not be null");
+ }
+ SingleBotResponse response;
+ try {
+ log.info("小爱,用户话:{}", userWord);
+ response = RequestTerminal.outSideRequestTerminate(userId, userWord, info.getBotAccount());
+ log.info("小爱,小悟返回:{}", response);
+ } catch (Exception e) {
+ log.error("向终端发出的请求信息失败:{}", e.toString());
+ return buildTextResponse(SORRY_REPEAT);
+ }
+ if (OutsideConstant.CMDCODE_OUT.equals(response.getData().getCmdCode())) {
+ String bye = info.getLastWord();
+ if (StringUtils.isBlank(bye)) bye = "再见";
+ return buildResponseBeforeLoadout(bye);
+ }
+ XiaoAiResponse xiaoAiResponse;
+ try {
+ String audioUrl;
+ xiaoAiResponse = buildAudioResponse((audioUrl=response.getData().getAudioUrl()));
+ if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfPresent(SpiritRedisService.PREFIX_REDIS+userId,
+ audioUrl, 15, TimeUnit.SECONDS))) {
+ log.info("outside xiaoai 超时redis存储成功");
+ }
+ } catch (Exception e) {
+ log.error("outside 没有获取到TTS返回的路径path");
+ xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
+ }
+ return xiaoAiResponse;
+ }
+
+ /**
+ * 构建基础返回信息,注意is_session_end字段置为false,
+ * open_mic这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,若不主动打开则小爱在一次会话后退出技能。
+ * @return 小爱返回信息
+ */
+ private XiaoAiResponse buildResponse() {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(false);
+
+ Response responseInfo = new Response();
+ // 这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,
+ // 若不主动打开则小爱在一次会话后退出技能。
+ responseInfo.setOpen_mic(true);
+ response.setResponse(responseInfo);
+ return response;
+ }
+
+ private XiaoAiResponse buildResponseBeforeLoadout(String text) {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(true);
+
+ Response responseInfo = new Response();
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+
+ response.setResponse(responseInfo);
+ return response;
+ }
+
+ /**
+ * 构建语音返回信息
+ * @param audioUrl 音频文件地址
+ * @return 小爱返回信息
+ */
+ private XiaoAiResponse buildAudioResponse(String audioUrl) {
+ XiaoAiResponse response = buildResponse();
+ Response responseInfo = response.getResponse();
+
+ Directive directive = new Directive();
+ directive.setType("audio");
+ AudioItem audioItem = new AudioItem();
+ AudioStream audioStream = new AudioStream();
+ audioStream.setUrl(audioUrl);
+ audioItem.setStream(audioStream);
+ directive.setAudio_item(audioItem);
+ List directives = new ArrayList<>();
+ directives.add(directive);
+ responseInfo.setDirectives(directives);
+
+ return response;
+ }
+
+ /**
+ * 构建文字返回信息
+ * @param text 文字
+ * @return 小爱返回信息
+ */
+ private XiaoAiResponse buildTextResponse(String text) {
+ XiaoAiResponse response = buildResponse();
+ Response responseInfo = response.getResponse();
+
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+
+ return response;
+ }
+
+ private XiaoAiResponse buildCancelTextResponse(String text) {
+ XiaoAiResponse response = new XiaoAiResponse();
+ response.setVersion("1.0");
+ response.setIs_session_end(true);
+
+ Response responseInfo = new Response();
+ // 这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,
+ // 若不主动打开则小爱在一次会话后退出技能。
+ responseInfo.setOpen_mic(false);
+ ToSpeak toSpeak = new ToSpeak();
+ toSpeak.setType(0);
+ toSpeak.setText(text);
+ responseInfo.setTo_speak(toSpeak);
+ response.setResponse(responseInfo);
+
+ return response;
+ }
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/AudioInfo.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/AudioInfo.java
new file mode 100644
index 0000000..b2af778
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/AudioInfo.java
@@ -0,0 +1,24 @@
+package ai.qiwu.com.xiaoduhome.outside.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * painter
+ * 20-7-1 下午5:40
+ */
+@Getter
+@Setter
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AudioInfo {
+ private Long infoId;
+ private String firstWord;
+ private String lastWord;
+ private String xiaoaiSecret;
+ private String xiaoaiKeyId;
+ private String publicKey;
+ private String botAccount;
+ private String privateKey;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/SingleBotData.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/SingleBotData.java
new file mode 100644
index 0000000..ee96b5b
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/SingleBotData.java
@@ -0,0 +1,20 @@
+package ai.qiwu.com.xiaoduhome.outside.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * painter
+ * 20-7-2 下午3:43
+ */
+@Getter
+@Setter
+@ToString
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class SingleBotData {
+ private String audioUrl;
+ private String text;
+ private Integer cmdCode;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/SingleBotRequest.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/SingleBotRequest.java
new file mode 100644
index 0000000..b5f6456
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/SingleBotRequest.java
@@ -0,0 +1,18 @@
+package ai.qiwu.com.xiaoduhome.outside.model;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * painter
+ * 20-7-2 下午3:27
+ */
+@Getter
+@Setter
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class SingleBotRequest {
+ private String uid;
+ private String msg;
+ private String botAccount;
+}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/SingleBotResponse.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/SingleBotResponse.java
new file mode 100644
index 0000000..d46bd37
--- /dev/null
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/outside/model/SingleBotResponse.java
@@ -0,0 +1,20 @@
+package ai.qiwu.com.xiaoduhome.outside.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * painter
+ * 20-7-2 下午3:42
+ */
+@Getter
+@Setter
+@ToString
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class SingleBotResponse {
+ private Integer code;
+ private String msg;
+ private SingleBotData data;
+}
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
index 65c1311..9c0f030 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotServiceBoth.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplBotServiceBoth.java
@@ -178,10 +178,10 @@ public class DplBotServiceBoth extends BaseBot {
break;
}
}
- StandardCard standardCard = new StandardCard(skillName, welcomeWord);
- standardCard.setImage(FIRST_IMAGE);
+// StandardCard standardCard = new StandardCard(skillName, welcomeWord);
+// standardCard.setImage(FIRST_IMAGE);
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord);
- return new Response(outputSpeech, standardCard);
+ return new Response(outputSpeech);
} else {
RenderDocument renderDocument = new RenderDocument(FIRST_PAGE);
this.addDirective(renderDocument);
@@ -229,20 +229,20 @@ public class DplBotServiceBoth extends BaseBot {
if (isNoScreenRequest()) {
final String userId = customUserId();
- String baseHostUrl = ScheduleServiceNew.BASE_HOST_URL;
- if (ScheduleServiceNew.SERVER_CHANGE) {
- if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.SERVER_CHANGE_KEY))) {
- if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))) {
- stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
- } else {
- stringRedisTemplate.opsForValue().set(Constants.CAN_NOT_MOVE_USER_KEY+userId, "1", 4, TimeUnit.MINUTES);
- }
- baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
- } else if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))){
- stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
- baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
- }
- }
+// String baseHostUrl = ScheduleServiceNew.BASE_HOST_URL;
+// if (ScheduleServiceNew.SERVER_CHANGE) {
+// if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.SERVER_CHANGE_KEY))) {
+// if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))) {
+// stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
+// } else {
+// stringRedisTemplate.opsForValue().set(Constants.CAN_NOT_MOVE_USER_KEY+userId, "1", 4, TimeUnit.MINUTES);
+// }
+// baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
+// } else if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))){
+// stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
+// baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
+// }
+// }
String redisId = SpiritRedisService.PREFIX_REDIS+userId;
// final String deviceUserId = PREFIX_USERID + getDeviceId();
@@ -297,9 +297,9 @@ public class DplBotServiceBoth extends BaseBot {
}
try {
- final String finalBaseHost = baseHostUrl;
+// final String finalBaseHost = baseHostUrl;
// log.info("BASE_HOST_URL:"+finalBaseHost);
- Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId, finalBaseHost));
+ Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId));
return future.get(2500, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
@@ -405,7 +405,7 @@ public class DplBotServiceBoth extends BaseBot {
return new Response();
}
- private Response dealNoScreenIntentTemp(IntentRequest intentRequest, String userId, String baseHostUrl) {
+ private Response dealNoScreenIntentTemp(IntentRequest intentRequest, String userId) {
// String intentName = getIntent().getName();
// if ("sendFlower".equals(intentName)) {
// return dealNoScreenSendFlowerIntent(userId, null);
@@ -434,7 +434,7 @@ public class DplBotServiceBoth extends BaseBot {
case 4 : channel = "jiaoyou-audio-adult-test";break;
default: channel = "jiaoyou-audio-test";break;
}
- String response = RequestTerminal.requestTerminateUrl(userWord, userId, channel, baseHostUrl);
+ String response = RequestTerminal.requestTerminateUrl(userWord, userId, channel, ScheduleServiceNew.BASE_HOST_URL);
// log.info("小度,小悟返回:{},",response);
if (StringUtils.isBlank(response)) {
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
@@ -497,7 +497,7 @@ public class DplBotServiceBoth extends BaseBot {
} catch (Exception e) {
log.error("推荐bot退出解析出错:"+e);
}
- String path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio", response);
+ String path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_AUDIO_URL+"/api/audio", response);
// log.info("小度,语音:"+path);
// String path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:8190/api/audio", response);
if (StringUtils.isBlank(path) || "null".equals(path)) {
@@ -553,7 +553,7 @@ public class DplBotServiceBoth extends BaseBot {
}
private String dealAudioUrl(String path) {
- return ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio/get?path="+path;
+ return ScheduleServiceNew.BASE_AUDIO_URL+"/api/audio/get?path="+path;
}
private String dealAudioUrlTemp(String path, String botAccount) {
@@ -934,7 +934,7 @@ public class DplBotServiceBoth extends BaseBot {
}
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
RequestTerminal.backRequest(userId, type);
- if (ScheduleServiceNew.SERVER_CHANGE) stringRedisTemplate.delete(Constants.CAN_NOT_MOVE_USER_KEY+userId);
+// if (ScheduleServiceNew.SERVER_CHANGE) stringRedisTemplate.delete(Constants.CAN_NOT_MOVE_USER_KEY+userId);
// try {
// if (DU_DEVICE_ID.equals(deviceId)) {
// RequestTerminal.backRequest(DU_DEVICE_ID, type);
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 024183d..ffec877 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
@@ -28,7 +28,8 @@ class RequestTerminal {
HashMap headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
headers.put("App-Channel-Id", channel);
- return OkHttp3Utils.doPostJsonStr(baseHostUrl+"8070/api/chat2", requestJsonStr, headers);
+// return OkHttp3Utils.doPostJsonStr(baseHostUrl, requestJsonStr, headers);
+ return OkHttp3Utils.doPostJsonStrForCentralWithUidParam(baseHostUrl, requestJsonStr, headers, userId);
}
static String requestTerminateTemp(String userWord, String userId, String channel) throws IOException {
@@ -65,7 +66,7 @@ class RequestTerminal {
// default: headers.put("App-Channel-Id", "jiaoyou-audio-test");
// }
// return OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, requestJsonStr, headers);
- return OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, headers);
+ return OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL, requestJsonStr, headers);
}
static QiWuResponse requestTerminate(String userWord, String userId, int type) throws IOException {
@@ -117,7 +118,8 @@ class RequestTerminal {
requestPojo.setUid(userId);
requestPojo.setMsg("退出");
String requestJsonStr = JSON.toJSONString(requestPojo);
- OkHttp3Utils.backPostAsync(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, type);
+// OkHttp3Utils.backPostAsync(ScheduleServiceNew.BASE_HOST_URL, requestJsonStr, type);
+ OkHttp3Utils.backPostAsync(ScheduleServiceNew.BASE_HOST_URL+"?uid="+userId, requestJsonStr, type);
// OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr, type);
}
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
index 7b26e27..bfcef7c 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java
@@ -51,7 +51,9 @@ public class ScheduleServiceNew implements InitializingBean {
public static volatile String BASE_HOST_URL = "http://didi-gz3.jiaoyou365.com:";
- public static volatile String OLD_BASE_HOST_URL = "http://didi-gz3.jiaoyou365.com:";
+ public static volatile String BASE_AUDIO_URL = "http://didi-gz3.jiaoyou365.com:";
+
+// public static volatile String OLD_BASE_HOST_URL = "http://didi-gz3.jiaoyou365.com:";
public static volatile String CDN_HOST_URL = "http://didi-gz2-cdn.jiaoyou365.com";
@@ -59,18 +61,20 @@ public class ScheduleServiceNew implements InitializingBean {
public static volatile boolean SERVER_CHANGE = false;
- public static Boolean THE_PROCESS_IS_MASTER = false;
+ private static Boolean THE_PROCESS_IS_MASTER = false;
@Override
public void afterPropertiesSet() throws Exception {
getAllProjects();
getOtherServerAddress();
getJiaoYouChannelRecordBots();
- BASE_HOST_URL = Config.getProperty("baseHostUrl", "http://didi-gz3.jiaoyou365.com:");
- OLD_BASE_HOST_URL = BASE_HOST_URL;
+ BASE_HOST_URL = Config.getProperty("baseHostUrl");
+ BASE_AUDIO_URL = Config.getProperty("baseAudioUrl");
+// OLD_BASE_HOST_URL = BASE_HOST_URL;
CDN_HOST_URL = Config.getProperty("cdnHostUrl", "http://didi-gz2-cdn.jiaoyou365.com");
XIAO_AI_ENCRY_HOST = Config.getProperty("host", "didi-gz3.jiaoyou365.com");
THE_PROCESS_IS_MASTER = Config.getProperty("masterSlave", "slave").equals("master");
+
log.info("BASE_HOST_URL:{},CDN_HOST_URL:{}, xiaoai encry host:{}, masterSlave:{}",BASE_HOST_URL,CDN_HOST_URL,
XIAO_AI_ENCRY_HOST,THE_PROCESS_IS_MASTER);
// buildLunchNewDocument
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
index 3b551cc..ae8ab13 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritRedisService.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritRedisService.java
@@ -74,16 +74,17 @@ public class SpiritRedisService {
private static final String PREFIX_TMALL = "TMALL_";
-// private static final HashMap ADULT_HEADER;
-// private static final HashMap CHILD_HEADER;
-//
-// static {
-// ADULT_HEADER = new HashMap<>();
-// ADULT_HEADER.put("Content-Type", "application/json;charset=utf-8");
-// ADULT_HEADER.put("App-Channel-Id", "tianmao-jiaoyou-audio-adult-test");tianmao-jiaoyou-audio-child-test
-// CHILD_HEADER = new HashMap<>();
-// CHILD_HEADER.put("Content-Type", "application/json;charset=utf-8");
-// }
+ private static final HashMap ADULT_HEADER;
+ private static final HashMap CHILD_HEADER;
+
+ static {
+ ADULT_HEADER = new HashMap<>();
+ ADULT_HEADER.put("Content-Type", "application/json;charset=utf-8");
+ ADULT_HEADER.put("App-Channel-Id", "tianmao-jiaoyou-audio-adult-test");
+ CHILD_HEADER = new HashMap<>();
+ CHILD_HEADER.put("Content-Type", "application/json;charset=utf-8");
+ CHILD_HEADER.put("App-Channel-Id", "tianmao-jiaoyou-audio-child-test");
+ }
public SpiritRedisService(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
@@ -121,20 +122,20 @@ public class SpiritRedisService {
return buildTextTaskResult(WELCOME_SMART, intentId);
}
- String baseHostUrl = ScheduleServiceNew.BASE_HOST_URL;
- if (ScheduleServiceNew.SERVER_CHANGE) {
- if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.SERVER_CHANGE_KEY))) {
- if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))) {
- stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
- } else {
- stringRedisTemplate.opsForValue().set(Constants.CAN_NOT_MOVE_USER_KEY+userId, "1", 4, TimeUnit.MINUTES);
- }
- baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
- } else if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))){
- stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
- baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
- }
- }
+// String baseHostUrl = ScheduleServiceNew.BASE_HOST_URL;
+// if (ScheduleServiceNew.SERVER_CHANGE) {
+// if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.SERVER_CHANGE_KEY))) {
+// if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))) {
+// stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
+// } else {
+// stringRedisTemplate.opsForValue().set(Constants.CAN_NOT_MOVE_USER_KEY+userId, "1", 4, TimeUnit.MINUTES);
+// }
+// baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
+// } else if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))){
+// stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
+// baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
+// }
+// }
try {
// long start = System.currentTimeMillis();
@@ -177,8 +178,8 @@ public class SpiritRedisService {
}
// log.info("天猫精灵用户说的话:"+userWord);
try {
- final String finalBaseHost = baseHostUrl;
- Future future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId, finalBaseHost));
+// final String finalBaseHost = baseHostUrl;
+ 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));
@@ -204,31 +205,30 @@ public class SpiritRedisService {
return null;
}
- private TaskResult requestTerminate(String userId, String userWord, Integer type, Long intentId, String baseHostUrl) throws IOException {
+ 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);
-// log.info("用户话:{}", userWord);
+ log.info("天猫用户话:{}", userWord);
String requestJsonStr = JSON.toJSONString(requestPojo);
- //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
- HashMap headers = new HashMap<>();
- headers.put("Content-Type", "application/json;charset=utf-8");
- String channelId;
+// log.info("向终端发出请求的参数信息:{}", requestJsonStr);
+
+ Map headers;
switch (type) {
case 2:
- case 4: channelId = "tianmao-jiaoyou-audio-child-test";break;
+ case 4: headers =CHILD_HEADER;break;
case 3:
- case 5: channelId= "tianmao-jiaoyou-audio-adult-test";break;
- default: channelId = "tianmao-jiaoyou-audio-test";
+ case 5:
+ default: headers =ADULT_HEADER;
}
- headers.put("App-Channel-Id", channelId);
-// String resStr= OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, headers);
- String resStr= OkHttp3Utils.doPostJsonStr(baseHostUrl+"8070/api/chat2", requestJsonStr, headers);
+
+// String resStr= OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL, requestJsonStr, headers);
+ String resStr= OkHttp3Utils.doPostJsonStrForCentralWithUidParam(ScheduleServiceNew.BASE_HOST_URL, requestJsonStr, headers, userId);
if (resStr == null) {
return null;
}
-// log.info("天猫精灵晓悟返回:"+resStr);
+ log.info("天猫精灵晓悟返回:"+resStr);
TaskResult taskResult = null;
try {
JSONObject object = JSON.parseObject(resStr);
@@ -314,7 +314,7 @@ public class SpiritRedisService {
// }
// }
// }
- String path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio", resStr);
+ String path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_AUDIO_URL+"/api/audio", resStr);
if (StringUtils.isBlank(path) || path.equals("null")) {
log.error("没有获取到TTS返回的路径path");
return buildTextTaskResult(SORRY_REPEAT,intentId);
@@ -324,7 +324,9 @@ public class SpiritRedisService {
log.warn("没有获取到aipioneerUsername");
botAccount = "empty";
}
- taskResult = buildAudioUrlResult(intentId, changeAudioUrlTemp(path, botAccount));
+ String s;
+ taskResult = buildAudioUrlResult(intentId, (s=changeAudioUrlTemp(path, botAccount)));
+ log.info("天猫音频地址:"+s);
stringRedisTemplate.opsForValue().setIfPresent(PREFIX_REDIS+userId, path, 20, TimeUnit.SECONDS);
} catch (Exception e) {
log.error(e.toString());
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritTerminateRequest.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritTerminateRequest.java
index 899de2e..3358812 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritTerminateRequest.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/spirit/SpiritTerminateRequest.java
@@ -1,6 +1,5 @@
package ai.qiwu.com.xiaoduhome.spirit;
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java
index d154828..dd94b36 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java
@@ -1,14 +1,13 @@
package ai.qiwu.com.xiaoduhome.xiaoai.common;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
+import ai.qiwu.com.xiaoduhome.outside.OutSideCache;
+import ai.qiwu.com.xiaoduhome.outside.model.SingleBotRequest;
+import ai.qiwu.com.xiaoduhome.outside.model.SingleBotResponse;
import ai.qiwu.com.xiaoduhome.service.ScheduleServiceNew;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest;
-import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuRequest;
-import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuResponse;
-import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.math.NumberUtils;
import java.io.IOException;
import java.util.HashMap;
@@ -24,16 +23,27 @@ public class RequestTerminal {
private static final HashMap CHILD_HEADERS;
private static final HashMap ADULT_HEADERS;
+ private static final HashMap OUTSIDE_XIAOAI_HEADER;
+ private static final HashMap OUTSIDE_XIAODU_HEADER;
+
static {
- ALL_HEADERS = new HashMap<>();
+ ALL_HEADERS = new HashMap<>(2);
ALL_HEADERS.put("Content-Type", "application/json;charset=utf-8");
ALL_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-test");
- CHILD_HEADERS = new HashMap<>();
+ CHILD_HEADERS = new HashMap<>(2);
CHILD_HEADERS.put("Content-Type", "application/json;charset=utf-8");
CHILD_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-child-test");
- ADULT_HEADERS = new HashMap<>();
+ ADULT_HEADERS = new HashMap<>(2);
ADULT_HEADERS.put("Content-Type", "application/json;charset=utf-8");
ADULT_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-adult-test");
+
+ OUTSIDE_XIAOAI_HEADER = new HashMap<>(2);
+ OUTSIDE_XIAOAI_HEADER.put("Content-Type", "application/json;charset=utf-8");
+ OUTSIDE_XIAOAI_HEADER.put("App-Channel-Id", "xiaoai-single-jiaoyou-pro");
+
+ OUTSIDE_XIAODU_HEADER = new HashMap<>(2);
+ OUTSIDE_XIAODU_HEADER.put("Content-Type", "application/json;charset=utf-8");
+ OUTSIDE_XIAODU_HEADER.put("App-Channel-Id", "xiaodu-single-jiaoyou-pro");
}
/**
@@ -55,15 +65,32 @@ public class RequestTerminal {
case 2: headers = ADULT_HEADERS; break;
default: headers = ALL_HEADERS; break;
}
-// String resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);;
-// String resStr = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, headers);
- String resStr = OkHttp3Utils.doPostJsonStr(baseHostUrl+"8070/api/chat2", requestJsonStr, headers);
-// if (userId.equals(XiaoAiService.deviceId)) {
-// resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
-// }else {
-// resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
-// }
- return resStr;
+// return OkHttp3Utils.doPostJsonStr(baseHostUrl, requestJsonStr, headers);
+ return OkHttp3Utils.doPostJsonStrForCentralWithUidParam(baseHostUrl, requestJsonStr, headers, userId);
+ }
+
+ public static SingleBotResponse outSideRequestTerminate(String userId, String userWord, String botAccount) throws IOException {
+ SingleBotRequest requestPojo = new SingleBotRequest();
+ requestPojo.setUid(userId);
+ requestPojo.setMsg(userWord);
+ requestPojo.setBotAccount(botAccount);
+ String requestJsonStr = JSON.toJSONString(requestPojo);
+ //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
+
+ String response = OkHttp3Utils.doPostJsonStr(OutSideCache.SINGLE_BOT_INTERFACE, requestJsonStr, OUTSIDE_XIAOAI_HEADER);
+ return JSON.parseObject(response, SingleBotResponse.class);
+ }
+
+ public static SingleBotResponse xiaoduOutSideRequestTerminate(String userId, String userWord, String botAccount) throws IOException {
+ SingleBotRequest requestPojo = new SingleBotRequest();
+ requestPojo.setUid(userId);
+ requestPojo.setMsg(userWord);
+ requestPojo.setBotAccount(botAccount);
+ String requestJsonStr = JSON.toJSONString(requestPojo);
+ //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
+
+ String response = OkHttp3Utils.doPostJsonStr(OutSideCache.SINGLE_BOT_INTERFACE, requestJsonStr, OUTSIDE_XIAODU_HEADER);
+ return JSON.parseObject(response, SingleBotResponse.class);
}
public static void backBotRequest(String userId, Integer type) {
@@ -71,7 +98,7 @@ public class RequestTerminal {
requestPojo.setUid(userId);
requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD);
String requestJsonStr = JSON.toJSONString(requestPojo);
- OkHttp3Utils.xiaoaiBackPostAsync(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, type);
+ OkHttp3Utils.xiaoaiBackPostAsync(ScheduleServiceNew.BASE_HOST_URL+"?uid="+userId, requestJsonStr, type);
// if (userId.equals(XiaoAiService.deviceId)) {
// OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
// }else {
@@ -84,7 +111,7 @@ public class RequestTerminal {
requestPojo.setUid(userId);
requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD);
String requestJsonStr = JSON.toJSONString(requestPojo);
- OkHttp3Utils.tmallBackPostAsync(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, type);
+ OkHttp3Utils.tmallBackPostAsync(ScheduleServiceNew.BASE_HOST_URL+"?uid="+userId, requestJsonStr, type);
// if (userId.equals(XiaoAiService.deviceId)) {
// OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
// }else {
@@ -97,7 +124,7 @@ public class RequestTerminal {
requestPojo.setUid(userId);
requestPojo.setMsg(XiaoAiConstants.TTS.END_BOT_WORD);
String requestJsonStr = JSON.toJSONString(requestPojo);
- OkHttp3Utils.tmallBackPostAsync(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, type);
+ OkHttp3Utils.tmallBackPostAsync(ScheduleServiceNew.BASE_HOST_URL, requestJsonStr, type);
}
public static void main(String[] args) throws IOException {
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiServiceRedis.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiServiceRedis.java
index 5957257..c41eec4 100644
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiServiceRedis.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiServiceRedis.java
@@ -229,20 +229,20 @@ public class XiaoAiServiceRedis {
private XiaoAiResponse dealWithIntentRequest(final XiaoAiRequest request, final String userId) {
Boolean idle = request.getRequest().getNo_response();
String redisId = SpiritRedisService.PREFIX_REDIS+userId;
- String baseHostUrl = ScheduleServiceNew.BASE_HOST_URL;
- if (ScheduleServiceNew.SERVER_CHANGE) {
- if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.SERVER_CHANGE_KEY))) {
- if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))) {
- stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
- } else {
- stringRedisTemplate.opsForValue().set(Constants.CAN_NOT_MOVE_USER_KEY+userId, "1", 4, TimeUnit.MINUTES);
- }
- baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
- } else if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))){
- stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
- baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
- }
- }
+// String baseHostUrl = ScheduleServiceNew.BASE_HOST_URL;
+// if (ScheduleServiceNew.SERVER_CHANGE) {
+// if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.SERVER_CHANGE_KEY))) {
+// if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))) {
+// stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
+// } else {
+// stringRedisTemplate.opsForValue().set(Constants.CAN_NOT_MOVE_USER_KEY+userId, "1", 4, TimeUnit.MINUTES);
+// }
+// baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
+// } else if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY+userId))){
+// stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY+userId, 4, TimeUnit.MINUTES);
+// baseHostUrl = ScheduleServiceNew.OLD_BASE_HOST_URL;
+// }
+// }
try {
// long start = System.currentTimeMillis();
// log.info("redis get cost:"+(System.currentTimeMillis()-start));
@@ -297,9 +297,9 @@ public class XiaoAiServiceRedis {
XiaoAiConstants.TTS.ANOTHER_USER_IDLE);
}
try {
- final String finalBaseHost = baseHostUrl;
+// final String finalBaseHost = baseHostUrl;
// log.info("XIAOAI_BASE_HOST_URL:"+finalBaseHost);
- Future future = DplbotServiceUtil.getPool().submit(() -> task(userId, request.getQuery(), request.getType(), finalBaseHost));
+ Future future = DplbotServiceUtil.getPool().submit(() -> task(userId, request.getQuery(), request.getType()));
return future.get(2000, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", e.toString());
@@ -372,7 +372,7 @@ public class XiaoAiServiceRedis {
}
}
- private XiaoAiResponse task(String userId, String userWord, Integer type, String baseHostUrl) {
+ private XiaoAiResponse task(String userId, String userWord, Integer type) {
XiaoAiResponse xiaoAiResponse;
if (userWord == null) {
log.warn("请求中没有带有用户的话");
@@ -380,9 +380,9 @@ public class XiaoAiServiceRedis {
}
String response;
try {
-// log.info("小爱,用户话:{}", userWord);
- response = RequestTerminal.requestTerminate(userId, userWord, type, baseHostUrl);
-// log.info("小爱,小悟返回:{}", response);
+ log.info("小爱,用户话:{}", userWord);
+ response = RequestTerminal.requestTerminate(userId, userWord, type, ScheduleServiceNew.BASE_HOST_URL);
+ log.info("小爱,小悟返回:{}", response);
} catch (Exception e) {
log.error("向终端发出的请求信息失败:{}", e.toString());
return buildTextResponse(SORRY_REPEAT);
@@ -444,9 +444,7 @@ public class XiaoAiServiceRedis {
String path;
try {
- path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL+"9663/api/audio", response);
-// log.info("小度,语音:"+path);
-// path = OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:8190/api/audio", response);
+ path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_AUDIO_URL+"/api/audio", response);
if (StringUtils.isBlank(path) || path.equals("null")) {
log.error("没有获取到TTS返回的路径path");
return buildTextResponse(SORRY_REPEAT);
@@ -456,8 +454,9 @@ public class XiaoAiServiceRedis {
log.warn("没有获取到aipioneerUsername");
botAccount = "empty";
}
- xiaoAiResponse = buildAudioResponse(changeAudioUrlTemp(path, botAccount));
-// xiaoAiResponse = buildAudioResponse(changeAudioUrl(path, userId));
+ String s;
+ xiaoAiResponse = buildAudioResponse((s = changeAudioUrlTemp(path, botAccount)));
+ log.info("音频地址:"+s);
if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue()
.setIfPresent(SpiritRedisService.PREFIX_REDIS+userId, path, 15, TimeUnit.SECONDS))) {
log.info("xiaoai 超时redis存储成功");