Commit f6c638bc by 苗权威

7.4

parent efc1a429
<component name="libraryTable">
<library name="Maven: com.alibaba:fastjson:1.2.72">
<CLASSES>
<root url="jar://$PROJECT_DIR$/../../../../maven/myRepository/com/alibaba/fastjson/1.2.72/fastjson-1.2.72.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$PROJECT_DIR$/../../../../maven/myRepository/com/alibaba/fastjson/1.2.72/fastjson-1.2.72-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$PROJECT_DIR$/../../../../maven/myRepository/com/alibaba/fastjson/1.2.72/fastjson-1.2.72-sources.jar!/" />
</SOURCES>
</library>
</component>
\ No newline at end of file
......@@ -1207,27 +1207,45 @@ public class SpiritAudioUpload {
return ApachHttpUtils.getProbe(path, headers);
}
private static void jmeter(List<String> recommendWordList, CSVPrinter csvPrinter, String uid, List<String> keyList,
int index, int botCount, Map<String, String> 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<String> recommendWordList = new ArrayList<>();
Map<String, String> 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<String> 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<String> recommendWordList = new ArrayList<>();
Map<String, String> 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<String> 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<String> recommendWordList, CSVPrinter csvPrinter, String uid, List<String> keyList,
int index, int botCount, Map<String, String> 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();
}
}
......@@ -57,11 +57,13 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpasyncclient -->
<dependency>
......@@ -72,7 +74,7 @@
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
<version>1.2.72</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
......
......@@ -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);
}
}
}
......@@ -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;
}
......
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 {
......
......@@ -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;
}
......
......@@ -81,11 +81,14 @@ public class Initialize implements InitializingBean {
*/
private static volatile Map<Integer, String> ONLINE_ID_2_URL;
private static volatile Map<Integer, List<String>> ONLINE_ID_2_PERSON_TON;
/**
* 线上url -> (person,mood)
*/
private static volatile Map<String, List<String>> 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<String, Integer> mood2jumpUrl = OFFLINE_2_ONLINE.computeIfAbsent(person_offline, k -> new HashMap<>());
mood2jumpUrl.put(mood, jump);
}
......@@ -283,6 +291,7 @@ public class Initialize implements InitializingBean {
List<String> URL_LS_TEMP = new ArrayList<>();
Map<Integer, String> ONLINE_ID_2_URL_TEMP = new HashMap<>();
Map<String, List<String>> URL_2_PERSON_TON_TEMP = new HashMap<>();
Map<Integer, List<String>> ONLINE_ID_2_PERSON_MOOD_TEMP = new HashMap<>();
Map<String, Map<String, String>> PERSON_MOODURL_TEMP = new HashMap<>();
Map<String, PersonInfo> PERSON_INFO_OFFLINE_TEMP = new HashMap<>();
Map<String, Map<String, Integer>> OFFLINE_2_ONLINE_TEMP = new HashMap<>();
......@@ -290,7 +299,7 @@ public class Initialize implements InitializingBean {
List<SpeakersInfo> 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<String, PersonInfo> PERSON_INFO_ONLINE, List<String> THIRD_PARTY_TTS,
List<String> URL_LS, Map<Integer, String> ONLINE_ID_2_URL, Map<String, List<String>> URL_2_PERSON_TON,
Map<String, Map<String, String>> PERSON_MOODURL, Map<String, PersonInfo> PERSON_INFO_OFFLINE, Map<String,
Map<String, Integer>> OFFLINE_2_ONLINE) {
Map<String, Integer>> OFFLINE_2_ONLINE, Map<Integer, List<String>> 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<String> getTheOfflineJumpPersonInfo(String person, String mood) {
List<String> list;
Map<String, Integer> 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<String> list = new ArrayList<>();
list = new ArrayList<>();
list.add(init_person);
list.add(init_tone);
log.warn("没有获取到该人物情绪对应的线上person选用默认");
......
......@@ -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) {
......
......@@ -94,7 +94,7 @@
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
<version>1.2.72</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency>
......@@ -126,16 +126,16 @@
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org.apache.httpcomponents</groupId>-->
<!--<artifactId>httpclient</artifactId>-->
<!--</dependency>-->
<!--&lt;!&ndash; https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org.apache.httpcomponents</groupId>-->
<!--<artifactId>httpmime</artifactId>-->
<!--</dependency>-->
<!--&lt;!&ndash; https://mvnrepository.com/artifact/org.apache.commons/commons-text &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org.apache.commons</groupId>-->
......
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<String, String> 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<String,String> map, Map<String,String> 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<String, String> 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;
}
}
......@@ -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<String, String> params, Map<String, String> 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<Map.Entry<String, String>> paramsIterator = params.entrySet().iterator();
paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
}
Headers.Builder headerBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = header.entrySet().iterator();
headIterator.forEachRemaining(e -> headerBuilder.add(e.getKey(), e.getValue()));
Iterator<Map.Entry<String, String>> paramsIterator = params.entrySet().iterator();
paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
if (!CollectionUtils.isEmpty(header)) {
Iterator<Map.Entry<String, String>> 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<String, String> headers) throws IOException {
public static String doPostJsonStr(String url, String requestJsonStr, Map<String, String> 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<String, String> 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<Map.Entry<String, String>> 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) {
......
......@@ -51,6 +51,7 @@ public class SpiritController {
*/
@PostMapping(value = "/") //智能小说
public ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) {
log.info("==========================");
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
......
......@@ -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);
}
......
......@@ -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<byte[]> 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<byte[]> 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<byte[]> 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<byte[]> 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) {
......
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<Long, AudioInfo> 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<Long, AudioInfo> map = null;
int count = 1;
do {
try {
String response = OkHttp3Utils.doGet(AUDIO_INFO_INTERFACE, null, null);
List<AudioInfo> infos = JSON.parseObject(response, new TypeReference<List<AudioInfo>>(){});
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<String, String> params = new HashMap<>(1);
params.put("infoId", String.valueOf(infoId));
try {
String response = OkHttp3Utils.doGet(AUDIO_INFO_INTERFACE, params, null);
List<AudioInfo> infos = JSON.parseObject(response, new TypeReference<List<AudioInfo>>(){});
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;
}
}
package ai.qiwu.com.xiaoduhome.outside;
/**
* painter
* 20-7-2 下午3:48
*/
public interface OutsideConstant {
Integer CMDCODE_OUT = 10011;
String OUTSIDE_BYE_WORD = "再见";
}
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<String> 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;
}
}
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;
}
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;
}
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;
}
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;
}
......@@ -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<Response> future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, userId, finalBaseHost));
Future<Response> 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);
......
......@@ -28,7 +28,8 @@ class RequestTerminal {
HashMap<String, String> 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);
}
......
......@@ -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
......
......@@ -74,16 +74,17 @@ public class SpiritRedisService {
private static final String PREFIX_TMALL = "TMALL_";
// private static final HashMap<String, String> ADULT_HEADER;
// private static final HashMap<String, String> 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<String, String> ADULT_HEADER;
private static final HashMap<String, String> 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<TaskResult> future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId, finalBaseHost));
// final String finalBaseHost = baseHostUrl;
Future<TaskResult> 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<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
String channelId;
// log.info("向终端发出请求的参数信息:{}", requestJsonStr);
Map<String, String> 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());
......
package ai.qiwu.com.xiaoduhome.spirit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
......
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<String, String> CHILD_HEADERS;
private static final HashMap<String, String> ADULT_HEADERS;
private static final HashMap<String, String> OUTSIDE_XIAOAI_HEADER;
private static final HashMap<String, String> 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 {
......
......@@ -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<XiaoAiResponse> future = DplbotServiceUtil.getPool().submit(() -> task(userId, request.getQuery(), request.getType(), finalBaseHost));
Future<XiaoAiResponse> 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存储成功");
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment