diff --git a/.idea/compiler.xml b/.idea/compiler.xml index a6f6f49..1cbf3a5 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -7,20 +7,26 @@ + - + + + + + + - + diff --git a/.idea/encodings.xml b/.idea/encodings.xml index 70dc759..3a6f015 100644 --- a/.idea/encodings.xml +++ b/.idea/encodings.xml @@ -1,7 +1,10 @@ + + + diff --git a/.idea/misc.xml b/.idea/misc.xml index a6496e7..8b0269f 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,14 @@ + + + + + + + + @@ -11,6 +19,8 @@ + + diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 8dce11d..4c2638e 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -1,7 +1,33 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -10,86 +36,71 @@ + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - + - - - - - + + - + - - + + - - - - - - - - - - - - - - - + + - + - - - - - - + + - + - - + + @@ -108,39 +119,73 @@ response + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -151,17 +196,19 @@ - - - + + + + + + - @@ -172,25 +219,25 @@ - + - + - + - + @@ -198,27 +245,18 @@ - + - - - - - - - - - - - + + @@ -228,9 +266,31 @@ - + + + + + + + + + + + + + + + + + + + + + + + @@ -244,8 +304,8 @@ - - + + @@ -275,6 +335,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -282,6 +402,20 @@ + + + + + + + + + + + + + + @@ -318,13 +452,17 @@ - + + + + + @@ -341,506 +479,595 @@ - + + + + + + + + + - + - + - + - - - + + + - - + + - + - + - - - + + + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - + + + + + - - + + - + + + + - - - - - - + + - + + + + - - + + - + - - - - - - - - + + - + - - - - - + + - + - - + + - + - - + + - + + - + - - - - - + + - + - - + + - + - - + + - + - - + + - + - + - + - - + + - + - - - - - + + - + - - - - - - - + + - + - - + + - + - - + + - + - - - - - - + + - + - - + + - + - - + + - - + - - - - - - - - + - - + + - - + - + - - - - - - - - - + + - - + - + - - + + - - + - + - - - - - - - - - + + + + + - + - - + + + + + - + - - + + - + - - + + + + + - + - - + + + + + - + - - + + - + - - + + + + + - + - - + + - + - - + + + + + - + - - + + + + + - + - - + + + + + - + - - + + + + + - + - - + + - - + - + - - + + - - + - + - - + + + + + - + - - + + + + + - + - - + + + + + - + - - + + - + - - + + - + - - - - - + + - + - - + + - + - - + + - + - - + + - - - - + + + - + - - - - - - + + + + + + RokidBox:war + + + + + + + + + + + + + Spring + + + + + + + + + + + + + + + + + + + + + + + 1.8 + + + + + + + + + + + + RokidBox + + + + + + + + + 1.8 @@ -853,6 +1080,18 @@ + + + Maven: aopalliance:aopalliance:1.0 + + + + + + + + + \ No newline at end of file diff --git a/dingdong/pom.xml b/dingdong/pom.xml index 3a07b64..318d4d6 100644 --- a/dingdong/pom.xml +++ b/dingdong/pom.xml @@ -11,6 +11,7 @@ ai.qiwu.dong dingdong 0.0.1-SNAPSHOT + war dingdong Demo project for Spring Boot @@ -22,6 +23,19 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + javax.servlet + javax.servlet-api + LATEST + provided @@ -50,6 +64,7 @@ + dingdong org.springframework.boot diff --git a/dingdong/src/main/java/ai/qiwu/dong/dingdong/DingdongApplication.java b/dingdong/src/main/java/ai/qiwu/dong/dingdong/DingdongApplication.java index b4c3faa..2a2a45c 100644 --- a/dingdong/src/main/java/ai/qiwu/dong/dingdong/DingdongApplication.java +++ b/dingdong/src/main/java/ai/qiwu/dong/dingdong/DingdongApplication.java @@ -2,12 +2,18 @@ package ai.qiwu.dong.dingdong; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication -public class DingdongApplication { +public class DingdongApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(DingdongApplication.class, args); } + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(DingdongApplication.class); + } } diff --git a/dingdong/src/main/java/ai/qiwu/dong/dingdong/common/Constants.java b/dingdong/src/main/java/ai/qiwu/dong/dingdong/common/Constants.java index d148754..af710c1 100644 --- a/dingdong/src/main/java/ai/qiwu/dong/dingdong/common/Constants.java +++ b/dingdong/src/main/java/ai/qiwu/dong/dingdong/common/Constants.java @@ -27,6 +27,7 @@ public interface Constants { String RECOMMEND = "recommend"; String START_BY_ANSWER = "startByAnswer"; String END_BY_END = "endByEnd"; + String ALL = "all"; } interface Status { diff --git a/dingdong/src/main/java/ai/qiwu/dong/dingdong/common/Holder.java b/dingdong/src/main/java/ai/qiwu/dong/dingdong/common/Holder.java new file mode 100644 index 0000000..616c721 --- /dev/null +++ b/dingdong/src/main/java/ai/qiwu/dong/dingdong/common/Holder.java @@ -0,0 +1,15 @@ +package ai.qiwu.dong.dingdong.common; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-7-2 下午2:22 + */ +@Getter +@Setter +public class Holder { + private volatile String word; + private volatile String lastAudioUrl; +} diff --git a/dingdong/src/main/java/ai/qiwu/dong/dingdong/controller/DingDongController.java b/dingdong/src/main/java/ai/qiwu/dong/dingdong/controller/DingDongController.java index 7833bcc..31a7d95 100644 --- a/dingdong/src/main/java/ai/qiwu/dong/dingdong/controller/DingDongController.java +++ b/dingdong/src/main/java/ai/qiwu/dong/dingdong/controller/DingDongController.java @@ -18,16 +18,16 @@ public class DingDongController { private static final Logger logger = LoggerFactory.getLogger(ParseService.class); -// @Autowired -// private ParseServiceCompromise compromise; - @Autowired - private ParseService parseService; + private ParseServiceCompromise compromise; + +// @Autowired +// private ParseService parseService; @RequestMapping("/ding") public @ResponseBody DingDongResponse dingdong(@RequestBody DingDongRequest request) { logger.info("Request params : "+ request); - return parseService.getResponse(request); + return compromise.getResponse(request); } @RequestMapping("/ding/callback") diff --git a/dingdong/src/main/java/ai/qiwu/dong/dingdong/service/ParseServiceCompromise.java b/dingdong/src/main/java/ai/qiwu/dong/dingdong/service/ParseServiceCompromise.java index 78683bc..5176c57 100644 --- a/dingdong/src/main/java/ai/qiwu/dong/dingdong/service/ParseServiceCompromise.java +++ b/dingdong/src/main/java/ai/qiwu/dong/dingdong/service/ParseServiceCompromise.java @@ -3,6 +3,7 @@ package ai.qiwu.dong.dingdong.service; import ai.qiwu.dong.dingdong.common.Constants; import ai.qiwu.dong.dingdong.common.Constants.Intent; import ai.qiwu.dong.dingdong.common.Constants.Status; +import ai.qiwu.dong.dingdong.common.Holder; import ai.qiwu.dong.dingdong.model.request.DingDongRequest; import ai.qiwu.dong.dingdong.model.request.user.User; import ai.qiwu.dong.dingdong.model.response.DingDongResponse; @@ -23,6 +24,7 @@ import org.springframework.stereotype.Service; import java.io.IOException; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; /** * @author 苗权威 @@ -33,6 +35,8 @@ public class ParseServiceCompromise { private final static Logger logger = LoggerFactory.getLogger(ParseServiceCompromise.class); + private final static ConcurrentHashMap USER_LAST_ALL_WORD_AudioUrl = new ConcurrentHashMap<>(); + public DingDongResponse getResponse(DingDongRequest request) { String userId = null; User user = request.getUser(); @@ -127,10 +131,11 @@ public class ParseServiceCompromise { } switch (intentKey) { - case Intent.END_BY_END : return parseWordInItsIntent(request, false, true, userId); - case Intent.XIAO_WU : return parseWordInItsIntent(request, true, true, userId); + case Intent.END_BY_END : return parseWordInItsIntent(request, false, true, userId); + case Intent.XIAO_WU : return parseWordInItsIntent(request, true, true, userId); case Intent.START_BY_ANSWER : return parseWordInItsIntent(request, true, true, userId); - case Intent.RECOMMEND : return parseWordInItsIntent(request, false, false, userId); + case Intent.RECOMMEND : return parseWordInItsIntent(request, true, false, userId); + case Intent.ALL : return parseWordInItsIntent(request, false, false, userId); default: { logger.info("没有匹配到任何已有意图,本次请求的意图名:"+intentKey); return buildErrorResponse(request, userId); @@ -141,14 +146,17 @@ public class ParseServiceCompromise { else if (slots.size() <= 1) { logger.info("slots不为null,但是没有映射到任何意图"); return buildErrorResponse(request, userId); + } else if (slots.size() == 3 && slots.containsKey(Intent.RECOMMEND)) { + return requestQiWuInterface(userId, request); } else { - logger.info("Intent请求slots大小>=3,预料之外"); + logger.info("Intent请求slots大小>3,或是等于3但是没有recommend意图,预料之外"); return buildErrorResponse(request, userId); } } private DingDongResponse parseWordInItsIntent(DingDongRequest request, boolean font, boolean needToCut, String userId) { String word = request.getInput_text(); + Holder holder = USER_LAST_ALL_WORD_AudioUrl.get(userId); DingDongResponse response; if (needToCut) { if (font) { @@ -171,8 +179,40 @@ public class ParseServiceCompromise { } } } + // 处理ALL意图 + else if (!font) { + if (holder != null && word.equals(holder.getWord())) { + logger.info("本次ALL意图的话语与上次相同,认定是用户说的话"); + } else { + if (holder == null) { + holder = new Holder(); + USER_LAST_ALL_WORD_AudioUrl.put(userId, holder); + } + holder.setWord(word); + DingDongResponse forbidResponse; + if (holder.getLastAudioUrl() != null) { + logger.info("本次ALL意图的话语与上次不同,重复播放上次音频"); + forbidResponse = buildResponse(request, userId); + forbidResponse.getDirective().getDirective_items().get(0).setContent(holder.getLastAudioUrl()); + } else { + logger.info("本次ALL意图的话语与上次不同,提醒用户再说一遍"); + forbidResponse = buildErrorResponse(request, userId); + } + return forbidResponse; + } + + } logger.info("此次解析得到的用户的话是:"+word); response = requestQiWuInterface(userId, request); + + String audioUrl = response.getDirective().getDirective_items().get(0).getContent(); + if (holder == null) { + holder = new Holder(); + holder.setLastAudioUrl(audioUrl); + USER_LAST_ALL_WORD_AudioUrl.put(userId, holder); + } else { + holder.setLastAudioUrl(audioUrl); + } return response; } @@ -210,11 +250,6 @@ public class ParseServiceCompromise { } private DingDongResponse dealLaunchIntent(DingDongRequest request, String userId) { - Map slots = request.getSlots(); - if (slots.containsKey(Intent.RECOMMEND)) { - request.setInput_text("推荐作品"); - return requestQiWuInterface(userId, request); - } DingDongResponse launchResponse = buildErrorResponse(request, userId); launchResponse.getDirective().getDirective_items().get(0).setContent("欢迎,这里有海量的作品,希望您玩的开心"); return launchResponse; @@ -230,6 +265,8 @@ public class ParseServiceCompromise { case Constants.DEV_SERVICE_RESP_PACK_ERROR: logger.info("status为NOTICE:开发者服务回包数据错误");break; case Constants.NOTICE_OPEN_PLATFORM_ERROR: logger.info("status为NOTICE:开放平台系统异常");break; } + + if (USER_LAST_ALL_WORD_AudioUrl.remove(userId) != null) logger.info("非正常结束,平台发出NOTICE信息,在此处删除缓存成功"); return buildErrorResponse(request, userId); } @@ -248,6 +285,8 @@ public class ParseServiceCompromise { } DingDongResponse response = buildErrorResponse(request, userId); response.getDirective().getDirective_items().get(0).setContent("我们的作品库在不断扩充,欢迎下次再来玩"); + + if (USER_LAST_ALL_WORD_AudioUrl.remove(userId) != null) logger.info("平台发出END信息,代表技能退出,在此处删除缓存成功"); return response; } } diff --git a/dingdong/src/main/resources/application.properties b/dingdong/src/main/resources/application.properties index 14933cd..8b13789 100644 --- a/dingdong/src/main/resources/application.properties +++ b/dingdong/src/main/resources/application.properties @@ -1 +1 @@ -server.port=8383 + diff --git a/dingdong/src/main/resources/logback.xml b/dingdong/src/main/resources/logback.xml new file mode 100644 index 0000000..bcd38ac --- /dev/null +++ b/dingdong/src/main/resources/logback.xml @@ -0,0 +1,42 @@ + + + + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + + + + + + + + /usr/mqw/logs/dingdong/ + + + /usr/mqw/logs/dingdong/base.log.%d.%i + + 64 MB + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + \ No newline at end of file diff --git a/jdwhale/.gitignore b/jdwhale/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/jdwhale/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/jdwhale/.mvn/wrapper/MavenWrapperDownloader.java b/jdwhale/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..7f91a56 --- /dev/null +++ b/jdwhale/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/jdwhale/.mvn/wrapper/maven-wrapper.jar b/jdwhale/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/jdwhale/.mvn/wrapper/maven-wrapper.jar differ diff --git a/jdwhale/.mvn/wrapper/maven-wrapper.properties b/jdwhale/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..cd0d451 --- /dev/null +++ b/jdwhale/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/jdwhale/mvnw b/jdwhale/mvnw new file mode 100755 index 0000000..8b9da3b --- /dev/null +++ b/jdwhale/mvnw @@ -0,0 +1,286 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/jdwhale/mvnw.cmd b/jdwhale/mvnw.cmd new file mode 100644 index 0000000..fef5a8f --- /dev/null +++ b/jdwhale/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/jdwhale/pom.xml b/jdwhale/pom.xml new file mode 100644 index 0000000..20d716c --- /dev/null +++ b/jdwhale/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + ai.qiwu.mqw + jdwhale + 0.0.1-SNAPSHOT + war + jdwhale + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + javax.servlet + javax.servlet-api + LATEST + provided + + + org.apache.httpcomponents + httpclient + 4.5.8 + + + com.alibaba + fastjson + 1.2.58 + + + + org.projectlombok + lombok + 1.18.8 + provided + + + + + JDWhale + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/JdwhaleApplication.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/JdwhaleApplication.java new file mode 100644 index 0000000..aa444ff --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/JdwhaleApplication.java @@ -0,0 +1,19 @@ +package ai.qiwu.mqw.jdwhale; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class JdwhaleApplication extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(JdwhaleApplication.class, args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(JdwhaleApplication.class); + } +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/common/Constants.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/common/Constants.java new file mode 100644 index 0000000..7d7683c --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/common/Constants.java @@ -0,0 +1,12 @@ +package ai.qiwu.mqw.jdwhale.common; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午5:57 + */ +public interface Constants { + String QI_WU_INTERFACE = "http://aliyun-hz1.chewrobot.com:8070/api/chat"; + String SERVICE_NAME = "DINGDONG"; + String CANCEL_INTENT = "Alpha.CancelIntent"; + String HELP_INTENT = "Alpha.HelpIntent"; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/common/MqwLru.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/common/MqwLru.java new file mode 100644 index 0000000..d48ca66 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/common/MqwLru.java @@ -0,0 +1,90 @@ +package ai.qiwu.mqw.jdwhale.common; + +import java.util.concurrent.locks.ReentrantLock; + +/** + * @author 苗权威 + * @dateTime 19-6-26 下午2:59 + */ +public class MqwLru { + + private static final int DEFAULT_SINGLE_SEGMENT_ENTRYS = 100; + + private static final float DEFAULT_LOAD_FACTOR = 0.75f; + + private static final int DEFAULT_SEGMENT_ARRAY_LENGTH = 16; + + private static final int MAXIMUM_CAPACITY = 1 << 30; + + private static final int MAX_SEGMENT_ARRAY_LENGTH = 1 << 16; + + final Segment[] segments; + + public MqwLru(int arrCapacity, int loadFactor, int segementCapacity) { + int arrayLength = tableSizeFor(arrCapacity); + this.segments = new Segment[arrayLength]; + for (int i = 0; i < arrayLength; i++) { + segments[i] = new Segment(segementCapacity, loadFactor); + } + } + + private static int tableSizeFor(int cap) { + int n = cap - 1; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; + } + + private static int hash(int h) { + h += (h << 15) ^ 0xffffcd7d; + h ^= (h >>> 10); + h += (h << 3); + h ^= (h >>> 6); + h += (h << 2) + (h << 14); + return h ^ (h >>> 16); + } + + static final class Entry { + final K key; + volatile V value; + final int hash; + Entry doubleLinkedBefore; + Entry doubleLinkedAfter; + + Entry(K key, V value, int hash) { + this.key = key; + this.value = value; + this.hash = hash; + } + } + + static final class Segment extends ReentrantLock { + volatile int count; + int threshold; + final float loadFactor; + final int maxCapacity; + volatile Entry header; + volatile Entry tail; + + Segment(int segmentCapacity, float loadFactor) { + this.maxCapacity = segmentCapacity; + this.loadFactor = loadFactor; + this.threshold = (int) (maxCapacity*loadFactor); + } + + V put(K key, V value, int hash) { + lock(); + try { + int c = count; + //if (c++ >= threshold) rehash(); + + } finally { + unlock(); + } + return null; + } + } +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/controller/DingDongController.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/controller/DingDongController.java new file mode 100644 index 0000000..98d93ba --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/controller/DingDongController.java @@ -0,0 +1,31 @@ +package ai.qiwu.mqw.jdwhale.controller; + +import ai.qiwu.mqw.jdwhale.model.RequestModel.DingDongRequest; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.DingDongResponse; +import ai.qiwu.mqw.jdwhale.service.ParseServiceWithoutLRU; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:51 + */ +@RestController +public class DingDongController { + private static final Logger logger = LoggerFactory.getLogger(DingDongController.class); + + @Autowired + private ParseServiceWithoutLRU serviceWithoutLRU; + + @RequestMapping("/dingdong") + public @ResponseBody + DingDongResponse dingdong(@RequestBody DingDongRequest request) { + logger.info("Request params: "+request); + return serviceWithoutLRU.getResponse(request); + } +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/DingDongRequest.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/DingDongRequest.java new file mode 100644 index 0000000..866b16b --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/DingDongRequest.java @@ -0,0 +1,20 @@ +package ai.qiwu.mqw.jdwhale.model.RequestModel; + +import ai.qiwu.mqw.jdwhale.model.RequestModel.request.TripleRequest; +import ai.qiwu.mqw.jdwhale.model.RequestModel.session.DingDongSession; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:30 + */ +@Getter +@Setter +@ToString +public class DingDongRequest { + private String version; + private DingDongSession session; + private TripleRequest request; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/IntentRequestIntent.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/IntentRequestIntent.java new file mode 100644 index 0000000..2f2a4a6 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/IntentRequestIntent.java @@ -0,0 +1,20 @@ +package ai.qiwu.mqw.jdwhale.model.RequestModel.request; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:45 + */ +@Getter +@Setter +@ToString +public class IntentRequestIntent { + private String name; + private String confirmResult; + private Map map; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/IntentRequestSlot.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/IntentRequestSlot.java new file mode 100644 index 0000000..6922f07 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/IntentRequestSlot.java @@ -0,0 +1,17 @@ +package ai.qiwu.mqw.jdwhale.model.RequestModel.request; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:46 + */ +@Getter +@Setter +public class IntentRequestSlot { + private String name; + private String value; + private boolean matched; + private String confirmResult; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/SessionEndRequestReason.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/SessionEndRequestReason.java new file mode 100644 index 0000000..0df7932 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/SessionEndRequestReason.java @@ -0,0 +1,17 @@ +package ai.qiwu.mqw.jdwhale.model.RequestModel.request; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:49 + */ +@Getter +@Setter +@ToString +public class SessionEndRequestReason { + private String type; + private String message; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/TripleRequest.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/TripleRequest.java new file mode 100644 index 0000000..ba4a476 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/request/TripleRequest.java @@ -0,0 +1,22 @@ +package ai.qiwu.mqw.jdwhale.model.RequestModel.request; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:43 + */ +@Getter +@Setter +@ToString +public class TripleRequest { + private String type; + private String requestId; + private Long timestamp; + private String dialogState; + private IntentRequestIntent intent; + private String original; + private SessionEndRequestReason reason; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/DingDongSession.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/DingDongSession.java new file mode 100644 index 0000000..8d984eb --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/DingDongSession.java @@ -0,0 +1,21 @@ +package ai.qiwu.mqw.jdwhale.model.RequestModel.session; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:31 + */ +@Getter +@Setter +@ToString +public class DingDongSession { + private boolean isNew; + private String sessionId; + private Object contexts; + private SessionApp application; + private SessionUser user; + private SessionDevice device; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/SessionApp.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/SessionApp.java new file mode 100644 index 0000000..5e84a2d --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/SessionApp.java @@ -0,0 +1,16 @@ +package ai.qiwu.mqw.jdwhale.model.RequestModel.session; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:33 + */ +@Getter +@Setter +@ToString +public class SessionApp { + private String applicationId; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/SessionDevice.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/SessionDevice.java new file mode 100644 index 0000000..581457a --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/SessionDevice.java @@ -0,0 +1,16 @@ +package ai.qiwu.mqw.jdwhale.model.RequestModel.session; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:36 + */ +@Getter +@Setter +@ToString +public class SessionDevice { + private String deviceId; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/SessionUser.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/SessionUser.java new file mode 100644 index 0000000..a4f65d3 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/RequestModel/session/SessionUser.java @@ -0,0 +1,17 @@ +package ai.qiwu.mqw.jdwhale.model.RequestModel.session; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:34 + */ +@Getter +@Setter +@ToString +public class SessionUser { + private String userId; + private String accessToken; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/DingDongResponse.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/DingDongResponse.java new file mode 100644 index 0000000..38ea983 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/DingDongResponse.java @@ -0,0 +1,23 @@ +package ai.qiwu.mqw.jdwhale.model.ResponseModel; + +import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioPlayerDirective; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.OutputResponse; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; +import java.util.Map; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:52 + */ +@Getter +@Setter +public class DingDongResponse { + private String version; + private boolean shouldEndSession; + private Map contexts; + private OutputResponse response; + private List directives; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/directives/audio/AudioPlayerDirective.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/directives/audio/AudioPlayerDirective.java new file mode 100644 index 0000000..835f37f --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/directives/audio/AudioPlayerDirective.java @@ -0,0 +1,16 @@ +package ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午5:08 + */ +@Getter +@Setter +public class AudioPlayerDirective { + private String type; + private String playBehavior; + private AudioStream audioStream; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/directives/audio/AudioStream.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/directives/audio/AudioStream.java new file mode 100644 index 0000000..693659a --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/directives/audio/AudioStream.java @@ -0,0 +1,17 @@ +package ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午5:10 + */ +@Getter +@Setter +public class AudioStream { + private String name; + private String url; + private String token; + private Long offsetInMilliseconds; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/response/Output.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/response/Output.java new file mode 100644 index 0000000..1174382 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/response/Output.java @@ -0,0 +1,15 @@ +package ai.qiwu.mqw.jdwhale.model.ResponseModel.response; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:58 + */ +@Getter +@Setter +public class Output { + private String type; + private String text; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/response/OutputResponse.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/response/OutputResponse.java new file mode 100644 index 0000000..73e117e --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/response/OutputResponse.java @@ -0,0 +1,15 @@ +package ai.qiwu.mqw.jdwhale.model.ResponseModel.response; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:57 + */ +@Getter +@Setter +public class OutputResponse { + private Output output; + private Reprompt reprompt; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/response/Reprompt.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/response/Reprompt.java new file mode 100644 index 0000000..38f92c7 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/model/ResponseModel/response/Reprompt.java @@ -0,0 +1,15 @@ +package ai.qiwu.mqw.jdwhale.model.ResponseModel.response; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午4:59 + */ +@Getter +@Setter +public class Reprompt { + private String type; + private String text; +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/service/ParseService.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/service/ParseService.java new file mode 100644 index 0000000..28b9894 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/service/ParseService.java @@ -0,0 +1,181 @@ +package ai.qiwu.mqw.jdwhale.service; + +import ai.qiwu.mqw.jdwhale.common.Constants; +import ai.qiwu.mqw.jdwhale.model.RequestModel.DingDongRequest; +import ai.qiwu.mqw.jdwhale.model.RequestModel.request.TripleRequest; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.DingDongResponse; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioPlayerDirective; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioStream; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.Output; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.OutputResponse; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.Reprompt; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午5:13 + */ +@Service("service") +public class ParseService { + private static final Logger logger = LoggerFactory.getLogger(ParseService.class); + + private static final ConcurrentHashMap userResponseMap = new ConcurrentHashMap<>(); + + public DingDongResponse getResponse(DingDongRequest request) { + String userId = request.getSession().getUser().getUserId(); + if (userId == null) userId = request.getSession().getApplication().getApplicationId(); + TripleRequest unknowRequest = request.getRequest(); + switch (unknowRequest.getType()) { + case "LaunchRequest": return dealLaunchRequest(); + case "IntentRequest": return dealIntentRequest(unknowRequest, userId); + case "SessionEndedRequest": dealSessionEndedRequest(unknowRequest, userId); return null; + default: logger.info("ERROR DIRECTIVE"); return dealLaunchRequest(); + } + } + + private DingDongResponse dealLaunchRequest() { + DingDongResponse response = new DingDongResponse(); + buildResponse(response); + response.getResponse().getOutput().setText("欢迎来到有声互动小说,请说推荐作品"); + response.getResponse().getReprompt().setText("请说推荐作品"); + return response; + } + + private DingDongResponse dealIntentRequest(TripleRequest request, String userId) { + // 处理Alpha.CancelIntent意图,该意图是平台默认的意图,用户说退出则退出技能, + // 我们这里需要对该意图进行判断处理. + // "request": { + // "dialogState": "STARTED", + // "intent": { + // "name": "Alpha.CancelIntent" + // }, + // "requestId": "42d7d9f2-4134-4979-82fc-44dafe408171_6006_test", + // "timestamp": 1561510754347, + // "type": "IntentRequest" + // }, + if (Constants.CANCEL_INTENT.equals(request.getIntent().getName())) { + dealSessionEndedRequest(request, userId); + return null; + } + if (Constants.HELP_INTENT.equals(request.getIntent().getName())) { + DingDongResponse response = new DingDongResponse(); + buildResponse(response); + response.getResponse().setReprompt(null); + response.getResponse().getOutput().setText("请明确一些说帮或不帮"); + return response; + } + DingDongResponse response = userResponseMap.get(userId); + if (response == null) { + response = buildResponseTemplate(); + userResponseMap.put(userId, response); + } + String userWord = request.getOriginal(); + requestQiWuInterface(userId, userWord, response); + return response; + } + + private void dealSessionEndedRequest(TripleRequest request, String userId) { + DingDongResponse response = userResponseMap.remove(userId); + logger.info("用户:"+userId+" 的缓存删除成功, " + response); + } + + private void requestQiWuInterface(String userId, String userWord, DingDongResponse response) { + String audioUrl = ""; + String textContent = "请说推荐作品"; + CloseableHttpClient httpClient = null; + CloseableHttpResponse httpResponse = null; + try { + httpClient = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE); + + HashMap params = new HashMap<>(); + params.put("user_id", String.valueOf(userId)); + params.put("text", userWord); + params.put("access",Constants.SERVICE_NAME); + + String paramsJsonFormat = JSON.toJSONString(params); + StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8"); + post.setHeader("Content-Type", "application/json;charset=utf-8"); + post.setEntity(body); + + httpResponse = httpClient.execute(post); + HttpEntity responseBody = httpResponse.getEntity(); + if (responseBody != null) { + String responseContent = EntityUtils.toString(responseBody); + logger.info("齐悟接口返回: "+ responseContent); + JSONObject responseJsonFormat = JSONObject.parseObject(responseContent); + audioUrl = (String) responseJsonFormat.get("audio"); + textContent = (String) responseJsonFormat.get("text"); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (httpClient != null) httpClient.close(); + if (httpResponse != null) httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + addUrlAndTextToResponse(audioUrl, textContent, response); + } + + private void addUrlAndTextToResponse(String url, String text, DingDongResponse response) { + //response.getResponse().getOutput().setText(text); + response.getDirectives().get(0).getAudioStream().setUrl(url); + } + + private DingDongResponse buildResponseTemplate() { + DingDongResponse response = new DingDongResponse(); + response.setVersion("1.0"); + response.setShouldEndSession(true); + buildDirectives(response); + return response; + } + + private void buildResponse(DingDongResponse response) { + response.setShouldEndSession(true); + response.setVersion("1.0"); + + OutputResponse outResponse = new OutputResponse(); + Output output = new Output(); + output.setType("PlainText"); + outResponse.setOutput(output); + Reprompt reprompt = new Reprompt(); + reprompt.setType("PlainText"); + reprompt.setText("哈哈,是不是后悔刚才的选择了,下次可要好好考虑考虑哦"); + outResponse.setReprompt(reprompt); + + response.setResponse(outResponse); + } + + private void buildDirectives(DingDongResponse response) { + AudioPlayerDirective audioDirective = new AudioPlayerDirective(); + audioDirective.setType("AudioPlayer.Play"); + audioDirective.setPlayBehavior("REPLACE_ALL"); + AudioStream audioStream = new AudioStream(); + audioStream.setToken("654987123"); + audioDirective.setAudioStream(audioStream); + + List directives = new ArrayList<>(); + directives.add(audioDirective); + response.setDirectives(directives); + } +} diff --git a/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/service/ParseServiceWithoutLRU.java b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/service/ParseServiceWithoutLRU.java new file mode 100644 index 0000000..f7c8a51 --- /dev/null +++ b/jdwhale/src/main/java/ai/qiwu/mqw/jdwhale/service/ParseServiceWithoutLRU.java @@ -0,0 +1,188 @@ +package ai.qiwu.mqw.jdwhale.service; + +import ai.qiwu.mqw.jdwhale.common.Constants; +import ai.qiwu.mqw.jdwhale.model.RequestModel.DingDongRequest; +import ai.qiwu.mqw.jdwhale.model.RequestModel.request.TripleRequest; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.DingDongResponse; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioPlayerDirective; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.directives.audio.AudioStream; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.Output; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.OutputResponse; +import ai.qiwu.mqw.jdwhale.model.ResponseModel.response.Reprompt; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-6-26 下午4:09 + */ +@Service("serviceWithoutLRU") +public class ParseServiceWithoutLRU { + private static final Logger logger = LoggerFactory.getLogger(ParseService.class); + + public DingDongResponse getResponse(DingDongRequest request) { + String userId = request.getSession().getUser().getUserId(); + if (userId == null) userId = request.getSession().getApplication().getApplicationId(); + TripleRequest unknowRequest = request.getRequest(); + switch (unknowRequest.getType()) { + case "LaunchRequest": return dealLaunchRequest(); + case "IntentRequest": return dealIntentRequest(unknowRequest, userId); + case "SessionEndedRequest": dealSessionEndedRequest(userId); return null; + default: logger.info("ERROR DIRECTIVE"); return dealLaunchRequest(); + } + } + + private DingDongResponse dealLaunchRequest() { + DingDongResponse response = new DingDongResponse(); + buildResponse(response); + response.getResponse().getOutput().setText("欢迎来到有声互动小说,请说推荐作品"); + response.getResponse().getReprompt().setText("请说推荐作品"); + return response; + } + + private DingDongResponse dealIntentRequest(TripleRequest request, String userId) { + // 处理Alpha.CancelIntent意图,该意图是平台默认的意图,用户说退出则退出技能, + // 我们这里需要对该意图进行判断处理. + // "request": { + // "dialogState": "STARTED", + // "intent": { + // "name": "Alpha.CancelIntent" + // }, + // "requestId": "42d7d9f2-4134-4979-82fc-44dafe408171_6006_test", + // "timestamp": 1561510754347, + // "type": "IntentRequest" + // }, + if (Constants.CANCEL_INTENT.equals(request.getIntent().getName())) { + dealSessionEndedRequest(userId); + return null; + } + if (Constants.HELP_INTENT.equals(request.getIntent().getName())) { + DingDongResponse response = new DingDongResponse(); + buildResponse(response); + response.getResponse().setReprompt(null); + response.getResponse().getOutput().setText("请明确一些说帮或不帮"); + return response; + } + DingDongResponse response = buildResponseInTTS(); + String userWord = request.getOriginal(); + requestQiWuInterface(userId, userWord, response); + return response; + } + + private void dealSessionEndedRequest(String userId) { + logger.info("用户 "+userId+" 会话结束"); + } + + private void requestQiWuInterface(String userId, String userWord, DingDongResponse response) { + String audioUrl = ""; + String textContent = "请说推荐作品"; + CloseableHttpClient httpClient = null; + CloseableHttpResponse httpResponse = null; + try { + httpClient = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE); + + HashMap params = new HashMap<>(); + params.put("user_id", String.valueOf(userId)); + params.put("text", userWord); + params.put("access",Constants.SERVICE_NAME); + + String paramsJsonFormat = JSON.toJSONString(params); + StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8"); + post.setHeader("Content-Type", "application/json;charset=utf-8"); + post.setEntity(body); + + httpResponse = httpClient.execute(post); + HttpEntity responseBody = httpResponse.getEntity(); + if (responseBody != null) { + String responseContent = EntityUtils.toString(responseBody); + logger.info("齐悟接口返回: "+ responseContent); + JSONObject responseJsonFormat = JSONObject.parseObject(responseContent); + audioUrl = (String) responseJsonFormat.get("audio"); + textContent = (String) responseJsonFormat.get("text"); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (httpClient != null) httpClient.close(); + if (httpResponse != null) httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + addUrlAndTextToResponse(audioUrl, textContent, response); + } + + private void addUrlAndTextToResponse(String url, String text, DingDongResponse response) { + response.getResponse().getOutput().setText(text); + response.getDirectives().get(0).getAudioStream().setUrl(url); + } + + /** + * 语音指令调用该方法生成Response + * @return + */ + private DingDongResponse buildResponseInDirective() { + DingDongResponse response = new DingDongResponse(); + response.setVersion("1.0"); + response.setShouldEndSession(true); + buildDirectives(response); + return response; + } + + /** + * TTS模式 + * @return + */ + private DingDongResponse buildResponseInTTS() { + DingDongResponse response = new DingDongResponse(); + buildResponse(response); + buildDirectives(response); + return response; + } + + private void buildResponse(DingDongResponse response) { + response.setShouldEndSession(false); + response.setVersion("1.0"); + + OutputResponse outResponse = new OutputResponse(); + Output output = new Output(); + output.setType("PlainText"); + outResponse.setOutput(output); + Reprompt reprompt = new Reprompt(); + reprompt.setType("PlainText"); + reprompt.setText("哈哈,是不是后悔刚才的选择了,下次可要好好考虑考虑哦"); + outResponse.setReprompt(reprompt); + + response.setResponse(outResponse); + } + + private void buildDirectives(DingDongResponse response) { + AudioPlayerDirective audioDirective = new AudioPlayerDirective(); + audioDirective.setType("AudioPlayer.Play"); + audioDirective.setPlayBehavior("REPLACE_ALL"); + AudioStream audioStream = new AudioStream(); + audioStream.setToken("654987123"); + audioDirective.setAudioStream(audioStream); + + List directives = new ArrayList<>(); + directives.add(audioDirective); + response.setDirectives(directives); + } +} diff --git a/jdwhale/src/main/resources/application.properties b/jdwhale/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/jdwhale/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/jdwhale/src/main/resources/logback.xml b/jdwhale/src/main/resources/logback.xml new file mode 100644 index 0000000..88ab8d5 --- /dev/null +++ b/jdwhale/src/main/resources/logback.xml @@ -0,0 +1,42 @@ + + + + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + + + + + + + + /usr/mqw/logs/jdWhale/ + + + /usr/mqw/logs/jdWhale/base.log.%d.%i + + 64 MB + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + \ No newline at end of file diff --git a/jdwhale/src/test/java/ai/qiwu/mqw/jdwhale/JdwhaleApplicationTests.java b/jdwhale/src/test/java/ai/qiwu/mqw/jdwhale/JdwhaleApplicationTests.java new file mode 100644 index 0000000..8866825 --- /dev/null +++ b/jdwhale/src/test/java/ai/qiwu/mqw/jdwhale/JdwhaleApplicationTests.java @@ -0,0 +1,16 @@ +package ai.qiwu.mqw.jdwhale; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class JdwhaleApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/pom.xml b/pom.xml index 1b62323..5f419bd 100644 --- a/pom.xml +++ b/pom.xml @@ -6,6 +6,7 @@ ai.qiwu smartbox + pom 1.0-SNAPSHOT diff --git a/ruoqi/pom.xml b/ruoqi/pom.xml index 97bacb8..0e37e1a 100644 --- a/ruoqi/pom.xml +++ b/ruoqi/pom.xml @@ -16,6 +16,16 @@ 1.8 + UTF-8 + UTF-8 + true + UTF-8 + 1.8 + 1.8 + + 2.6 + 1.9.13 + 2.8.5 @@ -29,6 +39,35 @@ spring-boot-starter-test test + + + commons-lang + commons-lang + ${commons_lang_version} + + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.13 + + + com.google.code.gson + gson + ${google_code_gson_version} + + + + org.apache.httpcomponents + httpclient + 4.5.8 + + + com.alibaba + fastjson + 1.2.58 + + diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/Constants.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/Constants.java new file mode 100644 index 0000000..a0ddcce --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/Constants.java @@ -0,0 +1,10 @@ +package ai.qiwu.rokid.ruoqi.common; + +/** + * @author 苗权威 + * @dateTime 19-7-2 下午7:36 + */ +public interface Constants { + String QI_WU_INTERFACE = "http://aliyun-hz1.chewrobot.com:8070/api/chat"; + String SERVICE_NAME = "DINGDONG"; +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/exception/ProtocolException.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/exception/ProtocolException.java new file mode 100644 index 0000000..010fadb --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/exception/ProtocolException.java @@ -0,0 +1,20 @@ +package ai.qiwu.rokid.ruoqi.common.exception; + +public class ProtocolException extends Exception { + /** + * + */ + private static final long serialVersionUID = 8914106243553844621L; + + public ProtocolException(String message) { + super(message); + } + + public ProtocolException(String message, Throwable throwable) { + super(message, throwable); + } + + public ProtocolException(Throwable throwable) { + super(throwable); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/exception/RokidException.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/exception/RokidException.java new file mode 100644 index 0000000..cbd2a8d --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/exception/RokidException.java @@ -0,0 +1,72 @@ +package ai.qiwu.rokid.ruoqi.common.exception; + +import org.springframework.http.HttpStatus; + +/** + * 通用异常情况 + * + * @author Bassam + * + */ +public class RokidException extends Exception { + + private static final long serialVersionUID = 9135801019232303753L; + // 默认提供了一定的错误定义/// + public static final String ERROR_CODE_SUCCESS = HttpStatus.OK.name();// 成功 + public static final String ERROR_CODE_NOTFOUND = "NotFound";// 没有找到 + public static final String ERROR_CODE_DATABASE = "DatabaseError";// 数据库错误 + public static final String ERROR_CODE_REDIS = "RedisError";// Redis错误 + public static final String ERROR_CODE_REDISFOUND = "RedisNotFound";// Redis数据没有找到 + public static final String ERROR_CODE_SECURITY = "SecurityError";// 安全检查错误 + public static final String ERROR_CODE_INVALIDHEAD = "InvalidHead";// 请求头有误 + public static final String ERROR_CODE_INVALIDBODY = "InvalidBody";// 请求数据有误 + public static final String ERROR_CODE_INVALIDARGUMENT = "InvalidArgument";// 无效的参数 + public static final String ERROR_CODE_RESONSE = "ResponseError";// 响应错误 + public static final String ERROR_CODE_MISSINGARGUMENT = "MissingArgument";// 参数缺失 + public static final String ERROR_CODE_METHODNOTALLOWED = "MethodNotAllowed";// 方法不支持 + public static final String ERROR_CODE_INTERNAL = "InternalError";// 内部错误 + public static final String ERROR_CODE_ACCESS = "AccessDenied";// 接入出错 + + private int httpStatusCode;// Http状态码 + private String errorCode;// 操作码 + + public int getHttpStatusCode() { + return httpStatusCode; + } + + public void setHttpStatusCode(int httpStatusCode) { + this.httpStatusCode = httpStatusCode; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public RokidException(int httpStatusCode, String errorCode) { + super(); + this.httpStatusCode = httpStatusCode; + this.errorCode = errorCode; + } + + public RokidException(int httpStatusCode, String errorCode, String message) { + super(message); + this.httpStatusCode = httpStatusCode; + this.errorCode = errorCode; + } + + public RokidException(int httpStatusCode, String errorCode, String message, Throwable throwable) { + super(message, throwable); + this.httpStatusCode = httpStatusCode; + this.errorCode = errorCode; + } + + public RokidException(int httpStatusCode, String errorCode, Throwable throwable) { + super(throwable); + this.httpStatusCode = httpStatusCode; + this.errorCode = errorCode; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/exception/RokidSpeechletException.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/exception/RokidSpeechletException.java new file mode 100644 index 0000000..f4212eb --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/exception/RokidSpeechletException.java @@ -0,0 +1,74 @@ +package ai.qiwu.rokid.ruoqi.common.exception; + +/** + * 语音业务异常情况 + * + * @author Bassam + * + */ +public class RokidSpeechletException extends RokidException { + + private static final long serialVersionUID = 9135801019232303753L; + private String actionType; + private String actionName; + + public RokidSpeechletException(int httpStatusCode, String errorCode, String message, Throwable throwable) { + super(httpStatusCode, errorCode, message, throwable); + } + + public RokidSpeechletException(int httpStatusCode, String errorCode, String message) { + super(httpStatusCode, errorCode, message); + } + + public RokidSpeechletException(int httpStatusCode, String errorCode, Throwable throwable) { + super(httpStatusCode, errorCode, throwable); + } + + public RokidSpeechletException(int httpStatusCode, String errorCode) { + super(httpStatusCode, errorCode); + } + + public RokidSpeechletException(int httpStatusCode, String errorCode, String actionType, String actionName) { + super(httpStatusCode, errorCode); + this.actionType = actionType; + this.actionName = actionName; + } + + public RokidSpeechletException(int httpStatusCode, String errorCode, String actionType, String actionName, + Throwable throwable) { + super(httpStatusCode, errorCode, throwable); + this.actionType = actionType; + this.actionName = actionName; + } + + public RokidSpeechletException(int httpStatusCode, String errorCode, String actionType, String actionName, + String message, Throwable throwable) { + super(httpStatusCode, errorCode, message, throwable); + this.actionType = actionType; + this.actionName = actionName; + } + + public RokidSpeechletException(int httpStatusCode, String errorCode, String actionType, String actionName, + String message) { + super(httpStatusCode, errorCode, message); + this.actionType = actionType; + this.actionName = actionName; + } + + public String getActionType() { + return actionType; + } + + public void setActionType(String actionType) { + this.actionType = actionType; + } + + public String getActionName() { + return actionName; + } + + public void setActionName(String actionName) { + this.actionName = actionName; + } + +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ActionUtils.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ActionUtils.java new file mode 100644 index 0000000..79278e7 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ActionUtils.java @@ -0,0 +1,291 @@ +package ai.qiwu.rokid.ruoqi.common.utils; + +import java.util.List; + +import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException; +import ai.qiwu.rokid.ruoqi.model.response.response.action.ResAction; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.confirm.ResConfirm; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.ResMedia; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.mediaitem.ResMediaItem; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.pickup.ResPickup; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.ResVoice; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.item.ResVoiceItem; +import org.apache.commons.lang.StringUtils; + + + +public class ActionUtils { + /** + * + * @param actionVersion + * @param actionType + * @param shouldEndSession + * @return + * @throws ProtocolException + */ + public static ResAction getEmptyAction(String actionVersion, String actionType, boolean shouldEndSession) + throws ProtocolException { + ResAction resAction = new ResAction(); + if (StringUtils.isBlank(actionVersion)) { + throw new ProtocolException("actionVersion is isBlank"); + } + resAction.setVersion(actionVersion); + if (StringUtils.isBlank(actionType) || (!ResAction.ACTION_TYPE_NORMAL.equals(actionType) + && !ResAction.ACTION_TYPE_EXIT.equals(actionType))) { + throw new ProtocolException("actionType is error"); + } + resAction.setType(actionType); + resAction.setShouldEndSession(shouldEndSession); + return resAction; + } + + /** + * 构建Voice节点 + * + * @param voiceAction + * 详见 ResVoice.VOICE_ACTION + * @param disableEvent + * 是否关闭Event事件 + * @param itemId + * @param voiceContent + * @return + * @throws ProtocolException + */ + public static ResVoice getResVoice(String voiceAction, boolean disableEvent, String itemId, String voiceContent) + throws ProtocolException { + if (checkVoiceAction(voiceAction)) { + ResVoice resVoice = new ResVoice(); + resVoice.setAction(voiceAction); + resVoice.setDisableEvent(disableEvent); + if (ResVoice.VOICE_ACTION_PLAY.equals(voiceAction)) { + if (StringUtils.isBlank(voiceContent)) { + throw new ProtocolException("voiceContent is isBlank"); + } + ResVoiceItem voiceItem = new ResVoiceItem(); + voiceItem.setItemId(itemId); + voiceItem.setTts(voiceContent); + resVoice.setItem(voiceItem); + } + return resVoice; + } + throw new ProtocolException("voiceAction is error"); + } + + /** + * 构建Confirm节点 + * + * @param confirmIntent + * @param confirmSlot + * @param optionWords + * @return + * @throws ProtocolException + */ + public static ResConfirm getResConfirm(String confirmIntent, String confirmSlot, List optionWords) + throws ProtocolException { + if (!StringUtils.isBlank(confirmIntent) && !StringUtils.isBlank(confirmSlot)) { + ResConfirm resConfirm = new ResConfirm(); + resConfirm.setConfirmIntent(confirmIntent); + resConfirm.setConfirmSlot(confirmSlot); + resConfirm.setOptionWords(optionWords); + return resConfirm; + } else { + throw new ProtocolException("confirmIntent or confirmSlot isBlank"); + } + } + + /** + * 检查Voice的Action事件 + * + * @param voiceAction + * @return + * @throws ProtocolException + */ + public static boolean checkVoiceAction(String voiceAction) throws ProtocolException { + if (StringUtils.isBlank(voiceAction)) { + throw new ProtocolException("Voice Directive's action is blank"); + } + if (!ResVoice.VOICE_ACTION_PLAY.equals(voiceAction) && !ResVoice.VOICE_ACTION_PAUSE.equals(voiceAction) + && !ResVoice.VOICE_ACTION_RESUME.equals(voiceAction) + && !ResVoice.VOICE_ACTION_STOP.equals(voiceAction)) { + throw new ProtocolException("Voice Directive's action is error"); + } + return true; + } + + /** + * 构建 ResMedia节点 + * + * @param mediaAction + * @param disableEvent + * @param itemId + * @param mediaToken + * @param mediaType + * @param mediaUrl + * @param mediaOffset + * @return + * @throws ProtocolException + */ + public static ResMedia getResMeida(String mediaAction, boolean disableEvent, String itemId, String mediaToken, + String mediaType, String mediaUrl, long mediaOffset) throws ProtocolException { + if (checkMediaAction(mediaAction)) { + ResMedia resMedia = new ResMedia(); + resMedia.setDisableEvent(disableEvent); + resMedia.setAction(mediaAction); + if (ResMedia.MEDIA_ACTION_PLAY.equals(mediaAction)) { + ResMediaItem resMediaItem = new ResMediaItem(); + if (StringUtils.isBlank(mediaUrl)) { + throw new ProtocolException("mediaUrl isBlank"); + } + resMediaItem.setUrl(mediaUrl); + if (StringUtils.isBlank(mediaType) || (!ResMediaItem.MEDIA_TYPE_AUDIO.equals(mediaType) + && !ResMediaItem.MEDIA_TYPE_VIDEO.equals(mediaType))) { + throw new ProtocolException("mediaType is error"); + } + resMediaItem.setType(mediaType); + resMediaItem.setToken(mediaToken); + if (mediaOffset < 0) { + throw new ProtocolException("mediaOffset is error"); + } + resMediaItem.setOffsetInMilliseconds(mediaOffset); + resMedia.setItem(resMediaItem); + } + } + throw new ProtocolException("Error mediaAction:" + mediaAction); + } + + /** + * 检查VoiceAction + * + * @param mediaAction + * @return + * @throws ProtocolException + */ + public static boolean checkMediaAction(String mediaAction) throws ProtocolException { + if (StringUtils.isBlank(mediaAction)) { + throw new ProtocolException("Media Directive's action is blank"); + } + if (!ResMedia.MEDIA_ACTION_PLAY.equals(mediaAction) && !ResMedia.MEDIA_ACTION_PAUSE.equals(mediaAction) + && !ResMedia.MEDIA_ACTION_RESUME.equals(mediaAction) + && !ResMedia.MEDIA_ACTION_STOP.equals(mediaAction)) { + throw new ProtocolException("Media Directive's action is error"); + } + return true; + } + + /** + * 获取ResPickUp节点 + * + * @param enable + * @param durationInMilliseconds + * @return + * @throws ProtocolException + */ + public static ResPickup getResPickup(boolean enable, long durationInMilliseconds) throws ProtocolException { + ResPickup resPickup = new ResPickup(); + resPickup.setEnable(enable); + if (durationInMilliseconds < 0) { + throw new ProtocolException("durationInMilliseconds is error"); + } + resPickup.setDurationInMilliseconds(durationInMilliseconds); + return resPickup; + } + + /** + * 检查Action类型 + * + * @param actionType + * @return + * @throws ProtocolException + */ + public static boolean checkActionType(String actionType) throws ProtocolException { + if (ResAction.ACTION_TYPE_EXIT.equals(actionType) || ResAction.ACTION_TYPE_NORMAL.equals(actionType)) { + return true; + } + throw new ProtocolException("actionType is error"); + } + + /** + * 检查ResVoice的合法性 + * + * @param resVoice + * @return + * @throws ProtocolException + */ + public static boolean checkVoice(ResVoice resVoice) throws ProtocolException { + if (resVoice != null) { + if (!checkVoiceAction(resVoice.getAction())) { + throw new ProtocolException("Voice Directive is error"); + } + if (ResVoice.VOICE_ACTION_PLAY.equals(resVoice.getAction())) { + if (resVoice.getItem() == null) { + throw new ProtocolException("Voice Directive's action is play,but item is null"); + } + if (StringUtils.isBlank(resVoice.getItem().getTts())) { + throw new ProtocolException("Voice Directive's action is play,but item's tts is blank"); + } + } + } + return true; + } + + /** + * 检查Media节点的合法性 + * + * @param resMedia + * @return + * @throws ProtocolException + */ + public static boolean checkMedia(ResMedia resMedia) throws ProtocolException { + if (resMedia != null) { + if (!checkMediaAction(resMedia.getAction())) { + throw new ProtocolException("Media Directivei is error"); + } + if (ResMedia.MEDIA_ACTION_PLAY.equals(resMedia.getAction())) { + if (resMedia.getItem() == null) { + throw new ProtocolException("Meida Directive's action is play,but item is null"); + } + if (StringUtils.isBlank(resMedia.getItem().getUrl())) { + throw new ProtocolException("Meida Directive's action is play,but item's url is Blank"); + } + if (resMedia.getItem().getOffsetInMilliseconds() < 0) { + throw new ProtocolException( + "Meida Directive's action is play,but item's OffsetInMilliseconds is <0"); + } + } + } + return true; + } + + /** + * 检查PickUp节点 + * + * @param resPickup + * @return + * @throws ProtocolException + */ + public static boolean checkPickup(ResPickup resPickup) throws ProtocolException { + if (resPickup != null) { + if (resPickup.getDurationInMilliseconds() < 0) { + throw new ProtocolException("PickUp Directive's DurationInMilliseconds is <0"); + } + } + return true; + } + + /** + * 检查confirm节点 + * + * @param resConfirm + * @return + * @throws ProtocolException + */ + public static boolean checkConfirm(ResConfirm resConfirm) throws ProtocolException { + if (resConfirm != null) { + if (StringUtils.isBlank(resConfirm.getConfirmIntent()) + || StringUtils.isBlank(resConfirm.getConfirmSlot())) { + throw new ProtocolException("Confirm Directive's Intent or slot is blank"); + } + } + return true; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ProtocolUtils.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ProtocolUtils.java new file mode 100644 index 0000000..aad6714 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ProtocolUtils.java @@ -0,0 +1,125 @@ +package ai.qiwu.rokid.ruoqi.common.utils; + +import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException; +import ai.qiwu.rokid.ruoqi.common.exception.RokidException; +import ai.qiwu.rokid.ruoqi.model.response.ResResponse; +import org.springframework.http.HttpStatus; + + +public class ProtocolUtils { + /** + * 忽略事件,比如Voice.STARTED的EventRequest来的时候我们可以使用这个操作忽略这个请求 + * + * @return + * @throws ProtocolException + */ + public static final ResResponse igonre() { + try { + return ResponseUtils.buildIngoreEventResponse(); + } catch (ProtocolException e) { + e.printStackTrace(); + return null; + } + } + + /** + * 退出 + * + * @举例 若琪停止播放 + * @return + * @throws ProtocolException + */ + public static final ResResponse exit() throws RokidException { + try { + return ResponseUtils.buildExitNowResponse(); + } catch (ProtocolException e) { + return null; + } + } + + /** + * 从0开始播放音乐,并且停止TTS + * + * @param songId + * @param songUrl + * @return + * @throws RokidException + */ + public static final ResResponse playSongAndFinished(String songId, String songUrl) throws RokidException { + try { + return ResponseBuilder.build().audioPlay(songId, null, songUrl, 0).mediaEventDisable().afterFinish() + .create(); + } catch (ProtocolException e) { + throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE, + e.getCause()); + } + } + + /** + * 暂停音乐 + * + * @举例 若琪暂停播放 + * @return + * @throws ProtocolException + */ + public static final ResResponse pauseMusic() throws RokidException { + try { + return ResponseBuilder.build().mediaPause().mediaEventDisable().create(); + } catch (ProtocolException e) { + throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE, + e.getCause()); + } + } + public static final ResResponse playTTs(String content) throws RokidException { + try { + return ResponseBuilder.build().voicePlay(null, content).sendChatCard(content).create(); + } catch (ProtocolException e) { + throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE, + e.getCause()); + } + } + /** + * 播放完tts退出示例 + * @param content + * @return + * @throws RokidException + */ + public static final ResResponse playTts(String content) throws RokidException{ + try { + return ResponseBuilder.build().voicePlay(null, content).sendChatCard(content).afterFinish().create(); + } catch (ProtocolException e) { + throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE, + e.getCause()); + } + } + /** + * 进入六十秒拾音状态 + * @param content + * @return + * @throws RokidException + */ + public static final ResResponse pickUp(String content) throws RokidException{ + try { + return ResponseBuilder.build().voicePlay(null, content).pickupOpen().sendChatCard(content).create(); + } catch (ProtocolException e) { + throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE, + e.getCause()); + } + } + + /** + * 继续播放音乐 + * + * @举例 若琪继续播放音乐 + * @return + * @throws ProtocolException + */ + public static final ResResponse resumeMusic() throws RokidException { + try { + return ResponseBuilder.build().mediaResume().mediaEventDisable().afterFinish().create(); + } catch (ProtocolException e) { + throw new RokidException(HttpStatus.INTERNAL_SERVER_ERROR.value(), RokidException.ERROR_CODE_RESONSE, + e.getCause()); + } + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ReqBasicInfo.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ReqBasicInfo.java new file mode 100644 index 0000000..63f61e2 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ReqBasicInfo.java @@ -0,0 +1,142 @@ +package ai.qiwu.rokid.ruoqi.common.utils; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; + +public class ReqBasicInfo implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + private String protocolVersion;// 当前协议版本 + private String requestId;// 请求ID + private String sessionId;// SessionId + private String appId;// 应用ID + private String deviceId;// 设备ID + private String deviceType;// 设备类型 + private String deviceVendor;// 厂商ID + private String masterId;// 设备主人的ID + private String userId;// 用户id + private String locale;// 用户语言 + private String actionType;// 操作类型 + private String actionName;// 操作名称 + private long timestamp;// 设备时间戳 + private String voicetrigger;// 当前设备激活词 + + public String getProtocolVersion() { + return protocolVersion; + } + + public String getRequestId() { + return requestId; + } + + public String getSessionId() { + return sessionId; + } + + public String getAppId() { + return appId; + } + + public String getDeviceId() { + return deviceId; + } + + public String getDeviceType() { + return deviceType; + } + + public String getDeviceVendor() { + return deviceVendor; + } + + public String getMasterId() { + return masterId; + } + + public String getUserId() { + return userId; + } + + public String getLocale() { + return locale; + } + + public String getActionType() { + return actionType; + } + + public String getActionName() { + return actionName; + } + + public long getTimestamp() { + return timestamp; + } + + public void setProtocolVersion(String protocolVersion) { + this.protocolVersion = protocolVersion; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public void setAppId(String appId) { + this.appId = appId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + + public void setDeviceVendor(String deviceVendor) { + this.deviceVendor = deviceVendor; + } + + public void setMasterId(String masterId) { + this.masterId = masterId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public void setLocale(String locale) { + this.locale = locale; + } + + public void setActionType(String actionType) { + this.actionType = actionType; + } + + public void setActionName(String actionName) { + this.actionName = actionName; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public String getVoicetrigger() { + return voicetrigger; + } + + public void setVoicetrigger(String voicetrigger) { + this.voicetrigger = voicetrigger; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/RequestUtils.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/RequestUtils.java new file mode 100644 index 0000000..bd2029d --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/RequestUtils.java @@ -0,0 +1,224 @@ +package ai.qiwu.rokid.ruoqi.common.utils; + +import java.util.HashMap; + +import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException; +import ai.qiwu.rokid.ruoqi.model.request.ReqRequest; +import ai.qiwu.rokid.ruoqi.model.request.context.application.media.ReqApplicationMedia; +import ai.qiwu.rokid.ruoqi.model.request.context.application.voice.ReqApplicationVoice; +import ai.qiwu.rokid.ruoqi.model.request.context.device.location.ReqLocation; +import ai.qiwu.rokid.ruoqi.model.request.request.ReqRequestValue; +import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.media.ReqExtraMedia; +import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.voice.ReqExtraVoice; +import ai.qiwu.rokid.ruoqi.model.request.request.content.slot.Slot; +import org.apache.commons.lang.StringUtils; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +/** + * 请求处理工具类 + * + * @author Bassam + * + */ +public class RequestUtils { + /** + * 获取ReqRequest对象 + * + * @param resuest + * @return + * @throws ProtocolException + */ + public static ReqRequest getRequest(String resuest) throws ProtocolException { + Gson gson = new GsonBuilder().disableHtmlEscaping().create(); + return gson.fromJson(resuest, ReqRequest.class); + } + + /** + * 获得基本请求信息 + * + * @param reqRequest + * @return + */ + public static ReqBasicInfo getBasicInfo(ReqRequest reqRequest) { + ReqBasicInfo reqBasicInfo = new ReqBasicInfo(); + if (reqRequest != null) { + reqBasicInfo.setProtocolVersion(reqRequest.getVersion()); + if (reqRequest.getSession() != null) { + reqBasicInfo.setSessionId(reqRequest.getSession().getSessionId()); + } + if (reqRequest.getContext() != null) { + if (reqRequest.getContext().getApplication() != null) { + reqBasicInfo.setAppId(reqRequest.getContext().getApplication().getApplicationId()); + } + if (reqRequest.getContext().getDevice() != null + && reqRequest.getContext().getDevice().getBasic() != null) { + reqBasicInfo.setDeviceId(reqRequest.getContext().getDevice().getBasic().getDeviceId()); + reqBasicInfo.setDeviceType(reqRequest.getContext().getDevice().getBasic().getDeviceType()); + reqBasicInfo.setDeviceVendor(reqRequest.getContext().getDevice().getBasic().getVendor()); + reqBasicInfo.setTimestamp(reqRequest.getContext().getDevice().getBasic().getTimestamp()); + reqBasicInfo.setMasterId(reqRequest.getContext().getDevice().getBasic().getMasterId()); + reqBasicInfo.setLocale(reqRequest.getContext().getDevice().getBasic().getLocale()); + reqBasicInfo.setVoicetrigger(reqRequest.getContext().getDevice().getBasic().getVoicetrigger()); + } + if (reqRequest.getContext().getUser() != null) { + reqBasicInfo.setUserId(reqRequest.getContext().getUser().getUserId()); + } + } + if (reqRequest.getRequest() != null) { + reqBasicInfo.setRequestId(reqRequest.getRequest().getReqId()); + reqBasicInfo.setActionType(reqRequest.getRequest().getReqType()); + if (reqRequest.getRequest().getContent() != null) { + if (ReqRequestValue.REQTYPE_EVENT.equals(reqBasicInfo.getActionType())) { + reqBasicInfo.setActionName(reqRequest.getRequest().getContent().getEvent()); + } else if (ReqRequestValue.REQTYPE_INTENT.equals(reqBasicInfo.getActionType())) { + reqBasicInfo.setActionName(reqRequest.getRequest().getContent().getIntent()); + } + } + } + } + return reqBasicInfo; + } + + /** + * 获得Media状态信息 + * + * @param reqRequest + * @return + */ + public static ReqApplicationMedia getMediaState(ReqRequest reqRequest) { + ReqApplicationMedia reqApplicationMedia = null; + if (reqRequest != null && reqRequest.getContext() != null && reqRequest.getContext().getApplication() != null) { + reqApplicationMedia = reqRequest.getContext().getApplication().getMedia(); + } + if (reqApplicationMedia == null) { + reqApplicationMedia = new ReqApplicationMedia(); + } + if (StringUtils.isBlank(reqApplicationMedia.getState())) { + reqApplicationMedia.setState(ReqApplicationMedia.STATE_IDLE); + } + return reqApplicationMedia; + } + + /** + * 获得VoiceState + * + * @param reqRequest + * @return + */ + public static ReqApplicationVoice getVoiceState(ReqRequest reqRequest) { + ReqApplicationVoice reqApplicationVoice = null; + if (reqRequest != null && reqRequest.getContext() != null && reqRequest.getContext().getApplication() != null) { + reqApplicationVoice = reqRequest.getContext().getApplication().getVoice(); + } + if (reqApplicationVoice == null) { + reqApplicationVoice = new ReqApplicationVoice(); + } + if (StringUtils.isBlank(reqApplicationVoice.getState())) { + reqApplicationVoice.setState(ReqApplicationVoice.STATE_IDLE); + } + return reqApplicationVoice; + } + + /** + * 获取位置信息 + * + * @param reqRequest + * @return + */ + public static ReqLocation getLocation(ReqRequest reqRequest) { + ReqLocation reqLocation = null; + if (reqRequest != null && reqRequest.getContext() != null && reqRequest.getContext().getDevice() != null) { + reqLocation = reqRequest.getContext().getDevice().getLocation(); + } + if (reqLocation == null) { + reqLocation = new ReqLocation(); + } + return reqLocation; + } + + /** + * 获取Media拓展信息 + * + * @param reqRequest + * @return + */ + public static ReqExtraMedia getMediaExtra(ReqRequest reqRequest) { + ReqExtraMedia reqExtraMedia = null; + if (reqRequest != null && reqRequest.getRequest() != null && reqRequest.getRequest().getContent() != null + && reqRequest.getRequest().getContent().getExtra() != null) { + reqExtraMedia = reqRequest.getRequest().getContent().getExtra().getMedia(); + } + if (reqExtraMedia == null) { + reqExtraMedia = new ReqExtraMedia(); + } + return reqExtraMedia; + } + + /** + * 获取Voice拓展信息 + * + * @param reqRequest + * @return + */ + public static ReqExtraVoice getVoiceExtra(ReqRequest reqRequest) { + ReqExtraVoice reqExtraVoice = null; + if (reqRequest != null && reqRequest.getRequest() != null && reqRequest.getRequest().getContent() != null + && reqRequest.getRequest().getContent().getExtra() != null) { + reqExtraVoice = reqRequest.getRequest().getContent().getExtra().getVoice(); + } + if (reqExtraVoice == null) { + reqExtraVoice = new ReqExtraVoice(); + } + return reqExtraVoice; + } + + /** + * 获取属性信息 + * + * @param reqRequest + * @return + */ + public static HashMap getAttributes(ReqRequest reqRequest) { + HashMap attributes = null; + if (reqRequest != null && reqRequest.getSession() != null && reqRequest.getSession().getAttributes() != null) { + attributes = reqRequest.getSession().getAttributes(); + } + if (attributes == null) { + attributes = new HashMap<>(); + } + return attributes; + } + + /** + * 获取Slots + * + * @param reqRequest + * @return + */ + public static HashMap getSlots(ReqRequest reqRequest) { + HashMap slots = null; + if (reqRequest != null && reqRequest.getRequest() != null && reqRequest.getRequest().getContent() != null) { + slots = reqRequest.getRequest().getContent().getSlots(); + } + if (slots == null) { + slots = new HashMap<>(); + } + return slots; + } + + /** + * 获取Intent Request的ASR结果 + * + * @param reqRequest + * @return + */ + public static String getSentence(ReqRequest reqRequest) { + String scentence = ""; + if (reqRequest != null && reqRequest.getRequest() != null && reqRequest.getRequest().getContent() != null) { + scentence = reqRequest.getRequest().getContent().getSentence(); + } + return scentence; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ResponseBuilder.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ResponseBuilder.java new file mode 100644 index 0000000..63dadbc --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ResponseBuilder.java @@ -0,0 +1,362 @@ +package ai.qiwu.rokid.ruoqi.common.utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException; +import ai.qiwu.rokid.ruoqi.model.response.ResResponse; +import ai.qiwu.rokid.ruoqi.model.response.response.ResResponseContent; +import ai.qiwu.rokid.ruoqi.model.response.response.action.ResAction; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.ResDirective; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.confirm.ResConfirm; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.ResMedia; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.mediaitem.ResMediaItem; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.pickup.ResPickup; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.ResVoice; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.item.ResVoiceItem; +import ai.qiwu.rokid.ruoqi.model.response.response.card.ResCard; +import ai.qiwu.rokid.ruoqi.model.response.response.card.chat.ResChatCard; +import ai.qiwu.rokid.ruoqi.model.response.session.ResSession; +import org.apache.commons.lang.StringUtils; + + + +public class ResponseBuilder { + private ResResponse response; + private boolean shouldEndSession = false;// 执行完这个action完毕 + private String actionType = ResAction.ACTION_TYPE_NORMAL; + private HashMap attributes; + private ResVoice resVoice; + private ResConfirm resConfirm; + private ResMedia resMedia; + private ResPickup pickup; + private ResCard card; + + public static ResponseBuilder build() { + return new ResponseBuilder(); + } + + public ResponseBuilder() { + response = buildEmptyActionResponse(ResResponse.RES_VERSION_V2, null, ResAction.ACTION_VERSION_V2, actionType, + shouldEndSession); + } + + /** + * 下一次请求原样带回的参数 + * + * @param attributes + * @return + */ + public ResponseBuilder setAttributes(HashMap attributes) { + this.attributes = attributes; + return this; + } + + /** + * 播放TTS + * + * @param voiceId + * @param voiceContent + * @return + */ + public ResponseBuilder voicePlay(String voiceId, String voiceContent) { + if (resVoice == null) { + resVoice = new ResVoice(); + } + ResVoiceItem resVoiceItem = new ResVoiceItem(); + resVoiceItem.setItemId(voiceId); + resVoiceItem.setTts(voiceContent); + resVoice.setAction(ResVoice.VOICE_ACTION_PLAY); + resVoice.setItem(resVoiceItem); + return this; + } + + /** + * 暂停Media + * + * @return + */ + public ResponseBuilder voicePause() { + if (resVoice == null) { + resVoice = new ResVoice(); + } + resVoice.setAction(ResVoice.VOICE_ACTION_PAUSE); + return this; + } + + /** + * 继续播放TTS + * + * @return + */ + public ResponseBuilder voiceResume() { + if (resVoice == null) { + resVoice = new ResVoice(); + } + resVoice.setAction(ResVoice.VOICE_ACTION_RESUME); + return this; + } + + /** + * 停止播放TTS + * + * @return + */ + public ResponseBuilder voiceStop() { + if (resVoice == null) { + resVoice = new ResVoice(); + } + resVoice.setAction(ResVoice.VOICE_ACTION_STOP); + return this; + } + + /** + * 关闭Voice的EventRequest + * + * @return + */ + public ResponseBuilder voiceEventDisable() { + if (resVoice == null) { + resVoice = new ResVoice(); + } + resVoice.setDisableEvent(true); + return this; + } + + /** + * 发起confirm + * + * @param confirmIntent + * @param confirmSlot + * @param optionWords + * @return + */ + public ResponseBuilder confirmOpen(String confirmIntent, String confirmSlot, List optionWords) { + if (resConfirm == null) { + resConfirm = new ResConfirm(); + } + resConfirm.setConfirmSlot(confirmSlot); + resConfirm.setConfirmIntent(confirmIntent); + resConfirm.setOptionWords(optionWords); + return this; + } + + /** + * 播放音频 + * + * @param audioId + * @param audioToken + * @param audioUrl + * @param offsetInMilliseconds + * @return + */ + public ResponseBuilder audioPlay(String audioId, String audioToken, String audioUrl, long offsetInMilliseconds) { + return mediaPlay(audioId, audioToken, ResMediaItem.MEDIA_TYPE_AUDIO, audioUrl, offsetInMilliseconds); + } + + /** + * 播放视频 + * + * @param mediaId + * @param videoToken + * @param videoUrl + * @param offsetInMilliseconds + * @return + */ + public ResponseBuilder videoPlay(String mediaId, String videoToken, String videoUrl, long offsetInMilliseconds) { + return mediaPlay(mediaId, videoToken, ResMediaItem.MEDIA_TYPE_VIDEO, videoUrl, offsetInMilliseconds); + } + + /** + * 播放Media + * + * @param mediaType + * @param mediaId + * @param mediaToken + * @param mediaUrl + * @param offsetInMilliseconds + * @return + */ + public ResponseBuilder mediaPlay(String mediaId, String mediaToken, String mediaType, String mediaUrl, + long offsetInMilliseconds) { + if (resMedia == null) { + resMedia = new ResMedia(); + } + ResMediaItem resMediaItem = new ResMediaItem(); + resMediaItem.setItemId(mediaId); + resMediaItem.setType(mediaType); + resMediaItem.setToken(mediaToken); + resMediaItem.setUrl(mediaUrl); + resMediaItem.setOffsetInMilliseconds(offsetInMilliseconds); + resMedia.setAction(ResMedia.MEDIA_ACTION_PLAY); + resMedia.setItem(resMediaItem); + return this; + } + + /** + * 暂停Media + * + * @return + */ + public ResponseBuilder mediaPause() { + if (resMedia == null) { + resMedia = new ResMedia(); + } + resMedia.setAction(ResMedia.MEDIA_ACTION_PAUSE); + return this; + } + + /** + * 继续播放Meida + * + * @return + */ + public ResponseBuilder mediaResume() { + if (resMedia == null) { + resMedia = new ResMedia(); + } + resMedia.setAction(ResMedia.MEDIA_ACTION_RESUME); + return this; + } + + /** + * 停止播放TTS + * + * @return + */ + public ResponseBuilder mediaStop() { + if (resMedia == null) { + resMedia = new ResMedia(); + } + resMedia.setAction(ResMedia.MEDIA_ACTION_STOP); + return this; + } + + /** + * 关闭Voice的EventRequest + * + * @return + */ + public ResponseBuilder mediaEventDisable() { + if (resMedia == null) { + resMedia = new ResMedia(); + } + resMedia.setDisableEvent(true); + return this; + } + + /** + * 打开拾音 + * + * @return + */ + public ResponseBuilder pickupOpen() { + return pickupOpen(null); + } + + /** + * 打开识音,并且设置重复播报的TTS + * + * @param retryTts + * @return + */ + public ResponseBuilder pickupOpen(String retryTts) { + if (pickup == null) { + pickup = new ResPickup(); + } + pickup.setEnable(true); + pickup.setDurationInMilliseconds(6000l); + if (StringUtils.isNotBlank(retryTts)) { + pickup.setRetryTts(retryTts); + } + return this; + } + + + /** + * 执行完毕以后退出应用 + * + * @return + */ + public ResponseBuilder afterFinish() { + shouldEndSession = true; + return this; + } + + /** + * 立即退出应用 + * + * @return + */ + public ResponseBuilder finishNow() { + actionType = ResAction.ACTION_TYPE_EXIT; + shouldEndSession = true; + return this; + } + + public ResponseBuilder sendChatCard(String content) { + card = new ResChatCard(content); + return this; + } + + public ResResponse create() throws ProtocolException { + response.getSession().setAttributes(attributes); + List directives = new ArrayList<>(); + response.getResponse().getAction().setDirectives(directives); + response.getResponse().getAction().setShouldEndSession(shouldEndSession); + if (!ActionUtils.checkActionType(actionType)) { + throw new ProtocolException("actionType is error"); + } + response.getResponse().getAction().setType(actionType); + if (!ActionUtils.checkVoice(resVoice)) { + throw new ProtocolException("resVoice is error"); + } + if (resVoice != null) { + response.getResponse().getAction().getDirectives().add(resVoice); + } + if (!ActionUtils.checkMedia(resMedia)) { + throw new ProtocolException("resMedia is error"); + } + if (resMedia != null) { + response.getResponse().getAction().getDirectives().add(resMedia); + } + if (!ActionUtils.checkConfirm(resConfirm)) { + throw new ProtocolException("resConfirm is error"); + } + if (resConfirm != null) { + response.getResponse().getAction().getDirectives().add(resConfirm); + } + if (!ActionUtils.checkPickup(pickup)) { + throw new ProtocolException("resPickup is error"); + } + if (pickup != null) { + response.getResponse().getAction().getDirectives().add(pickup); + } + if (card != null) { + response.getResponse().setCard(card); + } + return response; + } + + private ResResponse buildEmptyActionResponse(String resVersion, HashMap attributes, + String actionVersion, String actionType, boolean shouldEndSession) { + ResResponse resResponse = new ResResponse(); + resResponse.setVersion(resVersion); + ResSession resSession = new ResSession(); + if (attributes != null && !attributes.isEmpty()) { + resSession.setAttributes(attributes); + } + resResponse.setSession(resSession); + ResResponseContent resResponseContent = new ResResponseContent(); + ResAction resAction; + try { + resAction = ActionUtils.getEmptyAction(actionVersion, actionType, shouldEndSession); + resResponseContent.setAction(resAction); + } catch (ProtocolException e) { + e.printStackTrace(); + } + resResponse.setResponse(resResponseContent); + return resResponse; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ResponseUtils.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ResponseUtils.java new file mode 100644 index 0000000..a367f72 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/common/utils/ResponseUtils.java @@ -0,0 +1,214 @@ +package ai.qiwu.rokid.ruoqi.common.utils; + +import java.util.List; + +import ai.qiwu.rokid.ruoqi.common.exception.ProtocolException; +import ai.qiwu.rokid.ruoqi.model.response.ResResponse; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.mediaitem.ResMediaItem; +import org.apache.commons.lang.StringUtils; +import com.google.gson.GsonBuilder; + + +/** + * @类描述 用于快速构造CloudApp的Response的工具类 + * @对应结构以及命名 Response对应ResResponse:协议内容; response对应ResResponseContent:响应; + * action对应ResAction:事件; voice:文本; media:媒体; confirm:主动询问; + * confirmIntent:主动询问意图(比如询问歌手); confirmSlot:主动询问意图内容(比如歌手); + * optionWords:主动询问辅助信息; 场景化:scen;非场景化:cut + */ +public class ResponseUtils { + + /** + * @方法 构造一个退出应用的协议内容 + * @描述 客户端接收到该协议内容以后会立即退出应用 + * @使用场景 当我们的应用需要退出的时候返回这个协议内容 + * @注意 此协议内容的版本以及事件版本号都已经被固定为RES_VERSION_V2和ACTION_VERSION_V2,如协议版本变更,请自行修正一下;另外应用退出以后,nlp那边的session也会被清理 + * @return + * @throws ProtocolException + */ + public static ResResponse buildExitNowResponse() throws ProtocolException { + return ResponseBuilder.build().finishNow().create(); + } + + /** + * @方法 构造一个空的协议内容,Voice以及Media继续保持原有执行状态 + * @描述 客户端接收到该协议内容以后不会对当前的操作有任何的影响 + * @使用场景 当我们的应用接受到不需要处理,需要忽略的Event请求是,我们可以返回该响应 + * @注意 此协议内容的版本以及事件版本号都已经被固定为RES_VERSION_V2和ACTION_VERSION_V2,如协议版本变更,请自行修正一下,另外此协议内容会的shouldEndSession=false的 + * @return + * @throws ProtocolException + */ + public static ResResponse buildIngoreEventResponse() throws ProtocolException { + return ResponseBuilder.build().create(); + } + + /** + * @方法 播报一句TTS,Media继续保持原有执行状态,并且有EventRequest + * @param voiceId + * tts的ID,可以为空 + * @param voiceContent + * tts 内容 + * @return + * @throws ProtocolException + */ + public static ResResponse buildVoicePlayResponse(String voiceId, String voiceContent) throws ProtocolException { + if (StringUtils.isBlank(voiceContent)) { + throw new ProtocolException("voiceContent Can not be null"); + } + return ResponseBuilder.build().voicePlay(voiceId, voiceContent).create(); + } + + /** + * @方法 暂停播放Voice + * + * @return + * @throws ProtocolException + */ + public static ResResponse buildVoicePauseResponse() throws ProtocolException { + return ResponseBuilder.build().voicePause().create(); + } + + /** + * @方法 继续播放Voice + * + * @return + * @throws ProtocolException + */ + public static ResResponse buildVoiceResumeResponse() throws ProtocolException { + return ResponseBuilder.build().voiceResume().create(); + } + + /** + * @方法 停止播放Voice + * + * @return + * @throws ProtocolException + */ + public static ResResponse buildVoiceStopResponse() throws ProtocolException { + return ResponseBuilder.build().voiceStop().create(); + } + + /** + * @方法 播放Media事件,TTS继续保持原有执行状态, + * + * @param mediaToken + * @param mediaType + * @param mediaUrl + * @param mediaOffset + * @return + */ + public static ResResponse buildMediaPlayResponse(String mediaId, String mediaToken, String mediaType, + String mediaUrl, long mediaOffset) throws ProtocolException { + if (StringUtils.isBlank(mediaUrl)) { + throw new ProtocolException("mediaUrl Can not be null"); + } + if (mediaOffset < 0) { + throw new ProtocolException("mediaOffset Can not be < 0"); + } + if (!ResMediaItem.MEDIA_TYPE_AUDIO.equals(mediaType) && ResMediaItem.MEDIA_TYPE_VIDEO.equals(mediaType)) { + throw new ProtocolException("mediaType is error"); + } + return ResponseBuilder.build().mediaPlay(mediaId, mediaToken, mediaType, mediaUrl, mediaOffset).create(); + } + + /** + * @方法 暂停播放Media + * + * @return + * @throws ProtocolException + */ + public static ResResponse buildMediaPauseResponse() throws ProtocolException { + return ResponseBuilder.build().mediaPause().create(); + } + + /** + * @方法 继续播放Media + * + * @return + * @throws ProtocolException + */ + public static ResResponse buildMediaResumeResponse() throws ProtocolException { + return ResponseBuilder.build().mediaResume().create(); + } + + /** + * @方法 停止播放Media + * + * @return + * @throws ProtocolException + */ + public static ResResponse buildMediaStopResponse() throws ProtocolException { + return ResponseBuilder.build().mediaStop().create(); + } + + /** + * @方法 暂停播放Media和Voice + * + * @return + * @throws ProtocolException + */ + public static ResResponse buildPauseResponse() throws ProtocolException { + return ResponseBuilder.build().voicePause().mediaPause().create(); + } + + /** + * @方法 继续播放Voice和Meida + * + * @return + * @throws ProtocolException + */ + public static ResResponse buildResumeResponse() throws ProtocolException { + return ResponseBuilder.build().voiceResume().mediaResume().create(); + } + + /** + * @方法 停止播放Voice和Media + * + * @return + * @throws ProtocolException + */ + public static ResResponse buildStopResponse() throws ProtocolException { + return ResponseBuilder.build().voiceStop().mediaStop().create(); + } + + /** + * 构造一个Confirm,并且把Media停止 + * + * @param voiceContent + * @param confirmIntent + * 需要在平台上面定义过得intent,不能随便写 + * @param confirmSlot + * 需要在平台上面定义过得slot,不能随便写 + * @param confirmOptionWords + * @return + */ + public static ResResponse buildConfirmOpenResponse(String voiceContent, String confirmIntent, String confirmSlot, + List confirmOptionWords) throws ProtocolException { + if (StringUtils.isBlank(voiceContent)) { + throw new ProtocolException("voiceContent Can not be null"); + } + if (StringUtils.isBlank(confirmIntent)) { + throw new ProtocolException("confirmIntent Can not be null"); + } + if (StringUtils.isBlank(confirmSlot)) { + throw new ProtocolException("confirmSlot Can not be null"); + } + return ResponseBuilder.build().voicePlay(null, voiceContent).mediaStop() + .confirmOpen(confirmIntent, confirmSlot, confirmOptionWords).create(); + } + + /** + * 将ResResponse变成Json字符串 + * + * @param response + * @return + */ + public static String responseToString(ResResponse response) { + if (response != null) { + return new GsonBuilder().disableHtmlEscaping().create().toJson(response); + } else { + return null; + } + + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/controller/RokidController.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/controller/RokidController.java new file mode 100644 index 0000000..384b921 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/controller/RokidController.java @@ -0,0 +1,30 @@ +package ai.qiwu.rokid.ruoqi.controller; + +import ai.qiwu.rokid.ruoqi.model.request.ReqRequest; +import ai.qiwu.rokid.ruoqi.model.response.ResResponse; +import ai.qiwu.rokid.ruoqi.service.RokidRequestParse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author 苗权威 + * @dateTime 19-7-3 下午4:25 + */ +@RestController +public class RokidController { + + private static final Logger logger = LoggerFactory.getLogger(RokidController.class); + + @Autowired + private RokidRequestParse requestParse; + + @RequestMapping("/rokid") + public ResResponse chat(@RequestBody ReqRequest request) { + logger.info("请求消息:"+request.toString()); + return requestParse.getResponse(request); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/ReqRequest.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/ReqRequest.java new file mode 100644 index 0000000..6eface9 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/ReqRequest.java @@ -0,0 +1,77 @@ +package ai.qiwu.rokid.ruoqi.model.request; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.request.context.ReqContext; +import ai.qiwu.rokid.ruoqi.model.request.request.ReqRequestValue; +import ai.qiwu.rokid.ruoqi.model.request.session.ReqSession; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ + +/** + * + * + */ +/** + * @类描述 CloudApp协议,Request对象 + * @说明 Request主要包含四块内容 1、version:CloudApp协议版本; 2、session:当前的会话信息; + * 3、context:设备、用户、以及其他状态信息; 4、request:业务请求内容 + * @param <> + * Slots对象 + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqRequest implements Serializable { + /** + * + */ + private static final long serialVersionUID = -490292141289020844L; + /** + * + */ + private String version;// 协议版本号,当前版本2.0.0 + private ReqSession session;// 会话的信息 + private ReqContext context;// 当前的设备信息,用户信息和应用状态 + private ReqRequestValue request; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public ReqSession getSession() { + return session; + } + + public void setSession(ReqSession session) { + this.session = session; + } + + public ReqContext getContext() { + return context; + } + + public void setContext(ReqContext context) { + this.context = context; + } + + public ReqRequestValue getRequest() { + return request; + } + + public void setRequest(ReqRequestValue request) { + this.request = request; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/ReqContext.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/ReqContext.java new file mode 100644 index 0000000..9853522 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/ReqContext.java @@ -0,0 +1,53 @@ +package ai.qiwu.rokid.ruoqi.model.request.context; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.request.context.application.ReqApplication; +import ai.qiwu.rokid.ruoqi.model.request.context.device.ReqDevice; +import ai.qiwu.rokid.ruoqi.model.request.context.user.ReqUser; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqContext implements Serializable { + /** + * + */ + private static final long serialVersionUID = 5297187036481770538L; + private ReqApplication application; //ApplicationInfo对象,目前只有应用ID + private ReqDevice device;//此次请求发生时当前设备信息的描述 + private ReqUser user;//展示了与当前设备绑定的用户信息,通常是设备对应手机应用的账号 + + public ReqApplication getApplication() { + return application; + } + + public void setApplication(ReqApplication application) { + this.application = application; + } + + public ReqDevice getDevice() { + return device; + } + + public void setDevice(ReqDevice device) { + this.device = device; + } + + public ReqUser getUser() { + return user; + } + + public void setUser(ReqUser user) { + this.user = user; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/application/ReqApplication.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/application/ReqApplication.java new file mode 100644 index 0000000..0394633 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/application/ReqApplication.java @@ -0,0 +1,53 @@ +package ai.qiwu.rokid.ruoqi.model.request.context.application; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.request.context.application.media.ReqApplicationMedia; +import ai.qiwu.rokid.ruoqi.model.request.context.application.voice.ReqApplicationVoice; +import org.apache.commons.lang.builder.ToStringBuilder; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqApplication implements Serializable { + /** + * + */ + private static final long serialVersionUID = -6035458330596077339L; + private String applicationId;// 当前的应用ID + private ReqApplicationMedia media; + private ReqApplicationVoice voice; + + public String getApplicationId() { + return applicationId; + } + + public ReqApplicationMedia getMedia() { + return media; + } + + public ReqApplicationVoice getVoice() { + return voice; + } + + public void setMedia(ReqApplicationMedia media) { + this.media = media; + } + + public void setVoice(ReqApplicationVoice voice) { + this.voice = voice; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/application/media/ReqApplicationMedia.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/application/media/ReqApplicationMedia.java new file mode 100644 index 0000000..1d4739c --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/application/media/ReqApplicationMedia.java @@ -0,0 +1,67 @@ +package ai.qiwu.rokid.ruoqi.model.request.context.application.media; + +import java.io.Serializable; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqApplicationMedia implements Serializable { + public static final String STATE_PLAYING = "PLAYING";// 当前在播放状态 + public static final String STATE_PAUSED = "PAUSED";// 当前播放器在暂停状态 + public static final String STATE_IDLE = "IDLE";// 当前播放器状态在闲置状态 + public static final String STATE_UNKNOW = "UNKNOW";// 未知状态 + /** + * + */ + private static final long serialVersionUID = -6035458330596077339L; + private String state;// "PLAYING / PAUSED / IDLE", + private String itemId; + private String token; + private Long progress;// 毫秒 + private Long duration;// 毫秒 + + public String getState() { + return state; + } + + public String getItemId() { + return itemId; + } + + public String getToken() { + return token; + } + + public Long getProgress() { + return progress; + } + + public void setProgress(Long progress) { + this.progress = progress; + } + + public Long getDuration() { + return duration; + } + + public void setDuration(Long duration) { + this.duration = duration; + } + + public void setState(String state) { + this.state = state; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public void setToken(String token) { + this.token = token; + } + +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/application/voice/ReqApplicationVoice.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/application/voice/ReqApplicationVoice.java new file mode 100644 index 0000000..aed30af --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/application/voice/ReqApplicationVoice.java @@ -0,0 +1,45 @@ +package ai.qiwu.rokid.ruoqi.model.request.context.application.voice; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqApplicationVoice implements Serializable { + public static final String STATE_PLAYING = "PLAYING";// 当前在播放状态 + public static final String STATE_PAUSED = "PAUSED";// 当前播放器在暂停状态 + public static final String STATE_IDLE = "IDLE";// 当前播放器状态在闲置状态 + public static final String STATE_UNKNOW = "UNKNOW";// 未知状态 + /** + * + */ + private static final long serialVersionUID = -6035458330596077339L; + private String state;// "PLAYING / PAUSED / IDLE", + private String itemId; + + public String getState() { + return state; + } + + public String getItemId() { + return itemId; + } + + public void setState(String state) { + this.state = state; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/ReqDevice.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/ReqDevice.java new file mode 100644 index 0000000..958b9da --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/ReqDevice.java @@ -0,0 +1,73 @@ +package ai.qiwu.rokid.ruoqi.model.request.context.device; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.request.context.device.basic.ReqBasic; +import ai.qiwu.rokid.ruoqi.model.request.context.device.location.ReqLocation; +import ai.qiwu.rokid.ruoqi.model.request.context.device.media.ReqMedia; +import ai.qiwu.rokid.ruoqi.model.request.context.device.screen.ReqScreen; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqDevice implements Serializable { + /** + * + */ + private static final long serialVersionUID = -3966116657482862685L; + private ReqBasic basic;// 展示了当前设备的基础信息,主要包含设备制造信息、时间信息、国家文字信息。 + private ReqScreen screen;// 展示了当前设备的屏幕信息,主要包含屏幕的分辨率信息。 + private ReqMedia media;// 向CloudApp表明当前设备上CloudAppClient中的MediaPlayer的状态信息。 + private ReqMedia voice;// 向CloudApp表明当前设备上CloudAppClient中的Voice的状态信息。 + private ReqLocation location;// 位置信息,现在只有一个经纬度 + + public ReqBasic getBasic() { + return basic; + } + + public void setBasic(ReqBasic basic) { + this.basic = basic; + } + + public ReqScreen getScreen() { + return screen; + } + + public void setScreen(ReqScreen screen) { + this.screen = screen; + } + + public ReqMedia getMedia() { + return media; + } + + public void setMedia(ReqMedia media) { + this.media = media; + } + + public ReqMedia getVoice() { + return voice; + } + + public void setVoice(ReqMedia voice) { + this.voice = voice; + } + + public ReqLocation getLocation() { + return location; + } + + public void setLocation(ReqLocation location) { + this.location = location; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/basic/ReqBasic.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/basic/ReqBasic.java new file mode 100644 index 0000000..5e430be --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/basic/ReqBasic.java @@ -0,0 +1,84 @@ +package ai.qiwu.rokid.ruoqi.model.request.context.device.basic; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqBasic implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String vendor;// 注册生产商ID + private String deviceType;// 该生产商设定的设备型号 + private String deviceId;// 该型号下的设备ID + private String locale;// 国家及语言,标准locale格式 + private Long timestamp;// 设备当前时间,unix timestamp + private String masterId;// 设备主人的Id; + private String voicetrigger;// 设备当前激活词 + + public String getVendor() { + return vendor; + } + + public void setVendor(String vendor) { + this.vendor = vendor; + } + + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getLocale() { + return locale; + } + + public void setLocale(String locale) { + this.locale = locale; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + public String getMasterId() { + return masterId; + } + + public void setMasterId(String masterId) { + this.masterId = masterId; + } + + public String getVoicetrigger() { + return voicetrigger; + } + + public void setVoicetrigger(String voicetrigger) { + this.voicetrigger = voicetrigger; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/location/ReqLocation.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/location/ReqLocation.java new file mode 100644 index 0000000..76bc9f8 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/location/ReqLocation.java @@ -0,0 +1,142 @@ +package ai.qiwu.rokid.ruoqi.model.request.context.device.location; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqLocation implements Serializable { + /** + * + */ + private static final long serialVersionUID = -7136610825306612078L; + private String longitude;// 经度 + private String latitude;// 纬度 + private String country;// 国家 + private String state;// 州/省份 + private String city;// 城市 + private String area;// 区县 + private String district;// 地区,行政 + private String street;// 街道 + private String timeZone;//时区 + + + + public String getLongitude() { + return longitude; + } + + + + public void setLongitude(String longitude) { + this.longitude = longitude; + } + + + + public String getLatitude() { + return latitude; + } + + + + public void setLatitude(String latitude) { + this.latitude = latitude; + } + + + + public String getCountry() { + return country; + } + + + + public void setCountry(String country) { + this.country = country; + } + + + + public String getState() { + return state; + } + + + + public void setState(String state) { + this.state = state; + } + + + + public String getCity() { + return city; + } + + + + public void setCity(String city) { + this.city = city; + } + + + + public String getArea() { + return area; + } + + + + public void setArea(String area) { + this.area = area; + } + + + + public String getDistrict() { + return district; + } + + + + public void setDistrict(String district) { + this.district = district; + } + + + + public String getStreet() { + return street; + } + + + + public void setStreet(String street) { + this.street = street; + } + + + + public String getTimeZone() { + return timeZone; + } + + + + public void setTimeZone(String timeZone) { + this.timeZone = timeZone; + } + + + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/media/ReqMedia.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/media/ReqMedia.java new file mode 100644 index 0000000..af9eea6 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/media/ReqMedia.java @@ -0,0 +1,40 @@ +package ai.qiwu.rokid.ruoqi.model.request.context.device.media; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 25/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqMedia implements Serializable { + public static final String STATE_PLAYING = "PLAYING";// 当前在播放状态 + public static final String STATE_PAUSED = "PAUSED";// 当前播放器在暂停状态 + public static final String STATE_IDLE = "IDLE";//当前播放器状态在闲置状态 + public static final String STATE_UNKNOW = "UNKNOW";// 未知状态 + /** + * + */ + private static final long serialVersionUID = -6588484011026696932L; + private String state;// PLAYING PAUSED IDLE + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public boolean isPlaying() { + return STATE_PLAYING.equals(state); + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/screen/ReqScreen.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/screen/ReqScreen.java new file mode 100644 index 0000000..36ce6da --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/device/screen/ReqScreen.java @@ -0,0 +1,41 @@ +package ai.qiwu.rokid.ruoqi.model.request.context.device.screen; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 25/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqScreen implements Serializable { + /** + * + */ + private static final long serialVersionUID = 3108410377906776393L; + private String x;//X 方向上的像素大小 + private String y;//Y 方向上的像素大小 + + public String getX() { + return x; + } + + public void setX(String x) { + this.x = x; + } + + public String getY() { + return y; + } + + public void setY(String y) { + this.y = y; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/user/ReqUser.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/user/ReqUser.java new file mode 100644 index 0000000..42431ac --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/context/user/ReqUser.java @@ -0,0 +1,32 @@ +package ai.qiwu.rokid.ruoqi.model.request.context.user; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqUser implements Serializable { + /** + * + */ + private static final long serialVersionUID = 675958584565674347L; + private String userId;//用户ID + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/ReqRequestValue.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/ReqRequestValue.java new file mode 100644 index 0000000..e286d74 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/ReqRequestValue.java @@ -0,0 +1,55 @@ +package ai.qiwu.rokid.ruoqi.model.request.request; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.request.request.content.ReqRequestContent; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqRequestValue implements Serializable { + /** + * + */ + private static final long serialVersionUID = -6876155972421972250L; + public static final String REQTYPE_INTENT = "INTENT"; + public static final String REQTYPE_EVENT = "EVENT"; + private String reqType;// 表明请求的类型: INTENT 和 EVENT 分别对应 IntentRequest 和 + // EventRequest。 + private String reqId;// 每次请求都会对应一个唯一ID用以区分每一次的请求。请求ID将会与返回ID一一对应。 + private ReqRequestContent content;// IntentRequest 或 EventRequest的对象 + + public String getReqType() { + return reqType; + } + + public void setReqType(String reqType) { + this.reqType = reqType; + } + + public String getReqId() { + return reqId; + } + + public void setReqId(String reqId) { + this.reqId = reqId; + } + + public ReqRequestContent getContent() { + return content; + } + + public void setContent(ReqRequestContent content) { + this.content = content; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/ReqRequestContent.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/ReqRequestContent.java new file mode 100644 index 0000000..e0e0c7e --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/ReqRequestContent.java @@ -0,0 +1,78 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content; + +import java.io.Serializable; +import java.util.HashMap; + +import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.ReqEventExtra; +import ai.qiwu.rokid.ruoqi.model.request.request.content.slot.Slot; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqRequestContent implements Serializable { + /** + * + */ + private static final long serialVersionUID = -8296524576831663917L; + /** + * @see ai.qiwu.rokid.ruoqi.model.request.request.content.enums + */ + private String intent;// IntentRequest,CloudApp 对应的 nlp intent + private HashMap slots; + private String sentence;// asr 语音内容 + /** + * @see ai.qiwu.rokid.ruoqi.model.request.request.content.enums + */ + private String event; // EventRequest,事件类型 + private ReqEventExtra extra;// EventRequest + + public String getIntent() { + return intent; + } + + public void setIntent(String intent) { + this.intent = intent; + } + + public HashMap getSlots() { + return slots; + } + + public void setSlots(HashMap slots) { + this.slots = slots; + } + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } + + public ReqEventExtra getExtra() { + return extra; + } + + public void setExtra(ReqEventExtra extra) { + this.extra = extra; + } + + public String getSentence() { + return sentence; + } + + public void setSentence(String sentence) { + this.sentence = sentence; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidEventCommonEnums.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidEventCommonEnums.java new file mode 100644 index 0000000..c6fd356 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidEventCommonEnums.java @@ -0,0 +1,56 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content.enums; + +import org.apache.commons.lang.StringUtils; + +public enum RokidEventCommonEnums { + + // EVENT + SKILL_EXIT_EVENT("Skill.EXIT", "skillSuspendEvent", "EventRequest,event=Skill.EXIT"), // 当应用挂起的时候 TODO 需要修改名字 + + SKILL_SUSPEND_EVENT("Skill.SUSPEND", "skillSuspendEvent", "EventRequest,event=Skill.SUSPEND"), // 当应用挂起的时候的事件 + + SESSION_ENDED_EVENT("Session.ENDED", "sessionEndedEvent", "EventRequest,event=Session.ENDED");// 当Domain被切换到的时候的事件,可以用于关闭资源 + + private String event; + private String methodName; + private String cnHit; // 中文提示,仅作阅读代码的提示。 + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public String getCnHit() { + return cnHit; + } + + public void setCnHit(String cnHit) { + this.cnHit = cnHit; + } + + RokidEventCommonEnums(String event, String methodName, String cnHit) { + this.event = event; + this.methodName = methodName; + this.cnHit = cnHit; + } + + public static RokidEventCommonEnums convert(String event) { + for (RokidEventCommonEnums v : RokidEventCommonEnums.values()) { + if (StringUtils.equals(v.event, event)) { + return v; + } + } + return null; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidEventMediaEnums.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidEventMediaEnums.java new file mode 100644 index 0000000..9456ef8 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidEventMediaEnums.java @@ -0,0 +1,58 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content.enums; + +import org.apache.commons.lang.StringUtils; + +public enum RokidEventMediaEnums { + + // EVENT + MEDIA_STARTED_EVENT("Media.STARTED", "mediaStartedEvent", "EventRequest,event=Media.STARTED"), // 当MediaPlayer开始播放时发生。 + + MEDIA_FAILED_EVENT("Media.FAILED", "mediaFailedEvent", "EventRequest,event=Media.FAILED"), // 当MediaPlayer播放失败时发生。 + + MEDIA_PAUSED_EVENT("Media.PAUSED", "mediaPausedEvent", "EventRequest,event=Media.PAUSED"), // 当MediaPlayer中途停止时发生。 + + MEDIA_FINISHED_EVENT("Media.FINISHED", "mediaFinishedEvent", "EventRequest,event=Media.FINISHED");// 当播放内容结束时发生。 + + private String event; + private String methodName; + private String cnHit; // 中文提示,仅作阅读代码的提示。 + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public String getCnHit() { + return cnHit; + } + + public void setCnHit(String cnHit) { + this.cnHit = cnHit; + } + + RokidEventMediaEnums(String event, String methodName, String cnHit) { + this.event = event; + this.methodName = methodName; + this.cnHit = cnHit; + } + + public static RokidEventMediaEnums convert(String event) { + for (RokidEventMediaEnums v : RokidEventMediaEnums.values()) { + if (StringUtils.equals(v.event, event)) { + return v; + } + } + return null; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidEventVoiceEnums.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidEventVoiceEnums.java new file mode 100644 index 0000000..af98f08 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidEventVoiceEnums.java @@ -0,0 +1,56 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content.enums; + +import org.apache.commons.lang.StringUtils; + +public enum RokidEventVoiceEnums { + + // EVENT + VOICE_STARTED_EVENT("Voice.STARTED", "voiceStartedEvent", "EventRequest,event=Voice.STARTED"), // 当Voice开始播放时发生。 + + VOICE_FAILED_EVENT("Voice.FAILED", "voiceFailedEvent", "EventRequest,event=Voice.FAILED"), // 当Voice播放失败时发生。 + + VOICE_FINISHED_EVENT("Voice.FINISHED", "voiceFinishedEvent", "EventRequest,event=Voice.FINISHED"); // 当Voice播放内容结束时发生。 + + private String event; + private String methodName; + private String cnHit; // 中文提示,仅作阅读代码的提示。 + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public String getCnHit() { + return cnHit; + } + + public void setCnHit(String cnHit) { + this.cnHit = cnHit; + } + + RokidEventVoiceEnums(String event, String methodName, String cnHit) { + this.event = event; + this.methodName = methodName; + this.cnHit = cnHit; + } + + public static RokidEventVoiceEnums convert(String event) { + for (RokidEventVoiceEnums v : RokidEventVoiceEnums.values()) { + if (StringUtils.equals(v.event, event)) { + return v; + } + } + return null; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidIntentCommonEnums.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidIntentCommonEnums.java new file mode 100644 index 0000000..acbbada --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidIntentCommonEnums.java @@ -0,0 +1,60 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content.enums; + +import org.apache.commons.lang.StringUtils; + +/** + * 系统级的Intent事件 + * + * @author Bassam + * + */ +public enum RokidIntentCommonEnums { + WELECOME_INTENT("ROKID.INTENT.WELCOME", "appStartIntent", "打开应用事件"), // 通过激活词打开应用时会发送这个Intent + + UNKONWN_INTENT("ROKID.INTENT.UNKNOWN", "unkonwnIntent", "未知意图的Intent事件"), // 未知意图的Intent事件,当Skill开启PickUp以后,用户三次处理都出错,会命中该Intent + + EXIT_INTENT("ROKID.INTENT.EXIT", "appStopIntent", "退出应用事件");// Skill退出请求 + + private String intent; + private String methodName; + private String cnHit; // 中文提示,仅作阅读代码的提示。 + + public String getIntent() { + return intent; + } + + public void setIntent(String intent) { + this.intent = intent; + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public String getCnHit() { + return cnHit; + } + + public void setCnHit(String cnHit) { + this.cnHit = cnHit; + } + + RokidIntentCommonEnums(String intent, String methodName, String cnHit) { + this.intent = intent; + this.methodName = methodName; + this.cnHit = cnHit; + } + + public static RokidIntentCommonEnums convert(String intent) { + for (RokidIntentCommonEnums v : RokidIntentCommonEnums.values()) { + if (StringUtils.equals(v.intent, intent)) { + return v; + } + } + return null; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidIntentMediaEnums.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidIntentMediaEnums.java new file mode 100644 index 0000000..3f328f8 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/enums/RokidIntentMediaEnums.java @@ -0,0 +1,76 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content.enums; + +import org.apache.commons.lang.StringUtils; + +/** + * 系统级的Intent事件 + * + * @author Bassam + * + */ +public enum RokidIntentMediaEnums { + RESUME_INTENT("ROKID.INTENT.AUDIO_RESUME", "resumeIntent", "继续播放事件"), + + PAUSE_INTENT("ROKID.INTENT.AUDIO_PAUSE", "pauseIntent", "暂停播放事件"), + + STOP_INTENT("ROKID.INTENT.AUDIO_CANCEL", "stopIntent", "取消播放事件"), + + LOOP_INTENT("ROKID.INTENT.AUDIO_LOOPON", "loopIntent", "循环播放事件"), + + LOOPOFF_INTENT("ROKID.INTENT.AUDIO_LOOPOFF", "loopOffIntent", "取消循环播放事件"), + + NEXT_INTENT("ROKID.INTENT.AUDIO_NEXT", "nextIntent", "下一首播放事件"), + + PREVIOUS_INTENT("ROKID.INTENT.AUDIO_PREVIOUS", "previousIntent", "上一首播放事件"), + + REPEAT_INTENT("ROKID.INTENT.AUDIO_REPEAT", "repeatIntent", "重复播放事件"), + + STARTOVER_INTENT("ROKID.INTENT.AUDIO_STARTOVER", "startOverIntent", "重新播放事件"), + + SHUFFLE_INTENT("ROKID.INTENT.AUDIO_SHUFFLEON", "shuffleIntent", "随机播放事件"), + + SHUFFLEOFF_INTENT("ROKID.INTENT.AUDIO_SHUFFLEOFF", "shuffleOffIntent", "关闭随机播放事件"); + + private String intent; + private String methodName; + private String cnHit; // 中文提示,仅作阅读代码的提示。 + + public String getIntent() { + return intent; + } + + public void setIntent(String intent) { + this.intent = intent; + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public String getCnHit() { + return cnHit; + } + + public void setCnHit(String cnHit) { + this.cnHit = cnHit; + } + + RokidIntentMediaEnums(String intent, String methodName, String cnHit) { + this.intent = intent; + this.methodName = methodName; + this.cnHit = cnHit; + } + + public static RokidIntentMediaEnums convert(String intent) { + for (RokidIntentMediaEnums v : RokidIntentMediaEnums.values()) { + if (StringUtils.equals(v.intent, intent)) { + return v; + } + } + return null; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/extra/ReqEventExtra.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/extra/ReqEventExtra.java new file mode 100644 index 0000000..739cf69 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/extra/ReqEventExtra.java @@ -0,0 +1,45 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content.extra; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.media.ReqExtraMedia; +import ai.qiwu.rokid.ruoqi.model.request.request.content.extra.voice.ReqExtraVoice; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqEventExtra implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -6312382694862019116L; + + private ReqExtraMedia media; + private ReqExtraVoice voice; + + public ReqExtraMedia getMedia() { + return media; + } + + public void setMedia(ReqExtraMedia media) { + this.media = media; + } + + public ReqExtraVoice getVoice() { + return voice; + } + + public void setVoice(ReqExtraVoice voice) { + this.voice = voice; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/extra/media/ReqExtraMedia.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/extra/media/ReqExtraMedia.java new file mode 100644 index 0000000..b401972 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/extra/media/ReqExtraMedia.java @@ -0,0 +1,57 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content.extra.media; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqExtraMedia implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -4201471138232339064L; + private String itemId; + private String token; + private String progress; + private String duration; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getProgress() { + return progress; + } + + public void setProgress(String progress) { + this.progress = progress; + } + + public String getDuration() { + return duration; + } + + public void setDuration(String duration) { + this.duration = duration; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/extra/voice/ReqExtraVoice.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/extra/voice/ReqExtraVoice.java new file mode 100644 index 0000000..6778d99 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/extra/voice/ReqExtraVoice.java @@ -0,0 +1,32 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content.extra.voice; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqExtraVoice implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 4975096988067404659L; + + private String itemId; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/slot/Slot.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/slot/Slot.java new file mode 100644 index 0000000..bd9d4cd --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/content/slot/Slot.java @@ -0,0 +1,38 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.content.slot; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class Slot implements Serializable { + /** + * + */ + private static final long serialVersionUID = 8124321322315914064L; + private String type; + private String value; + + public String getType() { + return type; + } + + public String getValue() { + return value; + } + + public void setType(String type) { + this.type = type; + } + + public void setValue(String value) { + this.value = value; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/enums/RokidRequestTypeEnums.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/enums/RokidRequestTypeEnums.java new file mode 100644 index 0000000..a1d69e1 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/request/enums/RokidRequestTypeEnums.java @@ -0,0 +1,40 @@ +package ai.qiwu.rokid.ruoqi.model.request.request.enums; + +import org.apache.commons.lang.StringUtils; + +/** + * 请求类型 + * + * @author Bassam + * + */ +public enum RokidRequestTypeEnums { + EVENT_REQUEST("EVENT", "事件类型"), // 通过激活词打开应用时会发送这个Intent + + INTENT_REQUEST("INTENT", "语音请求类型"); + + private String type; + private String cnHit; // 中文提示,仅作阅读代码的提示。 + + public String getCnHit() { + return cnHit; + } + + public void setCnHit(String cnHit) { + this.cnHit = cnHit; + } + + RokidRequestTypeEnums(String type, String cnHit) { + this.type = type; + this.cnHit = cnHit; + } + + public static RokidRequestTypeEnums convert(String type) { + for (RokidRequestTypeEnums v : RokidRequestTypeEnums.values()) { + if (StringUtils.equals(v.type, type)) { + return v; + } + } + return null; + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/session/ReqSession.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/session/ReqSession.java new file mode 100644 index 0000000..4f2e6b3 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/request/session/ReqSession.java @@ -0,0 +1,49 @@ +package ai.qiwu.rokid.ruoqi.model.request.session; +import java.io.Serializable; +import java.util.HashMap; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReqSession implements Serializable { + /** + * + */ + private static final long serialVersionUID = -845013936250311340L; + private String sessionId;//每次会话的唯一ID,由系统填充 + private boolean newSession;//是否是新会话 + private HashMap attributes;//为CloudApp提供attributes字段留保存上下文信息的字段 + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public boolean isNewSession() { + return newSession; + } + + public void setNewSession(boolean newSession) { + this.newSession = newSession; + } + + public HashMap getAttributes() { + return attributes; + } + + public void setAttributes(HashMap attributes) { + this.attributes = attributes; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/ResResponse.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/ResResponse.java new file mode 100644 index 0000000..1fc49e3 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/ResResponse.java @@ -0,0 +1,71 @@ +package ai.qiwu.rokid.ruoqi.model.response; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.response.response.ResResponseContent; +import ai.qiwu.rokid.ruoqi.model.response.session.ResSession; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResResponse implements Serializable { + public static final String RES_VERSION_V2 = "2.0.0";// 协议版本 + + + /** + * + */ + private static final long serialVersionUID = -4299224159622592090L; + private String version;// 表明了Response协议的版本,必须由 CloudApp 填充。当前协议版本是 2.0.0. + private ResSession session;// 表示当前应用的session,与Request中的信息一致,CloudApp 可以在 + // attributes 里填充自己需要的上下文信息用于后面的请求。 + private ResResponseContent response;// 返回给 CloudAppClient 的Response内容。包括了 + // card 和 action 两个部分。card + // 会在之后的协议更新中作详细说明。 + + public ResResponse() { + ResSession resSession = new ResSession(); + this.session = resSession; + ResResponseContent resResponseContent = new ResResponseContent(); + this.response = resResponseContent; + } + + public ResResponse(String resVersion) { + this(); + this.version = resVersion; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public ResSession getSession() { + return session; + } + + public void setSession(ResSession session) { + this.session = session; + } + + public ResResponseContent getResponse() { + return response; + } + + public void setResponse(ResResponseContent response) { + this.response = response; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/ResResponseContent.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/ResResponseContent.java new file mode 100644 index 0000000..8ff6d65 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/ResResponseContent.java @@ -0,0 +1,44 @@ +package ai.qiwu.rokid.ruoqi.model.response.response; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.response.response.action.ResAction; +import ai.qiwu.rokid.ruoqi.model.response.response.card.ResCard; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResResponseContent implements Serializable { + /** + * + */ + private static final long serialVersionUID = -1480333446516655906L; + private ResCard card; + private ResAction action;//voice 和 media。voice 表示了语音交互的返回。media 是对媒体播放的返回。 + public ResCard getCard() { + return card; + } + + public void setCard(ResCard card) { + this.card = card; + } + + public ResAction getAction() { + return action; + } + + public void setAction(ResAction action) { + this.action = action; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/ResAction.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/ResAction.java new file mode 100644 index 0000000..c8b1eac --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/ResAction.java @@ -0,0 +1,81 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.action; +import java.io.Serializable; +import java.util.List; + +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.ResDirective; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResAction implements Serializable { + /** + * + */ + private static final long serialVersionUID = 8270863105569783649L; + public static final String ACTION_TYPE_NORMAL = "NORMAL"; + public static final String ACTION_TYPE_EXIT = "EXIT"; + public static final String ACTION_VERSION_V2 = "2.0.0";// 协议版本 + + private String version;// "version": "2.0.0", + private String type;// 当前action的类型:NORMAL 或 EXIT。 当 type 是 NORMAL 时,voice 和 + // media 会同时执行;当 type 是 EXIT + // 时,action会立即退出,并且在这种情况下,voice 和 media 将会被会被忽略 + private String form;// 当前action的展现形式:scene、cut、service。scene的action会在被打断后压栈,cut的action会在被打断后直接结束,service会在后台执行,但没有任何界面。该字段在技能创建时被确定,无法由cloud + // app更改。 + private boolean shouldEndSession;// 表明当此次返回的action执行完后 CloudAppClient + // 是否要退出,同时,当 shouldEndSession 为 true + // 时,CloudAppClient 将会忽略 + // EventRequests,即在action执行过程中不会产生 + // EventRequest。 + private List directives;// 行为操作 + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getForm() { + return form; + } + + public void setForm(String form) { + this.form = form; + } + + public boolean isShouldEndSession() { + return shouldEndSession; + } + + public void setShouldEndSession(boolean shouldEndSession) { + this.shouldEndSession = shouldEndSession; + } + + public List getDirectives() { + return directives; + } + + public void setDirectives(List directives) { + this.directives = directives; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/ResDirective.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/ResDirective.java new file mode 100644 index 0000000..2a0273d --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/ResDirective.java @@ -0,0 +1,31 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.action.directive; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public abstract class ResDirective implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = -4528558462654915554L; + private String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/confirm/ResConfirm.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/confirm/ResConfirm.java new file mode 100644 index 0000000..41f756d --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/confirm/ResConfirm.java @@ -0,0 +1,58 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.action.directive.confirm; + +import java.io.Serializable; +import java.util.List; + +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.ResDirective; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + + + +/** + * Created by Bassam on 25/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResConfirm extends ResDirective implements Serializable { + public ResConfirm() { + setType("confirm"); + } + /** + * + */ + private static final long serialVersionUID = 8416039262704445675L; + private String confirmIntent; + private String confirmSlot; + private List optionWords; + + public String getConfirmIntent() { + return confirmIntent; + } + + public void setConfirmIntent(String confirmIntent) { + this.confirmIntent = confirmIntent; + } + + public String getConfirmSlot() { + return confirmSlot; + } + + public void setConfirmSlot(String confirmSlot) { + this.confirmSlot = confirmSlot; + } + + public List getOptionWords() { + return optionWords; + } + + public void setOptionWords(List optionWords) { + this.optionWords = optionWords; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/display/ResDisplay.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/display/ResDisplay.java new file mode 100644 index 0000000..1132c09 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/display/ResDisplay.java @@ -0,0 +1,54 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.action.directive.display; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.ResDirective; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + +/** + * Created by Bassam on 25/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResDisplay extends ResDirective implements Serializable { + /** + * + */ + private static final long serialVersionUID = -2540353337364483125L; + private String action; + private boolean needEventCallback; + private long duration; + public ResDisplay() { + setType("display"); + } + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public boolean isNeedEventCallback() { + return needEventCallback; + } + + public void setNeedEventCallback(boolean needEventCallback) { + this.needEventCallback = needEventCallback; + } + + public long getDuration() { + return duration; + } + + public void setDuration(long duration) { + this.duration = duration; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/media/ResMedia.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/media/ResMedia.java new file mode 100644 index 0000000..ee8fc66 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/media/ResMedia.java @@ -0,0 +1,61 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.ResDirective; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.mediaitem.ResMediaItem; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + +/** + * Created by Bassam on 25/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResMedia extends ResDirective implements Serializable { + public static final String MEDIA_ACTION_PLAY = "PLAY";// 从头开始播放操作,最好带上MediaItem,否则一旦设备那边没有Item,则会出错 + public static final String MEDIA_ACTION_PAUSE = "PAUSE";// 暂停播放操作,暂停当前的Media播放 + public static final String MEDIA_ACTION_RESUME = "RESUME";// 继续播放操作,继续当前的播放,需要注意的是客户端那边必须要有MediaItem,否则会出错(可以校验一下当前的Media状态是否是PAUSE的状态) + public static final String MEDIA_ACTION_STOP = "STOP";// 停止播放操作,停止当前的Media播放 + /** + * + */ + private static final long serialVersionUID = -8814555042830620352L; + private boolean disableEvent; + private String action; + private ResMediaItem item; + + public ResMedia() { + setType("media"); + } + + public boolean isDisableEvent() { + return disableEvent; + } + + public void setDisableEvent(boolean disableEvent) { + this.disableEvent = disableEvent; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public ResMediaItem getItem() { + return item; + } + + public void setItem(ResMediaItem item) { + this.item = item; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/media/mediaitem/ResMediaItem.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/media/mediaitem/ResMediaItem.java new file mode 100644 index 0000000..451095a --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/media/mediaitem/ResMediaItem.java @@ -0,0 +1,70 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.action.directive.media.mediaitem; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 25/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResMediaItem implements Serializable { + public static String MEDIA_TYPE_AUDIO = "AUDIO"; + public static String MEDIA_TYPE_VIDEO = "VIDEO"; + /** + * + */ + private static final long serialVersionUID = -5505517316901645087L; + private String itemId; + private String token; + private String type; + private String url; + private Long offsetInMilliseconds; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Long getOffsetInMilliseconds() { + return offsetInMilliseconds; + } + + public void setOffsetInMilliseconds(Long offsetInMilliseconds) { + this.offsetInMilliseconds = offsetInMilliseconds; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/pickup/ResPickup.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/pickup/ResPickup.java new file mode 100644 index 0000000..46c2077 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/pickup/ResPickup.java @@ -0,0 +1,55 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.action.directive.pickup; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.ResDirective; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResPickup extends ResDirective implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -1498955831240619651L; + private boolean enable; + private Long durationInMilliseconds; + private String retryTts;// 重试一次的TTS + + public ResPickup() { + setType("pickup"); + } + + public boolean isEnable() { + return enable; + } + + public void setEnable(boolean enable) { + this.enable = enable; + } + + public Long getDurationInMilliseconds() { + return durationInMilliseconds; + } + + public void setDurationInMilliseconds(Long durationInMilliseconds) { + this.durationInMilliseconds = durationInMilliseconds; + } + + public String getRetryTts() { + return retryTts; + } + + public void setRetryTts(String retryTts) { + this.retryTts = retryTts; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/voice/ResVoice.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/voice/ResVoice.java new file mode 100644 index 0000000..106d66f --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/voice/ResVoice.java @@ -0,0 +1,60 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.ResDirective; +import ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.item.ResVoiceItem; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 25/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResVoice extends ResDirective implements Serializable { + public static final String VOICE_ACTION_PLAY = "PLAY";// 从头开始播放操作,最好带上VoiceItem,否则一旦设备那边没有Item,则会出错 + public static final String VOICE_ACTION_PAUSE = "PAUSE";// 暂停播放操作,暂停当前的Voice播放 + public static final String VOICE_ACTION_RESUME = "RESUME";// 继续播放操作,继续当前的播放,需要注意的是客户端那边必须要有VoiceItem,否则会出错(可以校验一下当前的Voice状态是否是PAUSE的状态) + public static final String VOICE_ACTION_STOP = "STOP";// 停止播放操作,停止当前的VOICE播放 + /** + * + */ + private static final long serialVersionUID = -5413825634268582630L; + private boolean disableEvent; + private String action;// 播放控制操作 "PLAY/PAUSE/RESUME/STOP" + private ResVoiceItem item;// tts 内容 + + public ResVoice() { + setType("voice"); + } + + public boolean isDisableEvent() { + return disableEvent; + } + + public void setDisableEvent(boolean disableEvent) { + this.disableEvent = disableEvent; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public ResVoiceItem getItem() { + return item; + } + + public void setItem(ResVoiceItem item) { + this.item = item; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/voice/item/ResVoiceItem.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/voice/item/ResVoiceItem.java new file mode 100644 index 0000000..f6e7aba --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/action/directive/voice/item/ResVoiceItem.java @@ -0,0 +1,41 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.action.directive.voice.item; + +import java.io.Serializable; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + +/** + * Created by Bassam on 25/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResVoiceItem implements Serializable { + /** + * + */ + private static final long serialVersionUID = -2690547231606519182L; + private String itemId; + private String tts; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getTts() { + return tts; + } + + public void setTts(String tts) { + this.tts = tts; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/card/ResCard.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/card/ResCard.java new file mode 100644 index 0000000..b20d703 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/card/ResCard.java @@ -0,0 +1,41 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.card; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 25/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResCard implements Serializable { + /** + * + */ + private static final long serialVersionUID = -7191961608130764058L; + private String version; + private String type; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/card/chat/ResChatCard.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/card/chat/ResChatCard.java new file mode 100644 index 0000000..3da0bf1 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/response/card/chat/ResChatCard.java @@ -0,0 +1,43 @@ +package ai.qiwu.rokid.ruoqi.model.response.response.card.chat; + +import java.io.Serializable; + +import ai.qiwu.rokid.ruoqi.model.response.response.card.ResCard; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + + + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResChatCard extends ResCard implements Serializable { + private static final String CARD_TYPE = "chat"; + /** + * + */ + private static final long serialVersionUID = -5802546637629946742L; + + public ResChatCard() { + setType(CARD_TYPE); + } + + public ResChatCard(String tts) { + setType(CARD_TYPE); + setContent(getTTSContent(tts)); + } + + private String content; + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + private String getTTSContent(String tts) { + return tts.replaceAll("<[^>]*>", "").replaceAll("\\[[^]]*\\]", ""); + } + +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/session/ResSession.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/session/ResSession.java new file mode 100644 index 0000000..06679e4 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/model/response/session/ResSession.java @@ -0,0 +1,33 @@ +package ai.qiwu.rokid.ruoqi.model.response.session; + +import java.io.Serializable; +import java.util.HashMap; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.map.annotate.JsonSerialize; + +/** + * Created by Bassam on 15/03/2017. + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResSession implements Serializable { + /** + * + */ + private static final long serialVersionUID = -716289067923877883L; + private HashMap attributes; + + public HashMap getAttributes() { + return attributes; + } + + public void setAttributes(HashMap attributes) { + this.attributes = attributes; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/service/RokidRequestParse.java b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/service/RokidRequestParse.java new file mode 100644 index 0000000..2109f81 --- /dev/null +++ b/ruoqi/src/main/java/ai/qiwu/rokid/ruoqi/service/RokidRequestParse.java @@ -0,0 +1,94 @@ +package ai.qiwu.rokid.ruoqi.service; + +import ai.qiwu.rokid.ruoqi.common.Constants; +import ai.qiwu.rokid.ruoqi.common.exception.RokidException; +import ai.qiwu.rokid.ruoqi.common.utils.ProtocolUtils; +import ai.qiwu.rokid.ruoqi.model.request.ReqRequest; +import ai.qiwu.rokid.ruoqi.model.response.ResResponse; +import ai.qiwu.rokid.ruoqi.model.response.response.action.ResAction; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.HashMap; + +/** + * @author 苗权威 + * @dateTime 19-7-2 下午7:27 + */ +@Service("requestParse") +public class RokidRequestParse { + + private static final Logger logger = LoggerFactory.getLogger(RokidRequestParse.class); + + public ResResponse getResponse(ReqRequest request) { + String userWord = request.getRequest().getContent().getSentence(); + String userId = request.getContext().getUser().getUserId(); + try { + return requestTerminate(userWord, userId); + } catch (RokidException e) { + logger.info("出错:"+e.toString()); + return ProtocolUtils.igonre(); + } + } + + private ResResponse requestTerminate(String word, String userId) throws RokidException { + String audioUrl = ""; + String textContent = "请说推荐作品"; + CloseableHttpClient httpClient = null; + CloseableHttpResponse httpResponse = null; + try { + httpClient = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE); + + HashMap params = new HashMap<>(); + params.put("user_id", String.valueOf(userId)); + params.put("text", word); + params.put("access",Constants.SERVICE_NAME); + + String paramsJsonFormat = JSON.toJSONString(params); + StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8"); + post.setHeader("Content-Type", "application/json;charset=utf-8"); + post.setEntity(body); + + httpResponse = httpClient.execute(post); + HttpEntity responseBody = httpResponse.getEntity(); + if (responseBody != null) { + String responseContent = EntityUtils.toString(responseBody); + logger.info("齐悟接口返回: "+ responseContent); + JSONObject responseJsonFormat = JSONObject.parseObject(responseContent); + audioUrl = (String) responseJsonFormat.get("audio"); + textContent = (String) responseJsonFormat.get("text"); + } + } catch (IOException e) { + logger.error("请求齐悟接口出错:"+e.toString()); + return null; + } finally { + try { + if (httpClient != null) httpClient.close(); + if (httpResponse != null) httpResponse.close(); + } catch (IOException e) { + logger.error("关闭与齐悟接口时出错:"+e.toString()); + } + } + return addUrlAndText(audioUrl, textContent); + } + + private ResResponse addUrlAndText(String url, String text) throws RokidException { + return buildResponse(text); + } + + private ResResponse buildResponse(String text) throws RokidException { + return ProtocolUtils.pickUp(text); + } +} diff --git a/ruoqi/src/main/resources/application.properties b/ruoqi/src/main/resources/application.properties index 8b13789..48e5999 100644 --- a/ruoqi/src/main/resources/application.properties +++ b/ruoqi/src/main/resources/application.properties @@ -1 +1 @@ - +server.port=8585 diff --git a/ruoqi/src/main/resources/lib/rokid-skill-kit-java-1.0.0.jar b/ruoqi/src/main/resources/lib/rokid-skill-kit-java-1.0.0.jar new file mode 100644 index 0000000..1caffa1 Binary files /dev/null and b/ruoqi/src/main/resources/lib/rokid-skill-kit-java-1.0.0.jar differ diff --git a/ruoqi/src/main/resources/lib/rokid-skill-protocol-1.0.0.jar b/ruoqi/src/main/resources/lib/rokid-skill-protocol-1.0.0.jar new file mode 100644 index 0000000..6c87cb0 Binary files /dev/null and b/ruoqi/src/main/resources/lib/rokid-skill-protocol-1.0.0.jar differ diff --git a/spirit/pom.xml b/spirit/pom.xml index aa29ff8..53227dd 100644 --- a/spirit/pom.xml +++ b/spirit/pom.xml @@ -11,6 +11,7 @@ ai.qiwu.tmall spirit 0.0.1-SNAPSHOT + war spirit Tmall spirit project @@ -22,6 +23,12 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + @@ -29,13 +36,78 @@ spring-boot-starter-test test + + + com.tmall.spirit + tmall-sdk + 1.0.0 + system + ${project.basedir}/src/main/resources/lib/aliGenie-intent-sematic.jar + + + + + org.apache.httpcomponents + httpclient + 4.5.8 + + + com.alibaba + fastjson + 1.2.58 + + + com.google.guava + guava + 18.0 + + + com.google.code.gson + gson + 2.8.5 + + + + javax.servlet + javax.servlet-api + LATEST + provided + + Spirit org.springframework.boot spring-boot-maven-plugin + + true + + + + maven-compiler-plugin + + 1.8 + 1.8 + UTF-8 + + ${project.basedir}/src/main/resources/lib + + + + + org.apache.maven.plugins + maven-war-plugin + 3.2.3 + + + + ${project.basedir}/src/main/resources/lib + WEB-INF/lib + + + diff --git a/spirit/src/main/java/ai/qiwu/tmall/spirit/SpiritApplication.java b/spirit/src/main/java/ai/qiwu/tmall/spirit/SpiritApplication.java index c3ad2bd..2ad7549 100644 --- a/spirit/src/main/java/ai/qiwu/tmall/spirit/SpiritApplication.java +++ b/spirit/src/main/java/ai/qiwu/tmall/spirit/SpiritApplication.java @@ -2,12 +2,18 @@ package ai.qiwu.tmall.spirit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication -public class SpiritApplication { +public class SpiritApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SpiritApplication.class, args); } + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(SpiritApplication.class); + } } diff --git a/spirit/src/main/java/ai/qiwu/tmall/spirit/controller/SpiritController.java b/spirit/src/main/java/ai/qiwu/tmall/spirit/controller/SpiritController.java new file mode 100755 index 0000000..2c10f51 --- /dev/null +++ b/spirit/src/main/java/ai/qiwu/tmall/spirit/controller/SpiritController.java @@ -0,0 +1,57 @@ +package ai.qiwu.tmall.spirit.controller; + +import ai.qiwu.tmall.spirit.service.SpiritService; +import com.alibaba.da.coin.ide.spi.standard.ResultModel; +import com.alibaba.da.coin.ide.spi.standard.TaskQuery; +import com.alibaba.da.coin.ide.spi.standard.TaskResult; +import com.alibaba.da.coin.ide.spi.trans.MetaFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * 天猫自定义技能里Webhook中URL,假如填写的是http://test.com/spirit, + * 他会访问这里,并将请求参数映射到taskQuery上.关于证书的访问, + * 以上面URL为例天猫会访问http://test.com/aligenie/xxx.file, + * 这里我们将xxx.file放到了resources/aligenie下 + * @author 苗权威 + * @dateTime 2019/6/18 + */ +@RestController +public class SpiritController { + + /** + * slf4j打印日志信息 + */ + private static final Logger logger = LoggerFactory.getLogger(SpiritController.class); + + /** + * 解析请求信息的实现类 + */ + @Autowired + private SpiritService spiritService; + + /** + * 利用天猫精灵打开发包解析请求并从构造响应数据返回 + * @param taskQuery 请求的参数信息 + * @return 返回响应的JSON数据 + */ + @RequestMapping(value = "/spirit") + public @ResponseBody ResultModel getResponse(@RequestBody String taskQuery) { + logger.info("TaskQuery:{}",taskQuery); + TaskQuery query = MetaFormat.parseToQuery(taskQuery); + + // build response + ResultModel resultModel = new ResultModel<>(); + TaskResult taskResult = spiritService.getResponse(query); + logger.info("taskResult:"+taskResult); + resultModel.setReturnCode("0"); + resultModel.setReturnValue(taskResult); + + return resultModel; + } +} diff --git a/spirit/src/main/java/ai/qiwu/tmall/spirit/service/SpiritService.java b/spirit/src/main/java/ai/qiwu/tmall/spirit/service/SpiritService.java new file mode 100755 index 0000000..7cdfc97 --- /dev/null +++ b/spirit/src/main/java/ai/qiwu/tmall/spirit/service/SpiritService.java @@ -0,0 +1,135 @@ +package ai.qiwu.tmall.spirit.service; + +import com.alibaba.da.coin.ide.spi.meta.AskedInfoMsg; +import com.alibaba.da.coin.ide.spi.meta.ExecuteCode; +import com.alibaba.da.coin.ide.spi.meta.ResultType; +import com.alibaba.da.coin.ide.spi.standard.TaskQuery; +import com.alibaba.da.coin.ide.spi.standard.TaskResult; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; + +/** + * 解析请求参数,构造向终端接口发送打数据打JSON,之后得到响应数据,提取构造返回给天猫的响应数据 + * @author 苗权威 + * @dateTime 2019/6/18 + */ +@Service +public class SpiritService { + + /** + * org.slf4j.Logger打印日志信息 + */ + private static final Logger logger = LoggerFactory.getLogger(SpiritService.class); + + /** + * 获取返回给天猫的数据 + * @param request 请求参数 + * @return 返回数据封装在开发包中的TaskResult + */ + public TaskResult getResponse(TaskQuery request) { + return getNeededParam(request); + } + + /** + * 解析获取需要的参数信息:用户的话,用户的id,意图id + * @param request 请求参数 + * @return 返回数据封装在开发包中的TaskResult + */ + private TaskResult getNeededParam(TaskQuery request) { + Long userId = request.getBotId(); + String userWord = request.getUtterance(); + logger.info("The customer say:"+userWord); + Long intentId = request.getIntentId(); + return postToQiWuInterface(userId, userWord, intentId); + } + + /** + * 向接口公司的接口发送数据:user_id 包括用户id, text TTS文本内容,access 来源标识 + * 获取返回:audio 音频链接,text TTS文本内容 + * @param userId 用户id + * @param userWord TTS文本内容 + * @param intentId 意图id + * @return 返回数据封装在开发包中的TaskResult + */ + private TaskResult postToQiWuInterface(Long userId, String userWord, Long intentId) { + String audioUrl = ""; + String textContent = "请说推荐作品"; + CloseableHttpClient httpClient = null; + CloseableHttpResponse response = null; + try { + httpClient = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost("http://aliyun-hz1.chewrobot.com:8070/api/chat"); + HashMap params = new HashMap<>(); + params.put("user_id", String.valueOf(userId)); + + params.put("text", userWord); + params.put("access","TIANMAO"); + String paramsJsonFormat = JSON.toJSONString(params); + StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8"); + post.setHeader("Content-Type", "application/json;charset=utf-8"); + post.setEntity(body); + + response = httpClient.execute(post); + HttpEntity responseBody = response.getEntity(); + if (responseBody != null) { + String responseContent = EntityUtils.toString(responseBody); + logger.info("齐悟接口返回: "+ responseContent); + JSONObject responseJsonFormat = JSONObject.parseObject(responseContent); + audioUrl = (String) responseJsonFormat.get("audio"); + textContent = (String) responseJsonFormat.get("text"); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (httpClient != null) httpClient.close(); + if (response != null) response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return buildTaskResult(audioUrl, textContent, intentId); + } + + /** + * 封装返回数据在TaskResult中 + * @param audio 音频链接 + * @param text TTS文本内容 + * @param intentId 意图id + * @return 返回数据封装在开发包中的TaskResult + */ + private TaskResult buildTaskResult(String audio, String text, Long intentId) { + TaskResult result = new TaskResult(); + result.setReply(text); + result.setResultType(ResultType.ASK_INF); + result.setExecuteCode(ExecuteCode.SUCCESS); + + AskedInfoMsg askedInfoMsg = new AskedInfoMsg("any", intentId); + ArrayList listInfo = new ArrayList<>(); + listInfo.add(askedInfoMsg); + result.setAskedInfos(listInfo); + +// List actions = new ArrayList<>(); +// Action action = new Action("audioPlayGenieSource"); +// //action.addProperty("audioGenieId", "21441"); +// action.addProperty("audioGenieId", audio); +// actions.add(action); +// result.setActions(actions); + + return result; + } +} diff --git a/spirit/src/main/resources/lib/aliGenie-intent-sematic.jar b/spirit/src/main/resources/lib/aliGenie-intent-sematic.jar new file mode 100644 index 0000000..27df896 Binary files /dev/null and b/spirit/src/main/resources/lib/aliGenie-intent-sematic.jar differ diff --git a/spirit/src/main/resources/logback.xml b/spirit/src/main/resources/logback.xml new file mode 100644 index 0000000..93d69ef --- /dev/null +++ b/spirit/src/main/resources/logback.xml @@ -0,0 +1,42 @@ + + + + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + + + + + + + + /usr/mqw/logs/spirit/ + + + /usr/mqw/logs/spirit/base.log.%d.%i + + 64 MB + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + \ No newline at end of file diff --git a/spirit/src/main/resources/static/aligenie/0b6b193b8b26ae5875b6d4e4f69a4103.txt b/spirit/src/main/resources/static/aligenie/0b6b193b8b26ae5875b6d4e4f69a4103.txt new file mode 100644 index 0000000..687e42a --- /dev/null +++ b/spirit/src/main/resources/static/aligenie/0b6b193b8b26ae5875b6d4e4f69a4103.txt @@ -0,0 +1 @@ +Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdYGH+f3XrduI0FLgVW7gXyV \ No newline at end of file diff --git a/xiaoai/pom.xml b/xiaoai/pom.xml index 1e2771c..3db9550 100644 --- a/xiaoai/pom.xml +++ b/xiaoai/pom.xml @@ -29,6 +29,24 @@ spring-boot-starter-test test + + + org.apache.httpcomponents + httpclient + 4.5.8 + + + com.alibaba + fastjson + 1.2.58 + + + + org.projectlombok + lombok + 1.18.8 + provided + diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/Utils.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/Utils.java new file mode 100644 index 0000000..af0374c --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/Utils.java @@ -0,0 +1,34 @@ +package ai.qiwu.mi.xiaoai.commons; + +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.util.Objects; + +/** + * @author 苗权威 + * @dateTime 19-7-6 上午11:16 + */ +public class Utils { + + public static HttpServletRequest getHttpServletRequest() { + return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder + .getRequestAttributes())).getRequest(); + } + + public static String useIPAsItsID() { + HttpServletRequest request = getHttpServletRequest(); + String ip = request.getHeader("x-forwarded-for"); + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + return ip; + } +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/XiaoAiConstants.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/XiaoAiConstants.java new file mode 100644 index 0000000..6004bb5 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/commons/XiaoAiConstants.java @@ -0,0 +1,26 @@ +package ai.qiwu.mi.xiaoai.commons; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:56 + */ +public interface XiaoAiConstants { + String QI_WU_TERMINATE = "http://aliyun-hz1.chewrobot.com:8070/api/chat"; + String DEVICE_NAME = "XIAOAI"; + String CONTENT_TYPE = "application/json;charset=utf-8"; + String PLAYBACK_NEARLY_FINISHED = "mediaplayer.playbacknearlyfinished"; + + + interface ERROR_MSG { + String SORRY_REPEAT = "不好意思,请再说一边吧"; + String TERMINATE_IO_EXCEPTION = "请求终端接口时发生IO错误"; + String HTTP_CONNECTION_CLOSE_EXCEPTION = "关闭与终端接口链接时出错"; + } + + interface TTS { + String WELCOME_WORD = "欢迎来到互动天地,请说推荐作品"; + String END_BYE = "我们的作品库在不断扩充,下次会有更大的惊喜哦"; + String END_WORD = "退出"; + String USER_IDLE = "小悟在等你的回复哦"; + } +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/controller/XiaoAiController.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/controller/XiaoAiController.java new file mode 100644 index 0000000..e609e14 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/controller/XiaoAiController.java @@ -0,0 +1,26 @@ +package ai.qiwu.mi.xiaoai.controller; + +import ai.qiwu.mi.xiaoai.model.request.XiaoAiRequest; +import ai.qiwu.mi.xiaoai.model.response.XiaoAiResponse; +import ai.qiwu.mi.xiaoai.service.XiaoAiService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author 苗权威 + * @dateTime 19-7-6 上午11:36 + */ +@RestController +public class XiaoAiController { + + @Autowired + private XiaoAiService xiaoAiService; + + @RequestMapping("/xiaoai") + public @ResponseBody XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) { + return xiaoAiService.getResponse(request); + } +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/XiaoAiRequest.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/XiaoAiRequest.java new file mode 100644 index 0000000..cd437ba --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/XiaoAiRequest.java @@ -0,0 +1,23 @@ +package ai.qiwu.mi.xiaoai.model.request; + +import ai.qiwu.mi.xiaoai.model.request.context.Context; +import ai.qiwu.mi.xiaoai.model.request.innerRequest.Request; +import ai.qiwu.mi.xiaoai.model.request.session.Session; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:10 + */ +@Getter +@Setter +@ToString +public class XiaoAiRequest { + private String version; + private String query; + private Session session; + private Context context; + private Request request; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/context/ClientAppInfo.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/context/ClientAppInfo.java new file mode 100644 index 0000000..6333e85 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/context/ClientAppInfo.java @@ -0,0 +1,17 @@ +package ai.qiwu.mi.xiaoai.model.request.context; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:21 + */ +@Getter +@Setter +@ToString +public class ClientAppInfo { + private String pkg_name; + private String version_name; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/context/Context.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/context/Context.java new file mode 100644 index 0000000..59f68b5 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/context/Context.java @@ -0,0 +1,20 @@ +package ai.qiwu.mi.xiaoai.model.request.context; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:20 + */ +@Getter +@Setter +@ToString +public class Context { + private String device_id; + private String passport; + private List app_info; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/EventProperty.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/EventProperty.java new file mode 100644 index 0000000..3fc2722 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/EventProperty.java @@ -0,0 +1,17 @@ +package ai.qiwu.mi.xiaoai.model.request.innerRequest; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:24 + */ +@Getter +@Setter +@ToString +public class EventProperty { + private String asr_text; + private String msg_file_id; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/Request.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/Request.java new file mode 100644 index 0000000..e50828a --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/Request.java @@ -0,0 +1,23 @@ +package ai.qiwu.mi.xiaoai.model.request.innerRequest; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:23 + */ +@Getter +@Setter +@ToString +public class Request { + private int type; + private String request_id; + private Long timestamp; + private Boolean no_response; + private String event_type; + private EventProperty event_property; + private String Locale; + private SlotInfo slot_info; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/SlotInfo.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/SlotInfo.java new file mode 100644 index 0000000..40c87ae --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/SlotInfo.java @@ -0,0 +1,21 @@ +package ai.qiwu.mi.xiaoai.model.request.innerRequest; + +import ai.qiwu.mi.xiaoai.model.request.innerRequest.slot.Slot; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:26 + */ +@Getter +@Setter +@ToString +public class SlotInfo { + private String intent_name; + private boolean is_confirmed; + private List slots; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/slot/Slot.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/slot/Slot.java new file mode 100644 index 0000000..a722c26 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/innerRequest/slot/Slot.java @@ -0,0 +1,18 @@ +package ai.qiwu.mi.xiaoai.model.request.innerRequest.slot; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:27 + */ +@Getter +@Setter +@ToString +public class Slot { + private String name; + private String value; + private boolean is_inquire_failed; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/session/Application.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/session/Application.java new file mode 100644 index 0000000..a1371a3 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/session/Application.java @@ -0,0 +1,16 @@ +package ai.qiwu.mi.xiaoai.model.request.session; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:16 + */ +@Getter +@Setter +@ToString +public class Application { + private String app_id; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/session/Session.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/session/Session.java new file mode 100644 index 0000000..14e6871 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/session/Session.java @@ -0,0 +1,21 @@ +package ai.qiwu.mi.xiaoai.model.request.session; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:15 + */ +@Getter +@Setter +@ToString +public class Session { + private String session_id; + private Application application; + private Map attributes; + private User user; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/session/User.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/session/User.java new file mode 100644 index 0000000..78b3cf2 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/request/session/User.java @@ -0,0 +1,19 @@ +package ai.qiwu.mi.xiaoai.model.request.session; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:16 + */ +@Getter +@Setter +@ToString +public class User { + private String user_id; + private String access_token; + private Boolean is_user_login; + private String gender; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/XiaoAiResponse.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/XiaoAiResponse.java new file mode 100644 index 0000000..55ca9e8 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/XiaoAiResponse.java @@ -0,0 +1,22 @@ +package ai.qiwu.mi.xiaoai.model.response; + +import ai.qiwu.mi.xiaoai.model.response.innerResponse.Response; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:30 + */ +@Getter +@Setter +@ToString +public class XiaoAiResponse { + private String version; + private Map session_attributes; + private Boolean is_session_end; + private Response response; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/Response.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/Response.java new file mode 100644 index 0000000..f5d49da --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/Response.java @@ -0,0 +1,30 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse; + +import ai.qiwu.mi.xiaoai.model.response.innerResponse.actionProperty.ActionProperty; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.Directive; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.registerEvent.RegisterEvent; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.toDisplay.ToDisplay; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.toSpeak.ToSpeak; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:31 + */ +@Getter +@Setter +@ToString +public class Response { + private ToSpeak to_speak; + private ToDisplay to_display; + private List directives; + private Boolean open_mic; + private Boolean not_understand; + private String action; + private ActionProperty action_property; + private List register_events; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/actionProperty/ActionProperty.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/actionProperty/ActionProperty.java new file mode 100644 index 0000000..6e57986 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/actionProperty/ActionProperty.java @@ -0,0 +1,18 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.actionProperty; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:47 + */ +@Getter +@Setter +@ToString +public class ActionProperty { + private List file_id_list; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/AudioItem/AudioItem.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/AudioItem/AudioItem.java new file mode 100644 index 0000000..8fa49f5 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/AudioItem/AudioItem.java @@ -0,0 +1,16 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:41 + */ +@Getter +@Setter +@ToString +public class AudioItem { + private AudioStream stream; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/AudioItem/AudioStream.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/AudioItem/AudioStream.java new file mode 100644 index 0000000..7707475 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/AudioItem/AudioStream.java @@ -0,0 +1,18 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:42 + */ +@Getter +@Setter +@ToString +public class AudioStream { + private String token; + private String url; + private Long offset_in_milliseconds; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/Directive.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/Directive.java new file mode 100644 index 0000000..e085069 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/Directive.java @@ -0,0 +1,20 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.directive; + +import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem.AudioItem; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.ttsItem.TTSItem; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:41 + */ +@Getter +@Setter +@ToString +public class Directive { + private String type; + private AudioItem audio_item; + private TTSItem tts_item; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/ttsItem/TTSItem.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/ttsItem/TTSItem.java new file mode 100644 index 0000000..b47c8c5 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/directive/ttsItem/TTSItem.java @@ -0,0 +1,17 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.ttsItem; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:44 + */ +@Getter +@Setter +@ToString +public class TTSItem { + private String type; + private String text; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/registerEvent/RegisterEvent.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/registerEvent/RegisterEvent.java new file mode 100644 index 0000000..891603f --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/registerEvent/RegisterEvent.java @@ -0,0 +1,16 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.registerEvent; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:49 + */ +@Getter +@Setter +@ToString +public class RegisterEvent { + private String event_name; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toDisplay/ToDisplay.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toDisplay/ToDisplay.java new file mode 100644 index 0000000..8bbb443 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toDisplay/ToDisplay.java @@ -0,0 +1,20 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.toDisplay; + +import ai.qiwu.mi.xiaoai.model.response.innerResponse.toDisplay.UITemplate.UITemplate; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:34 + */ +@Getter +@Setter +@ToString +public class ToDisplay { + private int type; + private String url; + private String text; + private UITemplate ui_template; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toDisplay/UITemplate/Item/Item.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toDisplay/UITemplate/Item/Item.java new file mode 100644 index 0000000..4007e68 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toDisplay/UITemplate/Item/Item.java @@ -0,0 +1,23 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.toDisplay.UITemplate.Item; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:36 + */ +@Getter +@Setter +@ToString +public class Item { + private String image_style; + private List images; + private String intent; + private String title; + private Object body; + private String background_image; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toDisplay/UITemplate/UITemplate.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toDisplay/UITemplate/UITemplate.java new file mode 100644 index 0000000..d698fd7 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toDisplay/UITemplate/UITemplate.java @@ -0,0 +1,22 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.toDisplay.UITemplate; + +import ai.qiwu.mi.xiaoai.model.response.innerResponse.toDisplay.UITemplate.Item.Item; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:35 + */ +@Getter +@Setter +@ToString +public class UITemplate { + private int type; + private List items; + private String logo; + private Item item; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toSpeak/ToSpeak.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toSpeak/ToSpeak.java new file mode 100644 index 0000000..cf0dda7 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/model/response/innerResponse/toSpeak/ToSpeak.java @@ -0,0 +1,17 @@ +package ai.qiwu.mi.xiaoai.model.response.innerResponse.toSpeak; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:33 + */ +@Getter +@Setter +@ToString +public class ToSpeak { + private int type; + private String text; +} diff --git a/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/service/XiaoAiService.java b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/service/XiaoAiService.java new file mode 100644 index 0000000..a038d44 --- /dev/null +++ b/xiaoai/src/main/java/ai/qiwu/mi/xiaoai/service/XiaoAiService.java @@ -0,0 +1,178 @@ +package ai.qiwu.mi.xiaoai.service; + +import ai.qiwu.mi.xiaoai.commons.Utils; +import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants; +import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.TTS; +import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.ERROR_MSG; +import ai.qiwu.mi.xiaoai.model.request.XiaoAiRequest; +import ai.qiwu.mi.xiaoai.model.response.XiaoAiResponse; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.Response; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem.AudioItem; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem.AudioStream; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.Directive; +import ai.qiwu.mi.xiaoai.model.response.innerResponse.toSpeak.ToSpeak; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-7-5 下午8:52 + */ +@Service +public class XiaoAiService { + + private static final Logger logger = LoggerFactory.getLogger(XiaoAiService.class); + + public XiaoAiResponse getResponse(XiaoAiRequest request) { + String userId = getUserId(request); + int type = request.getRequest().getType(); + switch (type) { + case 0 : return dealWithLaunchRequest(request); + case 1 : return dealWithIntentRequest(request, userId); + case 2 : return dealWithEndRequest(userId); + default: return buildTextResponse(ERROR_MSG.SORRY_REPEAT); + } + } + + private XiaoAiResponse postToQiWuInterface(String userId, String userWord) { + String audioUrl = null; + String textContent = null; + CloseableHttpClient httpClient = null; + CloseableHttpResponse httpResponse = null; + try { + httpClient = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(XiaoAiConstants.QI_WU_TERMINATE); + HashMap params = new HashMap<>(); + params.put("user_id", userId); + params.put("text", userWord); + params.put("access",XiaoAiConstants.DEVICE_NAME); + String paramsJsonFormat = JSON.toJSONString(params); + StringEntity body = new StringEntity(paramsJsonFormat, StandardCharsets.UTF_8); + post.setHeader("Content-Type", XiaoAiConstants.CONTENT_TYPE); + post.setEntity(body); + + httpResponse = httpClient.execute(post); + HttpEntity responseBody = httpResponse.getEntity(); + if (responseBody != null) { + String responseContent = EntityUtils.toString(responseBody); + logger.info("齐悟接口返回: "+ responseContent); + JSONObject responseJsonFormat = JSONObject.parseObject(responseContent); + audioUrl = (String) responseJsonFormat.get("audio"); + textContent = (String) responseJsonFormat.get("text"); + } + } catch (IOException e) { + logger.info(ERROR_MSG.TERMINATE_IO_EXCEPTION); + return buildTextResponse(ERROR_MSG.SORRY_REPEAT); + } finally { + try { + if (httpClient != null) httpClient.close(); + if (httpResponse != null) httpResponse.close(); + } catch (IOException e) { + logger.info(ERROR_MSG.HTTP_CONNECTION_CLOSE_EXCEPTION); + } + } + return buildAudioResponse(audioUrl); + } + + private XiaoAiResponse buildResponse() { + XiaoAiResponse response = new XiaoAiResponse(); + response.setVersion("1.0"); + response.setIs_session_end(false); + return response; + } + + private XiaoAiResponse buildAudioResponse(String audioUrl) { + XiaoAiResponse response = buildResponse(); + + Response responseInfo = new Response(); + Directive directive = new Directive(); + directive.setType("audio"); + AudioItem audioItem = new AudioItem(); + AudioStream audioStream = new AudioStream(); + audioStream.setUrl(audioUrl); + audioItem.setStream(audioStream); + directive.setAudio_item(audioItem); + List directives = new ArrayList<>(); + directives.add(directive); + responseInfo.setDirectives(directives); + + response.setResponse(responseInfo); + return response; + } + + private XiaoAiResponse buildTextResponse(String text) { + XiaoAiResponse response = buildResponse(); + + Response responseInfo = new Response(); + ToSpeak toSpeak = new ToSpeak(); + toSpeak.setType(0); + toSpeak.setText(text); + responseInfo.setTo_speak(toSpeak); + + response.setResponse(responseInfo); + return response; + } + + private XiaoAiResponse buildOpenMicResponse() { + XiaoAiResponse response = buildResponse(); + + Response responseInfo = new Response(); + responseInfo.setOpen_mic(true); + + response.setResponse(responseInfo); + return response; + } + + private XiaoAiResponse dealWithLaunchRequest(XiaoAiRequest request) { + return buildTextResponse(TTS.WELCOME_WORD); + } + + private XiaoAiResponse dealWithIntentRequest(XiaoAiRequest request, String userId) { + Boolean idle = request.getRequest().getNo_response(); + if (idle == null || idle) { + return buildTextResponse(TTS.USER_IDLE); + } + //String eventType = request.getRequest().getEvent_type(); + // 这里是否向小度一样需要在语音播放结束后主动开麦? +// if (eventType != null && eventType.equals(XiaoAiConstants.PLAYBACK_NEARLY_FINISHED)) { +// return buildOpenMicResponse(); +// } + String userWord = request.getQuery(); + if (userWord == null) { + return buildTextResponse(ERROR_MSG.SORRY_REPEAT); + } + return postToQiWuInterface(userId, userWord); + } + + private XiaoAiResponse dealWithEndRequest(String userId) { + postToQiWuInterface(userId, TTS.END_WORD); + return buildTextResponse(TTS.END_BYE); + } + + private String getUserId(XiaoAiRequest request) { + String userId = request.getSession().getUser().getUser_id(); + if (userId == null) { + userId = request.getContext().getDevice_id(); + } + if (userId == null) { + userId = Utils.useIPAsItsID(); + } + return userId; + } +} diff --git a/xiaodu/pom.xml b/xiaodu/pom.xml index f9ca0de..f547bad 100644 --- a/xiaodu/pom.xml +++ b/xiaodu/pom.xml @@ -11,6 +11,7 @@ ai.qiwu.baidu xiaodu 0.0.1-SNAPSHOT + war xiaodu Demo project for Spring Boot @@ -22,6 +23,20 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + + javax.servlet + javax.servlet-api + LATEST + provided @@ -50,6 +65,7 @@ + xiaodu org.springframework.boot diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/XiaoduApplication.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/XiaoduApplication.java index ee87320..1263a6f 100644 --- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/XiaoduApplication.java +++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/XiaoduApplication.java @@ -2,12 +2,18 @@ package ai.qiwu.baidu.xiaodu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication -public class XiaoduApplication { +public class XiaoduApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(XiaoduApplication.class, args); } + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(XiaoduApplication.class); + } } diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Constants.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Constants.java index a365570..6d4b006 100644 --- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Constants.java +++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Constants.java @@ -10,7 +10,7 @@ public interface Constants { String SERVICE_NAME = "BAIDU"; interface WelcomeWord { - String WELCOME = "在这里你就是主角,开始你的星辰大海吧"; + String WELCOME = "在这里你就是主角,开始你的星辰大海吧,请说推荐作品"; String BEGIN_NO_RESPONSE = "咋还没开始就停住了,我们这里可有很多好玩的作品哦"; } diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Holder.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Holder.java new file mode 100644 index 0000000..d92be32 --- /dev/null +++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/common/Holder.java @@ -0,0 +1,19 @@ +package ai.qiwu.baidu.xiaodu.common; + +import lombok.Getter; +import lombok.Setter; + +import java.util.concurrent.locks.ReentrantLock; + +/** + * @author 苗权威 + * @dateTime 19-7-1 下午8:39 + */ +@Getter +@Setter +public class Holder { + private volatile String timestamp; + private volatile String lastAudioUrl; + private final ReentrantLock FAIR_LOCK = new ReentrantLock(); + private volatile int first; +} diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/controller/XiaoDuController.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/controller/XiaoDuController.java index a32eba1..e2a973c 100644 --- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/controller/XiaoDuController.java +++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/controller/XiaoDuController.java @@ -9,11 +9,9 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.io.IOException; - /** * @author 苗权威 - * @dateTime 19-6-29 下午5:32 + * @dateTime 19-6-29 下午5:32cat */ @RestController public class XiaoDuController { @@ -25,6 +23,7 @@ public class XiaoDuController { try { ResponseEncapsulation response = new ResponseEncapsulation(Utils.getHttpServletRequest()); response.enableVerify(); + //response.disableVerify(); return response.run(); } catch (Exception e) { logger.info("出现错误 "+e.toString()); diff --git a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/ResponseEncapsulation.java b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/ResponseEncapsulation.java index b289421..e0247cf 100644 --- a/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/ResponseEncapsulation.java +++ b/xiaodu/src/main/java/ai/qiwu/baidu/xiaodu/service/ResponseEncapsulation.java @@ -1,15 +1,21 @@ package ai.qiwu.baidu.xiaodu.service; +import ai.qiwu.baidu.xiaodu.common.Constants; import ai.qiwu.baidu.xiaodu.common.Constants.ErrorMsg; import ai.qiwu.baidu.xiaodu.common.Constants.EndMsg; import ai.qiwu.baidu.xiaodu.common.Constants.WelcomeWord; +import ai.qiwu.baidu.xiaodu.common.Holder; import ai.qiwu.baidu.xiaodu.common.Utils; import ai.qiwu.baidu.xiaodu.pojo.AudioUrlAndText; +import com.alibaba.fastjson.JSON; import com.baidu.dueros.bot.AudioPlayer; import com.baidu.dueros.data.request.IntentRequest; import com.baidu.dueros.data.request.LaunchRequest; import com.baidu.dueros.data.request.Query; import com.baidu.dueros.data.request.SessionEndedRequest; +import com.baidu.dueros.data.request.audioplayer.event.PlaybackFinishedEvent; +import com.baidu.dueros.data.request.audioplayer.event.PlaybackNearlyFinishedEvent; +import com.baidu.dueros.data.request.audioplayer.event.PlaybackStoppedEvent; import com.baidu.dueros.data.response.OutputSpeech; import com.baidu.dueros.data.response.Reprompt; import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective; @@ -21,52 +27,147 @@ import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.io.IOException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; /** * @author 苗权威 * @dateTime 19-6-28 下午8:22 */ -@Service("service") public class ResponseEncapsulation extends AudioPlayer { - private static final Logger logger = LoggerFactory.getLogger(ResponseEncapsulation.class); + private static final ConcurrentHashMap USER_TIMESTAMP = new ConcurrentHashMap<>(); - private String userId; + private static final Logger logger = LoggerFactory.getLogger(ResponseEncapsulation.class); public ResponseEncapsulation(HttpServletRequest request) throws IOException { super(request); + String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s\n" + + "IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46\n" + + "W/NyJQkcddWrA/5OvcZw1uAmzTt8sWz1zokt2e6v6SucvvHoPxLGjfTKWh6Qr+2x\n" + + "K/5wmdOOpikL/ruH2ZviYjto2cBPAgMBAAECgYBuQCLnD8618uk/HWo53PqGAsjR\n" + + "wK+jtJLJk9/QLw9BSL/TJshyuVuFpF1ngtZ8Tj9V1/S9LQE08CUxcd3Q+49njgEq\n" + + "R60FKDjwCe8G9El5jIYIU0RTnd84I8B0RKWBO8ShZ29qWEVXOExPZc1fMlq4UgBr\n" + + "Xkfsh/E1cTfphYyS8QJBAOuX1c11XOSeDVo5KyxM26K2Kiekjm1cLIXJR54hetRN\n" + + "diCHqd5WyolKJzxFuUMEsq+sAfgd7KsrorO5hwY42lUCQQDlXt9TiIWGMt3oVEIf\n" + + "ulJQmURhkQ+Z9EC2wHnFrE3UhkCNyX3TOwTzV8bzC+Vr2hAobbhXTCr8tLGm0Yxk\n" + + "f1wTAkEAqbQtplosF+Jh6+PSXY7fh02BAB1hGxWSXKyokhe7ysIhnT0b97S9IDfy\n" + + "G1B+KvBvZmuY34luub4s7RlvUeQSIQJANaq7Cip5Q2sHbOK6Df5kYCNcUo/EXLs/\n" + + "oQLr+wpTs5Qt6n7oh9HZWK6DCD8SUOfWu/7gENzrefE1V9jTxnfeLQJBANKf4QfA\n" + + "CvwfHTyEgphcWrWDzB7bEqUDWiEjfO8sf+lwj9I0yU6fO/+aUtwU9xwkij1PscUF\n" + + "9AWUhbas+LG9mds="; + //privateKey为私钥内容,0代表你的Bot在DBP平台debug环境,1或者其他整数代表online环境, + // botMonitor对象已经在bot-sdk里初始化,可以直接调用 + //this.botMonitor.setEnvironmentInfo(privateKey, 0); + //this.botMonitor.setMonitorEnabled(true); } @Override - public Response onInent(IntentRequest intentRequest) { + protected Response onInent(IntentRequest intentRequest) { + String userId = getCustomerId(); + String timestamp = this.getRequest().getRequest().getTimestamp(); Query query = intentRequest.getQuery(); String userWord = null; - if (query != null) { - userWord = query.getOriginal(); - } + if (query != null) userWord = query.getOriginal(); if (userWord == null){ logger.info("小度没有传来任何话语"); return buildErrorResponse(ErrorMsg.SORRY_UNCATCH); } - if (userId == null) { - userId = Utils.useIPAsItsID(); + + Holder holder = USER_TIMESTAMP.get(userId); + ReentrantLock lock = null; + try { + lock = holder.getFAIR_LOCK(); + lock.lock(); + if (holder.getFirst() == 0) { + holder.setFirst(1); + Thread.sleep(60); + } + if (lock.hasQueuedThreads()) { + logger.info("由于请求间隔过短,因此认为本次请求为过于的重复请求,"+ "上次请求的时间:"+holder.getTimestamp() + + "这次请求的时间:"+ timestamp+"本次请求内容为:original:" + +intentRequest.getQuery().getOriginal()+"; asrRawResult:"+getAsrRawResult(this.getStrRequest())); + this.waitAnswer(); + return new Response(); + } + } catch (InterruptedException e) { + logger.info("睡眠中断"); + holder.setFirst(0); + return buildErrorResponse(ErrorMsg.SORRY_UNCATCH); + } catch (NullPointerException e) { + logger.info("锁未初始化"); + USER_TIMESTAMP.put(userId, new Holder()); + return buildErrorResponse(ErrorMsg.SORRY_UNCATCH); + } finally { + if (lock != null) lock.unlock(); } + holder.setTimestamp(timestamp); + holder.setFirst(0); + logger.info("请求消息:"+this.getStrRequest()); + + AudioUrlAndText data = RequestTerminal.requestTerminate(userWord, userId); if (data == null) { return buildErrorResponse(ErrorMsg.SORRY_UNCATCH); } - addDirective(buildPlayDirectice(data.getAudioUrl())); - // shouldEndSession字段和expectSpeech字段同时为false,技能还在会话中, - // 但是不需要用户进行回复,设备端会关闭麦克风,此时可以返回AudioPlayer.Play指令, - // 目的是为了防止设备读取自己正在播放的内容 - endDialog(); - setExpectSpeech(false); + String audioUrl = data.getAudioUrl(); + addDirective(buildPlayDirective(audioUrl, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL)); return new Response(); } + // @Override +// public Response onInent(IntentRequest intentRequest) { +// String userId = getCustomerId(); +// String timestamp = this.getRequest().getRequest().getTimestamp(); +// Holder preHolder = USER_TIMESTAMP.get(userId); +// if (preHolder == null) { +// preHolder = new Holder(); +// USER_TIMESTAMP.put(userId, preHolder); +// }else if (Long.parseLong(preHolder.getTimestamp())+9 >= Long.parseLong(timestamp)) { +// logger.info("由于请求间隔过短,因此认为本次请求为过于的重复请求,"+ "上次请求的时间:"+preHolder.getTimestamp() + +// "这次请求的时间:"+ timestamp+"本次请求内容为:original:" +// +intentRequest.getQuery().getOriginal()+"; asrRawResult:"+getAsrRawResult(this.getStrRequest())); +//// String lastAudioUrl = preHolder.getLastAudioUrl(); +//// if (lastAudioUrl == null || lastAudioUrl.isEmpty()) { +//// lastAudioUrl = "http://aliyun-hz1.chewrobot.com:9663/api/tts/get_audio?dirs=%5B5903691804%2Cxiaoai%5D&filename=86a667384722234e0060e3eae31dd223.mp3"; +//// } +//// addDirective(buildPlayDirective(lastAudioUrl, AudioPlayerDirective.PlayBehaviorType.ENQUEUE)); +// this.waitAnswer(); +// return new Response(); +// } +// preHolder.setTimestamp(timestamp); +// logger.info("请求消息:"+this.getStrRequest()); +// Query query = intentRequest.getQuery(); +// String userWord = null; +// if (query != null) userWord = query.getOriginal(); +// +//// String userWord = getAsrRawResult(this.getStrRequest()); +//// if (userWord.isEmpty() && query != null) { +//// userWord = query.getOriginal(); +//// } +// +// if (userWord == null){ +// logger.info("小度没有传来任何话语"); +// return buildErrorResponse(ErrorMsg.SORRY_UNCATCH); +// } +// +// AudioUrlAndText data = RequestTerminal.requestTerminate(userWord, userId); +// if (data == null) { +// return buildErrorResponse(ErrorMsg.SORRY_UNCATCH); +// } +// String audioUrl = data.getAudioUrl(); +// //preHolder.setLastAudioUrl(audioUrl); +// addDirective(buildPlayDirective(audioUrl, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL)); +// // shouldEndSession字段和expectSpeech字段同时为false,技能还在会话中, +// // 但是不需要用户进行回复,设备端会关闭麦克风,此时可以返回AudioPlayer.Play指令, +// // 目的是为了防止设备读取自己正在播放的内容,二者默认都是false +// return new Response(); +// } + @Override public Response onLaunch(LaunchRequest launchRequest) { - userId = getDeviceId(); + logger.info("请求消息:"+this.getStrRequest()); + USER_TIMESTAMP.put(getCustomerId(), new Holder()); OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, WelcomeWord.WELCOME); Reprompt reprompt = new Reprompt(new OutputSpeech(OutputSpeech.SpeechType.PlainText, WelcomeWord.BEGIN_NO_RESPONSE)); return new Response(outputSpeech, null, reprompt); @@ -74,6 +175,11 @@ public class ResponseEncapsulation extends AudioPlayer { @Override public Response onSessionEnded(SessionEndedRequest sessionEndedRequest) { + logger.info("触发结束事件,"+this.getStrRequest()); + Holder holder = USER_TIMESTAMP.remove(getCustomerId()); + if (holder != null) { + logger.info("删除用户:"+getCustomerId()+" 的缓存成功"); + } switch (sessionEndedRequest.getReason()) { case ERROR: dealWithError(sessionEndedRequest); break; case USER_INITIATED: logger.info(EndMsg.USER_SAY_CANCEL); break; @@ -81,6 +187,7 @@ public class ResponseEncapsulation extends AudioPlayer { } // 向终端发送“退出” OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, EndMsg.BYE_BYE); + RequestTerminal.requestTerminate("退出", getCustomerId()); return new Response(outputSpeech); } @@ -98,7 +205,86 @@ public class ResponseEncapsulation extends AudioPlayer { return new Response(outputSpeech); } - private Play buildPlayDirectice(String audioUrl) { - return new Play(AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL, audioUrl, 0); + private Play buildPlayDirective(String audioUrl, AudioPlayerDirective.PlayBehaviorType type) { + return new Play(type, audioUrl, 0); + } + + /** + * 不想对每个事件都进行处理,通过重写onDefaultEvent方法来统一处理。 + * 任何事件都不允许开麦 + * @return + */ +// @Override +// protected Response onDefaultEvent() { +// this.waitAnswer(); +// this.setExpectSpeech(false); +// return new Response(); +// } + + /** + * 音频播放结束,开麦 + * + * expectSpeech + * 在会话进行过程中,技能是否需要用户进行对话响应。该字段可选,并且仅在shouldEndSession为false时有效。 + * true:表示技能需要用户进行对话响应,设备端上打开麦克风聆听用户的语音。 + * false:表示技能不需要用户进行对话响应,设备端上关闭麦克风。 + * + * shouldEndSession字段和expectSpeech字段同时为false,技能还在会话中,但是不需要用户进行回复, + * 设备端会关闭麦克风,此时可以返回AudioPlayer.Play指令。 + * @param playbackFinishedEvent + * @return + */ + @Override + protected Response onPlaybackFinishedEvent(PlaybackFinishedEvent playbackFinishedEvent) { + logger.info("音频播放完毕,开麦"); + this.waitAnswer(); + this.setExpectSpeech(true); + return new Response(); + } + + @Override + protected Response onPlaybackStoppedEvent(PlaybackStoppedEvent playbackStoppedEvent) { + logger.info("音频播放停止"); + this.waitAnswer(); + return new Response(); + } + + // 不能提前开麦,这回让正在播放的音频停止 +// @Override +// protected Response onPlaybackNearlyFinishedEvent(PlaybackNearlyFinishedEvent playbackNearlyFinishedEvent) { +// logger.info("音频即将播出完毕,提前开麦"); +// this.waitAnswer(); +// this.setExpectSpeech(true); +// return new Response(); +// } + + @Override + protected Response onDefaultEvent() { + logger.info("未拦截的事件类型:"+getEventType(this.getStrRequest())); + this.waitAnswer(); + return new Response(); + } + + private String getCustomerId() { + String userId; + try { + userId = getUserId(); + } catch (NullPointerException e) { + userId = Utils.useIPAsItsID(); + } + return userId; + } + + private String getEventType(String requestStr) { + int typeIndex = requestStr.lastIndexOf("type"); + int comma = requestStr.indexOf(',', typeIndex); + return requestStr.substring(typeIndex, comma); + } + + private String getAsrRawResult(String requestStr) { + int asrIndex = requestStr.lastIndexOf("asrRawResult"); + int asrWordBegin = requestStr.indexOf(':', asrIndex)+2; + int asrWordEnd = requestStr.indexOf('"',asrWordBegin); + return requestStr.substring(asrWordBegin, asrWordEnd); } } diff --git a/xiaodu/src/main/resources/application.properties b/xiaodu/src/main/resources/application.properties index 8b13789..d71ec1c 100644 --- a/xiaodu/src/main/resources/application.properties +++ b/xiaodu/src/main/resources/application.properties @@ -1 +1,6 @@ - +log4j.appender.D = org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File = /usr/mqw/logs/xiaodu.log +log4j.appender.D.Append = true +log4j.appender.D.Threshold = DEBUG +log4j.appender.D.layout = org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n diff --git a/xiaodu/src/main/resources/logback.xml b/xiaodu/src/main/resources/logback.xml new file mode 100644 index 0000000..98cf148 --- /dev/null +++ b/xiaodu/src/main/resources/logback.xml @@ -0,0 +1,42 @@ + + + + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + + + + + + + + /usr/mqw/logs/xiaodu/ + + + /usr/mqw/logs/xiaodu/base.log.%d.%i + + 64 MB + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + \ No newline at end of file diff --git a/xiaoya/pom.xml b/xiaoya/pom.xml index f39fccc..0829857 100644 --- a/xiaoya/pom.xml +++ b/xiaoya/pom.xml @@ -11,6 +11,7 @@ ai.qiwu.xiaoya xiaoya 0.0.1-SNAPSHOT + war xiaoya Demo project for Spring Boot @@ -22,6 +23,19 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + javax.servlet + javax.servlet-api + LATEST + provided @@ -29,9 +43,26 @@ spring-boot-starter-test test + + org.projectlombok + lombok + 1.18.8 + provided + + + org.apache.httpcomponents + httpclient + 4.5.8 + + + com.alibaba + fastjson + 1.2.58 + + xiaoya org.springframework.boot diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/XiaoyaApplication.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/XiaoyaApplication.java index 189499f..d45dce6 100644 --- a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/XiaoyaApplication.java +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/XiaoyaApplication.java @@ -2,12 +2,18 @@ package ai.qiwu.xiaoya.xiaoya; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication -public class XiaoyaApplication { +public class XiaoyaApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(XiaoyaApplication.class, args); } + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(XiaoyaApplication.class); + } } diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/common/Constants.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/common/Constants.java new file mode 100644 index 0000000..5f8047c --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/common/Constants.java @@ -0,0 +1,10 @@ +package ai.qiwu.xiaoya.xiaoya.common; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:35 + */ +public interface Constants { + String QI_WU_INTERFACE = "http://aliyun-hz1.chewrobot.com:8070/api/chat"; + String SERVICE_NAME = "XIAOYA"; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/controller/XiaoYaController.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/controller/XiaoYaController.java new file mode 100644 index 0000000..8b840be --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/controller/XiaoYaController.java @@ -0,0 +1,35 @@ +package ai.qiwu.xiaoya.xiaoya.controller; + +import ai.qiwu.xiaoya.xiaoya.model.RequestModel.RequestParams; +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.Response; +import ai.qiwu.xiaoya.xiaoya.service.ParseService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:03 + */ +@RestController +public class XiaoYaController { + private static Logger logger = LoggerFactory.getLogger(XiaoYaController.class); + + @Autowired + private ParseService service; + + @RequestMapping("/xiaoya") + public @ResponseBody Response chat(@RequestBody RequestParams params) { + logger.info(params.toString()); + return service.getResponse(params); + } + + @RequestMapping("/hello") + public @ResponseBody String hello(@RequestBody RequestParams params) { + return "热部署测试成功7777777777777"; + } +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/ContextSystem.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/ContextSystem.java new file mode 100644 index 0000000..c2d5a9d --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/ContextSystem.java @@ -0,0 +1,21 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel; + +import ai.qiwu.xiaoya.xiaoya.model.RequestModel.contextSystem.SysUser; +import ai.qiwu.xiaoya.xiaoya.model.RequestModel.contextSystem.SystemApplication; +import ai.qiwu.xiaoya.xiaoya.model.RequestModel.contextSystem.SystemDevice; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午12:21 + */ +@Getter +@Setter +@ToString +public class ContextSystem { + private SystemDevice device; + private SystemApplication application; + private SysUser user; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/RequestContext.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/RequestContext.java new file mode 100644 index 0000000..b9dd5de --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/RequestContext.java @@ -0,0 +1,16 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午12:21 + */ +@Getter +@Setter +@ToString +public class RequestContext { + private ContextSystem system; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/RequestParams.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/RequestParams.java new file mode 100644 index 0000000..b626cb5 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/RequestParams.java @@ -0,0 +1,20 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel; + +import ai.qiwu.xiaoya.xiaoya.model.RequestModel.request.RequestPart; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:23 + */ +@Getter +@Setter +@ToString +public class RequestParams { + private String version; + private RequestSession session; + private RequestContext context; + private RequestPart request; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/RequestSession.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/RequestSession.java new file mode 100644 index 0000000..3b58b84 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/RequestSession.java @@ -0,0 +1,22 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel; + +import ai.qiwu.xiaoya.xiaoya.model.RequestModel.request.RequestPart; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午12:19 + */ +@Getter +@Setter +@ToString +public class RequestSession { + private String sid; + private Map attributes; + private RequestContext context; + private RequestPart request; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/AppClient.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/AppClient.java new file mode 100644 index 0000000..95d0896 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/AppClient.java @@ -0,0 +1,16 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel.contextSystem; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:07 + */ +@Getter +@Setter +@ToString +public class AppClient { + private String osClient; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/AppSkill.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/AppSkill.java new file mode 100644 index 0000000..1ab830f --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/AppSkill.java @@ -0,0 +1,17 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel.contextSystem; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:08 + */ +@Getter +@Setter +@ToString +public class AppSkill { + private String skillId; + private String version; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/SysUser.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/SysUser.java new file mode 100644 index 0000000..62fe25f --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/SysUser.java @@ -0,0 +1,17 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel.contextSystem; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:10 + */ +@Getter +@Setter +@ToString +public class SysUser { + private String uid; + private String osAccessToken; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/SystemApplication.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/SystemApplication.java new file mode 100644 index 0000000..6b1bc6c --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/SystemApplication.java @@ -0,0 +1,17 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel.contextSystem; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:07 + */ +@Getter +@Setter +@ToString +public class SystemApplication { + private AppClient client; + private AppSkill skill; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/SystemDevice.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/SystemDevice.java new file mode 100644 index 0000000..161888e --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/contextSystem/SystemDevice.java @@ -0,0 +1,23 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel.contextSystem; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午12:23 + */ +@Getter +@Setter +@ToString +public class SystemDevice { + private String deviceType; + private String deviceId; + private String sn; + private String productId; + private String version; + private String lat; + private String lng; + private String ip; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/request/RequestAsr.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/request/RequestAsr.java new file mode 100644 index 0000000..adaef9d --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/request/RequestAsr.java @@ -0,0 +1,17 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel.request; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:16 + */ +@Getter +@Setter +@ToString +public class RequestAsr { + private String text; + private String version; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/request/RequestNlu.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/request/RequestNlu.java new file mode 100644 index 0000000..081da37 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/request/RequestNlu.java @@ -0,0 +1,19 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel.request; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:17 + */ +@Getter +@Setter +@ToString +public class RequestNlu { + private String domain; + private String intent; + private Object slots; + private String env; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/request/RequestPart.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/request/RequestPart.java new file mode 100644 index 0000000..ae14511 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/RequestModel/request/RequestPart.java @@ -0,0 +1,20 @@ +package ai.qiwu.xiaoya.xiaoya.model.RequestModel.request; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:14 + */ +@Getter +@Setter +@ToString +public class RequestPart { + private String type; + private RequestAsr asr; + private List nlu; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/Response.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/Response.java new file mode 100644 index 0000000..3673ddc --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/Response.java @@ -0,0 +1,22 @@ +package ai.qiwu.xiaoya.xiaoya.model.ResponseModel; + +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.ResponsePart; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:06 + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@Getter +@Setter +@ToString + +public class Response { + private String version; + private Session session; + private ResponsePart response; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/Session.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/Session.java new file mode 100644 index 0000000..0b1211c --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/Session.java @@ -0,0 +1,17 @@ +package ai.qiwu.xiaoya.xiaoya.model.ResponseModel; + +import lombok.Getter; +import lombok.Setter; + +import java.util.Map; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:08 + */ +@Getter +@Setter +public class Session { + private String sid; + private Map attributes; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/OutputSpeech.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/OutputSpeech.java new file mode 100644 index 0000000..08d1622 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/OutputSpeech.java @@ -0,0 +1,16 @@ +package ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:14 + */ +@Getter +@Setter +public class OutputSpeech { + private String type; // plaintext + private String text; // tts + private String ssml; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/ResponsePart.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/ResponsePart.java new file mode 100644 index 0000000..c9fbab0 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/ResponsePart.java @@ -0,0 +1,19 @@ +package ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart; + +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive.Directive; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:14 + */ +@Getter +@Setter +public class ResponsePart { + private OutputSpeech outputSpeech; + private List directives; + private boolean shouldEndSession; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/Art.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/Art.java new file mode 100644 index 0000000..41f16bb --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/Art.java @@ -0,0 +1,16 @@ +package ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:24 + */ +@Getter +@Setter +public class Art { + private String small; + private String middle; + private String large; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/AudioItem.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/AudioItem.java new file mode 100644 index 0000000..baa911a --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/AudioItem.java @@ -0,0 +1,15 @@ +package ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:19 + */ +@Getter +@Setter +public class AudioItem { + private Stream stream; + private MetaData metaData; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/Directive.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/Directive.java new file mode 100644 index 0000000..567e896 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/Directive.java @@ -0,0 +1,15 @@ +package ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:18 + */ +@Getter +@Setter +public class Directive { + private String type; //AudioPlay.Play + private AudioItem audioItem; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/MetaData.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/MetaData.java new file mode 100644 index 0000000..247aeb7 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/MetaData.java @@ -0,0 +1,19 @@ +package ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:23 + */ +@Getter +@Setter +public class MetaData { + private String id; + private String title; + private String albumId; + private String albumTitle; + private String artist; + private Art art; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/Stream.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/Stream.java new file mode 100644 index 0000000..da3f776 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/model/ResponseModel/responsePart/directive/Stream.java @@ -0,0 +1,15 @@ +package ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author 苗权威 + * @dateTime 19-6-25 上午11:22 + */ +@Getter +@Setter +public class Stream { + private String url; //audio url + private int offsetInMilliseconds; +} diff --git a/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/service/ParseService.java b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/service/ParseService.java new file mode 100644 index 0000000..9cfceb6 --- /dev/null +++ b/xiaoya/src/main/java/ai/qiwu/xiaoya/xiaoya/service/ParseService.java @@ -0,0 +1,134 @@ +package ai.qiwu.xiaoya.xiaoya.service; + +import ai.qiwu.xiaoya.xiaoya.common.Constants; +import ai.qiwu.xiaoya.xiaoya.model.RequestModel.RequestParams; +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.Response; +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.Session; +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.OutputSpeech; +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.ResponsePart; +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive.AudioItem; +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive.Directive; +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive.MetaData; +import ai.qiwu.xiaoya.xiaoya.model.ResponseModel.responsePart.directive.Stream; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * @author 苗权威 + * @dateTime 19-6-25 下午1:25 + */ +@Service("service") +public class ParseService { + + private static Logger logger = LoggerFactory.getLogger(ParseService.class); + + public Response getResponse(RequestParams params) { + Response curResponse = buildResponse(); + String userId = params.getContext().getSystem().getDevice().getIp(); + addSidToResponse(params, curResponse); + String userWord = params.getRequest().getAsr().getText(); + requestQiWuInterface(userId, userWord, curResponse); + return curResponse; + } + + private void requestQiWuInterface(String userId, String userWord, Response response) { + String audioUrl = ""; + String textContent = "请说推荐作品"; + CloseableHttpClient httpClient = null; + CloseableHttpResponse httpResponse = null; + try { + httpClient = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE); + + HashMap params = new HashMap<>(); + params.put("user_id", String.valueOf(userId)); + params.put("text", userWord); + params.put("access",Constants.SERVICE_NAME); + + String paramsJsonFormat = JSON.toJSONString(params); + StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8"); + post.setHeader("Content-Type", "application/json;charset=utf-8"); + post.setEntity(body); + + httpResponse = httpClient.execute(post); + HttpEntity responseBody = httpResponse.getEntity(); + if (responseBody != null) { + String responseContent = EntityUtils.toString(responseBody); + logger.info("齐悟接口返回: "+ responseContent); + JSONObject responseJsonFormat = JSONObject.parseObject(responseContent); + audioUrl = (String) responseJsonFormat.get("audio"); + textContent = (String) responseJsonFormat.get("text"); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (httpClient != null) httpClient.close(); + if (httpResponse != null) httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + addUrlAndTextToResponse(audioUrl, textContent, response); + } + + private void addUrlAndTextToResponse(String audioUrl, String text, Response response) { + response.getResponse().getOutputSpeech().setText(text); + response.getResponse().getDirectives().get(0).getAudioItem().getStream().setUrl(audioUrl); + } + + private void addSidToResponse(RequestParams params, Response response) { + response.getSession().setSid(params.getSession().getSid()); + } + + private Response buildResponse() { + Response response = new Response(); + response.setVersion("1.0.0"); + Session session = new Session(); + response.setSession(session); + + ResponsePart responsePart = new ResponsePart(); + + OutputSpeech outputSpeech = new OutputSpeech(); + outputSpeech.setType("plaintext"); + responsePart.setOutputSpeech(outputSpeech); + + Directive directive = new Directive(); + directive.setType("AudioPlay.Play"); + + AudioItem audioItem = new AudioItem(); + Stream stream = new Stream(); + stream.setOffsetInMilliseconds(0); + MetaData metaData = new MetaData(); + metaData.setId("27299018"); + metaData.setTitle("Any"); + audioItem.setStream(stream); + audioItem.setMetaData(metaData); + + directive.setAudioItem(audioItem); + + List directives = new ArrayList<>(); + directives.add(directive); + responsePart.setDirectives(directives); + + responsePart.setShouldEndSession(false); + + response.setResponse(responsePart); + return response; + } +} diff --git a/xiaoya/src/main/resources/application.properties b/xiaoya/src/main/resources/application.properties index 8b13789..1c5cff4 100644 --- a/xiaoya/src/main/resources/application.properties +++ b/xiaoya/src/main/resources/application.properties @@ -1 +1,6 @@ - +log4j.appender.D = org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File = /usr/mqw/logs/xiaoyas.log +log4j.appender.D.Append = true +log4j.appender.D.Threshold = DEBUG +log4j.appender.D.layout = org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n diff --git a/xiaoya/src/main/resources/logback.xml b/xiaoya/src/main/resources/logback.xml new file mode 100644 index 0000000..cc93d5b --- /dev/null +++ b/xiaoya/src/main/resources/logback.xml @@ -0,0 +1,42 @@ + + + + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + + + + + + + + /usr/mqw/logs/xiaoya/ + + + /usr/mqw/logs/xiaoya/base.log.%d.%i + + 64 MB + + + + + %d %p (%file:%line\)- %m%n + + UTF-8 + + + + + + \ No newline at end of file