Commit bfcc6e65 by 李进峰

update

parent cd474350
......@@ -112,6 +112,34 @@ public class OkHttp3Utils {
return null;
}
public static String singleChat(String url, String requestJsonStr, Map<String, String> headers, String uid)
throws IOException {
log.info("#####->singleChat->url:{}, requestJsonStr:{}, uid:{}", url, requestJsonStr, uid);
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
HttpUrl.Builder urlBuild = request.url().newBuilder();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
urlBuild.addQueryParameter("uid", uid);
builder.url(urlBuild.build()).headers(headBuilder.build())
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
Response response = client.newCall(builder.build()).execute();
try (ResponseBody body = response.body()) {
return body.string();
} catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} catch (Exception e) {
log.error("doPostJsonStrForCentralWithUidParam error:" + e);
}
return null;
}
public static String doPostJsonStrForCentralWithUidParam(String url, String requestJsonStr, Map<String, String> headers,
String uid) throws IOException {
Request.Builder builder = new Request.Builder();
......
package ai.qiwu.com.xiaoduhome.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ai.qiwu.com.xiaoduhome.service.SingleBotService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("")
@Slf4j
@RequiredArgsConstructor(onConstructor_={@Autowired})
public class AudioSingleBotController {
private final StringRedisTemplate stringRedisTemplate;
@PostMapping("/xiaodu/single/bot")
public String xiaodu(HttpServletRequest request) {
String botAccount = request.getParameter("botAccount");
String serverCode = request.getParameter("serverCode");
if(StringUtils.isAnyBlank(botAccount, serverCode)) {
return "参数错误!";
}
try {
SingleBotService service = new SingleBotService(botAccount, serverCode, request, stringRedisTemplate);
service.enableVerify();
String str = service.run();
return str;
} catch (Exception e) {
log.info("AudioSingleBotController->xiaodu->e:{}", ExceptionUtils.getStackTrace(e));
}
return null;
}
}
......@@ -84,7 +84,7 @@ public class SpiritController {
@PostMapping(value = "/encryption") // 智能小说加密版
public ResultModel<TaskResult> story(@RequestBody String taskQuery) {
// log.info("天猫请求信息:{}",taskQuery);
log.info("天猫请求信息:{}",taskQuery);
TaskResult result;
try {
SecurityWrapperTaskQuery wrapperTaskQuery = MetaFormat.parseToWrapperQuery(taskQuery);
......@@ -100,7 +100,7 @@ public class SpiritController {
ResultModel<TaskResult> resultModel = new ResultModel<>();
resultModel.setReturnCode("0");
resultModel.setReturnValue(result);
// log.info("天猫响应信息:"+ JSON.toJSONString(resultModel));
log.info("天猫响应信息:"+ JSON.toJSONString(resultModel));
return resultModel;
}
......
package ai.qiwu.com.xiaoduhome.service;
import static ai.qiwu.com.xiaoduhome.common.Constants.LOAD_INTRO;
import static ai.qiwu.com.xiaoduhome.common.Constants.PREFIX_USERID;
import static ai.qiwu.com.xiaoduhome.common.Constants.PRIVATE_KEY;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.BACK_TRACE;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.COLLECTED_IMG_URL;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.COLLEC_ID;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.FLOWE;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.FLOWER_LOAD;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.NEXT_PAGE_INDEX;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.PRE_CATEGORY;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.PRE_COLLE;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.UN_COLLECTED_IMG_URL;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.UN_COLLEC_ID;
import static ai.qiwu.com.xiaoduhome.common.Constants.ErrorMsg.SORRY_UNCATCH;
import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.COLLECED;
import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.FLOWER;
import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.UN_COLLEC;
import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.USER_SEND_FLOWER;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.dueros.bot.BaseBot;
import com.baidu.dueros.data.request.IntentRequest;
import com.baidu.dueros.data.request.LaunchRequest;
import com.baidu.dueros.data.request.Query;
import com.baidu.dueros.data.request.RequestBody;
import com.baidu.dueros.data.request.SessionEndedRequest;
import com.baidu.dueros.data.request.audioplayer.event.AudioPlayerEvent;
import com.baidu.dueros.data.request.audioplayer.event.PlaybackFinishedEvent;
import com.baidu.dueros.data.request.audioplayer.event.PlaybackNearlyFinishedEvent;
import com.baidu.dueros.data.request.audioplayer.event.PlaybackStartedEvent;
import com.baidu.dueros.data.request.audioplayer.event.PlaybackStoppedEvent;
import com.baidu.dueros.data.request.events.LinkAccountSucceededEvent;
import com.baidu.dueros.data.request.events.NextRequired;
import com.baidu.dueros.data.request.pay.event.ChargeEvent;
import com.baidu.dueros.data.response.OutputSpeech;
import com.baidu.dueros.data.response.card.Card;
import com.baidu.dueros.data.response.card.LinkAccountCard;
import com.baidu.dueros.data.response.directive.Directive;
import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective;
import com.baidu.dueros.data.response.directive.audioplayer.Play;
import com.baidu.dueros.data.response.directive.dpl.ExecuteCommands;
import com.baidu.dueros.data.response.directive.dpl.RenderDocument;
import com.baidu.dueros.data.response.directive.dpl.commands.UpdateComponentCommand;
import com.baidu.dueros.data.response.directive.dpl.event.UserEvent;
import com.baidu.dueros.data.response.directive.pay.Charge;
import com.baidu.dueros.model.Response;
import ai.qiwu.com.xiaoduhome.common.Constants;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
import ai.qiwu.com.xiaoduhome.common.Utils;
import ai.qiwu.com.xiaoduhome.common.Constants.EndMsg;
import ai.qiwu.com.xiaoduhome.common.Constants.ErrorMsg;
import ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO;
import ai.qiwu.com.xiaoduhome.common.temple.CollectHistoryDocument;
import ai.qiwu.com.xiaoduhome.common.temple.TempleUtils;
import ai.qiwu.com.xiaoduhome.common.temple.onLunch.LunchDocument;
import ai.qiwu.com.xiaoduhome.common.temple.onLunch.LunchUtils;
import ai.qiwu.com.xiaoduhome.common.temple.play.PlayDocument;
import ai.qiwu.com.xiaoduhome.common.temple.play.PlayUtils;
import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoDocument;
import ai.qiwu.com.xiaoduhome.common.temple.productInfo.ProductInfoUtils;
import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommandDocument;
import ai.qiwu.com.xiaoduhome.common.temple.recommand.RecommendUtil;
import ai.qiwu.com.xiaoduhome.pojo.DialogData;
import ai.qiwu.com.xiaoduhome.pojo.ExitData;
import ai.qiwu.com.xiaoduhome.pojo.data.ProjectData;
import ai.qiwu.com.xiaoduhome.spirit.SpiritRedisService;
import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SingleBotService extends BaseBot {
private final StringRedisTemplate stringRedisTemplate;
private final String channel = "xiaodu-single-bot-jiaoyou-dev";
private final String ccSingleChatUrl;
private final String botAccount;
private String getBaseUrlByServerCode(String serverCode) {
String baseUrl = "";
switch (serverCode) {
case "gz25":
baseUrl = "http://hw-gz25.heyqiwu.cn:8070";
break;
case "gz33":
baseUrl = "http://hw-gz15.heyqiwu.cn:8070";
break;
}
return baseUrl;
}
public SingleBotService(String botAccount, String serverCode, HttpServletRequest request,
StringRedisTemplate stringRedisTemplate) throws IOException {
super(request);
this.stringRedisTemplate = stringRedisTemplate;
// privateKey为私钥内容,0代表你的Bot在DBP平台debug环境,1或者其他整数代表online环境,
// botMonitor对象已经在bot-sdk里初始化,可以直接调用
this.botMonitor.setEnvironmentInfo(PRIVATE_KEY, 1);
this.botMonitor.setMonitorEnabled(true);
this.ccSingleChatUrl = getBaseUrlByServerCode(serverCode) + "/api/chat/single/bot";
this.botAccount = botAccount;
}
@Override
public Response onLaunch(LaunchRequest launchRequest) {
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "欢迎来到单个作品测试,请说任意话语开始!");
return new Response(outputSpeech);
}
@Override
protected Response onInent(IntentRequest intentRequest) {
final String userId = customUserId();
String audioUrl = ScheduleServiceNew.BASE_AUDIO_URL;
String cdnUrl = ScheduleServiceNew.CDN_HOST_URL;
if (ScheduleServiceNew.SERVER_CHANGE) {
if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.SERVER_CHANGE_KEY))) {
if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY + userId))) {
stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY + userId, 4, TimeUnit.MINUTES);
} else {
stringRedisTemplate.opsForValue().set(Constants.CAN_NOT_MOVE_USER_KEY + userId, "1", 4,
TimeUnit.MINUTES);
}
audioUrl = ScheduleServiceNew.OLD_BASE_AUDIO_URL;
cdnUrl = ScheduleServiceNew.OLD_CDN_HOST_URL;
} else if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(Constants.CAN_NOT_MOVE_USER_KEY + userId))) {
stringRedisTemplate.expire(Constants.CAN_NOT_MOVE_USER_KEY + userId, 4, TimeUnit.MINUTES);
audioUrl = ScheduleServiceNew.OLD_BASE_AUDIO_URL;
cdnUrl = ScheduleServiceNew.OLD_CDN_HOST_URL;
}
}
String redisId = SpiritRedisService.PREFIX_REDIS + userId;
try {
if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(redisId))) {
String data = stringRedisTemplate.opsForValue().get(redisId);
log.warn("超时redis获取信息:" + data);
if (StringUtils.isNotBlank(data)) {
String redisIdleId = SpiritRedisService.PREFIX_REDIS_IDLE + userId;
if (data.equals("out")) {
String idleNum = stringRedisTemplate.opsForValue().get(redisIdleId);
boolean firstIdle;
if ((firstIdle = StringUtils.isBlank(idleNum)) || "1".equals(idleNum)) {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
if (firstIdle)
idleNum = "1";
else
idleNum = "2";
stringRedisTemplate.opsForValue().set(redisIdleId, idleNum, 15, TimeUnit.SECONDS);
return buildErrorResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1
: XiaoAiConstants.TTS.WAIT_WORD_2);
} else {
stringRedisTemplate.delete(redisIdleId);
stringRedisTemplate.delete(redisId);
}
} else {
stringRedisTemplate.delete(redisId);
stringRedisTemplate.delete(redisIdleId);
Directive play = buildNoScreenPlayDirec(data,
AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
addDirective(play);
return new Response();
}
} else {
stringRedisTemplate.delete(redisId);
}
}
} catch (Exception e) {
log.error("xiaodu redis error:" + e);
}
try {
final String finalAudioUrl = audioUrl;
final String finalCdnUrl = cdnUrl;
Future<Response> future = DplbotServiceUtil.getPOOL().submit(
() -> dealNoScreenIntentTemp(intentRequest, userId, ccSingleChatUrl, finalAudioUrl, finalCdnUrl));
return future.get(2500, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
return buildErrorResponse(SORRY_UNCATCH);
} catch (TimeoutException e) {
log.warn("超时,让用户再说一遍:{}");
stringRedisTemplate.opsForValue().setIfAbsent(redisId, "out", 15, TimeUnit.SECONDS);
return buildErrorResponse(SORRY_UNCATCH);
} catch (Exception all) {
log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
return buildErrorResponse(SORRY_UNCATCH);
}
}
String requestTerminateUrl(String userWord, String userId, String channel, String baseHostUrl) throws IOException {
JSONObject requestBody = new JSONObject();
requestBody.put("uid", userId);
requestBody.put("botAccount", botAccount);
requestBody.put("msg", userWord);
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
headers.put("App-Channel-Id", channel);
// return OkHttp3Utils.doPostJsonStr(baseHostUrl, requestJsonStr, headers);
return OkHttp3Utils.singleChat(baseHostUrl, requestBody.toJSONString(), headers, userId);
}
private Response dealNoScreenIntentTemp(IntentRequest intentRequest, String userId, String baseUrl, String audioUrl,
String cdnUrl) {
try {
final Query query = intentRequest.getQuery();
final String userWord = query.getOriginal();
// if (query != null) userWord = query.getOriginal();
if (userWord == null) {
log.error("小度没有传来任何话语");
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
String requestBodyStr = this.requestTerminateUrl(userWord, userId, channel, baseUrl);
log.info("小度,小悟返回:{},", requestBodyStr);
if (StringUtils.isBlank(requestBodyStr)) {
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
// String mark = RandomStringUtils.randomAlphabetic(3);
// AudioBoxData pathData = new AudioBoxData();
// OkHttp3Utils.asyncPost(XiaoAiConstants.TTS_DIDI3, response, pathData);
JSONObject requestBody = JSON.parseObject(requestBodyStr);
if (requestBody.getIntValue("code") == 1) {
JSONObject data = requestBody.getJSONObject("data");
String botAudioUrl = data.getString("audioUrl");
if (StringUtils.isBlank(botAudioUrl) || "null".equals(botAudioUrl)) {
log.error("小度没有获取到音频链接");
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
Directive play = buildNoScreenPlayDirec(botAudioUrl, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
addDirective(play);
}
} catch (Exception e) {
log.error("#######################");
}
return new Response();
}
private String dealAudioUrl(String path) {
return ScheduleServiceNew.BASE_AUDIO_URL + "/api/audio/get?path=" + path;
}
private Play buildNoScreenPlayDirec(String audioUrl, AudioPlayerDirective.PlayBehaviorType type) {
return new Play(type, audioUrl, 0);
}
@Override
protected Response onUserEvent(UserEvent userEvent) {
try {
// log.info("onUserEvent事件触发,token:{},
// componentId:{}",userEvent.getToken(),userEvent.getPayload().getComponentId());
if (getAccessToken() != null && getSessionAttribute("userId") == null) {
String userId = DplbotServiceUtil.getUsUserId(getUserId(), getAccessToken(), channel);
setSessionAttribute("userId", userId);
}
String componentId = userEvent.getPayload().getComponentId();
String componentPrefix;
if ("audio".equals(componentId)) {
if (getSessionAttribute("end") != null) {
try {
setSessionAttribute("end", null);
String endId = SpiritRedisService.PREFIX_REDIS + getUserId() + "_end";
String recommand = stringRedisTemplate.opsForValue().get(endId);
log.info("end play ended: recommand->" + recommand);
if (StringUtils.isNotBlank(recommand)) {
stringRedisTemplate.delete(endId);
String path = OkHttp3Utils
.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL + "9663/api/audio", recommand);
if (StringUtils.isBlank(path) || "null".equals(path)) {
log.error("小度没有获取到音频链接");
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
ExitData exitData = JSON.parseObject(recommand, ExitData.class);
String text = null;
for (DialogData data : exitData.getDialogs()) {
if (data.getBotAccount().equals(exitData.getAipioneerUsername())) {
text = data.getText();
break;
}
}
if (StringUtils.isBlank(text))
return new Response();
RecommandDocument document = displayFunnyRecommandPage(text, dealAudioUrl(path));
if (document != null) {
RenderDocument render = new RenderDocument(document);
addDirective(render);
setSessionAttribute(PRE_COLLE, document.getRecommendIdList());
setSessionAttribute(BACK_TRACE, "06");
}
return new Response();
}
} catch (Exception e) {
this.setExpectSpeech(true);
log.warn(ExceptionUtils.getStackTrace(e));
}
} else {
setExpectSpeech(true);
}
} else if (Constants.PRE_PRODUCT_IMG.equals((componentPrefix = componentId.substring(0, 5)))) {
// 作品图片点击事件
String accessToken = getAccessToken();
String userId = getUserId();
String productName = componentId.substring(5);
ProjectData productDetail = ScheduleServiceNew.getProjectByName(productName);
if (productDetail == null) {
return buildErrorResponse("目前不支持该作品");
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(productDetail.getCreateTime());
String time = new StringBuilder(PRODUCT_INTRO.CREATE_TIME).append(dateString).toString();
String author = new StringBuilder(PRODUCT_INTRO.AUTHOR).append(productDetail.getAuthorName())
.toString();
StringBuilder labels = new StringBuilder(PRODUCT_INTRO.LABEL);
for (String label : productDetail.getLabels()) {
labels.append(PRODUCT_INTRO.SPACE).append(label);
}
String intro = productDetail.getIntro();
String enterProName = new StringBuilder(Constants.PRE_ENTER_PRODUCT).append(productName).toString();
// "start product" container button
String flowers, flowerReward, collectText, collectUrl, collectComId;
if (accessToken != null) {
// flower container button
Long flowerCount = DplbotServiceUtil.getUserSendFlowerNum(productDetail.getBotAccount(), userId,
channel, accessToken, getSessionAttribute("userId"));
flowers = USER_SEND_FLOWER + flowerCount;
flowerReward = new StringBuilder(FLOWE).append(productDetail.getBotAccount()).toString();
// collection container button
boolean collec = DplbotServiceUtil.didUserCollecThisProduct(productDetail.getBotAccount(), userId,
accessToken, getSessionAttribute("userId"));
if (collec) {
collectText = COLLECED;
collectUrl = COLLECTED_IMG_URL;
collectComId = new StringBuilder(UN_COLLEC_ID).append(productDetail.getBotAccount()).toString();
} else {
collectText = UN_COLLEC;
collectUrl = UN_COLLECTED_IMG_URL;
collectComId = new StringBuilder(COLLEC_ID).append(productDetail.getBotAccount()).toString();
}
} else {
flowers = FLOWER;
flowerReward = FLOWER_LOAD;
collectText = UN_COLLEC;
collectUrl = UN_COLLECTED_IMG_URL;
collectComId = FLOWER_LOAD;
}
ProductInfoDocument document = ProductInfoUtils.getProductINfoDocument(productDetail.getBannerImgUrl(),
correctName(productName), time, author, labels.toString(), intro, enterProName, flowerReward,
flowers, collectComId, collectUrl, collectText);
RenderDocument renderDocument = new RenderDocument(document);
this.addDirective(renderDocument);
// this.addDirective(new PushStack());
String trace = getSessionAttribute(BACK_TRACE);
log.info("before trace------------:{}", trace);
StringBuilder builder = new StringBuilder();
if (trace == null || trace.length() < 2) {
builder.append("00");
} else if (trace.length() > 2) {
builder.append(trace, 0, 2);
} else {
builder.append(trace);
}
trace = builder.append(productDetail.getBotAccount()).toString();
log.info("after trace------------:{}", trace);
this.setSessionAttribute(BACK_TRACE, trace);
return new Response();
} else if (Constants.PRE_ENTER_PRODUCT.equals(componentPrefix)) {
String productName = componentId.substring(5);
String enterProductWord = new StringBuilder(Constants.PRE_PRODUCT_PLAY).append(productName).toString();
log.info("进入作品语句:{}", enterProductWord);
String data = null;
try {
data = RequestTerminal.requestTerminateTemp(enterProductWord, getUserId(), channel);
} catch (IOException e) {
log.error("请求终端接口出错:", e.toString());
}
if (data == null) {
return buildErrorResponse(SORRY_UNCATCH);
}
String path = null;
try {
path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL + "9663/api/audio", data);
} catch (Exception e) {
log.warn("没有获取到TTS返回地址");
}
if (StringUtils.isBlank(path) || "null".equals(path)) {
log.error("小度没有获取到音频链接");
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
String botID = ScheduleServiceNew.getBotAccountByWorkname(productName);
PlayDocument document = PlayUtils.getPlayDocument(productName,
DplbotServiceUtil.getTheActorsWithWords(JSON.parseObject(data).getJSONArray("dialogs"), botID),
dealAudioUrl(path), botID);
RenderDocument render = new RenderDocument(document);
this.setSessionAttribute(PRE_COLLE, null);
String trace = getSessionAttribute(BACK_TRACE);
if (trace == null || trace.length() < 2)
trace = "00";
else if (trace.length() > 2)
trace = trace.substring(0, 2);
this.setSessionAttribute(BACK_TRACE,
new StringBuilder(trace).append(botID).append(File.separator).toString());
this.addDirective(render);
} else if (FLOWE.equals(componentPrefix)) {
if (FLOWER_LOAD.equals(componentId)) {
return load();
} else {
// Buy buy = new Buy(FLOWER_PRODUCT_ID);
// String token = new String(Base64.getEncoder().encode(componentId.substring(5).getBytes()), StandardCharsets.UTF_8);
// buy.setToken(token);
// addDirective(buy);
// OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, REWARD_FLOWER);
// return new Response(outputSpeech);
Charge charge = DplbotServiceUtil.sendOneFlowerByCharge(getUserId(), getSessionAttribute("userId"),
getAccessToken(), getSessionAttribute("trace"), channel);
if (charge != null) {
addDirective(charge);
return buildErrorResponse("扫描屏幕上的二维码完成支付");
}
return new Response();
}
} else if ("loadingPage".equals(componentId)) {
RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
addDirective(renderDocument);
return new Response();
// this.addDirective(new PushStack());
// addDirective(new SendPart("lunch"));
} else if (PRE_COLLE.equals(componentPrefix)) {
boolean isUnCollect = "Un".equals(componentId.substring(5, 7));
final String botId = componentId.substring(7);
if (isUnCollect) {
// 取消收藏
if (DplbotServiceUtil.userUnCollectTheBot(getUserId(), botId, channel,
getSessionAttribute("userId"), getAccessToken())) {
changeIconIdTextAfterCollect(false, botId);
}
} else {
// 收藏
if (DplbotServiceUtil.userCollectTheBot(getUserId(), botId, channel, getSessionAttribute("userId"),
getAccessToken())) {
changeIconIdTextAfterCollect(true, botId);
}
}
} else if (PRE_CATEGORY.equals(componentPrefix)) {
String category = componentId.substring(5);
// 分类推荐页面相同
RecommandDocument document = RecommendUtil.getCategory(0, category);
if (document == null)
return buildErrorResponse("不好意思该分类还没有作品");
RenderDocument render = new RenderDocument(document);
this.addDirective(render);
this.setSessionAttribute("category", category);
this.setSessionAttribute("trace", "75");
} else if ("playButton".equals(componentId)) {
return buildErrorResponse("您可以直接对我说我要送花或者我要收藏或取消收藏");
} else if ("lunchCollect".equals(componentId)) {
return dealOpenCollectClick();
} else if ("lunchHistory".equals(componentId)) {
return dealHistoryClick();
}
// else if ("funnyChange".equals(componentId)) {
// ExecuteCommands executeCommands = new ExecuteCommands();
// AutoPageCommand page = new AutoPageCommand();
// page.setComponentId("funnyPage");
// page.setDurationInMillisecond(2000);
// executeCommands.addCommand(page);
// this.addDirective(executeCommands);
// }
} catch (Exception e) {
log.error("onUserEvent error:{}", ExceptionUtils.getStackTrace(e));
}
return new Response();
}
@Override
protected Response onSessionEnded(SessionEndedRequest sessionEndedRequest) {
switch (sessionEndedRequest.getReason()) {
case ERROR:
dealWithError(sessionEndedRequest);
break;
case USER_INITIATED:
log.info(EndMsg.USER_SAY_CANCEL);
break;
case EXCEEDED_MAX_REPROMPTS:
log.info(EndMsg.CAN_NOT_UNDERSTAND);
break;
}
if (isNoScreenRequest()) {
String userId = customUserId();
String byeWord = EndMsg.END_BYE_Adult;
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
RequestTerminal.backRequest(userId, 5);
if (ScheduleServiceNew.SERVER_CHANGE)
stringRedisTemplate.delete(Constants.CAN_NOT_MOVE_USER_KEY + userId);
// try {
// if (DU_DEVICE_ID.equals(deviceId)) {
// RequestTerminal.backRequest(DU_DEVICE_ID, type);
// } else {
// RequestTerminal.backRequestDU2(deviceId, type);
// }
// } catch (Exception e) {
// log.warn("用户退出向中控发出退出指令出错");
// }
return new Response(outputSpeech);
} else {
String byeWord = EndMsg.END_BYE_JIAOYOU;
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
RequestTerminal.backRequest(getUserId(), 5);
return new Response(outputSpeech);
}
}
private void dealWithError(SessionEndedRequest request) {
switch (request.getError().getType()) {
case INTERNAL_ERROR:
log.info(ErrorMsg.INTERNAL_ERROR);
break;
case INVALID_RESPONSE:
log.info(ErrorMsg.INVALID_RESPONSE);
break;
case DEVICE_COMMUNICATION_ERROR:
log.info(ErrorMsg.DEVICE_COMMUNICATION_ERROR);
break;
}
log.info("错误信息 : " + request.getError().getMessage());
}
private Response dealHistoryClick() {
CollectHistoryDocument document = DplbotServiceUtil.getHistory(getUserId(), getAccessToken(),
getSessionAttribute("userId"), 0, channel);
if (document == null)
return buildErrorResponse("不好意思,您太久没玩记录被清空了");
RenderDocument render = new RenderDocument(document);
addDirective(render);
setSessionAttribute(PRE_COLLE, document.getIdToken());
setSessionAttribute("recommand", null);
setSessionAttribute(NEXT_PAGE_INDEX, null);
setSessionAttribute(BACK_TRACE, "02");
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开历史记录");
return new Response(outputSpeech);
}
private Response dealOpenCollectClick() {
if (getAccessToken() == null) {
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "该功能需要登录,请说小度小度,登录");
return new Response(outputSpeech);
} else {
String appUserId = getSessionAttribute("userId");
if (appUserId == null) {
appUserId = DplbotServiceUtil.getUsUserId(getUserId(), getAccessToken(), channel);
if (appUserId == null) {
return new Response();
}
}
CollectHistoryDocument document = DplbotServiceUtil.getCollectPage(getUserId(), getAccessToken(), appUserId,
0, channel);
if (document != null) {
RenderDocument render = new RenderDocument(document);
addDirective(render);
setSessionAttribute(NEXT_PAGE_INDEX, null);
setSessionAttribute(PRE_COLLE, document.getIdToken());
setSessionAttribute(BACK_TRACE, "01");
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "正在为您打开收藏夹");
return new Response(outputSpeech);
}
}
return new Response();
}
private ExecuteCommands changeIconIdTextAfterCollect(boolean collect, String botId) {
ExecuteCommands executeCommands = new ExecuteCommands();
UpdateComponentCommand update = new UpdateComponentCommand();
String srcValue;
String textValue;
String idValue;
String previousClickId;
String unCollectId = new StringBuilder(UN_COLLEC_ID).append(botId).toString();
String collectId = new StringBuilder(COLLEC_ID).append(botId).toString();
if (collect) {
srcValue = COLLECTED_IMG_URL;
textValue = COLLECED;
idValue = unCollectId;
previousClickId = collectId;
} else {
srcValue = UN_COLLECTED_IMG_URL;
textValue = UN_COLLEC;
idValue = collectId;
previousClickId = unCollectId;
}
update.setComponentId(previousClickId);
update.setDocument(TempleUtils.getCollectIcon(idValue, srcValue, textValue));
executeCommands.addCommand(update);
this.addDirective(executeCommands);
return executeCommands;
}
private Response load() {
Card card = new LinkAccountCard();
Response response = buildErrorResponse(LOAD_INTRO);
response.setCard(card);
return response;
}
private static String correctName(String name) {
int brace = name.indexOf("{");
if (brace != -1)
name = name.substring(0, brace);
return name;
}
@Override
protected Response onLinkAccountSucceededEvent(LinkAccountSucceededEvent linkAccountSucceededEvent) {
log.info("登录成功返回信息:{}", linkAccountSucceededEvent);
String accessToken = getAccessToken();
String jytUserId;
if (!isNoScreenRequest()) {
log.info("检测到有屏登录");
String userId = getUserId();
jytUserId = DplbotServiceUtil.getUserIdByToken(accessToken, channel, userId);
DplbotServiceUtil.onLunchFillUserBehaviorData(userId, channel, jytUserId, true);
DplbotServiceUtil.noticeOtherServer(5, null, null, false, userId, jytUserId, channel, false);
if (jytUserId == null)
log.warn("登录后获取用户的app id 失败");
} else {
jytUserId = DplbotServiceUtil.getUserIdByToken(accessToken, null, getUserId());
if (jytUserId == null)
log.warn("登录后获取用户的app id 失败");
}
setSessionAttribute("userId", jytUserId);
return buildErrorResponse("您已登录成功");
}
private Response buildErrorResponse(String errorMsg) {
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
return new Response(outputSpeech);
}
private RecommandDocument displayFunnyRecommandPage(String word, String audio) {
try {
List<String> botNames = Utils.getRecommandBotNames(word);
log.info("botNames:{}", botNames);
List<ProjectData> bots = new ArrayList<>();
for (String botName : botNames) {
ProjectData detail = ScheduleServiceNew.getProjectByName(botName);
if (detail == null)
continue;
bots.add(detail);
}
if (bots.size() != 0)
return RecommendUtil.getFunnyDocument(bots, audio);
} catch (Exception e) {
log.error("获取funny页出错:{}", e.toString());
}
return null;
}
@Override
protected Response onChargeEvent(ChargeEvent chargeEvent) {
String token = chargeEvent.getToken();
String[] tokens = token.split(File.separator);
log.info("onChargeEvent token:" + token);
final String botAccount = tokens[0];
String str = "恭喜您支付成功,开始体验吧";
if (!isNoScreenRequest()) {
String userId = getUserId();
String jytUserId = getSessionAttribute("userId");
Boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, userId, getAccessToken(), jytUserId,
ScheduleServiceNew.getWorkNameByBotAccount(botAccount), channel);
log.info("onChargeEvent response:" + response);
if (Boolean.TRUE.equals(response)) {
str = "恭喜您支付成功";
} else {
str = "很抱歉,您没有支付成功";
}
// String trace = getSessionAttribute(BACK_TRACE);
// if (trace.length()>2 && !StringUtils.endsWith(trace, File.separator)) {
// backToBotIntro(trace.substring(2, trace.length()-1), channel);
// }
} else {
String userId = customUserId();
String jytUserId = getSessionAttribute("userId");
if (StringUtils.isBlank(jytUserId))
jytUserId = DplbotServiceUtil.getUserIdByToken(getAccessToken(), channel, getUserId());
if (StringUtils.isBlank(jytUserId)) {
jytUserId = "null";
}
boolean response = DplbotServiceUtil.dealChargeCallback(chargeEvent, userId, getAccessToken(), jytUserId,
ScheduleServiceNew.getWorkNameByBotAccount(botAccount), channel);
if (!response) {
str = "很抱歉,您没有支付成功";
}
}
return buildErrorResponse(str);
}
@Override
protected Response onPlaybackFinishedEvent(PlaybackFinishedEvent playbackFinishedEvent) {
// log.info("音频播放完毕,开麦");
// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
// log.error("FinishedEvent");
this.setExpectSpeech(true);
return new Response();
}
@Override
protected Response onPlaybackStoppedEvent(PlaybackStoppedEvent playbackStoppedEvent) {
// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
waitAnswer();
return new Response();
}
@Override
protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
// if (isNoScreenRequest()) {
// Boolean result = stringRedisTemplate.delete(SpiritRedisService.PREFIX_REDIS+customUserId());
// log.info("音频播放事件删除:"+result);
// }
waitAnswer();
return new Response();
}
@Override
protected Response onPlaybackNearlyFinishedEvent(PlaybackNearlyFinishedEvent playbackNearlyFinishedEvent) {
// setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
waitAnswer();
return new Response();
}
@Override
protected Response onNextRequiredEvent(NextRequired nextRequired) {
try {
switch (nextRequired.getToken()) {
case "lunch": {
RenderDocument renderDocument = new RenderDocument(LunchUtils.getLunchDocument());
addDirective(renderDocument);
break;
}
case "lunchBottom": {
String src = getSessionAttribute("lunchBottom");
if (StringUtils.isNotBlank(src)) {
LunchDocument document = LunchUtils.getLunchDocument();
document.getMainTemplate().getItems().add(LunchUtils.buildAudioComponent(src));
RenderDocument renderDocument = new RenderDocument(document);
addDirective(renderDocument);
setSessionAttribute("lunchBottom", null);
return new Response();
}
break;
}
case "direct": {
String userId = SpiritRedisService.PREFIX_REDIS_DIRECT + getUserId();
String data = stringRedisTemplate.opsForValue().get(userId);
log.info("send part direct:" + data);
if (StringUtils.isNotBlank(data)) {
stringRedisTemplate.delete(userId);
String path = null;
try {
path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_HOST_URL + "9663/api/audio", data);
} catch (Exception e) {
log.warn("没有获取到TTS返回地址");
}
if (StringUtils.isBlank(path) || "null".equals(path)) {
log.error("小度没有获取到音频链接");
return buildErrorResponse("由于网络原因,小悟没有获取到结果,您可以通过点击来进入游戏");
}
JSONObject object = JSON.parseObject(data);
String botId = object.getString("aipioneerUsername");
PlayDocument document = PlayUtils.getPlayDocument(ScheduleServiceNew.getWorkNameByBotAccount(botId),
DplbotServiceUtil.getTheActorsWithWords(object.getJSONArray("dialogs"), botId),
dealAudioUrl(path), botId);
RenderDocument render = new RenderDocument(document);
this.setSessionAttribute(PRE_COLLE, null);
String trace = getSessionAttribute(BACK_TRACE);
if (trace == null || trace.length() != 2)
trace = "00";
String backTrace = new StringBuilder(trace).append(botId).append(File.separator).toString();
this.setSessionAttribute(BACK_TRACE, backTrace);
this.addDirective(render);
} else {
log.warn("direct can not get data," + userId);
return buildErrorResponse("不好意思好像出了什么问题,请再说一边吧");
}
}
// case "payed" : {
// log.info("success pay part");
// String trace = getSessionAttribute(BACK_TRACE);
// if (StringUtils.isNotBlank(trace)) {
// String word = USER_SEND_FLOWER+USER_HISTORY.get(getUserId()).getUserBotId2Flowers().get(trace.substring(2));
// log.info("flower num update:"+word);
// ExecuteCommands executeCommands = new ExecuteCommands();
// SetStateCommand stateCommand = new SetStateCommand();
// stateCommand.setComponentId("pft");
// stateCommand.setState("text");
// stateCommand.setValue(word);
// executeCommands.addCommand(stateCommand);
// addDirective(executeCommands);
// }
// }
}
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
}
return new Response();
}
@Override
protected Response onDefaultEvent() {
RequestBody requestBody = getRequest().getRequest();
if (requestBody instanceof AudioPlayerEvent) {
this.setExpectSpeech(true);
return new Response();
}
return new Response();
}
private String customUserId() {
try {
return PREFIX_USERID + URLEncoder.encode(getUserId(), "UTF-8");
} catch (Exception e) {
log.error("xiaodu userid encode error:{}, {}", e, getUserId());
return PREFIX_USERID + getUserId().replaceAll("/", "");
}
// return PREFIX_USERID + ai.qiwu.com.xiaoduhome.xiaoai.common.Utils.modifyDeviceId(getUserId());
// return PREFIX_USERID + getUserId().replaceAll(NUM_OR_ALPHA, "");
}
private boolean isNoScreenRequest() {
// return getSupportedInterfaces().getDPL() == null;
return getSupportedInterfaces().getDisplay() == null;
}
public static void main(String[] args) throws IOException {
String result = RequestTerminal.requestTerminateTemp("退出吧", "234325626", "jiaoyou-audio-test");
System.out.println(result);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment