From cd474350270a1e8a1f9c065f6221f51f00e915cf Mon Sep 17 00:00:00 2001 From: 苗权威 <1160292058@qq.com> Date: Sat, 30 Jan 2021 10:59:48 +0800 Subject: [PATCH] 0130 --- xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Config.java | 1 + xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/dpl2/Dpl2Service.java | 102 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------- xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplbotServiceUtil.java | 8 ++++++++ xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java | 5 +++++ xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java | 20 +++++++++++++++++++- 5 files changed, 103 insertions(+), 33 deletions(-) diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Config.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Config.java index 6a69671..ca811f7 100755 --- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Config.java +++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/common/Config.java @@ -10,6 +10,7 @@ import java.nio.charset.StandardCharsets; import java.util.Properties; /** + * 读取配置文件数据工具类 * @author 苗权威 * @dateTime 19-7-30 下午2:40 */ diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/dpl2/Dpl2Service.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/dpl2/Dpl2Service.java index 9d54cbc..73b6562 100644 --- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/dpl2/Dpl2Service.java +++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/dpl2/Dpl2Service.java @@ -37,7 +37,6 @@ 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.ScrollToElementCommand; import com.baidu.dueros.data.response.directive.dpl.commands.ScrollToIndexCommand; -import com.baidu.dueros.data.response.directive.dpl.commands.UpdateDataSourceCommand; 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; @@ -78,8 +77,8 @@ import static ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil.POOL; @Slf4j public class Dpl2Service extends BaseBot { - private static Document FIRST_PAGE; - private static Document categoryPage; + private static Document FIRST_PAGE; // 欢迎画面 + private static Document categoryPage; // 作品标签分类页 private static JsonNode colHisPageData; private static JsonNode productListPageData; @@ -88,6 +87,7 @@ public class Dpl2Service extends BaseBot { private static JsonNode recommendPageData; private static JsonNode productDetailPageData; + // 初始化时将页面固定数据信息构建成对象,使用时直接深度拷贝再添加各自数据 static { try { FIRST_PAGE = ScheduleServiceNew.objectMapper.readValue(DplbotServiceUtil.getDPLTemple("static/dpl2/firstPage.json"), Document.class); @@ -112,10 +112,10 @@ public class Dpl2Service extends BaseBot { } } - private final String channel; - private final StringRedisTemplate stringRedisTemplate; + private final String channel; // 渠道 + private final StringRedisTemplate stringRedisTemplate; // redis - private String customUserId; + private String customUserId; // 变化后的用户id public Dpl2Service(HttpServletRequest request, StringRedisTemplate stringRedisTemplate) throws IOException { super(request); @@ -125,17 +125,24 @@ public class Dpl2Service extends BaseBot { this.botMonitor.setEnvironmentInfo(PRIVATE_KEY, 1); } + /** + * 进入技能先展示一个欢迎画面,停顿几秒后转到首页 + * @param launchRequest + * @return + */ @Override protected Response onLaunch(LaunchRequest launchRequest) { - RenderDocument renderDocument = new RenderDocument(FIRST_PAGE); + RenderDocument renderDocument = new RenderDocument(FIRST_PAGE); // 欢迎画面 this.addDirective(renderDocument); // 初次进入时创建用户的行为信息,包括历史记录,送花数,收藏记录 // 历史记录,收藏记录,送花数,郊游天下id final String accessToken = getAccessToken(); final String userId = customUserId(); if (accessToken == null) { + // 未登录状态 DplbotServiceUtil.onLunchFillUserBehaviorDataInMaster(userId, channel, null, false); } else { + // 已登录, 首先查看redis缓存中是否有用户的行为数据缓存 UserBehaviorData data = DplbotServiceUtil.getRedisTemplate().opsForValue().get(userId); String jytUserId = null; if (data != null) jytUserId = data.getJytUserId(); @@ -144,11 +151,17 @@ public class Dpl2Service extends BaseBot { UserBehaviorData behaviorData = DplbotServiceUtil.onLunchFillUserBehaviorDataInMaster(userId, channel, jytUserId, true); log.info("onLunch data:"+behaviorData); } + // 确保重新进入的用户在推荐bot而不是之前的某作品bot POOL.submit(() -> RequestTerminal.backRequestByChannel(userId, channel)); - setSessionAttribute(BACK_TRACE, null); + setSessionAttribute(BACK_TRACE, null); // 确保与百度平台的交流数据中旧数据的干扰 return new Response(); } + /** + * 该方法与DplBotServiceBoth的oneIntent基本一致,详细解释在那 + * @param intentRequest + * @return + */ @Override protected Response onInent(IntentRequest intentRequest) { String redisId = SpiritRedisService.PREFIX_REDIS+customUserId(); @@ -490,40 +503,46 @@ public class Dpl2Service extends BaseBot { if (StringUtils.isBlank(data)) { return buildTextResponse(SORRY_UNCATCH); } + // 接下来解析中控的数据,如果用户的话语命中某些预设的意图被中控识别出,则数据中会有相关命令,比如下一页,往下滑,刷新...等 + // 处理不同意图 try { + // 数据中的commands字段存在,说明命中了某个意图 List commands = centralResponse.getCommands(); if (commands != null && commands.size() == 1) { String txt = commands.get(0).getText(); int i; + // 取出指令 if (StringUtils.isNotBlank(txt) && (i = txt.indexOf("☛")) != -1) { int end = txt.indexOf("☚"); - String command = txt.substring(i+1, end).trim(); + String command = txt.substring(i+1, end).trim();// 指令 if (StringUtils.isNotBlank(command)) { - if (command.contains("out")) { + if (command.contains("out")) { // 退出指令 log.info("小度,推荐bot退出:{},{}",word,userId); return buildTextResponse("本技能暂不支持该功能,若您想要退技能,请说小度小度,退出"); } + // 这个字段是标识当前页面的第一个图标的作品在整个后台缓存作品列表里是第几个,当用户在该页面说打开第一个时,后台需要找到这个作品 + // 主动清除这个标记,防止旧数据污染新页面 String curFirstRowIndex = getSessionAttribute(CUR_FIRST_ROW_INDEX); if (curFirstRowIndex != null) setSessionAttribute(CUR_FIRST_ROW_INDEX, null); switch (command) { - case "refresh" : return homePageRefresh(); - case "recommend": return dealRecommend(data, centralResponse.getDialogs().get(0).getText(), null); - case "history" : return dealHistoryIntent(1); - case "collect" : return dealOpenCollectIntent(1); - case "next" : return dealNextPageIntent(); - case "before" : return dealLastPageIntent(); - case "back" : return dealBackIntent(); - case "load" : return load(); - case "start" : return dealStartIntent(intentRequest); - case "openRank" : return dealRankIntent(1); - case "openNum" : return dealOpenNumIntent(end+1 == txt.length() ? "1" : txt.substring(end+1)); - case "jump" : return dealJumpIntent(end+1 == txt.length() ? "1" : txt.substring(end+1)); - case "store" : return dealCollectOrUnCollectIntent( true, end+1 == txt.length() ? null : txt.substring(end+1), false); - case "unStore" : return dealCollectOrUnCollectIntent( false, end+1 == txt.length() ? null : txt.substring(end+1), false); - case "flower" : return dealSendFlowerIntent(userId, end+1 == txt.length() ? "1" : txt.substring(end+1)); - case "category" : return openCategory(); - case "up" : return dealUpOrDownCommand(true, curFirstRowIndex); - case "down" : return dealUpOrDownCommand(false, curFirstRowIndex); + case "refresh" : return homePageRefresh(); // 刷新页面指令 + case "recommend": return dealRecommend(data, centralResponse.getDialogs().get(0).getText(), null); // 打开推荐页 + case "history" : return dealHistoryIntent(1); // 打开历史页 + case "collect" : return dealOpenCollectIntent(1); // 打开收藏页 + case "next" : return dealNextPageIntent(); // 下一页 + case "before" : return dealLastPageIntent(); // 上一页 + case "back" : return dealBackIntent(); // 返回 + case "load" : return load(); //登录 + case "start" : return dealStartIntent(intentRequest); // 在技能详情页谁"开始"触发作品的开始 + case "openRank" : return dealRankIntent(1); // 排行榜 + case "openNum" : return dealOpenNumIntent(end+1 == txt.length() ? "1" : txt.substring(end+1)); // 打开第几个 + case "jump" : return dealJumpIntent(end+1 == txt.length() ? "1" : txt.substring(end+1)); // 跳到第几页 + case "store" : return dealCollectOrUnCollectIntent( true, end+1 == txt.length() ? null : txt.substring(end+1), false); // 收藏 + case "unStore" : return dealCollectOrUnCollectIntent( false, end+1 == txt.length() ? null : txt.substring(end+1), false); // 取消收藏 + case "flower" : return dealSendFlowerIntent(userId, end+1 == txt.length() ? "1" : txt.substring(end+1)); // 送花 + case "category" : return openCategory(); // 打开标签分类页-言情,武侠,科幻.... + case "up" : return dealUpOrDownCommand(true, curFirstRowIndex); // 向上滑 + case "down" : return dealUpOrDownCommand(false, curFirstRowIndex); // 向下滑 } } } @@ -532,10 +551,15 @@ public class Dpl2Service extends BaseBot { log.error("解析出错:"+e); return new Response(); } - boolean endMark = false; + boolean endMark = false; // 标识是否是作品最后一句话 + // 退出作品标识,通过记录用户上一页面信息的BACK_TRACE字段来从游戏作品中返回到之前页面 + //对于音箱作品结束语的返回形式是 作品最后一句话 + 推荐bot语句, + //对于有屏端就需要在作品游戏页展示完最后一句话后跳到推荐作品页, + //这里先是从数据中讲作品与推荐语句分离,讲推荐语句存储在redis中,在session中添加标识字段DPL2.PRODUCT_END_MARK, + //在语音播放完成后回调方法里会判断该标识是否存在,存在则跳到推荐页,这样做是确保作品最后一句语音播放完成再跳转。 if ("exit".equalsIgnoreCase(centralResponse.getBotStatus())) { String trace = getSessionAttribute(BACK_TRACE); - if (StringUtils.endsWith(trace, File.separator)) { + if (StringUtils.endsWith(trace, File.separator)) { // String botAccount = trace.substring(2, trace.length()-1); if (!CollectionUtils.isEmpty(centralResponse.getDialogs())) { final List recommendWord = new ArrayList<>(2); @@ -557,7 +581,7 @@ public class Dpl2Service extends BaseBot { stringRedisTemplate.opsForValue().set(SpiritRedisService.PREFIX_REDIS+userId+"_end", ScheduleServiceNew.objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(vo), 3, TimeUnit.MINUTES); - endMark = true; + endMark = true; // } catch (Exception e) { log.error("end recommend json error:"+e); } @@ -573,15 +597,18 @@ public class Dpl2Service extends BaseBot { } } + // 获取botid String botAccount = centralResponse.getAipioneerUsername(); if (StringUtils.isBlank(botAccount)) { log.warn("central response data botAccount is null:"+data); setExpectSpeech(true); return buildTextResponse("主人晓悟加载数据失败了,请再说一遍吧"); } - String path; + String path; // 获取音频访问url try { if (endMark) { + // 作品最后一句处理不同于其他,是要将作品与推荐分离 + // 这里先获取作品最后一句话的音频url path = OkHttp3Utils.doPostJsonStr(ScheduleServiceNew.BASE_AUDIO_URL+"/api/audio", ScheduleServiceNew.objectMapper.writeValueAsString(centralResponse)); } else { @@ -596,21 +623,28 @@ public class Dpl2Service extends BaseBot { log.error("小度没有获取到音频链接"); return buildTextResponse(Constants.ErrorMsg.SORRY_UNCATCH); } + // 这里是通过预先存储的推荐botid来判断用户现在是否在推荐bot中,这种判断方法是不完善的, + // 因为推荐bot的id是会随着作品版本的更新而改变的 + // 暂时先这样 if (!endMark && botAccount.equals(ScheduleServiceNew.getTheChannelBotAccount(channel))){ return dealRecommend(data, centralResponse.getDialogs().get(0).getText(), dealAudioUrl(path, botAccount)); } + // 每次玩一个作品就会在session中的botAcc字段存储该作品id,每次都判断,查看是否要更新用户行为数据 String beforeBotAccount = getSessionAttribute("botAcc"); if (!botAccount.equals(beforeBotAccount)) { DplbotServiceUtil.updateTheUserHistory(userId, botAccount, getAccessToken(), channel, getSessionAttribute("userId")); } + // 如果处理超时就缓存这次的处理结果,下次返回该结果 if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfPresent(SpiritRedisService.PREFIX_REDIS+userId, new StringBuilder(data).append("⧩").append(path).append("⧩").append(endMark).toString(), 20, TimeUnit.SECONDS))) { return new Response(); } if (endMark) { + // 标识这是作品最后一句话 setSessionAttribute(DPL2.PRODUCT_END_MARK, "1"); } + // 处理作品游戏页面返回数据 return openPlayPage(centralResponse.getPlotImgUrl(),ScheduleServiceNew.getWorkNameByBotAccount(botAccount), dealAudioUrl(path, botAccount), DplbotServiceUtil.getTheActorsWithWords(centralResponse.getDialogs(), botAccount), botAccount); } @@ -945,6 +979,10 @@ public class Dpl2Service extends BaseBot { // ============ back intent=================================== + /** + * 处理返回操作 + * @return + */ private Response dealBackIntent() { String trace = getSessionAttribute(BACK_TRACE); char second; diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplbotServiceUtil.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplbotServiceUtil.java index 8cbb6d7..55a57ce 100755 --- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplbotServiceUtil.java +++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/DplbotServiceUtil.java @@ -142,6 +142,14 @@ public class DplbotServiceUtil { }); } + /** + * 从数据库中读取用户之前的数据信息,送花数,分享数,收藏数 + * @param userId + * @param channelId + * @param jytUserId + * @param alreadyLoaded + * @return + */ public static UserBehaviorData onLunchFillUserBehaviorDataInMaster(final String userId, final String channelId, final String jytUserId, final Boolean alreadyLoaded) { // Map params = new HashMap<>(); diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java index 48fa266..c182e9e 100755 --- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java +++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/RequestTerminal.java @@ -137,6 +137,11 @@ public class RequestTerminal { OkHttp3Utils.backPostAsync(Constants.INTERFACE_DI, requestJsonStr, type); } + /** + * 发送"退出“指令给中控 + * @param userId + * @param channel + */ public static void backRequestByChannel(String userId, String channel) { SpiritTerminateRequest requestPojo = new SpiritTerminateRequest(); requestPojo.setUid(userId); diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java index 8e940a8..db50e2d 100644 --- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java +++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/service/ScheduleServiceNew.java @@ -32,6 +32,8 @@ import static ai.qiwu.com.xiaoduhome.common.Constants.UNIT_PRICE; @Slf4j @Component public class ScheduleServiceNew implements InitializingBean { + + // =============== private static volatile List allProjects = new ArrayList<>(); private static volatile Map botAccount2Project = new HashMap<>(); private static volatile Map name2Project = new HashMap<>(); @@ -59,7 +61,10 @@ public class ScheduleServiceNew implements InitializingBean { public static boolean THE_PROCESS_IS_MASTER = false; - //////////////////// + //============== 上述为止都是有屏端使用到的字段 + + //存储中控访问地址,语音tts访问地址,cdn访问地址,与接口切换url功能有关, + // 详细解释在XiaoDuHomeController#changeBaseHost public static volatile String BASE_HOST_URL; public static volatile String OLD_BASE_HOST_URL; public static volatile String BASE_AUDIO_URL; @@ -70,8 +75,10 @@ public class ScheduleServiceNew implements InitializingBean { private static volatile String HOST_UTL; private static volatile String CENTRAL_HOST; + // 序列化工具 public static final ObjectMapper objectMapper; + // 与小度登录回调有关的字段 public static final Set LOAD_AUTH_CALLBACK_URL; static { @@ -110,6 +117,9 @@ public class ScheduleServiceNew implements InitializingBean { // buildLunchNewDocument } + /** + * 获取所有作品信息,用于有屏端展示 + */ private void getAllProjects() { new Thread(() -> { try { @@ -193,6 +203,9 @@ public class ScheduleServiceNew implements InitializingBean { // curTime = System.currentTimeMillis(); // } + /** + * 多服务,获取其他服务地址 + */ private void getOtherServerAddress() { String servers = Config.getProperty("serverAddress"); if (StringUtils.isNotBlank(servers)) { @@ -220,6 +233,9 @@ public class ScheduleServiceNew implements InitializingBean { // } // } + /** + * 定时刷新渠道及其作品信息,用于郊游天下技能欢迎语使用(该技能欢迎语是随机的,选取范围就在这里) + */ @Scheduled(cron = "0 0 11,16,22 * * ?") public void getJiaoYouChannelRecordBots() { DplbotServiceUtil.POOL.submit(() -> { @@ -259,6 +275,8 @@ public class ScheduleServiceNew implements InitializingBean { }); } + //====下面都是根据之前获取的所有作品信息来的工具方法,有屏端使用 + public static String getWorkNameByBotAccount(String botAccount) { if (StringUtils.isNotBlank(botAccount)) { ProjectData data = botAccount2Project.get(botAccount); -- libgit2 0.27.1