Commit fa1dfaf3 by 苗权威

1.8

parent 35f456ef
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -122,6 +122,11 @@ public class SpiritController { ...@@ -122,6 +122,11 @@ public class SpiritController {
return "success"; return "success";
} }
@GetMapping("/del")
public void del(String filepath, Long skillId) {
spiritAudioUpload.deleteAudio(filepath, skillId);
}
@GetMapping("/get/csv") @GetMapping("/get/csv")
public void getCsv(String name, HttpServletResponse response) { public void getCsv(String name, HttpServletResponse response) {
String path = csvDic+name; String path = csvDic+name;
......
server: server:
port: 8188 port: 8189
logging: logging:
path: /home/dc2-user/projects/audiobox/spirit/logs path: /home/dc2-user/spirit/logs
level: level:
root: error root: error
csvDic: /home/dc2-user/audioBox/spirit/csv/ csvDic: /home/dc2-user/spirit/uploadCsv/
csvDicForBotChange: /home/dc2-user/spirit/fresh/
spring: spring:
......
...@@ -84,6 +84,13 @@ ...@@ -84,6 +84,13 @@
<systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath> <systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.tmall.spirit</groupId>
<artifactId>aliGenie</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/static/aliGenie-intent-sematic.jar</systemPath>
</dependency>
<dependency>
<groupId>ws.schild</groupId> <groupId>ws.schild</groupId>
<artifactId>jave-core</artifactId> <artifactId>jave-core</artifactId>
<version>2.7.1</version> <version>2.7.1</version>
......
...@@ -536,13 +536,18 @@ public class TTSUtils { ...@@ -536,13 +536,18 @@ public class TTSUtils {
// String command = "sox "+ StringUtils.join(filePathList, " "); // String command = "sox "+ StringUtils.join(filePathList, " ");
List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList()); if (filePathList.size() == 1) {
StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex "); String[] arr = filePathList.toArray(new String[]{});
for (int i = 0; i < filePathList.size(); i++) { Files.copy(Paths.get(arr[0]), Paths.get(targetFilepath));
builder.append("[").append(i).append(":a:0]"); } else {
List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex ");
for (int i = 0; i < filePathList.size(); i++) {
builder.append("[").append(i).append(":a:0]");
}
builder.append("concat=n=").append(filePathList.size()).append(":v=0:a=1[a] -map [a] ").append(targetFilepath);
CallPython.ffmpegExecute(builder.toString());
} }
builder.append("concat=n=").append(filePathList.size()).append(":v=0:a=1[a] -map [a] ").append(targetFilepath);
CallPython.ffmpegExecute(builder.toString());
// filePathList.add(targetFilepath); // filePathList.add(targetFilepath);
// CallPython.execute("sox "+ StringUtils.join(filePathList, " ")); // CallPython.execute("sox "+ StringUtils.join(filePathList, " "));
...@@ -656,6 +661,7 @@ public class TTSUtils { ...@@ -656,6 +661,7 @@ public class TTSUtils {
} }
public static void main(String[] args) throws IOException, UnsupportedAudioFileException { public static void main(String[] args) throws IOException, UnsupportedAudioFileException {
UploadCallbackUnzip("/home/yf01/下载/tts/testzip","/home/yf01/下载/testUnzip.zip"); // UploadCallbackUnzip("/home/yf01/下载/tts/testzip","/home/yf01/下载/testUnzip.zip");
Files.copy(Paths.get("/home/yf01/下载/d46f2708a6a79f5bcc4623b1030b8aca.mp3"), Paths.get("/home/yf01/下载/d46Test.mp3"));
} }
} }
...@@ -128,47 +128,71 @@ public class TTServiceUtil { ...@@ -128,47 +128,71 @@ public class TTServiceUtil {
} }
public static void buildMp3ResponseForAudio(HttpServletResponse response, String fileName, Boolean xiaoai, String range) { public static void buildMp3ResponseForAudio(HttpServletResponse response, String fileName, Boolean xiaoai, String range) {
response.setStatus(200);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName)); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
OutputStream out = new BufferedOutputStream(response.getOutputStream())){ OutputStream out = new BufferedOutputStream(response.getOutputStream())){
response.reset(); response.reset();
if (xiaoai) response.setStatus(206);
else response.setStatus(200);
response.setContentType("audio/mp3"); response.setContentType("audio/mp3");
// response.setHeader("Content-Type", "audio/mp3");
response.setHeader("Content-Type", "application/octet-stream");
int length = inputStream.available(); int length = inputStream.available();
// if (!Boolean.TRUE.equals(xiaoai)) {
// response.setHeader("Content-Length", String.valueOf(length));
// }
response.setHeader("Content-Length", String.valueOf(length)); response.setHeader("Content-Length", String.valueOf(length));
range = range.substring(range.indexOf("=")+1, range.indexOf("-")); if (xiaoai) {
String contentRange = "bytes "+range+"-"+length+"/"+length; response.setHeader("Content-Type", "application/octet-stream");
log.info("Content-Range:"+contentRange); range = range.substring(range.indexOf("=")+1, range.indexOf("-"));
response.setHeader("Content-Range", contentRange); String contentRange = "bytes "+range+"-"+length+"/"+length;
response.setHeader("Accept-Ranges", "bytes"); log.info("Content-Range:"+contentRange);
response.setHeader("icy-metaint", "8192"); response.setHeader("Content-Range", contentRange);
response.setHeader("Accept-Ranges", "bytes");
// response.setHeader("icy-metaint", "8192");
int begin = Integer.valueOf(range);
byte[] buffer = new byte[1024];
int ln;
while ((ln = inputStream.read(buffer)) != -1) {
if (begin > 0) {
begin -= ln;
if (begin < 0) {
out.write(buffer, ln+begin, -begin);
}
} else {
out.write(buffer, 0, ln);
}
}
out.flush();
} else {
response.setHeader("Content-Type", "audio/mp3");
byte[] buffer = new byte[1024];
int ln;
while ((ln = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, ln);
}
out.flush();
}
// response.setHeader("Cache-Control", "max-age=43200, public"); // response.setHeader("Cache-Control", "max-age=43200, public");
int begin = Integer.valueOf(range); } catch (ClientAbortException e) {
} catch (IOException e) {
log.error("buildMp3Response:写入音频流到HttpServletResponse失败:{}", e.toString());
}
}
public static void buildMp3ResponseForAudioNoRange(HttpServletResponse response, String fileName, Boolean xiaoai) {
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
OutputStream out = new BufferedOutputStream(response.getOutputStream())){
response.reset();
// if (xiaoai) response.setStatus(206);
// else response.setStatus(200);
response.setStatus(200);
response.setContentType("audio/mp3");
response.setHeader("Content-Type", "audio/mp3");
if (!xiaoai) response.setHeader("Content-Length", String.valueOf(inputStream.available()));
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int ln; int ln;
while ((ln = inputStream.read(buffer)) != -1) { while ((ln = inputStream.read(buffer)) != -1) {
if (begin > 0) { out.write(buffer, 0, ln);
begin -= ln;
if (begin < 0) {
out.write(buffer, ln+begin, -begin);
}
} else {
out.write(buffer, 0, ln);
}
} }
out.flush(); out.flush();
// byte[] buffer = new byte[1024];
// int ln;
// while ((ln = inputStream.read(buffer)) != -1) {
// out.write(buffer, 0, ln);
// }
// out.flush();
} catch (ClientAbortException e) { } catch (ClientAbortException e) {
} catch (IOException e) { } catch (IOException e) {
......
...@@ -236,7 +236,8 @@ public class TTSController { ...@@ -236,7 +236,8 @@ public class TTSController {
@GetMapping("/api/audio/get") @GetMapping("/api/audio/get")
public void apiAudioGet(@RequestParam(required = false) String type, @RequestParam String path, public void apiAudioGet(@RequestParam(required = false) String type, @RequestParam String path,
HttpServletResponse response, HttpServletRequest request) { HttpServletResponse response) {
ttService.apiAudioGet(type, path, response, request); // ttService.apiAudioGet(type, path, response, request);
ttService.apiAudioGetNoRange(type, path, response);
} }
} }
...@@ -2084,11 +2084,11 @@ public class TTService { ...@@ -2084,11 +2084,11 @@ public class TTService {
if (xiaoAi) { if (xiaoAi) {
OkHttp3Utils.backPostAsync(audioUrl+type); OkHttp3Utils.backPostAsync(audioUrl+type);
} }
Enumeration enumeration = request.getHeaderNames(); // Enumeration enumeration = request.getHeaderNames();
while (enumeration.hasMoreElements()) { // while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement(); // String name = (String) enumeration.nextElement();
log.warn(name+":"+request.getHeader(name)); // log.warn(name+":"+request.getHeader(name));
} // }
String range = request.getHeader("range"); String range = request.getHeader("range");
if (Files.exists((pt = Paths.get(path)))) { if (Files.exists((pt = Paths.get(path)))) {
while (XIAOAI_MP3_MARK.contains(path)) { while (XIAOAI_MP3_MARK.contains(path)) {
...@@ -2114,6 +2114,36 @@ public class TTService { ...@@ -2114,6 +2114,36 @@ public class TTService {
} }
} }
public void apiAudioGetNoRange(String type, String path, HttpServletResponse response) {
Path pt;
boolean xiaoAi = StringUtils.isNotBlank(type);
if (xiaoAi) {
OkHttp3Utils.backPostAsync(audioUrl+type);
}
if (Files.exists((pt = Paths.get(path)))) {
while (XIAOAI_MP3_MARK.contains(path)) {
try {
Thread.sleep(500);
} catch (Exception e) {}
}
TTServiceUtil.buildMp3ResponseForAudioNoRange(response, path, xiaoAi);
} else {
try {
Thread.sleep(1500);
} catch (Exception e) {}
if (Files.exists(pt)) {
while (XIAOAI_MP3_MARK.contains(path)) {
try {
Thread.sleep(300);
} catch (Exception e) {}
}
TTServiceUtil.buildMp3ResponseForAudioNoRange(response, path, xiaoAi);
} else {
log.error("等待2s后仍未获取到音箱的音频结果");
}
}
}
public String apiAudio(ApiAudioData apiAudioData) { public String apiAudio(ApiAudioData apiAudioData) {
List<Dialog> dialogs = apiAudioData.getDialogs(); List<Dialog> dialogs = apiAudioData.getDialogs();
// botname不能为空 // botname不能为空
......
...@@ -290,7 +290,7 @@ public class Test { ...@@ -290,7 +290,7 @@ public class Test {
Pattern pattern = Pattern.compile(TTSUtils.getAbRegex()); Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
String[] notVariableTextArray = pattern.split("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71"); String[] notVariableTextArray = pattern.split("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71");
System.out.println(notVariableTextArray.length);
System.out.println(Arrays.toString(notVariableTextArray)); System.out.println(TTSUtils.buildMP3Filename("为您推荐以上作品:《妖刀异闻录》、《小太阳》、《遇见伽利略》,你可以说:打开某作品"));
} }
} }
...@@ -132,6 +132,19 @@ ...@@ -132,6 +132,19 @@
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId> <artifactId>httpmime</artifactId>
</dependency> </dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/org.apache.commons/commons-text &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org.apache.commons</groupId>-->
<!--<artifactId>commons-text</artifactId>-->
<!--<version>1.8</version>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -7,8 +7,10 @@ package ai.qiwu.com.xiaoduhome.common; ...@@ -7,8 +7,10 @@ package ai.qiwu.com.xiaoduhome.common;
public interface Constants { public interface Constants {
String QI_WU_INTERFACE = "http://didi-gz3.jiaoyou365.com:8070/api/chat2"; String QI_WU_INTERFACE = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
String QI_WU_INTERFACE_di2 = "http://didi-gz2.jiaoyou365.com:8070/api/chat2";
String INTERFACE_DI = "http://didi-gz3.jiaoyou365.com:8070/api/chat2"; String INTERFACE_DI = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
String TTS_DIDI3_GET = "http://didi-gz3.jiaoyou365.com:9663/api/audio/get?path="; String TTS_DIDI3_GET = "http://didi-gz3.jiaoyou365.com:9663/api/audio/get?path=";
String TTS_DIDI2_GET = "http://didi-gz2.jiaoyou365.com:9663/api/audio/get?path=";
String TTS_DIDI3_GET_XIAOAI = "http://didi-gz3.jiaoyou365.com:9663/api/audio/get?type="; String TTS_DIDI3_GET_XIAOAI = "http://didi-gz3.jiaoyou365.com:9663/api/audio/get?type=";
String TTS_DIDI4_GET_XIAOAI = "http://didi-gz4.jiaoyou365.com:9663/api/audio/get?type="; String TTS_DIDI4_GET_XIAOAI = "http://didi-gz4.jiaoyou365.com:9663/api/audio/get?type=";
String TTS_DIDI4_GET_XIAOAI_STATIC = "http://didi-gz4.jiaoyou365.com:9663/static/"; String TTS_DIDI4_GET_XIAOAI_STATIC = "http://didi-gz4.jiaoyou365.com:9663/static/";
...@@ -101,11 +103,18 @@ public interface Constants { ...@@ -101,11 +103,18 @@ public interface Constants {
} }
interface WelcomeWord { interface WelcomeWord {
String WELCOME = "欢迎来到交游天下,你可以说推荐作品给我"; String WELCOME = "欢迎来到交游天下。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";
String WELCOME_FORMAT = "欢迎来到交游天下。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的%s,您可以说打开%s。或者说,推荐其它作品。";
String SKILL = "交游天下"; String SKILL = "交游天下";
String WELCOME_SMART = "小朋友你好,欢迎来到智能故事,你可以对我说有什么好玩的吗"; String SKILL_DEFAULT = "我们的技能";
// 欢迎来到晓悟智能故事。与可爱的角色们自由对话,畅游不同的故事世界。我们新上线了遇见伽利略,你可以说打开遇见伽利略。或者说,推荐其它作品。
String WELCOME_SMART = "欢迎来到晓悟智能故事。我们新上线了遇见伽利略,你可以说打开遇见伽利略。或者说,推荐其它作品。";
String WELCOME_SMART_FORMAT = "欢迎来到晓悟智能故事。与可爱的角色们自由对话,畅游不同的故事世界。我们新上线了%s,你可以说打开%s。或者说,推荐其它作品。";
String WELCOME_SMART_FORMAT_AI = "欢迎来到晓悟智能故事。推荐我们新上线的%s,你可以说打开%s。或者说,推荐其它作品。";
String SKILL_SMART = "智能故事"; String SKILL_SMART = "智能故事";
String WELCOME_NOVEL = "欢迎来到智能小说,你可以说推荐作品给我"; // 与剧情人物自由对话,带您体验不同的人生和情怀。
String WELCOME_NOVEL = "欢迎来到晓悟智能小说。向您推荐新上线的妖刀异闻录,您可以说打开妖刀异闻录。或者说,推荐其它作品。";
String WELCOME_NOVEL_FORMAT = "欢迎来到晓悟智能小说。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的%s,您可以说打开%s。或者说,推荐其它作品。";
String SKILL_NOVEL = "智能小说"; String SKILL_NOVEL = "智能小说";
String WELCOME_LITERATURE = "欢迎来到互动文艺,你可以说推荐作品给我"; String WELCOME_LITERATURE = "欢迎来到互动文艺,你可以说推荐作品给我";
String SKILL_LITERATURE = "互动文艺"; String SKILL_LITERATURE = "互动文艺";
...@@ -120,9 +129,15 @@ public interface Constants { ...@@ -120,9 +129,15 @@ public interface Constants {
interface EndMsg { interface EndMsg {
String BYE_BYE = "我们的作品库在不断的扩充,欢迎下次再来玩"; String BYE_BYE = "我们的作品库在不断的扩充,欢迎下次再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦"; String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_BYE_NOVEL = "后续有更多作品上线,欢迎常来访问智能小说。"; // smart novel
String END_BYE_STORY = "智能故事后续会有更多作品上线,欢迎常来"; // smart story
String END_BYE_JIAOYOU = "交游天下后续会有更多作品上线,欢迎常来";
String END_BYE_DEFAULT = "后续会有更多作品上线,欢迎常来我们的技能";
String END_BYE_Adult = "再见啦,记得下次再来玩哦"; String END_BYE_Adult = "再见啦,记得下次再来玩哦";
String CAN_NOT_UNDERSTAND = "用户无输入或多次输入无法理解"; String CAN_NOT_UNDERSTAND = "用户无输入或多次输入无法理解访问";
String USER_SAY_CANCEL = "用户直接说退出"; String USER_SAY_CANCEL = "用户直接说退出";
String BEFORE_LOAD_OUT = "如果您想退出我们的技能请对我说退出";
} }
interface ErrorMsg { interface ErrorMsg {
...@@ -160,7 +175,7 @@ public interface Constants { ...@@ -160,7 +175,7 @@ public interface Constants {
String FLOWER_INTERFACE = "http://aws-nx2.chewrobot.com:18082/api/flower/count"; String FLOWER_INTERFACE = "http://aws-nx2.chewrobot.com:18082/api/flower/count";
String USER_CLOOEC_LIST = "http://aliyun-hz1.chewrobot.com:18082/api/favorite"; String USER_CLOOEC_LIST = "http://aliyun-hz1.chewrobot.com:18082/api/favorite";
String USER_ID_BY_TOKEN = "https://account-center-test.chewrobot.com/api/sdk/user/info"; String USER_ID_BY_TOKEN = "https://account-center-test.chewrobot.com/api/sdk/user/info";
String ASIDE_IMG_URL = "http://didi-gz5.jiaoyou365.com:18082/api/works"; String ASIDE_IMG_URL = "http://didi-gz3.jiaoyou365.com:18082/api/works";
} }
interface BAI_DU { interface BAI_DU {
...@@ -168,5 +183,4 @@ public interface Constants { ...@@ -168,5 +183,4 @@ public interface Constants {
String BAIDU_TOKEN = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&client_id=dSG525LMr887uLlfAyK1C1ag&client_secret=1azuXoKHMSWT5MVNNkZ4C5mED23qySZh&redirect_uri=https%3A%2F%2Fwww.miaoshop.top%2Fxiaodu%2Fbaidu%2Fcode&code="; String BAIDU_TOKEN = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&client_id=dSG525LMr887uLlfAyK1C1ag&client_secret=1azuXoKHMSWT5MVNNkZ4C5mED23qySZh&redirect_uri=https%3A%2F%2Fwww.miaoshop.top%2Fxiaodu%2Fbaidu%2Fcode&code=";
String BAIDU_AUTHORIZE = "https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=dSG525LMr887uLlfAyK1C1ag&redirect_uri=https%3A%2F%2Fwww.miaoshop.top%2Fxiaodu%2Fbaidu%2Fcode&confirm_login=1&state=mqw"; String BAIDU_AUTHORIZE = "https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=dSG525LMr887uLlfAyK1C1ag&redirect_uri=https%3A%2F%2Fwww.miaoshop.top%2Fxiaodu%2Fbaidu%2Fcode&confirm_login=1&state=mqw";
} }
} }
...@@ -160,6 +160,45 @@ public class OkHttp3Utils { ...@@ -160,6 +160,45 @@ public class OkHttp3Utils {
@Override @Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody body = response.body()){ try (ResponseBody body = response.body()){
// body.string();
log.info("退出成功:{}", body.string());
} catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
}
}
});
}
public static void xiaoaiBackPostAsync(String url, String requestJsonStr, Integer type) {
String header = "xiaoai-jiaoyou-audio-test";
if (type != null) {
switch (type) {
case 1 :
case 3 : header = "xiaoai-jiaoyou-audio-child-test";break;
case 2 :
case 4 : header = "xiaoai-jiaoyou-audio-adult-test";break;
default: header = "xiaoai-jiaoyou-audio-test";
}
}
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr))
.header("App-Channel-Id", header)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
log.info("退出失败");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody body = response.body()){
// body.string();
log.info("退出成功:{}", body.string()); log.info("退出成功:{}", body.string());
} catch (SocketTimeoutException e) { } catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString()); log.error("捕获到SocketTimeoutException:{}", e.toString());
......
package ai.qiwu.com.xiaoduhome.common; package ai.qiwu.com.xiaoduhome.common;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
...@@ -18,6 +20,7 @@ import java.util.Objects; ...@@ -18,6 +20,7 @@ import java.util.Objects;
* @author 苗权威 * @author 苗权威
* @dateTime 19-6-29 下午5:11 * @dateTime 19-6-29 下午5:11
*/ */
@Slf4j
public class Utils { public class Utils {
/** /**
...@@ -129,6 +132,126 @@ public class Utils { ...@@ -129,6 +132,126 @@ public class Utils {
return new Timestamp(new Date(curTimeMills).getTime()); return new Timestamp(new Date(curTimeMills).getTime());
} }
/**
* 获取真实ip
*
* @param acceptInnerIp 是否可以返回内网ip
* @return 真实ip
*/
public static String getRemoteIpByServletRequest(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (StringUtils.isNotBlank(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
// log.info("x:"+ip);
if (ip.contains(",")) {
ip = ip.split(",")[0];
}
}
if (isIpValid(ip)) {
return ip;
}
ip = request.getHeader("Proxy-Client-IP");
if (isIpValid(ip)) {
// log.info("pro:"+ip);
return ip;
}
ip = request.getHeader("WL-Proxy-Client-IP");
if (isIpValid(ip)) {
// log.info("wl:"+ip);
return ip;
}
ip = request.getHeader("HTTP_CLIENT_IP");
if (isIpValid(ip)) {
return ip;
}
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
if (isIpValid(ip)) {
// log.info("HTTP:"+ip);
return ip;
}
ip = request.getHeader("X-Real-IP");
if (isIpValid(ip)) {
// log.info("x-R:"+ip);
return ip;
}
ip = request.getRemoteAddr();
// log.info("remote:"+ip);
return ip;
}
/**
* 判断是否有效
* @param ip ip
* @param acceptInnerIp 是否接受内网ip
* @return
*/
private static boolean isIpValid(String ip, boolean acceptInnerIp) {
return acceptInnerIp ? isIpValid(ip) : isIpValidAndNotPrivate(ip);
}
/**
* 仅仅判断ip是否有效
* @param ip
* @return
*/
private static boolean isIpValid(String ip) {
if (StringUtils.isBlank(ip)) {
return false;
}
String[] split = ip.split("\\.");
if (split.length != 4) {
return false;
}
try {
long first = Long.valueOf(split[0]);
long second = Long.valueOf(split[1]);
long third = Long.valueOf(split[2]);
long fourth = Long.valueOf(split[3]);
return first < 256 && first > 0
&& second < 256 && second >= 0
&& third < 256 && third >= 0
&& fourth < 256 && fourth >= 0;
} catch (NumberFormatException e) {
return false;
}
}
/**
* 判断ip是否有效,并且不是内网ip
* @param ip
* @return
*/
private static boolean isIpValidAndNotPrivate(String ip) {
if (StringUtils.isBlank(ip)) {
return false;
}
String[] split = ip.split("\\.");
try {
long first = Long.valueOf(split[0]);
long second = Long.valueOf(split[1]);
long third = Long.valueOf(split[2]);
long fourth = Long.valueOf(split[3]);
if (first < 256 && first > 0
&& second < 256 && second >= 0
&& third < 256 && third >= 0
&& fourth < 256 && fourth >= 0) {
if (first == 10) {
return false;
}
if (first == 172 && (second >= 16 && second <= 31)) {
return false;
}
if (first == 192 && second == 168) {
return false;
}
return true;
}
return false;
} catch (NumberFormatException e) {
return false;
}
}
public static void main(String[] args) throws ParseException { public static void main(String[] args) throws ParseException {
String s = "[{\"type\": \"SendEvent\",\"componentId\":\"%s\"}]"; String s = "[{\"type\": \"SendEvent\",\"componentId\":\"%s\"}]";
//System.out.println(String.format(s, "gsagh")); //System.out.println(String.format(s, "gsagh"));
......
...@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.controller; ...@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.controller;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException; import org.apache.catalina.connector.ClientAbortException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
...@@ -41,6 +42,11 @@ public class AudioGetController { ...@@ -41,6 +42,11 @@ public class AudioGetController {
// } // }
// } // }
// @GetMapping("/audio/name/change")
// public void changeName(Integer ) {
//
// }
private void buildMp3Response(HttpServletResponse response, String fileName) { private void buildMp3Response(HttpServletResponse response, String fileName) {
response.setStatus(200); response.setStatus(200);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName)); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
......
...@@ -34,7 +34,7 @@ public class SpiritController { ...@@ -34,7 +34,7 @@ public class SpiritController {
*/ */
@PostMapping(value = "/") //交游天下 @PostMapping(value = "/") //交游天下
public ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) { public ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) {
log.info("天猫请求信息:{}",taskQuery); // log.info("天猫请求信息:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery); TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response // build response
...@@ -42,7 +42,7 @@ public class SpiritController { ...@@ -42,7 +42,7 @@ public class SpiritController {
TaskResult taskResult = spiritService.getResponse(query, 1); TaskResult taskResult = spiritService.getResponse(query, 1);
resultModel.setReturnCode("0"); resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult); resultModel.setReturnValue(taskResult);
log.info("天猫响应信息:"+ JSON.toJSONString(resultModel)); // log.info("天猫响应信息:"+ JSON.toJSONString(resultModel));
return resultModel; return resultModel;
} }
......
package ai.qiwu.com.xiaoduhome.controller; package ai.qiwu.com.xiaoduhome.controller;
import ai.qiwu.com.xiaoduhome.service.chatsLog.ChatLogs;
import ai.qiwu.com.xiaoduhome.service.chatsLog.LoginData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-11-18 下午6:37 * @dateTime 19-11-18 下午6:37
*/ */
@Controller //@Controller
@Slf4j
public class WebSocketLogController { public class WebSocketLogController {
private final ChatLogs chatLogs;
private static ConcurrentHashMap<String, LoginData> loadState = new ConcurrentHashMap<>();
@Autowired
public WebSocketLogController(ChatLogs chatLogs) {
this.chatLogs = chatLogs;
}
@GetMapping("/audio/index") @GetMapping("/audio/index")
public String logIndexPage(ModelMap modelMap) { public String logIndexPage(ModelMap modelMap) {
return "index.html"; return "index.html";
...@@ -36,6 +54,85 @@ public class WebSocketLogController { ...@@ -36,6 +54,85 @@ public class WebSocketLogController {
return "Log4.html"; return "Log4.html";
} }
// @GetMapping("/chat/log")
// public @ResponseBody String logTemp(String token, @RequestParam(required = false) Integer row,
// @RequestParam(required = false) String count,
// @RequestParam(required = false) String type) {
// if (StringUtils.isBlank(token)) return "超时重新登录";
// LoginData data;
// if ((data = loadState.get(token)) == null) return "超时重新登录";
// long current = System.currentTimeMillis();
// if (current-data.getTime() > 7200000) {
// loadState.remove(token);
// return "超时重新登录";
// }
// if (row == null || row == 0) row = 1000;
// String s = chatLogs.look(row, count, type);
// if (s == null) s = "出错,请刷新重试";
// return s;
// }
@GetMapping("/chat/log")
public @ResponseBody String logTemp(String token, @RequestParam(required = false) Integer row,
@RequestParam(required = false) String count,
@RequestParam(required = false) String type) {
if (StringUtils.isBlank(token)) return "超时重新登录";
LoginData data;
if ((data = loadState.get(token)) == null) return "超时重新登录";
long current = System.currentTimeMillis();
if (current-data.getTime() > 7200000) {
loadState.remove(token);
return "超时重新登录";
}
if (row == null || row == 0) row = 1000;
String s = chatLogs.look(row, count, type);
if (s == null) s = "出错,请刷新重试";
return s;
}
@GetMapping("/chat/choose")
public String logTemp(String token, ModelMap modelMap) {
if (StringUtils.isBlank(token)) return "LoadFailed.html";
LoginData data;
if ((data = loadState.get(token)) == null) return "LoadFailed.html";
long current = System.currentTimeMillis();
if (current-data.getTime() > 7200000) {
loadState.remove(token);
return "LoadFailed.html";
}
modelMap.put("token", token);
return "ChatLogChoose.html";
}
@GetMapping("/chat/login/check")
public @ResponseBody String lookLogSignIn(String userName, String passwd) {
log.info(userName+":"+passwd);
long current = System.currentTimeMillis();
loadState.entrySet().removeIf(entry -> current-entry.getValue().getTime() > 7200000);
if ("qiwu".equals(userName) && "qiwuai2020".equals(passwd)) {
LoginData data;
for (Map.Entry<String, LoginData> entry: loadState.entrySet()) {
if (userName.equals(entry.getValue().getUsername())) {
entry.getValue().setTime(current);
return entry.getKey();
}
}
String token = RandomStringUtils.randomAlphabetic(8);
data = new LoginData();
data.setUsername(userName);
data.setToken(token);
data.setTime(current);
loadState.put(token, data);
return token;
}
return "0";
}
@GetMapping("/chat/login")
public String login(ModelMap modelMap) {
return "LookLogLogin.html";
}
// eae846c7d1ca51474ebc7230ace47bf2.txt // eae846c7d1ca51474ebc7230ace47bf2.txt
@GetMapping("/aligenie/{name}") @GetMapping("/aligenie/{name}")
public String spirit(@PathVariable String name, ModelMap modelMap) { public String spirit(@PathVariable String name, ModelMap modelMap) {
......
package ai.qiwu.com.xiaoduhome.controller; package ai.qiwu.com.xiaoduhome.controller;
import ai.qiwu.com.xiaoduhome.xiaoai.common.Utils;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest; import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.Response;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService; import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiTestService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RestController; import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Enumeration;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
/** /**
* @author 苗权威 * @author 苗权威
...@@ -18,60 +29,106 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -18,60 +29,106 @@ import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/xiaoai") @RequestMapping("/xiaoai")
@Slf4j @Slf4j
@RequiredArgsConstructor(onConstructor_={@Autowired})
public class XiaoAiController { public class XiaoAiController {
private final XiaoAiService xiaoAiService; private final XiaoAiService xiaoAiService;
private final XiaoAiTestService xiaoAiTestService;
@Autowired
public XiaoAiController(XiaoAiService xiaoAiService) {
this.xiaoAiService = xiaoAiService;
}
/** /**
* Controller控制器 * Controller控制器
* @param request * @param request
* @return * @return
*/ */
@RequestMapping("/") @PostMapping("/")
public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) { public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request,HttpServletRequest servletRequest) { // 交游天下
log.info("请求:"+request); log.info("请求:"+request);
XiaoAiResponse response = xiaoAiService.getResponse(request); // log.info("响应:"+response);
log.info("响应:"+response); try {
return response; if (!Utils.encry(5, servletRequest)) {
log.error("验证没通过:5");
return null;
}
request.setType(5);
return xiaoAiService.getResponse(request);
} catch (Exception e) {
log.error("controller xiaoai:"+e);
}
return buildTextResponse(SORRY_REPEAT);
// return xiaoAiService.getResponse(request); // return xiaoAiService.getResponse(request);
} }
@RequestMapping("/child") @PostMapping("/child")
public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request) { public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request,HttpServletRequest servletRequest) { // 智能故事
//log.info("请求:"+request); //log.info("请求:"+request);
request.setType(1); try {
XiaoAiResponse response = xiaoAiService.getResponse(request); if (!Utils.encry(1, servletRequest)) {
// log.info("响应:"+response); log.error("验证没通过:1");
return response; return null;
}
request.setType(1);
// log.info("响应:"+response);
return xiaoAiService.getResponse(request);
} catch (Exception e) {
log.error("controller xiaoaiChild:"+e);
}
return buildTextResponse(SORRY_REPEAT);
// return xiaoAiService.getResponse(request); // return xiaoAiService.getResponse(request);
} }
@RequestMapping("/story") //互动故事 @PostMapping("/story") //互动故事
public XiaoAiResponse xiaoaiChildStory(@RequestBody XiaoAiRequest request) { // @RequestBody XiaoAiRequest request,
//log.info("请求:"+request); public XiaoAiResponse xiaoaiChildStory(HttpServletRequest servletRequest) {
request.setType(3); // long start = System.currentTimeMillis();
XiaoAiResponse response = xiaoAiService.getResponse(request); // if (!Utils.encry(3, servletRequest)) return null;
// log.info("encry:"+(System.currentTimeMillis()-start));
try (InputStream stream = servletRequest.getInputStream()){
StringBuilder sb = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = stream.read(b)) != -1;)
{
sb.append(new String(b, 0, n));
}
String str = sb.toString();
log.info("请求:"+str);
XiaoAiRequest request = JSON.parseObject(str, XiaoAiRequest.class);
request.setType(5);
XiaoAiResponse response = xiaoAiTestService.getResponse(request);
log.info("响应:"+response);
return response;
} catch (Exception e) {
}
return null;
// log.info("请求:"+request);
// request.setType(5);
// XiaoAiResponse response = xiaoAiService.getResponse(request);
// log.info("响应:"+response); // log.info("响应:"+response);
return response; // return response;
// return xiaoAiService.getResponse(request); // return xiaoAiService.getResponse(request);
} }
@RequestMapping("/adult") @PostMapping("/adult")
public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request) { public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request, HttpServletRequest servletRequest) { // 智能小说
//log.info("请求:"+request); //log.info("请求:"+request);
request.setType(2); try {
XiaoAiResponse response = xiaoAiService.getResponse(request); if (!Utils.encry(2, servletRequest)) {
// log.info("响应:"+response); log.error("验证没通过:2");
return response; return null;
}
request.setType(2);
// log.info("响应:"+response);
return xiaoAiService.getResponse(request);
} catch (Exception e) {
log.error("controller xiaoaiAdult:"+e);
}
return buildTextResponse(SORRY_REPEAT);
// return xiaoAiService.getResponse(request); // return xiaoAiService.getResponse(request);
} }
@RequestMapping("/literature") // 互动文艺 // @PostMapping("/literature") // 互动文艺
public XiaoAiResponse xiaoaiAdultLiterature(@RequestBody XiaoAiRequest request) { public XiaoAiResponse xiaoaiAdultLiterature(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request); //log.info("请求:"+request);
request.setType(4); request.setType(4);
...@@ -85,8 +142,33 @@ public class XiaoAiController { ...@@ -85,8 +142,33 @@ public class XiaoAiController {
public void xiaoaiPlayed(String userId) { public void xiaoaiPlayed(String userId) {
if (StringUtils.isNotBlank(userId)) { if (StringUtils.isNotBlank(userId)) {
// log.info("小爱确认音频播放:"+userId); // log.info("小爱确认音频播放:"+userId);
xiaoAiService.changeAudioPlayMark(userId); // xiaoAiService.changeAudioPlayMark(userId);
} }
else log.error("/xiaoai/audio/play userId is null"); else log.error("/xiaoai/audio/play userId is null");
} }
private XiaoAiResponse buildResponse() {
XiaoAiResponse response = new XiaoAiResponse();
response.setVersion("1.0");
response.setIs_session_end(false);
Response responseInfo = new Response();
// 这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,
// 若不主动打开则小爱在一次会话后退出技能。
responseInfo.setOpen_mic(true);
response.setResponse(responseInfo);
return response;
}
private XiaoAiResponse buildTextResponse(String text) {
XiaoAiResponse response = buildResponse();
Response responseInfo = response.getResponse();
ToSpeak toSpeak = new ToSpeak();
toSpeak.setType(0);
toSpeak.setText(text);
responseInfo.setTo_speak(toSpeak);
return response;
}
} }
...@@ -11,15 +11,22 @@ import com.alibaba.da.coin.ide.spi.standard.ResultModel; ...@@ -11,15 +11,22 @@ import com.alibaba.da.coin.ide.spi.standard.ResultModel;
import com.alibaba.da.coin.ide.spi.standard.TaskQuery; import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult; import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.da.coin.ide.spi.trans.MetaFormat; import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils; import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.tags.HtmlEscapingAwareTag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
...@@ -32,36 +39,81 @@ import java.util.UUID; ...@@ -32,36 +39,81 @@ import java.util.UUID;
@Slf4j @Slf4j
public class XiaoDuHomeController { public class XiaoDuHomeController {
@RequestMapping("/chat") //互动天地 private int test = 0;
@RequestMapping(value = "/chat", method = RequestMethod.HEAD)
public void chatHead(HttpServletResponse response) {
// if (test++ < 5) {
// try {
// Enumeration enumeration = request.getHeaderNames();
// while (enumeration.hasMoreElements()) {
// String name = (String) enumeration.nextElement();
// log.info(name+":"+request.getHeader(name));
// }
// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
// StringBuilder builder = new StringBuilder();
// String temp;
// while((temp = bufferedReader.readLine()) != null) {
// builder.append(temp);
// }
// log.info("message:"+builder.toString());
// } catch (Exception e) {
// log.warn("探活 failed:"+e);
// }
// }
response.setStatus(200);
}
@PostMapping("/chat") //互动天地
public String chat() { public String chat() {
HttpServletRequest request = null;
try { try {
//log.info("--------------分界线-------------------"); //log.info("--------------分界线-------------------");
DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 5); DplBotService service = new DplBotService((request=Utils.getHttpServletRequest()), 5);
// log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes()); // log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
log.info(service.getStrRequest()); // log.info(service.getStrRequest());
//service.disableVerify(); //service.disableVerify();
service.enableVerify(); service.enableVerify();
String str = service.run(); // log.info("响应信息:{}", str);
log.info("响应信息:{}", str); return service.run();
return str; } catch (MismatchedInputException ex) {
log.info("交游探活:"+ex);
if (test++ < 5) {
try {
Enumeration enumeration = request.getHeaderNames();
while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
log.info(name+":"+request.getHeader(name));
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
StringBuilder builder = new StringBuilder();
String temp;
while((temp = bufferedReader.readLine()) != null) {
builder.append(temp);
}
log.info("message:"+builder.toString());
} catch (Exception e) {
log.warn("探活 failed:"+e);
}
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("交游:"+e);
//log.error("出现错误 "+e.toString()); //log.error("出现错误 "+e.toString());
} }
return null; return null;
} }
@RequestMapping("/story") //交互故事 @PostMapping("/story") //交互故事
public String story() { public String story() {
try { try {
//log.info("--------------分界线-------------------"); //log.info("--------------分界线-------------------");
DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 3); DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 5);
// log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes()); // log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
// log.info(service.getStrRequest()); log.info(service.getStrRequest());
//service.disableVerify(); //service.disableVerify();
service.enableVerify(); service.enableVerify();
String str = service.run(); String str = service.run();
// log.info("响应信息:{}", str); log.info("响应信息:{}", str);
return str; return str;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -70,7 +122,7 @@ public class XiaoDuHomeController { ...@@ -70,7 +122,7 @@ public class XiaoDuHomeController {
return null; return null;
} }
@RequestMapping("/literature") // 互动文艺 // @PostMapping("/literature") // 互动文艺
public String literature() { public String literature() {
try { try {
//log.info("--------------分界线-------------------"); //log.info("--------------分界线-------------------");
...@@ -89,7 +141,12 @@ public class XiaoDuHomeController { ...@@ -89,7 +141,12 @@ public class XiaoDuHomeController {
return null; return null;
} }
@RequestMapping("/smart") // 智能故事 @RequestMapping(value = "/smart", method = RequestMethod.HEAD)
public void smartHead(HttpServletResponse response) {
response.setStatus(200);
}
@PostMapping("/smart") // 智能故事
public String smart() { public String smart() {
try { try {
//log.info("--------------分界线-------------------"); //log.info("--------------分界线-------------------");
...@@ -98,17 +155,22 @@ public class XiaoDuHomeController { ...@@ -98,17 +155,22 @@ public class XiaoDuHomeController {
// log.info(service.getStrRequest()); // log.info(service.getStrRequest());
//service.disableVerify(); //service.disableVerify();
service.enableVerify(); service.enableVerify();
String str = service.run(); // log.info("响应信息:{}", str);
// log.info("响应信息:{}", str); return service.run();
return str; } catch (MismatchedInputException ex) {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("smart:"+e);
//log.error("出现错误 "+e.toString()); //log.error("出现错误 "+e.toString());
} }
return null; return null;
} }
@RequestMapping("/novel") // 智能小说 @RequestMapping(value = "/novel", method = RequestMethod.HEAD)
public void novelHead(HttpServletResponse response) {
response.setStatus(200);
}
@PostMapping("/novel") // 智能小说
public String novel() { public String novel() {
try { try {
//log.info("--------------分界线-------------------"); //log.info("--------------分界线-------------------");
...@@ -117,11 +179,11 @@ public class XiaoDuHomeController { ...@@ -117,11 +179,11 @@ public class XiaoDuHomeController {
// log.info(service.getStrRequest()); // log.info(service.getStrRequest());
//service.disableVerify(); //service.disableVerify();
service.enableVerify(); service.enableVerify();
String str = service.run(); // log.info("响应信息:{}", str);
// log.info("响应信息:{}", str); return service.run();
return str; } catch (MismatchedInputException ex) {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("novel:"+e);
//log.error("出现错误 "+e.toString()); //log.error("出现错误 "+e.toString());
} }
return null; return null;
......
...@@ -31,6 +31,9 @@ public class GameProjectTb { ...@@ -31,6 +31,9 @@ public class GameProjectTb {
@Column @Column
private Long watch; private Long watch;
// @Column(name = "work_type")
// private Long workType;
@Column(name = "banner_img_url") @Column(name = "banner_img_url")
private String bannerImgUrl; private String bannerImgUrl;
......
...@@ -35,6 +35,9 @@ public class OnProductDetail { ...@@ -35,6 +35,9 @@ public class OnProductDetail {
@Column @Column
private Float score; private Float score;
@Column(name = "work_type")
private Long workType;
@Column(name = "banner_img_url") @Column(name = "banner_img_url")
private String bannerImgUrl; private String bannerImgUrl;
......
...@@ -20,5 +20,5 @@ import java.util.Map; ...@@ -20,5 +20,5 @@ import java.util.Map;
public class OverTimeDetail { public class OverTimeDetail {
private final List<Directive> directives = new ArrayList<>(); private final List<Directive> directives = new ArrayList<>();
private final Map<String, String> attributes = new HashMap<>(); private final Map<String, String> attributes = new HashMap<>();
private Response response = new Response(); private volatile Response response = new Response();
} }
...@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.repository.primary; ...@@ -2,6 +2,7 @@ package ai.qiwu.com.xiaoduhome.repository.primary;
import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail; import ai.qiwu.com.xiaoduhome.entity.primary.OnProductDetail;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
...@@ -14,4 +15,9 @@ import java.util.List; ...@@ -14,4 +15,9 @@ import java.util.List;
public interface AllOnProductInfoRepository extends JpaRepository<OnProductDetail, Long> { public interface AllOnProductInfoRepository extends JpaRepository<OnProductDetail, Long> {
List<OnProductDetail> findAllByApplyStatusAndScoreNot(Integer applyStatus, Float score); List<OnProductDetail> findAllByApplyStatusAndScoreNot(Integer applyStatus, Float score);
List<OnProductDetail> findAllByApplyStatusAndWorkType(Integer applyStatus, Long workType);
@Query(value = "select name from game_project_tb where apply_status=1 and work_type=27",nativeQuery = true)
List<String> findNameByApplyStatusAndWorkType(Integer applyStatus, Long workType);
} }
...@@ -29,6 +29,6 @@ public interface GameProjectTbRepository extends JpaRepository<GameProjectTb, Lo ...@@ -29,6 +29,6 @@ public interface GameProjectTbRepository extends JpaRepository<GameProjectTb, Lo
@Query(value = "select id,intro,name,watch,banner_img_url,apply_status,bot_account,user_nickname,score from game_project_tb where apply_status = 1 order by watch desc limit ?1,8", nativeQuery = true) @Query(value = "select id,intro,name,watch,banner_img_url,apply_status,bot_account,user_nickname,score from game_project_tb where apply_status = 1 order by watch desc limit ?1,8", nativeQuery = true)
List<GameProjectTb> postRankBot(Integer begin); List<GameProjectTb> postRankBot(Integer begin);
@Query(value = "select bot_account from game_project_tb where apply_status=1",nativeQuery = true) @Query(value = "select bot_account from game_project_tb where apply_status=1 and work_type=27",nativeQuery = true)
List<String> getAllOnTableProductIds(); List<String> getAllOnTableProductIds();
} }
...@@ -7,12 +7,20 @@ import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest; ...@@ -7,12 +7,20 @@ import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest;
import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse; import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse;
import ai.qiwu.com.xiaoduhome.pojo.playAside.AsideImageResponse; import ai.qiwu.com.xiaoduhome.pojo.playAside.AsideImageResponse;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest; import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Random; import java.util.Random;
...@@ -23,7 +31,7 @@ import java.util.Random; ...@@ -23,7 +31,7 @@ import java.util.Random;
@Slf4j @Slf4j
class RequestTerminal { class RequestTerminal {
static String requestTerminateTemp(String userWord, String userId, int type) throws IOException { static String requestTerminateTemp(String userWord, String userId, String channel) throws IOException {
SpiritTerminateRequest requestPojo = new SpiritTerminateRequest(); SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
requestPojo.setMsg(userWord); requestPojo.setMsg(userWord);
...@@ -31,14 +39,33 @@ class RequestTerminal { ...@@ -31,14 +39,33 @@ class RequestTerminal {
// log.info("向小悟发送的请求信息:{}", requestJsonStr); // log.info("向小悟发送的请求信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8"); headers.put("Content-Type", "application/json;charset=utf-8");
switch (type) { headers.put("App-Channel-Id", channel);
case 1 : // String ip = Utils.getRemoteIpByServletRequest(request);
case 3 : headers.put("App-Channel-Id", "jiaoyou-audio-child-test");break; // if (StringUtils.isNotBlank(ip)) {
case 2 : // headers.put("ip", ip);
case 4 : headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");break; // if (test++ < 5) {
default: headers.put("App-Channel-Id", "jiaoyou-audio-test"); // try {
} // Enumeration enumeration = request.getHeaderNames();
// while (enumeration.hasMoreElements()) {
// String name = (String) enumeration.nextElement();
// log.info(name+":"+request.getHeader(name));
// }
// } catch (Exception e) {
// log.warn("failed:"+e);
// }
// }
// } else {
// log.warn("ip is null");
// }
// switch (type) {
// case 1 :
// case 3 : headers.put("App-Channel-Id", "jiaoyou-audio-child-test");break;
// case 2 :
// case 4 : headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");break;
// default: headers.put("App-Channel-Id", "jiaoyou-audio-test");
// }
return OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, requestJsonStr, headers); return OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, requestJsonStr, headers);
// return OkHttp3Utils.doPostJsonStr("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, headers);
} }
static QiWuResponse requestTerminate(String userWord, String userId, int type) throws IOException { static QiWuResponse requestTerminate(String userWord, String userId, int type) throws IOException {
...@@ -86,11 +113,11 @@ class RequestTerminal { ...@@ -86,11 +113,11 @@ class RequestTerminal {
} }
static void backRequest(String userId, int type) { static void backRequest(String userId, int type) {
QiWuRequest requestPojo = new QiWuRequest(); SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME); requestPojo.setMsg("退出");
requestPojo.setMsg("退出当前作品");
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
// OkHttp3Utils.backPostAsync("http://didi-gz5.jiaoyou365.com:8070/api/chat2", requestJsonStr, type);
OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr, type); OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr, type);
} }
......
...@@ -26,6 +26,7 @@ import org.springframework.beans.factory.InitializingBean; ...@@ -26,6 +26,7 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
...@@ -77,6 +78,13 @@ public class ScheduleService implements InitializingBean { ...@@ -77,6 +78,13 @@ public class ScheduleService implements InitializingBean {
public static volatile Map<String, String> channelId2RecommendBotAcc = new HashMap<>(); public static volatile Map<String, String> channelId2RecommendBotAcc = new HashMap<>();
public static volatile Map<String, List<String>> channel2Bots = new HashMap<>();
public static volatile Map<String, List<String>> jiaoyouChannel2Bots = new HashMap<>();
// public static volatile String STORY_WELCOME_WORD = "欢迎来到晓悟智能故事频道。与可爱的角色们自由对话,畅游不同的故事世界。我们新上线的遇见伽利略,你可以说打开遇见伽利略。或者说,推荐其它作品。";// 智能故事
// public static volatile String NOVEL_WELCOME_WORD = "欢迎来到晓悟智能小说频道。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";// 智能小说
// public static volatile String JIAOYOU_WELCOME_WORD = "欢迎来到晓悟智能小说频道。与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";// 智能小说
@Autowired @Autowired
public ScheduleService(GameProjectTbRepository gameProjectTbRepository, public ScheduleService(GameProjectTbRepository gameProjectTbRepository,
ProjectLabelRepository projectLabelRepository, ProjectLabelRepository projectLabelRepository,
...@@ -90,6 +98,14 @@ public class ScheduleService implements InitializingBean { ...@@ -90,6 +98,14 @@ public class ScheduleService implements InitializingBean {
this.xiaoDuOrderTbRepository = xiaoDuOrderTbRepository; this.xiaoDuOrderTbRepository = xiaoDuOrderTbRepository;
} }
// @Scheduled(cron = "* */10 * * * ?")
// public void updateTheWelcomeName() {
// DplbotServiceUtil.POOL.submit(() -> {
// List<OnProductDetail> onlinedProject = allOnProductInfoRepository.findAllByApplyStatusAndWorkType(1,27L);
//
// });
// }
@Scheduled(cron = "0 */30 * * * ?") @Scheduled(cron = "0 */30 * * * ?")
public void cleatUserBehaviorData() { public void cleatUserBehaviorData() {
DplbotServiceUtil.POOL.submit(() -> { DplbotServiceUtil.POOL.submit(() -> {
...@@ -126,7 +142,7 @@ public class ScheduleService implements InitializingBean { ...@@ -126,7 +142,7 @@ public class ScheduleService implements InitializingBean {
}); });
} }
@Scheduled(cron = "*/10 * * * * ?") // @Scheduled(cron = "*/10 * * * * ?")
public void updateTheCurTime() { public void updateTheCurTime() {
DplbotServiceUtil.POOL.submit(() -> curTime = System.currentTimeMillis()); DplbotServiceUtil.POOL.submit(() -> curTime = System.currentTimeMillis());
} }
...@@ -141,7 +157,7 @@ public class ScheduleService implements InitializingBean { ...@@ -141,7 +157,7 @@ public class ScheduleService implements InitializingBean {
//log.error("更新排行榜出错:{}", e.getMessage()); //log.error("更新排行榜出错:{}", e.getMessage());
} }
@Scheduled(cron = "0 0 */1 * * ?") @Scheduled(cron = "0 0 */2 * * ?")
public void initRecommendList() { public void initRecommendList() {
new Thread(() -> { new Thread(() -> {
RECOMMEND_LIST = gameProjectTbRepository.recommendList(); RECOMMEND_LIST = gameProjectTbRepository.recommendList();
...@@ -216,22 +232,21 @@ public class ScheduleService implements InitializingBean { ...@@ -216,22 +232,21 @@ public class ScheduleService implements InitializingBean {
}).start(); }).start();
} }
@Scheduled(cron = "0 0 */1 * * ?") // @Scheduled(cron = "0 0 */1 * * ?")
public void shuffleAllProList() { public void shuffleAllProList() {
new Thread(() -> { new Thread(() -> {
Collections.shuffle(ALL_ON_PRODUCT); Collections.shuffle(ALL_ON_PRODUCT);
}).start(); }).start();
} }
@Scheduled(cron = "0 */30 * * * ?") // @Scheduled(cron = "0 */20 * * * ?")
public void getAllChannelRecommendBotAccount() { public void getAllChannelRecommendBotAccount() {
String response = null; String response = null;
int count = 1; int count = 1;
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
do { do {
try { try {
Thread.sleep(count*5); response = OkHttp3Utils.doGet("http://didi-gz3.jiaoyou365.com:8070/api/sdk/botConfig/all");
response = OkHttp3Utils.doGet("http://didi-gz4.jiaoyou365.com:8070/api/sdk/botConfig/all");
JSONArray array = JSONObject.parseArray(response); JSONArray array = JSONObject.parseArray(response);
if (array != null) { if (array != null) {
for (Object o: array) { for (Object o: array) {
...@@ -244,13 +259,74 @@ public class ScheduleService implements InitializingBean { ...@@ -244,13 +259,74 @@ public class ScheduleService implements InitializingBean {
} catch (Exception e) { } catch (Exception e) {
log.error("getAllChannelRecommendBotAccount:{}",e); log.error("getAllChannelRecommendBotAccount:{}",e);
} }
if (StringUtils.isBlank(response)) log.warn("第"+count+"次获取channelId失败"); if (StringUtils.isBlank(response)) {
try {
Thread.sleep(count*5);
} catch (Exception e) {}
log.warn("第"+count+"次获取channelId失败");
}
count++; count++;
} while (StringUtils.isBlank(response) && count < 5); } while (StringUtils.isBlank(response) && count < 5);
if (map.size() != 0) { if (map.size() != 0) {
channelId2RecommendBotAcc = map; channelId2RecommendBotAcc = map;
log.error("audio channelId list:"+map);
} }
log.info("channelId2RecommendBotAcc:"+channelId2RecommendBotAcc);
}
@Scheduled(cron = "0 */30 * * * ?")
public void getChannelAllBots() {
String response;
JSONObject jsonObject;
int count = 1;
boolean success = false;
do {
try {
response = OkHttp3Utils.doGet("http://didi-gz3.jiaoyou365.com:18082/api/data/audio/list");
jsonObject = JSON.parseObject(response).getJSONObject("data");
Map<String, List<String>> map = jsonObject.toJavaObject(Map.class);
if (map != null && map.size() != 0) {
channel2Bots = map;
success = true;
} else {
log.info("getChannelAllBots failed count="+count);
Thread.sleep(count*5);
}
} catch (Exception e) {
log.warn("getChannelAllBots: "+e);
}
count++;
} while (!success && count < 5);
log.info("getChannelAllBots:"+channel2Bots);
}
@Scheduled(cron = "0 */30 * * * ?")
public void getJiaoYouChannelRecordBots() {
String response;
JSONObject jsonObject;
int count = 1;
boolean success = false;
do {
try {
response = OkHttp3Utils.doGet("http://didi-gz3.jiaoyou365.com:18082/api/data/audio/list/jiaoyou");
jsonObject = JSON.parseObject(response).getJSONObject("data");
Map<String, List<String>> map = jsonObject.toJavaObject(Map.class);
if (map != null && map.size() != 0) {
List<String> jiaoyouList = map.get("jiaoyou-audio-adult-test");
if (!CollectionUtils.isEmpty(jiaoyouList)) map.get("jiaoyou-audio-adult-test").add("遇见伽利略");
List<String> xiaoaiJiaoyouList = map.get("xiaoai-jiaoyou-audio-adult-test");
if (!CollectionUtils.isEmpty(xiaoaiJiaoyouList)) map.get("xiaoai-jiaoyou-audio-adult-test").add("遇见伽利略");
jiaoyouChannel2Bots = map;
success = true;
} else {
log.info("getChannelAllBots failed count="+count);
Thread.sleep(count*5);
}
} catch (Exception e) {
log.warn("getChannelAllBots: "+e);
}
count++;
} while (!success && count < 5);
log.info("getChannelAllBots:"+jiaoyouChannel2Bots);
} }
private void getAsideImg() { private void getAsideImg() {
...@@ -260,7 +336,7 @@ public class ScheduleService implements InitializingBean { ...@@ -260,7 +336,7 @@ public class ScheduleService implements InitializingBean {
for (String botId: botIds) { for (String botId: botIds) {
try { try {
HashMap<String, String> params = new HashMap<>(); HashMap<String, String> params = new HashMap<>();
params.put("include", "npcHeadImgUrl"); params.put("include", "audioNpc");
params.put("aipioneerUsername",botId); params.put("aipioneerUsername",botId);
String str = OkHttp3Utils.doGet(ASIDE_IMG_URL, params); String str = OkHttp3Utils.doGet(ASIDE_IMG_URL, params);
AsideImageResponse response = JSON.parseObject(str, AsideImageResponse.class); AsideImageResponse response = JSON.parseObject(str, AsideImageResponse.class);
...@@ -281,8 +357,11 @@ public class ScheduleService implements InitializingBean { ...@@ -281,8 +357,11 @@ public class ScheduleService implements InitializingBean {
initProductList(); initProductList();
deleteOverTimeHistory(); deleteOverTimeHistory();
deleteUnPayedOrder(); deleteUnPayedOrder();
tian(); // tian();
getAsideImg(); getAsideImg();
getAllChannelRecommendBotAccount();
getChannelAllBots();
getJiaoYouChannelRecordBots();
} }
private void tian(){ private void tian(){
......
package ai.qiwu.com.xiaoduhome.service.chatsLog;
import ai.qiwu.com.xiaoduhome.controller.WebSocketLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author 苗权威
* @dateTime 19-12-30 上午10:59
*/
@Service
@Slf4j
public class ChatLogs {
private static final String PATH = "/root/programsCN/chats.log";
public String look(Integer row, String typeCount, String type) {
if (row == null || row == 0) row = 1000;
try {
LogResponse response = readLastRows(PATH, StandardCharsets.UTF_8, row);
if (StringUtils.isNotBlank(response.getData())) {
StringBuilder builder = new StringBuilder("<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n" +
" <title>Title</title>\n" +
"</head>\n" +
"<body>");
// StringBuilder builder = new StringBuilder();
if (StringUtils.isNotBlank(type)) {
if (StringUtils.isBlank(typeCount)) typeCount = "100";
int count = Integer.parseInt(typeCount);
String[] arrTest = response.getData().split("\n\n");
List<String> list = Arrays.stream(arrTest).filter(s1 -> s1.contains(type))
.map(s1 -> {
String[] arr = s1.split("\n");
return Arrays.stream(arr).map(s -> "<span>"+s+"</span><br>").collect(Collectors.joining(""));
// return StringUtils.join(arr, "");
}).collect(Collectors.toList());
Collections.reverse(list);
List<String> result = new ArrayList<>(list);
int recur = 0;
while (result.size() < count && response.getIndex() > 0 && recur < 200) {
response = readLastRowsWithIndex(PATH, StandardCharsets.UTF_8, response.getIndex(), 800);
arrTest = response.getData().split("\n\n");
list = Arrays.stream(arrTest).filter(s1 -> s1.contains(type)).map(s -> {
String[] arr = s.split("\n");
return Arrays.stream(arr).map(s1 -> "<span>"+ s1 +"</span><br>").collect(Collectors.joining(""));
}).collect(Collectors.toList());
if (list.size() != 0) {
Collections.reverse(list);
result.addAll(list);
}
recur++;
}
result.forEach(s -> builder.append("<span>").append(s).append("</span><br>"));
} else {
String[] arr = response.getData().split("\n");
List<String> list = Arrays.asList(arr);
Collections.reverse(list);
list.forEach(s -> builder.append("<span>").append(s).append("</span><br>"));
// Arrays.stream(arr).forEach(s1 -> builder.append("<span>").append(s1).append("</span><br>"));
}
builder.append("</body>\n" +
"</html>");
return builder.toString();
// List<String> list = Arrays.stream(arr).map(s1 -> "<span>"+s1+"</span><br>").collect(Collectors.toList());
// s = StringUtils.join(list, "");
}
// s = s.replaceAll("\\{/.*/}", "");
// WebSocketLog.sendInfo(s, "chat");
} catch (Exception e) {
log.error("ChatLogs:"+e.toString());
}
return null;
}
private static LogResponse readLastRows(String filename, Charset charset, int rows) throws IOException {
charset = charset == null ? Charset.defaultCharset() : charset;
String lineSeparator = System.getProperty("line.separator");
try (RandomAccessFile rf = new RandomAccessFile(filename, "r")) {
// 每次读取的字节数要和系统换行符大小一致
byte[] c = new byte[lineSeparator.getBytes().length];
// 在获取到指定行数和读完文档之前,从文档末尾向前移动指针,遍历文档每一个字节
for (long pointer = rf.length(), lineSeparatorNum = 0; pointer >= 0; rf.seek(pointer--)) {
// 移动指针
rf.seek(pointer);
// 读取数据
int readLength = rf.read(c);
if (readLength != -1 && new String(c, 0, readLength).equals(lineSeparator) && ++lineSeparatorNum == rows) {
// 找到足够数量换行符则退出循环
break;
}
}
LogResponse response = new LogResponse();
long index = rf.getFilePointer();
response.setIndex(index);
byte[] tempbytes = new byte[(int) (rf.length() - index)];
rf.readFully(tempbytes);
response.setData(new String(tempbytes, charset));
return response;
}
}
private static LogResponse readLastRowsWithIndex(String filename, Charset charset, long start, int rows) throws IOException {
charset = charset == null ? Charset.defaultCharset() : charset;
String lineSeparator = System.getProperty("line.separator");
try (RandomAccessFile rf = new RandomAccessFile(filename, "r")) {
// 每次读取的字节数要和系统换行符大小一致
byte[] c = new byte[lineSeparator.getBytes().length];
// 在获取到指定行数和读完文档之前,从文档末尾向前移动指针,遍历文档每一个字节
for (long pointer = start, lineSeparatorNum = 0; pointer >= 0; rf.seek(pointer--)) {
// 移动指针
rf.seek(pointer);
// 读取数据
int readLength = rf.read(c);
if (readLength != -1 && new String(c, 0, readLength).equals(lineSeparator) && ++lineSeparatorNum == rows) {
// 找到足够数量换行符则退出循环
break;
}
}
LogResponse response = new LogResponse();
long index = rf.getFilePointer();
response.setIndex(index);
byte[] tempbytes = new byte[(int) (start-index)];
rf.readFully(tempbytes);
response.setData(new String(tempbytes, charset));
return response;
}
}
}
package ai.qiwu.com.xiaoduhome.service.chatsLog;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-12-30 下午4:53
*/
@Getter
@Setter
public class LogResponse {
private String data;
private Long index;
}
package ai.qiwu.com.xiaoduhome.service.chatsLog;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-12-30 下午3:15
*/
@Getter
@Setter
public class LoginData {
private String username;
private String passwd;
private Long time;
private String token;
}
...@@ -60,7 +60,7 @@ public class InitialData implements InitializingBean { ...@@ -60,7 +60,7 @@ public class InitialData implements InitializingBean {
} }
Map<String, Map<String, String>> npcName2nameId = recordMap.computeIfAbsent(botAccount, s -> new HashMap<>()); Map<String, Map<String, String>> npcName2nameId = recordMap.computeIfAbsent(botAccount, s -> new HashMap<>());
int j = 0; int j = 0;
// "person", "mood", "md5", "id", "text", "upUrl" // "person", "mood", "md5", "id", "upUrl"
for (CSVRecord line: reader) { for (CSVRecord line: reader) {
if (j == 0) { if (j == 0) {
j++; j++;
......
...@@ -72,7 +72,7 @@ public class SpiritService { ...@@ -72,7 +72,7 @@ public class SpiritService {
} }
} }
String userWord = request.getUtterance(); String userWord = request.getUtterance();
log.info("天猫精灵用户说的话:"+userWord); // log.info("天猫精灵用户说的话:"+userWord);
try { try {
Future<TaskResult> future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId)); Future<TaskResult> future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId));
return future.get(1700, TimeUnit.MILLISECONDS); return future.get(1700, TimeUnit.MILLISECONDS);
...@@ -95,19 +95,20 @@ public class SpiritService { ...@@ -95,19 +95,20 @@ public class SpiritService {
//log.info("向终端发出请求的参数信息:{}", requestJsonStr); //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8"); headers.put("Content-Type", "application/json;charset=utf-8");
String channelId = "jiaoyou-audio-test"; String channelId;
switch (type) { switch (type) {
case 2: case 2:
case 4: channelId = "jiaoyou-audio-child-test";break; case 4: channelId = "tianmao-jiaoyou-audio-child-test";break;
case 3: case 3:
case 5: channelId= "jiaoyou-audio-adult-test";break; case 5: channelId= "tianmao-jiaoyou-audio-adult-test";break;
default: channelId = "tianmao-jiaoyou-audio-test";
} }
headers.put("App-Channel-Id", channelId); headers.put("App-Channel-Id", channelId);
String resStr= OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI2, requestJsonStr, headers);; String resStr= OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);;
if (resStr == null) { if (resStr == null) {
return null; return null;
} }
log.info("天猫精灵晓悟返回:"+resStr); // log.info("天猫精灵晓悟返回:"+resStr);
TaskResult taskResult = null; TaskResult taskResult = null;
try { try {
final SpiritTerminateResponse response = JSON.parseObject(resStr, SpiritTerminateResponse.class); final SpiritTerminateResponse response = JSON.parseObject(resStr, SpiritTerminateResponse.class);
......
...@@ -26,13 +26,13 @@ public class RequestTerminal { ...@@ -26,13 +26,13 @@ public class RequestTerminal {
static { static {
ALL_HEADERS = new HashMap<>(); ALL_HEADERS = new HashMap<>();
ALL_HEADERS.put("Content-Type", "application/json;charset=utf-8"); ALL_HEADERS.put("Content-Type", "application/json;charset=utf-8");
ALL_HEADERS.put("App-Channel-Id", "jiaoyou-audio-test"); ALL_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-test");
CHILD_HEADERS = new HashMap<>(); CHILD_HEADERS = new HashMap<>();
CHILD_HEADERS.put("Content-Type", "application/json;charset=utf-8"); CHILD_HEADERS.put("Content-Type", "application/json;charset=utf-8");
CHILD_HEADERS.put("App-Channel-Id", "jiaoyou-audio-child-test"); CHILD_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-child-test");
ADULT_HEADERS = new HashMap<>(); ADULT_HEADERS = new HashMap<>();
ADULT_HEADERS.put("Content-Type", "application/json;charset=utf-8"); ADULT_HEADERS.put("Content-Type", "application/json;charset=utf-8");
ADULT_HEADERS.put("App-Channel-Id", "jiaoyou-audio-adult-test"); ADULT_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-adult-test");
} }
/** /**
...@@ -49,18 +49,17 @@ public class RequestTerminal { ...@@ -49,18 +49,17 @@ public class RequestTerminal {
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
//log.info("向终端发出请求的参数信息:{}", requestJsonStr); //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap<String, String> headers; HashMap<String, String> headers;
if (type != null) { switch (type) {
if ((type & 1) == 1) headers = CHILD_HEADERS; case 1: headers = CHILD_HEADERS; break;
else headers = ADULT_HEADERS; case 2: headers = ADULT_HEADERS; break;
} else { default: headers = ALL_HEADERS; break;
headers = ALL_HEADERS;
}
String resStr;
if (userId.equals(XiaoAiService.deviceId)) {
resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_nx2, requestJsonStr, headers);
}else {
resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
} }
String resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);;
// if (userId.equals(XiaoAiService.deviceId)) {
// resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
// }else {
// resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
// }
return resStr; return resStr;
} }
...@@ -69,10 +68,11 @@ public class RequestTerminal { ...@@ -69,10 +68,11 @@ public class RequestTerminal {
requestPojo.setUid(userId); requestPojo.setUid(userId);
requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD); requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD);
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
if (userId.equals(XiaoAiService.deviceId)) { OkHttp3Utils.xiaoaiBackPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type); // if (userId.equals(XiaoAiService.deviceId)) {
}else { // OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_nx2, requestJsonStr, type); // }else {
} // OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
// }
} }
} }
package ai.qiwu.com.xiaoduhome.xiaoai.common; package ai.qiwu.com.xiaoduhome.xiaoai.common;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects; import java.util.Objects;
/** /**
...@@ -11,12 +20,15 @@ import java.util.Objects; ...@@ -11,12 +20,15 @@ import java.util.Objects;
* @author 苗权威 * @author 苗权威
* @dateTime 19-7-6 上午11:16 * @dateTime 19-7-6 上午11:16
*/ */
@Slf4j
public class Utils { public class Utils {
/** /**
* 代表空格,斜杠,单引号,双引号,tab键 * 代表空格,斜杠,单引号,双引号,tab键
*/ */
private static final String STRIP = " /'\"\\t"; private static final String STRIP = " /'\"\\t+";
// public static final String NUM_OR_ALPHA = "[^0-9a-zA-Z]";
/** /**
* 获取HttpServletRequest对象 * 获取HttpServletRequest对象
...@@ -60,4 +72,82 @@ public class Utils { ...@@ -60,4 +72,82 @@ public class Utils {
} }
return builder.toString(); return builder.toString();
} }
public static boolean encry(Integer type, HttpServletRequest request) {
String host = "didi-gz4.jiaoyou365.com";
String xiaomiDate = request.getHeader("x-xiaomi-date");
String md5 = request.getHeader("content-md5");
if (StringUtils.isBlank(md5)) md5 = "";
String contentType = request.getHeader("content-type");
String authorization = request.getHeader("authorization");
if (StringUtils.isAnyBlank(xiaomiDate, contentType, authorization)) return false;
String secret, urlPath, keyId;
switch (type) {
case 1: {
secret = XiaoAiConstants.SECURITY.SMART_STORY_SECRET;
keyId = XiaoAiConstants.SECURITY.SMART_STORY_KEYID;
urlPath = "/xiaoai/child";
break;
}
case 2:{
secret = XiaoAiConstants.SECURITY.SMART_NOVEL_SECRET;
keyId = XiaoAiConstants.SECURITY.SMART_NOVEL_KEYID;
urlPath = "/xiaoai/adult";
break;
}
case 3:{
secret = "Q+TOpok4Dy/CMCXgHE6HFNrmdImYoJmRQlAGx7LkI54=";
keyId = "zOQuywFuKjlhbTMr4dHwFA==";
urlPath = "/xiaoaiTest/story";
break;
}
case 4:{
secret = "AaBr41l9jrPFir3c0tVdjl+nnwtMC6xcM4b/ua/MspA=";
keyId = "8eQZnL/YfA783qd/LOY0pw==";
urlPath = "/xiaoaiTest/story";
break;
}
default:{
secret = XiaoAiConstants.SECURITY.SMART_JIAOYOU_SECRET;
keyId = XiaoAiConstants.SECURITY.SMART_JIAOYOU_KEYID;
urlPath = "/xiaoai/";
break;
}
}
String algorithmForMac = "HmacSHA256";
String method = "POST";
String param = "";
String source = new StringBuilder().append(method).append('\n').append(urlPath).append('\n').append(param).append('\n')
.append(xiaomiDate).append('\n').append(host).append('\n')
.append(contentType).append('\n').append(md5).append('\n').toString();
try {
Mac mac = Mac.getInstance(algorithmForMac);
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.decodeBase64(secret), algorithmForMac);
mac.init(secretKeySpec);
// String signature = Hex.encodeHexString(mac.doFinal(source.getBytes(StandardCharsets.UTF_8)));
String signature = new StringBuilder("MIAI-HmacSHA256-V1 ").append(keyId).append("::")
.append(Hex.encodeHexString(mac.doFinal(source.getBytes(StandardCharsets.UTF_8)))).toString();
return signature.equals(authorization);
// boolean result = signature.equals(authorization);
// log.info("signature:{}, compare:{}",signature, result);
// return result;
} catch (Exception e) {
log.error("encry:"+e);
}
return false;
}
public static void main(String[] args) throws UnsupportedEncodingException {
// SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
// sdf3.setTimeZone(TimeZone.getTimeZone("GMT"));
// String rfc1123_3 = sdf3.format(new Date(System.currentTimeMillis()-100000));
// System.out.println("rfc1123_3 = "+rfc1123_3);
// System.out.println(new Date(System.currentTimeMillis()));
String s = URLEncoder.encode("+Ls69sFTjXN/6//831N1V==Vdfw", "UTF-8");
// System.out.println(s);
System.out.println("+Ls69sFTjXN/683//1N1V==Vdfw".replaceAll("/", ""));
System.out.println(URLEncoder.encode("sgagsgdg", "UTF-8"));
System.out.println(URLEncoder.encode("123467845131", "UTF-8"));
}
} }
...@@ -10,6 +10,7 @@ public interface XiaoAiConstants { ...@@ -10,6 +10,7 @@ public interface XiaoAiConstants {
String QI_WU_TERMINATE_DIDI2 = "http://didi-gz2.jiaoyou365.com:8070/api/chat2"; String QI_WU_TERMINATE_DIDI2 = "http://didi-gz2.jiaoyou365.com:8070/api/chat2";
String QI_WU_TERMINATE_nx2 = "http://didi-gz4.jiaoyou365.com:8070/api/chat2"; String QI_WU_TERMINATE_nx2 = "http://didi-gz4.jiaoyou365.com:8070/api/chat2";
String TTS_DIDI3 = "http://didi-gz3.jiaoyou365.com:9663/api/audio"; String TTS_DIDI3 = "http://didi-gz3.jiaoyou365.com:9663/api/audio";
String TTS_DIDI2 = "http://didi-gz2.jiaoyou365.com:9663/api/audio";
String TTS_DIDI4 = "http://didi-gz4.jiaoyou365.com:9663/api/audio"; String TTS_DIDI4 = "http://didi-gz4.jiaoyou365.com:9663/api/audio";
String DEVICE_NAME = "XIAOAI"; String DEVICE_NAME = "XIAOAI";
String CONTENT_TYPE = "application/json;charset=utf-8"; String CONTENT_TYPE = "application/json;charset=utf-8";
...@@ -30,6 +31,7 @@ public interface XiaoAiConstants { ...@@ -30,6 +31,7 @@ public interface XiaoAiConstants {
String WELCOME_WORD_CHILD_STORY = "小朋友你好,欢迎来到互动故事,你可以说推荐作品给我"; String WELCOME_WORD_CHILD_STORY = "小朋友你好,欢迎来到互动故事,你可以说推荐作品给我";
String WELCOME_WORD_Adult = "你好,欢迎来到智能小说,你可以说推荐作品给我"; String WELCOME_WORD_Adult = "你好,欢迎来到智能小说,你可以说推荐作品给我";
String WELCOME_WORD_Adult_literature = "你好,欢迎来到互动文艺,你可以说推荐作品给我"; String WELCOME_WORD_Adult_literature = "你好,欢迎来到互动文艺,你可以说推荐作品给我";
String WELCOME_WORD_DEFAULT = "欢迎来到我们的技能,与剧情人物自由对话,带您体验不同的人生和情怀。向您推荐新上线的求生记,您可以说打开求生记。或者说,推荐其它作品。";
String END_BYE = "我们的作品库在不断扩充,欢迎再来玩"; String END_BYE = "我们的作品库在不断扩充,欢迎再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦"; String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_BYE_Adult = "再见啦,记得下次再来玩哦"; String END_BYE_Adult = "再见啦,记得下次再来玩哦";
...@@ -41,4 +43,13 @@ public interface XiaoAiConstants { ...@@ -41,4 +43,13 @@ public interface XiaoAiConstants {
String WAIT_WORD_2 = "由于网络的原因,您可能需要稍稍等等"; String WAIT_WORD_2 = "由于网络的原因,您可能需要稍稍等等";
String WAIT_WORD_3 = "由于网络原因小悟正在加倍努力获取结果,不过您现在得快些对我说些什么,要不然您就退出我们的技能了"; String WAIT_WORD_3 = "由于网络原因小悟正在加倍努力获取结果,不过您现在得快些对我说些什么,要不然您就退出我们的技能了";
} }
interface SECURITY {
String SMART_STORY_SECRET = "J03wDvFuUtr0lgBAm628aSNZiC0haluC/yXe90//Z7M=";
String SMART_STORY_KEYID = "5hlvswxeP9J1Ths0+fL9vQ==";
String SMART_NOVEL_SECRET = "IeVTzSD1wHDSoboQhqQFTHJgB28Wr/HtxkgkL5HLmmY=";
String SMART_NOVEL_KEYID = "RrNYDL7DeNgKZGAW/KC6Iw==";
String SMART_JIAOYOU_SECRET = "kkluiypsxYwGzLej+ZAHoo/ec0gnoOsBdr8uzmBn1+M=";
String SMART_JIAOYOU_KEYID = "BDLeaCyRlF7wI8Wvb/RjwA==";
}
} }
package ai.qiwu.com.xiaoduhome.xiaoai.model.request.innerRequest; package ai.qiwu.com.xiaoduhome.xiaoai.model.request.innerRequest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
...@@ -11,8 +12,9 @@ import lombok.ToString; ...@@ -11,8 +12,9 @@ import lombok.ToString;
@Getter @Getter
@Setter @Setter
@ToString @ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Request { public class Request {
private int type; private Integer type;
private String request_id; private String request_id;
private Long timestamp; private Long timestamp;
private Boolean no_response; private Boolean no_response;
...@@ -20,4 +22,6 @@ public class Request { ...@@ -20,4 +22,6 @@ public class Request {
private EventProperty event_property; private EventProperty event_property;
private String Locale; private String Locale;
private SlotInfo slot_info; private SlotInfo slot_info;
private Boolean is_monitor;
} }
package ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toDisplay;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 20-1-7 下午8:34
*/
@Getter
@Setter
@ToString
public class PhoneTemplate {
private String template_name;
private Map<String, String> params;
}
...@@ -17,4 +17,7 @@ public class ToDisplay { ...@@ -17,4 +17,7 @@ public class ToDisplay {
private String url; private String url;
private String text; private String text;
private UITemplate ui_template; private UITemplate ui_template;
private String ui_type;
private PhoneTemplate phone_template;
} }
server: server:
port: 8188 port: 8188
tomcat:
# accesslog:
# enabled: true
# pattern: '%h %l %u %t "%r" %s %b bytes %D ms'
# directory: /home/dc2-user/projects/audiobox/duai/tomcat
max-threads: 1024
spring: spring:
datasource: datasource:
...@@ -10,11 +16,13 @@ spring: ...@@ -10,11 +16,13 @@ spring:
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
secondary: secondary:
jdbc-url: jdbc:mysql://localhost:3306/audiobox?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false jdbc-url: jdbc:mysql://localhost:3306/audiobox?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
# jdbc-url: jdbc:mysql://localhost:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root username: root
password: 38A0O1jEPOE password: 38A0O1jEPOE
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
analysis: analysis:
jdbc-url: jdbc:mysql://localhost:3306/analysis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false jdbc-url: jdbc:mysql://localhost:3306/analysis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
# jdbc-url: jdbc:mysql://localhost:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root username: root
password: 38A0O1jEPOE password: 38A0O1jEPOE
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
...@@ -27,6 +35,8 @@ spring: ...@@ -27,6 +35,8 @@ spring:
output: output:
ansi: ansi:
enabled: detect enabled: detect
thymeleaf:
cache: false
logging: logging:
path: /home/dc2-user/projects/audiobox/duai/logs path: /home/dc2-user/projects/audiobox/duai/logs
level: level:
......
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>对话日志</title>
<script type="text/javascript">
function getToken() {
var token = document.getElementById("tokens").value;
var type = document.getElementById("type").value;
var typeCount = document.getElementById("typeCount").value;
var row = document.getElementById("row").value;
var ajaxObj = new XMLHttpRequest();
console.log(token+":"+type+":"+typeCount+":"+row);
ajaxObj.open('get', '/chat/log?token='+token+'&row='+row+'&count='+typeCount+'&type='+type);
ajaxObj.send();
ajaxObj.onreadystatechange = function () {
if (ajaxObj.readyState === 4 && ajaxObj.status === 200) {
}
}
}
</script>
</head>
<body>
<div>
<label>
<select id="type">
<option value="jiaoyou-audio">音箱</option>
</select>
</label>
<input type="text" id="tokens" th:hidden="true" th:default="${token}"/>
<input type="text" id="typeCount" class="countC" placeholder="请输入所要显示的类型的个数"/>
<input type="text" id="row" class="rowC" placeholder="请输入所要显示的行数"/>
<input type="button" id="search" class="click" value="点击搜索" onclick="getToken()"/>
</div>
<div>
<span th:text="${data}"></span>
</div>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>CHAT LOG</title>
<link rel="stylesheet" type="text/css" th:href="@{/layui.css}">
</head>
<body>
<div class="mainbox">
<p></p>
<div class="subbox">
<p>显示全部日志:</p>
<input type="text" id="row" class="input" placeholder="请输入所要显示的行数,默认1000行"/>
<button type="button" class="layui-btn button " id="one" onclick="getAllToken()">点击搜索</button>
</div>
<div class="subbox">
<p>显示指定类型的日志:</p>
<label>
<select id="type" style="height: 60px; width: 80px;">
<option value="jiaoyou-audio">音箱</option>
<option value="jiaoyou-audio-adult">音箱-成人</option>
<option value="jiaoyou-audio-child">音箱-儿童</option>
<option value="XIAODU_">小度</option>
<option value="XIAOAI_">小爱</option>
</select>
</label>
<!--<input type="text" id="tokens" th:hidden="true" th:default="${token}"/>-->
<input type="text" id="typeCount" class="input" placeholder="请输入所要显示的类型的个数,默认100个"/>
<!--<input type="button" id="search" class="click" value="点击搜索" onclick="getToken()"/>-->
<button type="button" class="layui-btn button " id="two" onclick="getToken()">点击搜索</button>
</div>
</div>
</body>
<style>
.mainbox{
width: 900px;
height: 200px;
margin: 100px auto;
display: flex;
flex-direction: column;
}
.subbox{
width: 900px;
height: 200px;
margin: 100px auto;
display: flex;
flex-direction: row;
}
.input{
width: 500px;
}
button{
flex: 1;
}
</style>
<script th:inline="javascript">
var token = [[${token}]];
function getToken() {
var type = document.getElementById("type").value;
var typeCount = document.getElementById("typeCount").value;
console.log(token+":"+type+":"+typeCount);
window.location.href = "http://didi-gz3.jiaoyou365.com:8188/chat/log?token=" +token+'&count='+typeCount+'&type='+type;
}
function getAllToken() {
var row = document.getElementById("row").value;
window.location.href = "http://didi-gz3.jiaoyou365.com:8188/chat/log?token=" +token+'&row='+row;
}
</script>
</html>
\ No newline at end of file
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Title</title> <title>登录</title>
</head> </head>
<body> <body>
<span>登录失败,请返回</span> <span>登录失败,请返回</span>
......
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>对话日志</title>
<!--<link rel="stylesheet" href="../static/layui.css">-->
<!--<script src="./static/vue.js"></script>-->
<link rel="stylesheet" type="text/css" th:href="@{/layui.css}">
<script th:src="@{/vue.js}"></script>
</head>
<body>
<div id="app">
<div class="mainbox" id="mainbox" >
<!--<div v-for="item in datalist">-->
<div>
<!--<p class=" one_tack ai">{{item.text}}</p>-->
<p class=" one_tack ai">{{text}}</p>
<!-- <p class="one_tack self">{{item.self}}</p> -->
</div>
<p id="text"></p>
</div>
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
datalist: [],
text:"",
},
methods: {
},
mounted: function () {
let that = this;
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
socket = new WebSocket("ws://didi-gz3.jiaoyou365.com:8188/webSocket/chat"); //小度
//打开事件
socket.onopen = function () {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
// console.log(msg.data);
this.text+=msg.data;
var div = document.getElementById('mainbox');
var text = document.getElementById('text');
text.innerHTML=this.text;
div.scrollTop = div.scrollHeight;
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
}
})
</script>
<style>
.mainbox {
width: 1300px;
height: auto;
border: 1px solid black;
display: flex;
flex-direction: column;
margin: 100px auto;
padding: 20px;
}
.ai {
color: green;
}
.one_tack {
margin-top: 10;
}
</style>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>对话日志</title>
<!--<link rel="stylesheet" href="../static/layui.css">-->
<!--<script src="./static/vue.js"></script>-->
<link rel="stylesheet" type="text/css" th:href="@{/layui.css}">
<script th:src="@{/vue.js}"></script>
</head>
<body>
<div id="app">
<div class="mainbox" id="mainbox" >
<!--<div v-for="item in datalist">-->
<div>
<!--<p class=" one_tack ai">{{item.text}}</p>-->
<p class=" one_tack ai">{{text}}</p>
<!-- <p class="one_tack self">{{item.self}}</p> -->
</div>
<p id="text"></p>
</div>
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
datalist: [],
text:"",
},
methods: {
},
mounted: function () {
let that = this;
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
// socket = new WebSocket("${basePath}webSocket/${username}".replace("https","ws"));
// socket = new WebSocket("ws://didi-gz4.jiaoyou365.com:8188/webSocket/du"); //小度
// socket = new WebSocket("ws://didi-gz4.jiaoyou365.com:8188/webSocket/aigz3"); //小度
socket = new WebSocket("ws://didi-gz3.jiaoyou365.com:8188/webSocket/chat"); //小度
//打开事件
socket.onopen = function () {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
// console.log(msg.data);
this.text=msg.data;
// let text2=
// console.log(this.text,"11111");
// let obj = {
// ai: "",
// self: ""
// };
//
// let arr = msg.data.split("/");
// obj.ai = arr[0];
// obj.self = arr[1];
// that.datalist.push(msg.data);
// that.datalist.push(obj);
var div = document.getElementById('mainbox');
var text = document.getElementById('text');
text.innerHTML=msg.data;
div.scrollTop = div.scrollHeight;
// console.log(msg.data);
// console.log(this.alldata);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
}
})
</script>
<style>
.mainbox {
width: 1300px;
height: auto;
border: 1px solid black;
display: flex;
flex-direction: column;
margin: 100px auto;
padding: 20px;
}
.ai {
color: green;
}
.one_tack {
margin-top: 10;
}
</style>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>查看日志登录</title>
<script type="text/javascript">
function getToken() {
var phoneNum = document.getElementById("phoneNum").value;
var captcha = document.getElementById("getCaptcha").value;
// alert("phone:"+phoneNum+",captcha:"+captcha);
var ajaxObj = new XMLHttpRequest();
//var uri = '/xiaodu/security/token?phoneNumber='+phoneNum+'&captcha='+captcha;
ajaxObj.open('get', '/chat/login/check?userName='+phoneNum+'&passwd='+captcha);
ajaxObj.send();
ajaxObj.onreadystatechange = function () {
if (ajaxObj.readyState === 4 && ajaxObj.status === 200) {
if (ajaxObj.responseText.length === 8) {
window.location.href = "http://didi-gz3.jiaoyou365.com:8188/chat/choose?token=" + ajaxObj.responseText;
}
}
}
}
</script>
<style type="text/css">
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #eee;
margin:0;
}
.container {
width: 80%;
padding-left: 15px;
padding-right: 15px;
margin-right: auto;
margin-left: auto;
}
.whole {
text-align: center;
padding: 10px;
margin: 0 auto;
}
.title {
margin-top: 20px;
margin-bottom: 10px;
font-size: 26px;
}
.input {
margin-bottom: -1px;
border-radius: 4px;
height: auto;
width: 88%;
padding: 10px;
font-size: 16px;
color: #555;
background-color: #fff;
border:1px solid #ccc;
}
.click {
display: block;
font-size: 16px;
border-radius: 4px;
color: #fff;
background-color: #337ab7;
padding: 6px 12px;
font-weight: 400;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
border: 1px solid transparent;
margin:10px auto;
width: 96%;
}
</style>
</head>
<body>
<div class="container">
<div class="whole" id="captchaView">
<h2 class="title">CHAT日志</h2>
<input type="text" id="phoneNum" name="phone" class="input" placeholder="请输入用户名"/>
</div>
<div class="whole" id="tokenView">
<input type="password" id="getCaptcha" name="phone" class="input" placeholder="请输入密码"/>
<input type="button" id="toLoad" name="to_load" class="click" value="点击登录" onclick="getToken()"/>
</div>
</div>
</body>
</html>
\ No newline at end of file
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
<button type="button" class="layui-btn button " id="four">小度2号 (gz3)</button> <button type="button" class="layui-btn button " id="four">小度2号 (gz3)</button>
<button type="button" class="layui-btn button " id="tow">小爱1号(gz3)</button> <button type="button" class="layui-btn button " id="tow">小爱1号(gz3)</button>
<button type="button" class="layui-btn button " id="therr">小爱2号(gz3)</button> <button type="button" class="layui-btn button " id="therr">小爱2号(gz3)</button>
<button type="button" class="layui-btn button " id="five">对话日志</button>
</div> </div>
</body> </body>
<style> <style>
...@@ -34,6 +35,7 @@ ...@@ -34,6 +35,7 @@
var tow = document.getElementById("tow"); var tow = document.getElementById("tow");
var therr = document.getElementById("therr"); var therr = document.getElementById("therr");
var four = document.getElementById("four"); var four = document.getElementById("four");
var five = document.getElementById("five");
one.onclick = function(){ one.onclick = function(){
console.log("点击事件"); console.log("点击事件");
...@@ -53,7 +55,10 @@ ...@@ -53,7 +55,10 @@
four.onclick = function(){ four.onclick = function(){
console.log("点击事件"); console.log("点击事件");
window.open("./Log4.html","_blank"); window.open("./Log4.html","_blank");
};
five.onclick = function () {
console.log("点击事件");
window.open("./Log5.html","_blank");
} }
</script> </script>
</html> </html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment